// Package devices keeps the passwords a person makes for the apps and devices that connect to their server. // // A device password is a long random secret, shown once, that opens the music API for other apps (the OpenSubsonic // one) and nothing else: it cannot sign in to Sonda, change the account or make more passwords. A person can have one // for each phone or app and take it back at any time, so the account password never goes to an app. // // Subsonic's token login sends md5(secret + salt), so the server must know the secret itself, not a hash of it. The // secret is therefore kept sealed (AES-256-GCM, with a key derived from the server's jwt secret): a copy of the // database alone does not tell it. A hash of the secret is kept too, to find the device of an API key without trying // every one. package devices import ( "context" "crypto/aes" "crypto/cipher" "crypto/hkdf" "crypto/md5" //nolint:gosec // Subsonic's token login is md5(secret + salt): the protocol asks for it. "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/hex" "errors" "fmt" "sort" "strings" "time" "unicode/utf8" ) // Errors returned by the service. var ( ErrNotFound = errors.New("device not found") ErrInvalidName = errors.New("the name must have 1 to 60 characters") ErrTooMany = errors.New("there are too many devices: remove one first") // ErrBadCredentials is every way a login can fail: a wrong secret, a wrong person, none at all. ErrBadCredentials = errors.New("wrong user name or password") ) const ( // MaxDevices is how many a person can have: far more than anyone uses, and a bound on the work of a login. MaxDevices = 20 // MaxName is the longest name, in characters. MaxName = 60 secretSize = 24 // touchEvery is how often the use of a device is noted: a client asks all the time. touchEvery = 10 * time.Minute ) // Device is what a person sees of a device: never the secret. type Device struct { ID int64 Name string CreatedAt time.Time LastUsedAt *time.Time // nil until the device is used } // Row is a device as it is stored. type Row struct { ID int64 UserID int64 Name string KeyHash string // hex sha256 of the secret, to find it when only the secret is known Sealed []byte // the secret, sealed Email string // the address of the person: only when the row comes from a lookup by key or by address CreatedAt time.Time LastUsedAt *time.Time } // Store keeps the devices. type Store interface { // Create stores a device and returns it with its id. Create(ctx context.Context, r Row) (Row, error) // List returns the devices of a person. List(ctx context.Context, userID int64) ([]Row, error) // Delete removes a device of a person, with ErrNotFound when there is none. Delete(ctx context.Context, userID, id int64) error // ByKeyHash finds a device by the hash of its secret, with the address of its person, or ErrNotFound. ByKeyHash(ctx context.Context, hash string) (Row, error) // ByEmail returns the devices of the person with that address (lower case), with the address; none when // there is no such person. ByEmail(ctx context.Context, email string) ([]Row, error) // Touch notes when a device was last used. Touch(ctx context.Context, id int64, at time.Time) error } // Service makes and takes back device passwords. type Service struct { store Store aead cipher.AEAD now func() time.Time } // NewService builds a Service. secret is the server's jwt secret: the key that seals the passwords comes from it, so // a server that changes it makes the people make their device passwords again. func NewService(store Store, secret []byte) *Service { key, err := hkdf.Key(sha256.New, secret, nil, "sonda device passwords", 32) if err != nil { panic(fmt.Sprintf("devices: derive key: %v", err)) // only for a length that is out of range } block, err := aes.NewCipher(key) if err != nil { panic(fmt.Sprintf("devices: cipher: %v", err)) // a 32-byte key is always valid } aead, err := cipher.NewGCM(block) if err != nil { panic(fmt.Sprintf("devices: gcm: %v", err)) } return &Service{store: store, aead: aead, now: time.Now} } // Create makes a device for a person and returns it with its secret, which is never given again. func (s *Service) Create(ctx context.Context, userID int64, name string) (Device, string, error) { name = strings.TrimSpace(name) if n := utf8.RuneCountInString(name); n == 0 || n > MaxName { return Device{}, "", ErrInvalidName } rows, err := s.store.List(ctx, userID) if err != nil { return Device{}, "", fmt.Errorf("list devices: %w", err) } if len(rows) >= MaxDevices { return Device{}, "", ErrTooMany } raw := make([]byte, secretSize) if _, err := rand.Read(raw); err != nil { return Device{}, "", fmt.Errorf("generate secret: %w", err) } secret := hex.EncodeToString(raw) row, err := s.store.Create(ctx, Row{ UserID: userID, Name: name, KeyHash: KeyHash(secret), Sealed: s.seal(secret), CreatedAt: s.now(), }) if err != nil { return Device{}, "", fmt.Errorf("create device: %w", err) } return device(row), secret, nil } // List returns the devices of a person, the newest first. func (s *Service) List(ctx context.Context, userID int64) ([]Device, error) { rows, err := s.store.List(ctx, userID) if err != nil { return nil, fmt.Errorf("list devices: %w", err) } sort.Slice(rows, func(i, j int) bool { return rows[i].ID > rows[j].ID }) out := make([]Device, len(rows)) for i, r := range rows { out[i] = device(r) } return out, nil } // Revoke takes back the password of a device of a person: the app that had it can no longer connect. func (s *Service) Revoke(ctx context.Context, userID, id int64) error { return s.store.Delete(ctx, userID, id) } // Reveal opens a sealed secret. func (s *Service) Reveal(sealed []byte) (string, error) { n := s.aead.NonceSize() if len(sealed) < n+s.aead.Overhead() { return "", errors.New("devices: sealed secret is too short") } plain, err := s.aead.Open(nil, sealed[:n], sealed[n:], nil) if err != nil { return "", errors.New("devices: cannot open the sealed secret") } return string(plain), nil } func (s *Service) seal(secret string) []byte { nonce := make([]byte, s.aead.NonceSize()) if _, err := rand.Read(nonce); err != nil { panic(fmt.Sprintf("devices: nonce: %v", err)) // the system source of randomness failed: nothing is safe } return s.aead.Seal(nonce, nonce, []byte(secret), nil) } // KeyHash is what is kept to find a device by its secret. func KeyHash(secret string) string { sum := sha256.Sum256([]byte(secret)) return hex.EncodeToString(sum[:]) } func device(r Row) Device { return Device{ID: r.ID, Name: r.Name, CreatedAt: r.CreatedAt, LastUsedAt: r.LastUsedAt} } // Principal is who a login of a device is: the person, and which of their devices it was. type Principal struct { UserID int64 DeviceID int64 Email string } // ByKey logs in with an API key, which is the secret of a device. func (s *Service) ByKey(ctx context.Context, key string) (Principal, error) { if key == "" { return Principal{}, ErrBadCredentials } row, err := s.store.ByKeyHash(ctx, KeyHash(key)) if errors.Is(err, ErrNotFound) { return Principal{}, ErrBadCredentials } if err != nil { return Principal{}, fmt.Errorf("find device: %w", err) } return s.used(ctx, row), nil } // ByToken logs in the Subsonic way: the person's address and md5(secret + salt) of one of their devices. func (s *Service) ByToken(ctx context.Context, email, token, salt string) (Principal, error) { token = strings.ToLower(token) return s.match(ctx, email, func(secret string) bool { if token == "" || salt == "" { return false } sum := md5.Sum([]byte(secret + salt)) //nolint:gosec // see the import return same(hex.EncodeToString(sum[:]), token) }) } // ByPassword logs in with a person's address and the secret of one of their devices, written as it is or as // "enc:" and its bytes in hex. func (s *Service) ByPassword(ctx context.Context, email, password string) (Principal, error) { if rest, ok := strings.CutPrefix(password, "enc:"); ok { raw, err := hex.DecodeString(rest) if err != nil { return Principal{}, ErrBadCredentials } password = string(raw) } return s.match(ctx, email, func(secret string) bool { return password != "" && same(secret, password) }) } // match finds the device of the person whose secret the check accepts. It opens every device of the person, which is // at most MaxDevices. func (s *Service) match(ctx context.Context, email string, ok func(secret string) bool) (Principal, error) { rows, err := s.store.ByEmail(ctx, strings.ToLower(strings.TrimSpace(email))) if err != nil { return Principal{}, fmt.Errorf("find devices: %w", err) } found := -1 for i, r := range rows { secret, err := s.Reveal(r.Sealed) if err == nil && ok(secret) && found < 0 { found = i // keep going: the time must not tell which device it was } } if found < 0 { return Principal{}, ErrBadCredentials } return s.used(ctx, rows[found]), nil } func (s *Service) used(ctx context.Context, r Row) Principal { now := s.now() if r.LastUsedAt == nil || now.Sub(*r.LastUsedAt) >= touchEvery { _ = s.store.Touch(ctx, r.ID, now) // a failure to note the use does not stop the login } return Principal{UserID: r.UserID, DeviceID: r.ID, Email: r.Email} } func same(a, b string) bool { return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 }