| 1 | package api_rest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "net/http" |
| 7 | "sync" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/bettercap/bettercap/session" |
| 11 | "github.com/bettercap/bettercap/tls" |
| 12 | |
| 13 | "github.com/bettercap/recording" |
| 14 | |
| 15 | "github.com/gorilla/mux" |
| 16 | "github.com/gorilla/websocket" |
| 17 | |
| 18 | "github.com/evilsocket/islazy/fs" |
| 19 | ) |
| 20 | |
| 21 | type RestAPI struct { |
| 22 | session.SessionModule |
| 23 | server *http.Server |
| 24 | username string |
| 25 | password string |
| 26 | certFile string |
| 27 | keyFile string |
| 28 | allowOrigin string |
| 29 | useWebsocket bool |
| 30 | upgrader websocket.Upgrader |
| 31 | quit chan bool |
| 32 | |
| 33 | recClock int |
| 34 | recording bool |
| 35 | recTime int |
| 36 | loading bool |
| 37 | replaying bool |
| 38 | recordFileName string |
| 39 | recordWait *sync.WaitGroup |
| 40 | record *recording.Archive |
| 41 | recStarted time.Time |
| 42 | recStopped time.Time |
| 43 | } |
| 44 | |
| 45 | func NewRestAPI(s *session.Session) *RestAPI { |
| 46 | mod := &RestAPI{ |
| 47 | SessionModule: session.NewSessionModule("api.rest", s), |
| 48 | server: &http.Server{}, |
| 49 | quit: make(chan bool), |
| 50 | useWebsocket: false, |
| 51 | allowOrigin: "*", |
| 52 | upgrader: websocket.Upgrader{ |
| 53 | ReadBufferSize: 1024, |
| 54 | WriteBufferSize: 1024, |
| 55 | }, |
| 56 | recClock: 1, |
| 57 | recording: false, |
| 58 | recTime: 0, |
| 59 | loading: false, |
| 60 | replaying: false, |
| 61 | recordFileName: "", |
| 62 | recordWait: &sync.WaitGroup{}, |
| 63 | record: nil, |
| 64 | } |
| 65 | |
| 66 | mod.State.Store("recording", &mod.recording) |
| 67 | mod.State.Store("rec_clock", &mod.recClock) |
| 68 | mod.State.Store("replaying", &mod.replaying) |
| 69 | mod.State.Store("loading", &mod.loading) |
| 70 | mod.State.Store("load_progress", 0) |
| 71 | mod.State.Store("rec_time", &mod.recTime) |
| 72 | mod.State.Store("rec_filename", &mod.recordFileName) |
| 73 | mod.State.Store("rec_frames", 0) |
| 74 | mod.State.Store("rec_cur_frame", 0) |
| 75 | mod.State.Store("rec_started", &mod.recStarted) |
| 76 | mod.State.Store("rec_stopped", &mod.recStopped) |
| 77 | |
| 78 | mod.AddParam(session.NewStringParameter("api.rest.address", |
| 79 | "127.0.0.1", |
| 80 | session.IPv4Validator, |
| 81 | "Address to bind the API REST server to.")) |
| 82 | |
| 83 | mod.AddParam(session.NewIntParameter("api.rest.port", |
| 84 | "8081", |
| 85 | "Port to bind the API REST server to.")) |
| 86 | |
| 87 | mod.AddParam(session.NewStringParameter("api.rest.alloworigin", |
| 88 | mod.allowOrigin, |
| 89 | "", |
| 90 | "Value of the Access-Control-Allow-Origin header of the API server.")) |
| 91 | |
| 92 | mod.AddParam(session.NewStringParameter("api.rest.username", |
| 93 | "", |
| 94 | "", |
| 95 | "API authentication username.")) |
| 96 | |
| 97 | mod.AddParam(session.NewStringParameter("api.rest.password", |
| 98 | "", |
| 99 | "", |
| 100 | "API authentication password.")) |
| 101 | |
| 102 | mod.AddParam(session.NewStringParameter("api.rest.certificate", |
| 103 | "", |
| 104 | "", |
| 105 | "API TLS certificate.")) |
| 106 | |
| 107 | tls.CertConfigToModule("api.rest", &mod.SessionModule, tls.DefaultLegitConfig) |
| 108 | |
| 109 | mod.AddParam(session.NewStringParameter("api.rest.key", |
| 110 | "", |
| 111 | "", |
| 112 | "API TLS key")) |
| 113 | |
| 114 | mod.AddParam(session.NewBoolParameter("api.rest.websocket", |
| 115 | "false", |
| 116 | "If true the /api/events route will be available as a websocket endpoint instead of HTTPS.")) |
| 117 | |
| 118 | mod.AddHandler(session.NewModuleHandler("api.rest on", "", |
| 119 | "Start REST API server.", |
| 120 | func(args []string) error { |
| 121 | return mod.Start() |
| 122 | })) |
| 123 | |
| 124 | mod.AddHandler(session.NewModuleHandler("api.rest off", "", |
| 125 | "Stop REST API server.", |
| 126 | func(args []string) error { |
| 127 | return mod.Stop() |
| 128 | })) |
| 129 | |
| 130 | mod.AddParam(session.NewIntParameter("api.rest.record.clock", |
| 131 | "1", |
| 132 | "Number of seconds to wait while recording with api.rest.record between one sample and the next one.")) |
| 133 | |
| 134 | mod.AddHandler(session.NewModuleHandler("api.rest.record off", "", |
| 135 | "Stop recording the session.", |
| 136 | func(args []string) error { |
| 137 | return mod.stopRecording() |
| 138 | })) |
| 139 | |
| 140 | mod.AddHandler(session.NewModuleHandler("api.rest.record FILENAME", `api\.rest\.record (.+)`, |
| 141 | "Start polling the rest API periodically recording each sample in a compressed file that can be later replayed.", |
| 142 | func(args []string) error { |
| 143 | return mod.startRecording(args[0]) |
| 144 | })) |
| 145 | |
| 146 | mod.AddHandler(session.NewModuleHandler("api.rest.replay off", "", |
| 147 | "Stop replaying the recorded session.", |
| 148 | func(args []string) error { |
| 149 | return mod.stopReplay() |
| 150 | })) |
| 151 | |
| 152 | mod.AddHandler(session.NewModuleHandler("api.rest.replay FILENAME", `api\.rest\.replay (.+)`, |
| 153 | "Start the rest API module in replay mode using FILENAME as the recorded session file, will revert to normal mode once the replay is over.", |
| 154 | func(args []string) error { |
| 155 | return mod.startReplay(args[0]) |
| 156 | })) |
| 157 | |
| 158 | return mod |
| 159 | } |
| 160 | |
| 161 | type JSSessionRequest struct { |
| 162 | Command string `json:"cmd"` |
| 163 | } |
| 164 | |
| 165 | type JSSessionResponse struct { |
| 166 | Error string `json:"error"` |
| 167 | } |
| 168 | |
| 169 | func (mod *RestAPI) Name() string { |
| 170 | return "api.rest" |
| 171 | } |
| 172 | |
| 173 | func (mod *RestAPI) Description() string { |
| 174 | return "Expose a RESTful API." |
| 175 | } |
| 176 | |
| 177 | func (mod *RestAPI) Author() string { |
| 178 | return "Simone Margaritelli <[email protected]>" |
| 179 | } |
| 180 | |
| 181 | func (mod *RestAPI) isTLS() bool { |
| 182 | return mod.certFile != "" && mod.keyFile != "" |
| 183 | } |
| 184 | |
| 185 | func (mod *RestAPI) Configure() error { |
| 186 | var err error |
| 187 | var ip string |
| 188 | var port int |
| 189 | |
| 190 | if mod.Running() { |
| 191 | return session.ErrAlreadyStarted(mod.Name()) |
| 192 | } else if err, ip = mod.StringParam("api.rest.address"); err != nil { |
| 193 | return err |
| 194 | } else if err, port = mod.IntParam("api.rest.port"); err != nil { |
| 195 | return err |
| 196 | } else if err, mod.allowOrigin = mod.StringParam("api.rest.alloworigin"); err != nil { |
| 197 | return err |
| 198 | } else if err, mod.certFile = mod.StringParam("api.rest.certificate"); err != nil { |
| 199 | return err |
| 200 | } else if mod.certFile, err = fs.Expand(mod.certFile); err != nil { |
| 201 | return err |
| 202 | } else if err, mod.keyFile = mod.StringParam("api.rest.key"); err != nil { |
| 203 | return err |
| 204 | } else if mod.keyFile, err = fs.Expand(mod.keyFile); err != nil { |
| 205 | return err |
| 206 | } else if err, mod.username = mod.StringParam("api.rest.username"); err != nil { |
| 207 | return err |
| 208 | } else if err, mod.password = mod.StringParam("api.rest.password"); err != nil { |
| 209 | return err |
| 210 | } else if err, mod.useWebsocket = mod.BoolParam("api.rest.websocket"); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | |
| 214 | if mod.isTLS() { |
| 215 | if !fs.Exists(mod.certFile) || !fs.Exists(mod.keyFile) { |
| 216 | cfg, err := tls.CertConfigFromModule("api.rest", mod.SessionModule) |
| 217 | if err != nil { |
| 218 | return err |
| 219 | } |
| 220 | |
| 221 | mod.Debug("%+v", cfg) |
| 222 | mod.Info("generating TLS key to %s", mod.keyFile) |
| 223 | mod.Info("generating TLS certificate to %s", mod.certFile) |
| 224 | if err := tls.Generate(cfg, mod.certFile, mod.keyFile, false); err != nil { |
| 225 | return err |
| 226 | } |
| 227 | } else { |
| 228 | mod.Info("loading TLS key from %s", mod.keyFile) |
| 229 | mod.Info("loading TLS certificate from %s", mod.certFile) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | mod.server.Addr = fmt.Sprintf("%s:%d", ip, port) |
| 234 | |
| 235 | router := mux.NewRouter() |
| 236 | |
| 237 | router.Methods("OPTIONS").HandlerFunc(mod.corsRoute) |
| 238 | |
| 239 | router.HandleFunc("/api/file", mod.fileRoute) |
| 240 | |
| 241 | router.HandleFunc("/api/events", mod.eventsRoute) |
| 242 | |
| 243 | router.HandleFunc("/api/session", mod.sessionRoute) |
| 244 | router.HandleFunc("/api/session/ble", mod.sessionRoute) |
| 245 | router.HandleFunc("/api/session/ble/{mac}", mod.sessionRoute) |
| 246 | router.HandleFunc("/api/session/hid", mod.sessionRoute) |
| 247 | router.HandleFunc("/api/session/hid/{mac}", mod.sessionRoute) |
| 248 | router.HandleFunc("/api/session/env", mod.sessionRoute) |
| 249 | router.HandleFunc("/api/session/gateway", mod.sessionRoute) |
| 250 | router.HandleFunc("/api/session/interface", mod.sessionRoute) |
| 251 | router.HandleFunc("/api/session/modules", mod.sessionRoute) |
| 252 | router.HandleFunc("/api/session/lan", mod.sessionRoute) |
| 253 | router.HandleFunc("/api/session/lan/{mac}", mod.sessionRoute) |
| 254 | router.HandleFunc("/api/session/options", mod.sessionRoute) |
| 255 | router.HandleFunc("/api/session/packets", mod.sessionRoute) |
| 256 | router.HandleFunc("/api/session/started-at", mod.sessionRoute) |
| 257 | router.HandleFunc("/api/session/wifi", mod.sessionRoute) |
| 258 | router.HandleFunc("/api/session/wifi/{mac}", mod.sessionRoute) |
| 259 | |
| 260 | mod.server.Handler = router |
| 261 | |
| 262 | if mod.username == "" || mod.password == "" { |
| 263 | mod.Warning("api.rest.username and/or api.rest.password parameters are empty, authentication is disabled.") |
| 264 | } |
| 265 | |
| 266 | return nil |
| 267 | } |
| 268 | |
| 269 | func (mod *RestAPI) Start() error { |
| 270 | if mod.replaying { |
| 271 | return fmt.Errorf("the api is currently in replay mode, run api.rest.replay off before starting it") |
| 272 | } else if err := mod.Configure(); err != nil { |
| 273 | return err |
| 274 | } |
| 275 | |
| 276 | mod.SetRunning(true, func() { |
| 277 | var err error |
| 278 | |
| 279 | if mod.isTLS() { |
| 280 | mod.Info("api server starting on https://%s", mod.server.Addr) |
| 281 | err = mod.server.ListenAndServeTLS(mod.certFile, mod.keyFile) |
| 282 | } else { |
| 283 | mod.Info("api server starting on http://%s", mod.server.Addr) |
| 284 | err = mod.server.ListenAndServe() |
| 285 | } |
| 286 | |
| 287 | if err != nil && err != http.ErrServerClosed { |
| 288 | panic(err) |
| 289 | } |
| 290 | }) |
| 291 | |
| 292 | return nil |
| 293 | } |
| 294 | |
| 295 | func (mod *RestAPI) Stop() error { |
| 296 | if mod.recording { |
| 297 | mod.stopRecording() |
| 298 | } else if mod.replaying { |
| 299 | mod.stopReplay() |
| 300 | } |
| 301 | |
| 302 | return mod.SetRunning(false, func() { |
| 303 | go func() { |
| 304 | mod.quit <- true |
| 305 | }() |
| 306 | |
| 307 | ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| 308 | defer cancel() |
| 309 | mod.server.Shutdown(ctx) |
| 310 | }) |
| 311 | } |