1// Package scram implements the SCRAM-SHA-* SASL authentication mechanism, RFC 7677 and RFC 5802.
3// SCRAM-SHA-256 and SCRAM-SHA-1 allow a client to authenticate to a server using a
4// password without handing plaintext password over to the server. The client also
5// verifies the server knows (a derivative of) the password. Both the client and
6// server side are implemented.
9// todo: test with messages that contains extensions
10// todo: some tests for the parser
11// todo: figure out how invalid parameters etc should be handled. just abort? perhaps mostly a problem for imap.
16 cryptorand "crypto/rand"
24 "golang.org/x/crypto/pbkdf2"
25 "golang.org/x/text/secure/precis"
26 "golang.org/x/text/unicode/norm"
29// Errors at scram protocol level. Can be exchanged between client and server.
31 ErrInvalidEncoding Error = "invalid-encoding"
32 ErrExtensionsNotSupported Error = "extensions-not-supported"
33 ErrInvalidProof Error = "invalid-proof"
34 ErrChannelBindingsDontMatch Error = "channel-bindings-dont-match"
35 ErrServerDoesSupportChannelBinding Error = "server-does-support-channel-binding"
36 ErrChannelBindingNotSupported Error = "channel-binding-not-supported"
37 ErrUnsupportedChannelBindingType Error = "unsupported-channel-binding-type"
38 ErrUnknownUser Error = "unknown-user"
39 ErrNoResources Error = "no-resources"
40 ErrOtherError Error = "other-error"
43var scramErrors = makeErrors()
45func makeErrors() map[string]Error {
48 ErrExtensionsNotSupported,
50 ErrChannelBindingsDontMatch,
51 ErrServerDoesSupportChannelBinding,
52 ErrChannelBindingNotSupported,
53 ErrUnsupportedChannelBindingType,
58 m := map[string]Error{}
66 ErrNorm = errors.New("parameter not unicode normalized") // E.g. if client sends non-normalized username or authzid.
67 ErrUnsafe = errors.New("unsafe parameter") // E.g. salt, nonce too short, or too few iterations.
68 ErrProtocol = errors.New("protocol error") // E.g. server responded with a nonce not prefixed by the client nonce.
73func (e Error) Error() string {
77// MakeRandom returns a cryptographically random buffer for use as salt or as
79func MakeRandom() []byte {
80 buf := make([]byte, 12)
81 _, err := cryptorand.Read(buf)
83 panic("generate random")
88// Cleanup password with precis, like remote should have done. If the password
89// appears invalid, we'll return the original, there is a chance the server also
91func precisPassword(password string) string {
92 pw, err := precis.OpaqueString.String(password)
99// SaltPassword returns a salted password.
100func SaltPassword(h func() hash.Hash, password string, salt []byte, iterations int) []byte {
101 password = precisPassword(password)
102 return pbkdf2.Key([]byte(password), salt, iterations, h().Size(), h)
105// hmac0 returns the hmac with key over msg.
106func hmac0(h func() hash.Hash, key []byte, msg string) []byte {
107 mac := hmac.New(h, key)
108 mac.Write([]byte(msg))
112func xor(a, b []byte) {
118func channelBindData(cs *tls.ConnectionState) ([]byte, error) {
119 if cs.Version <= tls.VersionTLS12 {
120 if cs.TLSUnique == nil {
121 return nil, fmt.Errorf("no channel binding data available")
123 return cs.TLSUnique, nil
129 return cs.ExportKeyingMaterial("EXPORTER-Channel-Binding", []byte{}, 32)
132// Server represents the server-side of a SCRAM-SHA-* authentication.
134 Authentication string // Username for authentication, "authc". Always set and non-empty.
135 Authorization string // If set, role of user to assume after authentication, "authz".
137 h func() hash.Hash // sha1.New or sha256.New
139 // Messages used in hash calculations.
140 clientFirstBare string
142 clientFinalWithoutProof string
145 clientNonce string // Client-part of the nonce.
146 serverNonceOverride string // If set, server does not generate random nonce, but uses this. For tests with the test vector.
147 nonce string // Full client + server nonce.
148 channelBinding []byte
151// NewServer returns a server given the first SCRAM message from a client.
153// If cs is set, the PLUS variant can be negotiated, binding the authentication
154// exchange to the TLS channel (preventing MitM attempts). If a client
155// indicates it supports the PLUS variant, but thinks the server does not, the
156// authentication attempt will fail.
158// If channelBindingRequired is set, the client has indicated it will do channel
159// binding and not doing so will cause the authentication to fail.
161// The sequence for data and calls on a server:
163// - Read initial data from client, call NewServer (this call), then ServerFirst and write to the client.
164// - Read response from client, call Finish or FinishFinal and write the resulting string.
165func NewServer(h func() hash.Hash, clientFirst []byte, cs *tls.ConnectionState, channelBindingRequired bool) (server *Server, rerr error) {
166 p := newParser(clientFirst)
167 defer p.recover(&rerr)
169 server = &Server{h: h}
172 gs2cbindFlag := p.xbyte()
173 switch gs2cbindFlag {
175 // Client does not support channel binding.
176 if channelBindingRequired {
177 p.xerrorf("channel binding is required when specifying scram plus: %w", ErrChannelBindingsDontMatch)
180 // Client supports channel binding but thinks we as server do not.
181 p.xerrorf("gs2 channel bind flag is y, client believes server does not support channel binding: %w", ErrServerDoesSupportChannelBinding)
183 // Use channel binding.
184 // It seems a cyrus-sasl client tells a server it is using the bare (non-PLUS)
185 // scram authentication mechanism, but then does use channel binding. It seems to
186 // use the server announcement of the plus variant only to learn the server
187 // supports channel binding.
189 cbname := p.xcbname()
190 // Assume the channel binding name is case-sensitive, and lower-case as used in
191 // examples. The ABNF rule accepts both lower and upper case. But the ABNF for
192 // attribute names also allows that, while the text claims they are case
197 p.xerrorf("no tls connection: %w", ErrChannelBindingsDontMatch)
198 } else if cs.Version >= tls.VersionTLS13 {
200 p.xerrorf("tls-unique not defined for tls 1.3 and later, use tls-exporter: %w", ErrChannelBindingsDontMatch)
201 } else if cs.TLSUnique == nil {
202 // As noted in the crypto/tls documentation.
203 p.xerrorf("no tls-unique channel binding value for this tls connection, possibly due to missing extended master key support and/or resumed connection: %w", ErrChannelBindingsDontMatch)
207 p.xerrorf("no tls connection: %w", ErrChannelBindingsDontMatch)
208 } else if cs.Version < tls.VersionTLS13 {
209 // Using tls-exporter with pre-1.3 TLS would require more precautions. Perhaps later.
211 p.xerrorf("tls-exporter with tls before 1.3 not implemented, use tls-unique: %w", ErrChannelBindingsDontMatch)
214 p.xerrorf("unknown parameter p %s: %w", cbname, ErrUnsupportedChannelBindingType)
216 cb, err := channelBindData(cs)
218 // We can pass back the error, it should never contain sensitive data, and only
219 // happen due to incorrect calling or a TLS config that is currently impossible
220 // (renegotiation enabled).
221 p.xerrorf("error fetching channel binding data: %v: %w", err, ErrOtherError)
223 server.channelBinding = cb
225 p.xerrorf("unrecognized gs2 channel bind flag")
229 server.Authorization = p.xauthzid()
230 if norm.NFC.String(server.Authorization) != server.Authorization {
231 return nil, fmt.Errorf("%w: authzid", ErrNorm)
235 server.gs2header = p.s[:p.o]
236 server.clientFirstBare = p.s[p.o:]
241 p.xerrorf("unexpected mandatory extension: %w", ErrExtensionsNotSupported) //
../rfc/5802:973
243 server.Authentication = p.xusername()
244 if norm.NFC.String(server.Authentication) != server.Authentication {
245 return nil, fmt.Errorf("%w: username", ErrNorm)
248 server.clientNonce = p.xnonce()
249 if len(server.clientNonce) < 8 {
250 return nil, fmt.Errorf("%w: client nonce too short", ErrUnsafe)
252 // Extensions, we don't recognize them.
260// ServerFirst returns the string to send back to the client. To be called after NewServer.
261func (s *Server) ServerFirst(iterations int, salt []byte) (string, error) {
263 serverNonce := s.serverNonceOverride
264 if serverNonce == "" {
265 serverNonce = base64.StdEncoding.EncodeToString(MakeRandom())
267 s.nonce = s.clientNonce + serverNonce
268 s.serverFirst = fmt.Sprintf("r=%s,s=%s,i=%d", s.nonce, base64.StdEncoding.EncodeToString(salt), iterations)
269 return s.serverFirst, nil
272// Finish takes the final client message, and the salted password (probably
273// from server storage), verifies the client, and returns a message to return
274// to the client. If err is nil, authentication was successful. If the
275// authorization requested is not acceptable, the server should call
276// FinishError instead.
277func (s *Server) Finish(clientFinal []byte, saltedPassword []byte) (serverFinal string, rerr error) {
278 p := newParser(clientFinal)
279 defer p.recover(&rerr)
281 // If there is any channel binding, and it doesn't match, this may be a
282 // MitM-attack. If the MitM would replace the channel binding, the signature
283 // calculated below would not match.
284 cbind := p.xchannelBinding()
285 cbindExp := append([]byte(s.gs2header), s.channelBinding...)
286 if !bytes.Equal(cbind, cbindExp) {
287 return "e=" + string(ErrChannelBindingsDontMatch), ErrChannelBindingsDontMatch
291 if nonce != s.nonce {
292 return "e=" + string(ErrInvalidProof), ErrInvalidProof
296 p.xattrval() // Ignored.
298 s.clientFinalWithoutProof = p.s[:p.o]
303 authMsg := s.clientFirstBare + "," + s.serverFirst + "," + s.clientFinalWithoutProof
305 clientKey := hmac0(s.h, saltedPassword, "Client Key")
308 storedKey := h.Sum(nil)
310 clientSig := hmac0(s.h, storedKey, authMsg)
311 xor(clientSig, clientKey) // Now clientProof.
312 if !bytes.Equal(clientSig, proof) {
313 return "e=" + string(ErrInvalidProof), ErrInvalidProof
316 serverKey := hmac0(s.h, saltedPassword, "Server Key")
317 serverSig := hmac0(s.h, serverKey, authMsg)
318 return fmt.Sprintf("v=%s", base64.StdEncoding.EncodeToString(serverSig)), nil
321// FinishError returns an error message to write to the client for the final
323func (s *Server) FinishError(err Error) string {
324 return "e=" + string(err)
327// Client represents the client-side of a SCRAM-SHA-* authentication.
332 h func() hash.Hash // sha1.New or sha256.New
333 noServerPlus bool // Server did not announce support for PLUS-variant.
334 cs *tls.ConnectionState // If set, use PLUS-variant.
336 // Messages used in hash calculations.
337 clientFirstBare string
339 clientFinalWithoutProof string
344 nonce string // Full client + server nonce.
345 saltedPassword []byte
346 channelBindData []byte // For PLUS-variant.
349// NewClient returns a client for authentication authc, optionally for
350// authorization with role authz, for the hash (sha1.New or sha256.New).
352// If noServerPlus is true, the client would like to have used the PLUS-variant,
353// that binds the authentication attempt to the TLS connection, but the client did
354// not see support for the PLUS variant announced by the server. Used during
355// negotiation to detect possible MitM attempt.
357// If cs is not nil, the SCRAM PLUS-variant is negotiated, with channel binding to
358// the unique TLS connection, either using "tls-exporter" for TLS 1.3 and later, or
359// "tls-unique" otherwise.
361// If cs is nil, no channel binding is done. If noServerPlus is also false, the
362// client is configured to not attempt/"support" the PLUS-variant, ensuring servers
363// that do support the PLUS-variant do not abort the connection.
365// The sequence for data and calls on a client:
367// - ClientFirst, write result to server.
368// - Read response from server, feed to ServerFirst, write response to server.
369// - Read response from server, feed to ServerFinal.
370func NewClient(h func() hash.Hash, authc, authz string, noServerPlus bool, cs *tls.ConnectionState) *Client {
371 authc = norm.NFC.String(authc)
372 authz = norm.NFC.String(authz)
373 return &Client{authc: authc, authz: authz, h: h, noServerPlus: noServerPlus, cs: cs}
376// ClientFirst returns the first client message to write to the server.
377// No channel binding is done/supported.
378// A random nonce is generated.
379func (c *Client) ClientFirst() (clientFirst string, rerr error) {
380 if c.noServerPlus && c.cs != nil {
381 return "", fmt.Errorf("cannot set both claim channel binding is not supported, and use channel binding")
383 // The first byte of the gs2header indicates if/how channel binding should be used.
386 if c.cs.Version >= tls.VersionTLS13 {
387 c.gs2header = "p=tls-exporter"
389 c.gs2header = "p=tls-unique"
391 cbdata, err := channelBindData(c.cs)
393 return "", fmt.Errorf("get channel binding data: %v", err)
395 c.channelBindData = cbdata
396 } else if c.noServerPlus {
397 // We support it, but we think server does not. If server does support it, we may
398 // have been downgraded, and the server will tell us.
401 // We don't want to do channel binding.
404 c.gs2header += fmt.Sprintf(",%s,", saslname(c.authz))
405 if c.clientNonce == "" {
406 c.clientNonce = base64.StdEncoding.EncodeToString(MakeRandom())
408 c.clientFirstBare = fmt.Sprintf("n=%s,r=%s", saslname(c.authc), c.clientNonce)
409 return c.gs2header + c.clientFirstBare, nil
412// ServerFirst processes the first response message from the server. The
413// provided nonce, salt and iterations are checked. If valid, a final client
414// message is calculated and returned. This message must be written to the
415// server. It includes proof that the client knows the password.
416func (c *Client) ServerFirst(serverFirst []byte, password string) (clientFinal string, rerr error) {
417 c.serverFirst = string(serverFirst)
418 p := newParser(serverFirst)
419 defer p.recover(&rerr)
424 p.xerrorf("unsupported mandatory extension: %w", ErrExtensionsNotSupported) //
../rfc/5802:973
431 iterations := p.xiterations()
432 // We ignore extensions that we don't know about.
438 if !strings.HasPrefix(c.nonce, c.clientNonce) {
439 return "", fmt.Errorf("%w: server dropped our nonce", ErrProtocol)
441 if len(c.nonce)-len(c.clientNonce) < 8 {
442 return "", fmt.Errorf("%w: server nonce too short", ErrUnsafe)
445 return "", fmt.Errorf("%w: salt too short", ErrUnsafe)
447 if iterations < 2048 {
448 return "", fmt.Errorf("%w: too few iterations", ErrUnsafe)
451 // We send our channel binding data if present. If the server has different values,
452 // we'll get an error. If any MitM would try to modify the channel binding data,
453 // the server cannot verify our signature and will fail the attempt.
455 cbindInput := append([]byte(c.gs2header), c.channelBindData...)
456 c.clientFinalWithoutProof = fmt.Sprintf("c=%s,r=%s", base64.StdEncoding.EncodeToString(cbindInput), c.nonce)
458 c.authMessage = c.clientFirstBare + "," + c.serverFirst + "," + c.clientFinalWithoutProof
460 c.saltedPassword = SaltPassword(c.h, password, salt, iterations)
461 clientKey := hmac0(c.h, c.saltedPassword, "Client Key")
464 storedKey := h.Sum(nil)
465 clientSig := hmac0(c.h, storedKey, c.authMessage)
466 xor(clientSig, clientKey) // Now clientProof.
467 clientProof := clientSig
469 r := c.clientFinalWithoutProof + ",p=" + base64.StdEncoding.EncodeToString(clientProof)
473// ServerFinal processes the final message from the server, verifying that the
474// server knows the password.
475func (c *Client) ServerFinal(serverFinal []byte) (rerr error) {
476 p := newParser(serverFinal)
477 defer p.recover(&rerr)
481 var err error = scramErrors[errstr]
482 if err == Error("") {
483 err = errors.New(errstr)
485 return fmt.Errorf("error from server: %w", err)
488 verifier := p.xbase64()
490 serverKey := hmac0(c.h, c.saltedPassword, "Server Key")
491 serverSig := hmac0(c.h, serverKey, c.authMessage)
492 if !bytes.Equal(verifier, serverSig) {
493 return fmt.Errorf("incorrect server signature")
498// Convert "," to =2C and "=" to =3D.
499func saslname(s string) string {
501 for _, c := range s {