Debian Codegraph @

src/session/session.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 "common/cockpitframe.h"
9 #include "common/cockpitjsonprint.h"
10 #include "common/cockpitmemory.h"
11
12 #include "client-certificate.h"
13 #include "session-utils.h"
14
15 #include <security/pam_appl.h>
16 #include <gssapi/gssapi.h>
17 #include <gssapi/gssapi_generic.h>
18 #include <gssapi/gssapi_krb5.h>
19 #include <fcntl.h>
20
21 static char *last_txt_msg = NULL;
22 static char *last_err_msg = NULL;
23 static char *conversation = NULL;
24
25 /* This program opens a session for a given user and runs the bridge in
26 * it. It is used to manage localhost; for remote hosts sshd does
27 * this job.
28 */
29
30 #define COCKPIT_KTAB PACKAGE_SYSCONF_DIR "/cockpit/krb5.keytab"
31
32 /* exit status if cockpit-bridge binary does not exist */
33 #define EXIT_NOT_FOUND 127
34
35 static gss_cred_id_t creds = GSS_C_NO_CREDENTIAL;
36
37 /* Environment variables to transfer */
38 static const char *env_names[] = {
39 "G_DEBUG",
40 "G_MESSAGES_DEBUG",
41 "G_SLICE",
42 "PATH",
43 NULL
44 };
45
46 /* Holds environment values to set in pam context */
47 static char *env_saved[sizeof (env_names) / sizeof (env_names)[0]] = { NULL, };
48
49 static const char *
50 gssapi_strerror (gss_OID mech_type,
51 OM_uint32 major_status,
52 OM_uint32 minor_status)
53 {
54 static char buffer[1024];
55 OM_uint32 major, minor;
56 OM_uint32 ctx;
57 gss_buffer_desc status;
58 char *buf;
59 size_t len;
60 int had_major;
61 int had_minor;
62
63 debug ("gssapi: major_status: %8.8x, minor_status: %8.8x",
64 major_status, minor_status);
65
66 buf = buffer;
67 len = sizeof (buffer);
68 buf[0] = '\0';
69 had_major = 0;
70 ctx = 0;
71
72 if (major_status != GSS_S_FAILURE || minor_status == 0)
73 {
74 for (;;)
75 {
76 major = gss_display_status (&minor, major_status, GSS_C_GSS_CODE,
77 GSS_C_NO_OID, &ctx, &status);
78 if (GSS_ERROR (major))
79 break;
80
81 if (had_major)
82 build_string (&buf, &len, ": ", 2);
83 had_major = 1;
84
85 build_string (&buf, &len, status.value, status.length);
86 gss_release_buffer (&minor, &status);
87
88 if (!ctx)
89 break;
90 }
91 }
92
93 ctx = 0;
94 had_minor = 0;
95 for (;;)
96 {
97 major = gss_display_status (&minor, minor_status, GSS_C_MECH_CODE,
98 mech_type, &ctx, &status);
99 if (GSS_ERROR (major))
100 break;
101
102 if (had_minor)
103 build_string (&buf, &len, ", ", 2);
104 else if (had_major)
105 build_string (&buf, &len, " (", 2);
106 had_minor = 1;
107 build_string (&buf, &len, status.value, status.length);
108
109 gss_release_buffer (&minor, &status);
110
111 if (!ctx)
112 break;
113 }
114
115 if (had_major && had_minor)
116 build_string (&buf, &len, ")", 1);
117
118 return buffer;
119 }
120
121 static int
122 pam_conv_func (int num_msg,
123 const struct pam_message **msg,
124 struct pam_response **ret_resp,
125 void *appdata_ptr)
126 {
127 char **password = (char **)appdata_ptr;
128
129 /* For keeping track of messages returned by PAM */
130 char *err_msg = NULL;
131 char *txt_msg = NULL;
132 char *buf, **msgp;
133
134 struct pam_response *resp;
135 char *prompt = NULL;
136 int success = 1;
137 int i;
138
139 /* Any messages from the last conversation pass? */
140 txt_msg = last_txt_msg;
141 last_txt_msg = NULL;
142 err_msg = last_err_msg;
143 last_err_msg = NULL;
144
145 resp = callocx (sizeof (struct pam_response), num_msg);
146
147 for (i = 0; i < num_msg; i++)
148 {
149 if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF &&
150 *password != NULL)
151 {
152 debug ("answered pam password prompt");
153 resp[i].resp = *password;
154 resp[i].resp_retcode = 0;
155 *password = NULL;
156 }
157 else if (msg[i]->msg_style == PAM_ERROR_MSG || msg[i]->msg_style == PAM_TEXT_INFO)
158 {
159 if (msg[i]->msg_style == PAM_ERROR_MSG)
160 msgp = &err_msg;
161 else
162 msgp = &txt_msg;
163
164 if (*msgp)
165 {
166 buf = *msgp;
167 asprintfx (msgp, "%s\n%s", buf, msg[i]->msg);
168 free (buf);
169 }
170 else
171 {
172 asprintfx (msgp, "%s", msg[i]->msg);
173 }
174 warnx ("pam: %s", msg[i]->msg);
175 }
176 else
177 {
178 debug ("prompt for more data");
179 write_authorize_begin ();
180 prompt = cockpit_authorize_build_x_conversation (msg[i]->msg, &conversation);
181 if (!prompt)
182 err (EX, "couldn't generate prompt");
183
184 write_control_string ("challenge", prompt);
185 free (prompt);
186
187 if (txt_msg)
188 write_control_string ("message", txt_msg);
189 if (err_msg)
190 write_control_string ("error", err_msg);
191 write_control_bool ("echo", msg[i]->msg_style != PAM_PROMPT_ECHO_OFF);
192 write_control_end ();
193
194 if (err_msg)
195 {
196 free (err_msg);
197 err_msg = NULL;
198 }
199
200 if (txt_msg)
201 {
202 free (txt_msg);
203 txt_msg = NULL;
204 }
205
206 char *authorization = read_authorize_response (msg[i]->msg);
207 char *response = get_authorize_key (authorization, "response", true);
208 char *prompt_resp = cockpit_authorize_parse_x_conversation (response, NULL);
209 cockpit_memory_clear (response, -1);
210 free (response);
211
212 debug ("got prompt response");
213 if (prompt_resp)
214 {
215 resp[i].resp = prompt_resp;
216 resp[i].resp_retcode = 0;
217 prompt_resp = NULL;
218 }
219 else
220 {
221 success = 0;
222 }
223
224 cockpit_memory_clear (authorization, -1);
225 free (authorization);
226 }
227 }
228
229 if (!success)
230 {
231 for (i = 0; i < num_msg; i++)
232 free (resp[i].resp);
233 free (resp);
234 return PAM_CONV_ERR;
235 }
236
237 if (err_msg)
238 last_err_msg = err_msg;
239 if (txt_msg)
240 last_txt_msg = txt_msg;
241
242 *ret_resp = resp;
243 return PAM_SUCCESS;
244 }
245
246 static int
247 open_session (pam_handle_t *pamh)
248 {
249 const char *name;
250 int res;
251 static struct passwd pwd_buf;
252 static char pwd_string_buf[8192];
253 static char home_env_buf[8192];
254 int i;
255
256 name = NULL;
257 pwd = NULL;
258
259 res = pam_get_item (pamh, PAM_USER, (const void **)&name);
260 if (res != PAM_SUCCESS)
261 {
262 warnx ("couldn't load user from pam");
263 return res;
264 }
265
266 res = getpwnam_r (name, &pwd_buf, pwd_string_buf, sizeof (pwd_string_buf), &pwd);
267 if (pwd == NULL)
268 {
269 warnx ("couldn't load user info for: %s: %s", name,
270 res == 0 ? "not found" : strerror (res));
271 return PAM_SYSTEM_ERR;
272 }
273
274 if (pwd->pw_shell == NULL)
275 {
276 warnx ("user %s has no shell", name);
277 return PAM_SYSTEM_ERR;
278 }
279
280 /*
281 * If we're already running as the right user, and have authenticated
282 * then skip starting a new session. This is used when testing, or
283 * running as your own user.
284 */
285
286 want_session = !(geteuid () != 0 &&
287 geteuid () == pwd->pw_uid &&
288 getuid () == pwd->pw_uid &&
289 getegid () == pwd->pw_gid &&
290 getgid () == pwd->pw_gid);
291
292 if (want_session)
293 {
294 debug ("checking access for %s", name);
295 res = pam_acct_mgmt (pamh, 0);
296 if (res == PAM_NEW_AUTHTOK_REQD)
297 {
298 warnx ("user account or password has expired: %s: %s", name, pam_strerror (pamh, res));
299
300 /*
301 * Certain PAM implementations return PAM_AUTHTOK_ERR if the users input does not
302 * match criteria. Let the conversation happen three times in that case.
303 */
304 for (i = 0; i < 3; i++) {
305 res = pam_chauthtok (pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
306 if (res != PAM_SUCCESS)
307 warnx ("unable to change expired account or password: %s: %s", name, pam_strerror (pamh, res));
308 if (res != PAM_AUTHTOK_ERR)
309 break;
310 }
311 }
312 else if (res != PAM_SUCCESS)
313 {
314 warnx ("user account access failed: %d %s: %s", res, name, pam_strerror (pamh, res));
315 }
316
317 if (res != PAM_SUCCESS)
318 {
319 /* We change PAM_AUTH_ERR to PAM_PERM_DENIED so that we can
320 * distinguish between failures here and in *
321 * pam_authenticate.
322 */
323 if (res == PAM_AUTH_ERR)
324 res = PAM_PERM_DENIED;
325
326 return res;
327 }
328
329 debug ("opening pam session for %s", name);
330
331 res = snprintf (home_env_buf, sizeof (home_env_buf), "HOME=%s", pwd->pw_dir);
332 /* this really can't fail, as the buffer for the entire pwd is not larger, but make double sure */
333 assert (res < sizeof (home_env_buf));
334
335 pam_putenv (pamh, "XDG_SESSION_CLASS=user");
336 pam_putenv (pamh, "XDG_SESSION_TYPE=web");
337 pam_putenv (pamh, home_env_buf);
338
339 res = pam_setcred (pamh, PAM_ESTABLISH_CRED);
340 if (res != PAM_SUCCESS)
341 {
342 warnx ("establishing credentials failed: %s: %s", name, pam_strerror (pamh, res));
343 return res;
344 }
345
346 res = pam_open_session (pamh, 0);
347 if (res != PAM_SUCCESS)
348 {
349 warnx ("couldn't open session: %s: %s", name, pam_strerror (pamh, res));
350 return res;
351 }
352
353 res = pam_setcred (pamh, PAM_REINITIALIZE_CRED);
354 if (res != PAM_SUCCESS)
355 {
356 warnx ("reinitializing credentials failed: %s: %s", name, pam_strerror (pamh, res));
357 return res;
358 }
359 }
360
361 return PAM_SUCCESS;
362 }
363
364 __attribute__((__noreturn__)) static void
365 exit_pam_init_problem (int result_code)
366 {
367 const char *problem = NULL;
368 const char *message = NULL;
369
370 assert (result_code != PAM_SUCCESS);
371
372 debug ("writing PAM init problem %d", result_code);
373
374 if (result_code == PAM_AUTH_ERR || result_code == PAM_USER_UNKNOWN)
375 problem = "authentication-failed";
376 else if (result_code == PAM_PERM_DENIED)
377 problem = "access-denied";
378 else if (result_code == PAM_AUTHINFO_UNAVAIL)
379 problem = "authentication-unavailable";
380 else
381 problem = "internal-error";
382
383 if (last_err_msg)
384 message = last_err_msg;
385 else
386 message = pam_strerror (NULL, result_code);
387
388 exit_init_problem (problem, message);
389 }
390
391 static pam_handle_t *
392 perform_basic (const char *rhost,
393 const char *authorization)
394 {
395 struct pam_conv conv = { pam_conv_func, };
396 pam_handle_t *pamh;
397 char *password = NULL;
398 char *user = NULL;
399 int res;
400
401 assert (rhost != NULL);
402 assert (authorization != NULL);
403
404 debug ("basic authentication");
405
406 /* The input should be a user:password */
407 password = cockpit_authorize_parse_basic (authorization, &user);
408 if (password == NULL)
409 {
410 debug ("bad basic auth input");
411 exit_pam_init_problem (PAM_BUF_ERR);
412 }
413
414 conv.appdata_ptr = &password;
415
416 res = pam_start ("cockpit", user, &conv, &pamh);
417 if (res != PAM_SUCCESS)
418 errx (EX, "couldn't start pam: %s", pam_strerror (NULL, res));
419
420 if (pam_set_item (pamh, PAM_RHOST, rhost) != PAM_SUCCESS)
421 errx (EX, "couldn't setup pam");
422
423 debug ("authenticating");
424
425 res = pam_authenticate (pamh, 0);
426 if (res == PAM_SUCCESS)
427 res = open_session (pamh);
428 else
429 btmp_log (user, rhost);
430
431 free (user);
432 if (password)
433 {
434 cockpit_memory_clear (password, strlen (password));
435 free (password);
436 }
437
438 /* Our exit code is a PAM code */
439 if (res != PAM_SUCCESS)
440 exit_pam_init_problem (res);
441
442 return pamh;
443 }
444
445 static char *
446 map_gssapi_to_local (gss_name_t name,
447 gss_OID mech_type)
448 {
449 gss_buffer_desc local = GSS_C_EMPTY_BUFFER;
450 gss_buffer_desc display = GSS_C_EMPTY_BUFFER;
451 OM_uint32 major, minor;
452 char *str = NULL;
453
454 major = gss_localname (&minor, name, mech_type, &local);
455 if (major == GSS_S_COMPLETE)
456 {
457 minor = 0;
458 str = strndupx (local.value, local.length); /* user names are not allowed to contain \0 */
459 if (getpwnam (str))
460 {
461 debug ("mapped gssapi name to local user '%s'", str);
462 }
463 else
464 {
465 debug ("ignoring non-existent gssapi local user '%s'", str);
466
467 /* If the local user doesn't exist, pretend gss_localname() failed */
468 free (str);
469 str = NULL;
470 major = GSS_S_FAILURE;
471 minor = KRB5_NO_LOCALNAME;
472 }
473 }
474
475 /* Try a more pragmatic approach */
476 if (!str)
477 {
478 if (minor == (OM_uint32)KRB5_NO_LOCALNAME ||
479 minor == (OM_uint32)KRB5_LNAME_NOTRANS ||
480 minor == (OM_uint32)ENOENT)
481 {
482 major = gss_display_name (&minor, name, &display, NULL);
483 if (GSS_ERROR (major))
484 {
485 warnx ("couldn't get gssapi display name: %s", gssapi_strerror (mech_type, major, minor));
486 }
487 else
488 {
489 assert (display.value != NULL);
490 str = strndupx (display.value, display.length); /* display names are not allowed to contain \0 */
491 if (getpwnam (str))
492 {
493 debug ("no local user mapping for gssapi name '%s'", str);
494 }
495 else
496 {
497 warnx ("non-existent local user '%s'", str);
498 free (str);
499 str = NULL;
500 }
501 }
502 }
503 else
504 {
505 warnx ("couldn't map gssapi name to local user: %s", gssapi_strerror (mech_type, major, minor));
506 }
507 }
508
509 if (display.value)
510 gss_release_buffer (&minor, &display);
511 if (local.value)
512 gss_release_buffer (&minor, &local);
513
514 return str;
515 }
516
517 static bool
518 acquire_service_credentials (gss_OID mech_type, gss_cred_usage_t usage, gss_cred_id_t *cred)
519 {
520 /* custom credential store with our cockpit keytab */
521 gss_key_value_element_desc store_elements[] = {
522 { .key = (usage == GSS_C_INITIATE) ? "client_keytab" : "keytab", .value = COCKPIT_KTAB, },
523 { .key = "ccache", .value = "MEMORY:", }
524 };
525 const gss_key_value_set_desc cockpit_ktab_store = { .count = 2, .elements = store_elements };
526 OM_uint32 major, minor;
527
528 debug ("acquiring cockpit service credentials");
529 major = gss_acquire_cred_from (&minor, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, usage,
530 (!getenv ("COCKPIT_TEST_KEEP_KTAB") && access (COCKPIT_KTAB, F_OK) == 0) ? &cockpit_ktab_store : NULL,
531 cred, NULL, NULL);
532
533 if (GSS_ERROR (major))
534 {
535 const char *msg = gssapi_strerror (mech_type, major, minor);
536 /* don't litter journal with error message if keytab was not set up, as that's expected */
537 /* older krb versions hide the interesting bits behind the generic GSS_S_FAILURE and an uncomparable
538 * minor code, so do string comparison for these */
539 if (major != GSS_S_NO_CRED && !strstr (msg, "nonexistent or empty") && !strstr (msg, "No Kerberos credentials available"))
540 warnx ("couldn't acquire server credentials: %o %s", major, msg);
541 return false;
542 }
543
544 return true;
545 }
546
547 static pam_handle_t *
548 perform_gssapi (const char *rhost,
549 const char *authorization)
550 {
551 struct pam_conv conv = { pam_conv_func, };
552 OM_uint32 major, minor;
553 gss_cred_id_t client = GSS_C_NO_CREDENTIAL;
554 gss_cred_id_t server = GSS_C_NO_CREDENTIAL;
555 gss_buffer_desc input = GSS_C_EMPTY_BUFFER;
556 gss_buffer_desc output = GSS_C_EMPTY_BUFFER;
557 gss_buffer_desc export = GSS_C_EMPTY_BUFFER;
558 gss_name_t name = GSS_C_NO_NAME;
559 gss_ctx_id_t context = GSS_C_NO_CONTEXT;
560 gss_OID mech_type = GSS_C_NO_OID;
561 pam_handle_t *pamh = NULL;
562 char *challenge;
563 OM_uint32 flags = 0;
564 char *str = NULL;
565 OM_uint32 caps = 0;
566 int res;
567
568 assert (rhost != NULL);
569 assert (authorization != NULL);
570
571 res = PAM_AUTH_ERR;
572
573 debug ("reading kerberos auth from cockpit-ws");
574 input.value = cockpit_authorize_parse_negotiate (authorization, &input.length);
575
576 if (!acquire_service_credentials (mech_type, GSS_C_ACCEPT, &server))
577 {
578 res = PAM_AUTHINFO_UNAVAIL;
579 goto out;
580 }
581
582 for (;;)
583 {
584 debug ("gssapi negotiation");
585
586 if (client != GSS_C_NO_CREDENTIAL)
587 gss_release_cred (&minor, &client);
588 if (name != GSS_C_NO_NAME)
589 gss_release_name (&minor, &name);
590 if (output.value)
591 gss_release_buffer (&minor, &output);
592
593 if (input.length > 0)
594 {
595 major = gss_accept_sec_context (&minor, &context, server, &input,
596 GSS_C_NO_CHANNEL_BINDINGS, &name, &mech_type,
597 &output, &flags, &caps, &client);
598 }
599 else
600 {
601 debug ("initial gssapi negotiate output");
602 major = GSS_S_CONTINUE_NEEDED;
603 }
604
605 /* Our exit code is a PAM result code */
606 if (GSS_ERROR (major))
607 {
608 res = PAM_AUTH_ERR;
609 warnx ("gssapi auth failed: %s", gssapi_strerror (mech_type, major, minor));
610 goto out;
611 }
612
613 if ((major & GSS_S_CONTINUE_NEEDED) == 0)
614 break;
615
616 challenge = cockpit_authorize_build_negotiate (output.value, output.length);
617 if (!challenge)
618 errx (EX, "couldn't encode negotiate challenge");
619 write_authorize_begin ();
620 write_control_string ("challenge", challenge);
621 write_control_end ();
622 cockpit_memory_clear (challenge, -1);
623 free (challenge);
624
625 /*
626 * The GSSAPI mechanism can require multiple challenge response
627 * iterations ... so do that here.
628 */
629 free (input.value);
630 input.length = 0;
631
632 debug ("need to continue gssapi negotiation");
633 char *authorize = read_authorize_response ("negotiate");
634 char *response = get_authorize_key (authorize, "response", false);
635 cockpit_memory_clear (authorize, -1);
636 free (authorize);
637
638 input.value = cockpit_authorize_parse_negotiate (response, &input.length);
639 if (response)
640 {
641 cockpit_memory_clear (response, -1);
642 free (response);
643 }
644 }
645
646 str = map_gssapi_to_local (name, mech_type);
647 if (!str)
648 goto out;
649
650 res = pam_start ("cockpit", str, &conv, &pamh);
651
652 if (res != PAM_SUCCESS)
653 errx (EX, "couldn't start pam: %s", pam_strerror (NULL, res));
654 if (pam_set_item (pamh, PAM_RHOST, rhost) != PAM_SUCCESS)
655 errx (EX, "couldn't setup pam");
656
657 res = open_session (pamh);
658 if (res != PAM_SUCCESS)
659 {
660 btmp_log (str, rhost);
661 goto out;
662 }
663
664 /* The creds are used and cleaned up later */
665 creds = client;
666
667 out:
668 if (output.value)
669 gss_release_buffer (&minor, &output);
670 if (export.value)
671 gss_release_buffer (&minor, &export);
672 if (server != GSS_C_NO_CREDENTIAL)
673 gss_release_cred (&minor, &server);
674 if (name != GSS_C_NO_NAME)
675 gss_release_name (&minor, &name);
676 if (context != GSS_C_NO_CONTEXT)
677 gss_delete_sec_context (&minor, &context, GSS_C_NO_BUFFER);
678 free (input.value);
679 free (str);
680
681 if (res != PAM_SUCCESS)
682 exit_pam_init_problem (res);
683
684 return pamh;
685 }
686
687 static int
688 pam_conv_func_dummy (int num_msg,
689 const struct pam_message **msg,
690 struct pam_response **ret_resp,
691 void *appdata_ptr)
692 {
693 /* we don't expect (nor can handle) any actual auth conversation here, but
694 * PAM sometimes sends messages like "Creating home directory for USER" */
695 for (int i = 0; i < num_msg; ++i)
696 debug ("got PAM conversation message, ignoring: %s", msg[i]->msg);
697 return PAM_CONV_ERR;
698 }
699
700 static void
701 create_s4u_ticket (const char *username)
702 {
703 OM_uint32 major, minor;
704 gss_cred_id_t server_cred = GSS_C_NO_CREDENTIAL;
705 gss_name_t impersonee = GSS_C_NO_NAME;
706
707 debug ("Attempting to create an S4U ticket for user %s", username);
708
709 if (!acquire_service_credentials (GSS_C_NO_OID, GSS_C_INITIATE, &server_cred))
710 goto out;
711
712 gss_buffer_desc user_buf = { .length = strlen (username), .value = (char *) username };
713 major = gss_import_name (&minor, &user_buf, GSS_KRB5_NT_PRINCIPAL_NAME, &impersonee);
714 if (GSS_ERROR (major))
715 {
716 warnx ("Failed to import user name %s: %s", username, gssapi_strerror (GSS_C_NO_OID, major, minor));
717 goto out;
718 }
719
720 /* store credentials into global creds; they will be put into the session and cleaned up in main() */
721 major = gss_acquire_cred_impersonate_name (&minor, server_cred, impersonee,
722 GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_INITIATE,
723 &creds, NULL, NULL);
724 if (GSS_ERROR (major))
725 {
726 warnx ("Failed to impersonate %s: %s", username, gssapi_strerror (GSS_C_NO_OID, major, minor));
727 goto out;
728 }
729
730 debug ("S4U ticket for user %s created successfully", username);
731
732 out:
733 if (server_cred != GSS_C_NO_CREDENTIAL)
734 gss_release_cred (&minor, &server_cred);
735 if (impersonee != GSS_C_NO_NAME)
736 gss_release_name(&minor, &impersonee);
737 }
738
739 static pam_handle_t *
740 perform_tlscert (const char *rhost,
741 const char *authorization)
742 {
743 struct pam_conv conv = { pam_conv_func_dummy, };
744 pam_handle_t *pamh;
745 int res;
746
747 assert (rhost != NULL);
748 assert (authorization != NULL);
749
750 debug ("start tls-cert authentication for cockpit-ws %u", getppid ());
751
752 /* True, otherwise we wouldn't be here. */
753 assert (strncmp (authorization, "tls-cert ", 9) == 0);
754 const char *client_certificate_filename = authorization + 9;
755
756 char *username = cockpit_session_client_certificate_map_user (client_certificate_filename);
757 assert (username != NULL);
758
759 res = pam_start ("cockpit", username, &conv, &pamh);
760 if (res != PAM_SUCCESS)
761 errx (EX, "couldn't start pam: %s", pam_strerror (NULL, res));
762
763 if (pam_set_item (pamh, PAM_RHOST, rhost) != PAM_SUCCESS)
764 errx (EX, "couldn't setup pam rhost");
765
766 res = open_session (pamh);
767
768 create_s4u_ticket (username);
769
770 free (username);
771
772 /* Our exit code is a PAM code */
773 if (res != PAM_SUCCESS)
774 exit_pam_init_problem (res);
775
776 return pamh;
777 }
778
779
780 /* Return path of ccache file (including FILE: prefix), clean this up at session end */
781 static char *
782 store_krb_credentials (gss_cred_id_t creds, uid_t uid, gid_t gid)
783 {
784 gss_key_value_set_desc store;
785 struct gss_key_value_element_struct element;
786 OM_uint32 major, minor;
787 char *ccache;
788
789 assert (creds != GSS_C_NO_CREDENTIAL);
790
791 bool was_root = getuid() == 0;
792
793 /* We want to do this before the fork(), so we need to temporarily
794 * change our euid/egid
795 */
796 if (setresgid (gid, gid, -1) != 0 || setresuid (uid, uid, -1) != 0)
797 err (127, "Unable to temporarily drop permissions to store gss credentials");
798
799 assert (geteuid () == uid && getegid() == gid);
800
801 /* The ccache path needs to be unique per cockpit session; as cockpit-session runs throughout the
802 * lifetime of sessions, our pid is unique. We expect the cache to be cleaned up at the end, but
803 * if not, and the PID gets recycled, this just overwrites the old obsolete one, which is good. */
804 asprintfx (&ccache, "FILE:/run/user/%u/cockpit-session-%u.ccache", uid, getpid ());
805 debug ("storing kerberos credentials in session: %s", ccache);
806
807 store.count = 1;
808 store.elements = &element;
809 element.key = "ccache";
810 element.value = ccache;
811
812 major = gss_store_cred_into (&minor, creds, GSS_C_INITIATE, GSS_C_NULL_OID, 1, 1, &store, NULL, NULL);
813 if (GSS_ERROR (major))
814 warnx ("couldn't store gssapi credentials: %s", gssapi_strerror (GSS_C_NO_OID, major, minor));
815
816 if (was_root && (setresuid (0, 0, 0) != 0 || setresgid (0, 0, 0) != 0))
817 err (127, "Unable to restore permissions after storing gss credentials");
818
819 return ccache;
820 }
821
822 static void
823 release_krb_credentials (char *ccache)
824 {
825 /* strip off FILE: prefix for deleting */
826 assert (strncmp (ccache, "FILE:", 5) == 0);
827 if (unlink (ccache + 5) != 0)
828 warn ("couldn't clean up kerberos ticket cache %s", ccache);
829 free (ccache);
830 }
831
832 static bool
833 user_has_valid_login_shell (const char **envp)
834 {
835 /* <lis> >>> random.randint(0,127)
836 * <lis> 71
837 * <pitti> https://xkcd.com/221/
838 */
839 const char *argv[] = { pwd->pw_shell, "-c", "exit 71;", NULL };
840 assert (argv[0] != NULL);
841
842 int devnull = open ("/dev/null", O_RDONLY);
843 if (devnull < 0)
844 err (EX, "couldn't open /dev/null");
845
846 const int remap_fds[] = { devnull, 2, -1 }; /* send stdout to stderr */
847 int wstatus;
848
849 wstatus = spawn_and_wait (argv, envp, remap_fds, 3, pwd->pw_uid, pwd->pw_gid);
850 debug ("user_has_valid_login_shell: exited with status %x", wstatus);
851 close (devnull);
852 if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 71)
853 return true;
854
855 warnx ("User %s shell (%s) does not understand 'exit 71', unsupported with Cockpit",
856 pwd->pw_name, pwd->pw_shell);
857 return false;
858 }
859
860 static void
861 save_environment (void)
862 {
863 const char *value;
864 int i, j;
865
866 /* Force save our default path */
867 if (!getenv ("COCKPIT_TEST_KEEP_PATH"))
868 setenv ("PATH", DEFAULT_SESSION_PATH, 1);
869
870 for (i = 0, j = 0; env_names[i] != NULL; i++)
871 {
872 value = getenv (env_names[i]);
873 if (value)
874 {
875 if (asprintf (env_saved + (j++), "%s=%s", env_names[i], value) < 0)
876 errx (42, "couldn't allocate environment");
877 }
878 }
879
880 env_saved[j] = NULL;
881 }
882
883 static void
884 pass_to_child (int signo)
885 {
886 if (child > 0)
887 kill (child, signo);
888 }
889
890 static void
891 on_authorize_timeout (int signo)
892 {
893 /* Can't use errx() here: https://man7.org/linux/man-pages/man7/signal-safety.7.html */
894 static const char msg[] = "timed out waiting for authorize response\n";
895 /* ignore write errors(-Wunused-result); if that fails, we can do absolutely nothing about it */
896 (void) !write (STDERR_FILENO, msg, sizeof (msg) - 1);
897 _exit(EX);
898 }
899
900 int
901 main (int argc,
902 char **argv)
903 {
904 pam_handle_t *pamh = NULL;
905 OM_uint32 minor;
906 char *type = NULL;
907 const char **env;
908 char *ccache = NULL;
909 int status;
910 int res;
911 int i;
912
913 if (isatty (0))
914 errx (2, "this command is not meant to be run from the console");
915
916 /* COMPAT: argv[1] used to be used, but is now ignored */
917 if (argc != 1 && argc != 2)
918 errx (2, "invalid arguments to cockpit-session");
919
920 /* the initial authorization response should not take forever, time-bound it to guard
921 * against hacking/PID recycling attempts */
922 sigaction (SIGALRM, &(struct sigaction) { .sa_handler = on_authorize_timeout, .sa_flags = 0 }, NULL);
923 alarm (60); /* like cockpit_ws_auth_response_timeout on the ws side */
924
925 program_name = basename (argv[0]);
926
927 save_environment ();
928
929 /* When setuid root, make sure our group is also root */
930 if (geteuid () == 0)
931 {
932 /* Always clear the environment */
933 if (clearenv () != 0)
934 err (1, "couldn't clear environment");
935
936 /* set a minimal environment */
937 setenv ("PATH", DEFAULT_SESSION_PATH, 1);
938
939 if (setgid (0) != 0 || setuid (0) != 0)
940 err (1, "couldn't switch permissions correctly");
941 }
942
943 cockpit_authorize_logger (authorize_logger, DEBUG_SESSION);
944
945 /* Request authorization header */
946 write_authorize_begin ();
947 write_control_string ("challenge", "*");
948 write_control_end ();
949
950 /* And get back the authorization header */
951 char *authorization = read_authorize_response ("authorization");
952 char *remote_peer = get_authorize_key (authorization, "remote-peer", false);
953 /* the functions below require a non-NULL rhost */
954 const char *rhost = remote_peer ?: "";
955 debug ("initial authorize response rhost: %s", rhost);
956 char *response = get_authorize_key (authorization, "response", true);
957 cockpit_memory_clear (authorization, -1);
958 free (authorization);
959
960 if (!cockpit_authorize_type (response, &type))
961 errx (EX, "invalid authorization header received");
962
963 /* stop time-bounding */
964 alarm (0);
965 sigaction (SIGALRM, &(struct sigaction) { .sa_handler = SIG_DFL, .sa_flags = 0 }, NULL);
966
967 if (strcmp (type, "basic") == 0)
968 pamh = perform_basic (rhost, response);
969 else if (strcmp (type, "negotiate") == 0)
970 pamh = perform_gssapi (rhost, response);
971 else if (strcmp (type, "tls-cert") == 0)
972 pamh = perform_tlscert (rhost, response);
973
974 cockpit_memory_clear (response, -1);
975 free (response);
976
977 if (!pamh)
978 errx (2, "unrecognized authentication method: %s", type);
979
980 free (type);
981
982 for (i = 0; env_saved[i] != NULL; i++)
983 pam_putenv (pamh, env_saved[i]);
984
985 if (want_session) /* no session → no login messages or XDG_RUNTIME_DIR → no memfd or session ccache */
986 {
987 if (pam_putenv (pamh, "COCKPIT_LOGIN_MESSAGES_MEMFD=3") != PAM_SUCCESS)
988 errx (EX, "Failed to set COCKPIT_LOGIN_MESSAGES_MEMFD=3 in PAM environment");
989
990 if (creds != GSS_C_NO_CREDENTIAL)
991 {
992 ccache = store_krb_credentials (creds, pwd->pw_uid, pwd->pw_gid);
993 char *ccache_env = NULL;
994 asprintfx (&ccache_env, "KRB5CCNAME=%s", ccache);
995
996 if (pam_putenv (pamh, ccache_env) != PAM_SUCCESS)
997 errx (EX, "Failed to set KRB5CCNAME in PAM environment");
998 free (ccache_env);
999 }
1000 }
1001
1002 env = (const char **) pam_getenvlist (pamh);
1003 if (env == NULL)
1004 errx (EX, "get pam environment failed");
1005
1006 const char *bridge_argv[] = { "cockpit-bridge", NULL };
1007
1008 if (want_session)
1009 {
1010 assert (pwd != NULL);
1011
1012 if (initgroups (pwd->pw_name, pwd->pw_gid) < 0)
1013 err (EX, "%s: can't init groups", pwd->pw_name);
1014
1015 if (!user_has_valid_login_shell (env))
1016 {
1017 const char *msg = "\n{\"command\":\"init\",\"version\":1,\"problem\":\"unsupported-shell\"}";
1018 if (cockpit_frame_write (STDOUT_FILENO, (unsigned char *)msg, strlen (msg)) < 0)
1019 err (EX, "couldn't write init message");
1020
1021 exit_pam_init_problem (PAM_PERM_DENIED);
1022 }
1023
1024 signal (SIGTERM, pass_to_child);
1025 signal (SIGINT, pass_to_child);
1026 signal (SIGQUIT, pass_to_child);
1027 signal (SIGHUP, pass_to_child);
1028
1029 FILE *login_messages = cockpit_json_print_open_memfd ("cockpit login messages", 1);
1030
1031 utmp_log (1, rhost, login_messages);
1032
1033 int login_messages_fd = cockpit_json_print_finish_memfd (&login_messages);
1034
1035 const int remap_fds[] = { -1, -1, -1, login_messages_fd };
1036 status = spawn_and_wait (bridge_argv, env, remap_fds, 4, pwd->pw_uid, pwd->pw_gid);
1037
1038 utmp_log (0, rhost, NULL);
1039
1040 signal (SIGTERM, SIG_DFL);
1041 signal (SIGINT, SIG_DFL);
1042 signal (SIGQUIT, SIG_DFL);
1043 signal (SIGHUP, SIG_DFL);
1044
1045 close (login_messages_fd);
1046
1047 res = pam_setcred (pamh, PAM_DELETE_CRED);
1048 if (res != PAM_SUCCESS)
1049 err (EX, "%s: couldn't delete creds: %s", pwd->pw_name, pam_strerror (pamh, res));
1050 res = pam_close_session (pamh, 0);
1051 if (res != PAM_SUCCESS)
1052 err (EX, "%s: couldn't close session: %s", pwd->pw_name, pam_strerror (pamh, res));
1053 if (ccache)
1054 release_krb_credentials (ccache);
1055 }
1056 else
1057 {
1058 status = spawn_and_wait (bridge_argv, env, NULL, -1, pwd->pw_uid, pwd->pw_gid);
1059 }
1060
1061
1062 /* translate no-cockpit error for the UI, as the precise status cannot be propagated
1063 * through the session Unix socket */
1064 if (WIFEXITED (status) && WEXITSTATUS (status) == EXIT_NOT_FOUND)
1065 {
1066 debug ("bridge exited with status %d, no-cockpit", status);
1067 const char *no_cockpit = "\n{\"command\":\"init\",\"version\":1,\"problem\":\"no-cockpit\",\"message\":\"cockpit-bridge not found\"}";
1068 if (cockpit_frame_write (STDOUT_FILENO, (unsigned char *)no_cockpit, strlen (no_cockpit)) < 0)
1069 err (EX, "couldn't write init message");
1070 }
1071 else
1072 {
1073 debug ("bridge exited with status %d", status);
1074 }
1075
1076 pam_end (pamh, PAM_SUCCESS);
1077
1078 rhost = NULL;
1079 free (remote_peer);
1080 remote_peer = NULL;
1081 free (last_err_msg);
1082 last_err_msg = NULL;
1083 free (last_txt_msg);
1084 last_txt_msg = NULL;
1085 free (conversation);
1086 conversation = NULL;
1087
1088 if (creds != GSS_C_NO_CREDENTIAL)
1089 gss_release_cred (&minor, &creds);
1090
1091 if (WIFEXITED(status))
1092 exit (WEXITSTATUS(status));
1093 else if (WIFSIGNALED(status))
1094 raise (WTERMSIG(status));
1095 else
1096 exit (EX);
1097 }