Debian Codegraph @

src/tls/cockpit-certificate-ensure.c

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 #include <gnutls/gnutls.h>
9 #include <gnutls/x509.h>
10 #include <assert.h>
11 #include <err.h>
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <spawn.h>
15 #include <stdbool.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/stat.h>
19 #include <sys/wait.h>
20 #include <unistd.h>
21
22 #include <common/cockpitwebcertificate.h>
23 #include <common/cockpitmemory.h>
24
25 #include "utils.h"
26
27 #define COCKPIT_CERTIFICATE_HELPER LIBEXECDIR "/cockpit-certificate-helper"
28
29 // Cross-reference with cockpit-certificate-helper.in
30 #define COCKPIT_SELFSIGNED_FILENAME "/cockpit/ws-certs.d/0-self-signed.cert"
31 #define COCKPIT_SELFSIGNED_PATH PACKAGE_SYSCONF_DIR COCKPIT_SELFSIGNED_FILENAME
32
33 // Renew certificates with less than 30 days validity
34 #define EXPIRY_THRESHOLD (30 * 24 * 60 * 60)
35
36 // We used to issue 100 year certificates, but browsers no longer accept
37 // those. Make sure we reissue those as well: anything with an expiry
38 // of more than ~5 years from now was surely generated by the old code.
39 #define MAX_EXPIRY (5 * 365 * 24 * 60 * 60)
40
41 // We tolerate the deprecated merged cert/key files only for cockpit-tls.
42 static bool tolerate_merged_cert_key;
43
44 typedef struct
45 {
46 char *certificate_filename;
47 gnutls_datum_t certificate;
48 char *key_filename;
49 gnutls_datum_t key;
50
51 char *filename_for_errors;
52 } CertificateKeyPair;
53
54 static void
55 read_file (const char *filename,
56 gnutls_datum_t *result)
57 {
58 int fd = open (filename, O_RDONLY);
59 if (fd == -1)
60 err (EXIT_FAILURE, "open: %s", filename);
61
62 struct stat buf;
63 if (fstat (fd, &buf) != 0)
64 err (EXIT_FAILURE, "fstat: %s", filename);
65
66 if (!S_ISREG (buf.st_mode))
67 errx (EXIT_FAILURE, "%s: not a regular file", filename);
68
69 result->size = buf.st_size;
70 result->data = mallocx (result->size + 1);
71
72 ssize_t s = read (fd, result->data, result->size);
73 if (s == -1)
74 err (EXIT_FAILURE, "read: %s", filename);
75 if (s != result->size)
76 errx (EXIT_FAILURE, "read: %s: got %zu bytes, expecting %zu",
77 filename, s, (size_t) result->size);
78
79 result->data[s] = '\0';
80
81 close (fd);
82 }
83
84 static void
85 write_file (int dirfd,
86 const char *dirfd_filename,
87 const char *filename,
88 const gnutls_datum_t *data,
89 uid_t uid,
90 gid_t gid)
91 {
92 /* Just open the file directly: it doesn't exist yet and nobody will
93 * look at it until after we're done here.
94 */
95 int fd = openat (dirfd, filename, O_CREAT | O_EXCL | O_WRONLY, 0400);
96
97 if (fd == -1)
98 err (EXIT_FAILURE, "%s/%s: creat", dirfd_filename, filename);
99
100 size_t s = write (fd, data->data, data->size);
101 if (s == -1)
102 err (EXIT_FAILURE, "%s/%s: write", dirfd_filename, filename);
103 if (s != data->size)
104 errx (EXIT_FAILURE, "%s/%s: write: wrote %zu bytes, expecting %zu",
105 dirfd_filename, filename, s, (size_t) data->size);
106
107 /* This is actually making the file more accessible, to do it last */
108 if (fchown (fd, uid, gid) != 0)
109 err (EXIT_FAILURE, "%s/%s: fchown", dirfd_filename, filename);
110
111 close (fd);
112 }
113
114 static bool
115 is_selfsigned (const char *certificate_filename)
116 {
117 return strstr (certificate_filename, COCKPIT_SELFSIGNED_FILENAME) != NULL;
118 }
119
120 static bool
121 check_expiry (gnutls_certificate_credentials_t creds,
122 const char *certificate_filename)
123 {
124 gnutls_x509_crt_t *crt_list;
125 unsigned int crt_list_size;
126
127 int ret = gnutls_certificate_get_x509_crt (creds, 0, &crt_list, &crt_list_size);
128 assert (ret == GNUTLS_E_SUCCESS);
129
130 if (crt_list_size != 1)
131 errx (EXIT_FAILURE, "unable to check expiry of chained certificates");
132
133 time_t expires = gnutls_x509_crt_get_expiration_time (crt_list[0]);
134 gnutls_x509_crt_deinit (crt_list[0]);
135 gnutls_free (crt_list);
136
137 debug (ENSURE, "Certificate %s expires %ld", certificate_filename, (long) expires);
138
139 time_t now = time (NULL);
140 if (expires > now + MAX_EXPIRY)
141 {
142 debug (ENSURE, "Certificate %s expires %ld, too far in the future",
143 certificate_filename, (long) expires);
144
145 return true;
146 }
147
148 time_t last_valid_expiry = now + EXPIRY_THRESHOLD;
149 if (expires < last_valid_expiry)
150 {
151 debug (ENSURE, "Certificate %s expires %ld, which is before %ld",
152 certificate_filename, (long) expires, (long) last_valid_expiry);
153
154 return true;
155 }
156
157 debug (ENSURE, "Certificate %s expires %ld, which is after %ld",
158 certificate_filename, (long) expires, (long) last_valid_expiry);
159
160 return false;
161 }
162
163 static void
164 certificate_and_key_clear (CertificateKeyPair *self)
165 {
166 /* gnutls_datum_free is side-effecting and sets ->data = NULL */
167 free (self->certificate.data);
168 self->certificate.data = NULL;
169 self->certificate.size = 0;
170
171 free (self->certificate_filename);
172 self->certificate_filename = NULL;
173
174 free (self->key.data);
175 self->key.data = NULL;
176 self->key.size = 0;
177
178 free (self->key_filename);
179 self->key_filename = NULL;
180
181 free (self->filename_for_errors);
182 self->filename_for_errors = NULL;
183 }
184
185 static void
186 certificate_and_key_write (const CertificateKeyPair *self,
187 const char *directory)
188 {
189 int dirfd = open (directory, O_PATH | O_DIRECTORY | O_NOFOLLOW);
190 if (dirfd == -1)
191 err (EXIT_FAILURE, "open: %s", directory);
192
193 struct stat buf;
194 if (fstat (dirfd, &buf) != 0)
195 err (EXIT_FAILURE, "fstat: %s", directory);
196
197 int r = mkdirat (dirfd, "server", 0700);
198 if (r != 0)
199 err (EXIT_FAILURE, "mkdir: %s/%s", directory, "server");
200
201 /* fchown() won't accept file descriptors opened O_PATH */
202 int fd = openat (dirfd, "server", O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
203 if (fd == -1)
204 err (EXIT_FAILURE, "open: %s", directory);
205
206 /* Copy the owner/group from the parent directory */
207 if (fchown (fd, buf.st_uid, buf.st_gid) != 0)
208 err (EXIT_FAILURE, "%s: fchown", directory);
209
210 if (symlinkat (self->certificate_filename, fd, "0.crt.source") != 0)
211 err (EXIT_FAILURE, "%s/%s: symlinkat", directory, "0.crt.source");
212
213 if (symlinkat (self->key_filename, fd, "0.key.source") != 0)
214 err (EXIT_FAILURE, "%s/%s: symlinkat", directory, "0.key.source");
215
216 write_file (fd, directory, "0.crt", &self->certificate, buf.st_uid, buf.st_gid);
217
218 write_file (fd, directory, "0.key", &self->key, buf.st_uid, buf.st_gid);
219
220 close (dirfd);
221 close (fd);
222 }
223
224 static bool
225 certificate_and_key_split (CertificateKeyPair *self)
226 {
227 const char *pairs[][2] = {
228 { "-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----" },
229 /* this is slightly asymmetrical -- parameters and private key occur in the same file */
230 { "-----BEGIN EC PARAMETERS-----", "-----END EC PRIVATE KEY-----" },
231 { "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----" },
232 };
233
234 for (int i = 0; i < N_ELEMENTS (pairs); i++)
235 {
236 assert (self->certificate.data[self->certificate.size] == '\0');
237 char *start = strstr ((char *) self->certificate.data, pairs[i][0]);
238
239 if (!start)
240 continue;
241
242 /* NB: certificate.data is `unsigned char *` */
243 char *end = strstr ((char *) self->certificate.data, pairs[i][1]);
244 if (!end)
245 errx (EXIT_FAILURE, "%s: found '%s' but not '%s'",
246 self->certificate_filename, pairs[i][0], pairs[i][1]);
247
248 /* Consume the footer and any extra newlines */
249 end += strlen (pairs[i][1]);
250 while (*end == '\r' || *end == '\n')
251 end++;
252
253 /* Cut out the private key */
254 self->key.data = (unsigned char *) strndupx (start, end - start);
255 self->key.size = end - start;
256
257 /* Everything else before and after is the public key */
258 memmove (start, end, strlen (end) + 1);
259 self->certificate.size -= end - start;
260
261 return true;
262 }
263
264 return false;
265 }
266
267 static void
268 certificate_and_key_read (CertificateKeyPair *self,
269 const char *certificate_filename)
270 {
271 self->certificate_filename = strdupx (certificate_filename);
272 read_file (self->certificate_filename, &self->certificate);
273
274 if (certificate_and_key_split (self))
275 {
276 self->key_filename = strdupx (self->certificate_filename);
277 warnx ("%s: merged certificate and key files are %s. "
278 "Please use a separate .cert and .key file.\n",
279 certificate_filename,
280 tolerate_merged_cert_key ? "deprecated" : "unsupported");
281
282 if (!tolerate_merged_cert_key)
283 exit (EXIT_FAILURE);
284 }
285 else
286 {
287 self->key_filename = cockpit_certificate_key_path (self->certificate_filename);
288 read_file (self->key_filename, &self->key);
289 }
290
291 if (self->key_filename)
292 asprintfx (&self->filename_for_errors, "%s/.key", self->certificate_filename);
293 else
294 self->filename_for_errors = strdupx (self->certificate_filename);
295 }
296
297 static gnutls_certificate_credentials_t
298 certificate_and_key_parse_to_creds (CertificateKeyPair *self)
299 {
300 gnutls_certificate_credentials_t creds = NULL;
301
302 int r = gnutls_certificate_allocate_credentials (&creds);
303 assert (r == GNUTLS_E_SUCCESS);
304
305 r = gnutls_certificate_set_x509_key_mem (creds,
306 &self->certificate, &self->key,
307 GNUTLS_X509_FMT_PEM);
308
309 if (r != GNUTLS_E_SUCCESS)
310 errx (EXIT_FAILURE, "%s: %s", self->filename_for_errors, gnutls_strerror (r));
311
312 return creds;
313 }
314
315 static bool
316 cockpit_certificate_find (CertificateKeyPair *result,
317 bool verbose)
318 {
319 char *error = NULL;
320 char *certificate_filename = cockpit_certificate_locate (true, &error);
321
322 if (error != NULL)
323 errx (EXIT_FAILURE, "%s", error);
324
325 if (certificate_filename == NULL)
326 {
327 if (verbose)
328 printf ("Unable to find any certificate file\n");
329
330 return false;
331 }
332
333 certificate_and_key_read (result, certificate_filename);
334
335 gnutls_certificate_credentials_t creds = certificate_and_key_parse_to_creds (result);
336
337 bool expired = is_selfsigned (certificate_filename) && check_expiry (creds, certificate_filename);
338 if (expired)
339 {
340 if (verbose)
341 printf ("Found self-signed %s, but it needs to be reissued\n",
342 result->filename_for_errors);
343
344 certificate_and_key_clear (result);
345 }
346
347 gnutls_certificate_free_credentials (creds);
348 free (certificate_filename);
349
350 return !expired;
351 }
352
353 static void
354 cockpit_certificate_selfsign (CertificateKeyPair *result)
355 {
356 pid_t pid;
357 int r = posix_spawn (&pid, COCKPIT_CERTIFICATE_HELPER, NULL, NULL,
358 (char *[]){ COCKPIT_CERTIFICATE_HELPER, "selfsign", NULL },
359 NULL);
360
361 if (r != 0)
362 errx (EXIT_FAILURE, "posix_spawn: %s: %s",
363 COCKPIT_CERTIFICATE_HELPER, strerror (r));
364
365 int status;
366 do
367 r = waitpid (pid, &status, 0);
368 while (r == -1 && errno == EINTR);
369
370 if (r < 0)
371 err (EXIT_FAILURE, "wait: %s", COCKPIT_CERTIFICATE_HELPER);
372
373 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0)
374 errx (EXIT_FAILURE, "%s exited with non-zero status %d",
375 COCKPIT_CERTIFICATE_HELPER, WEXITSTATUS (status));
376
377 certificate_and_key_read (result, COCKPIT_SELFSIGNED_PATH);
378
379 /* We just generated this ourselves, so we don't bother to check it
380 * for validity.
381 */
382 }
383
384 int
385 main (int argc, char **argv)
386 {
387 CertificateKeyPair result = { };
388 bool check = false;
389 bool for_cockpit_tls = false;
390
391 if (argc == 1)
392 ;
393 else if (argc == 2 && strcmp (argv[1], "--check") == 0)
394 check = true;
395 else if (argc == 2 && strcmp (argv[1], "--for-cockpit-tls") == 0)
396 for_cockpit_tls = true;
397 else
398 errx (EXIT_FAILURE, "usage: %s [--check]", argv[0]);
399
400 if (for_cockpit_tls)
401 tolerate_merged_cert_key = true;
402
403 if (!cockpit_certificate_find (&result, check))
404 {
405 if (check)
406 {
407 printf ("Would create a self-signed certificate\n");
408 return 1;
409 }
410
411 cockpit_certificate_selfsign (&result);
412 }
413
414 if (check)
415 printf ("Would use certificate %s\n", result.certificate_filename);
416
417 if (for_cockpit_tls)
418 {
419 const char *runtime_directory = getenv ("RUNTIME_DIRECTORY");
420 if (runtime_directory == NULL)
421 errx (EXIT_FAILURE, "--for-cockpit-tls cannot be used unless RUNTIME_DIRECTORY is set");
422
423 certificate_and_key_write (&result, runtime_directory);
424 }
425
426 certificate_and_key_clear (&result);
427
428 return 0;
429 }