Coverage Report

Created: 2025-07-12 06:36

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