Coverage Report

Created: 2026-09-04 07:15

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