Debian Codegraph @

src/ws/test-kerberos.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 "cockpitauth.h"
9 #include "cockpitws.h"
10
11 #include "cockpitwebserver.h"
12 #include "cockpitwebrequest-private.h"
13
14 #include "testlib/cockpittest.h"
15
16 #include <krb5/krb5.h>
17 #include <gssapi/gssapi_krb5.h>
18
19 #include <sys/prctl.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 static gboolean mock_kdc_available;
28
29 static void mock_kdc_up (void);
30
31 static void mock_kdc_down (void);
32
33 typedef struct {
34 CockpitAuth *auth;
35 krb5_context krb;
36 krb5_ccache ccache;
37 char *ccache_name;
38 } TestCase;
39
40 static void
41 setup (TestCase *test,
42 gconstpointer data)
43 {
44 krb5_get_init_creds_opt *opt;
45 krb5_principal principal;
46 krb5_error_code code;
47 krb5_creds creds;
48 OM_uint32 status;
49 OM_uint32 minor;
50 gchar *name;
51
52 if (!mock_kdc_available)
53 return;
54
55 test->auth = cockpit_auth_new (FALSE, COCKPIT_AUTH_NONE);
56
57 mock_kdc_up ();
58
59 code = krb5_init_context (&test->krb);
60 g_assert (code != ENOMEM);
61 if (code != 0)
62 {
63 g_critical ("couldn't create krb context: %s", krb5_get_error_message (NULL, code));
64 return;
65 }
66
67 /* Initialize the client credential cache */
68 if (krb5_cc_new_unique (test->krb, "MEMORY", NULL, &test->ccache) != 0)
69 g_assert_not_reached ();
70
71 name = g_strdup_printf ("%[email protected]", g_get_user_name ());
72
73 /* Do a kerberos authentication */
74 if (krb5_parse_name (test->krb, name, &principal))
75 g_assert_not_reached ();
76 if (krb5_get_init_creds_opt_alloc (test->krb, &opt))
77 g_assert_not_reached ();
78 if (krb5_get_init_creds_opt_set_out_ccache (test->krb, opt, test->ccache))
79 g_assert_not_reached ();
80
81 code = krb5_get_init_creds_password (test->krb, &creds, principal, "marmalade",
82 NULL, NULL, 0, NULL, opt);
83
84 krb5_free_principal (test->krb, principal);
85 krb5_get_init_creds_opt_free (test->krb, opt);
86
87 g_assert (code != ENOMEM);
88 if (code != 0)
89 {
90 g_critical ("couldn't kinit for %s: %s", name, krb5_get_error_message (test->krb, code));
91 return;
92 }
93
94 krb5_free_cred_contents (test->krb, &creds);
95 g_free (name);
96
97 if (krb5_cc_get_full_name (test->krb, test->ccache, &test->ccache_name) != 0)
98 g_assert_not_reached ();
99
100 /* Sets the credential cache GSSAPI to use (for this thread) */
101 status = gss_krb5_ccache_name (&minor, test->ccache_name, NULL);
102 g_assert_cmpint (status, ==, 0);
103 }
104
105 static void
106 teardown (TestCase *test,
107 gconstpointer data)
108 {
109 if (!mock_kdc_available)
110 return;
111
112 if (test->ccache)
113 krb5_cc_close (test->krb, test->ccache);
114 if (test->ccache_name)
115 krb5_free_string (test->krb, test->ccache_name);
116 if (test->krb)
117 krb5_free_context (test->krb);
118
119 mock_kdc_down ();
120
121 g_clear_object (&test->auth);
122 }
123
124 static void
125 on_ready_get_result (GObject *source,
126 GAsyncResult *result,
127 gpointer user_data)
128 {
129 GAsyncResult **retval = user_data;
130 g_assert (retval != NULL);
131 g_assert (*retval == NULL);
132 *retval = g_object_ref (result);
133 }
134
135 static void
136 assert_gss_status_msg (const gchar *domain,
137 const gchar *file,
138 gint line,
139 const gchar *func,
140 const gchar *expr,
141 const gchar *cmp,
142 OM_uint32 expected,
143 OM_uint32 major_status,
144 OM_uint32 minor_status)
145 {
146 OM_uint32 major, minor;
147 OM_uint32 ctx = 0;
148 gss_buffer_desc status;
149 gboolean had_minor;
150 GString *result;
151
152 result = g_string_new ("");
153 g_string_printf (result, "assertion failed (%s): (%u %s %u)",
154 expr, (guint)expected, cmp, (guint)major_status);
155
156 for (;;)
157 {
158 major = gss_display_status (&minor, major_status, GSS_C_GSS_CODE,
159 GSS_C_NO_OID, &ctx, &status);
160 if (GSS_ERROR (major))
161 break;
162
163 if (result->len > 0)
164 g_string_append (result, ": ");
165
166 g_string_append_len (result, status.value, status.length);
167 gss_release_buffer (&minor, &status);
168
169 if (!ctx)
170 break;
171 }
172
173 ctx = 0;
174 had_minor = FALSE;
175 for (;;)
176 {
177 major = gss_display_status (&minor, minor_status, GSS_C_MECH_CODE,
178 GSS_C_NULL_OID, &ctx, &status);
179 if (GSS_ERROR (major))
180 break;
181
182 if (status.length)
183 {
184 if (!had_minor)
185 g_string_append (result, " (");
186 else
187 g_string_append (result, ", ");
188 had_minor = TRUE;
189 g_string_append_len (result, status.value, status.length);
190 }
191
192 gss_release_buffer (&minor, &status);
193
194 if (!ctx)
195 break;
196 }
197
198 if (had_minor)
199 g_string_append (result, ")");
200
201 g_assertion_message (domain, file ,line, func, result->str);
202 g_string_free (result, TRUE);
203 }
204
205 #define assert_gss_status(status, cmp, expect, minor) \
206 do { OM_uint32 __st = (status); OM_uint32 __ex = (expect); \
207 if (__st cmp __ex) ; else \
208 assert_gss_status_msg (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
209 #expect " " #cmp " " #status, #cmp, (__ex), (__st), (minor)); \
210 } while (0);
211
212 static void
213 build_authorization_header (GHashTable *headers,
214 gss_buffer_desc *buffer)
215 {
216 gchar *encoded;
217 gchar *value;
218
219 if (buffer->length)
220 {
221 encoded = g_base64_encode (buffer->value, buffer->length);
222 value = g_strdup_printf ("Negotiate %s", encoded);
223 g_free (encoded);
224 }
225 else
226 {
227 value = g_strdup ("Negotiate");
228 }
229
230 g_hash_table_replace (headers, g_strdup ("Authorization"), value);
231 }
232
233 static void
234 include_cookie_as_if_client (GHashTable *resp_headers,
235 GHashTable *req_headers)
236 {
237 gchar *cookie;
238 gchar *end;
239
240 cookie = g_strdup (g_hash_table_lookup (resp_headers, "Set-Cookie"));
241 g_assert (cookie != NULL);
242 end = strchr (cookie, ';');
243 g_assert (end != NULL);
244 end[0] = '\0';
245
246 g_hash_table_insert (req_headers, g_strdup ("Cookie"), cookie);
247 }
248
249 static void
250 test_authenticate (TestCase *test,
251 gconstpointer data)
252 {
253 GHashTable *in_headers;
254 GHashTable *out_headers;
255 GAsyncResult *result = NULL;
256 gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
257 OM_uint32 status;
258 OM_uint32 minor;
259 gss_buffer_desc input = GSS_C_EMPTY_BUFFER;
260 gss_buffer_desc output = GSS_C_EMPTY_BUFFER;
261 gss_name_t name = GSS_C_NO_NAME;
262 OM_uint32 flags = 0;
263 CockpitCreds *creds;
264 CockpitWebService *service;
265 JsonObject *response;
266 GError *error = NULL;
267
268 cockpit_test_setenv ("COCKPIT_TEST_KEEP_PATH", "1");
269 cockpit_test_setenv ("COCKPIT_TEST_KEEP_KTAB", "1");
270
271 if (!mock_kdc_available)
272 {
273 g_test_skip ("mock kdc not available to test against");
274 return;
275 }
276
277 in_headers = cockpit_web_server_new_table ();
278 out_headers = cockpit_web_server_new_table ();
279
280 input.value = "host@localhost";
281 input.length = strlen (input.value) + 1;
282 status = gss_import_name (&minor, &input, GSS_C_NT_HOSTBASED_SERVICE, &name);
283 assert_gss_status (status, ==, GSS_S_COMPLETE, minor);
284
285 input.length = 0;
286 status = gss_init_sec_context (&minor, GSS_C_NO_CREDENTIAL, &ctx, name, GSS_C_NO_OID,
287 GSS_C_MUTUAL_FLAG, GSS_C_INDEFINITE, GSS_C_NO_CHANNEL_BINDINGS,
288 &input, NULL, &output, &flags, NULL);
289 assert_gss_status (status, ==, GSS_S_CONTINUE_NEEDED, minor);
290
291 build_authorization_header (in_headers, &output);
292 gss_release_buffer (&minor, &output);
293
294 cockpit_auth_login_async (test->auth, WebRequest(.path="/cockpit+test", .headers=in_headers), on_ready_get_result, &result);
295 g_hash_table_unref (in_headers);
296
297 while (result == NULL)
298 g_main_context_iteration (NULL, TRUE);
299
300 response = cockpit_auth_login_finish (test->auth, result, NULL, out_headers, &error);
301 g_object_unref (result);
302 g_assert_no_error (error);
303 g_assert (response != NULL);
304 json_object_unref (response);
305
306 gss_release_name (&minor, &name);
307 gss_delete_sec_context (&minor, &ctx, &output);
308
309 include_cookie_as_if_client (out_headers, out_headers);
310
311 service = cockpit_auth_check_cookie (test->auth, WebRequest(.path="/cockpit+test", .headers=out_headers));
312 g_assert (service != NULL);
313
314 creds = cockpit_web_service_get_creds (service);
315 g_assert_cmpstr ("cockpit+test", ==, cockpit_creds_get_application (creds));
316 g_assert (NULL == cockpit_creds_get_password (creds));
317
318 g_unsetenv ("COCKPIT_TEST_KEEP_PATH");
319
320 g_hash_table_unref (out_headers);
321 g_object_unref (service);
322 }
323
324 struct {
325 GHashTable *environ;
326 gboolean stopped;
327 GPid pid;
328 } mock_kdc;
329
330 static void
331 on_kdc_child (GPid pid,
332 gint status,
333 gpointer user_data)
334 {
335 GError *error = NULL;
336
337 mock_kdc_available = FALSE;
338 if (!mock_kdc.stopped)
339 {
340 g_spawn_check_exit_status (status, &error);
341 g_assert_no_error (error);
342 g_critical ("mock-kdc exited prematurely");
343 }
344 }
345
346 static void
347 on_kdc_setup (gpointer user_data)
348 {
349 /* Kill all sub processes when this process exits */
350 if (prctl (PR_SET_PDEATHSIG, SIGTERM) < 0)
351 g_critical ("prctl failed: %s", g_strerror (errno));
352
353 /* Start a new session for this process */
354 setsid ();
355 }
356
357 static void
358 mock_kdc_start (void)
359 {
360 GString *input;
361 GError *error = NULL;
362 gint out_fd;
363 gsize len;
364 gssize ret;
365 gchar **vars;
366 gchar *pos;
367 gint i;
368
369 const gchar *argv[] = {
370 SRCDIR "/src/ws/mock-kdc",
371 NULL
372 };
373
374 mock_kdc_available = FALSE;
375
376 g_spawn_async_with_pipes (BUILDDIR, (gchar **)argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD,
377 on_kdc_setup, NULL, &mock_kdc.pid, NULL, &out_fd, NULL, &error);
378 g_assert_no_error (error);
379
380 g_child_watch_add (mock_kdc.pid, on_kdc_child, NULL);
381
382 /*
383 * mock-kdc prints environment vars on stdout, and then closes stdout
384 * This also lets us know when it has initialized.
385 */
386 input = g_string_new ("");
387 for (;;)
388 {
389 len = input->len;
390 g_string_set_size (input, len + 256);
391 ret = read (out_fd, input->str + len, 256);
392 if (ret < 0)
393 {
394 if (errno == EAGAIN || errno == EINTR)
395 continue;
396
397 g_error ("couldn't read from mock-kdc: %s", g_strerror (errno));
398 break;
399 }
400
401 g_string_set_size (input, len + ret);
402 if (strstr (input->str, "starting..."))
403 {
404 mock_kdc_available = TRUE;
405 break;
406 }
407 else if (ret == 0)
408 {
409 break;
410 }
411 }
412
413 /* Parse into a table of environment variables */
414 mock_kdc.environ = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
415 vars = g_strsplit (input->str, "\n", -1);
416 for (i = 0; vars[i] != NULL; i++)
417 {
418 pos = strchr (vars[i], '=');
419 if (pos)
420 {
421 *pos = '\0';
422 g_hash_table_replace (mock_kdc.environ, vars[i], pos + 1);
423 }
424 else
425 {
426 g_free (vars[i]);
427 }
428 }
429
430 g_string_free (input, TRUE);
431 g_free (vars);
432 }
433
434 static void
435 mock_kdc_up (void)
436 {
437 GHashTableIter iter;
438 const gchar *name;
439 const gchar *value;
440 g_hash_table_iter_init (&iter, mock_kdc.environ);
441 while (g_hash_table_iter_next (&iter, (gpointer *)&name, (gpointer *)&value))
442 cockpit_test_setenv (name, value);
443
444 /* Explicitly tell server side of GSSAPI about our keytab */
445 value = g_hash_table_lookup (mock_kdc.environ, "KRB5_KTNAME");
446 if (value)
447 cockpit_test_setenv ("KRB5_KTNAME", value);
448 }
449
450 static void
451 mock_kdc_down (void)
452 {
453 GHashTableIter iter;
454 const gchar *name;
455 g_hash_table_iter_init (&iter, mock_kdc.environ);
456 while (g_hash_table_iter_next (&iter, (gpointer *)&name, NULL))
457 g_unsetenv (name);
458 }
459
460 static void
461 mock_kdc_stop (void)
462 {
463 mock_kdc.stopped = TRUE;
464 if (mock_kdc_available)
465 {
466 if (kill (-mock_kdc.pid, SIGTERM) < 0)
467 g_error ("couldn't kill mock-kdc: %s", g_strerror (errno));
468 }
469 if (mock_kdc.environ)
470 g_hash_table_destroy (mock_kdc.environ);
471 }
472
473 int
474 main (int argc,
475 char *argv[])
476 {
477 int ret;
478
479 cockpit_ws_session_program = BUILDDIR "/cockpit-session";
480
481 cockpit_test_init (&argc, &argv);
482
483 if (g_strcmp0 (g_get_user_name (), "root") != 0)
484 mock_kdc_start ();
485
486 g_test_add ("/kerberos/authenticate", TestCase, NULL,
487 setup, test_authenticate, teardown);
488
489 ret = g_test_run ();
490
491 mock_kdc_stop ();
492
493 return ret;
494 }