tracker/middleware/jwt/jwt.go

252 lines
6.1 KiB
Go
Raw Normal View History

2016-09-01 03:09:34 +02:00
// Package jwt implements a Hook that fails an Announce if the client's request
// is missing a valid JSON Web Token.
//
// JWTs are validated against the standard claims in RFC7519 along with an
// extra "infohash" claim that verifies the client has access to the Swarm.
// RS256 keys are asychronously rotated from a provided JWK Set HTTP endpoint.
package jwt
import (
"context"
"crypto"
"encoding/hex"
2016-09-01 03:09:34 +02:00
"encoding/json"
"errors"
2017-12-23 20:54:51 +01:00
"fmt"
2016-09-01 03:09:34 +02:00
"net/http"
"strings"
2016-09-01 03:09:34 +02:00
"time"
jc "github.com/SermoDigital/jose/crypto"
"github.com/SermoDigital/jose/jws"
"github.com/SermoDigital/jose/jwt"
"github.com/mendsley/gojwk"
yaml "gopkg.in/yaml.v2"
2016-09-01 03:09:34 +02:00
"github.com/chihaya/chihaya/bittorrent"
"github.com/chihaya/chihaya/middleware"
2017-06-20 14:58:44 +02:00
"github.com/chihaya/chihaya/pkg/log"
"github.com/chihaya/chihaya/pkg/stop"
2016-09-01 03:09:34 +02:00
)
2017-12-23 20:54:51 +01:00
// Name is the name by which this middleware is registered with Chihaya.
const Name = "jwt"
func init() {
middleware.RegisterDriver(Name, driver{})
}
var _ middleware.Driver = driver{}
type driver struct{}
func (d driver) NewHook(optionBytes []byte) (middleware.Hook, error) {
var cfg Config
err := yaml.Unmarshal(optionBytes, &cfg)
if err != nil {
2022-01-16 05:28:52 +01:00
return nil, fmt.Errorf("invalid options for middleware %s: %w", Name, err)
2017-12-23 20:54:51 +01:00
}
return NewHook(cfg)
}
2016-09-01 03:09:34 +02:00
var (
// ErrMissingJWT is returned when a JWT is missing from a request.
ErrMissingJWT = bittorrent.ClientError("unapproved request: missing jwt")
// ErrInvalidJWT is returned when a JWT fails to verify.
ErrInvalidJWT = bittorrent.ClientError("unapproved request: invalid jwt")
)
// Config represents all the values required by this middleware to fetch JWKs
// and verify JWTs.
type Config struct {
Issuer string `yaml:"issuer"`
Audience string `yaml:"audience"`
JWKSetURL string `yaml:"jwk_set_url"`
JWKUpdateInterval time.Duration `yaml:"jwk_set_update_interval"`
}
2017-06-20 14:58:44 +02:00
// LogFields implements log.Fielder for a Config.
func (cfg Config) LogFields() log.Fields {
return log.Fields{
"issuer": cfg.Issuer,
"audience": cfg.Audience,
"JWKSetURL": cfg.JWKSetURL,
"JWKUpdateInterval": cfg.JWKUpdateInterval,
}
}
2016-09-01 03:09:34 +02:00
type hook struct {
cfg Config
publicKeys map[string]crypto.PublicKey
closing chan struct{}
}
// NewHook returns an instance of the JWT middleware.
func NewHook(cfg Config) (middleware.Hook, error) {
2017-06-20 14:58:44 +02:00
log.Debug("creating new JWT middleware", cfg)
2016-09-01 03:09:34 +02:00
h := &hook{
cfg: cfg,
publicKeys: map[string]crypto.PublicKey{},
closing: make(chan struct{}),
}
log.Debug("performing initial fetch of JWKs")
2022-01-16 05:28:52 +01:00
if err := h.updateKeys(); err != nil {
return nil, errors.New("failed to fetch initial JWK Set: " + err.Error())
}
2016-09-01 03:09:34 +02:00
go func() {
for {
select {
case <-h.closing:
return
case <-time.After(cfg.JWKUpdateInterval):
log.Debug("performing fetch of JWKs")
2022-01-15 19:31:14 +01:00
_ = h.updateKeys()
2016-09-01 03:09:34 +02:00
}
}
}()
return h, nil
2016-09-01 03:09:34 +02:00
}
func (h *hook) updateKeys() error {
resp, err := http.Get(h.cfg.JWKSetURL)
if err != nil {
2017-06-20 14:58:44 +02:00
log.Error("failed to fetch JWK Set", log.Err(err))
return err
}
var parsedJWKs gojwk.Key
err = json.NewDecoder(resp.Body).Decode(&parsedJWKs)
if err != nil {
resp.Body.Close()
2017-06-20 14:58:44 +02:00
log.Error("failed to decode JWK JSON", log.Err(err))
return err
}
resp.Body.Close()
keys := map[string]crypto.PublicKey{}
for _, parsedJWK := range parsedJWKs.Keys {
publicKey, err := parsedJWK.DecodePublicKey()
if err != nil {
2017-06-20 14:58:44 +02:00
log.Error("failed to decode JWK into public key", log.Err(err))
return err
}
keys[parsedJWK.Kid] = publicKey
}
h.publicKeys = keys
log.Debug("successfully fetched JWK Set")
return nil
}
func (h *hook) Stop() stop.Result {
log.Debug("attempting to shutdown JWT middleware")
2016-09-24 19:38:05 +02:00
select {
case <-h.closing:
return stop.AlreadyStopped
2016-09-24 19:38:05 +02:00
default:
}
c := make(stop.Channel)
2016-09-24 19:38:05 +02:00
go func() {
close(h.closing)
c.Done()
2016-09-24 19:38:05 +02:00
}()
return c.Result()
2016-09-01 03:09:34 +02:00
}
func (h *hook) HandleAnnounce(ctx context.Context, req *bittorrent.AnnounceRequest, resp *bittorrent.AnnounceResponse) (context.Context, error) {
2016-09-01 03:09:34 +02:00
if req.Params == nil {
return ctx, ErrMissingJWT
2016-09-01 03:09:34 +02:00
}
jwtParam, ok := req.Params.String("jwt")
if !ok {
return ctx, ErrMissingJWT
2016-09-01 03:09:34 +02:00
}
if err := validateJWT(req.InfoHash, []byte(jwtParam), h.cfg.Issuer, h.cfg.Audience, h.publicKeys); err != nil {
return ctx, ErrInvalidJWT
2016-09-01 03:09:34 +02:00
}
return ctx, nil
2016-09-01 03:09:34 +02:00
}
func (h *hook) HandleScrape(ctx context.Context, req *bittorrent.ScrapeRequest, resp *bittorrent.ScrapeResponse) (context.Context, error) {
2016-09-01 03:09:34 +02:00
// Scrapes don't require any protection.
return ctx, nil
2016-09-01 03:09:34 +02:00
}
func validateJWT(ih bittorrent.InfoHash, jwtBytes []byte, cfgIss, cfgAud string, publicKeys map[string]crypto.PublicKey) error {
parsedJWT, err := jws.ParseJWT(jwtBytes)
if err != nil {
return err
}
claims := parsedJWT.Claims()
if iss, ok := claims.Issuer(); !ok || iss != cfgIss {
2017-06-20 14:58:44 +02:00
log.Debug("unequal or missing issuer when validating JWT", log.Fields{
"exists": ok,
"claim": iss,
"config": cfgIss,
2017-06-20 14:58:44 +02:00
})
2016-09-01 03:09:34 +02:00
return jwt.ErrInvalidISSClaim
}
if auds, ok := claims.Audience(); !ok || !in(cfgAud, auds) {
2017-06-20 14:58:44 +02:00
log.Debug("unequal or missing audience when validating JWT", log.Fields{
"exists": ok,
"claim": strings.Join(auds, ","),
"config": cfgAud,
2017-06-20 14:58:44 +02:00
})
2016-09-01 03:09:34 +02:00
return jwt.ErrInvalidAUDClaim
}
ihHex := hex.EncodeToString(ih[:])
if ihClaim, ok := claims.Get("infohash").(string); !ok || ihClaim != ihHex {
2017-06-20 14:58:44 +02:00
log.Debug("unequal or missing infohash when validating JWT", log.Fields{
"exists": ok,
"claim": ihClaim,
"request": ihHex,
2017-06-20 14:58:44 +02:00
})
2016-09-01 03:09:34 +02:00
return errors.New("claim \"infohash\" is invalid")
}
parsedJWS := parsedJWT.(jws.JWS)
kid, ok := parsedJWS.Protected().Get("kid").(string)
if !ok {
2017-06-20 14:58:44 +02:00
log.Debug("missing kid when validating JWT", log.Fields{
"exists": ok,
"claim": kid,
2017-06-20 14:58:44 +02:00
})
2016-09-01 03:09:34 +02:00
return errors.New("invalid kid")
}
publicKey, ok := publicKeys[kid]
if !ok {
2017-06-20 14:58:44 +02:00
log.Debug("missing public key forkid when validating JWT", log.Fields{
"kid": kid,
2017-06-20 14:58:44 +02:00
})
2016-09-01 03:09:34 +02:00
return errors.New("signed by unknown kid")
}
err = parsedJWS.Verify(publicKey, jc.SigningMethodRS256)
if err != nil {
2017-06-20 14:58:44 +02:00
log.Debug("failed to verify signature of JWT", log.Err(err))
return err
}
return nil
2016-09-01 03:09:34 +02:00
}
func in(x string, xs []string) bool {
for _, y := range xs {
if x == y {
2016-09-01 03:09:34 +02:00
return true
}
}
return false
}