1// Package scram implements the SCRAM-SHA-* SASL authentication mechanisms, including the PLUS variants, 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. The *-PLUS variants
6// bind the authentication exchange to the TLS session, preventing MitM attempts.
7// Both the client and server side are implemented.
10// todo: test with messages that contains extensions
11// todo: some tests for the parser
12// todo: figure out how invalid parameters etc should be handled. just abort? perhaps mostly a problem for imap.
18 cryptorand "crypto/rand"
26 "golang.org/x/text/secure/precis"
27 "golang.org/x/text/unicode/norm"
30// Errors at scram protocol level. Can be exchanged between client and server.
32 ErrInvalidEncoding Error = "invalid-encoding"
33 ErrExtensionsNotSupported Error = "extensions-not-supported"
34 ErrInvalidProof Error = "invalid-proof"
35 ErrChannelBindingsDontMatch Error = "channel-bindings-dont-match"
36 ErrServerDoesSupportChannelBinding Error = "server-does-support-channel-binding"
37 ErrChannelBindingNotSupported Error = "channel-binding-not-supported"
38 ErrUnsupportedChannelBindingType Error = "unsupported-channel-binding-type"
39 ErrUnknownUser Error = "unknown-user"
40 ErrNoResources Error = "no-resources"
41 ErrOtherError Error = "other-error"
44var scramErrors = makeErrors()
46func makeErrors() map[string]Error {
49 ErrExtensionsNotSupported,
51 ErrChannelBindingsDontMatch,
52 ErrServerDoesSupportChannelBinding,
53 ErrChannelBindingNotSupported,
54 ErrUnsupportedChannelBindingType,
59 m := map[string]Error{}
67 ErrNorm = errors.New("parameter not unicode normalized") // E.g. if client sends non-normalized username or authzid.
68 ErrUnsafe = errors.New("unsafe parameter") // E.g. salt, nonce too short, or too few iterations.
69 ErrProtocol = errors.New("protocol error") // E.g. server responded with a nonce not prefixed by the client nonce.
74func (e Error) Error() string {
78// MakeRandom returns a cryptographically random buffer for use as salt or as
80func MakeRandom() []byte {
81 buf := make([]byte, 12)
86// Cleanup password with precis, like remote should have done. If the password
87// appears invalid, we'll return the original, there is a chance the server also
89func precisPassword(password string) string {
90 pw, err := precis.OpaqueString.String(password)
97// SaltPassword returns a salted password.
98func SaltPassword(h func() hash.Hash, password string, salt []byte, iterations int) ([]byte, error) {
99 password = precisPassword(password)
100 return pbkdf2.Key(h, password, salt, iterations, h().Size())
103// hmac0 returns the hmac with key over msg.
104func hmac0(h func() hash.Hash, key []byte, msg string) []byte {
105 mac := hmac.New(h, key)
106 mac.Write([]byte(msg))
110func xor(a, b []byte) {
116func channelBindData(cs *tls.ConnectionState) ([]byte, error) {
117 if cs.Version <= tls.VersionTLS12 {
118 if cs.TLSUnique == nil {
119 return nil, fmt.Errorf("no channel binding data available")
121 return cs.TLSUnique, nil
127 return cs.ExportKeyingMaterial("EXPORTER-Channel-Binding", []byte{}, 32)
130// Server represents the server-side of a SCRAM-SHA-* authentication.
132 Authentication string // Username for authentication, "authc". Always set and non-empty.
133 Authorization string // If set, role of user to assume after authentication, "authz".
135 h func() hash.Hash // sha1.New or sha256.New
137 // Messages used in hash calculations.
138 clientFirstBare string
140 clientFinalWithoutProof string
143 clientNonce string // Client-part of the nonce.
144 serverNonceOverride string // If set, server does not generate random nonce, but uses this. For tests with the test vector.
145 nonce string // Full client + server nonce.
146 channelBinding []byte
149// NewServer returns a server given the first SCRAM message from a client.
151// If cs is set, the PLUS variant can be negotiated, binding the authentication
152// exchange to the TLS channel (preventing MitM attempts). If a client
153// indicates it supports the PLUS variant, but thinks the server does not, the
154// authentication attempt will fail.
156// If channelBindingRequired is set, the client has indicated it will do channel
157// binding and not doing so will cause the authentication to fail.
159// The sequence for data and calls on a server:
161// - Read initial data from client, call NewServer (this call), then ServerFirst and write to the client.
162// - Read response from client, call Finish or FinishFinal and write the resulting string.
163func NewServer(h func() hash.Hash, clientFirst []byte, cs *tls.ConnectionState, channelBindingRequired bool) (server *Server, rerr error) {
164 p := newParser(clientFirst)
165 defer p.recover(&rerr)
167 server = &Server{h: h}
170 gs2cbindFlag := p.xbyte()
171 switch gs2cbindFlag {
173 // Client does not support channel binding.
174 if channelBindingRequired {
175 p.xerrorf("channel binding is required when specifying scram plus: %w", ErrChannelBindingsDontMatch)
178 // Client supports channel binding but thinks we as server do not.
179 p.xerrorf("gs2 channel bind flag is y, client believes server does not support channel binding: %w", ErrServerDoesSupportChannelBinding)
181 // Use channel binding.
182 // It seems a cyrus-sasl client tells a server it is using the bare (non-PLUS)
183 // scram authentication mechanism, but then does use channel binding. It seems to
184 // use the server announcement of the plus variant only to learn the server
185 // supports channel binding.
187 cbname := p.xcbname()
188 // Assume the channel binding name is case-sensitive, and lower-case as used in
189 // examples. The ABNF rule accepts both lower and upper case. But the ABNF for
190 // attribute names also allows that, while the text claims they are case
195 p.xerrorf("no tls connection: %w", ErrChannelBindingsDontMatch)
196 } else if cs.Version >= tls.VersionTLS13 {
198 p.xerrorf("tls-unique not defined for tls 1.3 and later, use tls-exporter: %w", ErrChannelBindingsDontMatch)
199 } else if cs.TLSUnique == nil {
200 // As noted in the crypto/tls documentation.
201 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)
205 p.xerrorf("no tls connection: %w", ErrChannelBindingsDontMatch)
206 } else if cs.Version < tls.VersionTLS13 {
207 // Using tls-exporter with pre-1.3 TLS would require more precautions. Perhaps later.
209 p.xerrorf("tls-exporter with tls before 1.3 not implemented, use tls-unique: %w", ErrChannelBindingsDontMatch)
212 p.xerrorf("unknown parameter p %s: %w", cbname, ErrUnsupportedChannelBindingType)
214 cb, err := channelBindData(cs)
216 // We can pass back the error, it should never contain sensitive data, and only
217 // happen due to incorrect calling or a TLS config that is currently impossible
218 // (renegotiation enabled).
219 p.xerrorf("error fetching channel binding data: %v: %w", err, ErrOtherError)
221 server.channelBinding = cb
223 p.xerrorf("unrecognized gs2 channel bind flag")
227 server.Authorization = p.xauthzid()
228 if norm.NFC.String(server.Authorization) != server.Authorization {
229 return nil, fmt.Errorf("%w: authzid", ErrNorm)
233 server.gs2header = p.s[:p.o]
234 server.clientFirstBare = p.s[p.o:]
239 p.xerrorf("unexpected mandatory extension: %w", ErrExtensionsNotSupported) //
../rfc/5802:973
241 server.Authentication = p.xusername()
242 if norm.NFC.String(server.Authentication) != server.Authentication {
243 return nil, fmt.Errorf("%w: username", ErrNorm)
246 server.clientNonce = p.xnonce()
247 if len(server.clientNonce) < 8 {
248 return nil, fmt.Errorf("%w: client nonce too short", ErrUnsafe)
250 // Extensions, we don't recognize them.
258// ServerFirst returns the string to send back to the client. To be called after NewServer.
259func (s *Server) ServerFirst(iterations int, salt []byte) (string, error) {
261 serverNonce := s.serverNonceOverride
262 if serverNonce == "" {
263 serverNonce = base64.StdEncoding.EncodeToString(MakeRandom())
265 s.nonce = s.clientNonce + serverNonce
266 s.serverFirst = fmt.Sprintf("r=%s,s=%s,i=%d", s.nonce, base64.StdEncoding.EncodeToString(salt), iterations)
267 return s.serverFirst, nil
270// Finish takes the final client message, and the salted password (probably
271// from server storage), verifies the client, and returns a message to return
272// to the client. If err is nil, authentication was successful. If the
273// authorization requested is not acceptable, the server should call
274// FinishError instead.
275func (s *Server) Finish(clientFinal []byte, saltedPassword []byte) (serverFinal string, rerr error) {
276 p := newParser(clientFinal)
277 defer p.recover(&rerr)
279 // If there is any channel binding, and it doesn't match, this may be a
280 // MitM-attack. If the MitM would replace the channel binding, the signature
281 // calculated below would not match.
282 cbind := p.xchannelBinding()
283 cbindExp := append([]byte(s.gs2header), s.channelBinding...)
284 if !bytes.Equal(cbind, cbindExp) {
285 return "e=" + string(ErrChannelBindingsDontMatch), ErrChannelBindingsDontMatch
289 if nonce != s.nonce {
290 return "e=" + string(ErrInvalidProof), ErrInvalidProof
294 p.xattrval() // Ignored.
296 s.clientFinalWithoutProof = p.s[:p.o]
301 authMsg := s.clientFirstBare + "," + s.serverFirst + "," + s.clientFinalWithoutProof
303 clientKey := hmac0(s.h, saltedPassword, "Client Key")
306 storedKey := h.Sum(nil)
308 clientSig := hmac0(s.h, storedKey, authMsg)
309 xor(clientSig, clientKey) // Now clientProof.
310 if !bytes.Equal(clientSig, proof) {
311 return "e=" + string(ErrInvalidProof), ErrInvalidProof
314 serverKey := hmac0(s.h, saltedPassword, "Server Key")
315 serverSig := hmac0(s.h, serverKey, authMsg)
316 return fmt.Sprintf("v=%s", base64.StdEncoding.EncodeToString(serverSig)), nil
319// FinishError returns an error message to write to the client for the final
321func (s *Server) FinishError(err Error) string {
322 return "e=" + string(err)
325// Client represents the client-side of a SCRAM-SHA-* authentication.
330 h func() hash.Hash // sha1.New or sha256.New
331 noServerPlus bool // Server did not announce support for PLUS-variant.
332 cs *tls.ConnectionState // If set, use PLUS-variant.
334 // Messages used in hash calculations.
335 clientFirstBare string
337 clientFinalWithoutProof string
342 nonce string // Full client + server nonce.
343 saltedPassword []byte
344 channelBindData []byte // For PLUS-variant.
347// NewClient returns a client for authentication authc, optionally for
348// authorization with role authz, for the hash (sha1.New or sha256.New).
350// If noServerPlus is true, the client would like to have used the PLUS-variant,
351// that binds the authentication attempt to the TLS connection, but the client did
352// not see support for the PLUS variant announced by the server. Used during
353// negotiation to detect possible MitM attempt.
355// If cs is not nil, the SCRAM PLUS-variant is negotiated, with channel binding to
356// the unique TLS connection, either using "tls-exporter" for TLS 1.3 and later, or
357// "tls-unique" otherwise.
359// If cs is nil, no channel binding is done. If noServerPlus is also false, the
360// client is configured to not attempt/"support" the PLUS-variant, ensuring servers
361// that do support the PLUS-variant do not abort the connection.
363// The sequence for data and calls on a client:
365// - ClientFirst, write result to server.
366// - Read response from server, feed to ServerFirst, write response to server.
367// - Read response from server, feed to ServerFinal.
368func NewClient(h func() hash.Hash, authc, authz string, noServerPlus bool, cs *tls.ConnectionState) *Client {
369 authc = norm.NFC.String(authc)
370 authz = norm.NFC.String(authz)
371 return &Client{authc: authc, authz: authz, h: h, noServerPlus: noServerPlus, cs: cs}
374// ClientFirst returns the first client message to write to the server.
375// No channel binding is done/supported.
376// A random nonce is generated.
377func (c *Client) ClientFirst() (clientFirst string, rerr error) {
378 if c.noServerPlus && c.cs != nil {
379 return "", fmt.Errorf("cannot set both claim channel binding is not supported, and use channel binding")
381 // The first byte of the gs2header indicates if/how channel binding should be used.
384 if c.cs.Version >= tls.VersionTLS13 {
385 c.gs2header = "p=tls-exporter"
387 c.gs2header = "p=tls-unique"
389 cbdata, err := channelBindData(c.cs)
391 return "", fmt.Errorf("get channel binding data: %v", err)
393 c.channelBindData = cbdata
394 } else if c.noServerPlus {
395 // We support it, but we think server does not. If server does support it, we may
396 // have been downgraded, and the server will tell us.
399 // We don't want to do channel binding.
402 c.gs2header += fmt.Sprintf(",%s,", saslname(c.authz))
403 if c.clientNonce == "" {
404 c.clientNonce = base64.StdEncoding.EncodeToString(MakeRandom())
406 c.clientFirstBare = fmt.Sprintf("n=%s,r=%s", saslname(c.authc), c.clientNonce)
407 return c.gs2header + c.clientFirstBare, nil
410// ServerFirst processes the first response message from the server. The
411// provided nonce, salt and iterations are checked. If valid, a final client
412// message is calculated and returned. This message must be written to the
413// server. It includes proof that the client knows the password.
414func (c *Client) ServerFirst(serverFirst []byte, password string) (clientFinal string, rerr error) {
415 c.serverFirst = string(serverFirst)
416 p := newParser(serverFirst)
417 defer p.recover(&rerr)
422 p.xerrorf("unsupported mandatory extension: %w", ErrExtensionsNotSupported) //
../rfc/5802:973
429 iterations := p.xiterations()
430 // We ignore extensions that we don't know about.
436 if !strings.HasPrefix(c.nonce, c.clientNonce) {
437 return "", fmt.Errorf("%w: server dropped our nonce", ErrProtocol)
439 if len(c.nonce)-len(c.clientNonce) < 8 {
440 return "", fmt.Errorf("%w: server nonce too short", ErrUnsafe)
443 return "", fmt.Errorf("%w: salt too short", ErrUnsafe)
445 if iterations < 2048 {
446 return "", fmt.Errorf("%w: too few iterations", ErrUnsafe)
449 // We send our channel binding data if present. If the server has different values,
450 // we'll get an error. If any MitM would try to modify the channel binding data,
451 // the server cannot verify our signature and will fail the attempt.
453 cbindInput := append([]byte(c.gs2header), c.channelBindData...)
454 c.clientFinalWithoutProof = fmt.Sprintf("c=%s,r=%s", base64.StdEncoding.EncodeToString(cbindInput), c.nonce)
456 c.authMessage = c.clientFirstBare + "," + c.serverFirst + "," + c.clientFinalWithoutProof
458 c.saltedPassword, rerr = SaltPassword(c.h, password, salt, iterations)
460 return "", fmt.Errorf("%w: salt password: %v", ErrUnsafe, rerr)
462 clientKey := hmac0(c.h, c.saltedPassword, "Client Key")
465 storedKey := h.Sum(nil)
466 clientSig := hmac0(c.h, storedKey, c.authMessage)
467 xor(clientSig, clientKey) // Now clientProof.
468 clientProof := clientSig
470 r := c.clientFinalWithoutProof + ",p=" + base64.StdEncoding.EncodeToString(clientProof)
474// ServerFinal processes the final message from the server, verifying that the
475// server knows the password.
476func (c *Client) ServerFinal(serverFinal []byte) (rerr error) {
477 p := newParser(serverFinal)
478 defer p.recover(&rerr)
482 var err error = scramErrors[errstr]
483 if err == Error("") {
484 err = errors.New(errstr)
486 return fmt.Errorf("error from server: %w", err)
489 verifier := p.xbase64()
491 serverKey := hmac0(c.h, c.saltedPassword, "Server Key")
492 serverSig := hmac0(c.h, serverKey, c.authMessage)
493 if !bytes.Equal(verifier, serverSig) {
494 return fmt.Errorf("incorrect server signature")
499// Convert "," to =2C and "=" to =3D.
500func saslname(s string) string {
502 for _, c := range s {