From 0957d30e86496c452a174187401976f04201b799 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adrien=20B=C3=A9raud?= <adrien.beraud@savoirfairelinux.com>
Date: Sat, 10 Feb 2018 23:21:09 +0100
Subject: [PATCH] y2038 bug: don't allow time wrap for certificate validity

---
 src/crypto.cpp | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/src/crypto.cpp b/src/crypto.cpp
index 957cdfad..348bdfdc 100644
--- a/src/crypto.cpp
+++ b/src/crypto.cpp
@@ -926,9 +926,13 @@ Certificate::generate(const PrivateKey& key, const std::string& name, Identity c
         return {};
     Certificate ret {cert};
 
-    std::time_t now = time(NULL);
-    gnutls_x509_crt_set_activation_time(cert, now);
-    gnutls_x509_crt_set_expiration_time(cert, now + (10 * 365 * 24 * 60 * 60));
+    int64_t now = time(NULL);
+    /* 2038 bug: don't allow time wrap */
+    auto boundTime = [](int64_t t) -> time_t {
+        return std::min<int64_t>(t, std::numeric_limits<time_t>::max());
+    };
+    gnutls_x509_crt_set_activation_time(cert, boundTime(now));
+    gnutls_x509_crt_set_expiration_time(cert, boundTime(now + (10 * 365 * 24 * 60 * 60)));
     if (gnutls_x509_crt_set_key(cert, key.x509_key) != GNUTLS_E_SUCCESS) {
         std::cerr << "Error when setting certificate key" << std::endl;
         return {};
-- 
GitLab