Coverage Report

Created: 2026-10-31 06:46

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