Blob


1 /*
2 * Copyright (c) 2021, 2023 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
4 * Copyright (c) 2008 Reyk Floeter <reyk@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include "gmid.h"
21 #include <errno.h>
22 #include <string.h>
24 #include <openssl/bn.h>
25 #include <openssl/err.h>
26 #include <openssl/pem.h>
27 #include <openssl/x509_vfy.h>
28 #include <openssl/x509v3.h>
30 #include "log.h"
32 const char *
33 strip_path(const char *path, int strip)
34 {
35 char *t;
37 while (strip > 0) {
38 if ((t = strchr(path, '/')) == NULL) {
39 path = strchr(path, '\0');
40 break;
41 }
42 path = t;
43 strip--;
44 }
46 return path;
47 }
49 int
50 starts_with(const char *str, const char *prefix)
51 {
52 size_t i;
54 if (prefix == NULL)
55 return 0;
57 for (i = 0; prefix[i] != '\0'; ++i)
58 if (str[i] != prefix[i])
59 return 0;
60 return 1;
61 }
63 int
64 ends_with(const char *str, const char *sufx)
65 {
66 size_t i, j;
68 i = strlen(str);
69 j = strlen(sufx);
71 if (j > i)
72 return 0;
74 i -= j;
75 for (j = 0; str[i] != '\0'; i++, j++)
76 if (str[i] != sufx[j])
77 return 0;
78 return 1;
79 }
81 ssize_t
82 filesize(int fd)
83 {
84 ssize_t len;
86 if ((len = lseek(fd, 0, SEEK_END)) == -1)
87 return -1;
88 if (lseek(fd, 0, SEEK_SET) == -1)
89 return -1;
90 return len;
91 }
93 char *
94 absolutify_path(const char *path)
95 {
96 char *wd, *r;
98 if (*path == '/') {
99 if ((r = strdup(path)) == NULL)
100 fatal("strdup");
101 return r;
104 wd = getcwd(NULL, 0);
105 if (asprintf(&r, "%s/%s", wd, path) == -1)
106 fatal("asprintf");
107 free(wd);
108 return r;
111 char *
112 xstrdup(const char *s)
114 char *d;
116 if ((d = strdup(s)) == NULL)
117 fatal("strdup");
118 return d;
121 void *
122 xcalloc(size_t nmemb, size_t size)
124 void *d;
126 if ((d = calloc(nmemb, size)) == NULL)
127 fatal("calloc");
128 return d;
131 void
132 gen_certificate(const char *hostname, const char *certpath, const char *keypath)
134 BIGNUM *e;
135 EVP_PKEY *pkey;
136 RSA *rsa;
137 X509 *x509;
138 X509_NAME *name;
139 FILE *f;
140 const unsigned char *host = (const unsigned char*)hostname;
142 log_info("generating new certificate for %s (it could take a while)",
143 host);
145 if ((pkey = EVP_PKEY_new()) == NULL)
146 fatalx("couldn't create a new private key");
148 if ((rsa = RSA_new()) == NULL)
149 fatalx("couldn't generate rsa");
151 if ((e = BN_new()) == NULL)
152 fatalx("couldn't allocate a bignum");
154 BN_set_word(e, RSA_F4);
155 if (!RSA_generate_key_ex(rsa, 4096, e, NULL))
156 fatalx("couldn't generate a rsa key");
158 if (!EVP_PKEY_assign_RSA(pkey, rsa))
159 fatalx("couldn't assign the key");
161 if ((x509 = X509_new()) == NULL)
162 fatalx("couldn't generate the X509 certificate");
164 ASN1_INTEGER_set(X509_get_serialNumber(x509), 0);
165 X509_gmtime_adj(X509_get_notBefore(x509), 0);
166 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
167 X509_set_version(x509, 3);
169 if (!X509_set_pubkey(x509, pkey))
170 fatalx("couldn't set the public key");
172 name = X509_get_subject_name(x509);
173 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
174 fatalx("couldn't add CN to cert");
175 X509_set_issuer_name(x509, name);
177 if (!X509_sign(x509, pkey, EVP_sha256()))
178 fatalx("couldn't sign the certificate");
180 if ((f = fopen(keypath, "w")) == NULL)
181 fatal("can't open %s", keypath);
182 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
183 fatalx("couldn't write private key");
184 fclose(f);
186 if ((f = fopen(certpath, "w")) == NULL)
187 fatal("can't open %s", certpath);
188 if (!PEM_write_X509(f, x509))
189 fatalx("couldn't write cert");
190 fclose(f);
192 BN_free(e);
193 X509_free(x509);
194 RSA_free(rsa);
196 log_info("certificate successfully generated");
199 X509_STORE *
200 load_ca(uint8_t *d, size_t len)
202 BIO *in;
203 X509 *x = NULL;
204 X509_STORE *store;
206 if ((store = X509_STORE_new()) == NULL) {
207 log_warnx("%s: X509_STORE_new failed", __func__);
208 return NULL;
211 if ((in = BIO_new_mem_buf(d, len)) == NULL) {
212 log_warnx("%s: BIO_new_mem_buf failed", __func__);
213 goto err;
216 if ((x = PEM_read_bio_X509(in, NULL, NULL, NULL)) == NULL) {
217 log_warnx("%s: PEM_read_bio_X509 failed", __func__);
218 ssl_error("PEM_read_bio_X509");
219 goto err;
222 if (X509_check_ca(x) == 0) {
223 ssl_error("X509_check_ca");
224 goto err;
227 if (!X509_STORE_add_cert(store, x)) {
228 ssl_error("X509_STORE_add_cert");
229 goto err;
232 X509_free(x);
233 BIO_free(in);
234 return store;
236 err:
237 X509_STORE_free(store);
238 if (x != NULL)
239 X509_free(x);
240 if (in != NULL)
241 BIO_free(in);
242 return NULL;
245 int
246 validate_against_ca(X509_STORE *ca, const uint8_t *chain, size_t len)
248 X509 *client;
249 BIO *m;
250 X509_STORE_CTX *ctx = NULL;
251 int ret = 0;
253 if ((m = BIO_new_mem_buf(chain, len)) == NULL)
254 return 0;
256 if ((client = PEM_read_bio_X509(m, NULL, NULL, NULL)) == NULL)
257 goto end;
259 if ((ctx = X509_STORE_CTX_new()) == NULL)
260 goto end;
262 if (!X509_STORE_CTX_init(ctx, ca, client, NULL))
263 goto end;
265 ret = X509_verify_cert(ctx);
267 end:
268 BIO_free(m);
269 if (client != NULL)
270 X509_free(client);
271 if (ctx != NULL)
272 X509_STORE_CTX_free(ctx);
273 return ret;
276 void
277 ssl_error(const char *where)
279 unsigned long code;
280 char errbuf[128];
282 while ((code = ERR_get_error()) != 0) {
283 ERR_error_string_n(code, errbuf, sizeof(errbuf));
284 log_debug("debug: SSL library error: %s: %s", where, errbuf);
288 char *
289 ssl_pubkey_hash(const uint8_t *buf, size_t len)
291 static const char hex[] = "0123456789abcdef";
292 BIO *in;
293 X509 *x509 = NULL;
294 char *hash = NULL;
295 size_t off;
296 unsigned char digest[EVP_MAX_MD_SIZE];
297 unsigned int dlen, i;
299 if ((in = BIO_new_mem_buf(buf, len)) == NULL) {
300 log_warnx("%s: BIO_new_mem_buf failed", __func__);
301 return NULL;
304 if ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL)) == NULL) {
305 log_warnx("%s: PEM_read_bio_X509 failed", __func__);
306 ssl_error("PEM_read_bio_X509");
307 goto fail;
310 if ((hash = malloc(TLS_CERT_HASH_SIZE)) == NULL) {
311 log_warn("%s: malloc", __func__);
312 goto fail;
315 if (X509_pubkey_digest(x509, EVP_sha256(), digest, &dlen) != 1) {
316 log_warnx("%s: X509_pubkey_digest failed", __func__);
317 ssl_error("X509_pubkey_digest");
318 free(hash);
319 hash = NULL;
320 goto fail;
323 if (TLS_CERT_HASH_SIZE < 2 * dlen + sizeof("SHA256:"))
324 fatalx("%s: hash buffer too small", __func__);
326 off = strlcpy(hash, "SHA256:", TLS_CERT_HASH_SIZE);
327 for (i = 0; i < dlen; ++i) {
328 hash[off++] = hex[(digest[i] >> 4) & 0xf];
329 hash[off++] = hex[digest[i] & 0xf];
331 hash[off] = '\0';
333 fail:
334 BIO_free(in);
335 if (x509)
336 X509_free(x509);
337 return hash;
340 EVP_PKEY *
341 ssl_load_pkey(const uint8_t *buf, size_t len)
343 BIO *in;
344 EVP_PKEY *pkey;
346 if ((in = BIO_new_mem_buf(buf, len)) == NULL) {
347 log_warnx("%s: BIO_new_mem_buf failed", __func__);
348 return NULL;
351 if ((pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL)) == NULL) {
352 log_warnx("%s: PEM_read_bio_PrivateKey failed", __func__);
353 ssl_error("PEM_read_bio_PrivateKey");
356 BIO_free(in);
357 return pkey;
360 struct vhost *
361 new_vhost(void)
363 struct vhost *h;
365 h = xcalloc(1, sizeof(*h));
366 TAILQ_INIT(&h->addrs);
367 TAILQ_INIT(&h->locations);
368 TAILQ_INIT(&h->aliases);
369 TAILQ_INIT(&h->proxies);
370 return h;
373 struct location *
374 new_location(void)
376 struct location *l;
378 l = xcalloc(1, sizeof(*l));
379 l->dirfd = -1;
380 l->fcgi = -1;
381 TAILQ_INIT(&l->params);
382 return l;
385 struct proxy *
386 new_proxy(void)
388 struct proxy *p;
390 p = xcalloc(1, sizeof(*p));
391 p->protocols = TLS_PROTOCOLS_DEFAULT;
392 return p;