xref: /openbsd-src/usr.sbin/acme-client/revokeproc.c (revision 5a38ef86d0b61900239c7913d24a05e7b88a58f0)
1 /*	$Id: revokeproc.c,v 1.19 2021/11/22 08:26:08 tb Exp $ */
2 /*
3  * Copyright (c) 2016 Kristaps Dzonsons <kristaps@bsd.lv>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <assert.h>
19 #include <ctype.h>
20 #include <err.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 
27 #include <openssl/pem.h>
28 #include <openssl/x509.h>
29 #include <openssl/x509v3.h>
30 #include <openssl/err.h>
31 
32 #include "extern.h"
33 
34 #define	RENEW_ALLOW (30 * 24 * 60 * 60)
35 
36 /*
37  * Convert the X509's expiration time (which is in ASN1_TIME format)
38  * into a time_t value.
39  * There are lots of suggestions on the Internet on how to do this and
40  * they're really, really unsafe.
41  * Adapt those poor solutions to a safe one.
42  */
43 static time_t
44 X509expires(X509 *x)
45 {
46 	ASN1_TIME	*atim;
47 	struct tm	 t;
48 	unsigned char	*str;
49 	size_t		 i = 0;
50 
51 	atim = X509_get_notAfter(x);
52 	str = atim->data;
53 	memset(&t, 0, sizeof(t));
54 
55 	/* Account for 2 and 4-digit time. */
56 
57 	if (atim->type == V_ASN1_UTCTIME) {
58 		if (atim->length <= 2) {
59 			warnx("invalid ASN1_TIME");
60 			return (time_t)-1;
61 		}
62 		t.tm_year = (str[0] - '0') * 10 + (str[1] - '0');
63 		if (t.tm_year < 70)
64 			t.tm_year += 100;
65 		i = 2;
66 	} else if (atim->type == V_ASN1_GENERALIZEDTIME) {
67 		if (atim->length <= 4) {
68 			warnx("invalid ASN1_TIME");
69 			return (time_t)-1;
70 		}
71 		t.tm_year = (str[0] - '0') * 1000 + (str[1] - '0') * 100 +
72 		    (str[2] - '0') * 10 + (str[3] - '0');
73 		t.tm_year -= 1900;
74 		i = 4;
75 	}
76 
77 	/* Now the post-year parts. */
78 
79 	if (atim->length <= (int)i + 10) {
80 		warnx("invalid ASN1_TIME");
81 		return (time_t)-1;
82 	}
83 
84 	t.tm_mon = ((str[i + 0] - '0') * 10 + (str[i + 1] - '0')) - 1;
85 	t.tm_mday = (str[i + 2] - '0') * 10 + (str[i + 3] - '0');
86 	t.tm_hour = (str[i + 4] - '0') * 10 + (str[i + 5] - '0');
87 	t.tm_min  = (str[i + 6] - '0') * 10 + (str[i + 7] - '0');
88 	t.tm_sec  = (str[i + 8] - '0') * 10 + (str[i + 9] - '0');
89 
90 	return mktime(&t);
91 }
92 
93 int
94 revokeproc(int fd, const char *certfile, int force,
95     int revocate, const char *const *alts, size_t altsz)
96 {
97 	char				*der = NULL, *dercp, *der64 = NULL;
98 	char				*san = NULL, *str, *tok;
99 	int				 rc = 0, cc, i, ssz, len;
100 	size_t				*found = NULL;
101 	BIO				*bio = NULL;
102 	FILE				*f = NULL;
103 	X509				*x = NULL;
104 	long				 lval;
105 	enum revokeop			 op, rop;
106 	time_t				 t;
107 	const STACK_OF(X509_EXTENSION)	*exts;
108 	X509_EXTENSION			*ex;
109 	ASN1_OBJECT			*obj;
110 	size_t				 j;
111 
112 	/*
113 	 * First try to open the certificate before we drop privileges
114 	 * and jail ourselves.
115 	 * We allow "f" to be NULL IFF the cert doesn't exist yet.
116 	 */
117 
118 	if ((f = fopen(certfile, "r")) == NULL && errno != ENOENT) {
119 		warn("%s", certfile);
120 		goto out;
121 	}
122 
123 	/* File-system and sandbox jailing. */
124 
125 	ERR_load_crypto_strings();
126 
127 	if (pledge("stdio", NULL) == -1) {
128 		warn("pledge");
129 		goto out;
130 	}
131 
132 	/*
133 	 * If we couldn't open the certificate, it doesn't exist so we
134 	 * haven't submitted it yet, so obviously we can mark that it
135 	 * has expired and we should renew it.
136 	 * If we're revoking, however, then that's an error!
137 	 * Ignore if the reader isn't reading in either case.
138 	 */
139 
140 	if (f == NULL && revocate) {
141 		warnx("%s: no certificate found", certfile);
142 		(void)writeop(fd, COMM_REVOKE_RESP, REVOKE_OK);
143 		goto out;
144 	} else if (f == NULL && !revocate) {
145 		if (writeop(fd, COMM_REVOKE_RESP, REVOKE_EXP) >= 0)
146 			rc = 1;
147 		goto out;
148 	}
149 
150 	if ((x = PEM_read_X509(f, NULL, NULL, NULL)) == NULL) {
151 		warnx("PEM_read_X509");
152 		goto out;
153 	}
154 
155 	/* Read out the expiration date. */
156 
157 	if ((t = X509expires(x)) == (time_t)-1) {
158 		warnx("X509expires");
159 		goto out;
160 	}
161 
162 	/*
163 	 * Next, the long process to make sure that the SAN entries
164 	 * listed with the certificate fully cover those passed on the
165 	 * command line.
166 	 */
167 
168 	exts = X509_get0_extensions(x);
169 
170 	/* Scan til we find the SAN NID. */
171 
172 	for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
173 		ex = sk_X509_EXTENSION_value(exts, i);
174 		assert(ex != NULL);
175 		obj = X509_EXTENSION_get_object(ex);
176 		assert(obj != NULL);
177 		if (NID_subject_alt_name != OBJ_obj2nid(obj))
178 			continue;
179 
180 		if (san != NULL) {
181 			warnx("%s: two SAN entries", certfile);
182 			goto out;
183 		}
184 
185 		bio = BIO_new(BIO_s_mem());
186 		if (bio == NULL) {
187 			warnx("BIO_new");
188 			goto out;
189 		}
190 		if (!X509V3_EXT_print(bio, ex, 0, 0)) {
191 			warnx("X509V3_EXT_print");
192 			goto out;
193 		}
194 		if ((san = calloc(1, BIO_number_written(bio) + 1)) == NULL) {
195 			warn("calloc");
196 			goto out;
197 		}
198 		ssz = BIO_read(bio, san, BIO_number_written(bio));
199 		if (ssz < 0 || (unsigned)ssz != BIO_number_written(bio)) {
200 			warnx("BIO_read");
201 			goto out;
202 		}
203 	}
204 
205 	if (san == NULL) {
206 		warnx("%s: does not have a SAN entry", certfile);
207 		if (revocate)
208 			goto out;
209 		force = 2;
210 	}
211 
212 	/* An array of buckets: the number of entries found. */
213 
214 	if ((found = calloc(altsz, sizeof(size_t))) == NULL) {
215 		warn("calloc");
216 		goto out;
217 	}
218 
219 	/*
220 	 * Parse the SAN line.
221 	 * Make sure that all of the domains are represented only once.
222 	 */
223 
224 	str = san;
225 	while ((tok = strsep(&str, ",")) != NULL) {
226 		if (*tok == '\0')
227 			continue;
228 		while (isspace((int)*tok))
229 			tok++;
230 		if (strncmp(tok, "DNS:", 4))
231 			continue;
232 		tok += 4;
233 		for (j = 0; j < altsz; j++)
234 			if (strcmp(tok, alts[j]) == 0)
235 				break;
236 		if (j == altsz) {
237 			if (revocate) {
238 				warnx("%s: unknown SAN entry: %s", certfile, tok);
239 				goto out;
240 			}
241 			force = 2;
242 		}
243 		if (found[j]++) {
244 			if (revocate) {
245 				warnx("%s: duplicate SAN entry: %s", certfile, tok);
246 				goto out;
247 			}
248 			force = 2;
249 		}
250 	}
251 
252 	for (j = 0; j < altsz; j++) {
253 		if (found[j])
254 			continue;
255 		if (revocate) {
256 			warnx("%s: domain not listed: %s", certfile, alts[j]);
257 			goto out;
258 		}
259 		force = 2;
260 	}
261 
262 	/*
263 	 * If we're going to revoke, write the certificate to the
264 	 * netproc in DER and base64-encoded format.
265 	 * Then exit: we have nothing left to do.
266 	 */
267 
268 	if (revocate) {
269 		dodbg("%s: revocation", certfile);
270 
271 		/*
272 		 * First, tell netproc we're online.
273 		 * If they're down, then just exit without warning.
274 		 */
275 
276 		cc = writeop(fd, COMM_REVOKE_RESP, REVOKE_EXP);
277 		if (cc == 0)
278 			rc = 1;
279 		if (cc <= 0)
280 			goto out;
281 
282 		if ((len = i2d_X509(x, NULL)) < 0) {
283 			warnx("i2d_X509");
284 			goto out;
285 		} else if ((der = dercp = malloc(len)) == NULL) {
286 			warn("malloc");
287 			goto out;
288 		} else if (len != i2d_X509(x, (u_char **)&dercp)) {
289 			warnx("i2d_X509");
290 			goto out;
291 		} else if ((der64 = base64buf_url(der, len)) == NULL) {
292 			warnx("base64buf_url");
293 			goto out;
294 		} else if (writestr(fd, COMM_CSR, der64) >= 0)
295 			rc = 1;
296 
297 		goto out;
298 	}
299 
300 	rop = time(NULL) >= (t - RENEW_ALLOW) ? REVOKE_EXP : REVOKE_OK;
301 
302 	if (rop == REVOKE_EXP)
303 		dodbg("%s: certificate renewable: %lld days left",
304 		    certfile, (long long)(t - time(NULL)) / 24 / 60 / 60);
305 	else
306 		dodbg("%s: certificate valid: %lld days left",
307 		    certfile, (long long)(t - time(NULL)) / 24 / 60 / 60);
308 
309 	if (rop == REVOKE_OK && force) {
310 		warnx("%s: %sforcing renewal", certfile,
311 		    force == 2 ? "domain list changed, " : "");
312 		rop = REVOKE_EXP;
313 	}
314 
315 	/*
316 	 * We can re-submit it given RENEW_ALLOW time before.
317 	 * If netproc is down, just exit.
318 	 */
319 
320 	if ((cc = writeop(fd, COMM_REVOKE_RESP, rop)) == 0)
321 		rc = 1;
322 	if (cc <= 0)
323 		goto out;
324 
325 	op = REVOKE__MAX;
326 	if ((lval = readop(fd, COMM_REVOKE_OP)) == 0)
327 		op = REVOKE_STOP;
328 	else if (lval == REVOKE_CHECK)
329 		op = lval;
330 
331 	if (op == REVOKE__MAX) {
332 		warnx("unknown operation from netproc");
333 		goto out;
334 	} else if (op == REVOKE_STOP) {
335 		rc = 1;
336 		goto out;
337 	}
338 
339 	rc = 1;
340 out:
341 	close(fd);
342 	if (f != NULL)
343 		fclose(f);
344 	X509_free(x);
345 	BIO_free(bio);
346 	free(san);
347 	free(der);
348 	free(found);
349 	free(der64);
350 	ERR_print_errors_fp(stderr);
351 	ERR_free_strings();
352 	return rc;
353 }
354