Refactoring modules

This commit is contained in:
Giuseppe Trotta 2019-02-10 23:58:08 +01:00
commit ed652622e2
89 changed files with 186 additions and 138 deletions

View file

@ -0,0 +1,235 @@
package api_rest
import (
"context"
"fmt"
"net/http"
"time"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/session"
"github.com/bettercap/bettercap/tls"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/evilsocket/islazy/fs"
)
type RestAPI struct {
session.SessionModule
server *http.Server
username string
password string
certFile string
keyFile string
allowOrigin string
useWebsocket bool
upgrader websocket.Upgrader
quit chan bool
}
func NewRestAPI(s *session.Session) *RestAPI {
api := &RestAPI{
SessionModule: session.NewSessionModule("api.rest", s),
server: &http.Server{},
quit: make(chan bool),
useWebsocket: false,
allowOrigin: "*",
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
}
api.AddParam(session.NewStringParameter("api.rest.address",
session.ParamIfaceAddress,
session.IPv4Validator,
"Address to bind the API REST server to."))
api.AddParam(session.NewIntParameter("api.rest.port",
"8081",
"Port to bind the API REST server to."))
api.AddParam(session.NewStringParameter("api.rest.alloworigin",
api.allowOrigin,
"",
"Value of the Access-Control-Allow-Origin header of the API server."))
api.AddParam(session.NewStringParameter("api.rest.username",
"",
"",
"API authentication username."))
api.AddParam(session.NewStringParameter("api.rest.password",
"",
"",
"API authentication password."))
api.AddParam(session.NewStringParameter("api.rest.certificate",
"",
"",
"API TLS certificate."))
tls.CertConfigToModule("api.rest", &api.SessionModule, tls.DefaultLegitConfig)
api.AddParam(session.NewStringParameter("api.rest.key",
"",
"",
"API TLS key"))
api.AddParam(session.NewBoolParameter("api.rest.websocket",
"false",
"If true the /api/events route will be available as a websocket endpoint instead of HTTPS."))
api.AddHandler(session.NewModuleHandler("api.rest on", "",
"Start REST API server.",
func(args []string) error {
return api.Start()
}))
api.AddHandler(session.NewModuleHandler("api.rest off", "",
"Stop REST API server.",
func(args []string) error {
return api.Stop()
}))
return api
}
type JSSessionRequest struct {
Command string `json:"cmd"`
}
type JSSessionResponse struct {
Error string `json:"error"`
}
func (api *RestAPI) Name() string {
return "api.rest"
}
func (api *RestAPI) Description() string {
return "Expose a RESTful API."
}
func (api *RestAPI) Author() string {
return "Simone Margaritelli <evilsocket@protonmail.com>"
}
func (api *RestAPI) isTLS() bool {
return api.certFile != "" && api.keyFile != ""
}
func (api *RestAPI) Configure() error {
var err error
var ip string
var port int
if api.Running() {
return session.ErrAlreadyStarted
} else if err, ip = api.StringParam("api.rest.address"); err != nil {
return err
} else if err, port = api.IntParam("api.rest.port"); err != nil {
return err
} else if err, api.allowOrigin = api.StringParam("api.rest.alloworigin"); err != nil {
return err
} else if err, api.certFile = api.StringParam("api.rest.certificate"); err != nil {
return err
} else if api.certFile, err = fs.Expand(api.certFile); err != nil {
return err
} else if err, api.keyFile = api.StringParam("api.rest.key"); err != nil {
return err
} else if api.keyFile, err = fs.Expand(api.keyFile); err != nil {
return err
} else if err, api.username = api.StringParam("api.rest.username"); err != nil {
return err
} else if err, api.password = api.StringParam("api.rest.password"); err != nil {
return err
} else if err, api.useWebsocket = api.BoolParam("api.rest.websocket"); err != nil {
return err
}
if api.isTLS() {
if !fs.Exists(api.certFile) || !fs.Exists(api.keyFile) {
err, cfg := tls.CertConfigFromModule("api.rest", api.SessionModule)
if err != nil {
return err
}
log.Debug("%+v", cfg)
log.Info("generating TLS key to %s", api.keyFile)
log.Info("generating TLS certificate to %s", api.certFile)
if err := tls.Generate(cfg, api.certFile, api.keyFile); err != nil {
return err
}
} else {
log.Info("loading TLS key from %s", api.keyFile)
log.Info("loading TLS certificate from %s", api.certFile)
}
}
api.server.Addr = fmt.Sprintf("%s:%d", ip, port)
router := mux.NewRouter()
router.HandleFunc("/api/events", api.eventsRoute)
router.HandleFunc("/api/session", api.sessionRoute)
router.HandleFunc("/api/session/ble", api.sessionRoute)
router.HandleFunc("/api/session/ble/{mac}", api.sessionRoute)
router.HandleFunc("/api/session/env", api.sessionRoute)
router.HandleFunc("/api/session/gateway", api.sessionRoute)
router.HandleFunc("/api/session/interface", api.sessionRoute)
router.HandleFunc("/api/session/modules", api.sessionRoute)
router.HandleFunc("/api/session/lan", api.sessionRoute)
router.HandleFunc("/api/session/lan/{mac}", api.sessionRoute)
router.HandleFunc("/api/session/options", api.sessionRoute)
router.HandleFunc("/api/session/packets", api.sessionRoute)
router.HandleFunc("/api/session/started-at", api.sessionRoute)
router.HandleFunc("/api/session/wifi", api.sessionRoute)
router.HandleFunc("/api/session/wifi/{mac}", api.sessionRoute)
api.server.Handler = router
if api.username == "" || api.password == "" {
log.Warning("api.rest.username and/or api.rest.password parameters are empty, authentication is disabled.")
}
return nil
}
func (api *RestAPI) Start() error {
if err := api.Configure(); err != nil {
return err
}
api.SetRunning(true, func() {
var err error
if api.isTLS() {
log.Info("api server starting on https://%s", api.server.Addr)
err = api.server.ListenAndServeTLS(api.certFile, api.keyFile)
} else {
log.Info("api server starting on http://%s", api.server.Addr)
err = api.server.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
panic(err)
}
})
return nil
}
func (api *RestAPI) Stop() error {
return api.SetRunning(false, func() {
go func() {
api.quit <- true
}()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
api.server.Shutdown(ctx)
})
}

View file

@ -0,0 +1,253 @@
package api_rest
import (
"crypto/subtle"
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/session"
"github.com/gorilla/mux"
)
type CommandRequest struct {
Command string `json:"cmd"`
}
type APIResponse struct {
Success bool `json:"success"`
Message string `json:"msg"`
}
func setAuthFailed(w http.ResponseWriter, r *http.Request) {
log.Warning("Unauthorized authentication attempt from %s", r.RemoteAddr)
w.Header().Set("WWW-Authenticate", `Basic realm="auth"`)
w.WriteHeader(401)
w.Write([]byte("Unauthorized"))
}
func toJSON(w http.ResponseWriter, o interface{}) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(o); err != nil {
log.Error("error while encoding object to JSON: %v", err)
}
}
func (api *RestAPI) setSecurityHeaders(w http.ResponseWriter) {
w.Header().Add("X-Frame-Options", "DENY")
w.Header().Add("X-Content-Type-Options", "nosniff")
w.Header().Add("X-XSS-Protection", "1; mode=block")
w.Header().Add("Referrer-Policy", "same-origin")
w.Header().Set("Access-Control-Allow-Origin", api.allowOrigin)
}
func (api *RestAPI) checkAuth(r *http.Request) bool {
if api.username != "" && api.password != "" {
user, pass, _ := r.BasicAuth()
// timing attack my ass
if subtle.ConstantTimeCompare([]byte(user), []byte(api.username)) != 1 {
return false
} else if subtle.ConstantTimeCompare([]byte(pass), []byte(api.password)) != 1 {
return false
}
}
return true
}
func (api *RestAPI) showSession(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I)
}
func (api *RestAPI) showBle(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
mac := strings.ToLower(params["mac"])
if mac == "" {
toJSON(w, session.I.BLE)
} else if dev, found := session.I.BLE.Get(mac); found {
toJSON(w, dev)
} else {
http.Error(w, "Not Found", 404)
}
}
func (api *RestAPI) showEnv(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I.Env)
}
func (api *RestAPI) showGateway(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I.Gateway)
}
func (api *RestAPI) showInterface(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I.Interface)
}
func (api *RestAPI) showModules(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I.Modules)
}
func (api *RestAPI) showLan(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
mac := strings.ToLower(params["mac"])
if mac == "" {
toJSON(w, session.I.Lan)
} else if host, found := session.I.Lan.Get(mac); found {
toJSON(w, host)
} else {
http.Error(w, "Not Found", 404)
}
}
func (api *RestAPI) showOptions(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I.Options)
}
func (api *RestAPI) showPackets(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I.Queue)
}
func (api *RestAPI) showStartedAt(w http.ResponseWriter, r *http.Request) {
toJSON(w, session.I.StartedAt)
}
func (api *RestAPI) showWiFi(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
mac := strings.ToLower(params["mac"])
if mac == "" {
toJSON(w, session.I.WiFi)
} else if station, found := session.I.WiFi.Get(mac); found {
toJSON(w, station)
} else if client, found := session.I.WiFi.GetClient(mac); found {
toJSON(w, client)
} else {
http.Error(w, "Not Found", 404)
}
}
func (api *RestAPI) runSessionCommand(w http.ResponseWriter, r *http.Request) {
var err error
var cmd CommandRequest
if r.Body == nil {
http.Error(w, "Bad Request", 400)
} else if err = json.NewDecoder(r.Body).Decode(&cmd); err != nil {
http.Error(w, "Bad Request", 400)
} else if err = session.I.Run(cmd.Command); err != nil {
http.Error(w, err.Error(), 400)
} else {
toJSON(w, APIResponse{Success: true})
}
}
func (api *RestAPI) showEvents(w http.ResponseWriter, r *http.Request) {
var err error
if api.useWebsocket {
api.startStreamingEvents(w, r)
} else {
events := session.I.Events.Sorted()
nevents := len(events)
nmax := nevents
n := nmax
q := r.URL.Query()
vals := q["n"]
if len(vals) > 0 {
n, err = strconv.Atoi(q["n"][0])
if err == nil {
if n > nmax {
n = nmax
}
} else {
n = nmax
}
}
toJSON(w, events[nevents-n:])
}
}
func (api *RestAPI) clearEvents(w http.ResponseWriter, r *http.Request) {
session.I.Events.Clear()
}
func (api *RestAPI) sessionRoute(w http.ResponseWriter, r *http.Request) {
api.setSecurityHeaders(w)
if !api.checkAuth(r) {
setAuthFailed(w, r)
return
} else if r.Method == "POST" {
api.runSessionCommand(w, r)
return
} else if r.Method != "GET" {
http.Error(w, "Bad Request", 400)
return
}
session.I.Lock()
defer session.I.Unlock()
path := r.URL.String()
switch {
case path == "/api/session":
api.showSession(w, r)
case path == "/api/session/env":
api.showEnv(w, r)
case path == "/api/session/gateway":
api.showGateway(w, r)
case path == "/api/session/interface":
api.showInterface(w, r)
case strings.HasPrefix(path, "/api/session/modules"):
api.showModules(w, r)
case strings.HasPrefix(path, "/api/session/lan"):
api.showLan(w, r)
case path == "/api/session/options":
api.showOptions(w, r)
case path == "/api/session/packets":
api.showPackets(w, r)
case path == "/api/session/started-at":
api.showStartedAt(w, r)
case strings.HasPrefix(path, "/api/session/ble"):
api.showBle(w, r)
case strings.HasPrefix(path, "/api/session/wifi"):
api.showWiFi(w, r)
default:
http.Error(w, "Not Found", 404)
}
}
func (api *RestAPI) eventsRoute(w http.ResponseWriter, r *http.Request) {
api.setSecurityHeaders(w)
if !api.checkAuth(r) {
setAuthFailed(w, r)
return
}
if r.Method == "GET" {
api.showEvents(w, r)
} else if r.Method == "DELETE" {
api.clearEvents(w, r)
} else {
http.Error(w, "Bad Request", 400)
}
}

View file

@ -0,0 +1,118 @@
package api_rest
import (
"encoding/json"
"net/http"
"strings"
"time"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/session"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write an event to the client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
)
func (api *RestAPI) streamEvent(ws *websocket.Conn, event session.Event) error {
msg, err := json.Marshal(event)
if err != nil {
log.Error("Error while creating websocket message: %s", err)
return err
}
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.TextMessage, msg); err != nil {
if !strings.Contains(err.Error(), "closed connection") {
log.Error("Error while writing websocket message: %s", err)
return err
}
}
return nil
}
func (api *RestAPI) sendPing(ws *websocket.Conn) error {
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
log.Error("Error while writing websocket ping message: %s", err)
return err
}
return nil
}
func (api *RestAPI) streamWriter(ws *websocket.Conn, w http.ResponseWriter, r *http.Request) {
defer ws.Close()
// first we stream what we already have
events := session.I.Events.Sorted()
n := len(events)
if n > 0 {
log.Debug("Sending %d events.", n)
for _, event := range events {
if err := api.streamEvent(ws, event); err != nil {
return
}
}
}
session.I.Events.Clear()
log.Debug("Listening for events and streaming to ws endpoint ...")
pingTicker := time.NewTicker(pingPeriod)
listener := session.I.Events.Listen()
defer session.I.Events.Unlisten(listener)
for {
select {
case <-pingTicker.C:
if err := api.sendPing(ws); err != nil {
return
}
case event := <-listener:
if err := api.streamEvent(ws, event); err != nil {
return
}
case <-api.quit:
log.Info("Stopping websocket events streamer ...")
return
}
}
}
func (api *RestAPI) streamReader(ws *websocket.Conn) {
defer ws.Close()
ws.SetReadLimit(512)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, _, err := ws.ReadMessage()
if err != nil {
log.Debug("Closing websocket reader.")
break
}
}
}
func (api *RestAPI) startStreamingEvents(w http.ResponseWriter, r *http.Request) {
ws, err := api.upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Error("Error while updating api.rest connection to websocket: %s", err)
}
return
}
log.Debug("Websocket streaming started for %s", r.RemoteAddr)
go api.streamWriter(ws, w, r)
api.streamReader(ws)
}