Krzysztof Opasiak | db2fcdd | 2019-03-20 23:55:01 +0100 | [diff] [blame] | 1 | #!/usr/bin/env bash |
| 2 | |
| 3 | # COPYRIGHT NOTICE STARTS HERE |
| 4 | # |
| 5 | # Copyright 2019 Samsung Electronics Co., Ltd. |
| 6 | # |
| 7 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | # you may not use this file except in compliance with the License. |
| 9 | # You may obtain a copy of the License at |
| 10 | # |
| 11 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | # |
| 13 | # Unless required by applicable law or agreed to in writing, software |
| 14 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | # See the License for the specific language governing permissions and |
| 17 | # limitations under the License. |
| 18 | # |
| 19 | # COPYRIGHT NOTICE ENDS HERE |
| 20 | |
| 21 | # Check all ports exposed outside of kubernetes cluster looking for plain http |
| 22 | # endpoints. |
| 23 | # |
| 24 | # Dependencies: |
| 25 | # nmap |
| 26 | # kubectl + config |
| 27 | # |
| 28 | # Return value: Number of discovered http ports |
| 29 | # Output: List of pods exposing http endpoints |
| 30 | # |
| 31 | |
| 32 | if [ "$#" -lt 1 ]; then |
| 33 | echo "Usage: $0 <k8s-namespace>" |
| 34 | exit 1 |
| 35 | fi |
| 36 | |
| 37 | K8S_NAMESPACE=$1 |
| 38 | |
| 39 | # Get both values on single call as this may get slow |
| 40 | PORTS_SVCS=`kubectl get svc --namespace=$K8S_NAMESPACE -o go-template='{{range $item := .items}}{{range $port := $item.spec.ports}}{{if .nodePort}}{{.nodePort}}{{"\t"}}{{$item.metadata.name}}{{"\n"}}{{end}}{{end}}{{end}}' | column -t | sort -n` |
| 41 | |
| 42 | # Split port number and service name |
| 43 | PORTS=`awk '{print $1}' <<<"$PORTS_SVCS"` |
| 44 | SVCS=`awk '{print $2}' <<<"$PORTS_SVCS"` |
| 45 | |
| 46 | # Create a list in nmap-compatible format |
| 47 | PORT_LIST=`tr "\\n" "," <<<"$PORTS" | sed 's/,$//'; echo ''` |
| 48 | |
| 49 | # Get IP addres of some cluster node |
Krzysztof Opasiak | 92ede49 | 2019-04-24 23:56:48 +0200 | [diff] [blame] | 50 | K8S_NODE=`kubectl describe nodes \`kubectl get nodes | grep -v NAME | head -n 1 | awk '{print $1}'\` | grep external-ip | awk '{print $2}'` |
Krzysztof Opasiak | db2fcdd | 2019-03-20 23:55:01 +0100 | [diff] [blame] | 51 | |
| 52 | # perform scan |
| 53 | SCAN_RESULT=`nmap $K8S_NODE -sV -p $PORT_LIST 2>/dev/null | grep \tcp` |
| 54 | |
| 55 | # Concatenate scan result with service name |
| 56 | RESULTS=`paste <(printf %s "$SVCS") <(printf %s "$SCAN_RESULT") | column -t` |
| 57 | |
| 58 | # Find all plain http ports |
| 59 | HTTP_PORTS=`grep http <<< "$RESULTS" | grep -v ssl/http` |
| 60 | |
| 61 | # Count them |
| 62 | N_HTTP=`wc -l <<<"$HTTP_PORTS"` |
| 63 | |
| 64 | if [ "$N_HTTP" -gt 0 ]; then |
| 65 | echo "$HTTP_PORTS" |
| 66 | fi |
| 67 | |
| 68 | exit $N_HTTP |