Coverage Report

Created: 2025-10-13 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/hsts.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
 ***************************************************************************/
24
/*
25
 * The Strict-Transport-Security header is defined in RFC 6797:
26
 * https://datatracker.ietf.org/doc/html/rfc6797
27
 */
28
#include "curl_setup.h"
29
30
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HSTS)
31
#include <curl/curl.h>
32
#include "urldata.h"
33
#include "llist.h"
34
#include "hsts.h"
35
#include "curl_fopen.h"
36
#include "curl_get_line.h"
37
#include "sendf.h"
38
#include "parsedate.h"
39
#include "rename.h"
40
#include "share.h"
41
#include "strdup.h"
42
#include "curlx/strparse.h"
43
44
/* The last 2 #include files should be in this order */
45
#include "curl_memory.h"
46
#include "memdebug.h"
47
48
105k
#define MAX_HSTS_LINE 4095
49
31.6k
#define MAX_HSTS_HOSTLEN 2048
50
0
#define MAX_HSTS_DATELEN 256
51
12
#define UNLIMITED "unlimited"
52
53
#if defined(DEBUGBUILD) || defined(UNITTESTS)
54
/* to play well with debug builds, we can *set* a fixed time this will
55
   return */
56
time_t deltatime; /* allow for "adjustments" for unit test purposes */
57
static time_t hsts_debugtime(void *unused)
58
36.3k
{
59
36.3k
  const char *timestr = getenv("CURL_TIME");
60
36.3k
  (void)unused;
61
36.3k
  if(timestr) {
62
0
    curl_off_t val;
63
0
    if(!curlx_str_number(&timestr, &val, TIME_T_MAX))
64
0
      val += (curl_off_t)deltatime;
65
0
    return (time_t)val;
66
0
  }
67
36.3k
  return time(NULL);
68
36.3k
}
69
#undef time
70
36.3k
#define time(x) hsts_debugtime(x)
71
#endif
72
73
struct hsts *Curl_hsts_init(void)
74
143k
{
75
143k
  struct hsts *h = calloc(1, sizeof(struct hsts));
76
143k
  if(h) {
77
143k
    Curl_llist_init(&h->list, NULL);
78
143k
  }
79
143k
  return h;
80
143k
}
81
82
static void hsts_free(struct stsentry *e)
83
146
{
84
146
  free(CURL_UNCONST(e->host));
85
146
  free(e);
86
146
}
87
88
void Curl_hsts_cleanup(struct hsts **hp)
89
316k
{
90
316k
  struct hsts *h = *hp;
91
316k
  if(h) {
92
143k
    struct Curl_llist_node *e;
93
143k
    struct Curl_llist_node *n;
94
143k
    for(e = Curl_llist_head(&h->list); e; e = n) {
95
125
      struct stsentry *sts = Curl_node_elem(e);
96
125
      n = Curl_node_next(e);
97
125
      hsts_free(sts);
98
125
    }
99
143k
    free(h->filename);
100
143k
    free(h);
101
143k
    *hp = NULL;
102
143k
  }
103
316k
}
104
105
static CURLcode hsts_create(struct hsts *h,
106
                            const char *hostname,
107
                            size_t hlen,
108
                            bool subdomains,
109
                            curl_off_t expires)
110
521
{
111
521
  DEBUGASSERT(h);
112
521
  DEBUGASSERT(hostname);
113
114
521
  if(hlen && (hostname[hlen - 1] == '.'))
115
    /* strip off any trailing dot */
116
401
    --hlen;
117
521
  if(hlen) {
118
146
    char *duphost;
119
146
    struct stsentry *sts = calloc(1, sizeof(struct stsentry));
120
146
    if(!sts)
121
0
      return CURLE_OUT_OF_MEMORY;
122
123
146
    duphost = Curl_memdup0(hostname, hlen);
124
146
    if(!duphost) {
125
0
      free(sts);
126
0
      return CURLE_OUT_OF_MEMORY;
127
0
    }
128
129
146
    sts->host = duphost;
130
146
    sts->expires = expires;
131
146
    sts->includeSubDomains = subdomains;
132
146
    Curl_llist_append(&h->list, sts, &sts->node);
133
146
  }
134
521
  return CURLE_OK;
135
521
}
136
137
CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname,
138
                         const char *header)
139
4.62k
{
140
4.62k
  const char *p = header;
141
4.62k
  curl_off_t expires = 0;
142
4.62k
  bool gotma = FALSE;
143
4.62k
  bool gotinc = FALSE;
144
4.62k
  bool subdomains = FALSE;
145
4.62k
  struct stsentry *sts;
146
4.62k
  time_t now = time(NULL);
147
4.62k
  size_t hlen = strlen(hostname);
148
149
4.62k
  if(Curl_host_is_ipnum(hostname))
150
    /* "explicit IP address identification of all forms is excluded."
151
       / RFC 6797 */
152
988
    return CURLE_OK;
153
154
11.4k
  do {
155
11.4k
    curlx_str_passblanks(&p);
156
11.4k
    if(curl_strnequal("max-age", p, 7)) {
157
2.54k
      bool quoted = FALSE;
158
2.54k
      int rc;
159
160
2.54k
      if(gotma)
161
201
        return CURLE_BAD_FUNCTION_ARGUMENT;
162
163
2.34k
      p += 7;
164
2.34k
      curlx_str_passblanks(&p);
165
2.34k
      if(curlx_str_single(&p, '='))
166
197
        return CURLE_BAD_FUNCTION_ARGUMENT;
167
2.14k
      curlx_str_passblanks(&p);
168
169
2.14k
      if(!curlx_str_single(&p, '\"'))
170
493
        quoted = TRUE;
171
172
2.14k
      rc = curlx_str_number(&p, &expires, TIME_T_MAX);
173
2.14k
      if(rc == STRE_OVERFLOW)
174
377
        expires = CURL_OFF_T_MAX;
175
1.77k
      else if(rc)
176
        /* invalid max-age */
177
211
        return CURLE_BAD_FUNCTION_ARGUMENT;
178
179
1.93k
      if(quoted) {
180
493
        if(*p != '\"')
181
205
          return CURLE_BAD_FUNCTION_ARGUMENT;
182
288
        p++;
183
288
      }
184
1.73k
      gotma = TRUE;
185
1.73k
    }
186
8.93k
    else if(curl_strnequal("includesubdomains", p, 17)) {
187
458
      if(gotinc)
188
216
        return CURLE_BAD_FUNCTION_ARGUMENT;
189
242
      subdomains = TRUE;
190
242
      p += 17;
191
242
      gotinc = TRUE;
192
242
    }
193
8.47k
    else {
194
      /* unknown directive, do a lame attempt to skip */
195
137k
      while(*p && (*p != ';'))
196
129k
        p++;
197
8.47k
    }
198
199
10.4k
    curlx_str_passblanks(&p);
200
10.4k
    if(*p == ';')
201
5.87k
      p++;
202
10.4k
  } while(*p);
203
204
2.60k
  if(!gotma)
205
    /* max-age is mandatory */
206
1.07k
    return CURLE_BAD_FUNCTION_ARGUMENT;
207
208
1.53k
  if(!expires) {
209
    /* remove the entry if present verbatim (without subdomain match) */
210
316
    sts = Curl_hsts(h, hostname, hlen, FALSE);
211
316
    if(sts) {
212
21
      Curl_node_remove(&sts->node);
213
21
      hsts_free(sts);
214
21
    }
215
316
    return CURLE_OK;
216
316
  }
217
218
1.21k
  if(CURL_OFF_T_MAX - now < expires)
219
    /* would overflow, use maximum value */
220
247
    expires = CURL_OFF_T_MAX;
221
967
  else
222
967
    expires += now;
223
224
  /* check if it already exists */
225
1.21k
  sts = Curl_hsts(h, hostname, hlen, FALSE);
226
1.21k
  if(sts) {
227
    /* just update these fields */
228
693
    sts->expires = expires;
229
693
    sts->includeSubDomains = subdomains;
230
693
  }
231
521
  else
232
521
    return hsts_create(h, hostname, hlen, subdomains, expires);
233
234
693
  return CURLE_OK;
235
1.21k
}
236
237
/*
238
 * Return TRUE if the given hostname is currently an HSTS one.
239
 *
240
 * The 'subdomain' argument tells the function if subdomain matching should be
241
 * attempted.
242
 */
243
struct stsentry *Curl_hsts(struct hsts *h, const char *hostname,
244
                           size_t hlen, bool subdomain)
245
31.6k
{
246
31.6k
  struct stsentry *bestsub = NULL;
247
31.6k
  if(h) {
248
31.6k
    time_t now = time(NULL);
249
31.6k
    struct Curl_llist_node *e;
250
31.6k
    struct Curl_llist_node *n;
251
31.6k
    size_t blen = 0;
252
253
31.6k
    if((hlen > MAX_HSTS_HOSTLEN) || !hlen)
254
18
      return NULL;
255
31.6k
    if(hostname[hlen-1] == '.')
256
      /* remove the trailing dot */
257
3.01k
      --hlen;
258
259
31.6k
    for(e = Curl_llist_head(&h->list); e; e = n) {
260
719
      struct stsentry *sts = Curl_node_elem(e);
261
719
      size_t ntail;
262
719
      n = Curl_node_next(e);
263
719
      if(sts->expires <= now) {
264
        /* remove expired entries */
265
0
        Curl_node_remove(&sts->node);
266
0
        hsts_free(sts);
267
0
        continue;
268
0
      }
269
719
      ntail = strlen(sts->host);
270
719
      if((subdomain && sts->includeSubDomains) && (ntail < hlen)) {
271
0
        size_t offs = hlen - ntail;
272
0
        if((hostname[offs-1] == '.') &&
273
0
           curl_strnequal(&hostname[offs], sts->host, ntail) &&
274
0
           (ntail > blen)) {
275
          /* save the tail match with the longest tail */
276
0
          bestsub = sts;
277
0
          blen = ntail;
278
0
        }
279
0
      }
280
      /* avoid curl_strequal because the host name is not null-terminated */
281
719
      if((hlen == ntail) && curl_strnequal(hostname, sts->host, hlen))
282
717
        return sts;
283
719
    }
284
31.6k
  }
285
30.9k
  return bestsub;
286
31.6k
}
287
288
/*
289
 * Send this HSTS entry to the write callback.
290
 */
291
static CURLcode hsts_push(struct Curl_easy *data,
292
                          struct curl_index *i,
293
                          struct stsentry *sts,
294
                          bool *stop)
295
0
{
296
0
  struct curl_hstsentry e;
297
0
  CURLSTScode sc;
298
0
  struct tm stamp;
299
0
  CURLcode result;
300
301
0
  e.name = (char *)CURL_UNCONST(sts->host);
302
0
  e.namelen = strlen(sts->host);
303
0
  e.includeSubDomains = sts->includeSubDomains;
304
305
0
  if(sts->expires != TIME_T_MAX) {
306
0
    result = Curl_gmtime((time_t)sts->expires, &stamp);
307
0
    if(result)
308
0
      return result;
309
310
0
    curl_msnprintf(e.expire, sizeof(e.expire), "%d%02d%02d %02d:%02d:%02d",
311
0
                   stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
312
0
                   stamp.tm_hour, stamp.tm_min, stamp.tm_sec);
313
0
  }
314
0
  else
315
0
    strcpy(e.expire, UNLIMITED);
316
317
0
  sc = data->set.hsts_write(data, &e, i,
318
0
                            data->set.hsts_write_userp);
319
0
  *stop = (sc != CURLSTS_OK);
320
0
  return sc == CURLSTS_FAIL ? CURLE_BAD_FUNCTION_ARGUMENT : CURLE_OK;
321
0
}
322
323
/*
324
 * Write this single hsts entry to a single output line
325
 */
326
static CURLcode hsts_out(struct stsentry *sts, FILE *fp)
327
125
{
328
125
  struct tm stamp;
329
125
  if(sts->expires != TIME_T_MAX) {
330
113
    CURLcode result = Curl_gmtime((time_t)sts->expires, &stamp);
331
113
    if(result)
332
43
      return result;
333
70
    curl_mfprintf(fp, "%s%s \"%d%02d%02d %02d:%02d:%02d\"\n",
334
70
                  sts->includeSubDomains ? ".": "", sts->host,
335
70
                  stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
336
70
                  stamp.tm_hour, stamp.tm_min, stamp.tm_sec);
337
70
  }
338
12
  else
339
12
    curl_mfprintf(fp, "%s%s \"%s\"\n",
340
12
                  sts->includeSubDomains ? ".": "", sts->host, UNLIMITED);
341
82
  return CURLE_OK;
342
125
}
343
344
345
/*
346
 * Curl_https_save() writes the HSTS cache to file and callback.
347
 */
348
CURLcode Curl_hsts_save(struct Curl_easy *data, struct hsts *h,
349
                        const char *file)
350
316k
{
351
316k
  struct Curl_llist_node *e;
352
316k
  struct Curl_llist_node *n;
353
316k
  CURLcode result = CURLE_OK;
354
316k
  FILE *out;
355
316k
  char *tempstore = NULL;
356
357
316k
  if(!h)
358
    /* no cache activated */
359
172k
    return CURLE_OK;
360
361
  /* if no new name is given, use the one we stored from the load */
362
143k
  if(!file && h->filename)
363
0
    file = h->filename;
364
365
143k
  if((h->flags & CURLHSTS_READONLYFILE) || !file || !file[0])
366
    /* marked as read-only, no file or zero length filename */
367
40
    goto skipsave;
368
369
143k
  result = Curl_fopen(data, file, &out, &tempstore);
370
143k
  if(!result) {
371
143k
    fputs("# Your HSTS cache. https://curl.se/docs/hsts.html\n"
372
143k
          "# This file was generated by libcurl! Edit at your own risk.\n",
373
143k
          out);
374
143k
    for(e = Curl_llist_head(&h->list); e; e = n) {
375
125
      struct stsentry *sts = Curl_node_elem(e);
376
125
      n = Curl_node_next(e);
377
125
      result = hsts_out(sts, out);
378
125
      if(result)
379
43
        break;
380
125
    }
381
143k
    curlx_fclose(out);
382
143k
    if(!result && tempstore && Curl_rename(tempstore, file))
383
0
      result = CURLE_WRITE_ERROR;
384
385
143k
    if(result && tempstore)
386
0
      unlink(tempstore);
387
143k
  }
388
143k
  free(tempstore);
389
143k
skipsave:
390
143k
  if(data->set.hsts_write) {
391
    /* if there is a write callback */
392
0
    struct curl_index i; /* count */
393
0
    i.total = Curl_llist_count(&h->list);
394
0
    i.index = 0;
395
0
    for(e = Curl_llist_head(&h->list); e; e = n) {
396
0
      struct stsentry *sts = Curl_node_elem(e);
397
0
      bool stop;
398
0
      n = Curl_node_next(e);
399
0
      result = hsts_push(data, &i, sts, &stop);
400
0
      if(result || stop)
401
0
        break;
402
0
      i.index++;
403
0
    }
404
0
  }
405
143k
  return result;
406
143k
}
407
408
/* only returns SERIOUS errors */
409
static CURLcode hsts_add(struct hsts *h, const char *line)
410
0
{
411
  /* Example lines:
412
     example.com "20191231 10:00:00"
413
     .example.net "20191231 10:00:00"
414
   */
415
0
  struct Curl_str host;
416
0
  struct Curl_str date;
417
418
0
  if(curlx_str_word(&line, &host, MAX_HSTS_HOSTLEN) ||
419
0
     curlx_str_singlespace(&line) ||
420
0
     curlx_str_quotedword(&line, &date, MAX_HSTS_DATELEN) ||
421
0
     curlx_str_newline(&line))
422
0
    ;
423
0
  else {
424
0
    CURLcode result = CURLE_OK;
425
0
    bool subdomain = FALSE;
426
0
    struct stsentry *e;
427
0
    char dbuf[MAX_HSTS_DATELEN + 1];
428
0
    time_t expires = 0;
429
0
    const char *hp = curlx_str(&host);
430
431
    /* The date parser works on a null-terminated string. The maximum length
432
       is upheld by curlx_str_quotedword(). */
433
0
    memcpy(dbuf, curlx_str(&date), curlx_strlen(&date));
434
0
    dbuf[curlx_strlen(&date)] = 0;
435
436
0
    if(!strcmp(dbuf, UNLIMITED))
437
0
      expires = TIME_T_MAX;
438
0
    else
439
0
      Curl_getdate_capped(dbuf, &expires);
440
441
0
    if(hp[0] == '.') {
442
0
      curlx_str_nudge(&host, 1);
443
0
      subdomain = TRUE;
444
0
    }
445
    /* only add it if not already present */
446
0
    e = Curl_hsts(h, curlx_str(&host), curlx_strlen(&host), subdomain);
447
0
    if(!e)
448
0
      result = hsts_create(h, curlx_str(&host), curlx_strlen(&host),
449
0
                           subdomain, expires);
450
0
    else if(curlx_str_casecompare(&host, e->host)) {
451
      /* the same hostname, use the largest expire time */
452
0
      if(expires > e->expires)
453
0
        e->expires = expires;
454
0
    }
455
0
    if(result)
456
0
      return result;
457
0
  }
458
459
0
  return CURLE_OK;
460
0
}
461
462
/*
463
 * Load HSTS data from callback.
464
 *
465
 */
466
static CURLcode hsts_pull(struct Curl_easy *data, struct hsts *h)
467
105k
{
468
  /* if the HSTS read callback is set, use it */
469
105k
  if(data->set.hsts_read) {
470
0
    CURLSTScode sc;
471
0
    DEBUGASSERT(h);
472
0
    do {
473
0
      char buffer[MAX_HSTS_HOSTLEN + 1];
474
0
      struct curl_hstsentry e;
475
0
      e.name = buffer;
476
0
      e.namelen = sizeof(buffer)-1;
477
0
      e.includeSubDomains = FALSE; /* default */
478
0
      e.expire[0] = 0;
479
0
      e.name[0] = 0; /* just to make it clean */
480
0
      sc = data->set.hsts_read(data, &e, data->set.hsts_read_userp);
481
0
      if(sc == CURLSTS_OK) {
482
0
        time_t expires = 0;
483
0
        CURLcode result;
484
0
        DEBUGASSERT(e.name[0]);
485
0
        if(!e.name[0])
486
          /* bail out if no name was stored */
487
0
          return CURLE_BAD_FUNCTION_ARGUMENT;
488
0
        if(e.expire[0])
489
0
          Curl_getdate_capped(e.expire, &expires);
490
0
        else
491
0
          expires = TIME_T_MAX; /* the end of time */
492
0
        result = hsts_create(h, e.name, strlen(e.name),
493
                             /* bitfield to bool conversion: */
494
0
                             e.includeSubDomains ? TRUE : FALSE,
495
0
                             expires);
496
0
        if(result)
497
0
          return result;
498
0
      }
499
0
      else if(sc == CURLSTS_FAIL)
500
0
        return CURLE_ABORTED_BY_CALLBACK;
501
0
    } while(sc == CURLSTS_OK);
502
0
  }
503
105k
  return CURLE_OK;
504
105k
}
505
506
/*
507
 * Load the HSTS cache from the given file. The text based line-oriented file
508
 * format is documented here: https://curl.se/docs/hsts.html
509
 *
510
 * This function only returns error on major problems that prevent hsts
511
 * handling to work completely. It will ignore individual syntactical errors
512
 * etc.
513
 */
514
static CURLcode hsts_load(struct hsts *h, const char *file)
515
105k
{
516
105k
  CURLcode result = CURLE_OK;
517
105k
  FILE *fp;
518
519
  /* we need a private copy of the filename so that the hsts cache file
520
     name survives an easy handle reset */
521
105k
  free(h->filename);
522
105k
  h->filename = strdup(file);
523
105k
  if(!h->filename)
524
0
    return CURLE_OUT_OF_MEMORY;
525
526
105k
  fp = curlx_fopen(file, FOPEN_READTEXT);
527
105k
  if(fp) {
528
105k
    struct dynbuf buf;
529
105k
    curlx_dyn_init(&buf, MAX_HSTS_LINE);
530
105k
    while(Curl_get_line(&buf, fp)) {
531
0
      const char *lineptr = curlx_dyn_ptr(&buf);
532
0
      curlx_str_passblanks(&lineptr);
533
534
      /*
535
       * Skip empty or commented lines, since we know the line will have a
536
       * trailing newline from Curl_get_line we can treat length 1 as empty.
537
       */
538
0
      if((*lineptr == '#') || strlen(lineptr) <= 1)
539
0
        continue;
540
541
0
      hsts_add(h, lineptr);
542
0
    }
543
105k
    curlx_dyn_free(&buf); /* free the line buffer */
544
105k
    curlx_fclose(fp);
545
105k
  }
546
105k
  return result;
547
105k
}
548
549
/*
550
 * Curl_hsts_loadfile() loads HSTS from file
551
 */
552
CURLcode Curl_hsts_loadfile(struct Curl_easy *data,
553
                            struct hsts *h, const char *file)
554
105k
{
555
105k
  DEBUGASSERT(h);
556
105k
  (void)data;
557
105k
  return hsts_load(h, file);
558
105k
}
559
560
/*
561
 * Curl_hsts_loadcb() loads HSTS from callback
562
 */
563
CURLcode Curl_hsts_loadcb(struct Curl_easy *data, struct hsts *h)
564
112k
{
565
112k
  if(h)
566
105k
    return hsts_pull(data, h);
567
7.64k
  return CURLE_OK;
568
112k
}
569
570
void Curl_hsts_loadfiles(struct Curl_easy *data)
571
112k
{
572
112k
  struct curl_slist *l = data->state.hstslist;
573
112k
  if(l) {
574
105k
    Curl_share_lock(data, CURL_LOCK_DATA_HSTS, CURL_LOCK_ACCESS_SINGLE);
575
576
210k
    while(l) {
577
105k
      (void)Curl_hsts_loadfile(data, data->hsts, l->data);
578
105k
      l = l->next;
579
105k
    }
580
105k
    Curl_share_unlock(data, CURL_LOCK_DATA_HSTS);
581
105k
  }
582
112k
}
583
584
#if defined(DEBUGBUILD) || defined(UNITTESTS)
585
#undef time
586
#endif
587
588
#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */