Coverage Report

Created: 2026-10-15 06:19

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