Bump versions.
[gsasl.git] / doc / specification / rfc2831.txt
blobc1a54c494403169b0bf6538509347e35378d130f
7 Network Working Group                                           P. Leach
8 Request for Comments: 2831                                     Microsoft
9 Category: Standards Track                                      C. Newman
10                                                                 Innosoft
11                                                                 May 2000
14             Using Digest Authentication as a SASL Mechanism
16 Status of this Memo
18    This document specifies an Internet standards track protocol for the
19    Internet community, and requests discussion and suggestions for
20    improvements.  Please refer to the current edition of the "Internet
21    Official Protocol Standards" (STD 1) for the standardization state
22    and status of this protocol.  Distribution of this memo is unlimited.
24 Copyright Notice
26    Copyright (C) The Internet Society (2000).  All Rights Reserved.
28 Abstract
30    This specification defines how HTTP Digest Authentication [Digest]
31    can be used as a SASL [RFC 2222] mechanism for any protocol that has
32    a SASL profile. It is intended both as an improvement over CRAM-MD5
33    [RFC 2195] and as a convenient way to support a single authentication
34    mechanism for web, mail, LDAP, and other protocols.
36 Table of Contents
38    1 INTRODUCTION.....................................................2
39     1.1 CONVENTIONS AND NOTATION......................................2
40     1.2 REQUIREMENTS..................................................3
41    2 AUTHENTICATION...................................................3
42     2.1 INITIAL AUTHENTICATION........................................3
43      2.1.1 Step One...................................................3
44      2.1.2 Step Two...................................................6
45      2.1.3 Step Three................................................12
46     2.2 SUBSEQUENT AUTHENTICATION....................................12
47      2.2.1 Step one..................................................13
48      2.2.2 Step Two..................................................13
49     2.3 INTEGRITY PROTECTION.........................................13
50     2.4 CONFIDENTIALITY PROTECTION...................................14
51    3 SECURITY CONSIDERATIONS.........................................15
52     3.1 AUTHENTICATION OF CLIENTS USING DIGEST AUTHENTICATION........15
53     3.2 COMPARISON OF DIGEST WITH PLAINTEXT PASSWORDS................16
54     3.3 REPLAY ATTACKS...............................................16
58 Leach & Newman              Standards Track                     [Page 1]
60 RFC 2831                 Digest SASL Mechanism                  May 2000
63     3.4 ONLINE DICTIONARY ATTACKS....................................16
64     3.5 OFFLINE DICTIONARY ATTACKS...................................16
65     3.6 MAN IN THE MIDDLE............................................17
66     3.7 CHOSEN PLAINTEXT ATTACKS.....................................17
67     3.8 SPOOFING BY COUNTERFEIT SERVERS..............................17
68     3.9 STORING PASSWORDS............................................17
69     3.10 MULTIPLE REALMS.............................................18
70     3.11 SUMMARY.....................................................18
71    4 EXAMPLE.........................................................18
72    5 REFERENCES......................................................20
73    6 AUTHORS' ADDRESSES..............................................21
74    7 ABNF............................................................21
75     7.1 AUGMENTED BNF................................................21
76     7.2 BASIC RULES..................................................23
77    8 SAMPLE CODE.....................................................25
78    9 FULL COPYRIGHT STATEMENT........................................27
80 1  Introduction
82    This specification describes the use of HTTP Digest Access
83    Authentication as a SASL mechanism. The authentication type
84    associated with the Digest SASL mechanism is "DIGEST-MD5".
86    This specification is intended to be upward compatible with the
87    "md5-sess" algorithm of HTTP/1.1 Digest Access Authentication
88    specified in [Digest]. The only difference in the "md5-sess"
89    algorithm is that some directives not needed in a SASL mechanism have
90    had their values defaulted.
92    There is one new feature for use as a SASL mechanism: integrity
93    protection on application protocol messages after an authentication
94    exchange.
96    Also, compared to CRAM-MD5, DIGEST-MD5 prevents chosen plaintext
97    attacks, and permits the use of third party authentication servers,
98    mutual authentication, and optimized reauthentication if a client has
99    recently authenticated to a server.
101 1.1  Conventions and Notation
103    This specification uses the same ABNF notation and lexical
104    conventions as HTTP/1.1 specification; see appendix A.
106    Let { a, b, ... } be the concatenation of the octet strings a, b, ...
108    Let H(s) be the 16 octet MD5 hash [RFC 1321] of the octet string s.
114 Leach & Newman              Standards Track                     [Page 2]
116 RFC 2831                 Digest SASL Mechanism                  May 2000
119    Let KD(k, s) be H({k, ":", s}), i.e., the 16 octet hash of the string
120    k, a colon and the string s.
122    Let HEX(n) be the representation of the 16 octet MD5 hash n as a
123    string of 32 hex digits (with alphabetic characters always in lower
124    case, since MD5 is case sensitive).
126    Let HMAC(k, s) be the 16 octet HMAC-MD5 [RFC 2104] of the octet
127    string s using the octet string k as a key.
129    The value of a quoted string constant as an octet string does not
130    include any terminating null character.
132 1.2  Requirements
134    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
135    "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
136    document are to be interpreted as described in RFC 2119 [RFC 2119].
138    An implementation is not compliant if it fails to satisfy one or more
139    of the MUST level requirements for the protocols it implements. An
140    implementation that satisfies all the MUST level and all the SHOULD
141    level requirements for its protocols is said to be "unconditionally
142    compliant"; one that satisfies all the MUST level requirements but
143    not all the SHOULD level requirements for its protocols is said to be
144    "conditionally compliant."
146 2  Authentication
148    The following sections describe how to use Digest as a SASL
149    authentication mechanism.
151 2.1  Initial Authentication
153    If the client has not recently authenticated to the server, then it
154    must perform "initial authentication", as defined in this section. If
155    it has recently authenticated, then a more efficient form is
156    available, defined in the next section.
158 2.1.1  Step One
160    The server starts by sending a challenge. The data encoded in the
161    challenge contains a string formatted according to the rules for a
162    "digest-challenge" defined as follows:
170 Leach & Newman              Standards Track                     [Page 3]
172 RFC 2831                 Digest SASL Mechanism                  May 2000
175    digest-challenge  =
176          1#( realm | nonce | qop-options | stale | maxbuf | charset
177                algorithm | cipher-opts | auth-param )
179         realm             = "realm" "=" <"> realm-value <">
180         realm-value       = qdstr-val
181         nonce             = "nonce" "=" <"> nonce-value <">
182         nonce-value       = qdstr-val
183         qop-options       = "qop" "=" <"> qop-list <">
184         qop-list          = 1#qop-value
185         qop-value         = "auth" | "auth-int" | "auth-conf" |
186                              token
187         stale             = "stale" "=" "true"
188         maxbuf            = "maxbuf" "=" maxbuf-value
189         maxbuf-value      = 1*DIGIT
190         charset           = "charset" "=" "utf-8"
191         algorithm         = "algorithm" "=" "md5-sess"
192         cipher-opts       = "cipher" "=" <"> 1#cipher-value <">
193         cipher-value      = "3des" | "des" | "rc4-40" | "rc4" |
194                             "rc4-56" | token
195         auth-param        = token "=" ( token | quoted-string )
197    The meanings of the values of the directives used above are as
198    follows:
200    realm
201       Mechanistically, a string which can enable users to know which
202       username and password to use, in case they might have different
203       ones for different servers. Conceptually, it is the name of a
204       collection of accounts that might include the user's account. This
205       string should contain at least the name of the host performing the
206       authentication and might additionally indicate the collection of
207       users who might have access. An example might be
208       "registered_users@gotham.news.example.com".  This directive is
209       optional; if not present, the client SHOULD solicit it from the
210       user or be able to compute a default; a plausible default might be
211       the realm supplied by the user when they logged in to the client
212       system. Multiple realm directives are allowed, in which case the
213       user or client must choose one as the realm for which to supply to
214       username and password.
216    nonce
217       A server-specified data string which MUST be different each time a
218       digest-challenge is sent as part of initial authentication.  It is
219       recommended that this string be base64 or hexadecimal data. Note
220       that since the string is passed as a quoted string, the
221       double-quote character is not allowed unless escaped (see section
222       7.2). The contents of the nonce are implementation dependent. The
226 Leach & Newman              Standards Track                     [Page 4]
228 RFC 2831                 Digest SASL Mechanism                  May 2000
231       security of the implementation depends on a good choice. It is
232       RECOMMENDED that it contain at least 64 bits of entropy. The nonce
233       is opaque to the client. This directive is required and MUST
234       appear exactly once; if not present, or if multiple instances are
235       present, the client should abort the authentication exchange.
237    qop-options
238       A quoted string of one or more tokens indicating the "quality of
239       protection" values supported by the server.  The value "auth"
240       indicates authentication; the value "auth-int" indicates
241       authentication with integrity protection; the value "auth-conf"
242       indicates authentication with integrity protection and encryption.
243       This directive is optional; if not present it defaults to "auth".
244       The client MUST ignore unrecognized options; if the client
245       recognizes no option, it should abort the authentication exchange.
247    stale
248       The "stale" directive is not used in initial authentication. See
249       the next section for its use in subsequent authentications. This
250       directive may appear at most once; if multiple instances are
251       present, the client should abort the authentication exchange.
253    maxbuf
254       A number indicating the size of the largest buffer the server is
255       able to receive when using "auth-int" or "auth-conf". If this
256       directive is missing, the default value is 65536. This directive
257       may appear at most once; if multiple instances are present, the
258       client should abort the authentication exchange.
260    charset
261       This directive, if present, specifies that the server supports
262       UTF-8 encoding for the username and password. If not present, the
263       username and password must be encoded in ISO 8859-1 (of which
264       US-ASCII is a subset). The directive is needed for backwards
265       compatibility with HTTP Digest, which only supports ISO 8859-1.
266       This directive may appear at most once; if multiple instances are
267       present, the client should abort the authentication exchange.
269    algorithm
270       This directive is required for backwards compatibility with HTTP
271       Digest., which supports other algorithms. . This directive is
272       required and MUST appear exactly once; if not present, or if
273       multiple instances are present, the client should abort the
274       authentication exchange.
282 Leach & Newman              Standards Track                     [Page 5]
284 RFC 2831                 Digest SASL Mechanism                  May 2000
287    cipher-opts
288       A list of ciphers that the server supports. This directive must be
289       present exactly once if "auth-conf" is offered in the
290       "qop-options" directive, in which case the "3des" and "des" modes
291       are mandatory-to-implement. The client MUST ignore unrecognized
292       options; if the client recognizes no option, it should abort the
293       authentication exchange.
295       des
296          the Data Encryption Standard (DES) cipher [FIPS] in cipher
297          block chaining (CBC) mode with a 56 bit key.
299       3des
300          the "triple DES" cipher in CBC mode with EDE with the same key
301          for each E stage (aka "two keys mode") for a total key length
302          of 112 bits.
304       rc4, rc4-40, rc4-56
305          the RC4 cipher with a 128 bit, 40 bit, and 56 bit key,
306          respectively.
308    auth-param This construct allows for future extensions; it may appear
309       more than once. The client MUST ignore any unrecognized
310       directives.
312    For use as a SASL mechanism, note that the following changes are made
313    to "digest-challenge" from HTTP: the following Digest options (called
314    "directives" in HTTP terminology) are unused (i.e., MUST NOT be sent,
315    and MUST be ignored if received):
317     opaque
318     domain
320    The size of a digest-challenge MUST be less than 2048 bytes.
322 2.1.2  Step Two
324    The client makes note of the "digest-challenge" and then responds
325    with a string formatted and computed according to the rules for a
326    "digest-response" defined as follows:
338 Leach & Newman              Standards Track                     [Page 6]
340 RFC 2831                 Digest SASL Mechanism                  May 2000
343    digest-response  = 1#( username | realm | nonce | cnonce |
344                           nonce-count | qop | digest-uri | response |
345                           maxbuf | charset | cipher | authzid |
346                           auth-param )
348        username         = "username" "=" <"> username-value <">
349        username-value   = qdstr-val
350        cnonce           = "cnonce" "=" <"> cnonce-value <">
351        cnonce-value     = qdstr-val
352        nonce-count      = "nc" "=" nc-value
353        nc-value         = 8LHEX
354        qop              = "qop" "=" qop-value
355        digest-uri       = "digest-uri" "=" <"> digest-uri-value <">
356        digest-uri-value  = serv-type "/" host [ "/" serv-name ]
357        serv-type        = 1*ALPHA
358        host             = 1*( ALPHA | DIGIT | "-" | "." )
359        serv-name        = host
360        response         = "response" "=" response-value
361        response-value   = 32LHEX
362        LHEX             = "0" | "1" | "2" | "3" |
363                           "4" | "5" | "6" | "7" |
364                           "8" | "9" | "a" | "b" |
365                           "c" | "d" | "e" | "f"
366        cipher           = "cipher" "=" cipher-value
367        authzid          = "authzid" "=" <"> authzid-value <">
368        authzid-value    = qdstr-val
371    username
372       The user's name in the specified realm, encoded according to the
373       value of the "charset" directive. This directive is required and
374       MUST be present exactly once; otherwise, authentication fails.
376    realm
377       The realm containing the user's account. This directive is
378       required if the server provided any realms in the
379       "digest-challenge", in which case it may appear exactly once and
380       its value SHOULD be one of those realms. If the directive is
381       missing, "realm-value" will set to the empty string when computing
382       A1 (see below for details).
384    nonce
385       The server-specified data string received in the preceding
386       digest-challenge. This directive is required and MUST be present
387       exactly once; otherwise, authentication fails.
394 Leach & Newman              Standards Track                     [Page 7]
396 RFC 2831                 Digest SASL Mechanism                  May 2000
399    cnonce
400       A client-specified data string which MUST be different each time a
401       digest-response is sent as part of initial authentication. The
402       cnonce-value is an opaque quoted string value provided by the
403       client and used by both client and server to avoid chosen
404       plaintext attacks, and to provide mutual authentication. The
405       security of the implementation depends on a good choice. It is
406       RECOMMENDED that it contain at least 64 bits of entropy. This
407       directive is required and MUST be present exactly once; otherwise,
408       authentication fails.
410    nonce-count
411       The nc-value is the hexadecimal count of the number of requests
412       (including the current request) that the client has sent with the
413       nonce value in this request.  For example, in the first request
414       sent in response to a given nonce value, the client sends
415       "nc=00000001". The purpose of this directive is to allow the
416       server to detect request replays by maintaining its own copy of
417       this count - if the same nc-value is seen twice, then the request
418       is a replay.   See the description below of the construction of
419       the response value. This directive may appear at most once; if
420       multiple instances are present, the client should abort the
421       authentication exchange.
423    qop
424       Indicates what "quality of protection" the client accepted. If
425       present, it may appear exactly once and  its value MUST be one of
426       the alternatives in qop-options. If not present, it defaults to
427       "auth". These values affect the computation of the response. Note
428       that this is a single token, not a quoted list of alternatives.
430    serv-type
431       Indicates the type of service, such as "www" for web service,
432       "ftp" for FTP service, "smtp" for mail delivery service, etc. The
433       service name as defined in the SASL profile for the protocol see
434       section 4 of [RFC 2222], registered in the IANA registry of
435       "service" elements for the GSSAPI host-based service name form
436       [RFC 2078].
438    host
439       The DNS host name or IP address for the service requested.  The
440       DNS host name must be the fully-qualified canonical name of the
441       host. The DNS host name is the preferred form; see notes on server
442       processing of the digest-uri.
450 Leach & Newman              Standards Track                     [Page 8]
452 RFC 2831                 Digest SASL Mechanism                  May 2000
455    serv-name
456       Indicates the name of the service if it is replicated. The service
457       is considered to be replicated if the client's service-location
458       process involves resolution using standard DNS lookup operations,
459       and if these operations involve DNS records (such as SRV, or MX)
460       which resolve one DNS name into a set of other DNS names. In this
461       case, the initial name used by the client is the "serv-name", and
462       the final name is the "host" component. For example, the incoming
463       mail service for "example.com" may be replicated through the use
464       of MX records stored in the DNS, one of which points at an SMTP
465       server called "mail3.example.com"; it's "serv-name" would be
466       "example.com", it's "host" would be "mail3.example.com". If the
467       service is not replicated, or the serv-name is identical to the
468       host, then the serv-name component MUST be omitted.
470    digest-uri
471       Indicates the principal name of the service with which the client
472       wishes to connect, formed from the serv-type, host, and serv-name.
473       For example, the FTP service on "ftp.example.com" would have a
474       "digest-uri" value of "ftp/ftp.example.com"; the SMTP server from
475       the example above would have a "digest-uri" value of
476       "smtp/mail3.example.com/example.com".
478    Servers SHOULD check that the supplied value is correct. This will
479    detect accidental connection to the incorrect server. It is also so
480    that clients will be trained to provide values that will work with
481    implementations that use a shared back-end authentication service
482    that can provide server authentication.
484    The serv-type component should match the service being offered. The
485    host component should match one of the host names of the host on
486    which the service is running, or it's IP address. Servers SHOULD NOT
487    normally support the IP address form, because server authentication
488    by IP address is not very useful; they should only do so if the DNS
489    is unavailable or unreliable. The serv-name component should match
490    one of the service's configured service names.
492    This directive may appear at most once; if multiple instances are
493    present, the client should abort the authentication exchange.
495    Note: In the HTTP use of Digest authentication, the digest-uri is the
496    URI (usually a URL) of the resource requested -- hence the name of
497    the directive.
499    response
500       A string of 32 hex digits computed as defined below, which proves
501       that the user knows a password. This directive is required and
502       MUST be present exactly once; otherwise, authentication fails.
506 Leach & Newman              Standards Track                     [Page 9]
508 RFC 2831                 Digest SASL Mechanism                  May 2000
511    maxbuf
512       A number indicating the size of the largest buffer the client is
513       able to receive. If this directive is missing, the default value
514       is 65536. This directive may appear at most once; if multiple
515       instances are present, the server should abort the authentication
516       exchange.
518    charset
519       This directive, if present, specifies that the client has used
520       UTF-8 encoding for the username and password. If not present, the
521       username and password must be encoded in ISO 8859-1 (of which
522       US-ASCII is a subset). The client should send this directive only
523       if the server has indicated it supports UTF-8. The directive is
524       needed for backwards compatibility with HTTP Digest, which only
525       supports ISO 8859-1.
527    LHEX
528       32 hex digits, where the alphabetic characters MUST be lower case,
529       because MD5 is not case insensitive.
531    cipher
532       The cipher chosen by the client. This directive MUST appear
533       exactly once if "auth-conf" is negotiated; if required and not
534       present, authentication fails.
536    authzid
537       The "authorization ID" as per RFC 2222, encoded in UTF-8. This
538       directive is optional. If present, and the authenticating user has
539       sufficient privilege, and the server supports it, then after
540       authentication the server will use this identity for making all
541       accesses and access checks. If the client specifies it, and the
542       server does not support it, then the response-value will be
543       incorrect, and authentication will fail.
545    The size of a digest-response MUST be less than 4096 bytes.
547 2.1.2.1   Response-value
549    The definition of "response-value" above indicates the encoding for
550    its value -- 32 lower case hex characters. The following definitions
551    show how the value is computed.
553    Although qop-value and components of digest-uri-value may be
554    case-insensitive, the case which the client supplies in step two is
555    preserved for the purpose of computing and verifying the
556    response-value.
558       response-value  =
562 Leach & Newman              Standards Track                    [Page 10]
564 RFC 2831                 Digest SASL Mechanism                  May 2000
567          HEX( KD ( HEX(H(A1)),
568                  { nonce-value, ":" nc-value, ":",
569                    cnonce-value, ":", qop-value, ":", HEX(H(A2)) }))
571    If authzid is specified, then A1 is
574       A1 = { H( { username-value, ":", realm-value, ":", passwd } ),
575            ":", nonce-value, ":", cnonce-value, ":", authzid-value }
577    If authzid is not specified, then A1 is
580       A1 = { H( { username-value, ":", realm-value, ":", passwd } ),
581            ":", nonce-value, ":", cnonce-value }
583    where
585          passwd   = *OCTET
587    The "username-value", "realm-value" and "passwd" are encoded
588    according to the value of the "charset" directive. If "charset=UTF-8"
589    is present, and all the characters of either "username-value" or
590    "passwd" are in the ISO 8859-1 character set, then it must be
591    converted to ISO 8859-1 before being hashed. This is so that
592    authentication databases that store the hashed username, realm and
593    password (which is common) can be shared compatibly with HTTP, which
594    specifies ISO 8859-1. A sample implementation of this conversion is
595    in section 8.
597    If the "qop" directive's value is "auth", then A2 is:
599       A2       = { "AUTHENTICATE:", digest-uri-value }
601    If the "qop" value is "auth-int" or "auth-conf" then A2 is:
603       A2       = { "AUTHENTICATE:", digest-uri-value,
604                ":00000000000000000000000000000000" }
606    Note that "AUTHENTICATE:" must be in upper case, and the second
607    string constant is a string with a colon followed by 32 zeros.
609    These apparently strange values of A2 are for compatibility with
610    HTTP; they were arrived at by setting "Method" to "AUTHENTICATE" and
611    the hash of the entity body to zero in the HTTP digest calculation of
612    A2.
614    Also, in the HTTP usage of Digest, several directives in the
618 Leach & Newman              Standards Track                    [Page 11]
620 RFC 2831                 Digest SASL Mechanism                  May 2000
623    "digest-challenge" sent by the server have to be returned by the
624    client in the "digest-response". These are:
626     opaque
627     algorithm
629    These directives are not needed when Digest is used as a SASL
630    mechanism (i.e., MUST NOT be sent, and MUST be ignored if received).
632 2.1.3  Step Three
634    The server receives and validates the "digest-response". The server
635    checks that the nonce-count is "00000001". If it supports subsequent
636    authentication (see section 2.2), it saves the value of the nonce and
637    the nonce-count. It sends a message formatted as follows:
639     response-auth = "rspauth" "=" response-value
641    where response-value is calculated as above, using the values sent in
642    step two, except that if qop is "auth", then A2 is
644        A2 = { ":", digest-uri-value }
646    And if qop is "auth-int" or "auth-conf" then A2 is
648        A2 = { ":", digest-uri-value, ":00000000000000000000000000000000" }
650    Compared to its use in HTTP, the following Digest directives in the
651    "digest-response" are unused:
653        nextnonce
654        qop
655        cnonce
656        nonce-count
658 2.2  Subsequent Authentication
660    If the client has previously authenticated to the server, and
661    remembers the values of username, realm, nonce, nonce-count, cnonce,
662    and qop that it used in that authentication, and the SASL profile for
663    a protocol permits an initial client response, then it MAY perform
664    "subsequent authentication", as defined in this section.
674 Leach & Newman              Standards Track                    [Page 12]
676 RFC 2831                 Digest SASL Mechanism                  May 2000
679 2.2.1  Step one
681    The client uses the values from the previous authentication and sends
682    an initial response with a string formatted and computed according to
683    the rules for a "digest-response", as defined above, but with a
684    nonce-count one greater than used in the last "digest-response".
686 2.2.2  Step Two
688    The server receives the "digest-response". If the server does not
689    support subsequent authentication, then it sends a
690    "digest-challenge", and authentication proceeds as in initial
691    authentication. If the server has no saved nonce and nonce-count from
692    a previous authentication, then it sends a "digest-challenge", and
693    authentication proceeds as in initial authentication. Otherwise, the
694    server validates the "digest-response", checks that the nonce-count
695    is one greater than that used in the previous authentication using
696    that nonce, and saves the new value of nonce-count.
698    If the response is invalid, then the server sends a
699    "digest-challenge", and authentication proceeds as in initial
700    authentication (and should be configurable to log an authentication
701    failure in some sort of security audit log, since the failure may be
702    a symptom of an attack). The nonce-count MUST NOT be incremented in
703    this case: to do so would allow a denial of service attack by sending
704    an out-of-order nonce-count.
706    If the response is valid, the server MAY choose to deem that
707    authentication has succeeded. However, if it has been too long since
708    the previous authentication, or for any other reason, the server MAY
709    send a new "digest-challenge" with a new value for nonce. The
710    challenge MAY contain a "stale" directive with value "true", which
711    says that the client may respond to the challenge using the password
712    it used in the previous response; otherwise, the client must solicit
713    the password anew from the user. This permits the server to make sure
714    that the user has presented their password recently. (The directive
715    name refers to the previous nonce being stale, not to the last use of
716    the password.) Except for the handling of "stale", after sending the
717    "digest-challenge" authentication proceeds as in the case of initial
718    authentication.
720 2.3   Integrity Protection
722    If the server offered "qop=auth-int" and the client responded
723    "qop=auth-int", then subsequent messages, up to but not including the
724    next subsequent authentication, between the client and the server
730 Leach & Newman              Standards Track                    [Page 13]
732 RFC 2831                 Digest SASL Mechanism                  May 2000
735    MUST be integrity protected. Using as a base session key the value of
736    H(A1) as defined above the client and server calculate a pair of
737    message integrity keys as follows.
739    The key for integrity protecting messages from client to server is:
741    Kic = MD5({H(A1),
742    "Digest session key to client-to-server signing key magic constant"})
744    The key for integrity protecting messages from server to client is:
746    Kis = MD5({H(A1),
747    "Digest session key to server-to-client signing key magic constant"})
749    where MD5 is as specified in [RFC 1321]. If message integrity is
750    negotiated, a MAC block for each message is appended to the message.
751    The MAC block is 16 bytes: the first 10 bytes of the HMAC-MD5 [RFC
752    2104] of the message, a 2-byte message type number in network byte
753    order with value 1, and the 4-byte sequence number in network byte
754    order. The message type is to allow for future extensions such as
755    rekeying.
757    MAC(Ki, SeqNum, msg) = (HMAC(Ki, {SeqNum, msg})[0..9], 0x0001,
758    SeqNum)
760    where Ki is Kic for messages sent by the client and Kis for those
761    sent by the server. The sequence number is initialized to zero, and
762    incremented by one for each message sent.
764    Upon receipt, MAC(Ki, SeqNum, msg) is computed and compared with the
765    received value; the message is discarded if they differ.
767 2.4   Confidentiality Protection
769    If the server sent a "cipher-opts" directive and the client responded
770    with a "cipher" directive, then subsequent messages between the
771    client and the server MUST be confidentiality protected. Using as a
772    base session key the value of H(A1) as defined above the client and
773    server calculate a pair of message integrity keys as follows.
775    The key for confidentiality protecting messages from client to server
776    is:
778    Kcc = MD5({H(A1)[0..n],
779    "Digest H(A1) to client-to-server sealing key magic constant"})
781    The key for confidentiality protecting messages from server to client
782    is:
786 Leach & Newman              Standards Track                    [Page 14]
788 RFC 2831                 Digest SASL Mechanism                  May 2000
791    Kcs = MD5({H(A1)[0..n],
792    "Digest H(A1) to server-to-client sealing key magic constant"})
794    where MD5 is as specified in [RFC 1321]. For cipher "rc4-40" n is 5;
795    for "rc4-56" n is 7; for the rest n is 16. The key for the "rc-*"
796    ciphers is all 16 bytes of Kcc or Kcs; the key for "des" is the first
797    7 bytes; the key for "3des" is the first 14 bytes. The IV for "des"
798    and "3des" is the last 8 bytes of Kcc or Kcs.
800    If message confidentiality is negotiated, each message is encrypted
801    with the chosen cipher and a MAC block is appended to the message.
803    The MAC block is a variable length padding prefix followed by 16
804    bytes formatted as follows: the first 10 bytes of the HMAC-MD5 [RFC
805    2104] of the message, a 2-byte message type number in network byte
806    order with value 1, and the 4-byte sequence number in network byte
807    order. If the blocksize of the chosen cipher is not 1 byte, the
808    padding prefix is one or more octets each containing the number of
809    padding bytes, such that total length of the encrypted part of the
810    message is a multiple of the blocksize. The padding and first 10
811    bytes of the MAC block are encrypted along with the message.
813    SEAL(Ki, Kc, SeqNum, msg) =
814          {CIPHER(Kc, {msg, pad, HMAC(Ki, {SeqNum, msg})[0..9])}), 0x0001,
815           SeqNum}
817    where CIPHER is the chosen cipher, Ki and Kc are Kic and Kcc for
818    messages sent by the client and Kis and Kcs for those sent by the
819    server. The sequence number is initialized to zero, and incremented
820    by one for each message sent.
822    Upon receipt, the message is decrypted, HMAC(Ki, {SeqNum, msg}) is
823    computed and compared with the received value; the message is
824    discarded if they differ.
826 3  Security Considerations
828 3.1   Authentication of Clients using Digest Authentication
830    Digest Authentication does not provide a strong authentication
831    mechanism, when compared to public key based mechanisms, for example.
832    However, since it prevents chosen plaintext attacks, it is stronger
833    than (e.g.) CRAM-MD5, which has been proposed for use with LDAP [10],
834    POP and IMAP (see RFC 2195 [9]).   It is intended to replace the much
835    weaker and even more dangerous use of plaintext passwords; however,
836    since it is still a password based mechanism it avoids some of the
837    potential deployabilty issues with public-key, OTP or similar
838    mechanisms.
842 Leach & Newman              Standards Track                    [Page 15]
844 RFC 2831                 Digest SASL Mechanism                  May 2000
847    Digest Authentication offers no confidentiality protection beyond
848    protecting the actual password. All of the rest of the challenge and
849    response are available to an eavesdropper, including the user's name
850    and authentication realm.
852 3.2   Comparison of Digest with Plaintext Passwords
854    The greatest threat to the type of transactions for which these
855    protocols are used is network snooping. This kind of transaction
856    might involve, for example, online access to a mail service whose use
857    is restricted to paying subscribers. With plaintext password
858    authentication an eavesdropper can obtain the password of the user.
859    This not only permits him to access anything in the database, but,
860    often worse, will permit access to anything else the user protects
861    with the same password.
863 3.3   Replay Attacks
865    Replay attacks are defeated if the client or the server chooses a
866    fresh nonce for each authentication, as this specification requires.
868 3.4  Online dictionary attacks
870    If the attacker can eavesdrop, then it can test any overheard
871    nonce/response pairs against a (potentially very large) list of
872    common words. Such a list is usually much smaller than the total
873    number of possible passwords. The cost of computing the response for
874    each password on the list is paid once for each challenge.
876    The server can mitigate this attack by not allowing users to select
877    passwords that are in a dictionary.
879 3.5  Offline dictionary attacks
881    If the attacker can choose the challenge, then it can precompute the
882    possible responses to that challenge for a list of common words. Such
883    a list is usually much smaller than the total number of possible
884    passwords. The cost of computing the response for each password on
885    the list is paid just once.
887    Offline dictionary attacks are defeated if the client chooses a fresh
888    nonce for each authentication, as this specification requires.
898 Leach & Newman              Standards Track                    [Page 16]
900 RFC 2831                 Digest SASL Mechanism                  May 2000
903 3.6  Man in the Middle
905    Digest authentication is vulnerable to "man in the middle" (MITM)
906    attacks. Clearly, a MITM would present all the problems of
907    eavesdropping. But it also offers some additional opportunities to
908    the attacker.
910    A possible man-in-the-middle attack would be to substitute a weaker
911    qop scheme for the one(s) sent by the server; the server will not be
912    able to detect this attack. For this reason, the client should always
913    use the strongest scheme that it understands from the choices
914    offered, and should never choose a scheme that does not meet its
915    minimum requirements.
917 3.7  Chosen plaintext attacks
919    A chosen plaintext attack is where a MITM or a malicious server can
920    arbitrarily choose the challenge that the client will use to compute
921    the response. The ability to choose the challenge is known to make
922    cryptanalysis much easier [8].
924    However, Digest does not permit the attack to choose the challenge as
925    long as the client chooses a fresh nonce for each authentication, as
926    this specification requires.
928 3.8  Spoofing by Counterfeit Servers
930    If a user can be led to believe that she is connecting to a host
931    containing information protected by a password she knows, when in
932    fact she is connecting to a hostile server, then the hostile server
933    can obtain challenge/response pairs where it was able to partly
934    choose the challenge. There is no known way that this can be
935    exploited.
937 3.9  Storing passwords
939    Digest authentication requires that the authenticating agent (usually
940    the server) store some data derived from the user's name and password
941    in a "password file" associated with a given realm. Normally this
942    might contain pairs consisting of username and H({ username-value,
943    ":", realm-value, ":", passwd }), which is adequate to compute H(A1)
944    as described above without directly exposing the user's password.
946    The security implications of this are that if this password file is
947    compromised, then an attacker gains immediate access to documents on
948    the server using this realm. Unlike, say a standard UNIX password
949    file, this information need not be decrypted in order to access
950    documents in the server realm associated with this file. On the other
954 Leach & Newman              Standards Track                    [Page 17]
956 RFC 2831                 Digest SASL Mechanism                  May 2000
959    hand, decryption, or more likely a brute force attack, would be
960    necessary to obtain the user's password. This is the reason that the
961    realm is part of the digested data stored in the password file. It
962    means that if one Digest authentication password file is compromised,
963    it does not automatically compromise others with the same username
964    and password (though it does expose them to brute force attack).
966    There are two important security consequences of this. First the
967    password file must be protected as if it contained plaintext
968    passwords, because for the purpose of accessing documents in its
969    realm, it effectively does.
971    A second consequence of this is that the realm string should be
972    unique among all realms that any single user is likely to use. In
973    particular a realm string should include the name of the host doing
974    the authentication.
976 3.10  Multiple realms
978    Use of multiple realms may mean both that compromise of a the
979    security database for a single realm does not compromise all
980    security, and that there are more things to protect in order to keep
981    the whole system secure.
983 3.11  Summary
985    By modern cryptographic standards Digest Authentication is weak,
986    compared to (say) public key based mechanisms. But for a large range
987    of purposes it is valuable as a replacement for plaintext passwords.
988    Its strength may vary depending on the implementation.
990 4  Example
992    This example shows the use of the Digest SASL mechanism with the
993    IMAP4 AUTHENTICATE command [RFC 2060].
995    In this example, "C:" and "S:" represent a line sent by the client or
996    server respectively including a CRLF at the end.  Linebreaks and
997    indentation within a "C:" or "S:" are editorial and not part of the
998    protocol. The password in this example was "secret".  Note that the
999    base64 encoding of the challenges and responses is part of the IMAP4
1000    AUTHENTICATE command, not part of the Digest specification itself.
1002     S: * OK elwood.innosoft.com PMDF IMAP4rev1 V6.0-9
1003     C: c CAPABILITY
1004     S: * CAPABILITY IMAP4 IMAP4rev1 ACL LITERAL+ NAMESPACE QUOTA
1005                 UIDPLUS AUTH=CRAM-MD5 AUTH=DIGEST-MD5 AUTH=PLAIN
1006     S: c OK Completed
1010 Leach & Newman              Standards Track                    [Page 18]
1012 RFC 2831                 Digest SASL Mechanism                  May 2000
1015     C: a AUTHENTICATE DIGEST-MD5
1016     S: + cmVhbG09ImVsd29vZC5pbm5vc29mdC5jb20iLG5vbmNlPSJPQTZNRzl0
1017          RVFHbTJoaCIscW9wPSJhdXRoIixhbGdvcml0aG09bWQ1LXNlc3MsY2hh
1018          cnNldD11dGYtOA==
1019     C: Y2hhcnNldD11dGYtOCx1c2VybmFtZT0iY2hyaXMiLHJlYWxtPSJlbHdvb2
1020        QuaW5ub3NvZnQuY29tIixub25jZT0iT0E2TUc5dEVRR20yaGgiLG5jPTAw
1021        MDAwMDAxLGNub25jZT0iT0E2TUhYaDZWcVRyUmsiLGRpZ2VzdC11cmk9Im
1022        ltYXAvZWx3b29kLmlubm9zb2Z0LmNvbSIscmVzcG9uc2U9ZDM4OGRhZDkw
1023        ZDRiYmQ3NjBhMTUyMzIxZjIxNDNhZjcscW9wPWF1dGg=
1024     S: + cnNwYXV0aD1lYTQwZjYwMzM1YzQyN2I1NTI3Yjg0ZGJhYmNkZmZmZA==
1025     C:
1026     S: a OK User logged in
1027     ---
1029     The base64-decoded version of the SASL exchange is:
1031     S: realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",qop="auth",
1032        algorithm=md5-sess,charset=utf-8
1033     C: charset=utf-8,username="chris",realm="elwood.innosoft.com",
1034        nonce="OA6MG9tEQGm2hh",nc=00000001,cnonce="OA6MHXh6VqTrRk",
1035        digest-uri="imap/elwood.innosoft.com",
1036        response=d388dad90d4bbd760a152321f2143af7,qop=auth
1037     S: rspauth=ea40f60335c427b5527b84dbabcdfffd
1039     The password in this example was "secret".
1041    This example shows the use of the Digest SASL mechanism with the
1042    ACAP, using the same notational conventions and password as in the
1043    previous example. Note that ACAP does not base64 encode and uses
1044    fewer round trips that IMAP4.
1046     S: * ACAP (IMPLEMENTATION "Test ACAP server") (SASL "CRAM-MD5"
1047                "DIGEST-MD5" "PLAIN")
1048     C: a AUTHENTICATE "DIGEST-MD5"
1049     S: + {94}
1050     S: realm="elwood.innosoft.com",nonce="OA9BSXrbuRhWay",qop="auth",
1051        algorithm=md5-sess,charset=utf-8
1052     C: {206}
1053     C: charset=utf-8,username="chris",realm="elwood.innosoft.com",
1054        nonce="OA9BSXrbuRhWay",nc=00000001,cnonce="OA9BSuZWMSpW8m",
1055        digest-uri="acap/elwood.innosoft.com",
1056        response=6084c6db3fede7352c551284490fd0fc,qop=auth
1057     S: a OK (SASL {40}
1058     S: rspauth=2f0b3d7c3c2e486600ef710726aa2eae) "AUTHENTICATE
1059     Completed"
1060     ---
1066 Leach & Newman              Standards Track                    [Page 19]
1068 RFC 2831                 Digest SASL Mechanism                  May 2000
1071    The server uses the values of all the directives, plus knowledge of
1072    the users password (or the hash of the user's name, server's realm
1073    and the user's password) to verify the computations above. If they
1074    check, then the user has authenticated.
1076 5   References
1078    [Digest]   Franks, J., et al., "HTTP Authentication: Basic and Digest
1079               Access Authentication", RFC 2617, June 1999.
1081    [ISO-8859] ISO-8859. International Standard--Information Processing--
1082               8-bit Single-Byte Coded Graphic Character Sets --
1083               Part 1: Latin alphabet No. 1, ISO-8859-1:1987.
1084               Part 2: Latin alphabet No. 2, ISO-8859-2, 1987.
1085               Part 3: Latin alphabet No. 3, ISO-8859-3, 1988.
1086               Part 4: Latin alphabet No. 4, ISO-8859-4, 1988.
1087               Part 5: Latin/Cyrillic alphabet, ISO-8859-5, 1988.
1088               Part 6: Latin/Arabic alphabet, ISO-8859-6, 1987.
1089               Part 7: Latin/Greek alphabet, ISO-8859-7, 1987.
1090               Part 8: Latin/Hebrew alphabet, ISO-8859-8, 1988.
1091               Part 9: Latin alphabet No. 5, ISO-8859-9, 1990.
1093    [RFC 822]  Crocker, D., "Standard for The Format of ARPA Internet
1094               Text Messages," STD 11, RFC 822, August 1982.
1096    [RFC 1321] Rivest, R., "The MD5 Message-Digest Algorithm", RFC 1321,
1097               April 1992.
1099    [RFC 2047] Moore, K., "MIME (Multipurpose Internet Mail Extensions)
1100               Part Three: Message Header Extensions for Non-ASCII Text",
1101               RFC 2047, November 1996.
1103    [RFC 2052] Gulbrandsen, A. and P. Vixie, "A DNS RR for specifying the
1104               location of services (DNS SRV)", RFC 2052, October 1996.
1106    [RFC 2060] Crispin, M., "Internet Message Access Protocol - Version
1107               4rev1", RFC 2060, December 1996.
1109    [RFC 2104] Krawczyk, H., Bellare, M. and R. Canetti, "HMAC:  Keyed-
1110               Hashing for  Message Authentication", RFC 2104, February
1111               1997.
1113    [RFC 2195] Klensin, J., Catoe, R. and P. Krumviede, "IMAP/POP
1114               AUTHorize Extension for Simple Challenge/Response", RFC
1115               2195, September 1997.
1122 Leach & Newman              Standards Track                    [Page 20]
1124 RFC 2831                 Digest SASL Mechanism                  May 2000
1127    [RFC 2119] Bradner, S., "Key words for use in RFCs to Indicate
1128               Requirement Levels", BCP 14, RFC 2119, March 1997.
1130    [RFC 2222] Myers, J., "Simple Authentication and Security Layer
1131               (SASL)", RFC 2222, October 1997.
1133    [USASCII]  US-ASCII. Coded Character Set - 7-Bit American Standard
1134               Code for Information Interchange. Standard ANSI X3.4-1986,
1135               ANSI, 1986.
1137 6  Authors' Addresses
1139    Paul Leach
1140    Microsoft
1141    1 Microsoft Way
1142    Redmond, WA  98052
1144    EMail: paulle@microsoft.com
1147    Chris Newman
1148    Innosoft International, Inc.
1149    1050 Lakes Drive
1150    West Covina, CA 91790 USA
1152    EMail: chris.newman@innosoft.com
1154 7  ABNF
1156    What follows is the definition of the notation as is used in the
1157    HTTP/1.1 specification (RFC 2616) and the HTTP authentication
1158    specification (RFC 2617); it is reproduced here for ease of
1159    reference. Since it is intended that a single Digest implementation
1160    can support both HTTP and SASL-based protocols, the same notation is
1161    used in both to facilitate comparison and prevention of unwanted
1162    differences. Since it is cut-and-paste from the HTTP specifications,
1163    not all productions may be used in this specification. It is also not
1164    quite legal ABNF; again, the errors were copied from the HTTP
1165    specifications.
1167 7.1   Augmented BNF
1169    All of the mechanisms specified in this document are described in
1170    both prose and an augmented Backus-Naur Form (BNF) similar to that
1171    used by RFC 822 [RFC 822]. Implementers will need to be familiar with
1172    the notation in order to understand this specification.
1178 Leach & Newman              Standards Track                    [Page 21]
1180 RFC 2831                 Digest SASL Mechanism                  May 2000
1183    The augmented BNF includes the following constructs:
1185    name = definition
1186       The name of a rule is simply the name itself (without any
1187       enclosing "<" and ">") and is separated from its definition by the
1188       equal "=" character. White space is only significant in that
1189       indentation of continuation lines is used to indicate a rule
1190       definition that spans more than one line. Certain basic rules are
1191       in uppercase, such as SP, LWS, HT, CRLF, DIGIT, ALPHA, etc. Angle
1192       brackets are used within definitions whenever their presence will
1193       facilitate discerning the use of rule names.
1195    "literal"
1196       Quotation marks surround literal text. Unless stated otherwise,
1197       the text is case-insensitive.
1199    rule1 | rule2
1200       Elements separated by a bar ("|") are alternatives, e.g., "yes |
1201       no" will accept yes or no.
1203    (rule1 rule2)
1204       Elements enclosed in parentheses are treated as a single element.
1205       Thus, "(elem (foo | bar) elem)" allows the token sequences
1206       "elem foo elem" and "elem bar elem".
1208    *rule
1209       The character "*" preceding an element indicates repetition. The
1210       full form is "<n>*<m>element" indicating at least <n> and at most
1211       <m> occurrences of element. Default values are 0 and infinity so
1212       that "*(element)" allows any number, including zero; "1*element"
1213       requires at least one; and "1*2element" allows one or two.
1215    [rule]
1216       Square brackets enclose optional elements; "[foo bar]" is
1217       equivalent to "*1(foo bar)".
1219    N rule
1220       Specific repetition: "<n>(element)" is equivalent to
1221       "<n>*<n>(element)"; that is, exactly <n> occurrences of (element).
1222       Thus 2DIGIT is a 2-digit number, and 3ALPHA is a string of three
1223       alphabetic characters.
1225    #rule
1226       A construct "#" is defined, similar to "*", for defining lists of
1227       elements. The full form is "<n>#<m>element" indicating at least
1228       <n> and at most <m> elements, each separated by one or more commas
1229       (",") and OPTIONAL linear white space (LWS). This makes the usual
1230       form of lists very easy; a rule such as
1234 Leach & Newman              Standards Track                    [Page 22]
1236 RFC 2831                 Digest SASL Mechanism                  May 2000
1239         ( *LWS element *( *LWS "," *LWS element ))
1240       can be shown as
1241         1#element
1242       Wherever this construct is used, null elements are allowed, but do
1243       not contribute to the count of elements present. That is,
1244       "(element), , (element) " is permitted, but counts as only two
1245       elements.  Therefore, where at least one element is required, at
1246       least one non-null element MUST be present. Default values are 0
1247       and infinity so that "#element" allows any number, including zero;
1248       "1#element" requires at least one; and "1#2element" allows one or
1249       two.
1251    ; comment
1252       A semi-colon, set off some distance to the right of rule text,
1253       starts a comment that continues to the end of line. This is a
1254       simple way of including useful notes in parallel with the
1255       specifications.
1257    implied *LWS
1258       The grammar described by this specification is word-based. Except
1259       where noted otherwise, linear white space (LWS) can be included
1260       between any two adjacent words (token or quoted-string), and
1261       between adjacent words and separators, without changing the
1262       interpretation of a field. At least one delimiter (LWS and/or
1263       separators) MUST exist between any two tokens (for the definition
1264       of "token" below), since they would otherwise be interpreted as a
1265       single token.
1267 7.2   Basic Rules
1269    The following rules are used throughout this specification to
1270    describe basic parsing constructs. The US-ASCII coded character set
1271    is defined by ANSI X3.4-1986 [USASCII].
1273        OCTET          = <any 8-bit sequence of data>
1274        CHAR           = <any US-ASCII character (octets 0 - 127)>
1275        UPALPHA        = <any US-ASCII uppercase letter "A".."Z">
1276        LOALPHA        = <any US-ASCII lowercase letter "a".."z">
1277        ALPHA          = UPALPHA | LOALPHA
1278        DIGIT          = <any US-ASCII digit "0".."9">
1279        CTL            = <any US-ASCII control character
1280                         (octets 0 - 31) and DEL (127)>
1281        CR             = <US-ASCII CR, carriage return (13)>
1282        LF             = <US-ASCII LF, linefeed (10)>
1283        SP             = <US-ASCII SP, space (32)>
1284        HT             = <US-ASCII HT, horizontal-tab (9)>
1285        <">            = <US-ASCII double-quote mark (34)>
1286        CRLF           = CR LF
1290 Leach & Newman              Standards Track                    [Page 23]
1292 RFC 2831                 Digest SASL Mechanism                  May 2000
1296    All linear white space, including folding, has the same semantics as
1297    SP. A recipient MAY replace any linear white space with a single SP
1298    before interpreting the field value or forwarding the message
1299    downstream.
1301        LWS            = [CRLF] 1*( SP | HT )
1303    The TEXT rule is only used for descriptive field contents and values
1304    that are not intended to be interpreted by the message parser. Words
1305    of *TEXT MAY contain characters from character sets other than
1306    ISO-8859-1 [ISO 8859] only when encoded according to the rules of RFC
1307    2047 [RFC 2047].
1309        TEXT           = <any OCTET except CTLs,
1310                         but including LWS>
1312    A CRLF is allowed in the definition of TEXT only as part of a header
1313    field continuation. It is expected that the folding LWS will be
1314    replaced with a single SP before interpretation of the TEXT value.
1316    Hexadecimal numeric characters are used in several protocol elements.
1318        HEX            = "A" | "B" | "C" | "D" | "E" | "F"
1319                       | "a" | "b" | "c" | "d" | "e" | "f" | DIGIT
1321    Many HTTP/1.1 header field values consist of words separated by LWS
1322    or special characters. These special characters MUST be in a quoted
1323    string to be used within a parameter value.
1325        token          = 1*<any CHAR except CTLs or separators>
1326        separators     = "(" | ")" | "<" | ">" | "@"
1327                       | "," | ";" | ":" | "\" | <">
1328                       | "/" | "[" | "]" | "?" | "="
1329                       | "{" | "}" | SP | HT
1331    A string of text is parsed as a single word if it is quoted using
1332    double-quote marks.
1334       quoted-string  = ( <"> qdstr-val <"> )
1335       qdstr-val      = *( qdtext | quoted-pair )
1336       qdtext         = <any TEXT except <">>
1338    Note that LWS is NOT implicit between the double-quote marks (<">)
1339    surrounding a qdstr-val and the qdstr-val; any LWS will be considered
1340    part of the qdstr-val.  This is also the case for quotation marks
1341    surrounding any other construct.
1346 Leach & Newman              Standards Track                    [Page 24]
1348 RFC 2831                 Digest SASL Mechanism                  May 2000
1351    The backslash character ("\") MAY be used as a single-character
1352    quoting mechanism only within qdstr-val and comment constructs.
1354        quoted-pair    = "\" CHAR
1356    The value of this construct is CHAR. Note that an effect of this rule
1357    is that backslash must be quoted.
1359 8  Sample Code
1361    The sample implementation in [Digest] also applies to DIGEST-MD5.
1363    The following code implements the conversion from UTF-8 to 8859-1 if
1364    necessary.
1366     /* if the string is entirely in the 8859-1 subset of UTF-8, then
1367      * translate to 8859-1 prior to MD5
1368      */
1369     void MD5_UTF8_8859_1(MD5_CTX *ctx, const unsigned char *base,
1370         int len)
1371     {
1372         const unsigned char *scan, *end;
1373         unsigned char cbuf;
1375         end = base + len;
1376         for (scan = base; scan < end; ++scan) {
1377             if (*scan > 0xC3) break; /* abort if outside 8859-1 */
1378             if (*scan >= 0xC0 && *scan <= 0xC3) {
1379                 if (++scan == end || *scan < 0x80 || *scan > 0xBF)
1380                     break;
1381             }
1382         }
1383         /* if we found a character outside 8859-1, don't alter string
1384          */
1385         if (scan < end) {
1386             MD5Update(ctx, base, len);
1387             return;
1388         }
1390         /* convert to 8859-1 prior to applying hash
1391          */
1392         do {
1393             for (scan = base; scan < end && *scan < 0xC0; ++scan)
1394                 ;
1395             if (scan != base) MD5Update(ctx, base, scan - base);
1396             if (scan + 1 >= end) break;
1397             cbuf = ((scan[0] & 0x3) << 6) | (scan[1] & 0x3f);
1398             MD5Update(ctx, &cbuf, 1);
1402 Leach & Newman              Standards Track                    [Page 25]
1404 RFC 2831                 Digest SASL Mechanism                  May 2000
1407             base = scan + 2;
1408         } while (base < end);
1409     }
1458 Leach & Newman              Standards Track                    [Page 26]
1460 RFC 2831                 Digest SASL Mechanism                  May 2000
1463 9  Full Copyright Statement
1465    Copyright (C) The Internet Society (2000).  All Rights Reserved.
1467    This document and translations of it may be copied and furnished to
1468    others, and derivative works that comment on or otherwise explain it
1469    or assist in its implementation may be prepared, copied, published
1470    and distributed, in whole or in part, without restriction of any
1471    kind, provided that the above copyright notice and this paragraph are
1472    included on all such copies and derivative works.  However, this
1473    document itself may not be modified in any way, such as by removing
1474    the copyright notice or references to the Internet Society or other
1475    Internet organizations, except as needed for the purpose of
1476    developing Internet standards in which case the procedures for
1477    copyrights defined in the Internet Standards process must be
1478    followed, or as required to translate it into languages other than
1479    English.
1481    The limited permissions granted above are perpetual and will not be
1482    revoked by the Internet Society or its successors or assigns.
1484    This document and the information contained herein is provided on an
1485    "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
1486    TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
1487    BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
1488    HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
1489    MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
1491 Acknowledgement
1493    Funding for the RFC Editor function is currently provided by the
1494    Internet Society.
1514 Leach & Newman              Standards Track                    [Page 27]