Blob


1 /*
2 * Copyright (c) 2021, 2023 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2019 Renaud Allard <renaud@allard.it>
4 * Copyright (c) 2016 Kristaps Dzonsons <kristaps@bsd.lv>
5 * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
6 * Copyright (c) 2008 Reyk Floeter <reyk@openbsd.org>
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
21 #include "gmid.h"
23 #include <errno.h>
24 #include <string.h>
25 #include <vis.h> /* for gmid_strnvis() */
27 #include <openssl/ec.h>
28 #include <openssl/err.h>
29 #include <openssl/evp.h>
30 #include <openssl/obj_mac.h>
31 #include <openssl/pem.h>
32 #include <openssl/rsa.h>
33 #include <openssl/x509_vfy.h>
34 #include <openssl/x509v3.h>
36 #include "log.h"
38 /*
39 * Default number of bits when creating a new RSA key.
40 */
41 #define KBITS 4096
43 const char *
44 strip_path(const char *path, int strip)
45 {
46 char *t;
48 while (strip > 0) {
49 if ((t = strchr(path, '/')) == NULL) {
50 path = strchr(path, '\0');
51 break;
52 }
53 path = t;
54 strip--;
55 }
57 return path;
58 }
60 int
61 ends_with(const char *str, const char *sufx)
62 {
63 size_t i, j;
65 i = strlen(str);
66 j = strlen(sufx);
68 if (j > i)
69 return 0;
71 i -= j;
72 for (j = 0; str[i] != '\0'; i++, j++)
73 if (str[i] != sufx[j])
74 return 0;
75 return 1;
76 }
78 char *
79 absolutify_path(const char *path)
80 {
81 char wd[PATH_MAX], *r;
83 if (*path == '/') {
84 if ((r = strdup(path)) == NULL)
85 fatal("strdup");
86 return r;
87 }
89 if (getcwd(wd, sizeof(wd)) == NULL)
90 fatal("getcwd");
91 if (asprintf(&r, "%s/%s", wd, path) == -1)
92 fatal("asprintf");
93 return r;
94 }
96 char *
97 xstrdup(const char *s)
98 {
99 char *d;
101 if ((d = strdup(s)) == NULL)
102 fatal("strdup");
103 return d;
106 void *
107 xcalloc(size_t nmemb, size_t size)
109 void *d;
111 if ((d = calloc(nmemb, size)) == NULL)
112 fatal("calloc");
113 return d;
116 static EVP_PKEY *
117 rsa_key_create(FILE *f, const char *fname)
119 EVP_PKEY_CTX *ctx = NULL;
120 EVP_PKEY *pkey = NULL;
121 int ret = -1;
123 /* First, create the context and the key. */
125 if ((ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL)) == NULL) {
126 log_warnx("EVP_PKEY_CTX_new_id failed");
127 ssl_error("EVP_PKEY_CTX_new_id");
128 goto done;
130 if (EVP_PKEY_keygen_init(ctx) <= 0) {
131 log_warnx("EVP_PKEY_keygen_init failed");
132 ssl_error("EVP_PKEY_keygen_init");
133 goto done;
135 if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, KBITS) <= 0) {
136 log_warnx("EVP_PKEY_CTX_set_rsa_keygen_bits failed");
137 ssl_error("EVP_PKEY_CTX_set_rsa_keygen_bits");
138 goto done;
140 if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
141 log_warnx("EVP_PKEY_keygen failed");
142 ssl_error("EVP_PKEY_keygen");
143 goto done;
146 /* Serialize the key to the disc. */
147 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL)) {
148 log_warnx("PEM_write_PrivateKey failed");
149 ssl_error("PEM_write_PrivateKey");
150 goto done;
153 ret = 0;
154 done:
155 if (ret == -1) {
156 EVP_PKEY_free(pkey);
157 pkey = NULL;
159 EVP_PKEY_CTX_free(ctx);
160 return pkey;
163 static EVP_PKEY *
164 ec_key_create(FILE *f, const char *fname)
166 EC_KEY *eckey = NULL;
167 EVP_PKEY *pkey = NULL;
168 int ret = -1;
170 if ((eckey = EC_KEY_new_by_curve_name(NID_secp384r1)) == NULL) {
171 log_warnx("EC_KEY_new_by_curve_name failed");
172 ssl_error("EC_KEY_new_by_curve_name");
173 goto done;
176 if (!EC_KEY_generate_key(eckey)) {
177 log_warnx("EC_KEY_generate_key failed");
178 ssl_error("EC_KEY_generate_key");
179 goto done;
182 /* Serialise the key to the disc in EC format */
183 if (!PEM_write_ECPrivateKey(f, eckey, NULL, NULL, 0, NULL, NULL)) {
184 log_warnx("PEM_write_ECPrivateKey failed");
185 ssl_error("PEM_write_ECPrivateKey");
186 goto done;
189 /* Convert the EC key into a PKEY structure */
190 if ((pkey = EVP_PKEY_new()) == NULL) {
191 log_warnx("EVP_PKEY_new failed");
192 ssl_error("EVP_PKEY_new");
193 goto done;
195 if (!EVP_PKEY_set1_EC_KEY(pkey, eckey)) {
196 log_warnx("EVP_PKEY_set1_EC_KEY failed");
197 ssl_error("EVP_PKEY_set1_EC_KEY");
198 goto done;
201 ret = 0;
202 done:
203 if (ret == -1) {
204 EVP_PKEY_free(pkey);
205 pkey = NULL;
206 log_warnx("WOOOPS");
208 EC_KEY_free(eckey);
209 return pkey;
212 void
213 gencert(const char *hostname, const char *certpath, const char *keypath,
214 int eckey)
216 EVP_PKEY *pkey;
217 X509 *x509;
218 X509_NAME *name;
219 FILE *f;
220 const unsigned char *host = (const unsigned char*)hostname;
222 log_info("Generating new %s key for %s (it could take a while)",
223 eckey ? "EC" : "RSA", host);
225 if ((f = fopen(keypath, "w")) == NULL) {
226 log_warn("can't open %s", keypath);
227 goto err;
229 if (eckey)
230 pkey = ec_key_create(f, keypath);
231 else
232 pkey = rsa_key_create(f, keypath);
233 if (pkey == NULL) {
234 log_warnx("failed to generate a private key");
235 goto err;
237 if (fflush(f) == EOF || fclose(f) == EOF) {
238 log_warn("failed to flush or close the private key");
239 goto err;
242 if ((x509 = X509_new()) == NULL) {
243 log_warnx("couldn't generate the X509 certificate");
244 ssl_error("X509_new");
245 goto err;
248 ASN1_INTEGER_set(X509_get_serialNumber(x509), 0);
249 X509_gmtime_adj(X509_get_notBefore(x509), 0);
250 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
251 X509_set_version(x509, 2); /* v3 */
253 if (!X509_set_pubkey(x509, pkey)) {
254 log_warnx("couldn't set the public key");
255 ssl_error("X509_set_pubkey");
256 goto err;
259 if ((name = X509_NAME_new()) == NULL) {
260 log_warnx("X509_NAME_new failed");
261 ssl_error("X509_NAME_new");
262 goto err;
265 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host,
266 -1, -1, 0)) {
267 log_warnx("couldn't add CN to cert");
268 ssl_error("X509_NAME_add_entry_by_txt");
269 goto err;
271 X509_set_subject_name(x509, name);
272 X509_set_issuer_name(x509, name);
274 if (!X509_sign(x509, pkey, EVP_sha256())) {
275 log_warnx("failed to sign the certificate");
276 ssl_error("X509_sign");
277 goto err;
280 if ((f = fopen(certpath, "w")) == NULL) {
281 log_warn("can't open %s", certpath);
282 goto err;
284 if (!PEM_write_X509(f, x509)) {
285 log_warnx("couldn't write cert");
286 ssl_error("PEM_write_X509");
287 goto err;
289 if (fflush(f) == EOF || fclose(f) == EOF) {
290 log_warn("failed to flush or close the private key");
291 goto err;
294 X509_free(x509);
295 EVP_PKEY_free(pkey);
296 log_info("Certificate for %s successfully generated", host);
297 return;
299 err:
300 (void) unlink(certpath);
301 (void) unlink(keypath);
302 exit(1);
305 X509_STORE *
306 load_ca(uint8_t *d, size_t len)
308 BIO *in;
309 X509 *x = NULL;
310 X509_STORE *store;
312 if ((store = X509_STORE_new()) == NULL) {
313 log_warnx("%s: X509_STORE_new failed", __func__);
314 return NULL;
317 if ((in = BIO_new_mem_buf(d, len)) == NULL) {
318 log_warnx("%s: BIO_new_mem_buf failed", __func__);
319 goto err;
322 if ((x = PEM_read_bio_X509(in, NULL, NULL, NULL)) == NULL) {
323 log_warnx("%s: PEM_read_bio_X509 failed", __func__);
324 ssl_error("PEM_read_bio_X509");
325 goto err;
328 if (X509_check_ca(x) == 0) {
329 ssl_error("X509_check_ca");
330 goto err;
333 if (!X509_STORE_add_cert(store, x)) {
334 ssl_error("X509_STORE_add_cert");
335 goto err;
338 X509_free(x);
339 BIO_free(in);
340 return store;
342 err:
343 X509_STORE_free(store);
344 if (x != NULL)
345 X509_free(x);
346 if (in != NULL)
347 BIO_free(in);
348 return NULL;
351 int
352 validate_against_ca(X509_STORE *ca, const uint8_t *chain, size_t len)
354 X509 *client;
355 BIO *m;
356 X509_STORE_CTX *ctx = NULL;
357 int ret = 0;
359 if ((m = BIO_new_mem_buf(chain, len)) == NULL)
360 return 0;
362 if ((client = PEM_read_bio_X509(m, NULL, NULL, NULL)) == NULL)
363 goto end;
365 if ((ctx = X509_STORE_CTX_new()) == NULL)
366 goto end;
368 if (!X509_STORE_CTX_init(ctx, ca, client, NULL))
369 goto end;
371 ret = X509_verify_cert(ctx);
373 end:
374 BIO_free(m);
375 if (client != NULL)
376 X509_free(client);
377 if (ctx != NULL)
378 X509_STORE_CTX_free(ctx);
379 return ret;
382 void
383 ssl_error(const char *where)
385 unsigned long code;
386 char errbuf[128];
388 while ((code = ERR_get_error()) != 0) {
389 ERR_error_string_n(code, errbuf, sizeof(errbuf));
390 log_debug("debug: SSL library error: %s: %s", where, errbuf);
394 char *
395 ssl_pubkey_hash(const uint8_t *buf, size_t len)
397 static const char hex[] = "0123456789abcdef";
398 BIO *in;
399 X509 *x509 = NULL;
400 char *hash = NULL;
401 size_t off;
402 unsigned char digest[EVP_MAX_MD_SIZE];
403 unsigned int dlen, i;
405 if ((in = BIO_new_mem_buf(buf, len)) == NULL) {
406 log_warnx("%s: BIO_new_mem_buf failed", __func__);
407 return NULL;
410 if ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL)) == NULL) {
411 log_warnx("%s: PEM_read_bio_X509 failed", __func__);
412 ssl_error("PEM_read_bio_X509");
413 goto fail;
416 if ((hash = malloc(TLS_CERT_HASH_SIZE)) == NULL) {
417 log_warn("%s: malloc", __func__);
418 goto fail;
421 if (X509_pubkey_digest(x509, EVP_sha256(), digest, &dlen) != 1) {
422 log_warnx("%s: X509_pubkey_digest failed", __func__);
423 ssl_error("X509_pubkey_digest");
424 free(hash);
425 hash = NULL;
426 goto fail;
429 if (TLS_CERT_HASH_SIZE < 2 * dlen + sizeof("SHA256:"))
430 fatalx("%s: hash buffer too small", __func__);
432 off = strlcpy(hash, "SHA256:", TLS_CERT_HASH_SIZE);
433 for (i = 0; i < dlen; ++i) {
434 hash[off++] = hex[(digest[i] >> 4) & 0xf];
435 hash[off++] = hex[digest[i] & 0xf];
437 hash[off] = '\0';
439 fail:
440 BIO_free(in);
441 if (x509)
442 X509_free(x509);
443 return hash;
446 EVP_PKEY *
447 ssl_load_pkey(const uint8_t *buf, size_t len)
449 BIO *in;
450 EVP_PKEY *pkey;
452 if ((in = BIO_new_mem_buf(buf, len)) == NULL) {
453 log_warnx("%s: BIO_new_mem_buf failed", __func__);
454 return NULL;
457 if ((pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL)) == NULL) {
458 log_warnx("%s: PEM_read_bio_PrivateKey failed", __func__);
459 ssl_error("PEM_read_bio_PrivateKey");
462 BIO_free(in);
463 return pkey;
466 struct vhost *
467 new_vhost(void)
469 struct vhost *h;
471 h = xcalloc(1, sizeof(*h));
472 TAILQ_INIT(&h->addrs);
473 TAILQ_INIT(&h->locations);
474 TAILQ_INIT(&h->aliases);
475 TAILQ_INIT(&h->proxies);
476 return h;
479 struct location *
480 new_location(void)
482 struct location *l;
484 l = xcalloc(1, sizeof(*l));
485 l->dirfd = -1;
486 l->fcgi = -1;
487 TAILQ_INIT(&l->params);
488 return l;
491 struct proxy *
492 new_proxy(void)
494 struct proxy *p;
496 p = xcalloc(1, sizeof(*p));
497 p->protocols = TLS_PROTOCOLS_DEFAULT;
498 return p;