-
Notifications
You must be signed in to change notification settings - Fork 2
/
store.go
301 lines (240 loc) · 6.59 KB
/
store.go
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"database/sql"
"errors"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/ant0ine/go-json-rest/rest"
"github.com/devel/dnsmapper/storeapi"
_ "github.com/lib/pq"
"github.com/oschwald/geoip2-golang"
)
var (
listen = flag.String("listen", "", "Listen on this ip:port for the HTTP API")
geoipPath = flag.String("geoip", "", "Optional directory for geoip database files")
dbuser = flag.String("dbuser", "ask", "Postgres user name")
dbpass = flag.String("dbpass", "", "Postgres password")
dbhost = flag.String("dbhost", "localhost", "Postgres host name")
)
var (
geodb *geoip2.Reader
geoasn *geoip2.Reader
db *sql.DB
)
func init() {
flag.Parse()
path, _ := os.LookupEnv("GEOIP")
if len(*geoipPath) > 0 {
path = *geoipPath
}
var err error
dbName := "GeoLite2-City.mmdb"
asnDbName := "GeoLite2-ASN.mmdb"
if len(path) > 0 {
dbName = filepath.Join(path, dbName)
asnDbName = filepath.Join(path, asnDbName)
}
geodb, err = geoip2.Open(dbName)
if err != nil {
log.Printf("Could not open City GeoIP database '%s': %s", dbName, err)
log.Fatal(err)
}
log.Printf("Opened '%s' (%s)", dbName, geodb.Metadata().DatabaseType)
geoasn, err = geoip2.Open(asnDbName)
if err != nil {
log.Printf("Could not open ASN GeoIP database '%s': %s", asnDbName, err)
log.Fatal(err)
}
log.Printf("Opened '%s' (%s)", asnDbName, geoasn.Metadata().DatabaseType)
}
func main() {
startHttp(*listen)
}
func buildMux() *http.ServeMux {
mux := http.NewServeMux()
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
rest.Post("/api/v1/store-result", storeHandler),
)
if err != nil {
log.Fatalf("Could not configure router: %s", err)
}
api.SetApp(router)
mux.Handle("/api/v1/", api.MakeHandler())
mux.HandleFunc("/healthz", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
w.Write([]byte("ok\n"))
return
})
return mux
}
func startHttp(listen string) {
fmt.Printf("Listening on http://%s\n", listen)
err := http.ListenAndServe(listen, buildMux())
fmt.Printf("Could not listen to %s: %s", listen, err)
}
func storeHandler(w rest.ResponseWriter, r *rest.Request) {
// err := r.ParseForm()
// if err != nil {
// log.Println("parse error", err)
// }
now := time.Now().UTC()
reqData := &storeapi.RequestData{}
err := r.DecodeJsonPayload(&reqData)
if err != nil {
rest.Error(w, "Could not decode JSON: "+err.Error(), 400)
return
}
data := &storeapi.LogData{
TestIP: reqData.TestIP,
ClientIP: reqData.ClientIP,
ServerIP: reqData.ServerIP,
EdnsNet: reqData.EdnsNet,
LastSeen: &now,
}
data.ClientCC, data.ClientRC, data.ClientASN = ccLookup(net.ParseIP(data.ClientIP))
data.ServerCC, data.ServerRC, data.ServerASN = ccLookup(net.ParseIP(data.ServerIP))
if len(data.EdnsNet) > 0 {
ednsIP, _, _ := net.ParseCIDR(data.EdnsNet)
data.EdnsCC, data.EdnsRC, data.EdnsASN = ccLookup(net.ParseIP(ednsIP.String()))
data.HasEdns = true
} else {
data.EdnsNet = data.ServerIP
data.EdnsCC, data.EdnsRC, data.EdnsASN = data.ServerCC, data.ServerRC, data.ServerASN
data.HasEdns = false
}
w.WriteHeader(204)
// w.WriteJson(data)
dbStore(data)
}
func ccLookup(ip net.IP) (rcc string, rrc string, rasn uint) {
// rcc: return country code, rrc: return region code, rasn: return asn
if ip == nil {
return
}
// If you are using strings that may be invalid, check that ip is not nil
record, err := geodb.City(ip)
if err != nil || record.Country.IsoCode == "" {
if err == nil {
err = errors.New("not found")
}
log.Printf("Could not lookup data for '%s': %s", ip.String(), err)
} else {
// fmt.Printf("city name: %v\n", record.City.Names["en"])
// if len(record.Subdivisions) > 0 {
// fmt.Printf("subdivision name: %v\n", record.Subdivisions[0].Names["en"])
// }
// fmt.Printf("country name: %v\n", record.Country.Names["en"])
// fmt.Printf("ISO country code: %v\n", record.Country.IsoCode)
// fmt.Printf("Time zone: %v\n", record.Location.TimeZone)
// fmt.Printf("Coordinates: %v, %v\n", record.Location.Latitude, record.Location.Longitude)
rcc = record.Country.IsoCode
if len(record.Subdivisions) > 0 {
rrc = record.Subdivisions[0].IsoCode
}
}
asn, err := geoasn.ASN(ip)
if err != nil {
log.Printf("Could not lookup ASN data for '%s': %s", ip.String(), err)
} else {
rasn = asn.AutonomousSystemNumber
}
return rcc, rrc, rasn
}
func dbConnect() {
var err error
db, err = sql.Open("postgres", fmt.Sprintf("user=%s host=%s password=%s", *dbuser, *dbhost, *dbpass))
if err != nil {
log.Fatalf("create db error: %s", err)
}
db.SetMaxOpenConns(50)
}
func dbStore(data *storeapi.LogData) error {
if db == nil {
dbConnect()
}
fmt.Printf("dbStore: %#v\n", data)
rv, err := db.Exec(`
WITH upsert_data AS (
SELECT
$1::inet AS client_ip,
$2::inet AS server_ip,
$3::cidr AS edns_net,
$4::char(2) AS client_cc,
$5::char(2) AS client_rc,
$6::int AS client_asn,
$7::char(2) AS server_cc,
$8::char(2) AS server_rc,
$9::int AS server_asn,
$10::char(2) AS edns_cc,
$11::char(2) AS edns_rc,
$12::int AS edns_asn,
$13::inet AS test_ip,
$14::boolean AS has_edns,
$15::timestamp AS last_seen
),
update_ips AS (
UPDATE ips
SET
edns_net = ud.edns_net,
client_cc = ud.client_cc,
client_rc = ud.client_rc,
client_asn = ud.client_asn,
server_cc = ud.server_cc,
server_rc = ud.server_rc,
server_asn = ud.server_asn,
edns_cc = ud.edns_cc,
edns_rc = ud.edns_rc,
edns_asn = ud.edns_asn,
test_ip = ud.test_ip,
has_edns = ud.has_edns,
last_seen = ud.last_seen
FROM upsert_data ud
WHERE
ips.client_ip = ud.client_ip AND
ips.server_ip = ud.server_ip
RETURNING ips.*
)
INSERT INTO
ips
(client_ip, server_ip, edns_net,
client_cc, client_rc, client_asn,
server_cc, server_rc, server_asn,
edns_cc, edns_rc, edns_asn,
test_ip, has_edns,
first_seen, last_seen
)
SELECT
client_ip, server_ip, edns_net,
client_cc, client_rc, client_asn,
server_cc, server_rc, server_asn,
edns_cc, edns_rc, edns_asn,
test_ip, has_edns,
last_seen, last_seen
FROM upsert_data
WHERE NOT EXISTS (
SELECT 1 FROM update_ips up
WHERE (up.client_ip = upsert_data.client_ip)
)
`,
data.ClientIP, data.ServerIP, data.EdnsNet,
data.ClientCC, data.ClientRC, data.ClientASN,
data.ServerCC, data.ServerRC, data.ServerASN,
data.EdnsCC, data.EdnsRC, data.EdnsASN,
data.TestIP, data.HasEdns, data.LastSeen,
)
if err != nil {
fmt.Printf("DB Error: %s\n", err)
return err
}
updated, _ := rv.RowsAffected()
fmt.Printf("Updated %d rows\n", updated)
return err
}