new: implemented POST /api/session route (ref #5).

This commit is contained in:
evilsocket 2018-01-08 04:26:19 +01:00
parent c2826c9094
commit ee4b783015
2 changed files with 46 additions and 10 deletions

View file

@ -57,25 +57,60 @@ func NewRestAPI(s *session.Session) *RestAPI {
return api.Stop() return api.Stop()
})) }))
http.HandleFunc("/api/session", api.getSession) http.HandleFunc("/api/session", api.sessRoute)
return api 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 { if api.checkAuth(w, r) == false {
return return
} }
js, err := json.Marshal(api.Session) if r.Method == "GET" {
if err != nil { js, err := json.Marshal(api.Session)
log.Errorf("Error while returning session: %s", err) if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) log.Errorf("Error while returning session: %s", err)
return http.Error(w, err.Error(), http.StatusInternalServerError)
} return
}
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write(js) 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 { func (api RestAPI) checkAuth(w http.ResponseWriter, r *http.Request) bool {

View file

@ -141,6 +141,7 @@ func (s *Session) registerCoreHandlers() {
"Close the session and exit.", "Close the session and exit.",
func(args []string, s *Session) error { func(args []string, s *Session) error {
s.Active = false s.Active = false
s.Input.Close()
return nil return nil
})) }))