| 1 | package api_rest |
| 2 | |
| 3 | import ( |
| 4 | "crypto/subtle" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "io/ioutil" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | |
| 14 | "github.com/bettercap/bettercap/session" |
| 15 | |
| 16 | "github.com/gorilla/mux" |
| 17 | ) |
| 18 | |
| 19 | type CommandRequest struct { |
| 20 | Command string `json:"cmd"` |
| 21 | } |
| 22 | |
| 23 | type APIResponse struct { |
| 24 | Success bool `json:"success"` |
| 25 | Message string `json:"msg"` |
| 26 | } |
| 27 | |
| 28 | func (mod *RestAPI) setAuthFailed(w http.ResponseWriter, r *http.Request) { |
| 29 | mod.Warning("Unauthorized authentication attempt from %s to %s", r.RemoteAddr, r.URL.String()) |
| 30 | |
| 31 | w.Header().Set("WWW-Authenticate", `Basic realm="auth"`) |
| 32 | w.WriteHeader(401) |
| 33 | w.Write([]byte("Unauthorized")) |
| 34 | } |
| 35 | |
| 36 | func (mod *RestAPI) toJSON(w http.ResponseWriter, o interface{}) { |
| 37 | w.Header().Set("Content-Type", "application/json") |
| 38 | if err := json.NewEncoder(w).Encode(o); err != nil { |
| 39 | mod.Debug("error while encoding object to JSON: %v", err) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func (mod *RestAPI) setSecurityHeaders(w http.ResponseWriter) { |
| 44 | w.Header().Add("X-Frame-Options", "DENY") |
| 45 | w.Header().Add("X-Content-Type-Options", "nosniff") |
| 46 | w.Header().Add("X-XSS-Protection", "1; mode=block") |
| 47 | w.Header().Add("Referrer-Policy", "same-origin") |
| 48 | |
| 49 | w.Header().Set("Access-Control-Allow-Origin", mod.allowOrigin) |
| 50 | w.Header().Add("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") |
| 51 | w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") |
| 52 | } |
| 53 | |
| 54 | func (mod *RestAPI) checkAuth(r *http.Request) bool { |
| 55 | if mod.username != "" && mod.password != "" { |
| 56 | user, pass, _ := r.BasicAuth() |
| 57 | // timing attack my ass |
| 58 | if subtle.ConstantTimeCompare([]byte(user), []byte(mod.username)) != 1 { |
| 59 | return false |
| 60 | } else if subtle.ConstantTimeCompare([]byte(pass), []byte(mod.password)) != 1 { |
| 61 | return false |
| 62 | } |
| 63 | } |
| 64 | return true |
| 65 | } |
| 66 | |
| 67 | func (mod *RestAPI) patchFrame(buf []byte) (frame map[string]interface{}, err error) { |
| 68 | // this is ugly but necessary: since we're replaying, the |
| 69 | // api.rest state object is filled with *old* values (the |
| 70 | // recorded ones), but the UI needs updated values at least |
| 71 | // of that in order to understand that a replay is going on |
| 72 | // and where we are at it. So we need to parse the record |
| 73 | // back into a session object and update only the api.rest.state |
| 74 | frame = make(map[string]interface{}) |
| 75 | |
| 76 | if err = json.Unmarshal(buf, &frame); err != nil { |
| 77 | return |
| 78 | } |
| 79 | |
| 80 | for _, i := range frame["modules"].([]interface{}) { |
| 81 | m := i.(map[string]interface{}) |
| 82 | if m["name"] == "api.rest" { |
| 83 | state := m["state"].(map[string]interface{}) |
| 84 | mod.State.Range(func(key interface{}, value interface{}) bool { |
| 85 | state[key.(string)] = value |
| 86 | return true |
| 87 | }) |
| 88 | break |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | return |
| 93 | } |
| 94 | |
| 95 | func (mod *RestAPI) showSession(w http.ResponseWriter, r *http.Request) { |
| 96 | if mod.replaying { |
| 97 | if !mod.record.Session.Over() { |
| 98 | from := mod.record.Session.Index() - 1 |
| 99 | q := r.URL.Query() |
| 100 | vals := q["from"] |
| 101 | if len(vals) > 0 { |
| 102 | if n, err := strconv.Atoi(vals[0]); err == nil { |
| 103 | from = n |
| 104 | } |
| 105 | } |
| 106 | mod.record.Session.SetFrom(from) |
| 107 | |
| 108 | mod.Debug("replaying session %d of %d from %s", |
| 109 | mod.record.Session.Index(), |
| 110 | mod.record.Session.Frames(), |
| 111 | mod.recordFileName) |
| 112 | |
| 113 | mod.State.Store("rec_frames", mod.record.Session.Frames()) |
| 114 | mod.State.Store("rec_cur_frame", mod.record.Session.Index()) |
| 115 | |
| 116 | buf := mod.record.Session.Next() |
| 117 | if frame, err := mod.patchFrame(buf); err != nil { |
| 118 | mod.Error("%v", err) |
| 119 | } else { |
| 120 | mod.toJSON(w, frame) |
| 121 | return |
| 122 | } |
| 123 | } else { |
| 124 | mod.stopReplay() |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | mod.toJSON(w, mod.Session) |
| 129 | } |
| 130 | |
| 131 | func (mod *RestAPI) showBLE(w http.ResponseWriter, r *http.Request) { |
| 132 | params := mux.Vars(r) |
| 133 | mac := strings.ToLower(params["mac"]) |
| 134 | |
| 135 | if mac == "" { |
| 136 | mod.toJSON(w, mod.Session.BLE) |
| 137 | } else if dev, found := mod.Session.BLE.Get(mac); found { |
| 138 | mod.toJSON(w, dev) |
| 139 | } else { |
| 140 | http.Error(w, "Not Found", 404) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | func (mod *RestAPI) showHID(w http.ResponseWriter, r *http.Request) { |
| 145 | params := mux.Vars(r) |
| 146 | mac := strings.ToLower(params["mac"]) |
| 147 | |
| 148 | if mac == "" { |
| 149 | mod.toJSON(w, mod.Session.HID) |
| 150 | } else if dev, found := mod.Session.HID.Get(mac); found { |
| 151 | mod.toJSON(w, dev) |
| 152 | } else { |
| 153 | http.Error(w, "Not Found", 404) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | func (mod *RestAPI) showEnv(w http.ResponseWriter, r *http.Request) { |
| 158 | mod.toJSON(w, mod.Session.Env) |
| 159 | } |
| 160 | |
| 161 | func (mod *RestAPI) showGateway(w http.ResponseWriter, r *http.Request) { |
| 162 | mod.toJSON(w, mod.Session.Gateway) |
| 163 | } |
| 164 | |
| 165 | func (mod *RestAPI) showInterface(w http.ResponseWriter, r *http.Request) { |
| 166 | mod.toJSON(w, mod.Session.Interface) |
| 167 | } |
| 168 | |
| 169 | func (mod *RestAPI) showModules(w http.ResponseWriter, r *http.Request) { |
| 170 | mod.toJSON(w, mod.Session.Modules) |
| 171 | } |
| 172 | |
| 173 | func (mod *RestAPI) showLAN(w http.ResponseWriter, r *http.Request) { |
| 174 | params := mux.Vars(r) |
| 175 | mac := strings.ToLower(params["mac"]) |
| 176 | |
| 177 | if mac == "" { |
| 178 | mod.toJSON(w, mod.Session.Lan) |
| 179 | } else if host, found := mod.Session.Lan.Get(mac); found { |
| 180 | mod.toJSON(w, host) |
| 181 | } else { |
| 182 | http.Error(w, "Not Found", 404) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | func (mod *RestAPI) showOptions(w http.ResponseWriter, r *http.Request) { |
| 187 | mod.toJSON(w, mod.Session.Options) |
| 188 | } |
| 189 | |
| 190 | func (mod *RestAPI) showPackets(w http.ResponseWriter, r *http.Request) { |
| 191 | mod.toJSON(w, mod.Session.Queue) |
| 192 | } |
| 193 | |
| 194 | func (mod *RestAPI) showStartedAt(w http.ResponseWriter, r *http.Request) { |
| 195 | mod.toJSON(w, mod.Session.StartedAt) |
| 196 | } |
| 197 | |
| 198 | func (mod *RestAPI) showWiFi(w http.ResponseWriter, r *http.Request) { |
| 199 | params := mux.Vars(r) |
| 200 | mac := strings.ToLower(params["mac"]) |
| 201 | |
| 202 | if mac == "" { |
| 203 | mod.toJSON(w, mod.Session.WiFi) |
| 204 | } else if station, found := mod.Session.WiFi.Get(mac); found { |
| 205 | mod.toJSON(w, station) |
| 206 | } else if client, found := mod.Session.WiFi.GetClient(mac); found { |
| 207 | mod.toJSON(w, client) |
| 208 | } else { |
| 209 | http.Error(w, "Not Found", 404) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | func (mod *RestAPI) runSessionCommand(w http.ResponseWriter, r *http.Request) { |
| 214 | var err error |
| 215 | var cmd CommandRequest |
| 216 | |
| 217 | if r.Body == nil { |
| 218 | http.Error(w, "Bad Request", 400) |
| 219 | } else if err = json.NewDecoder(r.Body).Decode(&cmd); err != nil { |
| 220 | http.Error(w, "Bad Request", 400) |
| 221 | } |
| 222 | |
| 223 | for _, aCommand := range session.ParseCommands(cmd.Command) { |
| 224 | if err = mod.Session.Run(aCommand); err != nil { |
| 225 | http.Error(w, err.Error(), 400) |
| 226 | return |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | mod.toJSON(w, APIResponse{Success: true}) |
| 231 | } |
| 232 | |
| 233 | func (mod *RestAPI) getEvents(limit int) []session.Event { |
| 234 | events := make([]session.Event, 0) |
| 235 | for _, e := range mod.Session.Events.Sorted() { |
| 236 | if mod.Session.EventsIgnoreList.Ignored(e) == false { |
| 237 | events = append(events, e) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | nevents := len(events) |
| 242 | nmax := nevents |
| 243 | n := nmax |
| 244 | |
| 245 | if limit > 0 && limit < nmax { |
| 246 | n = limit |
| 247 | } |
| 248 | |
| 249 | return events[nevents-n:] |
| 250 | } |
| 251 | |
| 252 | func (mod *RestAPI) showEvents(w http.ResponseWriter, r *http.Request) { |
| 253 | q := r.URL.Query() |
| 254 | |
| 255 | if mod.replaying { |
| 256 | if !mod.record.Events.Over() { |
| 257 | from := mod.record.Events.Index() - 1 |
| 258 | vals := q["from"] |
| 259 | if len(vals) > 0 { |
| 260 | if n, err := strconv.Atoi(vals[0]); err == nil { |
| 261 | from = n |
| 262 | } |
| 263 | } |
| 264 | mod.record.Events.SetFrom(from) |
| 265 | |
| 266 | mod.Debug("replaying events %d of %d from %s", |
| 267 | mod.record.Events.Index(), |
| 268 | mod.record.Events.Frames(), |
| 269 | mod.recordFileName) |
| 270 | |
| 271 | buf := mod.record.Events.Next() |
| 272 | if _, err := w.Write(buf); err != nil { |
| 273 | mod.Error("%v", err) |
| 274 | } else { |
| 275 | return |
| 276 | } |
| 277 | } else { |
| 278 | mod.stopReplay() |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | if mod.useWebsocket { |
| 283 | mod.startStreamingEvents(w, r) |
| 284 | } else { |
| 285 | vals := q["n"] |
| 286 | limit := 0 |
| 287 | if len(vals) > 0 { |
| 288 | if n, err := strconv.Atoi(q["n"][0]); err == nil { |
| 289 | limit = n |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | mod.toJSON(w, mod.getEvents(limit)) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | func (mod *RestAPI) clearEvents(w http.ResponseWriter, r *http.Request) { |
| 298 | mod.Session.Events.Clear() |
| 299 | } |
| 300 | |
| 301 | func (mod *RestAPI) corsRoute(w http.ResponseWriter, r *http.Request) { |
| 302 | mod.setSecurityHeaders(w) |
| 303 | w.WriteHeader(http.StatusNoContent) |
| 304 | } |
| 305 | |
| 306 | func (mod *RestAPI) sessionRoute(w http.ResponseWriter, r *http.Request) { |
| 307 | mod.setSecurityHeaders(w) |
| 308 | |
| 309 | if !mod.checkAuth(r) { |
| 310 | mod.setAuthFailed(w, r) |
| 311 | return |
| 312 | } else if r.Method == "POST" { |
| 313 | mod.runSessionCommand(w, r) |
| 314 | return |
| 315 | } else if r.Method != "GET" { |
| 316 | http.Error(w, "Bad Request", 400) |
| 317 | return |
| 318 | } |
| 319 | |
| 320 | mod.Session.Lock() |
| 321 | defer mod.Session.Unlock() |
| 322 | |
| 323 | path := r.URL.Path |
| 324 | switch { |
| 325 | case path == "/api/session": |
| 326 | mod.showSession(w, r) |
| 327 | |
| 328 | case path == "/api/session/env": |
| 329 | mod.showEnv(w, r) |
| 330 | |
| 331 | case path == "/api/session/gateway": |
| 332 | mod.showGateway(w, r) |
| 333 | |
| 334 | case path == "/api/session/interface": |
| 335 | mod.showInterface(w, r) |
| 336 | |
| 337 | case strings.HasPrefix(path, "/api/session/modules"): |
| 338 | mod.showModules(w, r) |
| 339 | |
| 340 | case strings.HasPrefix(path, "/api/session/lan"): |
| 341 | mod.showLAN(w, r) |
| 342 | |
| 343 | case path == "/api/session/options": |
| 344 | mod.showOptions(w, r) |
| 345 | |
| 346 | case path == "/api/session/packets": |
| 347 | mod.showPackets(w, r) |
| 348 | |
| 349 | case path == "/api/session/started-at": |
| 350 | mod.showStartedAt(w, r) |
| 351 | |
| 352 | case strings.HasPrefix(path, "/api/session/ble"): |
| 353 | mod.showBLE(w, r) |
| 354 | |
| 355 | case strings.HasPrefix(path, "/api/session/hid"): |
| 356 | mod.showHID(w, r) |
| 357 | |
| 358 | case strings.HasPrefix(path, "/api/session/wifi"): |
| 359 | mod.showWiFi(w, r) |
| 360 | |
| 361 | default: |
| 362 | http.Error(w, "Not Found", 404) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | func (mod *RestAPI) readFile(fileName string, w http.ResponseWriter, r *http.Request) { |
| 367 | fp, err := os.Open(fileName) |
| 368 | if err != nil { |
| 369 | msg := fmt.Sprintf("could not open %s for reading: %s", fileName, err) |
| 370 | mod.Debug(msg) |
| 371 | http.Error(w, msg, 404) |
| 372 | return |
| 373 | } |
| 374 | defer fp.Close() |
| 375 | |
| 376 | w.Header().Set("Content-type", "application/octet-stream") |
| 377 | |
| 378 | io.Copy(w, fp) |
| 379 | } |
| 380 | |
| 381 | func (mod *RestAPI) writeFile(fileName string, w http.ResponseWriter, r *http.Request) { |
| 382 | data, err := ioutil.ReadAll(r.Body) |
| 383 | if err != nil { |
| 384 | msg := fmt.Sprintf("invalid file upload: %s", err) |
| 385 | mod.Warning(msg) |
| 386 | http.Error(w, msg, 404) |
| 387 | return |
| 388 | } |
| 389 | |
| 390 | err = ioutil.WriteFile(fileName, data, 0666) |
| 391 | if err != nil { |
| 392 | msg := fmt.Sprintf("can't write to %s: %s", fileName, err) |
| 393 | mod.Warning(msg) |
| 394 | http.Error(w, msg, 404) |
| 395 | return |
| 396 | } |
| 397 | |
| 398 | mod.toJSON(w, APIResponse{ |
| 399 | Success: true, |
| 400 | Message: fmt.Sprintf("%s created", fileName), |
| 401 | }) |
| 402 | } |
| 403 | |
| 404 | func (mod *RestAPI) eventsRoute(w http.ResponseWriter, r *http.Request) { |
| 405 | mod.setSecurityHeaders(w) |
| 406 | |
| 407 | if !mod.checkAuth(r) { |
| 408 | mod.setAuthFailed(w, r) |
| 409 | return |
| 410 | } |
| 411 | |
| 412 | if r.Method == "GET" { |
| 413 | mod.showEvents(w, r) |
| 414 | } else if r.Method == "DELETE" { |
| 415 | mod.clearEvents(w, r) |
| 416 | } else { |
| 417 | http.Error(w, "Bad Request", 400) |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | func (mod *RestAPI) fileRoute(w http.ResponseWriter, r *http.Request) { |
| 422 | mod.setSecurityHeaders(w) |
| 423 | |
| 424 | if !mod.checkAuth(r) { |
| 425 | mod.setAuthFailed(w, r) |
| 426 | return |
| 427 | } |
| 428 | |
| 429 | fileName := r.URL.Query().Get("name") |
| 430 | |
| 431 | if fileName != "" && r.Method == "GET" { |
| 432 | mod.readFile(fileName, w, r) |
| 433 | } else if fileName != "" && r.Method == "POST" { |
| 434 | mod.writeFile(fileName, w, r) |
| 435 | } else { |
| 436 | http.Error(w, "Bad Request", 400) |
| 437 | } |
| 438 | } |