forked from 0xrawsec/whids
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager_endpoint_api.go
399 lines (356 loc) · 11.3 KB
/
manager_endpoint_api.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package api
import (
"bufio"
"compress/gzip"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
"github.com/0xrawsec/golang-evtx/evtx"
"github.com/0xrawsec/whids/utils"
"github.com/0xrawsec/golang-utils/log"
"github.com/0xrawsec/mux"
)
var (
// ErrUnkEndpoint error to return when endpoint is unknown
ErrUnkEndpoint = fmt.Errorf("Unknown endpoint")
)
/////////////////// Utils
func (m *Manager) endpointFromRequest(rq *http.Request) *Endpoint {
uuid := rq.Header.Get("UUID")
if endpt, ok := m.endpoints.GetByUUID(uuid); ok {
return endpt
}
return nil
}
func (m *Manager) endpointAuthorizationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(wt http.ResponseWriter, rq *http.Request) {
var endpt *Endpoint
var ok bool
uuid := rq.Header.Get("UUID")
key := rq.Header.Get("Api-Key")
hostname := rq.Header.Get("Hostname")
if endpt, ok = m.endpoints.GetMutByUUID(uuid); !ok {
http.Error(wt, "Not Authorized", http.StatusForbidden)
// we have to return not to reach ServeHTTP
return
}
if endpt.UUID != uuid || endpt.Key != key {
http.Error(wt, "Not Authorized", http.StatusForbidden)
// we have to return not to reach ServeHTTP
return
}
ip, err := IPFromRequest(rq)
if err != nil {
log.Errorf("Failed to parse client IP address: %s", err)
} else {
// update endpoint IP at every request if possible
endpt.IP = ip.String()
}
switch {
case endpt.Hostname == "":
endpt.Hostname = hostname
case endpt.Hostname != hostname:
log.Errorf("Two hosts are using the same credentials %s (%s) and %s (%s)", endpt.Hostname, endpt.IP, hostname, ip)
http.Error(wt, "Not Authorized", http.StatusForbidden)
// we have to return not to reach ServeHTTP
return
}
// update last connection timestamp
endpt.LastConnection = time.Now()
next.ServeHTTP(wt, rq)
})
}
func isVerboseURL(u *url.URL) bool {
for _, vu := range eptAPIVerbosePaths {
if u.Path == vu {
return true
}
}
return false
}
func quietLogHTTPMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !isVerboseURL(r.URL) {
// src-ip:src-port http-method http-proto url user-agent UUID content-length
fmt.Printf("%s %s %s %s %s \"%s\" \"%s\" %d\n", time.Now().Format(time.RFC3339Nano), r.RemoteAddr, r.Method, r.Proto, r.URL, r.UserAgent(), r.Header.Get("UUID"), r.ContentLength)
}
next.ServeHTTP(w, r)
})
}
func (m *Manager) runEndpointAPI() {
go func() {
// If we fail due to server crash we properly shutdown
// the receiver to avoid log corruption
defer func() {
if err := recover(); err != nil {
m.Shutdown()
}
}()
rt := mux.NewRouter()
// Middleware initialization
// Manages Request Logging
if m.Config.Logging.VerboseHTTP {
rt.Use(logHTTPMiddleware)
} else {
rt.Use(quietLogHTTPMiddleware)
}
// Manages Authorization
rt.Use(m.endpointAuthorizationMiddleware)
// Manages Compression
rt.Use(gunzipMiddleware)
// Routes initialization
// POST based
rt.HandleFunc(EptAPIPostLogsPath, m.Collect).Methods("POST")
rt.HandleFunc(EptAPIPostDumpPath, m.UploadDump).Methods("POST")
// GET based
rt.HandleFunc(EptAPIServerKeyPath, m.ServerKey).Methods("GET")
rt.HandleFunc(EptAPIRulesPath, m.Rules).Methods("GET")
rt.HandleFunc(EptAPIRulesSha256Path, m.RulesSha256).Methods("GET")
rt.HandleFunc(EptAPIContainerPath, m.Container).Methods("GET")
rt.HandleFunc(EptAPIContainerListPath, m.ContainerList).Methods("GET")
rt.HandleFunc(EptAPIContainerSha256Path, m.ContainerSha256).Methods("GET")
// GET and POST
rt.HandleFunc(EptAPICommandPath, m.Command).Methods("GET", "POST")
uri := fmt.Sprintf("%s:%d", m.Config.EndpointAPI.Host, m.Config.EndpointAPI.Port)
m.endpointAPI = &http.Server{
Handler: rt,
Addr: uri,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
if m.Config.TLS.Empty() {
// Bind to a port and pass our router in
log.Infof("Running endpoint HTTP API server on: %s", uri)
if err := m.endpointAPI.ListenAndServe(); err != http.ErrServerClosed {
log.Panic(err)
}
} else {
// Bind to a port and pass our router in
log.Infof("Running endpoint HTTPS API server on: %s", uri)
if err := m.endpointAPI.ListenAndServeTLS(m.Config.TLS.Cert, m.Config.TLS.Key); err != http.ErrServerClosed {
log.Panic(err)
}
}
}()
}
// ServerKey HTTP handler used to authenticate server on client side
func (m *Manager) ServerKey(wt http.ResponseWriter, rq *http.Request) {
wt.Write([]byte(m.Config.EndpointAPI.ServerKey))
}
// Rules HTTP handler used to serve the rules
func (m *Manager) Rules(wt http.ResponseWriter, rq *http.Request) {
m.RLock()
defer m.RUnlock()
wt.Write([]byte(m.rules))
}
// RulesSha256 returns the sha256 of the latest set of rules loaded into the manager
func (m *Manager) RulesSha256(wt http.ResponseWriter, rq *http.Request) {
m.RLock()
defer m.RUnlock()
wt.Write([]byte(m.rulesSha256))
}
// UploadDump HTTP handler used to upload dump files from client to manager
func (m *Manager) UploadDump(wt http.ResponseWriter, rq *http.Request) {
defer rq.Body.Close()
if m.Config.DumpDir == "" {
log.Errorf("Upload handler won't dump because no dump directory set")
http.Error(wt, "Failed to dump file", http.StatusInternalServerError)
return
}
fu := FileUpload{}
dec := json.NewDecoder(rq.Body)
if endpt := m.endpointFromRequest(rq); endpt != nil {
if err := dec.Decode(&fu); err != nil {
log.Errorf("Upload handler failed to decode JSON")
http.Error(wt, "Failed to decode JSON", http.StatusInternalServerError)
return
}
endptDumpDir := filepath.Join(m.Config.DumpDir, endpt.UUID)
if err := fu.Dump(endptDumpDir); err != nil {
log.Errorf("Upload handler failed to dump file (%s): %s", fu.Implode(), err)
http.Error(wt, "Failed to dump file", http.StatusInternalServerError)
return
}
} else {
log.Error("Failed to retrieve endpoint from request")
}
}
// Container HTTP handler serves Gene containers to clients
func (m *Manager) Container(wt http.ResponseWriter, rq *http.Request) {
m.RLock()
defer m.RUnlock()
vars := mux.Vars(rq)
if name, ok := vars["name"]; ok {
if cont, ok := m.containers[name]; ok {
b, err := json.Marshal(cont)
if err != nil {
log.Errorf("Container handler failed to JSON encode container")
http.Error(wt, "Failed to JSON encode container", http.StatusInternalServerError)
} else {
wt.Write(b)
}
} else {
http.Error(wt, "Unavailable container", http.StatusNotFound)
}
}
}
// ContainerList HTTP handler to server the list of available containers
func (m *Manager) ContainerList(wt http.ResponseWriter, rq *http.Request) {
m.RLock()
defer m.RUnlock()
list := make([]string, 0, len(m.containers))
for cn := range m.containers {
list = append(list, cn)
}
b, err := json.Marshal(list)
if err == nil {
wt.Write(b)
} else {
log.Errorf("ContainerList handler failed to JSON encode list")
http.Error(wt, "Failed to JSON encode list", http.StatusInternalServerError)
}
}
// ContainerSha256 HTTP handler to server the Sha256 of a given container
func (m *Manager) ContainerSha256(wt http.ResponseWriter, rq *http.Request) {
m.RLock()
defer m.RUnlock()
vars := mux.Vars(rq)
if name, ok := vars["name"]; ok {
if sha256, ok := m.containersSha256[name]; ok {
wt.Write([]byte(sha256))
} else {
http.Error(wt, "Unavailable container", http.StatusNotFound)
}
}
}
// Collect HTTP handler
func (m *Manager) Collect(wt http.ResponseWriter, rq *http.Request) {
cnt := 0
uuid := rq.Header.Get("UUID")
paths := make(map[string]*gzip.Writer)
defer rq.Body.Close()
s := bufio.NewScanner(rq.Body)
for s.Scan() {
tok := s.Text()
log.Debugf("Received Event: %s", tok)
e := evtx.GoEvtxMap{}
if err := json.Unmarshal([]byte(tok), &e); err != nil {
log.Errorf("Failed to unmarshal: %s", tok)
} else {
if endpt := m.endpointFromRequest(rq); endpt != nil {
m.UpdateReducer(endpt.UUID, &e)
} else {
log.Error("Failed to retrieve endpoint from request")
}
// endpoint specific logging
// this part is part to race because there is no sync
// mechanisms on endpoints log files. However we are not supposed
// to receive logs in parallel from the same endpoint because it
// would break the order of the events received.
if m.Config.Logging.EnEnptLogs {
tc := e.TimeCreated()
logPaths := []string{m.Config.Logging.LogPath(uuid, tc)}
// we test if the event is an alert
if _, err := e.Get(&sigPath); err == nil {
logPaths = append(logPaths, m.Config.Logging.AlertPath(uuid, tc))
}
for _, path := range logPaths {
if _, ok := paths[path]; !ok {
if err := os.MkdirAll(filepath.Dir(path), utils.DefaultPerms); err != nil {
log.Errorf("Failed to create endpoint log directory %s: %s", path, err)
} else {
fd, err := os.OpenFile(path, os.O_APPEND|os.O_RDWR|os.O_CREATE, DefaultLogPerm)
if err == nil {
w := gzip.NewWriter(fd)
defer fd.Close()
defer w.Close()
paths[path] = w
} else {
log.Errorf("Failed to write enpoint logs to %s: %s", path, err)
}
}
}
if w, ok := paths[path]; ok {
w.Write([]byte(fmt.Sprintln(tok)))
w.Flush()
}
}
}
// logging to main log stream
m.logfile.Write([]byte(fmt.Sprintln(tok)))
}
cnt++
}
log.Debugf("Count Event Received: %d", cnt)
}
// AddCommand sets a command to be executed on endpoint specified by UUID
func (m *Manager) AddCommand(uuid string, c *Command) error {
if endpt, ok := m.endpoints.GetMutByUUID(uuid); ok {
endpt.Command = c
return nil
}
return ErrUnkEndpoint
}
// GetCommand gets the command set for an endpoint specified by UUID
func (m *Manager) GetCommand(uuid string) (*Command, error) {
if endpt, ok := m.endpoints.GetByUUID(uuid); ok {
// We return the command of an unmutable endpoint struct
// so if Command is modified this will not affect Endpoint
return endpt.Command, nil
}
return nil, ErrUnkEndpoint
}
// Command HTTP handler
func (m *Manager) Command(wt http.ResponseWriter, rq *http.Request) {
id := rq.Header.Get("UUID")
switch rq.Method {
case "GET":
if endpt, ok := m.endpoints.GetMutByUUID(id); ok {
// we send back the command to execute only if was not already sent
if endpt.Command != nil {
if !endpt.Command.Sent {
jsonCmd, err := json.Marshal(endpt.Command)
if err != nil {
log.Errorf("Failed at serializing command to JSON: %s", err)
} else {
wt.Write(jsonCmd)
}
endpt.Command.Sent = true
endpt.Command.SentTime = time.Now()
return
}
}
// if the command is nil or already sent
http.Error(wt, "", http.StatusNoContent)
}
case "POST":
if endpt, ok := m.endpoints.GetMutByUUID(id); ok {
// if command is nil we actually don't expect any result
if endpt.Command != nil {
if !endpt.Command.Completed {
defer rq.Body.Close()
body, err := ioutil.ReadAll(rq.Body)
if err != nil {
log.Errorf("Failed to read response body: %s", err)
} else {
rcmd := Command{}
err := json.Unmarshal(body, &rcmd)
if err != nil {
log.Errorf("Failed to unmarshal received command: %s", err)
} else {
// we complete the command executed on the endpoint
endpt.Command.Complete(&rcmd)
}
}
} else {
log.Errorf("Command is already completed")
}
}
}
}
}