Debian Codegraph @

src/session/client-certificate.c

raw
1 /*
2 * Copyright (C) 2019 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 #include "client-certificate.h"
9
10 #include <assert.h>
11 #include <err.h>
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <regex.h>
15 #include <stdbool.h>
16 #include <stddef.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20
21 #ifdef HAVE_PIDFD_GETPID
22 #include <sys/pidfd.h>
23 #endif
24
25 #include <sys/socket.h>
26 #include <sys/stat.h>
27 #include <sys/un.h>
28 #include <syslog.h>
29 #include <unistd.h>
30
31 #include <systemd/sd-bus.h>
32
33 #include "session-utils.h"
34
35 #define CLIENT_CERTIFICATE_DIRECTORY "/run/cockpit/tls/clients"
36
37 static int
38 open_proc_pid (pid_t pid)
39 {
40 char path[100];
41 int r = snprintf (path, sizeof path, "/proc/%lu", (unsigned long) pid);
42 if (r < 0 || r >= sizeof path)
43 errx (EX, "memory error");
44 int fd = open (path, O_DIRECTORY | O_NOFOLLOW | O_PATH | O_CLOEXEC);
45 if (fd < 0)
46 err (EX, "failed to open %s", path);
47 return fd;
48 }
49
50 static size_t
51 read_proc_file (int dirfd, const char *name, char *buffer, size_t bufsize)
52 {
53 int fd = openat (dirfd, name, O_RDONLY | O_CLOEXEC);
54 if (fd < 0)
55 err (EX, "Failed to open %s proc file", name);
56
57 /* we don't accept/expect EINTR or short reads here: this is /proc, and we don't have
58 * signal handlers which survive the login */
59 ssize_t len = read (fd, buffer, bufsize);
60 if (len < 0)
61 err (EX, "Failed to read /proc file %s", name);
62
63 close (fd);
64 if (len >= bufsize)
65 errx (EX, "proc file %s exceeds buffer size %zu", name, bufsize);
66 buffer[len] = '\0';
67 return len;
68 }
69
70 /* This is a bit lame, but having a hard limit on peer certificates is
71 * desirable: Let's not get DoSed by huge certs */
72 #define MAX_PEER_CERT_SIZE 100000
73
74 /* Reads the cgroupsv2-style /proc/[pid]/cgroup file of the process,
75 * including "0::" prefix and newline.
76 * NB: the kernel doesn't allow newlines in cgroup names. */
77 static char *
78 read_proc_pid_cgroup (int dirfd, size_t *out_length)
79 {
80 char buffer[1024];
81 size_t len = read_proc_file (dirfd, "cgroup", buffer, sizeof buffer);
82
83 if (strncmp (buffer, "0::/", 4) == 0 && /* must be a cgroupsv2 */
84 buffer[len - 1] == '\n') /* must end with a newline */
85 {
86 *out_length = len;
87 return strdupx (buffer);
88 }
89
90 warnx ("unexpected cgroups content, certificate matching only supports cgroup v2: '%s'", buffer);
91 exit_init_problem ("authentication-unavailable", "certificate matching only supports cgroup v2");
92 }
93
94 static
95 unsigned long long get_proc_pid_start_time (int dirfd)
96 {
97 char buffer[4096];
98 read_proc_file (dirfd, "stat", buffer, sizeof buffer);
99
100 /* start time is the token at index 19 after the '(process name)' entry - since only this
101 * field can contain the ')' character, search backwards for this to avoid malicious
102 * processes trying to fool us; See proc_pid_stat(5) */
103 const char *p = strrchr (buffer, ')');
104 if (p == NULL)
105 errx (EX, "Failed to find process name in /proc/pid/stat: %s", buffer);
106 for (int i = 0; i <= 19; i++) /* NB: ')' is the first token */
107 {
108 p = strchr (p, ' ');
109 if (p == NULL)
110 errx (EX, "Failed to find start time in /proc/pid/stat");
111 ++p; /* skip over the space */
112 }
113
114 char *endptr;
115 unsigned long long start_time = strtoull (p, &endptr, 10);
116 if (*endptr != ' ')
117 errx (EX, "Failed to parse start time in /proc/pid/stat from %s", p);
118 return start_time;
119 }
120
121 /* Fallback for get_ws_proc_fd() on older kernels which don't support enough pidfd API */
122 static int
123 get_ws_proc_fd_pid_time (int unix_fd)
124 {
125 struct ucred ucred;
126 socklen_t ucred_len = sizeof ucred;
127 if (getsockopt (unix_fd, SOL_SOCKET, SO_PEERCRED, &ucred, &ucred_len) != 0 ||
128 /* this is an inout parameter, be extra suspicious */
129 ucred_len != sizeof ucred)
130 {
131 debug ("failed to read stdin peer credentials: %m; not in socket mode?");
132 warnx ("Certificate authentication only supported with cockpit-session.socket");
133 exit_init_problem ("authentication-unavailable", "Certificate authentication only supported with cockpit-session.socket");
134 }
135
136 debug ("unix socket mode, ws peer pid %d", ucred.pid);
137 int ws_proc_dirfd = open_proc_pid (ucred.pid);
138 unsigned long long ws_start_time = get_proc_pid_start_time (ws_proc_dirfd);
139
140 int my_pid_dirfd = open_proc_pid (getpid ());
141 unsigned long long my_start_time = get_proc_pid_start_time (my_pid_dirfd);
142 close (my_pid_dirfd);
143
144 debug ("peer start time: %llu, my start time: %llu", ws_start_time, my_start_time);
145
146 /* Guard against pid recycling: If a malicious user captures ws, keeps the socket in a forked child and exits
147 * the original pid, they can trick a different user to login, get the old pid (pointing to their cgroup), and
148 * capture their session. To prevent that, require that ws must have started earlier than ourselves. */
149 if (my_start_time < ws_start_time)
150 {
151 warnx ("start time of this process (%llu) is older than cockpit-ws (%llu), pid recycling attack?",
152 my_start_time, ws_start_time);
153 close (ws_proc_dirfd);
154 exit_init_problem ("access-denied", "implausible cockpit-ws start time");
155 }
156
157 return ws_proc_dirfd;
158 }
159
160 /* Get a /proc/[pid] dirfd for our Unix socket peer (i.e. cockpit-ws).
161 * We only support being called via cockpit-session.socket (i.e. Unix socket).
162 */
163 static int
164 get_ws_proc_fd (int unix_fd)
165 {
166 #if defined(SO_PEERPIDFD) && defined(HAVE_PIDFD_GETPID)
167 int pidfd = -1;
168 socklen_t socklen = sizeof pidfd;
169 /* this is always the pidfd for the process that started the communication, it cannot be recycled */
170 if (getsockopt (unix_fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &socklen) < 0)
171 {
172 if (errno == ENOPROTOOPT)
173 {
174 debug ("SO_PEERPIDFD not supported: %m, falling back to pid/time check");
175 return get_ws_proc_fd_pid_time (unix_fd);
176 }
177
178 warn ("Failed to get peer pidfd");
179 exit_init_problem ("access-denied", "Failed to get peer pidfd");
180 }
181 /* this is an inout parameter, be extra suspicious; this really Should Not Happen™, so bomb out */
182 if (socklen != sizeof pidfd)
183 errx (EX, "SO_PEERPIDFD returned too small result");
184
185 /* get pid for pidfd; from here on this is racy and could suffer from PID recycling */
186 pid_t pid = pidfd_getpid (pidfd);
187 if (pid < 0)
188 {
189 /* be *very* strict here. This could theoretically ENOSYS if glibc has pidfd_getpid() but the kernel doesn't
190 * support it; but err on the side of denying access rather than falling back */
191 warn ("Failed to get pid from pidfd");
192 exit_init_problem ("access-denied", "Failed to get pid from pidfd");
193 }
194
195 debug ("pid from ws peer pidfd: %i", (int) pid);
196 int ws_proc_dirfd = open_proc_pid (pid);
197
198 /* check that the pid is still valid to guard against recycling */
199 if (pidfd_getpid (pidfd) != pid)
200 {
201 warn ("original pid %i is not valid any more", (int) pid);
202 exit_init_problem ("access-denied", "Failed to get cockpit-ws pid");
203 }
204
205 close (pidfd);
206 return ws_proc_dirfd;
207
208 #else
209 debug ("not built with pidfd support, falling back to pid/time check");
210 return get_ws_proc_fd_pid_time (unix_fd);
211 #endif
212 }
213
214 /* valid_256_bit_hex_string:
215 * @str: a string
216 *
217 * Ensures that str is a hexadecimal character string, exactly 64
218 * characters in length.
219 */
220 static bool
221 valid_256_bit_hex_string (const char *str)
222 {
223 size_t length = strspn (str, "0123456789abcdef");
224
225 return str[length] == '\0' && length == 64;
226 }
227
228 /**
229 * read_cert_file:
230 * @contents: a buffer to read the certificate into
231 * @contents_size: the size of @contents
232 *
233 * Reads the contents of the certificate file into @contents (of size @contents_size).
234 * The buffer must be large enough for the contents of the certificate file, plus
235 * a nul terminator (which will be added).
236 *
237 * On success, the size of the certificate file (excluding nul
238 * terminator) is returned. This value is never 0. On error, -1 is
239 * returned with errno not guaranteed to be set (but a message will be
240 * logged).
241 */
242 static ssize_t
243 read_cert_file (const char *filename,
244 char *contents,
245 size_t contents_size)
246 {
247 int dirfd = -1, filefd = -1;
248 ssize_t result = -1;
249 struct stat buf;
250 ssize_t r;
251
252 /* No tricky stuff, please */
253 if (!valid_256_bit_hex_string (filename))
254 {
255 warnx ("tls-cert authentication token is invalid");
256 goto out;
257 }
258
259 dirfd = open (CLIENT_CERTIFICATE_DIRECTORY, O_PATH | O_DIRECTORY | O_NOFOLLOW);
260 if (dirfd == -1)
261 {
262 warn ("Failed to open " CLIENT_CERTIFICATE_DIRECTORY);
263 goto out;
264 }
265
266 filefd = openat (dirfd, filename, O_RDONLY | O_NOFOLLOW);
267 if (filefd == -1)
268 {
269 warn ("Failed to open certificate file %s/%s",
270 CLIENT_CERTIFICATE_DIRECTORY, filename);
271 goto out;
272 }
273
274 if (fstat (filefd, &buf) != 0)
275 {
276 warn ("Failed to stat certificate file %s/%s",
277 CLIENT_CERTIFICATE_DIRECTORY, filename);
278 goto out;
279 }
280
281 if (!S_ISREG (buf.st_mode))
282 {
283 warnx ("Could not read certificate: %s/%s is not a regular file",
284 CLIENT_CERTIFICATE_DIRECTORY, filename);
285 goto out;
286 }
287
288 if (buf.st_size == 0)
289 {
290 warnx ("Could not read certificate: %s/%s is empty",
291 CLIENT_CERTIFICATE_DIRECTORY, filename);
292 goto out;
293 }
294
295 /* Strictly less than, since we will add a nul */
296 if (!(buf.st_size < contents_size))
297 {
298 warnx ("Insufficient space in read buffer for %s/%s",
299 CLIENT_CERTIFICATE_DIRECTORY, filename);
300 goto out;
301 }
302
303 do
304 r = pread (filefd, contents, buf.st_size, 0);
305 while (r == -1 && errno == EINTR);
306 if (r == -1)
307 {
308 warn ("Could not read certificate file %s/%s",
309 CLIENT_CERTIFICATE_DIRECTORY, filename);
310 goto out;
311 }
312 if (r != buf.st_size)
313 {
314 warnx ("Read incomplete contents of certificate file %s/%s: %zu of %zu bytes",
315 CLIENT_CERTIFICATE_DIRECTORY, filename, r, (size_t) buf.st_size);
316 goto out;
317 }
318
319 contents[buf.st_size] = '\0';
320
321 if (strlen (contents) != buf.st_size)
322 {
323 warnx ("Certificate file %s/%s contains nul characters",
324 CLIENT_CERTIFICATE_DIRECTORY, filename);
325 goto out;
326 }
327
328 result = buf.st_size;
329
330 out:
331 if (filefd != -1)
332 close (filefd);
333
334 if (dirfd != -1)
335 close (dirfd);
336
337 return result;
338 }
339
340 static bool
341 sssd_map_certificate (const char *certificate, char** username)
342 {
343 int result = false;
344 sd_bus_error err = SD_BUS_ERROR_NULL;
345 sd_bus *bus = NULL;
346 sd_bus_message *user_obj_msg = NULL;
347 const char *user_obj_path = NULL;
348 int r;
349
350 assert (username);
351 assert (!*username);
352
353 r = sd_bus_open_system (&bus);
354 if (r < 0)
355 {
356 warnx ("Failed to connect to system bus: %s", strerror (-r));
357 goto out;
358 }
359
360 /* sssd 2.6.1 introduces certificate validation against the configured CA. This version is in all supported distros */
361 r = sd_bus_call_method (bus,
362 "org.freedesktop.sssd.infopipe",
363 "/org/freedesktop/sssd/infopipe/Users",
364 "org.freedesktop.sssd.infopipe.Users",
365 "FindByValidCertificate",
366 &err,
367 &user_obj_msg,
368 "s",
369 certificate);
370
371 if (r < 0)
372 {
373 /* The error name is a bit confusing, and this is the common case; translate to readable error */
374 if (sd_bus_error_has_name (&err, "sbus.Error.NotFound"))
375 {
376 warnx ("No matching user for certificate");
377 goto out;
378 }
379
380 warnx ("Failed to map certificate to user: [%s] %s", err.name, err.message);
381 goto out;
382 }
383
384 assert (user_obj_msg);
385
386 r = sd_bus_message_read (user_obj_msg, "o", &user_obj_path);
387 if (r < 0)
388 {
389 warnx ("Failed to parse response message: %s", strerror (-r));
390 goto out;
391 }
392
393 debug ("certificate mapped to user object path %s", user_obj_path);
394
395 r = sd_bus_get_property_string (bus,
396 "org.freedesktop.sssd.infopipe",
397 user_obj_path,
398 "org.freedesktop.sssd.infopipe.Users.User",
399 "name",
400 &err,
401 username);
402
403 if (r < 0)
404 {
405 warnx ("Failed to map user object to name: [%s] %s", err.name, err.message);
406 goto out;
407 }
408
409 assert (*username);
410 debug ("mapped certificate to user %s", *username);
411 result = true;
412
413 out:
414 sd_bus_error_free (&err);
415 sd_bus_message_unref (user_obj_msg);
416 sd_bus_unref (bus);
417 return result;
418 }
419
420 /**
421 * cockpit_session_client_certificate_map_user
422 *
423 * Read the given certificate file, ensure that it belongs to our own cgroup, and ask
424 * sssd to map it to a user. If everything matches as expected, return the user name.
425 * Otherwise exit the process with sending an appropriate error to stdout using the
426 * Cockpit protocol.
427 */
428 char *
429 cockpit_session_client_certificate_map_user (const char *client_certificate_filename)
430 {
431 char cert_pem[MAX_PEER_CERT_SIZE];
432 char *sssd_user = NULL;
433
434 /* read the certificate file from disk */
435 if (read_cert_file (client_certificate_filename, cert_pem, sizeof cert_pem) < 0)
436 {
437 warnx ("No https instance certificate present");
438 exit_init_problem ("authentication-unavailable", "No https instance certificate present");
439 }
440
441 /* We need to check the cgroup of cockpit-ws (our peer); we are systemd socket activated, so stdin is a socket */
442 int ws_proc_dirfd = get_ws_proc_fd (STDIN_FILENO);
443 size_t ws_cgroup_length;
444 char *ws_cgroup = read_proc_pid_cgroup (ws_proc_dirfd, &ws_cgroup_length);
445 assert (ws_cgroup);
446 close (ws_proc_dirfd);
447
448 /* read_proc_pid_cgroup() already ensures that, but just in case we refactor this: this is *essential* for the
449 * subsequent comparison */
450 if (ws_cgroup[ws_cgroup_length - 1] != '\n')
451 errx (EX, "cgroup does not end in newline");
452
453 /* A simple prefix comparison is appropriate here because ws_cgroup
454 * contains exactly one newline (at the end), and the expected
455 * value of ws_cgroup is on the first line in cert_pem.
456 */
457 if (strncmp (cert_pem, ws_cgroup, ws_cgroup_length) != 0)
458 {
459 warnx ("This client certificate is only meant to be used from another cgroup");
460 free (ws_cgroup);
461 exit_init_problem ("access-denied", "mismatching client certificate");
462 }
463 free (ws_cgroup);
464
465 /* ask sssd to map cert to a user */
466 if (!sssd_map_certificate (cert_pem + ws_cgroup_length, &sssd_user))
467 exit_init_problem ("authentication-failed", "sssd does not know this certificate");
468
469 return sssd_user;
470 }