// Package oidc signs people in with an OpenID Connect provider: the // Federated Core's Authelia. The authorization code flow, with PKCE (S256) // and a nonce; the client authenticates to the token endpoint with its // secret in the form (client_secret_post). // // The ID token comes straight from the provider's token endpoint over TLS, // so (as OpenID Connect Core 1.0, 3.1.3.7, allows) its issuer is trusted // from TLS rather than by checking its signature; its claims are checked: // the issuer, the audience, the expiry and the nonce. package oidc import ( "context" "crypto/rand" "crypto/sha256" "crypto/sha512" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" "golang.org/x/crypto/pbkdf2" ) // Provider is what an issuer's discovery document says. type Provider struct { Issuer string `json:"issuer"` Authorization string `json:"authorization_endpoint"` Token string `json:"token_endpoint"` UserInfo string `json:"userinfo_endpoint"` EndSession string `json:"end_session_endpoint"` // empty if the provider has no sign-out Scopes []string `json:"scopes_supported"` PKCEMethods []string `json:"code_challenge_methods_supported"` } // Client is how Supermarket is registered with the provider. type Client struct { ID, Secret string RedirectURI string } // Scopes are what Supermarket asks for. const Scopes = "openid profile email groups" // HTTP is the client used to reach providers; tests replace it. var HTTP = &http.Client{Timeout: 20 * time.Second} // Discover reads an issuer's discovery document, and checks it names the // same issuer and the endpoints the code flow needs. func Discover(ctx context.Context, issuer string) (*Provider, error) { issuer = strings.TrimRight(issuer, "/") req, err := http.NewRequestWithContext(ctx, http.MethodGet, issuer+"/.well-known/openid-configuration", nil) if err != nil { return nil, err } resp, err := HTTP.Do(req) if err != nil { return nil, fmt.Errorf("reaching %s: %w", issuer, err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("%s has no OpenID Connect discovery document (%s)", issuer, resp.Status) } var p Provider if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&p); err != nil { return nil, fmt.Errorf("%s's discovery document can't be read: %w", issuer, err) } if strings.TrimRight(p.Issuer, "/") != issuer { return nil, fmt.Errorf("the discovery document names another issuer (%s)", p.Issuer) } if p.Authorization == "" || p.Token == "" { return nil, errors.New("the discovery document lacks the authorization or token endpoint") } return &p, nil } // Flow is a sign-in under way: kept until the provider sends the browser // back. type Flow struct { State string `json:"state"` Nonce string `json:"nonce"` Verifier string `json:"verifier"` Started time.Time `json:"started"` Next string `json:"next,omitempty"` Browser string `json:"browser,omitempty"` // the hash of the cookie that ties it to a browser } func random() (string, error) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(b), nil } // Start begins a sign-in: the address to send the browser to, and the // flow to keep. statePrefix goes before the random state (the team, on // the multi-tenant edition). func Start(p *Provider, c Client, statePrefix string) (string, *Flow, error) { f := &Flow{Started: time.Now()} var err error if f.State, err = random(); err != nil { return "", nil, err } f.State = statePrefix + f.State if f.Nonce, err = random(); err != nil { return "", nil, err } if f.Verifier, err = random(); err != nil { return "", nil, err } sum := sha256.Sum256([]byte(f.Verifier)) q := url.Values{ "response_type": {"code"}, "client_id": {c.ID}, "redirect_uri": {c.RedirectURI}, "scope": {Scopes}, "state": {f.State}, "nonce": {f.Nonce}, "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}, } sep := "?" if strings.Contains(p.Authorization, "?") { sep = "&" } return p.Authorization + sep + q.Encode(), f, nil } // Identity is who signed in. type Identity struct { Subject string // the provider's ID for them: stable, unlike the email Email string Verified bool // the provider vouches for the email Name string Groups []string IDToken string // for signing out of the provider } // Finish trades the code for tokens, checks the ID token's claims, and // reads who it is (the ID token, completed by the userinfo endpoint). func Finish(ctx context.Context, p *Provider, c Client, f *Flow, code string, now time.Time) (*Identity, error) { form := url.Values{ "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {c.RedirectURI}, "client_id": {c.ID}, "client_secret": {c.Secret}, "code_verifier": {f.Verifier}, } req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.Token, strings.NewReader(form.Encode())) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") resp, err := HTTP.Do(req) if err != nil { return nil, fmt.Errorf("reaching the token endpoint: %w", err) } defer resp.Body.Close() var tok struct { AccessToken string `json:"access_token"` IDToken string `json:"id_token"` Error string `json:"error"` Description string `json:"error_description"` } if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&tok); err != nil { return nil, fmt.Errorf("the token endpoint's answer can't be read (%s)", resp.Status) } if resp.StatusCode != http.StatusOK || tok.Error != "" { return nil, fmt.Errorf("the provider refused the code: %s %s", tok.Error, tok.Description) } claims, err := parseIDToken(tok.IDToken) if err != nil { return nil, err } if err := claims.check(p.Issuer, c.ID, f.Nonce, now); err != nil { return nil, err } id := &Identity{Subject: claims.Subject, Email: claims.Email, Verified: claims.EmailVerified, Name: claims.Name, Groups: claims.Groups, IDToken: tok.IDToken} if p.UserInfo != "" && tok.AccessToken != "" { if ui, err := userInfo(ctx, p.UserInfo, tok.AccessToken); err == nil && ui.Subject == claims.Subject { if ui.Email != "" { id.Email, id.Verified = ui.Email, ui.EmailVerified } if ui.Name != "" { id.Name = ui.Name } if len(ui.Groups) > 0 { id.Groups = ui.Groups } } } if id.Subject == "" { return nil, errors.New("the provider sent no subject") } id.Email = strings.ToLower(strings.TrimSpace(id.Email)) return id, nil } // claims are the ID token's (and userinfo's). type claims struct { Issuer string `json:"iss"` Subject string `json:"sub"` Audience audience `json:"aud"` Expiry int64 `json:"exp"` IssuedAt int64 `json:"iat"` Nonce string `json:"nonce"` Email string `json:"email"` EmailVerified bool `json:"email_verified"` Name string `json:"name"` Groups []string `json:"groups"` } // audience is a string or a list of them. type audience []string func (a *audience) UnmarshalJSON(b []byte) error { var one string if json.Unmarshal(b, &one) == nil { *a = []string{one} return nil } var many []string if err := json.Unmarshal(b, &many); err != nil { return err } *a = many return nil } func parseIDToken(tok string) (*claims, error) { parts := strings.Split(tok, ".") if len(parts) != 3 { return nil, errors.New("the provider sent no ID token") } raw, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil { return nil, errors.New("the ID token can't be read") } var c claims if err := json.Unmarshal(raw, &c); err != nil { return nil, errors.New("the ID token can't be read") } return &c, nil } // leeway allows for clocks that differ a little. const leeway = 2 * time.Minute func (c *claims) check(issuer, clientID, nonce string, now time.Time) error { switch { case strings.TrimRight(c.Issuer, "/") != strings.TrimRight(issuer, "/"): return errors.New("the ID token is from another issuer") case !c.has(clientID): return errors.New("the ID token is for another client") case c.Expiry == 0 || now.After(time.Unix(c.Expiry, 0).Add(leeway)): return errors.New("the ID token has expired: check the server's clock") case c.IssuedAt != 0 && time.Unix(c.IssuedAt, 0).After(now.Add(leeway)): return errors.New("the ID token is from the future: check the server's clock") case nonce == "" || c.Nonce != nonce: return errors.New("the ID token doesn't match this sign-in") } return nil } func (c *claims) has(clientID string) bool { for _, a := range c.Audience { if a == clientID { return true } } return false } func userInfo(ctx context.Context, endpoint, access string) (*claims, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+access) resp, err := HTTP.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("userinfo: %s", resp.Status) } var c claims return &c, json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&c) } // SignOutURL is where to send the browser to sign out of the provider too, // or "" if it has no end-session endpoint. func SignOutURL(p *Provider, idToken, back string) string { if p == nil || p.EndSession == "" { return "" } q := url.Values{"post_logout_redirect_uri": {back}} if idToken != "" { q.Set("id_token_hint", idToken) } sep := "?" if strings.Contains(p.EndSession, "?") { sep = "&" } return p.EndSession + sep + q.Encode() } // Secrets, as Authelia's configuration takes them. // NewSecret is a client secret: 48 random characters. func NewSecret() (string, error) { b := make([]byte, 36) if _, err := rand.Read(b); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(b), nil } // HashRounds is how many PBKDF2 rounds the Core's own clients use. const HashRounds = 310000 // ab64 is passlib's base64: the standard alphabet with . for +, no padding. func ab64(b []byte) string { return strings.ReplaceAll(base64.RawStdEncoding.EncodeToString(b), "+", ".") } // HashSecret is a secret as Authelia's client_secret takes it: // $pbkdf2-sha512$310000$$, like the Core's other clients. func HashSecret(secret string) (string, error) { salt := make([]byte, 16) if _, err := rand.Read(salt); err != nil { return "", err } return hashWith(secret, salt, HashRounds), nil } func hashWith(secret string, salt []byte, rounds int) string { key := pbkdf2.Key([]byte(secret), salt, rounds, sha512.Size, sha512.New) return fmt.Sprintf("$pbkdf2-sha512$%d$%s$%s", rounds, ab64(salt), ab64(key)) } // CheckHash says whether a secret matches a hash from HashSecret. func CheckHash(secret, hash string) bool { parts := strings.Split(hash, "$") if len(parts) != 5 || parts[1] != "pbkdf2-sha512" { return false } var rounds int if _, err := fmt.Sscanf(parts[2], "%d", &rounds); err != nil || rounds < 1 || rounds > 10_000_000 { return false } salt, err := base64.RawStdEncoding.DecodeString(strings.ReplaceAll(parts[3], ".", "+")) if err != nil { return false } return hashWith(secret, salt, rounds) == hash }