Debian Codegraph @

src/session/session-utils.c

raw
1 /*
2 * Copyright (C) 2013 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 #include "session-utils.h"
9
10 #include "common/cockpitframe.h"
11 #include "common/cockpitjsonprint.h"
12 #include "common/cockpitmemory.h"
13
14 #include <fcntl.h>
15 #include <paths.h>
16 #include <stdarg.h>
17 #include <stdlib.h>
18 #include <sys/param.h>
19 #include <time.h>
20 #include <utmp.h>
21
22 #ifndef _PATH_BTMP
23 #define _PATH_BTMP "/var/log/btmp"
24 #endif
25
26 const char *program_name;
27 struct passwd *pwd;
28 pid_t child;
29 int want_session = 1;
30
31 static char *auth_prefix = NULL;
32 static size_t auth_prefix_size = 0;
33 static char *auth_msg = NULL;
34 static size_t auth_msg_size = 0;
35 static FILE *authf = NULL;
36
37 char *
38 read_authorize_response (const char *what)
39 {
40 unsigned char *message;
41 debug ("reading %s authorize message", what);
42 ssize_t len = cockpit_frame_read (STDIN_FILENO, &message);
43 if (len < 0)
44 err (EX, "couldn't read %s", what);
45 if (len == 0)
46 {
47 debug ("EOF reading %s authorize message", what);
48 exit (0);
49 }
50 return (char *)message;
51 }
52
53 char *get_authorize_key (const char *json, const char *key, bool required)
54 {
55 /*
56 * The authorize messages we receive always have this structure:
57 *
58 * \n{"command":"authorize","cookie":"NNN","response":"...",...more entries...}
59 *
60 * We make many assumptions/restrictions here to keep the parser simple. In particular, no extra
61 * whitespace, everything is a string, and no escaped ".
62 */
63 if (json == NULL || json[0] != '\n' || json[1] != '{')
64 errx (EX, "authorize message doesn't start with \\n{");
65
66 char *key_match;
67 int key_match_len = asprintfx (&key_match, "\"%s\":\"", key);
68
69 const char *match = strstr (json, key_match);
70 free (key_match);
71 if (!match)
72 {
73 if (required)
74 errx (EX, "authorize message missing required key %s", key);
75 debug ("authorize message missing optional key %s", key);
76 return NULL;
77 }
78
79 /* advance to the start of the value */
80 match += key_match_len;
81 /* find end of value */
82 size_t value_len = strcspn (match, "\"");
83 if (match[value_len] != '"')
84 errx (EX, "syntax error, expected closing quote");
85 return strndup (match, value_len);
86 }
87
88 void
89 write_control_string (const char *field,
90 const char *str)
91 {
92 cockpit_json_print_string_property (authf, field, str, -1);
93 }
94
95 void
96 write_control_bool (const char *field,
97 bool val)
98 {
99 cockpit_json_print_bool_property (authf, field, val);
100 }
101
102 void
103 write_authorize_begin (void)
104 {
105 assert (authf == NULL);
106 assert (auth_msg_size == 0);
107 assert (auth_msg == NULL);
108
109 debug ("writing auth challenge");
110
111 if (auth_prefix)
112 {
113 free (auth_prefix);
114 auth_prefix = NULL;
115 }
116
117 if (asprintf (&auth_prefix, "\n{\"command\":\"authorize\",\"cookie\":\"session%u%u\"",
118 (unsigned int)getpid(), (unsigned int)time (NULL)) < 0)
119 {
120 errx (EX, "out of memory allocating string");
121 }
122 auth_prefix_size = strlen (auth_prefix);
123
124 authf = open_memstream (&auth_msg, &auth_msg_size);
125 if (!authf)
126 err (EX, "failed to open_memstream()");
127 fprintf (authf, "%s", auth_prefix);
128 }
129
130 void
131 write_control_end (void)
132 {
133 assert (authf != NULL);
134
135 fprintf (authf, "}\n");
136 fflush (authf);
137 fclose (authf);
138
139 assert (auth_msg_size > 0);
140 assert (auth_msg != NULL);
141
142 if (cockpit_frame_write (STDOUT_FILENO, (unsigned char *)auth_msg, auth_msg_size) < 0)
143 err (EX, "couldn't write auth request");
144
145 debug ("finished auth request");
146 free (auth_msg);
147 auth_msg = NULL;
148 authf = NULL;
149 auth_msg_size = 0;
150 }
151
152 __attribute__((__noreturn__)) void
153 exit_init_problem (const char *problem, const char *message)
154 {
155 char *payload = NULL;
156 size_t payload_size = 0;
157
158 debug ("writing init problem %s message %s", problem, message);
159
160 FILE *stream = open_memstream (&payload, &payload_size);
161 if (!stream)
162 errx (EX, "couldn't allocate memory for message");
163
164 fprintf (stream, "\n{\"command\":\"init\",\"version\":1");
165 cockpit_json_print_string_property (stream, "problem", problem, -1);
166 cockpit_json_print_string_property (stream, "message", message, -1);
167 fprintf (stream, "}");
168 fclose (stream);
169
170 if (cockpit_frame_write (STDOUT_FILENO, (unsigned char *)payload, payload_size) < 0)
171 err (EX, "couldn't write init message");
172
173 free (payload);
174 exit (5);
175 }
176
177 void
178 build_string (char **buf,
179 size_t *size,
180 const char *str,
181 size_t len)
182 {
183 if (*size == 0)
184 return;
185
186 if (len > *size - 1)
187 len = *size - 1;
188
189 memcpy (*buf, str, len);
190 (*buf)[len] = '\0';
191 *buf += len;
192 *size -= len;
193 }
194
195 static bool
196 do_lastlog (uid_t uid,
197 const struct timeval *now,
198 const char *rhost,
199 time_t *out_last_login,
200 FILE *messages)
201 {
202 struct lastlog entry;
203 bool result = false;
204 int fd = -1;
205 ssize_t r;
206
207 fd = open (_PATH_LASTLOG, O_RDWR);
208 if (fd == -1)
209 {
210 warn ("failed to open %s", _PATH_LASTLOG);
211 goto out;
212 }
213
214 r = pread (fd, &entry, sizeof entry, uid * sizeof entry);
215 if (r == sizeof entry && entry.ll_time != 0)
216 {
217 /* got an entry for the user */
218
219 /* the ll_host and ll_line fields can be nul-terminated, but they
220 * can also extend to the full length of the field without
221 * nul-termination. use the maxlen parameter to help with that.
222 */
223 if (!cockpit_json_print_integer_property (messages, "last-login-time", entry.ll_time) ||
224 !cockpit_json_print_string_property (messages, "last-login-host", entry.ll_host, UT_HOSTSIZE) ||
225 !cockpit_json_print_string_property (messages, "last-login-line", entry.ll_line, UT_LINESIZE))
226 {
227 warnx ("failed to print last-login details to messages memfd");
228 goto out;
229 }
230
231 if (out_last_login)
232 *out_last_login = entry.ll_time;
233 }
234 else if (r == sizeof entry)
235 {
236 /* read the entry, but it's nul. user never logged in. */
237 *out_last_login = 0;
238 }
239 else if (r == 0)
240 {
241 /* no such entry in file: never logged in? */
242 *out_last_login = 0;
243 }
244 else if (r < 0)
245 {
246 /* error */
247 warn ("failed to pread() %s for uid %u", _PATH_LASTLOG, (unsigned) uid);
248 goto out;
249 }
250 else
251 {
252 /* some other size (incomplete read) */
253 warnx ("incomplete pread() %s for uid %u: %zu of %zu bytes",
254 _PATH_LASTLOG, (unsigned) uid, r, sizeof entry);
255 goto out;
256 }
257
258 /* XXX: We'd really like to use strncpy() here, which is perfectly
259 * designed for what we need to do: copy a string up to N characters
260 * into a fixed width field, adding nul bytes if the string is shorter
261 * than N.
262 *
263 * Unfortunately, when you use it in this way, GCC is convinced that
264 * you don't know what you're doing and gives a warning that's very
265 * difficult to get rid of. We tried using #pragma here before, but
266 * after several attempts, it was difficult to get the
267 * conditionalising (for the compiler version) correct.
268 *
269 * Let's just nul out the struct and use memcpy(). Sigh.
270 *
271 * strncpy (entry.ll_host, rhost, sizeof entry.ll_host);
272 * strncpy (entry.ll_line, "web console", sizeof entry.ll_line);
273 *
274 * See also https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94615
275 * See also https://sourceware.org/bugzilla/show_bug.cgi?id=25844
276 */
277 memset (&entry, 0, sizeof entry);
278 memcpy (entry.ll_host, rhost, MIN (strlen (rhost), sizeof entry.ll_host));
279 const char * const line = "web console";
280 memcpy (entry.ll_line, line, MIN (strlen (line), sizeof entry.ll_line));
281
282 entry.ll_time = now->tv_sec;
283
284 r = pwrite (fd, &entry, sizeof entry, uid * sizeof entry);
285 if (r == -1)
286 {
287 /* error */
288 warn ("failed to pwrite() %s for uid %u", _PATH_LASTLOG, (unsigned) uid);
289 goto out;
290 }
291 else if (r != sizeof entry)
292 {
293 /* incomplete write */
294 warnx ("incomplete pwrite() %s for uid %u: %zu or %zu bytes",
295 _PATH_LASTLOG, (unsigned) uid, r, sizeof entry);
296 goto out;
297 }
298
299 result = true;
300
301 out:
302 if (fd != -1)
303 close (fd);
304
305 return result;
306 }
307
308 static bool
309 scan_btmp (const char *username,
310 time_t last_success,
311 FILE *messages)
312 {
313 bool success = false;
314 int fail_count = 0;
315 struct utmp last;
316 int fd;
317
318 fd = open (_PATH_BTMP, O_RDONLY | O_CLOEXEC);
319 if (fd == -1)
320 {
321 if (errno == ENOENT)
322 {
323 /* no btmp → no failed attempts */
324 success = true;
325 goto out;
326 }
327
328 warn ("open(%s) failed", _PATH_BTMP);
329 goto out;
330 }
331
332 while (true)
333 {
334 struct utmp entry;
335 ssize_t r;
336
337 do
338 r = read (fd, &entry, sizeof entry);
339 while (r == -1 && errno == EINTR);
340
341 if (r == 0)
342 break;
343
344 if (r < 0)
345 {
346 warn ("read(%s) failed", _PATH_BTMP);
347 goto out;
348 }
349 if (r != sizeof entry)
350 {
351 warnx ("read(%s) returned partial result (%zu of %zu bytes)",
352 _PATH_BTMP, r, sizeof entry);
353 goto out;
354 }
355
356 if (entry.ut_tv.tv_sec > last_success &&
357 strncmp (entry.ut_user, username, sizeof entry.ut_user) == 0)
358 {
359 last = entry;
360 fail_count++;
361 }
362 }
363
364 if (fail_count == 0)
365 {
366 success = true;
367 goto out;
368 }
369
370 /* only print messages if we actually have failures */
371 success = cockpit_json_print_integer_property (messages, "fail-count", fail_count) &&
372 cockpit_json_print_integer_property (messages, "last-fail-time", last.ut_tv.tv_sec) &&
373 cockpit_json_print_string_property (messages, "last-fail-host", last.ut_host, UT_HOSTSIZE) &&
374 cockpit_json_print_string_property (messages, "last-fail-line", last.ut_line, UT_LINESIZE);
375
376 out:
377 if (fd > -1)
378 close (fd);
379
380 return success;
381 }
382
383 void
384 utmp_log (int login,
385 const char *rhost,
386 FILE *messages)
387 {
388 char id[UT_LINESIZE + 1];
389 struct utmp ut;
390 struct timeval tv;
391 int pid;
392
393 pid = getpid ();
394
395 snprintf (id, UT_LINESIZE, "%d", pid);
396
397 assert (pwd != NULL);
398 utmpname (_PATH_UTMP);
399 setutent ();
400
401 memset (&ut, 0, sizeof(ut));
402
403 strncpy (ut.ut_id, id, sizeof (ut.ut_id));
404 ut.ut_id[sizeof (ut.ut_id) - 1] = 0;
405
406 strncpy (ut.ut_line, "web console", sizeof ut.ut_line);
407 ut.ut_line[sizeof ut.ut_line - 1] = 0;
408
409 if (login)
410 {
411 strncpy (ut.ut_user, pwd->pw_name, sizeof(ut.ut_user));
412 ut.ut_user[sizeof (ut.ut_user) - 1] = 0;
413 strncpy (ut.ut_host, rhost, sizeof(ut.ut_host));
414 ut.ut_host[sizeof (ut.ut_host) - 1] = 0;
415 }
416
417 gettimeofday (&tv, NULL);
418 ut.ut_tv.tv_sec = tv.tv_sec;
419 ut.ut_tv.tv_usec = tv.tv_usec;
420
421 ut.ut_type = login ? USER_PROCESS : DEAD_PROCESS;
422 ut.ut_pid = pid;
423
424 pututline (&ut);
425 endutent ();
426
427 updwtmp (_PATH_WTMP, &ut);
428
429 if (login)
430 {
431 time_t last_success;
432
433 if (do_lastlog (pwd->pw_uid, &tv, rhost, &last_success, messages))
434 scan_btmp (pwd->pw_name, last_success, messages);
435 }
436 }
437
438 void
439 btmp_log (const char *username,
440 const char *rhost)
441 {
442 struct timeval tv;
443
444 /* the `tv` in the utmp struct is not actually a `struct timeval`, so
445 * we need to read into a temporary variable and then copy the fields.
446 */
447 gettimeofday (&tv, NULL);
448
449 struct utmp entry = {
450 .ut_line = "web console",
451 .ut_pid = getpid (),
452 .ut_tv.tv_sec = tv.tv_sec,
453 .ut_tv.tv_usec = tv.tv_usec,
454 .ut_type = LOGIN_PROCESS,
455 };
456
457 /* see utmp(5), it is ok to not null-terminate these if they have maximum size */
458 /* add coverity markers for older glibcs: https://sourceware.org/bugzilla/show_bug.cgi?id=24899 */
459 /* coverity[buffer_size_warning : FALSE] */
460 strncpy (entry.ut_host, rhost, sizeof entry.ut_host);
461 /* coverity[buffer_size_warning : FALSE] */
462 strncpy (entry.ut_user, username, sizeof entry.ut_user);
463
464 int fd = open (_PATH_BTMP, O_WRONLY | O_APPEND);
465 if (fd == -1)
466 {
467 warn ("open(%s) failed", _PATH_BTMP);
468 goto out;
469 }
470
471 ssize_t r = write (fd, &entry, sizeof entry);
472 if (r < 0)
473 {
474 warn ("write() %s failed", _PATH_BTMP);
475 goto out;
476 }
477 else if (r != sizeof entry)
478 {
479 warnx ("incomplete write() %s: %zu of %zu bytes",
480 _PATH_BTMP, r, sizeof entry);
481 goto out;
482 }
483
484 out:
485 if (fd != -1)
486 close (fd);
487 }
488
489 void
490 authorize_logger (const char *data)
491 {
492 warnx ("%s", data);
493 }
494
495 /* signal- and after-fork()-safe function to format a string, print it
496 * to stderr and abort execution. Never returns.
497 */
498 static noreturn void
499 __attribute__ ((format (printf, 1, 2)))
500 abort_with_message (const char *format,
501 ...)
502 {
503 char buffer[1024];
504 va_list ap;
505
506 va_start (ap, format);
507 size_t length = vsnprintf (buffer, sizeof buffer, format, ap);
508 va_end (ap);
509
510 size_t ofs = 0;
511 while (ofs != length)
512 {
513 ssize_t r;
514 do
515 r = write (STDERR_FILENO, buffer + ofs, length - ofs);
516 while (r == -1 && errno == EINTR);
517
518 if (0 <= r && r <= length - ofs)
519 ofs += r;
520 else
521 break; /* something went wrong, but we can't deal with it */
522 }
523
524 abort ();
525 }
526
527 /* signal- and after-fork()-safe function to remap file descriptors
528 * according to a specified array. All other file descriptors are
529 * closed.
530 *
531 * Commonly used after fork() and before exec().
532 */
533 static void
534 fd_remap (const int *remap_fds,
535 int n_remap_fds)
536 {
537 if (n_remap_fds < 0 || n_remap_fds > 1024)
538 abort_with_message ("requested to fd_remap() too many fds!");
539
540 int *fds = alloca (sizeof (int) * n_remap_fds);
541 memcpy (fds, remap_fds, sizeof (int) * n_remap_fds);
542
543 /* we need to get all of the remap-fds to be numerically above
544 * n_remap_fds in order to make sure that we don't overwrite them in
545 * the middle of the dup2() loop below, and also avoid the case that
546 * dup2() is a no-op (which could fail to clear the O_CLOEXEC flag,
547 * for example).
548 */
549 for (int i = 0; i < n_remap_fds; i++)
550 if (fds[i] != -1 && fds[i] < n_remap_fds)
551 {
552 int new_fd = fcntl (fds[i], F_DUPFD, n_remap_fds); /* returns >= n_remap_fds */
553
554 if (new_fd == -1)
555 abort_with_message ("fcntl(%d, F_DUPFD) failed: %m", fds[i]);
556
557 fds[i] = new_fd;
558 }
559
560 /* now we can map the fds into their final spot */
561 for (int i = 0; i < n_remap_fds; i++)
562 if (fds[i] != -1) /* no-op */
563 if (dup2 (fds[i], i) != i)
564 abort_with_message ("dup2(%d, %d) failed: %m", fds[i], i);
565
566 /* close everything else */
567 close_range (n_remap_fds, ~0U, 0);
568 }
569
570 int
571 spawn_and_wait (const char **argv, const char **envp,
572 const int *remap_fds, int n_remap_fds,
573 uid_t uid, gid_t gid)
574 {
575 pid_t child;
576
577 child = fork ();
578 if (child == -1)
579 abort_with_message ("cockpit-session: fork() failed: %m");
580
581 if (child == 0)
582 {
583 /* This is the child process. Do preparation, and exec(). */
584 if (setresgid (gid, gid, gid) != 0)
585 abort_with_message ("setresgid: couldn't set gid to %u: %m\n", (int) gid);
586
587 if (setresuid (uid, uid, uid) != 0)
588 abort_with_message ("setresuid: couldn't set uid to %u: %m\n", (int) uid);
589
590 /* paranoid */
591 {
592 uid_t real, effective, saved;
593 int r;
594
595 r = getresuid (&real, &effective, &saved);
596 assert (r == 0 && real == uid && effective == uid && saved == uid);
597 }
598
599 {
600 gid_t real, effective, saved;
601 int r;
602
603 r = getresgid (&real, &effective, &saved);
604 assert (r == 0 && real == gid && effective == gid && saved == gid);
605 }
606
607 if (n_remap_fds != -1)
608 fd_remap (remap_fds, n_remap_fds);
609
610 execvpe (argv[0], (char **) argv, (char **) envp);
611 _exit(127);
612 }
613
614 else
615 {
616 /* This is the parent process. Wait for the child to exit. */
617 int wstatus;
618 int r;
619
620 do
621 r = waitpid (child, &wstatus, 0);
622 while (r == -1 && errno == EINTR);
623
624 if (r == -1)
625 abort_with_message ("waitpid(%d) on cockpit-bridge process failed: %m", (int) child);
626
627 /* 0 can only be returned of WNOHANG was given */
628 assert (r == child);
629
630 return wstatus;
631 }
632 }