blob: f86f777301a21f9b5e981de029d434e33691b328 [file] [log] [blame]
Krzysztof Opasiakdb2fcdd2019-03-20 23:55:01 +01001#!/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
Lucjan Bryndzac43f25d2019-05-29 16:02:46 +020032#Prerequisities commands list
33REQ_APPS=(kubectl nmap awk column sort paste grep wc)
34
35# Check for prerequisites apps
36for cmd in "${REQ_APPS[@]}"; do
37 if ! [ -x "$(command -v "$cmd")" ]; then
38 echo "Error: command $cmd is not installed"
39 exit 1
40 fi
41done
42
Krzysztof Opasiakdb2fcdd2019-03-20 23:55:01 +010043if [ "$#" -lt 1 ]; then
44 echo "Usage: $0 <k8s-namespace>"
45 exit 1
46fi
47
48K8S_NAMESPACE=$1
49
50# Get both values on single call as this may get slow
51PORTS_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`
52
53# Split port number and service name
54PORTS=`awk '{print $1}' <<<"$PORTS_SVCS"`
55SVCS=`awk '{print $2}' <<<"$PORTS_SVCS"`
56
57# Create a list in nmap-compatible format
58PORT_LIST=`tr "\\n" "," <<<"$PORTS" | sed 's/,$//'; echo ''`
59
Pawel Wieczorek62b59082020-01-28 16:26:24 +010060# Get IP address of some cluster node (both "external-ip" and "ExternalIP" labels are matched)
61K8S_NODE=`kubectl describe nodes \`kubectl get nodes | grep -v NAME | head -n 1 | awk '{print $1}'\` | grep "external-ip\|ExternalIP" | awk '{print $2}'`
Krzysztof Opasiakdb2fcdd2019-03-20 23:55:01 +010062
63# perform scan
64SCAN_RESULT=`nmap $K8S_NODE -sV -p $PORT_LIST 2>/dev/null | grep \tcp`
65
66# Concatenate scan result with service name
67RESULTS=`paste <(printf %s "$SVCS") <(printf %s "$SCAN_RESULT") | column -t`
68
69# Find all plain http ports
70HTTP_PORTS=`grep http <<< "$RESULTS" | grep -v ssl/http`
71
72# Count them
73N_HTTP=`wc -l <<<"$HTTP_PORTS"`
74
75if [ "$N_HTTP" -gt 0 ]; then
76 echo "$HTTP_PORTS"
77fi
78
79exit $N_HTTP