about summary refs log tree commit diff
path: root/main.go
blob: b4a660ad334bbaf1a7b19d19c3b6466b338f1039 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package main

import (
	"encoding/json"
	"fmt"
	"github.com/gliderlabs/ssh"
	//"github.com/gorilla/mux"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

var (
	metrics_num_passwords int
	metrics_city_num      map[string]int
	cities                map[string]location
)

type geoipresult struct {
	Query       string  `json:"query"`
	Status      string  `json:"status"`
	Country     string  `json:"country"`
	CountryCode string  `json:"countryCode"`
	Region      string  `json:"region"`
	RegionName  string  `json:"regionName"`
	City        string  `json:"city"`
	Zip         string  `json:"zip"`
	Lat         float64 `json:"lat"`
	Lon         float64 `json:"lon"`
	Timezone    string  `json:"timezone"`
	Isp         string  `json:"isp"`
	Org         string  `json:"org"`
	As          string  `json:"as"`
}

type location struct {
	key       string  `json:"key"`
	latitude  float64 `json:"latitude"`
	longitude float64 `json:"longitude"`
	name      string  `json:"name"`
}

func main() {

	// create a map mapping a city to an amount of hits
	metrics_city_num = make(map[string]int)

	// create a cities map mapping a city to a location
	cities = make(map[string]location)

	// start the ssh server
	log.Println("Starting SSH listener")
	go func() {
		listenErr := ssh.ListenAndServe(":2222", nil, ssh.PasswordAuth(handlePass))
		if listenErr != nil {
			log.Fatalln(listenErr.Error())
		}
	}()

	// start the http server logging the metrics
	log.Println("Starting HTTP metrics listener")
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/metrics", metricsHandler)
	http.HandleFunc("/locations", locationHandlerEndpoint)

	// start the http server exposing the metrics and the locations
	listenErr := http.ListenAndServe(":8084", nil)

	// handle potential errors
	if listenErr != nil {
		log.Fatalln(listenErr.Error())
	}
}

// locationHandlerEndpoint handles requests to the /locations endpoint
// This is used by the grafana worldmap plugin to find out where to draw the
// fancy circles
func locationHandlerEndpoint(w http.ResponseWriter, r *http.Request) {

	// set some headers
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "https://grafana.nbg1.emile.space")

	// start building json (yes, this is not a nice implementation, PRs welcome!)
	fmt.Fprintf(w, "%s", "[")

	var i int = 0
	for _, v := range cities {

		// print the "json" object containing the metrics needed
		fmt.Fprintf(w, "{")
		fmt.Fprintf(w, "\"key\": \"%s\",", v.key)
		fmt.Fprintf(w, "\"latitude\": %f,", v.latitude)
		fmt.Fprintf(w, "\"longitude\": %f,", v.longitude)
		fmt.Fprintf(w, "\"name\": \"%s\"", v.name)

		// close the object (this handles the trailing comma problem)
		if i == len(cities) - 1 {
			fmt.Fprintf(w, "}")
		} else {
			fmt.Fprintf(w, "},")
		}
		i++
	}
	fmt.Fprintf(w, "%s", "]")
}

// Handling incoming SSH connections
func handlePass(ctx ssh.Context, pass string) bool {

	// increase the counter tracking the amount of passwords catched
	metrics_num_passwords++
	log.Printf("%s@%s: '%s'", ctx.User(), ctx.RemoteAddr().String(), pass)

	// get the ip of the remote user
	stringip := strings.Split(ctx.RemoteAddr().String(), ":")[0]

	// Define the request string for the geoip service
	requestString := fmt.Sprintf("%s%s", "http://ip-api.com/json/", stringip)

	// Send the GET request
	resp, err := http.Get(requestString)
	if err != nil {
		log.Fatal(err)
	}

	// if the response status code from the geoip service is not a 200 code, return false
	if resp.StatusCode != 200 {
		return false
	}

	// Read the response
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// Unmarshal the response to json
	var result geoipresult
	err = json.Unmarshal(body, &result)
	if err != nil {
		fmt.Println("JSON ERROR, abort mission!")
		log.Fatal(err)
	}

	// if an entry for the city does not exists yet, create the city
	// if the city does allready exist, increase it's value by one
	if metrics_city_num[result.City] == 0 {
		metrics_city_num[result.City] = 1
	} else {
		metrics_city_num[result.City] += 1
	}

	// if the actual city is not known, create the city
	// this is used for the grafana worldmap plugin
	if (cities[result.City] == location{}) {
		newCity := location{
			key:       strings.ToLower(result.City),
			latitude:  result.Lat,
			longitude: result.Lon,
			name:      result.City,
		}

		cities[result.City] = newCity
	}

	return false
}

// Handle HTTP requests to the /metrics endpoint
func metricsHandler(w http.ResponseWriter, req *http.Request) {

	// return the overall amount of passwords catched
	fmt.Fprintf(w, "num_passwords %d\n", metrics_num_passwords)

	// return the amount of passwords catched from a given city
	for k, v := range metrics_city_num {
		fmt.Fprintf(w, "a_metric{city=\"%s\"} %d\n", strings.ToLower(k), v)
	}
}

// indexHandler handles the request to the / endpoint
// It simply returns a link to the /metrics page
func indexHandler(w http.ResponseWriter, req *http.Request) {
	_, _ = fmt.Fprintf(w, "<a href='/metrics'>metrics</a>")
}