From ee4b7830151ea4c886217f4f11b1eca4b34e48f5 Mon Sep 17 00:00:00 2001 From: evilsocket Date: Mon, 8 Jan 2018 04:26:19 +0100 Subject: [PATCH] new: implemented POST /api/session route (ref #5). --- session/modules/api_rest.go | 55 ++++++++++++++++++++++++++++++------- session/session.go | 1 + 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/session/modules/api_rest.go b/session/modules/api_rest.go index a894e8c6..a56a5442 100644 --- a/session/modules/api_rest.go +++ b/session/modules/api_rest.go @@ -57,25 +57,60 @@ func NewRestAPI(s *session.Session) *RestAPI { return api.Stop() })) - http.HandleFunc("/api/session", api.getSession) + http.HandleFunc("/api/session", api.sessRoute) return api } -func (api *RestAPI) getSession(w http.ResponseWriter, r *http.Request) { +type JSSessionRequest struct { + Command string `json:"cmd"` +} + +type JSSessionResponse struct { + Error string `json:"error"` +} + +func (api *RestAPI) sessRoute(w http.ResponseWriter, r *http.Request) { if api.checkAuth(w, r) == false { return } - js, err := json.Marshal(api.Session) - if err != nil { - log.Errorf("Error while returning session: %s", err) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } + if r.Method == "GET" { + js, err := json.Marshal(api.Session) + if err != nil { + log.Errorf("Error while returning session: %s", err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } - w.Header().Set("Content-Type", "application/json") - w.Write(js) + w.Header().Set("Content-Type", "application/json") + w.Write(js) + } else if r.Method == "POST" && r.Body != nil { + var req JSSessionRequest + var res JSSessionResponse + + err := json.NewDecoder(r.Body).Decode(&req) + if err != nil { + http.Error(w, err.Error(), 400) + return + } + + err = api.Session.Run(req.Command) + if err != nil { + res.Error = err.Error() + } + js, err := json.Marshal(res) + if err != nil { + log.Errorf("Error while returning response: %s", err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Write(js) + } else { + http.Error(w, "Not Found", 404) + } } func (api RestAPI) checkAuth(w http.ResponseWriter, r *http.Request) bool { diff --git a/session/session.go b/session/session.go index 8e870749..de64f448 100644 --- a/session/session.go +++ b/session/session.go @@ -141,6 +141,7 @@ func (s *Session) registerCoreHandlers() { "Close the session and exit.", func(args []string, s *Session) error { s.Active = false + s.Input.Close() return nil }))