1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2009 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
25 #include <glib/gi18n.h>
27 #include "gdbusauth.h"
28 #include "gdbusauthmechanismanon.h"
29 #include "gdbusauthmechanismexternal.h"
30 #include "gdbusauthmechanismsha1.h"
32 #include "gdbusauthobserver.h"
34 #include "gdbuserror.h"
35 #include "gdbusutils.h"
36 #include "gioenumtypes.h"
37 #include "gcredentials.h"
38 #include "gdbusprivate.h"
41 #include <gio/gunixconnection.h>
42 #include "gunixcredentialsmessage.h"
43 #include <sys/types.h>
44 #include <sys/socket.h>
47 #define DEBUG_ENABLED 1
50 debug_print (const gchar *message, ...)
53 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
60 va_start (var_args, message);
61 s = g_strdup_vprintf (message, var_args);
64 str = g_string_new (NULL);
65 for (n = 0; s[n] != '\0'; n++)
67 if (G_UNLIKELY (s[n] == '\r'))
68 g_string_append (str, "\\r");
69 else if (G_UNLIKELY (s[n] == '\n'))
70 g_string_append (str, "\\n");
72 g_string_append_c (str, s[n]);
74 g_print ("GDBus-debug:Auth: %s\n", str->str);
75 g_string_free (str, TRUE);
82 /* ---------------------------------------------------------------------------------------------------- */
83 /* TODO: move to gio */
86 * g_unix_connection_send_credentials:
87 * @connection: A #GUnixConnection.
88 * @credentials: A #GCredentials to send.
89 * @cancellable: A #GCancellable or %NULL.
90 * @error: Return location for error or %NULL.
92 * Passes the credentials stored in @credentials to the recieving side
93 * of the connection. The recieving end has to call
94 * g_unix_connection_receive_credentials() (or similar) to accept the
97 * The credentials which the sender specifies are checked by the
98 * kernel. A process with effective user ID 0 is allowed to specify
99 * values that do not match its own. This means that the credentials
100 * can be used to authenticate other connections.
102 * As well as sending the credentials this also writes a single NUL
103 * byte to the stream, as this is required for credentials passing to
104 * work on some implementations.
106 * Returns: %TRUE on success, %FALSE if @error is set.
111 g_unix_connection_send_credentials (GUnixConnection *connection,
112 GCredentials *credentials,
113 GCancellable *cancellable,
116 GSocketControlMessage *scm;
119 GOutputVector vector;
120 guchar nul_byte[1] = {'\0'};
122 g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), FALSE);
123 g_return_val_if_fail (G_IS_CREDENTIALS (credentials), FALSE);
124 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
128 vector.buffer = &nul_byte;
130 scm = g_unix_credentials_message_new_with_credentials (credentials);
131 g_object_get (connection, "socket", &socket, NULL);
132 if (g_socket_send_message (socket,
142 g_prefix_error (error, _("Error sending credentials: "));
149 g_object_unref (socket);
150 g_object_unref (scm);
155 * g_unix_connection_receive_credentials:
156 * @connection: A #GUnixConnection.
157 * @cancellable: A #GCancellable or %NULL.
158 * @error: Return location for error or %NULL.
160 * Receives credentials from the sending end of the connection. The
161 * sending end has to call g_unix_connection_send_credentials() (or
162 * similar) for this to work.
164 * As well as reading the credentials this also reads (and discards) a
165 * single byte from the stream, as this is required for credentials
166 * passing to work on some implementations.
168 * Returns: Received credentials on success (free with
169 * g_object_unref()), %NULL if @error is set.
173 static GCredentials *
174 g_unix_connection_receive_credentials (GUnixConnection *connection,
175 GCancellable *cancellable,
179 GSocketControlMessage **scms;
183 volatile GType credentials_message_gtype;
184 gssize num_bytes_read;
186 g_return_val_if_fail (G_IS_UNIX_CONNECTION (connection), NULL);
187 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
192 g_object_get (connection, "socket", &socket, NULL);
195 /* TODO: Move this to gsocket.c... */
198 if (setsockopt (g_socket_get_fd (socket),
202 sizeof opt_val) != 0)
204 g_warning ("boo, error setting SO_PASSCRED: %m");
209 /* ensure the type of GUnixCredentialsMessage has been registered with the type system */
210 credentials_message_gtype = G_TYPE_UNIX_CREDENTIALS_MESSAGE;
211 num_bytes_read = g_socket_receive_message (socket,
212 NULL, /* GSocketAddress **address */
220 if (num_bytes_read != 1)
222 /* Handle situation where g_socket_receive_message() returns
223 * 0 bytes and not setting @error
225 if (num_bytes_read == 0 && error != NULL && *error == NULL)
227 g_set_error_literal (error,
230 _("Expecting to read a single byte for receiving credentials but read zero bytes"));
240 _("Expecting 1 control message, got %d"),
245 if (!G_IS_UNIX_CREDENTIALS_MESSAGE (scms[0]))
247 g_set_error_literal (error,
250 _("Unexpected type of ancillary data"));
254 ret = g_unix_credentials_message_get_credentials (G_UNIX_CREDENTIALS_MESSAGE (scms[0]));
260 for (n = 0; n < nscm; n++)
261 g_object_unref (scms[n]);
264 g_object_unref (socket);
268 /* ---------------------------------------------------------------------------------------------------- */
277 static void mechanism_free (Mechanism *m);
279 struct _GDBusAuthPrivate
283 /* A list of available Mechanism, sorted according to priority */
284 GList *available_mechanisms;
293 G_DEFINE_TYPE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT);
295 /* ---------------------------------------------------------------------------------------------------- */
298 _g_dbus_auth_finalize (GObject *object)
300 GDBusAuth *auth = G_DBUS_AUTH (object);
302 if (auth->priv->stream != NULL)
303 g_object_unref (auth->priv->stream);
304 g_list_foreach (auth->priv->available_mechanisms, (GFunc) mechanism_free, NULL);
305 g_list_free (auth->priv->available_mechanisms);
307 if (G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize != NULL)
308 G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize (object);
312 _g_dbus_auth_get_property (GObject *object,
317 GDBusAuth *auth = G_DBUS_AUTH (object);
322 g_value_set_object (value, auth->priv->stream);
326 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
332 _g_dbus_auth_set_property (GObject *object,
337 GDBusAuth *auth = G_DBUS_AUTH (object);
342 auth->priv->stream = g_value_dup_object (value);
346 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
352 _g_dbus_auth_class_init (GDBusAuthClass *klass)
354 GObjectClass *gobject_class;
356 g_type_class_add_private (klass, sizeof (GDBusAuthPrivate));
358 gobject_class = G_OBJECT_CLASS (klass);
359 gobject_class->get_property = _g_dbus_auth_get_property;
360 gobject_class->set_property = _g_dbus_auth_set_property;
361 gobject_class->finalize = _g_dbus_auth_finalize;
363 g_object_class_install_property (gobject_class,
365 g_param_spec_object ("stream",
367 _("The underlying GIOStream used for I/O"),
371 G_PARAM_CONSTRUCT_ONLY |
372 G_PARAM_STATIC_NAME |
373 G_PARAM_STATIC_BLURB |
374 G_PARAM_STATIC_NICK));
378 mechanism_free (Mechanism *m)
384 add_mechanism (GDBusAuth *auth,
385 GType mechanism_type)
389 m = g_new0 (Mechanism, 1);
390 m->name = _g_dbus_auth_mechanism_get_name (mechanism_type);
391 m->priority = _g_dbus_auth_mechanism_get_priority (mechanism_type);
392 m->gtype = mechanism_type;
394 auth->priv->available_mechanisms = g_list_prepend (auth->priv->available_mechanisms, m);
398 mech_compare_func (Mechanism *a, Mechanism *b)
401 /* ensure deterministic order */
402 ret = b->priority - a->priority;
404 ret = g_strcmp0 (b->name, a->name);
409 _g_dbus_auth_init (GDBusAuth *auth)
411 auth->priv = G_TYPE_INSTANCE_GET_PRIVATE (auth, G_TYPE_DBUS_AUTH, GDBusAuthPrivate);
413 /* TODO: trawl extension points */
414 add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_ANON);
415 add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_SHA1);
416 add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_EXTERNAL);
418 auth->priv->available_mechanisms = g_list_sort (auth->priv->available_mechanisms,
419 (GCompareFunc) mech_compare_func);
423 find_mech_by_name (GDBusAuth *auth,
431 for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
433 Mechanism *m = l->data;
434 if (g_strcmp0 (name, m->name) == 0)
446 _g_dbus_auth_new (GIOStream *stream)
448 return g_object_new (G_TYPE_DBUS_AUTH,
453 /* ---------------------------------------------------------------------------------------------------- */
454 /* like g_data_input_stream_read_line() but sets error if there's no content to read */
456 _my_g_data_input_stream_read_line (GDataInputStream *dis,
457 gsize *out_line_length,
458 GCancellable *cancellable,
463 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
465 ret = g_data_input_stream_read_line (dis,
469 if (ret == NULL && error != NULL && *error == NULL)
471 g_set_error_literal (error,
474 _("Unexpected lack of content trying to read a line"));
480 /* This function is to avoid situations like this
482 * BEGIN\r\nl\0\0\1...
484 * e.g. where we read into the first D-Bus message while waiting for
485 * the final line from the client (TODO: file bug against gio for
489 _my_g_input_stream_read_line_safe (GInputStream *i,
490 gsize *out_line_length,
491 GCancellable *cancellable,
497 gboolean last_was_cr;
499 str = g_string_new (NULL);
504 num_read = g_input_stream_read (i,
513 if (error != NULL && *error == NULL)
515 g_set_error_literal (error,
518 _("Unexpected lack of content trying to (safely) read a line"));
523 g_string_append_c (str, (gint) c);
528 g_assert (str->len >= 2);
529 g_string_set_size (str, str->len - 2);
533 last_was_cr = (c == 0x0d);
537 if (out_line_length != NULL)
538 *out_line_length = str->len;
539 return g_string_free (str, FALSE);
542 g_assert (error == NULL || *error != NULL);
543 g_string_free (str, TRUE);
547 /* ---------------------------------------------------------------------------------------------------- */
550 append_nibble (GString *s, gint val)
552 g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
556 hexdecode (const gchar *str,
565 s = g_string_new (NULL);
567 for (n = 0; str[n] != '\0'; n += 2)
573 upper_nibble = g_ascii_xdigit_value (str[n]);
574 lower_nibble = g_ascii_xdigit_value (str[n + 1]);
575 if (upper_nibble == -1 || lower_nibble == -1)
580 "Error hexdecoding string `%s' around position %d",
584 value = (upper_nibble<<4) | lower_nibble;
585 g_string_append_c (s, value);
588 ret = g_string_free (s, FALSE);
593 g_string_free (s, TRUE);
599 hexencode (const gchar *str)
604 s = g_string_new (NULL);
605 for (n = 0; str[n] != '\0'; n++)
611 val = ((const guchar *) str)[n];
612 upper_nibble = val >> 4;
613 lower_nibble = val & 0x0f;
615 append_nibble (s, upper_nibble);
616 append_nibble (s, lower_nibble);
619 return g_string_free (s, FALSE);
622 /* ---------------------------------------------------------------------------------------------------- */
624 static GDBusAuthMechanism *
625 client_choose_mech_and_send_initial_response (GDBusAuth *auth,
626 GCredentials *credentials_that_were_sent,
627 const gchar* const *supported_auth_mechs,
628 GPtrArray *attempted_auth_mechs,
629 GDataOutputStream *dos,
630 GCancellable *cancellable,
633 GDBusAuthMechanism *mech;
634 GType auth_mech_to_use_gtype;
637 gchar *initial_response;
638 gsize initial_response_len;
645 debug_print ("CLIENT: Trying to choose mechanism");
647 /* find an authentication mechanism to try, if any */
648 auth_mech_to_use_gtype = (GType) 0;
649 for (n = 0; supported_auth_mechs[n] != NULL; n++)
651 gboolean attempted_already;
652 attempted_already = FALSE;
653 for (m = 0; m < attempted_auth_mechs->len; m++)
655 if (g_strcmp0 (supported_auth_mechs[n], attempted_auth_mechs->pdata[m]) == 0)
657 attempted_already = TRUE;
661 if (!attempted_already)
663 auth_mech_to_use_gtype = find_mech_by_name (auth, supported_auth_mechs[n]);
664 if (auth_mech_to_use_gtype != (GType) 0)
669 if (auth_mech_to_use_gtype == (GType) 0)
675 debug_print ("CLIENT: Exhausted all available mechanisms");
677 available = g_strjoinv (", ", (gchar **) supported_auth_mechs);
679 tried_str = g_string_new (NULL);
680 for (n = 0; n < attempted_auth_mechs->len; n++)
683 g_string_append (tried_str, ", ");
684 g_string_append (tried_str, attempted_auth_mechs->pdata[n]);
689 _("Exhausted all available authentication mechanisms (tried: %s) (available: %s)"),
692 g_string_free (tried_str, TRUE);
697 /* OK, decided on a mechanism - let's do this thing */
698 mech = g_object_new (auth_mech_to_use_gtype,
699 "stream", auth->priv->stream,
700 "credentials", credentials_that_were_sent,
702 debug_print ("CLIENT: Trying mechanism `%s'", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
703 g_ptr_array_add (attempted_auth_mechs, (gpointer) _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
705 /* the auth mechanism may not be supported
706 * (for example, EXTERNAL only works if credentials were exchanged)
708 if (!_g_dbus_auth_mechanism_is_supported (mech))
710 debug_print ("CLIENT: Mechanism `%s' says it is not supported", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
711 g_object_unref (mech);
716 initial_response_len = -1;
717 initial_response = _g_dbus_auth_mechanism_client_initiate (mech,
718 &initial_response_len);
720 g_printerr ("using auth mechanism with name `%s' of type `%s' with initial response `%s'\n",
721 _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
722 g_type_name (G_TYPE_FROM_INSTANCE (mech)),
725 if (initial_response != NULL)
727 //g_printerr ("initial_response = `%s'\n", initial_response);
728 encoded = hexencode (initial_response);
729 s = g_strdup_printf ("AUTH %s %s\r\n",
730 _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
732 g_free (initial_response);
737 s = g_strdup_printf ("AUTH %s\r\n", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
739 debug_print ("CLIENT: writing `%s'", s);
740 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
742 g_object_unref (mech);
754 /* ---------------------------------------------------------------------------------------------------- */
758 CLIENT_STATE_WAITING_FOR_DATA,
759 CLIENT_STATE_WAITING_FOR_OK,
760 CLIENT_STATE_WAITING_FOR_REJECT,
761 CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD
765 _g_dbus_auth_run_client (GDBusAuth *auth,
766 GDBusCapabilityFlags offered_capabilities,
767 GDBusCapabilityFlags *out_negotiated_capabilities,
768 GCancellable *cancellable,
772 GDataInputStream *dis;
773 GDataOutputStream *dos;
774 GCredentials *credentials;
778 gchar **supported_auth_mechs;
779 GPtrArray *attempted_auth_mechs;
780 GDBusAuthMechanism *mech;
782 GDBusCapabilityFlags negotiated_capabilities;
784 debug_print ("CLIENT: initiating");
787 supported_auth_mechs = NULL;
788 attempted_auth_mechs = g_ptr_array_new ();
790 negotiated_capabilities = 0;
793 dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
794 dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
796 g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
799 if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
801 credentials = g_credentials_new_for_process ();
802 if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (auth->priv->stream),
810 if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
814 if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
818 if (credentials != NULL)
820 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
822 s = g_credentials_to_string (credentials);
823 debug_print ("CLIENT: sent credentials `%s'", s);
829 debug_print ("CLIENT: didn't send any credentials");
832 /* TODO: to reduce rountrips, try to pick an auth mechanism to start with */
834 /* Get list of supported authentication mechanisms */
836 debug_print ("CLIENT: writing `%s'", s);
837 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
839 state = CLIENT_STATE_WAITING_FOR_REJECT;
845 case CLIENT_STATE_WAITING_FOR_REJECT:
846 debug_print ("CLIENT: WaitingForReject");
847 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
850 debug_print ("CLIENT: WaitingForReject, read '%s'", line);
852 if (!g_str_has_prefix (line, "REJECTED "))
857 "In WaitingForReject: Expected `REJECTED am1 am2 ... amN', got `%s'",
862 if (supported_auth_mechs == NULL)
864 supported_auth_mechs = g_strsplit (line + sizeof ("REJECTED ") - 1, " ", 0);
866 for (n = 0; supported_auth_mechs != NULL && supported_auth_mechs[n] != NULL; n++)
867 g_printerr ("supported_auth_mechs[%d] = `%s'\n", n, supported_auth_mechs[n]);
871 mech = client_choose_mech_and_send_initial_response (auth,
873 (const gchar* const *) supported_auth_mechs,
874 attempted_auth_mechs,
880 if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA)
881 state = CLIENT_STATE_WAITING_FOR_DATA;
883 state = CLIENT_STATE_WAITING_FOR_OK;
886 case CLIENT_STATE_WAITING_FOR_OK:
887 debug_print ("CLIENT: WaitingForOK");
888 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
891 debug_print ("CLIENT: WaitingForOK, read `%s'", line);
892 if (g_str_has_prefix (line, "OK "))
894 if (!g_dbus_is_guid (line + 3))
899 "Invalid OK response `%s'",
904 ret_guid = g_strdup (line + 3);
907 if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
909 s = "NEGOTIATE_UNIX_FD\r\n";
910 debug_print ("CLIENT: writing `%s'", s);
911 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
913 state = CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD;
918 debug_print ("CLIENT: writing `%s'", s);
919 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
921 /* and we're done! */
925 else if (g_str_has_prefix (line, "REJECTED "))
931 /* TODO: handle other valid responses */
935 "In WaitingForOk: unexpected response `%s'",
942 case CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD:
943 debug_print ("CLIENT: WaitingForAgreeUnixFD");
944 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
947 debug_print ("CLIENT: WaitingForAgreeUnixFD, read=`%s'", line);
948 if (g_strcmp0 (line, "AGREE_UNIX_FD") == 0)
950 negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
952 debug_print ("CLIENT: writing `%s'", s);
953 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
955 /* and we're done! */
958 else if (g_str_has_prefix (line, "ERROR") && (line[5] == 0 || g_ascii_isspace (line[5])))
960 //g_strstrip (line + 5); g_debug ("bah, no unix_fd: `%s'", line + 5);
963 debug_print ("CLIENT: writing `%s'", s);
964 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
966 /* and we're done! */
971 /* TODO: handle other valid responses */
975 "In WaitingForAgreeUnixFd: unexpected response `%s'",
982 case CLIENT_STATE_WAITING_FOR_DATA:
983 debug_print ("CLIENT: WaitingForData");
984 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
987 debug_print ("CLIENT: WaitingForData, read=`%s'", line);
988 if (g_str_has_prefix (line, "DATA "))
992 gsize decoded_data_len;
994 encoded = g_strdup (line + 5);
996 g_strstrip (encoded);
997 decoded_data = hexdecode (encoded, &decoded_data_len, error);
999 if (decoded_data == NULL)
1001 g_prefix_error (error, "DATA response is malformed: ");
1002 /* invalid encoding, disconnect! */
1005 _g_dbus_auth_mechanism_client_data_receive (mech, decoded_data, decoded_data_len);
1006 g_free (decoded_data);
1008 if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND)
1012 gchar *encoded_data;
1013 data = _g_dbus_auth_mechanism_client_data_send (mech, &data_len);
1014 encoded_data = hexencode (data);
1015 s = g_strdup_printf ("DATA %s\r\n", encoded_data);
1016 g_free (encoded_data);
1018 debug_print ("CLIENT: writing `%s'", s);
1019 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1026 state = CLIENT_STATE_WAITING_FOR_OK;
1033 "In WaitingForData: unexpected response `%s'",
1041 g_assert_not_reached ();
1045 }; /* main authentication client loop */
1049 g_object_unref (mech);
1050 g_ptr_array_unref (attempted_auth_mechs);
1051 g_strfreev (supported_auth_mechs);
1055 /* ensure return value is NULL if error is set */
1056 if (error != NULL && *error != NULL)
1062 if (ret_guid != NULL)
1064 if (out_negotiated_capabilities != NULL)
1065 *out_negotiated_capabilities = negotiated_capabilities;
1068 if (credentials != NULL)
1069 g_object_unref (credentials);
1071 debug_print ("CLIENT: Done, authenticated=%d", ret_guid != NULL);
1076 /* ---------------------------------------------------------------------------------------------------- */
1079 get_auth_mechanisms (GDBusAuth *auth,
1080 gboolean allow_anonymous,
1081 const gchar *prefix,
1082 const gchar *suffix,
1083 const gchar *separator)
1089 str = g_string_new (prefix);
1091 for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
1093 Mechanism *m = l->data;
1095 if (!allow_anonymous && g_strcmp0 (m->name, "ANONYMOUS") == 0)
1099 g_string_append (str, separator);
1100 g_string_append (str, m->name);
1104 g_string_append (str, suffix);
1105 return g_string_free (str, FALSE);
1111 SERVER_STATE_WAITING_FOR_AUTH,
1112 SERVER_STATE_WAITING_FOR_DATA,
1113 SERVER_STATE_WAITING_FOR_BEGIN
1117 _g_dbus_auth_run_server (GDBusAuth *auth,
1118 GDBusAuthObserver *observer,
1120 gboolean allow_anonymous,
1121 GDBusCapabilityFlags offered_capabilities,
1122 GDBusCapabilityFlags *out_negotiated_capabilities,
1123 GCredentials **out_received_credentials,
1124 GCancellable *cancellable,
1129 GDataInputStream *dis;
1130 GDataOutputStream *dos;
1131 GError *local_error;
1135 GDBusAuthMechanism *mech;
1137 GDBusCapabilityFlags negotiated_capabilities;
1138 GCredentials *credentials;
1140 debug_print ("SERVER: initiating");
1146 negotiated_capabilities = 0;
1149 if (!g_dbus_is_guid (guid))
1154 "The given guid `%s' is not valid",
1159 dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
1160 dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
1162 g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
1164 /* first read the NUL-byte (TODO: read credentials if using a unix domain socket) */
1166 if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
1169 credentials = g_unix_connection_receive_credentials (G_UNIX_CONNECTION (auth->priv->stream),
1172 if (credentials == NULL)
1174 g_propagate_error (error, local_error);
1181 byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
1182 if (local_error != NULL)
1184 g_propagate_error (error, local_error);
1190 byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
1191 if (local_error != NULL)
1193 g_propagate_error (error, local_error);
1197 if (credentials != NULL)
1199 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
1201 s = g_credentials_to_string (credentials);
1202 debug_print ("SERVER: received credentials `%s'", s);
1208 debug_print ("SERVER: didn't receive any credentials");
1211 state = SERVER_STATE_WAITING_FOR_AUTH;
1216 case SERVER_STATE_WAITING_FOR_AUTH:
1217 debug_print ("SERVER: WaitingForAuth");
1218 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1219 debug_print ("SERVER: WaitingForAuth, read `%s'", line);
1222 if (g_strcmp0 (line, "AUTH") == 0)
1224 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1225 debug_print ("SERVER: writing `%s'", s);
1226 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1234 else if (g_str_has_prefix (line, "AUTH "))
1237 const gchar *encoded;
1238 const gchar *mech_name;
1239 GType auth_mech_to_use_gtype;
1241 tokens = g_strsplit (line, " ", 0);
1244 switch (g_strv_length (tokens))
1247 /* no initial response */
1248 mech_name = tokens[1];
1253 /* initial response */
1254 mech_name = tokens[1];
1255 encoded = tokens[2];
1262 "Unexpected line `%s' while in WaitingForAuth state",
1264 g_strfreev (tokens);
1268 /* TODO: record that the client has attempted to use this mechanism */
1269 //g_debug ("client is trying `%s'", mech_name);
1271 auth_mech_to_use_gtype = find_mech_by_name (auth, mech_name);
1272 if ((auth_mech_to_use_gtype == (GType) 0) ||
1273 (!allow_anonymous && g_strcmp0 (mech_name, "ANONYMOUS") == 0))
1275 /* We don't support this auth mechanism */
1276 g_strfreev (tokens);
1277 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1278 debug_print ("SERVER: writing `%s'", s);
1279 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1286 /* stay in WAITING FOR AUTH */
1287 state = SERVER_STATE_WAITING_FOR_AUTH;
1291 gchar *initial_response;
1292 gsize initial_response_len;
1294 mech = g_object_new (auth_mech_to_use_gtype,
1295 "stream", auth->priv->stream,
1296 "credentials", credentials,
1299 initial_response = NULL;
1300 initial_response_len = 0;
1301 if (encoded != NULL)
1303 initial_response = hexdecode (encoded, &initial_response_len, error);
1304 if (initial_response == NULL)
1306 g_prefix_error (error, "Initial response is malformed: ");
1307 /* invalid encoding, disconnect! */
1308 g_strfreev (tokens);
1313 _g_dbus_auth_mechanism_server_initiate (mech,
1315 initial_response_len);
1316 g_free (initial_response);
1317 g_strfreev (tokens);
1320 switch (_g_dbus_auth_mechanism_server_get_state (mech))
1322 case G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED:
1323 if (observer != NULL &&
1324 g_dbus_auth_observer_deny_authenticated_peer (observer,
1329 g_set_error_literal (error,
1332 _("Cancelled via GDBusAuthObserver::deny-authenticated-peer"));
1337 s = g_strdup_printf ("OK %s\r\n", guid);
1338 debug_print ("SERVER: writing `%s'", s);
1339 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1345 state = SERVER_STATE_WAITING_FOR_BEGIN;
1349 case G_DBUS_AUTH_MECHANISM_STATE_REJECTED:
1350 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1351 debug_print ("SERVER: writing `%s'", s);
1352 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1358 state = SERVER_STATE_WAITING_FOR_AUTH;
1361 case G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA:
1362 state = SERVER_STATE_WAITING_FOR_DATA;
1365 case G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND:
1369 gchar *encoded_data;
1370 data = _g_dbus_auth_mechanism_server_data_send (mech, &data_len);
1371 encoded_data = hexencode (data);
1372 s = g_strdup_printf ("DATA %s\r\n", encoded_data);
1373 g_free (encoded_data);
1375 debug_print ("SERVER: writing `%s'", s);
1376 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1388 g_assert_not_reached ();
1398 "Unexpected line `%s' while in WaitingForAuth state",
1405 case SERVER_STATE_WAITING_FOR_DATA:
1406 debug_print ("SERVER: WaitingForData");
1407 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1408 debug_print ("SERVER: WaitingForData, read `%s'", line);
1411 if (g_str_has_prefix (line, "DATA "))
1414 gchar *decoded_data;
1415 gsize decoded_data_len;
1417 encoded = g_strdup (line + 5);
1419 g_strstrip (encoded);
1420 decoded_data = hexdecode (encoded, &decoded_data_len, error);
1422 if (decoded_data == NULL)
1424 g_prefix_error (error, "DATA response is malformed: ");
1425 /* invalid encoding, disconnect! */
1428 _g_dbus_auth_mechanism_server_data_receive (mech, decoded_data, decoded_data_len);
1429 g_free (decoded_data);
1430 /* oh man, this goto-crap is so ugly.. really need to rewrite the state machine */
1438 "Unexpected line `%s' while in WaitingForData state",
1444 case SERVER_STATE_WAITING_FOR_BEGIN:
1445 debug_print ("SERVER: WaitingForBegin");
1446 /* Use extremely slow (but reliable) line reader - this basically
1447 * does a recvfrom() system call per character
1449 * (the problem with using GDataInputStream's read_line is that because of
1450 * buffering it might start reading into the first D-Bus message that
1451 * appears after "BEGIN\r\n"....)
1453 line = _my_g_input_stream_read_line_safe (g_io_stream_get_input_stream (auth->priv->stream),
1457 debug_print ("SERVER: WaitingForBegin, read `%s'", line);
1460 if (g_strcmp0 (line, "BEGIN") == 0)
1467 else if (g_strcmp0 (line, "NEGOTIATE_UNIX_FD") == 0)
1469 if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
1471 negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1472 s = "AGREE_UNIX_FD\r\n";
1473 debug_print ("SERVER: writing `%s'", s);
1474 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1479 s = "ERROR \"fd passing not offered\"\r\n";
1480 debug_print ("SERVER: writing `%s'", s);
1481 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1487 g_debug ("Unexpected line `%s' while in WaitingForBegin state", line);
1489 s = "ERROR \"Unknown Command\"\r\n";
1490 debug_print ("SERVER: writing `%s'", s);
1491 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1497 g_assert_not_reached ();
1503 g_set_error_literal (error,
1506 "Not implemented (server)");
1510 g_object_unref (mech);
1516 /* ensure return value is FALSE if error is set */
1517 if (error != NULL && *error != NULL)
1524 if (out_negotiated_capabilities != NULL)
1525 *out_negotiated_capabilities = negotiated_capabilities;
1526 if (out_received_credentials != NULL)
1527 *out_received_credentials = credentials != NULL ? g_object_ref (credentials) : NULL;
1530 if (credentials != NULL)
1531 g_object_unref (credentials);
1533 debug_print ("SERVER: Done, authenticated=%d", ret);
1538 /* ---------------------------------------------------------------------------------------------------- */