Debian Codegraph @

extra/curl/curl-8.14.1/lib/vauth/digest.c

raw
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <[email protected]>, et al.
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 * SPDX-License-Identifier: curl
22 *
23 * RFC2831 DIGEST-MD5 authentication
24 * RFC7616 DIGEST-SHA256, DIGEST-SHA512-256 authentication
25 *
26 ***************************************************************************/
27
28 #include "../curl_setup.h"
29
30 #ifndef CURL_DISABLE_DIGEST_AUTH
31
32 #include <curl/curl.h>
33
34 #include "vauth.h"
35 #include "digest.h"
36 #include "../urldata.h"
37 #include "../curlx/base64.h"
38 #include "../curl_hmac.h"
39 #include "../curl_md5.h"
40 #include "../curl_sha256.h"
41 #include "../curl_sha512_256.h"
42 #include "../vtls/vtls.h"
43 #include "../curlx/warnless.h"
44 #include "../curlx/strparse.h"
45 #include "../strcase.h"
46 #include "../curl_printf.h"
47 #include "../rand.h"
48
49 /* The last #include files should be: */
50 #include "../curl_memory.h"
51 #include "../memdebug.h"
52
53 #ifndef USE_WINDOWS_SSPI
54 #define SESSION_ALGO 1 /* for algos with this bit set */
55
56 #define ALGO_MD5 0
57 #define ALGO_MD5SESS (ALGO_MD5 | SESSION_ALGO)
58 #define ALGO_SHA256 2
59 #define ALGO_SHA256SESS (ALGO_SHA256 | SESSION_ALGO)
60 #define ALGO_SHA512_256 4
61 #define ALGO_SHA512_256SESS (ALGO_SHA512_256 | SESSION_ALGO)
62
63 #define DIGEST_QOP_VALUE_AUTH (1 << 0)
64 #define DIGEST_QOP_VALUE_AUTH_INT (1 << 1)
65 #define DIGEST_QOP_VALUE_AUTH_CONF (1 << 2)
66
67 #define DIGEST_QOP_VALUE_STRING_AUTH "auth"
68 #define DIGEST_QOP_VALUE_STRING_AUTH_INT "auth-int"
69 #define DIGEST_QOP_VALUE_STRING_AUTH_CONF "auth-conf"
70 #endif
71
72 bool Curl_auth_digest_get_pair(const char *str, char *value, char *content,
73 const char **endptr)
74 {
75 int c;
76 bool starts_with_quote = FALSE;
77 bool escape = FALSE;
78
79 for(c = DIGEST_MAX_VALUE_LENGTH - 1; (*str && (*str != '=') && c--);)
80 *value++ = *str++;
81 *value = 0;
82
83 if('=' != *str++)
84 /* eek, no match */
85 return FALSE;
86
87 if('\"' == *str) {
88 /* This starts with a quote so it must end with one as well! */
89 str++;
90 starts_with_quote = TRUE;
91 }
92
93 for(c = DIGEST_MAX_CONTENT_LENGTH - 1; *str && c--; str++) {
94 if(!escape) {
95 switch(*str) {
96 case '\\':
97 if(starts_with_quote) {
98 /* the start of an escaped quote */
99 escape = TRUE;
100 continue;
101 }
102 break;
103
104 case ',':
105 if(!starts_with_quote) {
106 /* This signals the end of the content if we did not get a starting
107 quote and then we do "sloppy" parsing */
108 c = 0; /* the end */
109 continue;
110 }
111 break;
112
113 case '\r':
114 case '\n':
115 /* end of string */
116 if(starts_with_quote)
117 return FALSE; /* No closing quote */
118 c = 0;
119 continue;
120
121 case '\"':
122 if(starts_with_quote) {
123 /* end of string */
124 c = 0;
125 continue;
126 }
127 else
128 return FALSE;
129 }
130 }
131
132 escape = FALSE;
133 *content++ = *str;
134 }
135 if(escape)
136 return FALSE; /* No character after backslash */
137
138 *content = 0;
139 *endptr = str;
140
141 return TRUE;
142 }
143
144 #ifndef USE_WINDOWS_SSPI
145 /* Convert MD5 chunk to RFC2617 (section 3.1.3) -suitable ASCII string */
146 static void auth_digest_md5_to_ascii(unsigned char *source, /* 16 bytes */
147 unsigned char *dest) /* 33 bytes */
148 {
149 int i;
150 for(i = 0; i < 16; i++)
151 msnprintf((char *) &dest[i * 2], 3, "%02x", source[i]);
152 }
153
154 /* Convert sha256 or SHA-512/256 chunk to RFC7616 -suitable ASCII string */
155 static void auth_digest_sha256_to_ascii(unsigned char *source, /* 32 bytes */
156 unsigned char *dest) /* 65 bytes */
157 {
158 int i;
159 for(i = 0; i < 32; i++)
160 msnprintf((char *) &dest[i * 2], 3, "%02x", source[i]);
161 }
162
163 /* Perform quoted-string escaping as described in RFC2616 and its errata */
164 static char *auth_digest_string_quoted(const char *source)
165 {
166 char *dest;
167 const char *s = source;
168 size_t n = 1; /* null-terminator */
169
170 /* Calculate size needed */
171 while(*s) {
172 ++n;
173 if(*s == '"' || *s == '\\') {
174 ++n;
175 }
176 ++s;
177 }
178
179 dest = malloc(n);
180 if(dest) {
181 char *d = dest;
182 s = source;
183 while(*s) {
184 if(*s == '"' || *s == '\\') {
185 *d++ = '\\';
186 }
187 *d++ = *s++;
188 }
189 *d = '\0';
190 }
191
192 return dest;
193 }
194
195 /* Retrieves the value for a corresponding key from the challenge string
196 * returns TRUE if the key could be found, FALSE if it does not exists
197 */
198 static bool auth_digest_get_key_value(const char *chlg,
199 const char *key,
200 char *value,
201 size_t max_val_len,
202 char end_char)
203 {
204 char *find_pos;
205 size_t i;
206
207 find_pos = strstr(chlg, key);
208 if(!find_pos)
209 return FALSE;
210
211 find_pos += strlen(key);
212
213 for(i = 0; *find_pos && *find_pos != end_char && i < max_val_len - 1; ++i)
214 value[i] = *find_pos++;
215 value[i] = '\0';
216
217 return TRUE;
218 }
219
220 static CURLcode auth_digest_get_qop_values(const char *options, int *value)
221 {
222 struct Curl_str out;
223 /* Initialise the output */
224 *value = 0;
225
226 while(!curlx_str_until(&options, &out, 32, ',')) {
227 if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH))
228 *value |= DIGEST_QOP_VALUE_AUTH;
229 else if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH_INT))
230 *value |= DIGEST_QOP_VALUE_AUTH_INT;
231 else if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH_CONF))
232 *value |= DIGEST_QOP_VALUE_AUTH_CONF;
233 if(curlx_str_single(&options, ','))
234 break;
235 }
236
237 return CURLE_OK;
238 }
239
240 /*
241 * auth_decode_digest_md5_message()
242 *
243 * This is used internally to decode an already encoded DIGEST-MD5 challenge
244 * message into the separate attributes.
245 *
246 * Parameters:
247 *
248 * chlgref [in] - The challenge message.
249 * nonce [in/out] - The buffer where the nonce will be stored.
250 * nlen [in] - The length of the nonce buffer.
251 * realm [in/out] - The buffer where the realm will be stored.
252 * rlen [in] - The length of the realm buffer.
253 * alg [in/out] - The buffer where the algorithm will be stored.
254 * alen [in] - The length of the algorithm buffer.
255 * qop [in/out] - The buffer where the qop-options will be stored.
256 * qlen [in] - The length of the qop buffer.
257 *
258 * Returns CURLE_OK on success.
259 */
260 static CURLcode auth_decode_digest_md5_message(const struct bufref *chlgref,
261 char *nonce, size_t nlen,
262 char *realm, size_t rlen,
263 char *alg, size_t alen,
264 char *qop, size_t qlen)
265 {
266 const char *chlg = (const char *) Curl_bufref_ptr(chlgref);
267
268 /* Ensure we have a valid challenge message */
269 if(!Curl_bufref_len(chlgref))
270 return CURLE_BAD_CONTENT_ENCODING;
271
272 /* Retrieve nonce string from the challenge */
273 if(!auth_digest_get_key_value(chlg, "nonce=\"", nonce, nlen, '\"'))
274 return CURLE_BAD_CONTENT_ENCODING;
275
276 /* Retrieve realm string from the challenge */
277 if(!auth_digest_get_key_value(chlg, "realm=\"", realm, rlen, '\"')) {
278 /* Challenge does not have a realm, set empty string [RFC2831] page 6 */
279 *realm = '\0';
280 }
281
282 /* Retrieve algorithm string from the challenge */
283 if(!auth_digest_get_key_value(chlg, "algorithm=", alg, alen, ','))
284 return CURLE_BAD_CONTENT_ENCODING;
285
286 /* Retrieve qop-options string from the challenge */
287 if(!auth_digest_get_key_value(chlg, "qop=\"", qop, qlen, '\"'))
288 return CURLE_BAD_CONTENT_ENCODING;
289
290 return CURLE_OK;
291 }
292
293 /*
294 * Curl_auth_is_digest_supported()
295 *
296 * This is used to evaluate if DIGEST is supported.
297 *
298 * Parameters: None
299 *
300 * Returns TRUE as DIGEST as handled by libcurl.
301 */
302 bool Curl_auth_is_digest_supported(void)
303 {
304 return TRUE;
305 }
306
307 /*
308 * Curl_auth_create_digest_md5_message()
309 *
310 * This is used to generate an already encoded DIGEST-MD5 response message
311 * ready for sending to the recipient.
312 *
313 * Parameters:
314 *
315 * data [in] - The session handle.
316 * chlg [in] - The challenge message.
317 * userp [in] - The username.
318 * passwdp [in] - The user's password.
319 * service [in] - The service type such as http, smtp, pop or imap.
320 * out [out] - The result storage.
321 *
322 * Returns CURLE_OK on success.
323 */
324 CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data,
325 const struct bufref *chlg,
326 const char *userp,
327 const char *passwdp,
328 const char *service,
329 struct bufref *out)
330 {
331 size_t i;
332 struct MD5_context *ctxt;
333 char *response = NULL;
334 unsigned char digest[MD5_DIGEST_LEN];
335 char HA1_hex[2 * MD5_DIGEST_LEN + 1];
336 char HA2_hex[2 * MD5_DIGEST_LEN + 1];
337 char resp_hash_hex[2 * MD5_DIGEST_LEN + 1];
338 char nonce[64];
339 char realm[128];
340 char algorithm[64];
341 char qop_options[64];
342 int qop_values;
343 char cnonce[33];
344 char nonceCount[] = "00000001";
345 char method[] = "AUTHENTICATE";
346 char qop[] = DIGEST_QOP_VALUE_STRING_AUTH;
347 char *spn = NULL;
348
349 /* Decode the challenge message */
350 CURLcode result = auth_decode_digest_md5_message(chlg,
351 nonce, sizeof(nonce),
352 realm, sizeof(realm),
353 algorithm,
354 sizeof(algorithm),
355 qop_options,
356 sizeof(qop_options));
357 if(result)
358 return result;
359
360 /* We only support md5 sessions */
361 if(strcmp(algorithm, "md5-sess") != 0)
362 return CURLE_BAD_CONTENT_ENCODING;
363
364 /* Get the qop-values from the qop-options */
365 result = auth_digest_get_qop_values(qop_options, &qop_values);
366 if(result)
367 return result;
368
369 /* We only support auth quality-of-protection */
370 if(!(qop_values & DIGEST_QOP_VALUE_AUTH))
371 return CURLE_BAD_CONTENT_ENCODING;
372
373 /* Generate 32 random hex chars, 32 bytes + 1 null-termination */
374 result = Curl_rand_hex(data, (unsigned char *)cnonce, sizeof(cnonce));
375 if(result)
376 return result;
377
378 /* So far so good, now calculate A1 and H(A1) according to RFC 2831 */
379 ctxt = Curl_MD5_init(&Curl_DIGEST_MD5);
380 if(!ctxt)
381 return CURLE_OUT_OF_MEMORY;
382
383 Curl_MD5_update(ctxt, (const unsigned char *) userp,
384 curlx_uztoui(strlen(userp)));
385 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
386 Curl_MD5_update(ctxt, (const unsigned char *) realm,
387 curlx_uztoui(strlen(realm)));
388 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
389 Curl_MD5_update(ctxt, (const unsigned char *) passwdp,
390 curlx_uztoui(strlen(passwdp)));
391 Curl_MD5_final(ctxt, digest);
392
393 ctxt = Curl_MD5_init(&Curl_DIGEST_MD5);
394 if(!ctxt)
395 return CURLE_OUT_OF_MEMORY;
396
397 Curl_MD5_update(ctxt, (const unsigned char *) digest, MD5_DIGEST_LEN);
398 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
399 Curl_MD5_update(ctxt, (const unsigned char *) nonce,
400 curlx_uztoui(strlen(nonce)));
401 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
402 Curl_MD5_update(ctxt, (const unsigned char *) cnonce,
403 curlx_uztoui(strlen(cnonce)));
404 Curl_MD5_final(ctxt, digest);
405
406 /* Convert calculated 16 octet hex into 32 bytes string */
407 for(i = 0; i < MD5_DIGEST_LEN; i++)
408 msnprintf(&HA1_hex[2 * i], 3, "%02x", digest[i]);
409
410 /* Generate our SPN */
411 spn = Curl_auth_build_spn(service, data->conn->host.name, NULL);
412 if(!spn)
413 return CURLE_OUT_OF_MEMORY;
414
415 /* Calculate H(A2) */
416 ctxt = Curl_MD5_init(&Curl_DIGEST_MD5);
417 if(!ctxt) {
418 free(spn);
419
420 return CURLE_OUT_OF_MEMORY;
421 }
422
423 Curl_MD5_update(ctxt, (const unsigned char *) method,
424 curlx_uztoui(strlen(method)));
425 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
426 Curl_MD5_update(ctxt, (const unsigned char *) spn,
427 curlx_uztoui(strlen(spn)));
428 Curl_MD5_final(ctxt, digest);
429
430 for(i = 0; i < MD5_DIGEST_LEN; i++)
431 msnprintf(&HA2_hex[2 * i], 3, "%02x", digest[i]);
432
433 /* Now calculate the response hash */
434 ctxt = Curl_MD5_init(&Curl_DIGEST_MD5);
435 if(!ctxt) {
436 free(spn);
437
438 return CURLE_OUT_OF_MEMORY;
439 }
440
441 Curl_MD5_update(ctxt, (const unsigned char *) HA1_hex, 2 * MD5_DIGEST_LEN);
442 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
443 Curl_MD5_update(ctxt, (const unsigned char *) nonce,
444 curlx_uztoui(strlen(nonce)));
445 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
446
447 Curl_MD5_update(ctxt, (const unsigned char *) nonceCount,
448 curlx_uztoui(strlen(nonceCount)));
449 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
450 Curl_MD5_update(ctxt, (const unsigned char *) cnonce,
451 curlx_uztoui(strlen(cnonce)));
452 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
453 Curl_MD5_update(ctxt, (const unsigned char *) qop,
454 curlx_uztoui(strlen(qop)));
455 Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
456
457 Curl_MD5_update(ctxt, (const unsigned char *) HA2_hex, 2 * MD5_DIGEST_LEN);
458 Curl_MD5_final(ctxt, digest);
459
460 for(i = 0; i < MD5_DIGEST_LEN; i++)
461 msnprintf(&resp_hash_hex[2 * i], 3, "%02x", digest[i]);
462
463 /* Generate the response */
464 response = aprintf("username=\"%s\",realm=\"%s\",nonce=\"%s\","
465 "cnonce=\"%s\",nc=\"%s\",digest-uri=\"%s\",response=%s,"
466 "qop=%s",
467 userp, realm, nonce,
468 cnonce, nonceCount, spn, resp_hash_hex, qop);
469 free(spn);
470 if(!response)
471 return CURLE_OUT_OF_MEMORY;
472
473 /* Return the response. */
474 Curl_bufref_set(out, response, strlen(response), curl_free);
475 return result;
476 }
477
478 /*
479 * Curl_auth_decode_digest_http_message()
480 *
481 * This is used to decode an HTTP DIGEST challenge message into the separate
482 * attributes.
483 *
484 * Parameters:
485 *
486 * chlg [in] - The challenge message.
487 * digest [in/out] - The digest data struct being used and modified.
488 *
489 * Returns CURLE_OK on success.
490 */
491 CURLcode Curl_auth_decode_digest_http_message(const char *chlg,
492 struct digestdata *digest)
493 {
494 bool before = FALSE; /* got a nonce before */
495
496 /* If we already have received a nonce, keep that in mind */
497 if(digest->nonce)
498 before = TRUE;
499
500 /* Clean up any former leftovers and initialise to defaults */
501 Curl_auth_digest_cleanup(digest);
502
503 for(;;) {
504 char value[DIGEST_MAX_VALUE_LENGTH];
505 char content[DIGEST_MAX_CONTENT_LENGTH];
506
507 /* Pass all additional spaces here */
508 while(*chlg && ISBLANK(*chlg))
509 chlg++;
510
511 /* Extract a value=content pair */
512 if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) {
513 if(strcasecompare(value, "nonce")) {
514 free(digest->nonce);
515 digest->nonce = strdup(content);
516 if(!digest->nonce)
517 return CURLE_OUT_OF_MEMORY;
518 }
519 else if(strcasecompare(value, "stale")) {
520 if(strcasecompare(content, "true")) {
521 digest->stale = TRUE;
522 digest->nc = 1; /* we make a new nonce now */
523 }
524 }
525 else if(strcasecompare(value, "realm")) {
526 free(digest->realm);
527 digest->realm = strdup(content);
528 if(!digest->realm)
529 return CURLE_OUT_OF_MEMORY;
530 }
531 else if(strcasecompare(value, "opaque")) {
532 free(digest->opaque);
533 digest->opaque = strdup(content);
534 if(!digest->opaque)
535 return CURLE_OUT_OF_MEMORY;
536 }
537 else if(strcasecompare(value, "qop")) {
538 const char *token = content;
539 struct Curl_str out;
540 bool foundAuth = FALSE;
541 bool foundAuthInt = FALSE;
542 /* Pass leading spaces */
543 while(*token && ISBLANK(*token))
544 token++;
545 while(!curlx_str_until(&token, &out, 32, ',')) {
546 if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH))
547 foundAuth = TRUE;
548 else if(curlx_str_casecompare(&out,
549 DIGEST_QOP_VALUE_STRING_AUTH_INT))
550 foundAuthInt = TRUE;
551 if(curlx_str_single(&token, ','))
552 break;
553 while(*token && ISBLANK(*token))
554 token++;
555 }
556
557 /* Select only auth or auth-int. Otherwise, ignore */
558 if(foundAuth) {
559 free(digest->qop);
560 digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH);
561 if(!digest->qop)
562 return CURLE_OUT_OF_MEMORY;
563 }
564 else if(foundAuthInt) {
565 free(digest->qop);
566 digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT);
567 if(!digest->qop)
568 return CURLE_OUT_OF_MEMORY;
569 }
570 }
571 else if(strcasecompare(value, "algorithm")) {
572 free(digest->algorithm);
573 digest->algorithm = strdup(content);
574 if(!digest->algorithm)
575 return CURLE_OUT_OF_MEMORY;
576
577 if(strcasecompare(content, "MD5-sess"))
578 digest->algo = ALGO_MD5SESS;
579 else if(strcasecompare(content, "MD5"))
580 digest->algo = ALGO_MD5;
581 else if(strcasecompare(content, "SHA-256"))
582 digest->algo = ALGO_SHA256;
583 else if(strcasecompare(content, "SHA-256-SESS"))
584 digest->algo = ALGO_SHA256SESS;
585 else if(strcasecompare(content, "SHA-512-256")) {
586 #ifdef CURL_HAVE_SHA512_256
587 digest->algo = ALGO_SHA512_256;
588 #else /* ! CURL_HAVE_SHA512_256 */
589 return CURLE_NOT_BUILT_IN;
590 #endif /* ! CURL_HAVE_SHA512_256 */
591 }
592 else if(strcasecompare(content, "SHA-512-256-SESS")) {
593 #ifdef CURL_HAVE_SHA512_256
594 digest->algo = ALGO_SHA512_256SESS;
595 #else /* ! CURL_HAVE_SHA512_256 */
596 return CURLE_NOT_BUILT_IN;
597 #endif /* ! CURL_HAVE_SHA512_256 */
598 }
599 else
600 return CURLE_BAD_CONTENT_ENCODING;
601 }
602 else if(strcasecompare(value, "userhash")) {
603 if(strcasecompare(content, "true")) {
604 digest->userhash = TRUE;
605 }
606 }
607 else {
608 /* Unknown specifier, ignore it! */
609 }
610 }
611 else
612 break; /* We are done here */
613
614 /* Pass all additional spaces here */
615 while(*chlg && ISBLANK(*chlg))
616 chlg++;
617
618 /* Allow the list to be comma-separated */
619 if(',' == *chlg)
620 chlg++;
621 }
622
623 /* We had a nonce since before, and we got another one now without
624 'stale=true'. This means we provided bad credentials in the previous
625 request */
626 if(before && !digest->stale)
627 return CURLE_BAD_CONTENT_ENCODING;
628
629 /* We got this header without a nonce, that is a bad Digest line! */
630 if(!digest->nonce)
631 return CURLE_BAD_CONTENT_ENCODING;
632
633 /* "<algo>-sess" protocol versions require "auth" or "auth-int" qop */
634 if(!digest->qop && (digest->algo & SESSION_ALGO))
635 return CURLE_BAD_CONTENT_ENCODING;
636
637 return CURLE_OK;
638 }
639
640 /*
641 * auth_create_digest_http_message()
642 *
643 * This is used to generate an HTTP DIGEST response message ready for sending
644 * to the recipient.
645 *
646 * Parameters:
647 *
648 * data [in] - The session handle.
649 * userp [in] - The username.
650 * passwdp [in] - The user's password.
651 * request [in] - The HTTP request.
652 * uripath [in] - The path of the HTTP uri.
653 * digest [in/out] - The digest data struct being used and modified.
654 * outptr [in/out] - The address where a pointer to newly allocated memory
655 * holding the result will be stored upon completion.
656 * outlen [out] - The length of the output message.
657 *
658 * Returns CURLE_OK on success.
659 */
660 static CURLcode auth_create_digest_http_message(
661 struct Curl_easy *data,
662 const char *userp,
663 const char *passwdp,
664 const unsigned char *request,
665 const unsigned char *uripath,
666 struct digestdata *digest,
667 char **outptr, size_t *outlen,
668 void (*convert_to_ascii)(unsigned char *, unsigned char *),
669 CURLcode (*hash)(unsigned char *, const unsigned char *,
670 const size_t))
671 {
672 CURLcode result;
673 unsigned char hashbuf[32]; /* 32 bytes/256 bits */
674 unsigned char request_digest[65];
675 unsigned char ha1[65]; /* 64 digits and 1 zero byte */
676 unsigned char ha2[65]; /* 64 digits and 1 zero byte */
677 char userh[65];
678 char *cnonce = NULL;
679 size_t cnonce_sz = 0;
680 char *userp_quoted;
681 char *realm_quoted;
682 char *nonce_quoted;
683 char *response = NULL;
684 char *hashthis = NULL;
685 char *tmp = NULL;
686
687 memset(hashbuf, 0, sizeof(hashbuf));
688 if(!digest->nc)
689 digest->nc = 1;
690
691 if(!digest->cnonce) {
692 char cnoncebuf[12];
693 result = Curl_rand_bytes(data,
694 #ifdef DEBUGBUILD
695 TRUE,
696 #endif
697 (unsigned char *)cnoncebuf,
698 sizeof(cnoncebuf));
699 if(result)
700 return result;
701
702 result = curlx_base64_encode(cnoncebuf, sizeof(cnoncebuf),
703 &cnonce, &cnonce_sz);
704 if(result)
705 return result;
706
707 digest->cnonce = cnonce;
708 }
709
710 if(digest->userhash) {
711 hashthis = aprintf("%s:%s", userp, digest->realm ? digest->realm : "");
712 if(!hashthis)
713 return CURLE_OUT_OF_MEMORY;
714
715 result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis));
716 free(hashthis);
717 if(result)
718 return result;
719 convert_to_ascii(hashbuf, (unsigned char *)userh);
720 }
721
722 /*
723 If the algorithm is "MD5" or unspecified (which then defaults to MD5):
724
725 A1 = unq(username-value) ":" unq(realm-value) ":" passwd
726
727 If the algorithm is "MD5-sess" then:
728
729 A1 = H(unq(username-value) ":" unq(realm-value) ":" passwd) ":"
730 unq(nonce-value) ":" unq(cnonce-value)
731 */
732
733 hashthis = aprintf("%s:%s:%s", userp, digest->realm ? digest->realm : "",
734 passwdp);
735 if(!hashthis)
736 return CURLE_OUT_OF_MEMORY;
737
738 result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis));
739 free(hashthis);
740 if(result)
741 return result;
742 convert_to_ascii(hashbuf, ha1);
743
744 if(digest->algo & SESSION_ALGO) {
745 /* nonce and cnonce are OUTSIDE the hash */
746 tmp = aprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce);
747 if(!tmp)
748 return CURLE_OUT_OF_MEMORY;
749
750 result = hash(hashbuf, (unsigned char *) tmp, strlen(tmp));
751 free(tmp);
752 if(result)
753 return result;
754 convert_to_ascii(hashbuf, ha1);
755 }
756
757 /*
758 If the "qop" directive's value is "auth" or is unspecified, then A2 is:
759
760 A2 = Method ":" digest-uri-value
761
762 If the "qop" value is "auth-int", then A2 is:
763
764 A2 = Method ":" digest-uri-value ":" H(entity-body)
765
766 (The "Method" value is the HTTP request method as specified in section
767 5.1.1 of RFC 2616)
768 */
769
770 hashthis = aprintf("%s:%s", request, uripath);
771 if(!hashthis)
772 return CURLE_OUT_OF_MEMORY;
773
774 if(digest->qop && strcasecompare(digest->qop, "auth-int")) {
775 /* We do not support auth-int for PUT or POST */
776 char hashed[65];
777 char *hashthis2;
778
779 result = hash(hashbuf, (const unsigned char *)"", 0);
780 if(result) {
781 free(hashthis);
782 return result;
783 }
784 convert_to_ascii(hashbuf, (unsigned char *)hashed);
785
786 hashthis2 = aprintf("%s:%s", hashthis, hashed);
787 free(hashthis);
788 hashthis = hashthis2;
789 }
790
791 if(!hashthis)
792 return CURLE_OUT_OF_MEMORY;
793
794 result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis));
795 free(hashthis);
796 if(result)
797 return result;
798 convert_to_ascii(hashbuf, ha2);
799
800 if(digest->qop) {
801 hashthis = aprintf("%s:%s:%08x:%s:%s:%s", ha1, digest->nonce, digest->nc,
802 digest->cnonce, digest->qop, ha2);
803 }
804 else {
805 hashthis = aprintf("%s:%s:%s", ha1, digest->nonce, ha2);
806 }
807
808 if(!hashthis)
809 return CURLE_OUT_OF_MEMORY;
810
811 result = hash(hashbuf, (unsigned char *) hashthis, strlen(hashthis));
812 free(hashthis);
813 if(result)
814 return result;
815 convert_to_ascii(hashbuf, request_digest);
816
817 /* For test case 64 (snooped from a Mozilla 1.3a request)
818
819 Authorization: Digest username="testuser", realm="testrealm", \
820 nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
821
822 Digest parameters are all quoted strings. Username which is provided by
823 the user will need double quotes and backslashes within it escaped.
824 realm, nonce, and opaque will need backslashes as well as they were
825 de-escaped when copied from request header. cnonce is generated with
826 web-safe characters. uri is already percent encoded. nc is 8 hex
827 characters. algorithm and qop with standard values only contain web-safe
828 characters.
829 */
830 userp_quoted = auth_digest_string_quoted(digest->userhash ? userh : userp);
831 if(!userp_quoted)
832 return CURLE_OUT_OF_MEMORY;
833 if(digest->realm)
834 realm_quoted = auth_digest_string_quoted(digest->realm);
835 else {
836 realm_quoted = malloc(1);
837 if(realm_quoted)
838 realm_quoted[0] = 0;
839 }
840 if(!realm_quoted) {
841 free(userp_quoted);
842 return CURLE_OUT_OF_MEMORY;
843 }
844 nonce_quoted = auth_digest_string_quoted(digest->nonce);
845 if(!nonce_quoted) {
846 free(realm_quoted);
847 free(userp_quoted);
848 return CURLE_OUT_OF_MEMORY;
849 }
850
851 if(digest->qop) {
852 response = aprintf("username=\"%s\", "
853 "realm=\"%s\", "
854 "nonce=\"%s\", "
855 "uri=\"%s\", "
856 "cnonce=\"%s\", "
857 "nc=%08x, "
858 "qop=%s, "
859 "response=\"%s\"",
860 userp_quoted,
861 realm_quoted,
862 nonce_quoted,
863 uripath,
864 digest->cnonce,
865 digest->nc,
866 digest->qop,
867 request_digest);
868
869 /* Increment nonce-count to use another nc value for the next request */
870 digest->nc++;
871 }
872 else {
873 response = aprintf("username=\"%s\", "
874 "realm=\"%s\", "
875 "nonce=\"%s\", "
876 "uri=\"%s\", "
877 "response=\"%s\"",
878 userp_quoted,
879 realm_quoted,
880 nonce_quoted,
881 uripath,
882 request_digest);
883 }
884 free(nonce_quoted);
885 free(realm_quoted);
886 free(userp_quoted);
887 if(!response)
888 return CURLE_OUT_OF_MEMORY;
889
890 /* Add the optional fields */
891 if(digest->opaque) {
892 char *opaque_quoted;
893 /* Append the opaque */
894 opaque_quoted = auth_digest_string_quoted(digest->opaque);
895 if(!opaque_quoted) {
896 free(response);
897 return CURLE_OUT_OF_MEMORY;
898 }
899 tmp = aprintf("%s, opaque=\"%s\"", response, opaque_quoted);
900 free(response);
901 free(opaque_quoted);
902 if(!tmp)
903 return CURLE_OUT_OF_MEMORY;
904
905 response = tmp;
906 }
907
908 if(digest->algorithm) {
909 /* Append the algorithm */
910 tmp = aprintf("%s, algorithm=%s", response, digest->algorithm);
911 free(response);
912 if(!tmp)
913 return CURLE_OUT_OF_MEMORY;
914
915 response = tmp;
916 }
917
918 if(digest->userhash) {
919 /* Append the userhash */
920 tmp = aprintf("%s, userhash=true", response);
921 free(response);
922 if(!tmp)
923 return CURLE_OUT_OF_MEMORY;
924
925 response = tmp;
926 }
927
928 /* Return the output */
929 *outptr = response;
930 *outlen = strlen(response);
931
932 return CURLE_OK;
933 }
934
935 /*
936 * Curl_auth_create_digest_http_message()
937 *
938 * This is used to generate an HTTP DIGEST response message ready for sending
939 * to the recipient.
940 *
941 * Parameters:
942 *
943 * data [in] - The session handle.
944 * userp [in] - The username.
945 * passwdp [in] - The user's password.
946 * request [in] - The HTTP request.
947 * uripath [in] - The path of the HTTP uri.
948 * digest [in/out] - The digest data struct being used and modified.
949 * outptr [in/out] - The address where a pointer to newly allocated memory
950 * holding the result will be stored upon completion.
951 * outlen [out] - The length of the output message.
952 *
953 * Returns CURLE_OK on success.
954 */
955 CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data,
956 const char *userp,
957 const char *passwdp,
958 const unsigned char *request,
959 const unsigned char *uripath,
960 struct digestdata *digest,
961 char **outptr, size_t *outlen)
962 {
963 if(digest->algo <= ALGO_MD5SESS)
964 return auth_create_digest_http_message(data, userp, passwdp,
965 request, uripath, digest,
966 outptr, outlen,
967 auth_digest_md5_to_ascii,
968 Curl_md5it);
969
970 if(digest->algo <= ALGO_SHA256SESS)
971 return auth_create_digest_http_message(data, userp, passwdp,
972 request, uripath, digest,
973 outptr, outlen,
974 auth_digest_sha256_to_ascii,
975 Curl_sha256it);
976 #ifdef CURL_HAVE_SHA512_256
977 if(digest->algo <= ALGO_SHA512_256SESS)
978 return auth_create_digest_http_message(data, userp, passwdp,
979 request, uripath, digest,
980 outptr, outlen,
981 auth_digest_sha256_to_ascii,
982 Curl_sha512_256it);
983 #endif /* CURL_HAVE_SHA512_256 */
984
985 /* Should be unreachable */
986 return CURLE_BAD_CONTENT_ENCODING;
987 }
988
989 /*
990 * Curl_auth_digest_cleanup()
991 *
992 * This is used to clean up the digest specific data.
993 *
994 * Parameters:
995 *
996 * digest [in/out] - The digest data struct being cleaned up.
997 *
998 */
999 void Curl_auth_digest_cleanup(struct digestdata *digest)
1000 {
1001 Curl_safefree(digest->nonce);
1002 Curl_safefree(digest->cnonce);
1003 Curl_safefree(digest->realm);
1004 Curl_safefree(digest->opaque);
1005 Curl_safefree(digest->qop);
1006 Curl_safefree(digest->algorithm);
1007
1008 digest->nc = 0;
1009 digest->algo = ALGO_MD5; /* default algorithm */
1010 digest->stale = FALSE; /* default means normal, not stale */
1011 digest->userhash = FALSE;
1012 }
1013 #endif /* !USE_WINDOWS_SSPI */
1014
1015 #endif /* !CURL_DISABLE_DIGEST_AUTH */