From 33b9ba9abadb8cea8f5840bb11fb9de489b120e3 Mon Sep 17 00:00:00 2001 From: "kali kaneko (leap communications)" Date: Tue, 23 Jun 2020 19:34:47 +0200 Subject: [feat] authentication token for webapi --- pkg/backend/webapi.go | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) (limited to 'pkg/backend/webapi.go') diff --git a/pkg/backend/webapi.go b/pkg/backend/webapi.go index e3918c5..a8844e8 100644 --- a/pkg/backend/webapi.go +++ b/pkg/backend/webapi.go @@ -4,8 +4,35 @@ import ( "fmt" "log" "net/http" + "os" + + "0xacab.org/leap/bitmask-vpn/pkg/bitmask" ) +func Adapt(h http.Handler, adapters ...Adapter) http.Handler { + for _, adapter := range adapters { + h = adapter(h) + } + return h +} + +type Adapter func(http.Handler) http.Handler + +func CheckAuth(token string) Adapter { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t := r.Header.Get("X-Auth-Token") + if t == token { + h.ServeHTTP(w, r) + } else { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("401 - Unauthorized")) + } + + }) + } +} + func webOn(w http.ResponseWriter, r *http.Request) { log.Println("Web UI: on") SwitchOn() @@ -24,12 +51,15 @@ func webStatus(w http.ResponseWriter, r *http.Request) { func webQuit(w http.ResponseWriter, r *http.Request) { log.Println("Web UI: quit") Quit() + os.Exit(0) } func enableWebAPI() { - http.HandleFunc("/vpn/start", webOn) - http.HandleFunc("/vpn/stop", webOff) - http.HandleFunc("/vpn/status", webStatus) - http.HandleFunc("/vpn/quit", webQuit) + bitmask.GenerateAuthToken() + auth := CheckAuth(bitmask.ReadAuthToken()) + http.Handle("/vpn/start", Adapt(http.HandlerFunc(webOn), auth)) + http.Handle("/vpn/stop", Adapt(http.HandlerFunc(webOff), auth)) + http.Handle("/vpn/status", Adapt(http.HandlerFunc(webStatus), auth)) + http.Handle("/vpn/quit", Adapt(http.HandlerFunc(webQuit), auth)) http.ListenAndServe(":8080", nil) } -- cgit v1.2.3