Coverage Report

Created: 2025-11-11 06:17

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