Coverage Report

Created: 2026-07-16 06:10

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