2020-11-13 09:43:17 +00:00
|
|
|
package mgmt
|
2020-05-30 23:14:40 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2020-08-14 09:24:32 +00:00
|
|
|
"os"
|
2020-11-05 09:11:17 +00:00
|
|
|
"path/filepath"
|
2020-05-30 23:14:40 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2020-08-14 09:24:32 +00:00
|
|
|
"git.rootprojects.org/root/telebit/dbg"
|
2020-11-13 09:43:17 +00:00
|
|
|
"git.rootprojects.org/root/telebit/internal/mgmt/authstore"
|
|
|
|
|
2020-05-30 23:14:40 +00:00
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
|
|
"github.com/go-chi/chi"
|
|
|
|
"github.com/go-chi/chi/middleware"
|
|
|
|
)
|
|
|
|
|
2020-11-12 13:30:52 +00:00
|
|
|
// MgmtClaims includes a Slug, for backwards compatibility
|
2020-05-30 23:14:40 +00:00
|
|
|
type MgmtClaims struct {
|
|
|
|
Slug string `json:"slug"`
|
|
|
|
jwt.StandardClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
var presenters = make(chan *Challenge)
|
|
|
|
var cleanups = make(chan *Challenge)
|
|
|
|
|
2020-11-13 09:43:17 +00:00
|
|
|
func RouteStatic() chi.Router {
|
2020-11-05 09:11:17 +00:00
|
|
|
r := chi.NewRouter()
|
|
|
|
|
|
|
|
r.Use(middleware.Logger)
|
|
|
|
r.Use(middleware.Timeout(15 * time.Second))
|
|
|
|
r.Use(middleware.Recoverer)
|
|
|
|
|
|
|
|
r.Get("/.well-known/acme-challenge/{token}", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
//token := chi.URLParam(r, "token")
|
2020-11-05 09:40:19 +00:00
|
|
|
host := r.Host
|
2020-11-05 09:11:17 +00:00
|
|
|
if strings.ContainsAny(host, "/:|\\") {
|
|
|
|
host = ""
|
|
|
|
}
|
|
|
|
tokenPath := filepath.Join(tmpBase, host)
|
|
|
|
|
|
|
|
fsrv := http.FileServer(http.Dir(tokenPath))
|
|
|
|
fsrv.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
2020-11-13 09:43:17 +00:00
|
|
|
func RouteAll() chi.Router {
|
2020-05-30 23:14:40 +00:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
// TODO make parallel?
|
|
|
|
// TODO make cancellable?
|
|
|
|
ch := <-presenters
|
|
|
|
err := provider.Present(ch.Domain, ch.Token, ch.KeyAuth)
|
|
|
|
ch.error <- err
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
// TODO make parallel?
|
|
|
|
// TODO make cancellable?
|
|
|
|
ch := <-cleanups
|
|
|
|
ch.error <- provider.CleanUp(ch.Domain, ch.Token, ch.KeyAuth)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
r := chi.NewRouter()
|
|
|
|
r.Use(middleware.Logger)
|
|
|
|
r.Use(middleware.Timeout(15 * time.Second))
|
|
|
|
r.Use(middleware.Recoverer)
|
|
|
|
|
|
|
|
r.Route("/api", func(r chi.Router) {
|
|
|
|
r.Use(func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
|
|
|
var tokenString string
|
|
|
|
if auth := strings.Split(r.Header.Get("Authorization"), " "); len(auth) > 1 {
|
|
|
|
// TODO handle Basic auth tokens as well
|
|
|
|
tokenString = auth[1]
|
|
|
|
}
|
|
|
|
|
|
|
|
//var err2 error = nil
|
|
|
|
tok, err := jwt.ParseWithClaims(
|
|
|
|
tokenString,
|
|
|
|
&MgmtClaims{},
|
|
|
|
func(token *jwt.Token) (interface{}, error) {
|
2020-08-14 09:24:32 +00:00
|
|
|
if dbg.Debug {
|
|
|
|
fmt.Println("parsed jwt", token)
|
|
|
|
}
|
2020-05-30 23:14:40 +00:00
|
|
|
kid, ok := token.Header["kid"].(string)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("missing jwt header 'kid' (key id)")
|
|
|
|
}
|
|
|
|
auth, err := store.Get(kid)
|
|
|
|
if nil != err {
|
|
|
|
return nil, fmt.Errorf("invalid jwt header 'kid' (key id)")
|
|
|
|
}
|
|
|
|
|
|
|
|
claims := token.Claims.(*MgmtClaims)
|
|
|
|
jti := claims.Id
|
|
|
|
if "" == jti {
|
|
|
|
return nil, fmt.Errorf("missing jwt payload 'jti' (jwt id / nonce)")
|
|
|
|
}
|
|
|
|
iat := claims.IssuedAt
|
|
|
|
if 0 == iat {
|
|
|
|
return nil, fmt.Errorf("missing jwt payload 'iat' (issued at)")
|
|
|
|
}
|
|
|
|
exp := claims.ExpiresAt
|
|
|
|
if 0 == exp {
|
|
|
|
return nil, fmt.Errorf("missing jwt payload 'exp' (expires at)")
|
|
|
|
}
|
|
|
|
|
|
|
|
if "" != claims.Slug {
|
|
|
|
return nil, fmt.Errorf("extra jwt payload 'slug' (unknown)")
|
|
|
|
}
|
|
|
|
claims.Slug = auth.Slug
|
2020-06-22 06:34:42 +00:00
|
|
|
if "" != claims.Subject && auth.Slug != claims.Subject {
|
|
|
|
return nil, fmt.Errorf("invalid jwt payload 'sub' (mismatch)")
|
|
|
|
}
|
2020-07-22 03:56:46 +00:00
|
|
|
claims.Subject = claims.Slug
|
2020-11-13 09:43:17 +00:00
|
|
|
claims.Issuer = DeviceDomain
|
|
|
|
claims.Audience = fmt.Sprintf("wss://%s/ws", RelayDomain)
|
2020-05-30 23:14:40 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
// a little misdirection there
|
|
|
|
mac := hmac.New(sha256.New, auth.MachinePPID)
|
|
|
|
_ = mac.Write([]byte(auth.SharedKey))
|
|
|
|
_ = mac.Write([]byte(fmt.Sprintf("%d", exp)))
|
|
|
|
return []byte(auth.SharedKey), nil
|
|
|
|
*/
|
|
|
|
|
2020-06-22 06:34:42 +00:00
|
|
|
//fmt.Println("ppid:", auth.MachinePPID)
|
2020-05-31 12:19:41 +00:00
|
|
|
|
2020-05-30 23:14:40 +00:00
|
|
|
return []byte(auth.MachinePPID), nil
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
2020-05-31 12:19:41 +00:00
|
|
|
ctx := r.Context()
|
2020-05-30 23:14:40 +00:00
|
|
|
if nil != tok {
|
|
|
|
if tok.Valid {
|
2020-05-31 12:19:41 +00:00
|
|
|
ctx = context.WithValue(ctx, MWKey("token"), tok)
|
|
|
|
ctx = context.WithValue(ctx, MWKey("claims"), tok.Claims)
|
|
|
|
ctx = context.WithValue(ctx, MWKey("valid"), true)
|
2020-08-14 09:24:32 +00:00
|
|
|
fmt.Println("[auth] Token is fully valid:")
|
|
|
|
fmt.Println(ctx.Value(MWKey("claims")))
|
|
|
|
} else {
|
|
|
|
fmt.Println("[auth] Token was parsed, but NOT valid:", tok)
|
2020-05-30 23:14:40 +00:00
|
|
|
}
|
|
|
|
}
|
2020-08-14 09:24:32 +00:00
|
|
|
if nil != err {
|
|
|
|
fmt.Println("[auth] Token is NOT valid due to error:", err)
|
|
|
|
ctx = context.WithValue(ctx, MWKey("error"), err)
|
|
|
|
}
|
2020-05-30 23:14:40 +00:00
|
|
|
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
handleDNSRoutes(r)
|
|
|
|
handleDeviceRoutes(r)
|
|
|
|
|
2020-06-01 07:38:18 +00:00
|
|
|
r.Get("/inspect", func(w http.ResponseWriter, r *http.Request) {
|
2020-05-31 13:02:46 +00:00
|
|
|
ctx := r.Context()
|
|
|
|
claims, ok := ctx.Value(MWKey("claims")).(*MgmtClaims)
|
|
|
|
if !ok {
|
2020-08-14 09:24:32 +00:00
|
|
|
msg := `{"error":"failure to ping: 3", "code":"E_TOKEN"}`
|
2020-05-31 13:02:46 +00:00
|
|
|
fmt.Println("touch no claims", claims)
|
|
|
|
http.Error(w, msg+"\n", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-06-22 06:34:42 +00:00
|
|
|
w.Write([]byte(fmt.Sprintf(
|
2020-07-22 03:56:46 +00:00
|
|
|
`{ "sub": "%s", "aud": "%s", "domains": [ "%s.%s" ], "ports": [] }`+"\n",
|
2020-06-22 06:34:42 +00:00
|
|
|
claims.Subject,
|
2020-07-22 03:56:46 +00:00
|
|
|
claims.Audience,
|
2020-06-22 06:34:42 +00:00
|
|
|
claims.Slug,
|
2020-11-13 09:43:17 +00:00
|
|
|
DeviceDomain,
|
2020-06-22 06:34:42 +00:00
|
|
|
)))
|
2020-05-31 13:02:46 +00:00
|
|
|
})
|
|
|
|
|
2020-05-30 23:14:40 +00:00
|
|
|
r.Route("/register-device", func(r chi.Router) {
|
|
|
|
// r.Use() // must NOT have slug '*'
|
|
|
|
|
|
|
|
r.Post("/{otp}", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
sharedKey := chi.URLParam(r, "otp")
|
|
|
|
original, err := store.Get(sharedKey)
|
2020-08-13 09:48:21 +00:00
|
|
|
if nil != err {
|
2020-08-14 09:24:32 +00:00
|
|
|
msg := `{"error":"not found", "code":"E_NOT_FOUND"}`
|
2020-08-13 09:48:21 +00:00
|
|
|
log.Printf("/api/register-device/\n")
|
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, msg, http.StatusNotFound)
|
2020-08-14 08:17:13 +00:00
|
|
|
return
|
2020-08-13 09:48:21 +00:00
|
|
|
}
|
2020-11-12 13:30:52 +00:00
|
|
|
if len(original.MachinePPID) > 0 {
|
2020-08-14 09:24:32 +00:00
|
|
|
msg := `{"error":"the presented key has already been used", "code":"E_EXIST"}`
|
2020-05-30 23:14:40 +00:00
|
|
|
log.Printf("/api/register-device/\n")
|
|
|
|
log.Println(err)
|
2020-08-14 09:24:32 +00:00
|
|
|
http.Error(w, msg, http.StatusUnprocessableEntity)
|
2020-05-30 23:14:40 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
auth := &authstore.Authorization{}
|
|
|
|
decoder := json.NewDecoder(r.Body)
|
|
|
|
err = decoder.Decode(&auth)
|
|
|
|
// MachinePPID and PublicKey are required. ID must NOT be set. Slug is ignored.
|
|
|
|
epoch := time.Time{}
|
|
|
|
auth.SharedKey = sharedKey
|
|
|
|
if nil != err || "" != auth.ID || "" == auth.MachinePPID ||
|
|
|
|
"" == auth.PublicKey || "" == auth.SharedKey ||
|
|
|
|
epoch != auth.CreatedAt || epoch != auth.UpdatedAt || epoch != auth.DeletedAt {
|
|
|
|
msg, _ := json.Marshal(&struct {
|
|
|
|
Error string `json:"error"`
|
|
|
|
}{
|
|
|
|
Error: "expected JSON in the format {\"machine_ppid\":\"\",\"public_key\":\"\"}",
|
|
|
|
})
|
|
|
|
http.Error(w, string(msg), http.StatusUnprocessableEntity)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO hash the PPID and check against the Public Key?
|
2020-05-31 12:19:41 +00:00
|
|
|
pub := authstore.ToPublicKeyString(auth.MachinePPID)
|
|
|
|
if pub != auth.PublicKey {
|
|
|
|
msg, _ := json.Marshal(&struct {
|
|
|
|
Error string `json:"error"`
|
|
|
|
}{
|
|
|
|
Error: "expected `public_key` to be the first 24 bytes of the hash of the `machine_ppid`",
|
|
|
|
})
|
|
|
|
http.Error(w, string(msg), http.StatusUnprocessableEntity)
|
|
|
|
return
|
|
|
|
}
|
2020-05-30 23:14:40 +00:00
|
|
|
original.PublicKey = auth.PublicKey
|
|
|
|
original.MachinePPID = auth.MachinePPID
|
|
|
|
err = store.Set(original)
|
|
|
|
if nil != err {
|
2020-08-14 09:24:32 +00:00
|
|
|
msg := `{"error":"not really sure what happened, but it didn't go well (check the logs)", "code":"E_SERVER"}`
|
2020-05-30 23:14:40 +00:00
|
|
|
log.Printf("/api/register-device/\n")
|
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, msg, http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
result, _ := json.Marshal(auth)
|
|
|
|
w.Write(result)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2020-05-31 12:19:41 +00:00
|
|
|
r.Post("/ping", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
claims, ok := ctx.Value(MWKey("claims")).(*MgmtClaims)
|
|
|
|
if !ok {
|
2020-08-14 09:24:32 +00:00
|
|
|
msg := `{"error":"failure to ping: 1", "code":"E_TOKEN"}`
|
2020-05-31 12:19:41 +00:00
|
|
|
http.Error(w, msg+"\n", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println("ping pong??", claims)
|
|
|
|
err := store.Touch(claims.Slug)
|
|
|
|
if nil != err {
|
2020-08-14 09:24:32 +00:00
|
|
|
fmt.Fprintf(os.Stderr, "touch err %s\n", err)
|
|
|
|
var msg string
|
|
|
|
if err == authstore.ErrNotFound {
|
|
|
|
// if the token is valid, touch should ALWAYS work
|
|
|
|
msg = `{"error":"failure to ping: inconsistent database data", "code":"E_SERVER"}`
|
|
|
|
} else {
|
|
|
|
msg = `{"error":"failure to ping: 2", "code":"E_SERVER"}`
|
|
|
|
}
|
2020-05-31 12:19:41 +00:00
|
|
|
http.Error(w, msg+"\n", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Write([]byte(`{ "success": true }` + "\n"))
|
|
|
|
})
|
|
|
|
|
2020-05-30 23:14:40 +00:00
|
|
|
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
2020-05-31 12:19:41 +00:00
|
|
|
w.Write([]byte("Hello\n"))
|
2020-05-30 23:14:40 +00:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
return r
|
|
|
|
}
|