Coverage Report

Created: 2022-09-28 06:21

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