Coverage Report

Created: 2022-09-28 06:21

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