-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgreynoise.go
239 lines (193 loc) · 4.5 KB
/
greynoise.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
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"sort"
"sync"
"time"
)
type GreyNoise interface {
IPLookup(ctx context.Context, ip string) (*GNoiseResponse, error)
ParseLogFiles(directory string, days int) (map[string]string, error)
}
type GNoiseResponse struct {
IP string
Noise bool
Riot bool
Classification string
Name string
Link string
LastSeen string
}
type GNoise struct {
ApiKey string
Http *http.Transport
}
type Result struct {
AmountOfNoise int
AmountOfNonNoise int
TopNoisyIP []string
TopClassification []string
TopName []string
}
func getTopValues(data map[string]int) []string {
keys := make([]string, 0, len(data))
for key := range data {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool { return data[keys[i]] > data[keys[j]] })
top := []string{}
for k := range data {
top = append(top, k)
}
if len(top) == 0 {
return []string{}
}
if len(top) <= 3 {
return top[:]
}
return top[:2]
}
// ParseLogFiles Parses log files within a given directory that are not older than days
func (gn *GNoise) ParseLogFiles(directory string, days int) (map[string]string, error) {
files, err := ioutil.ReadDir(directory)
if err != nil {
log.Fatal(err)
}
var (
ips map[string]string = map[string]string{}
ip []byte = []byte{}
before time.Time = time.Now().AddDate(0, 0, -days)
)
// Goroutines can be used to read multiple files, if needed
for _, file := range files {
t := GetCreationDate(file)
if t.After(before) {
filePath := path.Join(directory, file.Name())
logFile, err := os.Open(filePath)
if err != nil {
log.Println(err)
continue
}
scanner := bufio.NewScanner(logFile)
if err := scanner.Err(); err != nil {
return map[string]string{}, err
}
for scanner.Scan() {
ip = []byte{}
for _, b := range scanner.Bytes() {
if b == 32 {
break
}
ip = append(ip, b)
}
ips[string(ip)] = string(ip)
}
}
}
return ips, nil
}
func (gn *GNoise) IPLookup(ctx context.Context, ip string) (*GNoiseResponse, error) {
apiPath := fmt.Sprintf("https://api.greynoise.io/v3/community/%s", ip)
data := &GNoiseResponse{IP: ip}
client := &http.Client{Transport: gn.Http}
req, err := http.NewRequestWithContext(ctx, "GET", apiPath, nil)
if err != nil {
return &GNoiseResponse{}, err
}
req.Header.Add("key", gn.ApiKey)
resp, err := client.Do(req)
if err != nil {
return &GNoiseResponse{}, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case 400:
return &GNoiseResponse{}, errors.New("HTTP code 400 - Invalid Request")
case 401:
return &GNoiseResponse{}, errors.New("HTTP code 401 - Authentication Error")
case 429:
return &GNoiseResponse{}, errors.New("HTTP code 429 - Daily Rate-Limit Exceeded")
case 500:
return &GNoiseResponse{}, errors.New("HTTP code 500 - Internal Error")
}
body, err := io.ReadAll(resp.Body)
if err := json.Unmarshal(body, data); err != nil {
return &GNoiseResponse{}, err
}
return data, err
}
func CheckNoise(ctx context.Context, gn GreyNoise, directory string, days int) (*Result, error) {
ips, err := gn.ParseLogFiles(directory, days)
if err != nil {
log.Fatal(err)
}
if len(ips) == 0 {
return &Result{}, errors.New("no IPs parsed")
}
wg := &sync.WaitGroup{}
workers := 5
ipChan := make(chan string, 1)
done := make(chan bool, 1)
output := make(chan *GNoiseResponse, 1)
go func() {
for _, ip := range ips {
ipChan <- ip
}
close(ipChan)
}()
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for ip := range ipChan {
data, _ := gn.IPLookup(ctx, ip)
output <- data
}
done <- true
}()
}
workerDone := 0
responses := []*GNoiseResponse{}
for {
select {
case r := <-output:
responses = append(responses, r)
case <-done:
workerDone++
default:
}
if workerDone == workers {
break
}
}
wg.Wait()
// Perform calculation
noise := 0
topName := map[string]int{}
topClassification := map[string]int{}
// listan är ju unik ya fool........
for _, data := range responses {
if data.Noise {
noise++
topClassification[data.Classification] += 1
topName[data.Name] += 1
}
}
result := &Result{
AmountOfNoise: noise,
AmountOfNonNoise: len(responses) - noise,
TopClassification: getTopValues(topClassification),
TopName: getTopValues(topName),
}
return result, nil
}