From f8d95a83ef84bc22260445fd2e6d52bc0096d75f Mon Sep 17 00:00:00 2001 From: Rudi Date: Sat, 23 Apr 2022 10:53:22 -0400 Subject: [PATCH] Ready to Test --- go.mod | 21 ++++++ go.sum | 64 ++++++++++++++++++ main.go | 199 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ types.go | 48 ++++++++++++++ 4 files changed, 332 insertions(+) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go create mode 100644 types.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..15c1cf2 --- /dev/null +++ b/go.mod @@ -0,0 +1,21 @@ +module git.hugfreevikings.wtf/rudi/SecREST + +go 1.18 + +require github.com/gorilla/mux v1.8.0 + +require ( + github.com/ProtonMail/gopenpgp/v2 v2.4.6 + github.com/google/uuid v1.3.0 +) + +require ( + github.com/ProtonMail/go-crypto v0.0.0-20220113124808-70ae35bab23f // indirect + github.com/ProtonMail/go-mime v0.0.0-20220302105931-303f85f7fe0f // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.1 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/sirupsen/logrus v1.4.2 // indirect + golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect + golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 // indirect + golang.org/x/text v0.3.3 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e044c9c --- /dev/null +++ b/go.sum @@ -0,0 +1,64 @@ +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/ProtonMail/go-crypto v0.0.0-20220113124808-70ae35bab23f h1:J2FzIrXN82q5uyUraeJpLIm7U6PffRwje2ORho5yIik= +github.com/ProtonMail/go-crypto v0.0.0-20220113124808-70ae35bab23f/go.mod h1:z4/9nQmJSSwwds7ejkxaJwO37dru3geImFUdJlaLzQo= +github.com/ProtonMail/go-mime v0.0.0-20220302105931-303f85f7fe0f h1:CGq7OieOz3wyQJ1fO8S0eO9TCW1JyvLrf8fhzz1i8ko= +github.com/ProtonMail/go-mime v0.0.0-20220302105931-303f85f7fe0f/go.mod h1:NYt+V3/4rEeDuaev/zw1zCq8uqVEuPHzDPo3OZrlGJ4= +github.com/ProtonMail/gopenpgp/v2 v2.4.6 h1:/EcJsFIsE0ywShAJ+lNLafcaSd6GBhIzHsaBID5pGXw= +github.com/ProtonMail/gopenpgp/v2 v2.4.6/go.mod h1:ZW1KxHNG6q5LMgFKf9Ap/d2eVYeyGf5+fAUEAjJWtmo= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20200801112145-973feb4309de/go.mod h1:skQtrUTUwhdJvXM/2KKJzY8pDgNr9I/FOMqDVRPBUS4= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191209134235-331c550502dd/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200117012304-6edc0a871e69/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/main.go b/main.go new file mode 100644 index 0000000..e6a3869 --- /dev/null +++ b/main.go @@ -0,0 +1,199 @@ +package SecREST + +import ( + "bytes" + "encoding/json" + "log" + "net/http" + "time" + + "github.com/ProtonMail/gopenpgp/v2/helper" + "github.com/google/uuid" + "github.com/gorilla/mux" +) + +var ( + // Handlers that will be called for internall routing after de/encryption + Handlers []SecRESTHandler + // Auth handler + Auth SecRESTAuth + // SERVER public key, armored + PubKey string + // SERVER private key, armored + PrivKey string + // Password for SERVER private key + KeyPass string + // AuthClients is intentionally made non-persistent, expires all clients on reboot. + // This however is open for debate. + AuthClients = make(map[string]string) +) + +// StartRouter accepts a Port string, and a slice of SecRESTHandler +// then starts the router. +func StartRouter(port string, pubKey string, privKey string, keyPass string, handlers []SecRESTHandler, auth SecRESTAuth) { + log.Printf("Initializing SecREST Server") + // Get Config + Handlers = handlers + Auth = auth + PrivKey = privKey + KeyPass = keyPass + PubKey = pubKey + log.Printf("Preparing SecREST Server on port %+v", port) + + r := mux.NewRouter() + + r.HandleFunc("/", handleRoot) + r.HandleFunc("/secure", handleSecure) + r.HandleFunc("/insecure", handleInsecure) + r.HandleFunc("/handshake", handleHandshake) + log.Printf("Starting SecREST Server") + log.Printf("Fatal error serving SecREST: %+v", http.ListenAndServe(":"+port, r)) + +} + +// Serve the base site's basic HTML and JavaScript, maybe via static file? +func handleRoot(w http.ResponseWriter, r *http.Request) { + +} + +// Accept RAW POST of PGP armored text, and decrypt with server key +// should be in SecRESTRequest format +// will respond with SecRESTResponse, encrypted to client +// ClientIdentifier header needs to match UUID in storage +func handleSecure(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/crypt64") + clientIdentifier := w.Header().Get("ClientIdentifier") + if val, ok := AuthClients[clientIdentifier]; !ok { + log.Printf("%+v not found in authorized clients. Returning 401 with empty body.", val) + w.WriteHeader(401) + w.Write(nil) + return + } + buf := new(bytes.Buffer) + buf.ReadFrom(r.Body) + decrypted, err := helper.DecryptVerifyMessageArmored(AuthClients[clientIdentifier], PrivKey, []byte(KeyPass), buf.String()) + if err != nil { + log.Printf("Unable to decrypt request from %+v, returning 500 with empty body.\n%+v", clientIdentifier, err) + w.WriteHeader(500) + w.Write(nil) + return + } + var request SecRESTRequest + err = json.Unmarshal([]byte(decrypted), &request) + if err != nil { + log.Printf("Unable to unmarshal decrypted request from %+v\n%+v", clientIdentifier, err) + w.WriteHeader(500) + w.Write(nil) + return + } + request.Insecure = false + request.TimeStamp = time.Now() + resp := routeRequest(request) + payload, err := json.Marshal(resp) + if err != nil { + log.Printf("Unable to marshal internal response for %+v\n%+v", clientIdentifier, err) + w.WriteHeader(500) + w.Write(nil) + return + } + armor, err := helper.EncryptSignMessageArmored(AuthClients[clientIdentifier], PrivKey, []byte(KeyPass), string(payload)) + if err != nil { + log.Printf("Unable to encrypt and sign message for %+v\n%+v", clientIdentifier, err) + w.WriteHeader(500) + w.Write(nil) + return + } + w.Write([]byte(armor)) + +} + +// Accept JSON Request, will route if destination allows insecure, +// otherwise will respond with HTTP 401 +func handleInsecure(w http.ResponseWriter, r *http.Request) { + ipaddr := r.Header.Get("X-Real-IP") + request := SecRESTRequest{ + TimeStamp: time.Now(), + Insecure: true, + } + w.Header().Set("Content-Type", "application/json") + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&request); err != nil { + log.Printf("Unable to decode request from %+v\n%+v", ipaddr, err) + w.WriteHeader(400) + w.Write(nil) + return + } + defer r.Body.Close() + resp := routeRequest(request) + payload, err := json.Marshal(resp) + if err != nil { + log.Printf("Unable to marshal internal response for %+v\n%+v", ipaddr, err) + w.WriteHeader(500) + w.Write(nil) + return + } + w.Write(payload) +} + +func routeRequest(r SecRESTRequest) SecRESTResponse { + var resp SecRESTResponse + for _, h := range Handlers { + if h.Path == r.Path { + if h.Insecure == r.Insecure { + resp = h.Run(r) + } else { + log.Printf("Client attempted to access secure path \"%+v\" via /insecure but is denied.", r.Path) + resp.Status = 401 + } + } + } + // If resp.Status isn't set above, no matching path found. + if resp.Status == 0 { + log.Printf("Client attempted to access \"%+v\" but it was not found.", r.Path) + resp.Status = 404 + } + resp.Ellapsed = time.Since(r.TimeStamp).String() + return resp +} + +// Request body should contain PGP Public Key for new client, +// and respond with PGP Public Key for Server if authorized. +func handleHandshake(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + ipaddr := r.Header.Get("X-Real-IP") + start := time.Now() + success, req := Auth.Run(w, r) + if success { + w.WriteHeader(200) + clientIdentifier := uuid.New().String() + AuthClients[clientIdentifier] = req.ClientKey + authResp := SecRESTAuthResponse{ + ServerKey: PubKey, + ClientIdentifier: clientIdentifier, + } + resp := SecRESTResponse{ + AuthResponse: authResp, + Ellapsed: time.Since(start).String(), + Status: 200, + Body: "Success", + } + payload, err := json.Marshal(resp) + if err != nil { + log.Printf("Unable to marshal response payload for %+v's successful handshake:\n%+v", clientIdentifier, err) + w.WriteHeader(500) + w.Write(nil) + } + armor, err := helper.EncryptSignMessageArmored(AuthClients[clientIdentifier], PrivKey, []byte(KeyPass), string(payload)) + if err != nil { + log.Printf("Unable to encrypt response payload for %+v's successful handshake:\n%+v", clientIdentifier, err) + w.WriteHeader(500) + w.Write(nil) + } + w.Write([]byte(armor)) + + } else { + log.Printf("%+v tried to authenticate, unsuccessfully.", ipaddr) + w.WriteHeader(418) + w.Write([]byte("no")) + } +} diff --git a/types.go b/types.go new file mode 100644 index 0000000..5da962e --- /dev/null +++ b/types.go @@ -0,0 +1,48 @@ +package SecREST + +import ( + "net/http" + "time" +) + +// SecRESTRequest is a decrypted request coming in from a client +type SecRESTRequest struct { + Path string `json:"Path"` + Body string `json:"Body"` + ClientIdentifier string `json:"ClientIdentifier"` + Insecure bool + TimeStamp time.Time `json:"TimeStamp"` + AuthRequest SecRESTAuthRequest `json:"AuthRequest"` +} + +// SecRESTResponse is a decrypted response to be sent to the client +// Will be encrypted if request.Insecure = false +type SecRESTResponse struct { + Status int `json:"Status"` + Body string `json:"Body"` + Ellapsed string `json:"Ellapsed"` + AuthResponse SecRESTAuthResponse `json:"AuthResponse"` +} + +// Struct for handlers, Insecure = True allows /insecure access +type SecRESTHandler struct { + Path string + Insecure bool + Body string + Run func(SecRESTRequest) SecRESTResponse +} + +// SecRESTAuth struct is for authenticating a client, and storing their PGP key +type SecRESTAuth struct { + // Handle Authentication for new client + Run func(w http.ResponseWriter, r *http.Request) (bool, SecRESTAuthRequest) +} + +type SecRESTAuthResponse struct { + ServerKey string `json:"ServerKey"` + ClientIdentifier string `json:"ClientIdentifier"` +} + +type SecRESTAuthRequest struct { + ClientKey string `json:"ClientKey"` +}