Coverage Report

Created: 2025-10-10 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PROJ/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
0
#define MAX_HSTS_LINE 4095
49
0
#define MAX_HSTS_HOSTLEN 2048
50
0
#define MAX_HSTS_DATELEN 256
51
0
#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
{
59
  const char *timestr = getenv("CURL_TIME");
60
  (void)unused;
61
  if(timestr) {
62
    curl_off_t val;
63
    if(!curlx_str_number(&timestr, &val, TIME_T_MAX))
64
      val += (curl_off_t)deltatime;
65
    return (time_t)val;
66
  }
67
  return time(NULL);
68
}
69
#undef time
70
#define time(x) hsts_debugtime(x)
71
#endif
72
73
struct hsts *Curl_hsts_init(void)
74
0
{
75
0
  struct hsts *h = calloc(1, sizeof(struct hsts));
76
0
  if(h) {
77
0
    Curl_llist_init(&h->list, NULL);
78
0
  }
79
0
  return h;
80
0
}
81
82
static void hsts_free(struct stsentry *e)
83
0
{
84
0
  free(CURL_UNCONST(e->host));
85
0
  free(e);
86
0
}
87
88
void Curl_hsts_cleanup(struct hsts **hp)
89
0
{
90
0
  struct hsts *h = *hp;
91
0
  if(h) {
92
0
    struct Curl_llist_node *e;
93
0
    struct Curl_llist_node *n;
94
0
    for(e = Curl_llist_head(&h->list); e; e = n) {
95
0
      struct stsentry *sts = Curl_node_elem(e);
96
0
      n = Curl_node_next(e);
97
0
      hsts_free(sts);
98
0
    }
99
0
    free(h->filename);
100
0
    free(h);
101
0
    *hp = NULL;
102
0
  }
103
0
}
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
0
{
111
0
  DEBUGASSERT(h);
112
0
  DEBUGASSERT(hostname);
113
114
0
  if(hlen && (hostname[hlen - 1] == '.'))
115
    /* strip off any trailing dot */
116
0
    --hlen;
117
0
  if(hlen) {
118
0
    char *duphost;
119
0
    struct stsentry *sts = calloc(1, sizeof(struct stsentry));
120
0
    if(!sts)
121
0
      return CURLE_OUT_OF_MEMORY;
122
123
0
    duphost = Curl_memdup0(hostname, hlen);
124
0
    if(!duphost) {
125
0
      free(sts);
126
0
      return CURLE_OUT_OF_MEMORY;
127
0
    }
128
129
0
    sts->host = duphost;
130
0
    sts->expires = expires;
131
0
    sts->includeSubDomains = subdomains;
132
0
    Curl_llist_append(&h->list, sts, &sts->node);
133
0
  }
134
0
  return CURLE_OK;
135
0
}
136
137
CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname,
138
                         const char *header)
139
0
{
140
0
  const char *p = header;
141
0
  curl_off_t expires = 0;
142
0
  bool gotma = FALSE;
143
0
  bool gotinc = FALSE;
144
0
  bool subdomains = FALSE;
145
0
  struct stsentry *sts;
146
0
  time_t now = time(NULL);
147
0
  size_t hlen = strlen(hostname);
148
149
0
  if(Curl_host_is_ipnum(hostname))
150
    /* "explicit IP address identification of all forms is excluded."
151
       / RFC 6797 */
152
0
    return CURLE_OK;
153
154
0
  do {
155
0
    curlx_str_passblanks(&p);
156
0
    if(curl_strnequal("max-age", p, 7)) {
157
0
      bool quoted = FALSE;
158
0
      int rc;
159
160
0
      if(gotma)
161
0
        return CURLE_BAD_FUNCTION_ARGUMENT;
162
163
0
      p += 7;
164
0
      curlx_str_passblanks(&p);
165
0
      if(curlx_str_single(&p, '='))
166
0
        return CURLE_BAD_FUNCTION_ARGUMENT;
167
0
      curlx_str_passblanks(&p);
168
169
0
      if(!curlx_str_single(&p, '\"'))
170
0
        quoted = TRUE;
171
172
0
      rc = curlx_str_number(&p, &expires, TIME_T_MAX);
173
0
      if(rc == STRE_OVERFLOW)
174
0
        expires = CURL_OFF_T_MAX;
175
0
      else if(rc)
176
        /* invalid max-age */
177
0
        return CURLE_BAD_FUNCTION_ARGUMENT;
178
179
0
      if(quoted) {
180
0
        if(*p != '\"')
181
0
          return CURLE_BAD_FUNCTION_ARGUMENT;
182
0
        p++;
183
0
      }
184
0
      gotma = TRUE;
185
0
    }
186
0
    else if(curl_strnequal("includesubdomains", p, 17)) {
187
0
      if(gotinc)
188
0
        return CURLE_BAD_FUNCTION_ARGUMENT;
189
0
      subdomains = TRUE;
190
0
      p += 17;
191
0
      gotinc = TRUE;
192
0
    }
193
0
    else {
194
      /* unknown directive, do a lame attempt to skip */
195
0
      while(*p && (*p != ';'))
196
0
        p++;
197
0
    }
198
199
0
    curlx_str_passblanks(&p);
200
0
    if(*p == ';')
201
0
      p++;
202
0
  } while(*p);
203
204
0
  if(!gotma)
205
    /* max-age is mandatory */
206
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
207
208
0
  if(!expires) {
209
    /* remove the entry if present verbatim (without subdomain match) */
210
0
    sts = Curl_hsts(h, hostname, hlen, FALSE);
211
0
    if(sts) {
212
0
      Curl_node_remove(&sts->node);
213
0
      hsts_free(sts);
214
0
    }
215
0
    return CURLE_OK;
216
0
  }
217
218
0
  if(CURL_OFF_T_MAX - now < expires)
219
    /* would overflow, use maximum value */
220
0
    expires = CURL_OFF_T_MAX;
221
0
  else
222
0
    expires += now;
223
224
  /* check if it already exists */
225
0
  sts = Curl_hsts(h, hostname, hlen, FALSE);
226
0
  if(sts) {
227
    /* just update these fields */
228
0
    sts->expires = expires;
229
0
    sts->includeSubDomains = subdomains;
230
0
  }
231
0
  else
232
0
    return hsts_create(h, hostname, hlen, subdomains, expires);
233
234
0
  return CURLE_OK;
235
0
}
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
0
{
246
0
  struct stsentry *bestsub = NULL;
247
0
  if(h) {
248
0
    time_t now = time(NULL);
249
0
    struct Curl_llist_node *e;
250
0
    struct Curl_llist_node *n;
251
0
    size_t blen = 0;
252
253
0
    if((hlen > MAX_HSTS_HOSTLEN) || !hlen)
254
0
      return NULL;
255
0
    if(hostname[hlen-1] == '.')
256
      /* remove the trailing dot */
257
0
      --hlen;
258
259
0
    for(e = Curl_llist_head(&h->list); e; e = n) {
260
0
      struct stsentry *sts = Curl_node_elem(e);
261
0
      size_t ntail;
262
0
      n = Curl_node_next(e);
263
0
      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
0
      ntail = strlen(sts->host);
270
0
      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
0
      if((hlen == ntail) && curl_strnequal(hostname, sts->host, hlen))
282
0
        return sts;
283
0
    }
284
0
  }
285
0
  return bestsub;
286
0
}
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
0
{
328
0
  struct tm stamp;
329
0
  if(sts->expires != TIME_T_MAX) {
330
0
    CURLcode result = Curl_gmtime((time_t)sts->expires, &stamp);
331
0
    if(result)
332
0
      return result;
333
0
    curl_mfprintf(fp, "%s%s \"%d%02d%02d %02d:%02d:%02d\"\n",
334
0
                  sts->includeSubDomains ? ".": "", sts->host,
335
0
                  stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
336
0
                  stamp.tm_hour, stamp.tm_min, stamp.tm_sec);
337
0
  }
338
0
  else
339
0
    curl_mfprintf(fp, "%s%s \"%s\"\n",
340
0
                  sts->includeSubDomains ? ".": "", sts->host, UNLIMITED);
341
0
  return CURLE_OK;
342
0
}
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
0
{
351
0
  struct Curl_llist_node *e;
352
0
  struct Curl_llist_node *n;
353
0
  CURLcode result = CURLE_OK;
354
0
  FILE *out;
355
0
  char *tempstore = NULL;
356
357
0
  if(!h)
358
    /* no cache activated */
359
0
    return CURLE_OK;
360
361
  /* if no new name is given, use the one we stored from the load */
362
0
  if(!file && h->filename)
363
0
    file = h->filename;
364
365
0
  if((h->flags & CURLHSTS_READONLYFILE) || !file || !file[0])
366
    /* marked as read-only, no file or zero length filename */
367
0
    goto skipsave;
368
369
0
  result = Curl_fopen(data, file, &out, &tempstore);
370
0
  if(!result) {
371
0
    fputs("# Your HSTS cache. https://curl.se/docs/hsts.html\n"
372
0
          "# This file was generated by libcurl! Edit at your own risk.\n",
373
0
          out);
374
0
    for(e = Curl_llist_head(&h->list); e; e = n) {
375
0
      struct stsentry *sts = Curl_node_elem(e);
376
0
      n = Curl_node_next(e);
377
0
      result = hsts_out(sts, out);
378
0
      if(result)
379
0
        break;
380
0
    }
381
0
    curlx_fclose(out);
382
0
    if(!result && tempstore && Curl_rename(tempstore, file))
383
0
      result = CURLE_WRITE_ERROR;
384
385
0
    if(result && tempstore)
386
0
      unlink(tempstore);
387
0
  }
388
0
  free(tempstore);
389
0
skipsave:
390
0
  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
0
  return result;
406
0
}
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
0
{
468
  /* if the HSTS read callback is set, use it */
469
0
  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
0
  return CURLE_OK;
504
0
}
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
0
{
516
0
  CURLcode result = CURLE_OK;
517
0
  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
0
  free(h->filename);
522
0
  h->filename = strdup(file);
523
0
  if(!h->filename)
524
0
    return CURLE_OUT_OF_MEMORY;
525
526
0
  fp = curlx_fopen(file, FOPEN_READTEXT);
527
0
  if(fp) {
528
0
    struct dynbuf buf;
529
0
    curlx_dyn_init(&buf, MAX_HSTS_LINE);
530
0
    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
0
    curlx_dyn_free(&buf); /* free the line buffer */
544
0
    curlx_fclose(fp);
545
0
  }
546
0
  return result;
547
0
}
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
0
{
555
0
  DEBUGASSERT(h);
556
0
  (void)data;
557
0
  return hsts_load(h, file);
558
0
}
559
560
/*
561
 * Curl_hsts_loadcb() loads HSTS from callback
562
 */
563
CURLcode Curl_hsts_loadcb(struct Curl_easy *data, struct hsts *h)
564
0
{
565
0
  if(h)
566
0
    return hsts_pull(data, h);
567
0
  return CURLE_OK;
568
0
}
569
570
void Curl_hsts_loadfiles(struct Curl_easy *data)
571
0
{
572
0
  struct curl_slist *l = data->state.hstslist;
573
0
  if(l) {
574
0
    Curl_share_lock(data, CURL_LOCK_DATA_HSTS, CURL_LOCK_ACCESS_SINGLE);
575
576
0
    while(l) {
577
0
      (void)Curl_hsts_loadfile(data, data->hsts, l->data);
578
0
      l = l->next;
579
0
    }
580
0
    Curl_share_unlock(data, CURL_LOCK_DATA_HSTS);
581
0
  }
582
0
}
583
584
#if defined(DEBUGBUILD) || defined(UNITTESTS)
585
#undef time
586
#endif
587
588
#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */