2 * Copyright 1999-2024 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 * This is an implementation of the ASN1 Time structure which is:
14 * generalTime GeneralizedTime }
19 #include "crypto/asn1.h"
20 #include "crypto/ctype.h"
21 #include "internal/cryptlib.h"
22 #include <openssl/asn1t.h>
23 #include "asn1_local.h"
25 IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME)
27 IMPLEMENT_ASN1_FUNCTIONS(ASN1_TIME)
28 IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_TIME)
30 static int is_utc(const int year)
32 if (50 <= year && year <= 149)
37 static int leap_year(const int year)
39 if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
45 * Compute the day of the week and the day of the year from the year, month
46 * and day. The day of the year is straightforward, the day of the week uses
47 * a form of Zeller's congruence. For this months start with March and are
48 * numbered 4 through 15.
50 static void determine_days(struct tm *tm)
52 static const int ydays[12] = {
53 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
55 int y = tm->tm_year + 1900;
60 tm->tm_yday = ydays[m] + d - 1;
62 /* March and onwards can be one day further into the year */
63 tm->tm_yday += leap_year(y);
66 /* Treat January and February as part of the previous year */
72 /* Zeller's congruence */
73 tm->tm_wday = (d + (13 * m) / 5 + y + y / 4 + c / 4 + 5 * c + 6) % 7;
76 int ossl_asn1_time_to_tm(struct tm *tm, const ASN1_TIME *d)
78 static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
79 static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
80 static const int mdays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
82 int n, i, i2, l, o, min_l, strict = 0, end = 6, btz = 5, md;
84 #if defined(CHARSET_EBCDIC)
85 const char upper_z = 0x5A, num_zero = 0x30, period = 0x2E, minus = 0x2D, plus = 0x2B;
87 const char upper_z = 'Z', num_zero = '0', period = '.', minus = '-', plus = '+';
90 * ASN1_STRING_FLAG_X509_TIME is used to enforce RFC 5280
91 * time string format, in which:
93 * 1. "seconds" is a 'MUST'
94 * 2. "Zulu" timezone is a 'MUST'
95 * 3. "+|-" is not allowed to indicate a timezone
97 if (d->type == V_ASN1_UTCTIME) {
99 if (d->flags & ASN1_STRING_FLAG_X509_TIME) {
102 } else if (d->type == V_ASN1_GENERALIZEDTIME) {
106 if (d->flags & ASN1_STRING_FLAG_X509_TIME) {
116 memset(&tmp, 0, sizeof(tmp));
119 * GENERALIZEDTIME is similar to UTCTIME except the year is represented
120 * as YYYY. This stuff treats everything as a two digit field so make
121 * first two fields 00 to 99
126 for (i = 0; i < end; i++) {
127 if (!strict && (i == btz) && ((a[o] == upper_z) || (a[o] == plus) || (a[o] == minus))) {
131 if (!ossl_ascii_isdigit(a[o]))
134 /* incomplete 2-digital number */
138 if (!ossl_ascii_isdigit(a[o]))
140 n = (n * 10) + a[o] - num_zero;
141 /* no more bytes to read, but we haven't seen time-zone yet */
145 i2 = (d->type == V_ASN1_UTCTIME) ? i + 1 : i;
147 if ((n < min[i2]) || (n > max[i2]))
151 /* UTC will never be here */
152 tmp.tm_year = n * 100 - 1900;
155 if (d->type == V_ASN1_UTCTIME)
156 tmp.tm_year = n < 50 ? n + 100 : n;
164 /* check if tm_mday is valid in tm_mon */
165 if (tmp.tm_mon == 1) {
167 md = mdays[1] + leap_year(tmp.tm_year + 1900);
169 md = mdays[tmp.tm_mon];
174 determine_days(&tmp);
189 * Optional fractional seconds: decimal point followed by one or more
192 if (d->type == V_ASN1_GENERALIZEDTIME && a[o] == period) {
194 /* RFC 5280 forbids fractional seconds */
199 while ((o < l) && ossl_ascii_isdigit(a[o]))
201 /* Must have at least one digit after decimal point */
204 /* no more bytes to read, but we haven't seen time-zone yet */
210 * 'o' will never point to '\0' at this point, the only chance
211 * 'o' can point to '\0' is either the subsequent if or the first
214 if (a[o] == upper_z) {
216 } else if (!strict && ((a[o] == plus) || (a[o] == minus))) {
217 int offsign = a[o] == minus ? 1 : -1;
222 * if not equal, no need to do subsequent checks
223 * since the following for-loop will add 'o' by 4
224 * and the final return statement will check if 'l'
229 for (i = end; i < end + 2; i++) {
230 if (!ossl_ascii_isdigit(a[o]))
234 if (!ossl_ascii_isdigit(a[o]))
236 n = (n * 10) + a[o] - num_zero;
237 i2 = (d->type == V_ASN1_UTCTIME) ? i + 1 : i;
238 if ((n < min[i2]) || (n > max[i2]))
240 /* if tm is NULL, no need to adjust */
244 else if (i == end + 1)
249 if (offset && !OPENSSL_gmtime_adj(&tmp, 0, offset * offsign))
252 /* not Z, or not +/- in non-strict mode */
256 /* success, check if tm should be filled */
265 ASN1_TIME *ossl_asn1_time_from_tm(ASN1_TIME *s, struct tm *ts, int type)
268 ASN1_TIME *tmps = NULL;
269 const size_t len = 20;
271 if (type == V_ASN1_UNDEF) {
272 if (is_utc(ts->tm_year))
273 type = V_ASN1_UTCTIME;
275 type = V_ASN1_GENERALIZEDTIME;
276 } else if (type == V_ASN1_UTCTIME) {
277 if (!is_utc(ts->tm_year))
279 } else if (type != V_ASN1_GENERALIZEDTIME) {
284 tmps = ASN1_STRING_new();
290 if (!ASN1_STRING_set(tmps, NULL, len))
294 p = (char*)tmps->data;
296 if (ts->tm_mon > INT_MAX - 1)
299 if (type == V_ASN1_GENERALIZEDTIME) {
300 if (ts->tm_year > INT_MAX - 1900)
302 tmps->length = BIO_snprintf(p, len, "%04d%02d%02d%02d%02d%02dZ",
303 ts->tm_year + 1900, ts->tm_mon + 1,
304 ts->tm_mday, ts->tm_hour, ts->tm_min,
307 tmps->length = BIO_snprintf(p, len, "%02d%02d%02d%02d%02d%02dZ",
308 ts->tm_year % 100, ts->tm_mon + 1,
309 ts->tm_mday, ts->tm_hour, ts->tm_min,
313 #ifdef CHARSET_EBCDIC
314 ebcdic2ascii(tmps->data, tmps->data, tmps->length);
319 ASN1_STRING_free(tmps);
323 ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t)
325 return ASN1_TIME_adj(s, t, 0, 0);
328 ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
329 int offset_day, long offset_sec)
334 ts = OPENSSL_gmtime(&t, &data);
336 ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_GETTING_TIME);
339 if (offset_day || offset_sec) {
340 if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
343 return ossl_asn1_time_from_tm(s, ts, V_ASN1_UNDEF);
346 int ASN1_TIME_check(const ASN1_TIME *t)
348 if (t->type == V_ASN1_GENERALIZEDTIME)
349 return ASN1_GENERALIZEDTIME_check(t);
350 else if (t->type == V_ASN1_UTCTIME)
351 return ASN1_UTCTIME_check(t);
355 /* Convert an ASN1_TIME structure to GeneralizedTime */
356 ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
357 ASN1_GENERALIZEDTIME **out)
359 ASN1_GENERALIZEDTIME *ret = NULL;
362 if (!ASN1_TIME_to_tm(t, &tm))
368 ret = ossl_asn1_time_from_tm(ret, &tm, V_ASN1_GENERALIZEDTIME);
370 if (out != NULL && ret != NULL)
376 int ASN1_TIME_set_string(ASN1_TIME *s, const char *str)
378 /* Try UTC, if that fails, try GENERALIZED */
379 if (ASN1_UTCTIME_set_string(s, str))
381 return ASN1_GENERALIZEDTIME_set_string(s, str);
384 int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str)
390 t.length = strlen(str);
391 t.data = (unsigned char *)str;
392 t.flags = ASN1_STRING_FLAG_X509_TIME;
394 t.type = V_ASN1_UTCTIME;
396 if (!ASN1_TIME_check(&t)) {
397 t.type = V_ASN1_GENERALIZEDTIME;
398 if (!ASN1_TIME_check(&t))
403 * Per RFC 5280 (section 4.1.2.5.), the valid input time
404 * strings should be encoded with the following rules:
406 * 1. UTC: YYMMDDHHMMSSZ, if YY < 50 (20YY) --> UTC: YYMMDDHHMMSSZ
407 * 2. UTC: YYMMDDHHMMSSZ, if YY >= 50 (19YY) --> UTC: YYMMDDHHMMSSZ
408 * 3. G'd: YYYYMMDDHHMMSSZ, if YYYY >= 2050 --> G'd: YYYYMMDDHHMMSSZ
409 * 4. G'd: YYYYMMDDHHMMSSZ, if YYYY < 2050 --> UTC: YYMMDDHHMMSSZ
411 * Only strings of the 4th rule should be reformatted, but since a
412 * UTC can only present [1950, 2050), so if the given time string
413 * is less than 1950 (e.g. 19230419000000Z), we do nothing...
416 if (s != NULL && t.type == V_ASN1_GENERALIZEDTIME) {
417 if (!ossl_asn1_time_to_tm(&tm, &t))
419 if (is_utc(tm.tm_year)) {
422 * it's OK to let original t.data go since that's assigned
423 * to a piece of memory allocated outside of this function.
424 * new t.data would be freed after ASN1_STRING_copy is done.
426 t.data = OPENSSL_zalloc(t.length + 1);
429 memcpy(t.data, str + 2, t.length);
430 t.type = V_ASN1_UTCTIME;
434 if (s == NULL || ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t))
437 if (t.data != (unsigned char *)str)
438 OPENSSL_free(t.data);
443 int ASN1_TIME_to_tm(const ASN1_TIME *s, struct tm *tm)
449 memset(tm, 0, sizeof(*tm));
450 if (OPENSSL_gmtime(&now_t, tm) != NULL)
455 return ossl_asn1_time_to_tm(tm, s);
458 int ASN1_TIME_diff(int *pday, int *psec,
459 const ASN1_TIME *from, const ASN1_TIME *to)
461 struct tm tm_from, tm_to;
463 if (!ASN1_TIME_to_tm(from, &tm_from))
465 if (!ASN1_TIME_to_tm(to, &tm_to))
467 return OPENSSL_gmtime_diff(pday, psec, &tm_from, &tm_to);
470 static const char _asn1_mon[12][4] = {
471 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
472 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
475 /* prints the time with the default date format (RFC 822) */
476 int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm)
478 return ASN1_TIME_print_ex(bp, tm, ASN1_DTFLGS_RFC822);
481 /* returns 1 on success, 0 on BIO write error or parse failure */
482 int ASN1_TIME_print_ex(BIO *bp, const ASN1_TIME *tm, unsigned long flags)
484 return ossl_asn1_time_print_ex(bp, tm, flags) > 0;
488 /* prints the time with the date format of ISO 8601 */
489 /* returns 0 on BIO write error, else -1 in case of parse failure, else 1 */
490 int ossl_asn1_time_print_ex(BIO *bp, const ASN1_TIME *tm, unsigned long flags)
495 const char upper_z = 0x5A, period = 0x2E;
497 /* ossl_asn1_time_to_tm will check the time type */
498 if (!ossl_asn1_time_to_tm(&stm, tm))
499 return BIO_write(bp, "Bad time value", 14) ? -1 : 0;
502 v = (char *)tm->data;
503 if (v[l - 1] == upper_z)
506 if (tm->type == V_ASN1_GENERALIZEDTIME) {
511 * Try to parse fractional seconds. '14' is the place of
512 * 'fraction point' in a GeneralizedTime string.
514 if (tm->length > 15 && v[14] == period) {
517 while (14 + f_len < l && ossl_ascii_isdigit(f[f_len]))
521 if ((flags & ASN1_DTFLGS_TYPE_MASK) == ASN1_DTFLGS_ISO8601) {
522 return BIO_printf(bp, "%4d-%02d-%02d %02d:%02d:%02d%.*s%s",
523 stm.tm_year + 1900, stm.tm_mon + 1,
524 stm.tm_mday, stm.tm_hour,
525 stm.tm_min, stm.tm_sec, f_len, f,
526 (gmt ? "Z" : "")) > 0;
529 return BIO_printf(bp, "%s %2d %02d:%02d:%02d%.*s %d%s",
530 _asn1_mon[stm.tm_mon], stm.tm_mday, stm.tm_hour,
531 stm.tm_min, stm.tm_sec, f_len, f, stm.tm_year + 1900,
532 (gmt ? " GMT" : "")) > 0;
535 if ((flags & ASN1_DTFLGS_TYPE_MASK) == ASN1_DTFLGS_ISO8601) {
536 return BIO_printf(bp, "%4d-%02d-%02d %02d:%02d:%02d%s",
537 stm.tm_year + 1900, stm.tm_mon + 1,
538 stm.tm_mday, stm.tm_hour,
539 stm.tm_min, stm.tm_sec,
540 (gmt ? "Z" : "")) > 0;
543 return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d%s",
544 _asn1_mon[stm.tm_mon], stm.tm_mday, stm.tm_hour,
545 stm.tm_min, stm.tm_sec, stm.tm_year + 1900,
546 (gmt ? " GMT" : "")) > 0;
551 int ASN1_TIME_cmp_time_t(const ASN1_TIME *s, time_t t)
556 if (!ASN1_TIME_to_tm(s, &stm))
559 if (!OPENSSL_gmtime(&t, &ttm))
562 if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
565 if (day > 0 || sec > 0)
567 if (day < 0 || sec < 0)
572 int ASN1_TIME_normalize(ASN1_TIME *t)
576 if (t == NULL || !ASN1_TIME_to_tm(t, &tm))
579 return ossl_asn1_time_from_tm(t, &tm, V_ASN1_UNDEF) != NULL;
582 int ASN1_TIME_compare(const ASN1_TIME *a, const ASN1_TIME *b)
586 if (!ASN1_TIME_diff(&day, &sec, b, a))
588 if (day > 0 || sec > 0)
590 if (day < 0 || sec < 0)
599 # define timezone _timezone
602 #if defined(__FreeBSD__) || defined(__wasi__)
606 time_t ossl_asn1_string_to_time_t(const char *asn1_string)
608 ASN1_TIME *timestamp_asn1 = NULL;
609 struct tm *timestamp_tm = NULL;
610 #if defined(__DJGPP__)
612 #elif !defined(USE_TIMEGM)
613 time_t timestamp_local;
615 time_t timestamp_utc;
617 timestamp_asn1 = ASN1_TIME_new();
618 if (!ASN1_TIME_set_string(timestamp_asn1, asn1_string))
620 ASN1_TIME_free(timestamp_asn1);
624 timestamp_tm = OPENSSL_malloc(sizeof(*timestamp_tm));
625 if (timestamp_tm == NULL) {
626 ASN1_TIME_free(timestamp_asn1);
629 if (!(ASN1_TIME_to_tm(timestamp_asn1, timestamp_tm))) {
630 OPENSSL_free(timestamp_tm);
631 ASN1_TIME_free(timestamp_asn1);
634 ASN1_TIME_free(timestamp_asn1);
636 #if defined(__DJGPP__)
638 * This is NOT thread-safe. Do not use this method for platforms other
643 tz = OPENSSL_strdup(tz);
645 OPENSSL_free(timestamp_tm);
649 setenv("TZ", "UTC", 1);
651 timestamp_utc = mktime(timestamp_tm);
659 #elif defined(USE_TIMEGM)
660 timestamp_utc = timegm(timestamp_tm);
662 timestamp_local = mktime(timestamp_tm);
663 timestamp_utc = timestamp_local - timezone;
665 OPENSSL_free(timestamp_tm);
667 return timestamp_utc;