sso.go 7.01 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12 13
package sso

import (
	"encoding/base64"
	"errors"
	"strconv"
	"strings"
	"time"

	"golang.org/x/crypto/ed25519"
)

var (
14 15 16 17 18 19 20 21 22
	// ErrMissingRequiredField is returned when a ticket does not
	// contain a required field.
	ErrMissingRequiredField = errors.New("missing required field")

	// ErrDeserialization means that the input is not valid base64.
	ErrDeserialization = errors.New("deserialization error")

	// ErrUnsupportedTicketVersion is returned for unsupported
	// ticket versions (either too old or too recent).
ale's avatar
ale committed
23
	ErrUnsupportedTicketVersion = errors.New("unsupported ticket version")
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

	// ErrMessageTooShort means that the input is shorter than the
	// fixed signature length + minimum ticket size.
	ErrMessageTooShort = errors.New("encoded message too short")

	// ErrBadSignature is returned when the signature does not
	// match the given public key.
	ErrBadSignature = errors.New("bad signature")

	// ErrBadService is returned when validation fails due to a
	// SSO service mismatch.
	ErrBadService = errors.New("service mismatch")

	// ErrBadDomain is returned when validation fails due to a SSO
	// domain mismatch.
	ErrBadDomain = errors.New("auth domain mismatch")

	// ErrBadNonce is returned when validation fails due to a
	// nonce mismatch.
	ErrBadNonce = errors.New("nonce mismatch")

	// ErrExpired means the ticket has expired.
	ErrExpired = errors.New("ticket expired")

	// ErrUnauthorized is returned when the user lacks the
	// necessary group membership.
	ErrUnauthorized = errors.New("unauthorized")
ale's avatar
ale committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
)

const (
	ticketVersion    = "4"
	separatorCh      = "|"
	groupSeparatorCh = ","
	charsToEscape    = "%|,"

	signatureLen = ed25519.SignatureSize
)

func escapeField(s string) string {
	if strings.ContainsAny(s, charsToEscape) {
		s = strings.Replace(s, "%", "%25", -1)
		s = strings.Replace(s, "|", "%7C", -1)
		s = strings.Replace(s, ",", "%2C", -1)
	}
	return s
}

func unescapeField(s string) string {
	s = strings.Replace(s, "%2C", ",", -1)
	s = strings.Replace(s, "%7C", "|", -1)
	s = strings.Replace(s, "%25", "%", -1)
	return s
}

// A Ticket attests a user's identity within the scope of a specific
// service, when properly signed.
type Ticket struct {
	User    string
	Service string
	Domain  string
	Nonce   string
	Groups  []string
	Expires time.Time
}

func (t *Ticket) validateFields() error {
	if t.User == "" || t.Service == "" || t.Domain == "" {
		return ErrMissingRequiredField
	}
	return nil
}

func (t *Ticket) serialize() string {
	var escapedGroups []string
	for _, g := range t.Groups {
		escapedGroups = append(escapedGroups, escapeField(g))
	}
	return strings.Join(
		[]string{
			ticketVersion,
			escapeField(t.User),
			escapeField(t.Service),
			escapeField(t.Domain),
			escapeField(t.Nonce),
			strconv.FormatInt(t.Expires.Unix(), 10),
			strings.Join(escapedGroups, groupSeparatorCh),
		},
		separatorCh,
	)
}

func deserializeTicket(s string) (*Ticket, error) {
	parts := strings.Split(s, separatorCh)
	if len(parts) != 7 {
		return nil, ErrDeserialization
	}

	if parts[0] != ticketVersion {
		return nil, ErrUnsupportedTicketVersion
	}

	secs, err := strconv.ParseInt(parts[5], 10, 64)
	if err != nil {
		return nil, ErrDeserialization
	}

	var groups []string
	for _, g := range strings.Split(parts[6], groupSeparatorCh) {
		groups = append(groups, unescapeField(g))
	}

	return &Ticket{
		User:    unescapeField(parts[1]),
		Service: unescapeField(parts[2]),
		Domain:  unescapeField(parts[3]),
		Nonce:   unescapeField(parts[4]),
		Expires: time.Unix(secs, 0),
		Groups:  groups,
	}, nil
}

// NewTicket creates a new Ticket, filling in all required values.
func NewTicket(user, service, domain, nonce string, groups []string, validity time.Duration) *Ticket {
	// Let's set nanoseconds to 0 - they don't go over the wire anyway.
	expires := time.Now().Add(validity)
	expires = time.Unix(expires.Unix(), 0)

	return &Ticket{
		User:    user,
		Service: service,
		Domain:  domain,
		Nonce:   nonce,
		Groups:  groups,
		Expires: expires,
	}
}

// A Signer can sign tickets.
type Signer interface {
	Sign(*Ticket) (string, error)
}

type ssoSigner struct {
	key ed25519.PrivateKey
}

// NewSigner creates a new ED25519 signer with the given private key.
func NewSigner(privateKey []byte) (Signer, error) {
	if len(privateKey) != ed25519.PrivateKeySize {
		return nil, errors.New("bad key size")
	}
	return &ssoSigner{key: privateKey}, nil
}

func (s *ssoSigner) Sign(t *Ticket) (string, error) {
	if err := t.validateFields(); err != nil {
		return "", err
	}

	serialized := []byte(t.serialize())
	signature := ed25519.Sign(s.key, serialized)
	signed := append(signature, serialized...)
	return base64.RawURLEncoding.EncodeToString(signed), nil
}

// A Validator can verify that a ticket is valid.
type Validator interface {
	Validate(string, string, string, []string) (*Ticket, error)
}

type ssoValidator struct {
	publicKey ed25519.PublicKey
	domain    string
}

// NewValidator creates a new ED25519 validator for a specific domain,
// with the provided public key.
func NewValidator(publicKey []byte, domain string) (Validator, error) {
	if len(publicKey) != ed25519.PublicKeySize {
		return nil, errors.New("bad key size")
	}
	if domain == "" {
		return nil, errors.New("empty domain")
	}
	return &ssoValidator{
		publicKey: publicKey,
		domain:    domain,
	}, nil
}

func (v *ssoValidator) parse(encoded string) (*Ticket, error) {
	decoded, err := base64.RawURLEncoding.DecodeString(encoded)
	if err != nil {
		return nil, err
	}

	if len(decoded) < signatureLen {
		return nil, ErrMessageTooShort
	}
	serialized := decoded[signatureLen:]
	signature := decoded[:signatureLen]
	if !ed25519.Verify(v.publicKey, serialized, signature) {
		return nil, ErrBadSignature
	}

	return deserializeTicket(string(serialized))
}

func anyGroupAllowed(allowedGroups, groups []string) bool {
	for _, g := range groups {
		for _, ag := range allowedGroups {
			if g == ag {
				return true
			}
		}
	}
	return false
}

func (v *ssoValidator) Validate(encoded, nonce, service string, allowedGroups []string) (*Ticket, error) {
	if service == "" {
		return nil, errors.New("empty service")
	}

	t, err := v.parse(encoded)
	if err != nil {
		return nil, err
	}

	if t.Domain != v.domain {
		return nil, ErrBadDomain
	}
	if t.Service != service {
		return nil, ErrBadService
	}
	if t.Expires.Before(time.Now()) {
		return nil, ErrExpired
	}
262
	if nonce != "" && t.Nonce != nonce {
ale's avatar
ale committed
263 264 265 266 267 268 269 270 271 272
		return nil, ErrBadNonce
	}

	// Only perform a group check if allowedGroups is not nil.
	if allowedGroups != nil && !anyGroupAllowed(allowedGroups, t.Groups) {
		return nil, ErrUnauthorized
	}

	return t, nil
}
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

// InspectTicket reads a ticket without validating it (beyond syntax),
// returning user and service. The results are untrusted.
func InspectTicket(encoded string) (string, string, error) {
	decoded, err := base64.RawURLEncoding.DecodeString(encoded)
	if err != nil {
		return "", "", err
	}
	if len(decoded) < signatureLen {
		return "", "", ErrMessageTooShort
	}
	serialized := decoded[signatureLen:]
	t, err := deserializeTicket(string(serialized))
	if err != nil {
		return "", "", err
	}
	return t.User, t.Service, nil
}