1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-auth.c Authentication
3  *
4  * Copyright (C) 2002, 2003, 2004 Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23 
24 #include <config.h>
25 #include "dbus-auth.h"
26 #include "dbus-string.h"
27 #include "dbus-list.h"
28 #include "dbus-internals.h"
29 #include "dbus-keyring.h"
30 #include "dbus-sha.h"
31 #include "dbus-protocol.h"
32 #include "dbus-credentials.h"
33 
34 /**
35  * @defgroup DBusAuth Authentication
36  * @ingroup  DBusInternals
37  * @brief DBusAuth object
38  *
39  * DBusAuth manages the authentication negotiation when a connection
40  * is first established, and also manages any encryption used over a
41  * connection.
42  *
43  * @todo some SASL profiles require sending the empty string as a
44  * challenge/response, but we don't currently allow that in our
45  * protocol.
46  *
47  * @todo right now sometimes both ends will block waiting for input
48  * from the other end, e.g. if there's an error during
49  * DBUS_COOKIE_SHA1.
50  *
51  * @todo the cookie keyring needs to be cached globally not just
52  * per-auth (which raises threadsafety issues too)
53  *
54  * @todo grep FIXME in dbus-auth.c
55  */
56 
57 /**
58  * @defgroup DBusAuthInternals Authentication implementation details
59  * @ingroup  DBusInternals
60  * @brief DBusAuth implementation details
61  *
62  * Private details of authentication code.
63  *
64  * @{
65  */
66 
67 /**
68  * This function appends an initial client response to the given string
69  */
70 typedef dbus_bool_t (* DBusInitialResponseFunction)  (DBusAuth         *auth,
71                                                       DBusString       *response);
72 
73 /**
74  * This function processes a block of data received from the peer.
75  * i.e. handles a DATA command.
76  */
77 typedef dbus_bool_t (* DBusAuthDataFunction)     (DBusAuth         *auth,
78                                                   const DBusString *data);
79 
80 /**
81  * This function encodes a block of data from the peer.
82  */
83 typedef dbus_bool_t (* DBusAuthEncodeFunction)   (DBusAuth         *auth,
84                                                   const DBusString *data,
85                                                   DBusString       *encoded);
86 
87 /**
88  * This function decodes a block of data from the peer.
89  */
90 typedef dbus_bool_t (* DBusAuthDecodeFunction)   (DBusAuth         *auth,
91                                                   const DBusString *data,
92                                                   DBusString       *decoded);
93 
94 /**
95  * This function is called when the mechanism is abandoned.
96  */
97 typedef void        (* DBusAuthShutdownFunction) (DBusAuth       *auth);
98 
99 /**
100  * Virtual table representing a particular auth mechanism.
101  */
102 typedef struct
103 {
104   const char *mechanism; /**< Name of the mechanism */
105   DBusAuthDataFunction server_data_func; /**< Function on server side for DATA */
106   DBusAuthEncodeFunction server_encode_func; /**< Function on server side to encode */
107   DBusAuthDecodeFunction server_decode_func; /**< Function on server side to decode */
108   DBusAuthShutdownFunction server_shutdown_func; /**< Function on server side to shut down */
109   DBusInitialResponseFunction client_initial_response_func; /**< Function on client side to handle initial response */
110   DBusAuthDataFunction client_data_func; /**< Function on client side for DATA */
111   DBusAuthEncodeFunction client_encode_func; /**< Function on client side for encode */
112   DBusAuthDecodeFunction client_decode_func; /**< Function on client side for decode */
113   DBusAuthShutdownFunction client_shutdown_func; /**< Function on client side for shutdown */
114 } DBusAuthMechanismHandler;
115 
116 /**
117  * Enumeration for the known authentication commands.
118  */
119 typedef enum {
120   DBUS_AUTH_COMMAND_AUTH,
121   DBUS_AUTH_COMMAND_CANCEL,
122   DBUS_AUTH_COMMAND_DATA,
123   DBUS_AUTH_COMMAND_BEGIN,
124   DBUS_AUTH_COMMAND_REJECTED,
125   DBUS_AUTH_COMMAND_OK,
126   DBUS_AUTH_COMMAND_ERROR,
127   DBUS_AUTH_COMMAND_UNKNOWN,
128   DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD,
129   DBUS_AUTH_COMMAND_AGREE_UNIX_FD
130 } DBusAuthCommand;
131 
132 /**
133  * Auth state function, determines the reaction to incoming events for
134  * a particular state. Returns whether we had enough memory to
135  * complete the operation.
136  */
137 typedef dbus_bool_t (* DBusAuthStateFunction) (DBusAuth         *auth,
138                                                DBusAuthCommand   command,
139                                                const DBusString *args);
140 
141 /**
142  * Information about a auth state.
143  */
144 typedef struct
145 {
146   const char *name;               /**< Name of the state */
147   DBusAuthStateFunction handler;  /**< State function for this state */
148 } DBusAuthStateData;
149 
150 /**
151  * Internal members of DBusAuth.
152  */
153 struct DBusAuth
154 {
155   int refcount;           /**< reference count */
156   const char *side;       /**< Client or server */
157 
158   DBusString incoming;    /**< Incoming data buffer */
159   DBusString outgoing;    /**< Outgoing data buffer */
160 
161   const DBusAuthStateData *state;         /**< Current protocol state */
162 
163   const DBusAuthMechanismHandler *mech;   /**< Current auth mechanism */
164 
165   DBusString identity;                   /**< Current identity we're authorizing
166                                           *   as.
167                                           */
168 
169   DBusCredentials *credentials;          /**< Credentials read from socket
170                                           */
171 
172   DBusCredentials *authorized_identity; /**< Credentials that are authorized */
173 
174   DBusCredentials *desired_identity;    /**< Identity client has requested */
175 
176   DBusString context;               /**< Cookie scope */
177   DBusKeyring *keyring;             /**< Keyring for cookie mechanism. */
178   int cookie_id;                    /**< ID of cookie to use */
179   DBusString challenge;             /**< Challenge sent to client */
180 
181   char **allowed_mechs;             /**< Mechanisms we're allowed to use,
182                                      * or #NULL if we can use any
183                                      */
184 
185   unsigned int needed_memory : 1;   /**< We needed memory to continue since last
186                                      * successful getting something done
187                                      */
188   unsigned int already_got_mechanisms : 1;       /**< Client already got mech list */
189   unsigned int already_asked_for_initial_response : 1; /**< Already sent a blank challenge to get an initial response */
190   unsigned int buffer_outstanding : 1; /**< Buffer is "checked out" for reading data into */
191 
192   unsigned int unix_fd_possible : 1;  /**< This side could do unix fd passing */
193   unsigned int unix_fd_negotiated : 1; /**< Unix fd was successfully negotiated */
194 };
195 
196 /**
197  * "Subclass" of DBusAuth for client side
198  */
199 typedef struct
200 {
201   DBusAuth base;    /**< Parent class */
202 
203   DBusList *mechs_to_try; /**< Mechanisms we got from the server that we're going to try using */
204 
205   DBusString guid_from_server; /**< GUID received from server */
206 
207 } DBusAuthClient;
208 
209 /**
210  * "Subclass" of DBusAuth for server side.
211  */
212 typedef struct
213 {
214   DBusAuth base;    /**< Parent class */
215 
216   int failures;     /**< Number of times client has been rejected */
217   int max_failures; /**< Number of times we reject before disconnect */
218 
219   DBusString guid;  /**< Our globally unique ID in hex encoding */
220 
221 } DBusAuthServer;
222 
223 static void        goto_state                (DBusAuth                       *auth,
224                                               const DBusAuthStateData        *new_state);
225 static dbus_bool_t send_auth                 (DBusAuth *auth,
226                                               const DBusAuthMechanismHandler *mech);
227 static dbus_bool_t send_data                 (DBusAuth *auth,
228                                               DBusString *data);
229 static dbus_bool_t send_rejected             (DBusAuth *auth);
230 static dbus_bool_t send_error                (DBusAuth *auth,
231                                               const char *message);
232 static dbus_bool_t send_ok                   (DBusAuth *auth);
233 static dbus_bool_t send_begin                (DBusAuth *auth);
234 static dbus_bool_t send_cancel               (DBusAuth *auth);
235 static dbus_bool_t send_negotiate_unix_fd    (DBusAuth *auth);
236 static dbus_bool_t send_agree_unix_fd        (DBusAuth *auth);
237 
238 /**
239  * Client states
240  */
241 
242 static dbus_bool_t handle_server_state_waiting_for_auth  (DBusAuth         *auth,
243                                                           DBusAuthCommand   command,
244                                                           const DBusString *args);
245 static dbus_bool_t handle_server_state_waiting_for_data  (DBusAuth         *auth,
246                                                           DBusAuthCommand   command,
247                                                           const DBusString *args);
248 static dbus_bool_t handle_server_state_waiting_for_begin (DBusAuth         *auth,
249                                                           DBusAuthCommand   command,
250                                                           const DBusString *args);
251 
252 static const DBusAuthStateData server_state_waiting_for_auth = {
253   "WaitingForAuth", handle_server_state_waiting_for_auth
254 };
255 static const DBusAuthStateData server_state_waiting_for_data = {
256   "WaitingForData", handle_server_state_waiting_for_data
257 };
258 static const DBusAuthStateData server_state_waiting_for_begin = {
259   "WaitingForBegin", handle_server_state_waiting_for_begin
260 };
261 
262 /**
263  * Client states
264  */
265 
266 static dbus_bool_t handle_client_state_waiting_for_data   (DBusAuth         *auth,
267                                                            DBusAuthCommand   command,
268                                                            const DBusString *args);
269 static dbus_bool_t handle_client_state_waiting_for_ok     (DBusAuth         *auth,
270                                                            DBusAuthCommand   command,
271                                                            const DBusString *args);
272 static dbus_bool_t handle_client_state_waiting_for_reject (DBusAuth         *auth,
273                                                            DBusAuthCommand   command,
274                                                            const DBusString *args);
275 static dbus_bool_t handle_client_state_waiting_for_agree_unix_fd (DBusAuth         *auth,
276                                                            DBusAuthCommand   command,
277                                                            const DBusString *args);
278 
279 static const DBusAuthStateData client_state_need_send_auth = {
280   "NeedSendAuth", NULL
281 };
282 static const DBusAuthStateData client_state_waiting_for_data = {
283   "WaitingForData", handle_client_state_waiting_for_data
284 };
285 /* The WaitingForOK state doesn't appear to be used.
286  * See https://bugs.freedesktop.org/show_bug.cgi?id=97298 */
287 _DBUS_GNUC_UNUSED
288 static const DBusAuthStateData client_state_waiting_for_ok = {
289   "WaitingForOK", handle_client_state_waiting_for_ok
290 };
291 static const DBusAuthStateData client_state_waiting_for_reject = {
292   "WaitingForReject", handle_client_state_waiting_for_reject
293 };
294 static const DBusAuthStateData client_state_waiting_for_agree_unix_fd = {
295   "WaitingForAgreeUnixFD", handle_client_state_waiting_for_agree_unix_fd
296 };
297 
298 /**
299  * Common terminal states.  Terminal states have handler == NULL.
300  */
301 
302 static const DBusAuthStateData common_state_authenticated = {
303   "Authenticated",  NULL
304 };
305 
306 static const DBusAuthStateData common_state_need_disconnect = {
307   "NeedDisconnect",  NULL
308 };
309 
310 static const char auth_side_client[] = "client";
311 static const char auth_side_server[] = "server";
312 /**
313  * @param auth the auth conversation
314  * @returns #TRUE if the conversation is the server side
315  */
316 #define DBUS_AUTH_IS_SERVER(auth) ((auth)->side == auth_side_server)
317 /**
318  * @param auth the auth conversation
319  * @returns #TRUE if the conversation is the client side
320  */
321 #define DBUS_AUTH_IS_CLIENT(auth) ((auth)->side == auth_side_client)
322 /**
323  * @param auth the auth conversation
324  * @returns auth cast to DBusAuthClient
325  */
326 #define DBUS_AUTH_CLIENT(auth)    ((DBusAuthClient*)(auth))
327 /**
328  * @param auth the auth conversation
329  * @returns auth cast to DBusAuthServer
330  */
331 #define DBUS_AUTH_SERVER(auth)    ((DBusAuthServer*)(auth))
332 
333 /**
334  * The name of the auth ("client" or "server")
335  * @param auth the auth conversation
336  * @returns a string
337  */
338 #define DBUS_AUTH_NAME(auth)      ((auth)->side)
339 
340 static DBusAuth*
_dbus_auth_new(int size)341 _dbus_auth_new (int size)
342 {
343   DBusAuth *auth;
344 
345   auth = dbus_malloc0 (size);
346   if (auth == NULL)
347     return NULL;
348 
349   auth->refcount = 1;
350 
351   auth->keyring = NULL;
352   auth->cookie_id = -1;
353 
354   /* note that we don't use the max string length feature,
355    * because you can't use that feature if you're going to
356    * try to recover from out-of-memory (it creates
357    * what looks like unrecoverable inability to alloc
358    * more space in the string). But we do handle
359    * overlong buffers in _dbus_auth_do_work().
360    */
361 
362   if (!_dbus_string_init (&auth->incoming))
363     goto enomem_0;
364 
365   if (!_dbus_string_init (&auth->outgoing))
366     goto enomem_1;
367 
368   if (!_dbus_string_init (&auth->identity))
369     goto enomem_2;
370 
371   if (!_dbus_string_init (&auth->context))
372     goto enomem_3;
373 
374   if (!_dbus_string_init (&auth->challenge))
375     goto enomem_4;
376 
377   /* default context if none is specified */
378   if (!_dbus_string_append (&auth->context, "org_freedesktop_general"))
379     goto enomem_5;
380 
381   auth->credentials = _dbus_credentials_new ();
382   if (auth->credentials == NULL)
383     goto enomem_6;
384 
385   auth->authorized_identity = _dbus_credentials_new ();
386   if (auth->authorized_identity == NULL)
387     goto enomem_7;
388 
389   auth->desired_identity = _dbus_credentials_new ();
390   if (auth->desired_identity == NULL)
391     goto enomem_8;
392 
393   return auth;
394 
395 #if 0
396  enomem_9:
397   _dbus_credentials_unref (auth->desired_identity);
398 #endif
399  enomem_8:
400   _dbus_credentials_unref (auth->authorized_identity);
401  enomem_7:
402   _dbus_credentials_unref (auth->credentials);
403  enomem_6:
404  /* last alloc was an append to context, which is freed already below */ ;
405  enomem_5:
406   _dbus_string_free (&auth->challenge);
407  enomem_4:
408   _dbus_string_free (&auth->context);
409  enomem_3:
410   _dbus_string_free (&auth->identity);
411  enomem_2:
412   _dbus_string_free (&auth->outgoing);
413  enomem_1:
414   _dbus_string_free (&auth->incoming);
415  enomem_0:
416   dbus_free (auth);
417   return NULL;
418 }
419 
420 static void
shutdown_mech(DBusAuth * auth)421 shutdown_mech (DBusAuth *auth)
422 {
423   /* Cancel any auth */
424   auth->already_asked_for_initial_response = FALSE;
425   _dbus_string_set_length (&auth->identity, 0);
426 
427   _dbus_credentials_clear (auth->authorized_identity);
428   _dbus_credentials_clear (auth->desired_identity);
429 
430   if (auth->mech != NULL)
431     {
432       _dbus_verbose ("%s: Shutting down mechanism %s\n",
433                      DBUS_AUTH_NAME (auth), auth->mech->mechanism);
434 
435       if (DBUS_AUTH_IS_CLIENT (auth))
436         (* auth->mech->client_shutdown_func) (auth);
437       else
438         (* auth->mech->server_shutdown_func) (auth);
439 
440       auth->mech = NULL;
441     }
442 }
443 
444 /*
445  * DBUS_COOKIE_SHA1 mechanism
446  */
447 
448 /* Returns TRUE but with an empty string hash if the
449  * cookie_id isn't known. As with all this code
450  * TRUE just means we had enough memory.
451  */
452 static dbus_bool_t
sha1_compute_hash(DBusAuth * auth,int cookie_id,const DBusString * server_challenge,const DBusString * client_challenge,DBusString * hash)453 sha1_compute_hash (DBusAuth         *auth,
454                    int               cookie_id,
455                    const DBusString *server_challenge,
456                    const DBusString *client_challenge,
457                    DBusString       *hash)
458 {
459   DBusString cookie;
460   DBusString to_hash;
461   dbus_bool_t retval;
462 
463   _dbus_assert (auth->keyring != NULL);
464 
465   retval = FALSE;
466 
467   if (!_dbus_string_init (&cookie))
468     return FALSE;
469 
470   if (!_dbus_keyring_get_hex_key (auth->keyring, cookie_id,
471                                   &cookie))
472     goto out_0;
473 
474   if (_dbus_string_get_length (&cookie) == 0)
475     {
476       retval = TRUE;
477       goto out_0;
478     }
479 
480   if (!_dbus_string_init (&to_hash))
481     goto out_0;
482 
483   if (!_dbus_string_copy (server_challenge, 0,
484                           &to_hash, _dbus_string_get_length (&to_hash)))
485     goto out_1;
486 
487   if (!_dbus_string_append (&to_hash, ":"))
488     goto out_1;
489 
490   if (!_dbus_string_copy (client_challenge, 0,
491                           &to_hash, _dbus_string_get_length (&to_hash)))
492     goto out_1;
493 
494   if (!_dbus_string_append (&to_hash, ":"))
495     goto out_1;
496 
497   if (!_dbus_string_copy (&cookie, 0,
498                           &to_hash, _dbus_string_get_length (&to_hash)))
499     goto out_1;
500 
501   if (!_dbus_sha_compute (&to_hash, hash))
502     goto out_1;
503 
504   retval = TRUE;
505 
506  out_1:
507   _dbus_string_zero (&to_hash);
508   _dbus_string_free (&to_hash);
509  out_0:
510   _dbus_string_zero (&cookie);
511   _dbus_string_free (&cookie);
512   return retval;
513 }
514 
515 /** http://www.ietf.org/rfc/rfc2831.txt suggests at least 64 bits of
516  * entropy, we use 128. This is the number of bytes in the random
517  * challenge.
518  */
519 #define N_CHALLENGE_BYTES (128/8)
520 
521 static dbus_bool_t
sha1_handle_first_client_response(DBusAuth * auth,const DBusString * data)522 sha1_handle_first_client_response (DBusAuth         *auth,
523                                    const DBusString *data)
524 {
525   /* We haven't sent a challenge yet, we're expecting a desired
526    * username from the client.
527    */
528   DBusString tmp;
529   DBusString tmp2;
530   dbus_bool_t retval = FALSE;
531   DBusError error = DBUS_ERROR_INIT;
532   DBusCredentials *myself = NULL;
533 
534   _dbus_string_set_length (&auth->challenge, 0);
535 
536   if (_dbus_string_get_length (data) > 0)
537     {
538       if (_dbus_string_get_length (&auth->identity) > 0)
539         {
540           /* Tried to send two auth identities, wtf */
541           _dbus_verbose ("%s: client tried to send auth identity, but we already have one\n",
542                          DBUS_AUTH_NAME (auth));
543           return send_rejected (auth);
544         }
545       else
546         {
547           /* this is our auth identity */
548           if (!_dbus_string_copy (data, 0, &auth->identity, 0))
549             return FALSE;
550         }
551     }
552 
553   if (!_dbus_credentials_add_from_user (auth->desired_identity, data))
554     {
555       _dbus_verbose ("%s: Did not get a valid username from client\n",
556                      DBUS_AUTH_NAME (auth));
557       return send_rejected (auth);
558     }
559 
560   if (!_dbus_string_init (&tmp))
561     return FALSE;
562 
563   if (!_dbus_string_init (&tmp2))
564     {
565       _dbus_string_free (&tmp);
566       return FALSE;
567     }
568 
569   myself = _dbus_credentials_new_from_current_process ();
570 
571   if (myself == NULL)
572     goto out;
573 
574   if (!_dbus_credentials_same_user (myself, auth->desired_identity))
575     {
576       /*
577        * DBUS_COOKIE_SHA1 is not suitable for authenticating that the
578        * client is anyone other than the user owning the process
579        * containing the DBusServer: we probably aren't allowed to write
580        * to other users' home directories. Even if we can (for example
581        * uid 0 on traditional Unix or CAP_DAC_OVERRIDE on Linux), we
582        * must not, because the other user controls their home directory,
583        * and could carry out symlink attacks to make us read from or
584        * write to unintended locations. It's difficult to avoid symlink
585        * attacks in a portable way, so we just don't try. This isn't a
586        * regression, because DBUS_COOKIE_SHA1 never worked for other
587        * users anyway.
588        */
589       _dbus_verbose ("%s: client tried to authenticate as \"%s\", "
590                      "but that doesn't match this process",
591                      DBUS_AUTH_NAME (auth),
592                      _dbus_string_get_const_data (data));
593       retval = send_rejected (auth);
594       goto out;
595     }
596 
597   /* we cache the keyring for speed, so here we drop it if it's the
598    * wrong one. FIXME caching the keyring here is useless since we use
599    * a different DBusAuth for every connection.
600    */
601   if (auth->keyring &&
602       !_dbus_keyring_is_for_credentials (auth->keyring,
603                                          auth->desired_identity))
604     {
605       _dbus_keyring_unref (auth->keyring);
606       auth->keyring = NULL;
607     }
608 
609   if (auth->keyring == NULL)
610     {
611       auth->keyring = _dbus_keyring_new_for_credentials (auth->desired_identity,
612                                                          &auth->context,
613                                                          &error);
614 
615       if (auth->keyring == NULL)
616         {
617           if (dbus_error_has_name (&error,
618                                    DBUS_ERROR_NO_MEMORY))
619             {
620               dbus_error_free (&error);
621               goto out;
622             }
623           else
624             {
625               _DBUS_ASSERT_ERROR_IS_SET (&error);
626               _dbus_verbose ("%s: Error loading keyring: %s\n",
627                              DBUS_AUTH_NAME (auth), error.message);
628               if (send_rejected (auth))
629                 retval = TRUE; /* retval is only about mem */
630               dbus_error_free (&error);
631               goto out;
632             }
633         }
634       else
635         {
636           _dbus_assert (!dbus_error_is_set (&error));
637         }
638     }
639 
640   _dbus_assert (auth->keyring != NULL);
641 
642   auth->cookie_id = _dbus_keyring_get_best_key (auth->keyring, &error);
643   if (auth->cookie_id < 0)
644     {
645       _DBUS_ASSERT_ERROR_IS_SET (&error);
646       _dbus_verbose ("%s: Could not get a cookie ID to send to client: %s\n",
647                      DBUS_AUTH_NAME (auth), error.message);
648       if (send_rejected (auth))
649         retval = TRUE;
650       dbus_error_free (&error);
651       goto out;
652     }
653   else
654     {
655       _dbus_assert (!dbus_error_is_set (&error));
656     }
657 
658   if (!_dbus_string_copy (&auth->context, 0,
659                           &tmp2, _dbus_string_get_length (&tmp2)))
660     goto out;
661 
662   if (!_dbus_string_append (&tmp2, " "))
663     goto out;
664 
665   if (!_dbus_string_append_int (&tmp2, auth->cookie_id))
666     goto out;
667 
668   if (!_dbus_string_append (&tmp2, " "))
669     goto out;
670 
671   if (!_dbus_generate_random_bytes (&tmp, N_CHALLENGE_BYTES, &error))
672     {
673       if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
674         {
675           dbus_error_free (&error);
676           goto out;
677         }
678       else
679         {
680           _DBUS_ASSERT_ERROR_IS_SET (&error);
681           _dbus_verbose ("%s: Error generating challenge: %s\n",
682                          DBUS_AUTH_NAME (auth), error.message);
683           if (send_rejected (auth))
684             retval = TRUE; /* retval is only about mem */
685 
686           dbus_error_free (&error);
687           goto out;
688         }
689     }
690 
691   _dbus_string_set_length (&auth->challenge, 0);
692   if (!_dbus_string_hex_encode (&tmp, 0, &auth->challenge, 0))
693     goto out;
694 
695   if (!_dbus_string_hex_encode (&tmp, 0, &tmp2,
696                                 _dbus_string_get_length (&tmp2)))
697     goto out;
698 
699   if (!send_data (auth, &tmp2))
700     goto out;
701 
702   goto_state (auth, &server_state_waiting_for_data);
703   retval = TRUE;
704 
705  out:
706   _dbus_string_zero (&tmp);
707   _dbus_string_free (&tmp);
708   _dbus_string_zero (&tmp2);
709   _dbus_string_free (&tmp2);
710 
711   if (myself != NULL)
712     _dbus_credentials_unref (myself);
713 
714   return retval;
715 }
716 
717 static dbus_bool_t
sha1_handle_second_client_response(DBusAuth * auth,const DBusString * data)718 sha1_handle_second_client_response (DBusAuth         *auth,
719                                     const DBusString *data)
720 {
721   /* We are expecting a response which is the hex-encoded client
722    * challenge, space, then SHA-1 hash of the concatenation of our
723    * challenge, ":", client challenge, ":", secret key, all
724    * hex-encoded.
725    */
726   int i;
727   DBusString client_challenge;
728   DBusString client_hash;
729   dbus_bool_t retval;
730   DBusString correct_hash;
731 
732   retval = FALSE;
733 
734   if (!_dbus_string_find_blank (data, 0, &i))
735     {
736       _dbus_verbose ("%s: no space separator in client response\n",
737                      DBUS_AUTH_NAME (auth));
738       return send_rejected (auth);
739     }
740 
741   if (!_dbus_string_init (&client_challenge))
742     goto out_0;
743 
744   if (!_dbus_string_init (&client_hash))
745     goto out_1;
746 
747   if (!_dbus_string_copy_len (data, 0, i, &client_challenge,
748                               0))
749     goto out_2;
750 
751   _dbus_string_skip_blank (data, i, &i);
752 
753   if (!_dbus_string_copy_len (data, i,
754                               _dbus_string_get_length (data) - i,
755                               &client_hash,
756                               0))
757     goto out_2;
758 
759   if (_dbus_string_get_length (&client_challenge) == 0 ||
760       _dbus_string_get_length (&client_hash) == 0)
761     {
762       _dbus_verbose ("%s: zero-length client challenge or hash\n",
763                      DBUS_AUTH_NAME (auth));
764       if (send_rejected (auth))
765         retval = TRUE;
766       goto out_2;
767     }
768 
769   if (!_dbus_string_init (&correct_hash))
770     goto out_2;
771 
772   if (!sha1_compute_hash (auth, auth->cookie_id,
773                           &auth->challenge,
774                           &client_challenge,
775                           &correct_hash))
776     goto out_3;
777 
778   /* if cookie_id was invalid, then we get an empty hash */
779   if (_dbus_string_get_length (&correct_hash) == 0)
780     {
781       if (send_rejected (auth))
782         retval = TRUE;
783       goto out_3;
784     }
785 
786   if (!_dbus_string_equal (&client_hash, &correct_hash))
787     {
788       if (send_rejected (auth))
789         retval = TRUE;
790       goto out_3;
791     }
792 
793   if (!_dbus_credentials_add_credentials (auth->authorized_identity,
794                                           auth->desired_identity))
795     goto out_3;
796 
797   /* Copy process ID from the socket credentials if it's there
798    */
799   if (!_dbus_credentials_add_credential (auth->authorized_identity,
800                                          DBUS_CREDENTIAL_UNIX_PROCESS_ID,
801                                          auth->credentials))
802     goto out_3;
803 
804   if (!send_ok (auth))
805     goto out_3;
806 
807   _dbus_verbose ("%s: authenticated client using DBUS_COOKIE_SHA1\n",
808                  DBUS_AUTH_NAME (auth));
809 
810   retval = TRUE;
811 
812  out_3:
813   _dbus_string_zero (&correct_hash);
814   _dbus_string_free (&correct_hash);
815  out_2:
816   _dbus_string_zero (&client_hash);
817   _dbus_string_free (&client_hash);
818  out_1:
819   _dbus_string_free (&client_challenge);
820  out_0:
821   return retval;
822 }
823 
824 static dbus_bool_t
handle_server_data_cookie_sha1_mech(DBusAuth * auth,const DBusString * data)825 handle_server_data_cookie_sha1_mech (DBusAuth         *auth,
826                                      const DBusString *data)
827 {
828   if (auth->cookie_id < 0)
829     return sha1_handle_first_client_response (auth, data);
830   else
831     return sha1_handle_second_client_response (auth, data);
832 }
833 
834 static void
handle_server_shutdown_cookie_sha1_mech(DBusAuth * auth)835 handle_server_shutdown_cookie_sha1_mech (DBusAuth *auth)
836 {
837   auth->cookie_id = -1;
838   _dbus_string_set_length (&auth->challenge, 0);
839 }
840 
841 static dbus_bool_t
handle_client_initial_response_cookie_sha1_mech(DBusAuth * auth,DBusString * response)842 handle_client_initial_response_cookie_sha1_mech (DBusAuth   *auth,
843                                                  DBusString *response)
844 {
845   DBusString username;
846   dbus_bool_t retval;
847 
848   retval = FALSE;
849 
850   if (!_dbus_string_init (&username))
851     return FALSE;
852 
853   if (!_dbus_append_user_from_current_process (&username))
854     goto out_0;
855 
856   if (!_dbus_string_hex_encode (&username, 0,
857 				response,
858 				_dbus_string_get_length (response)))
859     goto out_0;
860 
861   retval = TRUE;
862 
863  out_0:
864   _dbus_string_free (&username);
865 
866   return retval;
867 }
868 
869 static dbus_bool_t
handle_client_data_cookie_sha1_mech(DBusAuth * auth,const DBusString * data)870 handle_client_data_cookie_sha1_mech (DBusAuth         *auth,
871                                      const DBusString *data)
872 {
873   /* The data we get from the server should be the cookie context
874    * name, the cookie ID, and the server challenge, separated by
875    * spaces. We send back our challenge string and the correct hash.
876    */
877   dbus_bool_t retval = FALSE;
878   DBusString context;
879   DBusString cookie_id_str;
880   DBusString server_challenge;
881   DBusString client_challenge;
882   DBusString correct_hash;
883   DBusString tmp;
884   int i, j;
885   long val;
886   DBusError error = DBUS_ERROR_INIT;
887 
888   if (!_dbus_string_find_blank (data, 0, &i))
889     {
890       if (send_error (auth,
891                       "Server did not send context/ID/challenge properly"))
892         retval = TRUE;
893       goto out_0;
894     }
895 
896   if (!_dbus_string_init (&context))
897     goto out_0;
898 
899   if (!_dbus_string_copy_len (data, 0, i,
900                               &context, 0))
901     goto out_1;
902 
903   _dbus_string_skip_blank (data, i, &i);
904   if (!_dbus_string_find_blank (data, i, &j))
905     {
906       if (send_error (auth,
907                       "Server did not send context/ID/challenge properly"))
908         retval = TRUE;
909       goto out_1;
910     }
911 
912   if (!_dbus_string_init (&cookie_id_str))
913     goto out_1;
914 
915   if (!_dbus_string_copy_len (data, i, j - i,
916                               &cookie_id_str, 0))
917     goto out_2;
918 
919   if (!_dbus_string_init (&server_challenge))
920     goto out_2;
921 
922   i = j;
923   _dbus_string_skip_blank (data, i, &i);
924   j = _dbus_string_get_length (data);
925 
926   if (!_dbus_string_copy_len (data, i, j - i,
927                               &server_challenge, 0))
928     goto out_3;
929 
930   if (!_dbus_keyring_validate_context (&context))
931     {
932       if (send_error (auth, "Server sent invalid cookie context"))
933         retval = TRUE;
934       goto out_3;
935     }
936 
937   if (!_dbus_string_parse_int (&cookie_id_str, 0, &val, NULL))
938     {
939       if (send_error (auth, "Could not parse cookie ID as an integer"))
940         retval = TRUE;
941       goto out_3;
942     }
943 
944   if (_dbus_string_get_length (&server_challenge) == 0)
945     {
946       if (send_error (auth, "Empty server challenge string"))
947         retval = TRUE;
948       goto out_3;
949     }
950 
951   if (auth->keyring == NULL)
952     {
953       auth->keyring = _dbus_keyring_new_for_credentials (NULL,
954                                                          &context,
955                                                          &error);
956 
957       if (auth->keyring == NULL)
958         {
959           if (dbus_error_has_name (&error,
960                                    DBUS_ERROR_NO_MEMORY))
961             {
962               dbus_error_free (&error);
963               goto out_3;
964             }
965           else
966             {
967               _DBUS_ASSERT_ERROR_IS_SET (&error);
968 
969               _dbus_verbose ("%s: Error loading keyring: %s\n",
970                              DBUS_AUTH_NAME (auth), error.message);
971 
972               if (send_error (auth, "Could not load cookie file"))
973                 retval = TRUE; /* retval is only about mem */
974 
975               dbus_error_free (&error);
976               goto out_3;
977             }
978         }
979       else
980         {
981           _dbus_assert (!dbus_error_is_set (&error));
982         }
983     }
984 
985   _dbus_assert (auth->keyring != NULL);
986 
987   if (!_dbus_string_init (&tmp))
988     goto out_3;
989 
990   if (!_dbus_generate_random_bytes (&tmp, N_CHALLENGE_BYTES, &error))
991     {
992       if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
993         {
994           dbus_error_free (&error);
995           goto out_4;
996         }
997       else
998         {
999           _DBUS_ASSERT_ERROR_IS_SET (&error);
1000 
1001           _dbus_verbose ("%s: Failed to generate challenge: %s\n",
1002                          DBUS_AUTH_NAME (auth), error.message);
1003 
1004           if (send_error (auth, "Failed to generate challenge"))
1005             retval = TRUE; /* retval is only about mem */
1006 
1007           dbus_error_free (&error);
1008           goto out_4;
1009         }
1010     }
1011 
1012   if (!_dbus_string_init (&client_challenge))
1013     goto out_4;
1014 
1015   if (!_dbus_string_hex_encode (&tmp, 0, &client_challenge, 0))
1016     goto out_5;
1017 
1018   if (!_dbus_string_init (&correct_hash))
1019     goto out_5;
1020 
1021   if (!sha1_compute_hash (auth, val,
1022                           &server_challenge,
1023                           &client_challenge,
1024                           &correct_hash))
1025     goto out_6;
1026 
1027   if (_dbus_string_get_length (&correct_hash) == 0)
1028     {
1029       /* couldn't find the cookie ID or something */
1030       if (send_error (auth, "Don't have the requested cookie ID"))
1031         retval = TRUE;
1032       goto out_6;
1033     }
1034 
1035   _dbus_string_set_length (&tmp, 0);
1036 
1037   if (!_dbus_string_copy (&client_challenge, 0, &tmp,
1038                           _dbus_string_get_length (&tmp)))
1039     goto out_6;
1040 
1041   if (!_dbus_string_append (&tmp, " "))
1042     goto out_6;
1043 
1044   if (!_dbus_string_copy (&correct_hash, 0, &tmp,
1045                           _dbus_string_get_length (&tmp)))
1046     goto out_6;
1047 
1048   if (!send_data (auth, &tmp))
1049     goto out_6;
1050 
1051   retval = TRUE;
1052 
1053  out_6:
1054   _dbus_string_zero (&correct_hash);
1055   _dbus_string_free (&correct_hash);
1056  out_5:
1057   _dbus_string_free (&client_challenge);
1058  out_4:
1059   _dbus_string_zero (&tmp);
1060   _dbus_string_free (&tmp);
1061  out_3:
1062   _dbus_string_free (&server_challenge);
1063  out_2:
1064   _dbus_string_free (&cookie_id_str);
1065  out_1:
1066   _dbus_string_free (&context);
1067  out_0:
1068   return retval;
1069 }
1070 
1071 static void
handle_client_shutdown_cookie_sha1_mech(DBusAuth * auth)1072 handle_client_shutdown_cookie_sha1_mech (DBusAuth *auth)
1073 {
1074   auth->cookie_id = -1;
1075   _dbus_string_set_length (&auth->challenge, 0);
1076 }
1077 
1078 /*
1079  * EXTERNAL mechanism
1080  */
1081 
1082 static dbus_bool_t
handle_server_data_external_mech(DBusAuth * auth,const DBusString * data)1083 handle_server_data_external_mech (DBusAuth         *auth,
1084                                   const DBusString *data)
1085 {
1086   if (_dbus_credentials_are_anonymous (auth->credentials))
1087     {
1088       _dbus_verbose ("%s: no credentials, mechanism EXTERNAL can't authenticate\n",
1089                      DBUS_AUTH_NAME (auth));
1090       return send_rejected (auth);
1091     }
1092 
1093   if (_dbus_string_get_length (data) > 0)
1094     {
1095       if (_dbus_string_get_length (&auth->identity) > 0)
1096         {
1097           /* Tried to send two auth identities, wtf */
1098           _dbus_verbose ("%s: client tried to send auth identity, but we already have one\n",
1099                          DBUS_AUTH_NAME (auth));
1100           return send_rejected (auth);
1101         }
1102       else
1103         {
1104           /* this is our auth identity */
1105           if (!_dbus_string_copy (data, 0, &auth->identity, 0))
1106             return FALSE;
1107         }
1108     }
1109 
1110   /* Poke client for an auth identity, if none given */
1111   if (_dbus_string_get_length (&auth->identity) == 0 &&
1112       !auth->already_asked_for_initial_response)
1113     {
1114       if (send_data (auth, NULL))
1115         {
1116           _dbus_verbose ("%s: sending empty challenge asking client for auth identity\n",
1117                          DBUS_AUTH_NAME (auth));
1118           auth->already_asked_for_initial_response = TRUE;
1119           goto_state (auth, &server_state_waiting_for_data);
1120           return TRUE;
1121         }
1122       else
1123         return FALSE;
1124     }
1125 
1126   _dbus_credentials_clear (auth->desired_identity);
1127 
1128   /* If auth->identity is still empty here, then client
1129    * responded with an empty string after we poked it for
1130    * an initial response. This means to try to auth the
1131    * identity provided in the credentials.
1132    */
1133   if (_dbus_string_get_length (&auth->identity) == 0)
1134     {
1135       if (!_dbus_credentials_add_credentials (auth->desired_identity,
1136                                               auth->credentials))
1137         {
1138           return FALSE; /* OOM */
1139         }
1140     }
1141   else
1142     {
1143       if (!_dbus_credentials_add_from_user (auth->desired_identity,
1144                                             &auth->identity))
1145         {
1146           _dbus_verbose ("%s: could not get credentials from uid string\n",
1147                          DBUS_AUTH_NAME (auth));
1148           return send_rejected (auth);
1149         }
1150     }
1151 
1152   if (_dbus_credentials_are_anonymous (auth->desired_identity))
1153     {
1154       _dbus_verbose ("%s: desired user %s is no good\n",
1155                      DBUS_AUTH_NAME (auth),
1156                      _dbus_string_get_const_data (&auth->identity));
1157       return send_rejected (auth);
1158     }
1159 
1160   if (_dbus_credentials_are_superset (auth->credentials,
1161                                       auth->desired_identity))
1162     {
1163       /* client has authenticated */
1164       if (!_dbus_credentials_add_credentials (auth->authorized_identity,
1165                                               auth->desired_identity))
1166         return FALSE;
1167 
1168       /* also copy misc process info from the socket credentials
1169        */
1170       if (!_dbus_credentials_add_credential (auth->authorized_identity,
1171                                              DBUS_CREDENTIAL_UNIX_PROCESS_ID,
1172                                              auth->credentials))
1173         return FALSE;
1174 
1175       if (!_dbus_credentials_add_credential (auth->authorized_identity,
1176                                              DBUS_CREDENTIAL_ADT_AUDIT_DATA_ID,
1177                                              auth->credentials))
1178         return FALSE;
1179 
1180       if (!_dbus_credentials_add_credential (auth->authorized_identity,
1181                                              DBUS_CREDENTIAL_LINUX_SECURITY_LABEL,
1182                                              auth->credentials))
1183         return FALSE;
1184 
1185       if (!send_ok (auth))
1186         return FALSE;
1187 
1188       _dbus_verbose ("%s: authenticated client based on socket credentials\n",
1189                      DBUS_AUTH_NAME (auth));
1190 
1191       return TRUE;
1192     }
1193   else
1194     {
1195       _dbus_verbose ("%s: desired identity not found in socket credentials\n",
1196                      DBUS_AUTH_NAME (auth));
1197       return send_rejected (auth);
1198     }
1199 }
1200 
1201 static void
handle_server_shutdown_external_mech(DBusAuth * auth)1202 handle_server_shutdown_external_mech (DBusAuth *auth)
1203 {
1204 
1205 }
1206 
1207 static dbus_bool_t
handle_client_initial_response_external_mech(DBusAuth * auth,DBusString * response)1208 handle_client_initial_response_external_mech (DBusAuth         *auth,
1209                                               DBusString       *response)
1210 {
1211   /* We always append our UID as an initial response, so the server
1212    * doesn't have to send back an empty challenge to check whether we
1213    * want to specify an identity. i.e. this avoids a round trip that
1214    * the spec for the EXTERNAL mechanism otherwise requires.
1215    */
1216   DBusString plaintext;
1217 
1218   if (!_dbus_string_init (&plaintext))
1219     return FALSE;
1220 
1221   if (!_dbus_append_user_from_current_process (&plaintext))
1222     goto failed;
1223 
1224   if (!_dbus_string_hex_encode (&plaintext, 0,
1225 				response,
1226 				_dbus_string_get_length (response)))
1227     goto failed;
1228 
1229   _dbus_string_free (&plaintext);
1230 
1231   return TRUE;
1232 
1233  failed:
1234   _dbus_string_free (&plaintext);
1235   return FALSE;
1236 }
1237 
1238 static dbus_bool_t
handle_client_data_external_mech(DBusAuth * auth,const DBusString * data)1239 handle_client_data_external_mech (DBusAuth         *auth,
1240                                   const DBusString *data)
1241 {
1242 
1243   return TRUE;
1244 }
1245 
1246 static void
handle_client_shutdown_external_mech(DBusAuth * auth)1247 handle_client_shutdown_external_mech (DBusAuth *auth)
1248 {
1249 
1250 }
1251 
1252 /*
1253  * ANONYMOUS mechanism
1254  */
1255 
1256 static dbus_bool_t
handle_server_data_anonymous_mech(DBusAuth * auth,const DBusString * data)1257 handle_server_data_anonymous_mech (DBusAuth         *auth,
1258                                    const DBusString *data)
1259 {
1260   if (_dbus_string_get_length (data) > 0)
1261     {
1262       /* Client is allowed to send "trace" data, the only defined
1263        * meaning is that if it contains '@' it is an email address,
1264        * and otherwise it is anything else, and it's supposed to be
1265        * UTF-8
1266        */
1267       if (!_dbus_string_validate_utf8 (data, 0, _dbus_string_get_length (data)))
1268         {
1269           _dbus_verbose ("%s: Received invalid UTF-8 trace data from ANONYMOUS client\n",
1270                          DBUS_AUTH_NAME (auth));
1271           return send_rejected (auth);
1272         }
1273 
1274       _dbus_verbose ("%s: ANONYMOUS client sent trace string: '%s'\n",
1275                      DBUS_AUTH_NAME (auth),
1276                      _dbus_string_get_const_data (data));
1277     }
1278 
1279   /* We want to be anonymous (clear in case some other protocol got midway through I guess) */
1280   _dbus_credentials_clear (auth->desired_identity);
1281 
1282   /* Copy process ID from the socket credentials
1283    */
1284   if (!_dbus_credentials_add_credential (auth->authorized_identity,
1285                                          DBUS_CREDENTIAL_UNIX_PROCESS_ID,
1286                                          auth->credentials))
1287     return FALSE;
1288 
1289   /* Anonymous is always allowed */
1290   if (!send_ok (auth))
1291     return FALSE;
1292 
1293   _dbus_verbose ("%s: authenticated client as anonymous\n",
1294                  DBUS_AUTH_NAME (auth));
1295 
1296   return TRUE;
1297 }
1298 
1299 static void
handle_server_shutdown_anonymous_mech(DBusAuth * auth)1300 handle_server_shutdown_anonymous_mech (DBusAuth *auth)
1301 {
1302 
1303 }
1304 
1305 static dbus_bool_t
handle_client_initial_response_anonymous_mech(DBusAuth * auth,DBusString * response)1306 handle_client_initial_response_anonymous_mech (DBusAuth         *auth,
1307                                                DBusString       *response)
1308 {
1309   /* Our initial response is a "trace" string which must be valid UTF-8
1310    * and must be an email address if it contains '@'.
1311    * We just send the dbus implementation info, like a user-agent or
1312    * something, because... why not. There's nothing guaranteed here
1313    * though, we could change it later.
1314    */
1315   DBusString plaintext;
1316 
1317   if (!_dbus_string_init (&plaintext))
1318     return FALSE;
1319 
1320   if (!_dbus_string_append (&plaintext,
1321                             "libdbus " DBUS_VERSION_STRING))
1322     goto failed;
1323 
1324   if (!_dbus_string_hex_encode (&plaintext, 0,
1325 				response,
1326 				_dbus_string_get_length (response)))
1327     goto failed;
1328 
1329   _dbus_string_free (&plaintext);
1330 
1331   return TRUE;
1332 
1333  failed:
1334   _dbus_string_free (&plaintext);
1335   return FALSE;
1336 }
1337 
1338 static dbus_bool_t
handle_client_data_anonymous_mech(DBusAuth * auth,const DBusString * data)1339 handle_client_data_anonymous_mech (DBusAuth         *auth,
1340                                   const DBusString *data)
1341 {
1342 
1343   return TRUE;
1344 }
1345 
1346 static void
handle_client_shutdown_anonymous_mech(DBusAuth * auth)1347 handle_client_shutdown_anonymous_mech (DBusAuth *auth)
1348 {
1349 
1350 }
1351 
1352 /* Put mechanisms here in order of preference.
1353  * Right now we have:
1354  *
1355  * - EXTERNAL checks socket credentials (or in the future, other info from the OS)
1356  * - DBUS_COOKIE_SHA1 uses a cookie in the home directory, like xauth or ICE
1357  * - ANONYMOUS checks nothing but doesn't auth the person as a user
1358  *
1359  * We might ideally add a mechanism to chain to Cyrus SASL so we can
1360  * use its mechanisms as well.
1361  *
1362  */
1363 static const DBusAuthMechanismHandler
1364 all_mechanisms[] = {
1365   { "EXTERNAL",
1366     handle_server_data_external_mech,
1367     NULL, NULL,
1368     handle_server_shutdown_external_mech,
1369     handle_client_initial_response_external_mech,
1370     handle_client_data_external_mech,
1371     NULL, NULL,
1372     handle_client_shutdown_external_mech },
1373   { "DBUS_COOKIE_SHA1",
1374     handle_server_data_cookie_sha1_mech,
1375     NULL, NULL,
1376     handle_server_shutdown_cookie_sha1_mech,
1377     handle_client_initial_response_cookie_sha1_mech,
1378     handle_client_data_cookie_sha1_mech,
1379     NULL, NULL,
1380     handle_client_shutdown_cookie_sha1_mech },
1381   { "ANONYMOUS",
1382     handle_server_data_anonymous_mech,
1383     NULL, NULL,
1384     handle_server_shutdown_anonymous_mech,
1385     handle_client_initial_response_anonymous_mech,
1386     handle_client_data_anonymous_mech,
1387     NULL, NULL,
1388     handle_client_shutdown_anonymous_mech },
1389   { NULL, NULL }
1390 };
1391 
1392 static const DBusAuthMechanismHandler*
find_mech(const DBusString * name,char ** allowed_mechs)1393 find_mech (const DBusString  *name,
1394            char             **allowed_mechs)
1395 {
1396   int i;
1397 
1398   if (allowed_mechs != NULL &&
1399       !_dbus_string_array_contains ((const char**) allowed_mechs,
1400                                     _dbus_string_get_const_data (name)))
1401     return NULL;
1402 
1403   i = 0;
1404   while (all_mechanisms[i].mechanism != NULL)
1405     {
1406       if (_dbus_string_equal_c_str (name,
1407                                     all_mechanisms[i].mechanism))
1408 
1409         return &all_mechanisms[i];
1410 
1411       ++i;
1412     }
1413 
1414   return NULL;
1415 }
1416 
1417 static dbus_bool_t
send_auth(DBusAuth * auth,const DBusAuthMechanismHandler * mech)1418 send_auth (DBusAuth *auth, const DBusAuthMechanismHandler *mech)
1419 {
1420   DBusString auth_command;
1421 
1422   if (!_dbus_string_init (&auth_command))
1423     return FALSE;
1424 
1425   if (!_dbus_string_append (&auth_command,
1426                             "AUTH "))
1427     {
1428       _dbus_string_free (&auth_command);
1429       return FALSE;
1430     }
1431 
1432   if (!_dbus_string_append (&auth_command,
1433                             mech->mechanism))
1434     {
1435       _dbus_string_free (&auth_command);
1436       return FALSE;
1437     }
1438 
1439   if (mech->client_initial_response_func != NULL)
1440     {
1441       if (!_dbus_string_append (&auth_command, " "))
1442         {
1443           _dbus_string_free (&auth_command);
1444           return FALSE;
1445         }
1446 
1447       if (!(* mech->client_initial_response_func) (auth, &auth_command))
1448         {
1449           _dbus_string_free (&auth_command);
1450           return FALSE;
1451         }
1452     }
1453 
1454   if (!_dbus_string_append (&auth_command,
1455                             "\r\n"))
1456     {
1457       _dbus_string_free (&auth_command);
1458       return FALSE;
1459     }
1460 
1461   if (!_dbus_string_copy (&auth_command, 0,
1462                           &auth->outgoing,
1463                           _dbus_string_get_length (&auth->outgoing)))
1464     {
1465       _dbus_string_free (&auth_command);
1466       return FALSE;
1467     }
1468 
1469   _dbus_string_free (&auth_command);
1470   shutdown_mech (auth);
1471   auth->mech = mech;
1472   goto_state (auth, &client_state_waiting_for_data);
1473 
1474   return TRUE;
1475 }
1476 
1477 static dbus_bool_t
send_data(DBusAuth * auth,DBusString * data)1478 send_data (DBusAuth *auth, DBusString *data)
1479 {
1480   int old_len;
1481 
1482   if (data == NULL || _dbus_string_get_length (data) == 0)
1483     return _dbus_string_append (&auth->outgoing, "DATA\r\n");
1484   else
1485     {
1486       old_len = _dbus_string_get_length (&auth->outgoing);
1487       if (!_dbus_string_append (&auth->outgoing, "DATA "))
1488         goto out;
1489 
1490       if (!_dbus_string_hex_encode (data, 0, &auth->outgoing,
1491                                     _dbus_string_get_length (&auth->outgoing)))
1492         goto out;
1493 
1494       if (!_dbus_string_append (&auth->outgoing, "\r\n"))
1495         goto out;
1496 
1497       return TRUE;
1498 
1499     out:
1500       _dbus_string_set_length (&auth->outgoing, old_len);
1501 
1502       return FALSE;
1503     }
1504 }
1505 
1506 static dbus_bool_t
send_rejected(DBusAuth * auth)1507 send_rejected (DBusAuth *auth)
1508 {
1509   DBusString command;
1510   DBusAuthServer *server_auth;
1511   int i;
1512 
1513   if (!_dbus_string_init (&command))
1514     return FALSE;
1515 
1516   if (!_dbus_string_append (&command,
1517                             "REJECTED"))
1518     goto nomem;
1519 
1520   for (i = 0; all_mechanisms[i].mechanism != NULL; i++)
1521     {
1522       /* skip mechanisms that aren't allowed */
1523       if (auth->allowed_mechs != NULL &&
1524           !_dbus_string_array_contains ((const char**)auth->allowed_mechs,
1525                                         all_mechanisms[i].mechanism))
1526         continue;
1527 
1528       if (!_dbus_string_append (&command,
1529                                 " "))
1530         goto nomem;
1531 
1532       if (!_dbus_string_append (&command,
1533                                 all_mechanisms[i].mechanism))
1534         goto nomem;
1535     }
1536 
1537   if (!_dbus_string_append (&command, "\r\n"))
1538     goto nomem;
1539 
1540   if (!_dbus_string_copy (&command, 0, &auth->outgoing,
1541                           _dbus_string_get_length (&auth->outgoing)))
1542     goto nomem;
1543 
1544   shutdown_mech (auth);
1545 
1546   _dbus_assert (DBUS_AUTH_IS_SERVER (auth));
1547   server_auth = DBUS_AUTH_SERVER (auth);
1548   server_auth->failures += 1;
1549 
1550   if (server_auth->failures >= server_auth->max_failures)
1551     goto_state (auth, &common_state_need_disconnect);
1552   else
1553     goto_state (auth, &server_state_waiting_for_auth);
1554 
1555   _dbus_string_free (&command);
1556 
1557   return TRUE;
1558 
1559  nomem:
1560   _dbus_string_free (&command);
1561   return FALSE;
1562 }
1563 
1564 static dbus_bool_t
send_error(DBusAuth * auth,const char * message)1565 send_error (DBusAuth *auth, const char *message)
1566 {
1567   return _dbus_string_append_printf (&auth->outgoing,
1568                                      "ERROR \"%s\"\r\n", message);
1569 }
1570 
1571 static dbus_bool_t
send_ok(DBusAuth * auth)1572 send_ok (DBusAuth *auth)
1573 {
1574   int orig_len;
1575 
1576   orig_len = _dbus_string_get_length (&auth->outgoing);
1577 
1578   if (_dbus_string_append (&auth->outgoing, "OK ") &&
1579       _dbus_string_copy (& DBUS_AUTH_SERVER (auth)->guid,
1580                          0,
1581                          &auth->outgoing,
1582                          _dbus_string_get_length (&auth->outgoing)) &&
1583       _dbus_string_append (&auth->outgoing, "\r\n"))
1584     {
1585       goto_state (auth, &server_state_waiting_for_begin);
1586       return TRUE;
1587     }
1588   else
1589     {
1590       _dbus_string_set_length (&auth->outgoing, orig_len);
1591       return FALSE;
1592     }
1593 }
1594 
1595 static dbus_bool_t
send_begin(DBusAuth * auth)1596 send_begin (DBusAuth         *auth)
1597 {
1598 
1599   if (!_dbus_string_append (&auth->outgoing,
1600                             "BEGIN\r\n"))
1601     return FALSE;
1602 
1603   goto_state (auth, &common_state_authenticated);
1604   return TRUE;
1605 }
1606 
1607 static dbus_bool_t
process_ok(DBusAuth * auth,const DBusString * args_from_ok)1608 process_ok(DBusAuth *auth,
1609           const DBusString *args_from_ok) {
1610 
1611   int end_of_hex;
1612 
1613   /* "args_from_ok" should be the GUID, whitespace already pulled off the front */
1614   _dbus_assert (_dbus_string_get_length (& DBUS_AUTH_CLIENT (auth)->guid_from_server) == 0);
1615 
1616   /* We decode the hex string to binary, using guid_from_server as scratch... */
1617 
1618   end_of_hex = 0;
1619   if (!_dbus_string_hex_decode (args_from_ok, 0, &end_of_hex,
1620                                 & DBUS_AUTH_CLIENT (auth)->guid_from_server, 0))
1621     return FALSE;
1622 
1623   /* now clear out the scratch */
1624   _dbus_string_set_length (& DBUS_AUTH_CLIENT (auth)->guid_from_server, 0);
1625 
1626   if (end_of_hex != _dbus_string_get_length (args_from_ok) ||
1627       end_of_hex == 0)
1628     {
1629       _dbus_verbose ("Bad GUID from server, parsed %d bytes and had %d bytes from server\n",
1630                      end_of_hex, _dbus_string_get_length (args_from_ok));
1631       goto_state (auth, &common_state_need_disconnect);
1632       return TRUE;
1633     }
1634 
1635   if (!_dbus_string_copy (args_from_ok, 0, &DBUS_AUTH_CLIENT (auth)->guid_from_server, 0)) {
1636       _dbus_string_set_length (& DBUS_AUTH_CLIENT (auth)->guid_from_server, 0);
1637       return FALSE;
1638   }
1639 
1640   _dbus_verbose ("Got GUID '%s' from the server\n",
1641                  _dbus_string_get_const_data (& DBUS_AUTH_CLIENT (auth)->guid_from_server));
1642 
1643   if (auth->unix_fd_possible)
1644     return send_negotiate_unix_fd(auth);
1645 
1646   _dbus_verbose("Not negotiating unix fd passing, since not possible\n");
1647   return send_begin (auth);
1648 }
1649 
1650 static dbus_bool_t
send_cancel(DBusAuth * auth)1651 send_cancel (DBusAuth *auth)
1652 {
1653   if (_dbus_string_append (&auth->outgoing, "CANCEL\r\n"))
1654     {
1655       goto_state (auth, &client_state_waiting_for_reject);
1656       return TRUE;
1657     }
1658   else
1659     return FALSE;
1660 }
1661 
1662 static dbus_bool_t
process_data(DBusAuth * auth,const DBusString * args,DBusAuthDataFunction data_func)1663 process_data (DBusAuth             *auth,
1664               const DBusString     *args,
1665               DBusAuthDataFunction  data_func)
1666 {
1667   int end;
1668   DBusString decoded;
1669 
1670   if (!_dbus_string_init (&decoded))
1671     return FALSE;
1672 
1673   if (!_dbus_string_hex_decode (args, 0, &end, &decoded, 0))
1674     {
1675       _dbus_string_free (&decoded);
1676       return FALSE;
1677     }
1678 
1679   if (_dbus_string_get_length (args) != end)
1680     {
1681       _dbus_string_free (&decoded);
1682       if (!send_error (auth, "Invalid hex encoding"))
1683         return FALSE;
1684 
1685       return TRUE;
1686     }
1687 
1688 #ifdef DBUS_ENABLE_VERBOSE_MODE
1689   if (_dbus_string_validate_ascii (&decoded, 0,
1690                                    _dbus_string_get_length (&decoded)))
1691     _dbus_verbose ("%s: data: '%s'\n",
1692                    DBUS_AUTH_NAME (auth),
1693                    _dbus_string_get_const_data (&decoded));
1694 #endif
1695 
1696   if (!(* data_func) (auth, &decoded))
1697     {
1698       _dbus_string_free (&decoded);
1699       return FALSE;
1700     }
1701 
1702   _dbus_string_free (&decoded);
1703   return TRUE;
1704 }
1705 
1706 static dbus_bool_t
send_negotiate_unix_fd(DBusAuth * auth)1707 send_negotiate_unix_fd (DBusAuth *auth)
1708 {
1709   if (!_dbus_string_append (&auth->outgoing,
1710                             "NEGOTIATE_UNIX_FD\r\n"))
1711     return FALSE;
1712 
1713   goto_state (auth, &client_state_waiting_for_agree_unix_fd);
1714   return TRUE;
1715 }
1716 
1717 static dbus_bool_t
send_agree_unix_fd(DBusAuth * auth)1718 send_agree_unix_fd (DBusAuth *auth)
1719 {
1720   _dbus_assert(auth->unix_fd_possible);
1721 
1722   auth->unix_fd_negotiated = TRUE;
1723   _dbus_verbose("Agreed to UNIX FD passing\n");
1724 
1725   if (!_dbus_string_append (&auth->outgoing,
1726                             "AGREE_UNIX_FD\r\n"))
1727     return FALSE;
1728 
1729   goto_state (auth, &server_state_waiting_for_begin);
1730   return TRUE;
1731 }
1732 
1733 static dbus_bool_t
handle_auth(DBusAuth * auth,const DBusString * args)1734 handle_auth (DBusAuth *auth, const DBusString *args)
1735 {
1736   if (_dbus_string_get_length (args) == 0)
1737     {
1738       /* No args to the auth, send mechanisms */
1739       if (!send_rejected (auth))
1740         return FALSE;
1741 
1742       return TRUE;
1743     }
1744   else
1745     {
1746       int i;
1747       DBusString mech;
1748       DBusString hex_response;
1749 
1750       _dbus_string_find_blank (args, 0, &i);
1751 
1752       if (!_dbus_string_init (&mech))
1753         return FALSE;
1754 
1755       if (!_dbus_string_init (&hex_response))
1756         {
1757           _dbus_string_free (&mech);
1758           return FALSE;
1759         }
1760 
1761       if (!_dbus_string_copy_len (args, 0, i, &mech, 0))
1762         goto failed;
1763 
1764       _dbus_string_skip_blank (args, i, &i);
1765       if (!_dbus_string_copy (args, i, &hex_response, 0))
1766         goto failed;
1767 
1768       auth->mech = find_mech (&mech, auth->allowed_mechs);
1769       if (auth->mech != NULL)
1770         {
1771           _dbus_verbose ("%s: Trying mechanism %s\n",
1772                          DBUS_AUTH_NAME (auth),
1773                          auth->mech->mechanism);
1774 
1775           if (!process_data (auth, &hex_response,
1776                              auth->mech->server_data_func))
1777             goto failed;
1778         }
1779       else
1780         {
1781           /* Unsupported mechanism */
1782           _dbus_verbose ("%s: Unsupported mechanism %s\n",
1783                          DBUS_AUTH_NAME (auth),
1784                          _dbus_string_get_const_data (&mech));
1785 
1786           if (!send_rejected (auth))
1787             goto failed;
1788         }
1789 
1790       _dbus_string_free (&mech);
1791       _dbus_string_free (&hex_response);
1792 
1793       return TRUE;
1794 
1795     failed:
1796       auth->mech = NULL;
1797       _dbus_string_free (&mech);
1798       _dbus_string_free (&hex_response);
1799       return FALSE;
1800     }
1801 }
1802 
1803 static dbus_bool_t
handle_server_state_waiting_for_auth(DBusAuth * auth,DBusAuthCommand command,const DBusString * args)1804 handle_server_state_waiting_for_auth  (DBusAuth         *auth,
1805                                        DBusAuthCommand   command,
1806                                        const DBusString *args)
1807 {
1808   switch (command)
1809     {
1810     case DBUS_AUTH_COMMAND_AUTH:
1811       return handle_auth (auth, args);
1812 
1813     case DBUS_AUTH_COMMAND_CANCEL:
1814     case DBUS_AUTH_COMMAND_DATA:
1815       return send_error (auth, "Not currently in an auth conversation");
1816 
1817     case DBUS_AUTH_COMMAND_BEGIN:
1818       goto_state (auth, &common_state_need_disconnect);
1819       return TRUE;
1820 
1821     case DBUS_AUTH_COMMAND_ERROR:
1822       return send_rejected (auth);
1823 
1824     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
1825       return send_error (auth, "Need to authenticate first");
1826 
1827     case DBUS_AUTH_COMMAND_REJECTED:
1828     case DBUS_AUTH_COMMAND_OK:
1829     case DBUS_AUTH_COMMAND_UNKNOWN:
1830     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
1831     default:
1832       return send_error (auth, "Unknown command");
1833     }
1834 }
1835 
1836 static dbus_bool_t
handle_server_state_waiting_for_data(DBusAuth * auth,DBusAuthCommand command,const DBusString * args)1837 handle_server_state_waiting_for_data  (DBusAuth         *auth,
1838                                        DBusAuthCommand   command,
1839                                        const DBusString *args)
1840 {
1841   switch (command)
1842     {
1843     case DBUS_AUTH_COMMAND_AUTH:
1844       return send_error (auth, "Sent AUTH while another AUTH in progress");
1845 
1846     case DBUS_AUTH_COMMAND_CANCEL:
1847     case DBUS_AUTH_COMMAND_ERROR:
1848       return send_rejected (auth);
1849 
1850     case DBUS_AUTH_COMMAND_DATA:
1851       return process_data (auth, args, auth->mech->server_data_func);
1852 
1853     case DBUS_AUTH_COMMAND_BEGIN:
1854       goto_state (auth, &common_state_need_disconnect);
1855       return TRUE;
1856 
1857     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
1858       return send_error (auth, "Need to authenticate first");
1859 
1860     case DBUS_AUTH_COMMAND_REJECTED:
1861     case DBUS_AUTH_COMMAND_OK:
1862     case DBUS_AUTH_COMMAND_UNKNOWN:
1863     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
1864     default:
1865       return send_error (auth, "Unknown command");
1866     }
1867 }
1868 
1869 static dbus_bool_t
handle_server_state_waiting_for_begin(DBusAuth * auth,DBusAuthCommand command,const DBusString * args)1870 handle_server_state_waiting_for_begin (DBusAuth         *auth,
1871                                        DBusAuthCommand   command,
1872                                        const DBusString *args)
1873 {
1874   switch (command)
1875     {
1876     case DBUS_AUTH_COMMAND_AUTH:
1877       return send_error (auth, "Sent AUTH while expecting BEGIN");
1878 
1879     case DBUS_AUTH_COMMAND_DATA:
1880       return send_error (auth, "Sent DATA while expecting BEGIN");
1881 
1882     case DBUS_AUTH_COMMAND_BEGIN:
1883       goto_state (auth, &common_state_authenticated);
1884       return TRUE;
1885 
1886     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
1887       if (auth->unix_fd_possible)
1888         return send_agree_unix_fd(auth);
1889       else
1890         return send_error(auth, "Unix FD passing not supported, not authenticated or otherwise not possible");
1891 
1892     case DBUS_AUTH_COMMAND_REJECTED:
1893     case DBUS_AUTH_COMMAND_OK:
1894     case DBUS_AUTH_COMMAND_UNKNOWN:
1895     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
1896     default:
1897       return send_error (auth, "Unknown command");
1898 
1899     case DBUS_AUTH_COMMAND_CANCEL:
1900     case DBUS_AUTH_COMMAND_ERROR:
1901       return send_rejected (auth);
1902     }
1903 }
1904 
1905 /* return FALSE if no memory, TRUE if all OK */
1906 static dbus_bool_t
get_word(const DBusString * str,int * start,DBusString * word)1907 get_word (const DBusString *str,
1908           int              *start,
1909           DBusString       *word)
1910 {
1911   int i;
1912 
1913   _dbus_string_skip_blank (str, *start, start);
1914   _dbus_string_find_blank (str, *start, &i);
1915 
1916   if (i > *start)
1917     {
1918       if (!_dbus_string_copy_len (str, *start, i - *start, word, 0))
1919         return FALSE;
1920 
1921       *start = i;
1922     }
1923 
1924   return TRUE;
1925 }
1926 
1927 static dbus_bool_t
record_mechanisms(DBusAuth * auth,const DBusString * args)1928 record_mechanisms (DBusAuth         *auth,
1929                    const DBusString *args)
1930 {
1931   int next;
1932   int len;
1933 
1934   if (auth->already_got_mechanisms)
1935     return TRUE;
1936 
1937   len = _dbus_string_get_length (args);
1938 
1939   next = 0;
1940   while (next < len)
1941     {
1942       DBusString m;
1943       const DBusAuthMechanismHandler *mech;
1944 
1945       if (!_dbus_string_init (&m))
1946         goto nomem;
1947 
1948       if (!get_word (args, &next, &m))
1949         {
1950           _dbus_string_free (&m);
1951           goto nomem;
1952         }
1953 
1954       mech = find_mech (&m, auth->allowed_mechs);
1955 
1956       if (mech != NULL)
1957         {
1958           /* FIXME right now we try mechanisms in the order
1959            * the server lists them; should we do them in
1960            * some more deterministic order?
1961            *
1962            * Probably in all_mechanisms order, our order of
1963            * preference. Of course when the server is us,
1964            * it lists things in that order anyhow.
1965            */
1966 
1967           if (mech != &all_mechanisms[0])
1968             {
1969               _dbus_verbose ("%s: Adding mechanism %s to list we will try\n",
1970                              DBUS_AUTH_NAME (auth), mech->mechanism);
1971 
1972               if (!_dbus_list_append (& DBUS_AUTH_CLIENT (auth)->mechs_to_try,
1973                                       (void*) mech))
1974                 {
1975                   _dbus_string_free (&m);
1976                   goto nomem;
1977                 }
1978             }
1979           else
1980             {
1981               _dbus_verbose ("%s: Already tried mechanism %s; not adding to list we will try\n",
1982                              DBUS_AUTH_NAME (auth), mech->mechanism);
1983             }
1984         }
1985       else
1986         {
1987           _dbus_verbose ("%s: Server offered mechanism \"%s\" that we don't know how to use\n",
1988                          DBUS_AUTH_NAME (auth),
1989                          _dbus_string_get_const_data (&m));
1990         }
1991 
1992       _dbus_string_free (&m);
1993     }
1994 
1995   auth->already_got_mechanisms = TRUE;
1996 
1997   return TRUE;
1998 
1999  nomem:
2000   _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
2001 
2002   return FALSE;
2003 }
2004 
2005 static dbus_bool_t
process_rejected(DBusAuth * auth,const DBusString * args)2006 process_rejected (DBusAuth *auth, const DBusString *args)
2007 {
2008   const DBusAuthMechanismHandler *mech;
2009   DBusAuthClient *client;
2010 
2011   client = DBUS_AUTH_CLIENT (auth);
2012 
2013   if (!auth->already_got_mechanisms)
2014     {
2015       if (!record_mechanisms (auth, args))
2016         return FALSE;
2017     }
2018 
2019   if (DBUS_AUTH_CLIENT (auth)->mechs_to_try != NULL)
2020     {
2021       mech = client->mechs_to_try->data;
2022 
2023       if (!send_auth (auth, mech))
2024         return FALSE;
2025 
2026       _dbus_list_pop_first (&client->mechs_to_try);
2027 
2028       _dbus_verbose ("%s: Trying mechanism %s\n",
2029                      DBUS_AUTH_NAME (auth),
2030                      mech->mechanism);
2031     }
2032   else
2033     {
2034       /* Give up */
2035       _dbus_verbose ("%s: Disconnecting because we are out of mechanisms to try using\n",
2036                      DBUS_AUTH_NAME (auth));
2037       goto_state (auth, &common_state_need_disconnect);
2038     }
2039 
2040   return TRUE;
2041 }
2042 
2043 
2044 static dbus_bool_t
handle_client_state_waiting_for_data(DBusAuth * auth,DBusAuthCommand command,const DBusString * args)2045 handle_client_state_waiting_for_data (DBusAuth         *auth,
2046                                       DBusAuthCommand   command,
2047                                       const DBusString *args)
2048 {
2049   _dbus_assert (auth->mech != NULL);
2050 
2051   switch (command)
2052     {
2053     case DBUS_AUTH_COMMAND_DATA:
2054       return process_data (auth, args, auth->mech->client_data_func);
2055 
2056     case DBUS_AUTH_COMMAND_REJECTED:
2057       return process_rejected (auth, args);
2058 
2059     case DBUS_AUTH_COMMAND_OK:
2060       return process_ok(auth, args);
2061 
2062     case DBUS_AUTH_COMMAND_ERROR:
2063       return send_cancel (auth);
2064 
2065     case DBUS_AUTH_COMMAND_AUTH:
2066     case DBUS_AUTH_COMMAND_CANCEL:
2067     case DBUS_AUTH_COMMAND_BEGIN:
2068     case DBUS_AUTH_COMMAND_UNKNOWN:
2069     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2070     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2071     default:
2072       return send_error (auth, "Unknown command");
2073     }
2074 }
2075 
2076 static dbus_bool_t
handle_client_state_waiting_for_ok(DBusAuth * auth,DBusAuthCommand command,const DBusString * args)2077 handle_client_state_waiting_for_ok (DBusAuth         *auth,
2078                                     DBusAuthCommand   command,
2079                                     const DBusString *args)
2080 {
2081   switch (command)
2082     {
2083     case DBUS_AUTH_COMMAND_REJECTED:
2084       return process_rejected (auth, args);
2085 
2086     case DBUS_AUTH_COMMAND_OK:
2087       return process_ok(auth, args);
2088 
2089     case DBUS_AUTH_COMMAND_DATA:
2090     case DBUS_AUTH_COMMAND_ERROR:
2091       return send_cancel (auth);
2092 
2093     case DBUS_AUTH_COMMAND_AUTH:
2094     case DBUS_AUTH_COMMAND_CANCEL:
2095     case DBUS_AUTH_COMMAND_BEGIN:
2096     case DBUS_AUTH_COMMAND_UNKNOWN:
2097     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2098     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2099     default:
2100       return send_error (auth, "Unknown command");
2101     }
2102 }
2103 
2104 static dbus_bool_t
handle_client_state_waiting_for_reject(DBusAuth * auth,DBusAuthCommand command,const DBusString * args)2105 handle_client_state_waiting_for_reject (DBusAuth         *auth,
2106                                         DBusAuthCommand   command,
2107                                         const DBusString *args)
2108 {
2109   switch (command)
2110     {
2111     case DBUS_AUTH_COMMAND_REJECTED:
2112       return process_rejected (auth, args);
2113 
2114     case DBUS_AUTH_COMMAND_AUTH:
2115     case DBUS_AUTH_COMMAND_CANCEL:
2116     case DBUS_AUTH_COMMAND_DATA:
2117     case DBUS_AUTH_COMMAND_BEGIN:
2118     case DBUS_AUTH_COMMAND_OK:
2119     case DBUS_AUTH_COMMAND_ERROR:
2120     case DBUS_AUTH_COMMAND_UNKNOWN:
2121     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2122     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2123     default:
2124       goto_state (auth, &common_state_need_disconnect);
2125       return TRUE;
2126     }
2127 }
2128 
2129 static dbus_bool_t
handle_client_state_waiting_for_agree_unix_fd(DBusAuth * auth,DBusAuthCommand command,const DBusString * args)2130 handle_client_state_waiting_for_agree_unix_fd(DBusAuth         *auth,
2131                                               DBusAuthCommand   command,
2132                                               const DBusString *args)
2133 {
2134   switch (command)
2135     {
2136     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2137       _dbus_assert(auth->unix_fd_possible);
2138       auth->unix_fd_negotiated = TRUE;
2139       _dbus_verbose("Successfully negotiated UNIX FD passing\n");
2140       return send_begin (auth);
2141 
2142     case DBUS_AUTH_COMMAND_ERROR:
2143       _dbus_assert(auth->unix_fd_possible);
2144       auth->unix_fd_negotiated = FALSE;
2145       _dbus_verbose("Failed to negotiate UNIX FD passing\n");
2146       return send_begin (auth);
2147 
2148     case DBUS_AUTH_COMMAND_OK:
2149     case DBUS_AUTH_COMMAND_DATA:
2150     case DBUS_AUTH_COMMAND_REJECTED:
2151     case DBUS_AUTH_COMMAND_AUTH:
2152     case DBUS_AUTH_COMMAND_CANCEL:
2153     case DBUS_AUTH_COMMAND_BEGIN:
2154     case DBUS_AUTH_COMMAND_UNKNOWN:
2155     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2156     default:
2157       return send_error (auth, "Unknown command");
2158     }
2159 }
2160 
2161 /**
2162  * Mapping from command name to enum
2163  */
2164 typedef struct {
2165   const char *name;        /**< Name of the command */
2166   DBusAuthCommand command; /**< Corresponding enum */
2167 } DBusAuthCommandName;
2168 
2169 static const DBusAuthCommandName auth_command_names[] = {
2170   { "AUTH",              DBUS_AUTH_COMMAND_AUTH },
2171   { "CANCEL",            DBUS_AUTH_COMMAND_CANCEL },
2172   { "DATA",              DBUS_AUTH_COMMAND_DATA },
2173   { "BEGIN",             DBUS_AUTH_COMMAND_BEGIN },
2174   { "REJECTED",          DBUS_AUTH_COMMAND_REJECTED },
2175   { "OK",                DBUS_AUTH_COMMAND_OK },
2176   { "ERROR",             DBUS_AUTH_COMMAND_ERROR },
2177   { "NEGOTIATE_UNIX_FD", DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD },
2178   { "AGREE_UNIX_FD",     DBUS_AUTH_COMMAND_AGREE_UNIX_FD }
2179 };
2180 
2181 static DBusAuthCommand
lookup_command_from_name(DBusString * command)2182 lookup_command_from_name (DBusString *command)
2183 {
2184   int i;
2185 
2186   for (i = 0; i < _DBUS_N_ELEMENTS (auth_command_names); i++)
2187     {
2188       if (_dbus_string_equal_c_str (command,
2189                                     auth_command_names[i].name))
2190         return auth_command_names[i].command;
2191     }
2192 
2193   return DBUS_AUTH_COMMAND_UNKNOWN;
2194 }
2195 
2196 static void
goto_state(DBusAuth * auth,const DBusAuthStateData * state)2197 goto_state (DBusAuth *auth,
2198             const DBusAuthStateData *state)
2199 {
2200   _dbus_verbose ("%s: going from state %s to state %s\n",
2201                  DBUS_AUTH_NAME (auth),
2202                  auth->state->name,
2203                  state->name);
2204 
2205   auth->state = state;
2206 }
2207 
2208 /* returns whether to call it again right away */
2209 static dbus_bool_t
process_command(DBusAuth * auth)2210 process_command (DBusAuth *auth)
2211 {
2212   DBusAuthCommand command;
2213   DBusString line;
2214   DBusString args;
2215   int eol;
2216   int i, j;
2217   dbus_bool_t retval;
2218 
2219   /* _dbus_verbose ("%s:   trying process_command()\n"); */
2220 
2221   retval = FALSE;
2222 
2223   eol = 0;
2224   if (!_dbus_string_find (&auth->incoming, 0, "\r\n", &eol))
2225     return FALSE;
2226 
2227   if (!_dbus_string_init (&line))
2228     {
2229       auth->needed_memory = TRUE;
2230       return FALSE;
2231     }
2232 
2233   if (!_dbus_string_init (&args))
2234     {
2235       _dbus_string_free (&line);
2236       auth->needed_memory = TRUE;
2237       return FALSE;
2238     }
2239 
2240   if (!_dbus_string_copy_len (&auth->incoming, 0, eol, &line, 0))
2241     goto out;
2242 
2243   if (!_dbus_string_validate_ascii (&line, 0,
2244                                     _dbus_string_get_length (&line)))
2245     {
2246       _dbus_verbose ("%s: Command contained non-ASCII chars or embedded nul\n",
2247                      DBUS_AUTH_NAME (auth));
2248       if (!send_error (auth, "Command contained non-ASCII"))
2249         goto out;
2250       else
2251         goto next_command;
2252     }
2253 
2254   _dbus_verbose ("%s: got command \"%s\"\n",
2255                  DBUS_AUTH_NAME (auth),
2256                  _dbus_string_get_const_data (&line));
2257 
2258   _dbus_string_find_blank (&line, 0, &i);
2259   _dbus_string_skip_blank (&line, i, &j);
2260 
2261   if (j > i)
2262     _dbus_string_delete (&line, i, j - i);
2263 
2264   if (!_dbus_string_move (&line, i, &args, 0))
2265     goto out;
2266 
2267   /* FIXME 1.0 we should probably validate that only the allowed
2268    * chars are in the command name
2269    */
2270 
2271   command = lookup_command_from_name (&line);
2272   if (!(* auth->state->handler) (auth, command, &args))
2273     goto out;
2274 
2275  next_command:
2276 
2277   /* We've succeeded in processing the whole command so drop it out
2278    * of the incoming buffer and return TRUE to try another command.
2279    */
2280 
2281   _dbus_string_delete (&auth->incoming, 0, eol);
2282 
2283   /* kill the \r\n */
2284   _dbus_string_delete (&auth->incoming, 0, 2);
2285 
2286   retval = TRUE;
2287 
2288  out:
2289   _dbus_string_free (&args);
2290   _dbus_string_free (&line);
2291 
2292   if (!retval)
2293     auth->needed_memory = TRUE;
2294   else
2295     auth->needed_memory = FALSE;
2296 
2297   return retval;
2298 }
2299 
2300 
2301 /** @} */
2302 
2303 /**
2304  * @addtogroup DBusAuth
2305  * @{
2306  */
2307 
2308 /**
2309  * Creates a new auth conversation object for the server side.
2310  * See http://dbus.freedesktop.org/doc/dbus-specification.html#auth-protocol
2311  * for full details on what this object does.
2312  *
2313  * @returns the new object or #NULL if no memory
2314  */
2315 DBusAuth*
_dbus_auth_server_new(const DBusString * guid)2316 _dbus_auth_server_new (const DBusString *guid)
2317 {
2318   DBusAuth *auth;
2319   DBusAuthServer *server_auth;
2320   DBusString guid_copy;
2321 
2322   if (!_dbus_string_init (&guid_copy))
2323     return NULL;
2324 
2325   if (!_dbus_string_copy (guid, 0, &guid_copy, 0))
2326     {
2327       _dbus_string_free (&guid_copy);
2328       return NULL;
2329     }
2330 
2331   auth = _dbus_auth_new (sizeof (DBusAuthServer));
2332   if (auth == NULL)
2333     {
2334       _dbus_string_free (&guid_copy);
2335       return NULL;
2336     }
2337 
2338   auth->side = auth_side_server;
2339   auth->state = &server_state_waiting_for_auth;
2340 
2341   server_auth = DBUS_AUTH_SERVER (auth);
2342 
2343   server_auth->guid = guid_copy;
2344 
2345   /* perhaps this should be per-mechanism with a lower
2346    * max
2347    */
2348   server_auth->failures = 0;
2349   server_auth->max_failures = 6;
2350 
2351   return auth;
2352 }
2353 
2354 /**
2355  * Creates a new auth conversation object for the client side.
2356  * See http://dbus.freedesktop.org/doc/dbus-specification.html#auth-protocol
2357  * for full details on what this object does.
2358  *
2359  * @returns the new object or #NULL if no memory
2360  */
2361 DBusAuth*
_dbus_auth_client_new(void)2362 _dbus_auth_client_new (void)
2363 {
2364   DBusAuth *auth;
2365   DBusString guid_str;
2366 
2367   if (!_dbus_string_init (&guid_str))
2368     return NULL;
2369 
2370   auth = _dbus_auth_new (sizeof (DBusAuthClient));
2371   if (auth == NULL)
2372     {
2373       _dbus_string_free (&guid_str);
2374       return NULL;
2375     }
2376 
2377   DBUS_AUTH_CLIENT (auth)->guid_from_server = guid_str;
2378 
2379   auth->side = auth_side_client;
2380   auth->state = &client_state_need_send_auth;
2381 
2382   /* Start the auth conversation by sending AUTH for our default
2383    * mechanism */
2384   if (!send_auth (auth, &all_mechanisms[0]))
2385     {
2386       _dbus_auth_unref (auth);
2387       return NULL;
2388     }
2389 
2390   return auth;
2391 }
2392 
2393 /**
2394  * Increments the refcount of an auth object.
2395  *
2396  * @param auth the auth conversation
2397  * @returns the auth conversation
2398  */
2399 DBusAuth *
_dbus_auth_ref(DBusAuth * auth)2400 _dbus_auth_ref (DBusAuth *auth)
2401 {
2402   _dbus_assert (auth != NULL);
2403 
2404   auth->refcount += 1;
2405 
2406   return auth;
2407 }
2408 
2409 /**
2410  * Decrements the refcount of an auth object.
2411  *
2412  * @param auth the auth conversation
2413  */
2414 void
_dbus_auth_unref(DBusAuth * auth)2415 _dbus_auth_unref (DBusAuth *auth)
2416 {
2417   _dbus_assert (auth != NULL);
2418   _dbus_assert (auth->refcount > 0);
2419 
2420   auth->refcount -= 1;
2421   if (auth->refcount == 0)
2422     {
2423       shutdown_mech (auth);
2424 
2425       if (DBUS_AUTH_IS_CLIENT (auth))
2426         {
2427           _dbus_string_free (& DBUS_AUTH_CLIENT (auth)->guid_from_server);
2428           _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
2429         }
2430       else
2431         {
2432           _dbus_assert (DBUS_AUTH_IS_SERVER (auth));
2433 
2434           _dbus_string_free (& DBUS_AUTH_SERVER (auth)->guid);
2435         }
2436 
2437       if (auth->keyring)
2438         _dbus_keyring_unref (auth->keyring);
2439 
2440       _dbus_string_free (&auth->context);
2441       _dbus_string_free (&auth->challenge);
2442       _dbus_string_free (&auth->identity);
2443       _dbus_string_free (&auth->incoming);
2444       _dbus_string_free (&auth->outgoing);
2445 
2446       dbus_free_string_array (auth->allowed_mechs);
2447 
2448       _dbus_credentials_unref (auth->credentials);
2449       _dbus_credentials_unref (auth->authorized_identity);
2450       _dbus_credentials_unref (auth->desired_identity);
2451 
2452       dbus_free (auth);
2453     }
2454 }
2455 
2456 /**
2457  * Sets an array of authentication mechanism names
2458  * that we are willing to use.
2459  *
2460  * @param auth the auth conversation
2461  * @param mechanisms #NULL-terminated array of mechanism names
2462  * @returns #FALSE if no memory
2463  */
2464 dbus_bool_t
_dbus_auth_set_mechanisms(DBusAuth * auth,const char ** mechanisms)2465 _dbus_auth_set_mechanisms (DBusAuth    *auth,
2466                            const char **mechanisms)
2467 {
2468   char **copy;
2469 
2470   if (mechanisms != NULL)
2471     {
2472       copy = _dbus_dup_string_array (mechanisms);
2473       if (copy == NULL)
2474         return FALSE;
2475     }
2476   else
2477     copy = NULL;
2478 
2479   dbus_free_string_array (auth->allowed_mechs);
2480 
2481   auth->allowed_mechs = copy;
2482 
2483   return TRUE;
2484 }
2485 
2486 /**
2487  * @param auth the auth conversation object
2488  * @returns #TRUE if we're in a final state
2489  */
2490 #define DBUS_AUTH_IN_END_STATE(auth) ((auth)->state->handler == NULL)
2491 
2492 /**
2493  * Analyzes buffered input and moves the auth conversation forward,
2494  * returning the new state of the auth conversation.
2495  *
2496  * @param auth the auth conversation
2497  * @returns the new state
2498  */
2499 DBusAuthState
_dbus_auth_do_work(DBusAuth * auth)2500 _dbus_auth_do_work (DBusAuth *auth)
2501 {
2502   auth->needed_memory = FALSE;
2503 
2504   /* Max amount we'll buffer up before deciding someone's on crack */
2505 #define MAX_BUFFER (16 * _DBUS_ONE_KILOBYTE)
2506 
2507   do
2508     {
2509       if (DBUS_AUTH_IN_END_STATE (auth))
2510         break;
2511 
2512       if (_dbus_string_get_length (&auth->incoming) > MAX_BUFFER ||
2513           _dbus_string_get_length (&auth->outgoing) > MAX_BUFFER)
2514         {
2515           goto_state (auth, &common_state_need_disconnect);
2516           _dbus_verbose ("%s: Disconnecting due to excessive data buffered in auth phase\n",
2517                          DBUS_AUTH_NAME (auth));
2518           break;
2519         }
2520     }
2521   while (process_command (auth));
2522 
2523   if (auth->needed_memory)
2524     return DBUS_AUTH_STATE_WAITING_FOR_MEMORY;
2525   else if (_dbus_string_get_length (&auth->outgoing) > 0)
2526     return DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND;
2527   else if (auth->state == &common_state_need_disconnect)
2528     return DBUS_AUTH_STATE_NEED_DISCONNECT;
2529   else if (auth->state == &common_state_authenticated)
2530     return DBUS_AUTH_STATE_AUTHENTICATED;
2531   else return DBUS_AUTH_STATE_WAITING_FOR_INPUT;
2532 }
2533 
2534 /**
2535  * Gets bytes that need to be sent to the peer we're conversing with.
2536  * After writing some bytes, _dbus_auth_bytes_sent() must be called
2537  * to notify the auth object that they were written.
2538  *
2539  * @param auth the auth conversation
2540  * @param str return location for a ref to the buffer to send
2541  * @returns #FALSE if nothing to send
2542  */
2543 dbus_bool_t
_dbus_auth_get_bytes_to_send(DBusAuth * auth,const DBusString ** str)2544 _dbus_auth_get_bytes_to_send (DBusAuth          *auth,
2545                               const DBusString **str)
2546 {
2547   _dbus_assert (auth != NULL);
2548   _dbus_assert (str != NULL);
2549 
2550   *str = NULL;
2551 
2552   if (_dbus_string_get_length (&auth->outgoing) == 0)
2553     return FALSE;
2554 
2555   *str = &auth->outgoing;
2556 
2557   return TRUE;
2558 }
2559 
2560 /**
2561  * Notifies the auth conversation object that
2562  * the given number of bytes of the outgoing buffer
2563  * have been written out.
2564  *
2565  * @param auth the auth conversation
2566  * @param bytes_sent number of bytes written out
2567  */
2568 void
_dbus_auth_bytes_sent(DBusAuth * auth,int bytes_sent)2569 _dbus_auth_bytes_sent (DBusAuth *auth,
2570                        int       bytes_sent)
2571 {
2572   _dbus_verbose ("%s: Sent %d bytes of: %s\n",
2573                  DBUS_AUTH_NAME (auth),
2574                  bytes_sent,
2575                  _dbus_string_get_const_data (&auth->outgoing));
2576 
2577   _dbus_string_delete (&auth->outgoing,
2578                        0, bytes_sent);
2579 }
2580 
2581 /**
2582  * Get a buffer to be used for reading bytes from the peer we're conversing
2583  * with. Bytes should be appended to this buffer.
2584  *
2585  * @param auth the auth conversation
2586  * @param buffer return location for buffer to append bytes to
2587  */
2588 void
_dbus_auth_get_buffer(DBusAuth * auth,DBusString ** buffer)2589 _dbus_auth_get_buffer (DBusAuth     *auth,
2590                        DBusString **buffer)
2591 {
2592   _dbus_assert (auth != NULL);
2593   _dbus_assert (!auth->buffer_outstanding);
2594 
2595   *buffer = &auth->incoming;
2596 
2597   auth->buffer_outstanding = TRUE;
2598 }
2599 
2600 /**
2601  * Returns a buffer with new data read into it.
2602  *
2603  * @param auth the auth conversation
2604  * @param buffer the buffer being returned
2605  */
2606 void
_dbus_auth_return_buffer(DBusAuth * auth,DBusString * buffer)2607 _dbus_auth_return_buffer (DBusAuth               *auth,
2608                           DBusString             *buffer)
2609 {
2610   _dbus_assert (buffer == &auth->incoming);
2611   _dbus_assert (auth->buffer_outstanding);
2612 
2613   auth->buffer_outstanding = FALSE;
2614 }
2615 
2616 /**
2617  * Returns leftover bytes that were not used as part of the auth
2618  * conversation.  These bytes will be part of the message stream
2619  * instead. This function may not be called until authentication has
2620  * succeeded.
2621  *
2622  * @param auth the auth conversation
2623  * @param str return location for pointer to string of unused bytes
2624  */
2625 void
_dbus_auth_get_unused_bytes(DBusAuth * auth,const DBusString ** str)2626 _dbus_auth_get_unused_bytes (DBusAuth           *auth,
2627                              const DBusString **str)
2628 {
2629   if (!DBUS_AUTH_IN_END_STATE (auth))
2630     return;
2631 
2632   *str = &auth->incoming;
2633 }
2634 
2635 
2636 /**
2637  * Gets rid of unused bytes returned by _dbus_auth_get_unused_bytes()
2638  * after we've gotten them and successfully moved them elsewhere.
2639  *
2640  * @param auth the auth conversation
2641  */
2642 void
_dbus_auth_delete_unused_bytes(DBusAuth * auth)2643 _dbus_auth_delete_unused_bytes (DBusAuth *auth)
2644 {
2645   if (!DBUS_AUTH_IN_END_STATE (auth))
2646     return;
2647 
2648   _dbus_string_set_length (&auth->incoming, 0);
2649 }
2650 
2651 /**
2652  * Called post-authentication, indicates whether we need to encode
2653  * the message stream with _dbus_auth_encode_data() prior to
2654  * sending it to the peer.
2655  *
2656  * @param auth the auth conversation
2657  * @returns #TRUE if we need to encode the stream
2658  */
2659 dbus_bool_t
_dbus_auth_needs_encoding(DBusAuth * auth)2660 _dbus_auth_needs_encoding (DBusAuth *auth)
2661 {
2662   if (auth->state != &common_state_authenticated)
2663     return FALSE;
2664 
2665   if (auth->mech != NULL)
2666     {
2667       if (DBUS_AUTH_IS_CLIENT (auth))
2668         return auth->mech->client_encode_func != NULL;
2669       else
2670         return auth->mech->server_encode_func != NULL;
2671     }
2672   else
2673     return FALSE;
2674 }
2675 
2676 /**
2677  * Called post-authentication, encodes a block of bytes for sending to
2678  * the peer. If no encoding was negotiated, just copies the bytes
2679  * (you can avoid this by checking _dbus_auth_needs_encoding()).
2680  *
2681  * @param auth the auth conversation
2682  * @param plaintext the plain text data
2683  * @param encoded initialized string to where encoded data is appended
2684  * @returns #TRUE if we had enough memory and successfully encoded
2685  */
2686 dbus_bool_t
_dbus_auth_encode_data(DBusAuth * auth,const DBusString * plaintext,DBusString * encoded)2687 _dbus_auth_encode_data (DBusAuth         *auth,
2688                         const DBusString *plaintext,
2689                         DBusString       *encoded)
2690 {
2691   _dbus_assert (plaintext != encoded);
2692 
2693   if (auth->state != &common_state_authenticated)
2694     return FALSE;
2695 
2696   if (_dbus_auth_needs_encoding (auth))
2697     {
2698       if (DBUS_AUTH_IS_CLIENT (auth))
2699         return (* auth->mech->client_encode_func) (auth, plaintext, encoded);
2700       else
2701         return (* auth->mech->server_encode_func) (auth, plaintext, encoded);
2702     }
2703   else
2704     {
2705       return _dbus_string_copy (plaintext, 0, encoded,
2706                                 _dbus_string_get_length (encoded));
2707     }
2708 }
2709 
2710 /**
2711  * Called post-authentication, indicates whether we need to decode
2712  * the message stream with _dbus_auth_decode_data() after
2713  * receiving it from the peer.
2714  *
2715  * @param auth the auth conversation
2716  * @returns #TRUE if we need to encode the stream
2717  */
2718 dbus_bool_t
_dbus_auth_needs_decoding(DBusAuth * auth)2719 _dbus_auth_needs_decoding (DBusAuth *auth)
2720 {
2721   if (auth->state != &common_state_authenticated)
2722     return FALSE;
2723 
2724   if (auth->mech != NULL)
2725     {
2726       if (DBUS_AUTH_IS_CLIENT (auth))
2727         return auth->mech->client_decode_func != NULL;
2728       else
2729         return auth->mech->server_decode_func != NULL;
2730     }
2731   else
2732     return FALSE;
2733 }
2734 
2735 
2736 /**
2737  * Called post-authentication, decodes a block of bytes received from
2738  * the peer. If no encoding was negotiated, just copies the bytes (you
2739  * can avoid this by checking _dbus_auth_needs_decoding()).
2740  *
2741  * @todo 1.0? We need to be able to distinguish "out of memory" error
2742  * from "the data is hosed" error.
2743  *
2744  * @param auth the auth conversation
2745  * @param encoded the encoded data
2746  * @param plaintext initialized string where decoded data is appended
2747  * @returns #TRUE if we had enough memory and successfully decoded
2748  */
2749 dbus_bool_t
_dbus_auth_decode_data(DBusAuth * auth,const DBusString * encoded,DBusString * plaintext)2750 _dbus_auth_decode_data (DBusAuth         *auth,
2751                         const DBusString *encoded,
2752                         DBusString       *plaintext)
2753 {
2754   _dbus_assert (plaintext != encoded);
2755 
2756   if (auth->state != &common_state_authenticated)
2757     return FALSE;
2758 
2759   if (_dbus_auth_needs_decoding (auth))
2760     {
2761       if (DBUS_AUTH_IS_CLIENT (auth))
2762         return (* auth->mech->client_decode_func) (auth, encoded, plaintext);
2763       else
2764         return (* auth->mech->server_decode_func) (auth, encoded, plaintext);
2765     }
2766   else
2767     {
2768       return _dbus_string_copy (encoded, 0, plaintext,
2769                                 _dbus_string_get_length (plaintext));
2770     }
2771 }
2772 
2773 /**
2774  * Sets credentials received via reliable means from the operating
2775  * system.
2776  *
2777  * @param auth the auth conversation
2778  * @param credentials the credentials received
2779  * @returns #FALSE on OOM
2780  */
2781 dbus_bool_t
_dbus_auth_set_credentials(DBusAuth * auth,DBusCredentials * credentials)2782 _dbus_auth_set_credentials (DBusAuth               *auth,
2783                             DBusCredentials        *credentials)
2784 {
2785   _dbus_credentials_clear (auth->credentials);
2786   return _dbus_credentials_add_credentials (auth->credentials,
2787                                             credentials);
2788 }
2789 
2790 /**
2791  * Gets the identity we authorized the client as.  Apps may have
2792  * different policies as to what identities they allow.
2793  *
2794  * Returned credentials are not a copy and should not be modified
2795  *
2796  * @param auth the auth conversation
2797  * @returns the credentials we've authorized BY REFERENCE do not modify
2798  */
2799 DBusCredentials*
_dbus_auth_get_identity(DBusAuth * auth)2800 _dbus_auth_get_identity (DBusAuth               *auth)
2801 {
2802   if (auth->state == &common_state_authenticated)
2803     {
2804       return auth->authorized_identity;
2805     }
2806   else
2807     {
2808       /* FIXME instead of this, keep an empty credential around that
2809        * doesn't require allocation or something
2810        */
2811       /* return empty credentials */
2812       _dbus_assert (_dbus_credentials_are_empty (auth->authorized_identity));
2813       return auth->authorized_identity;
2814     }
2815 }
2816 
2817 /**
2818  * Gets the GUID from the server if we've authenticated; gets
2819  * #NULL otherwise.
2820  * @param auth the auth object
2821  * @returns the GUID in ASCII hex format
2822  */
2823 const char*
_dbus_auth_get_guid_from_server(DBusAuth * auth)2824 _dbus_auth_get_guid_from_server (DBusAuth *auth)
2825 {
2826   _dbus_assert (DBUS_AUTH_IS_CLIENT (auth));
2827 
2828   if (auth->state == &common_state_authenticated)
2829     return _dbus_string_get_const_data (& DBUS_AUTH_CLIENT (auth)->guid_from_server);
2830   else
2831     return NULL;
2832 }
2833 
2834 /**
2835  * Sets the "authentication context" which scopes cookies
2836  * with the DBUS_COOKIE_SHA1 auth mechanism for example.
2837  *
2838  * @param auth the auth conversation
2839  * @param context the context
2840  * @returns #FALSE if no memory
2841  */
2842 dbus_bool_t
_dbus_auth_set_context(DBusAuth * auth,const DBusString * context)2843 _dbus_auth_set_context (DBusAuth               *auth,
2844                         const DBusString       *context)
2845 {
2846   return _dbus_string_replace_len (context, 0, _dbus_string_get_length (context),
2847                                    &auth->context, 0, _dbus_string_get_length (context));
2848 }
2849 
2850 /**
2851  * Sets whether unix fd passing is potentially on the transport and
2852  * hence shall be negotiated.
2853  *
2854  * @param auth the auth conversation
2855  * @param b TRUE when unix fd passing shall be negotiated, otherwise FALSE
2856  */
2857 void
_dbus_auth_set_unix_fd_possible(DBusAuth * auth,dbus_bool_t b)2858 _dbus_auth_set_unix_fd_possible(DBusAuth *auth, dbus_bool_t b)
2859 {
2860   auth->unix_fd_possible = b;
2861 }
2862 
2863 /**
2864  * Queries whether unix fd passing was successfully negotiated.
2865  *
2866  * @param auth the auth conversion
2867  * @returns #TRUE when unix fd passing was negotiated.
2868  */
2869 dbus_bool_t
_dbus_auth_get_unix_fd_negotiated(DBusAuth * auth)2870 _dbus_auth_get_unix_fd_negotiated(DBusAuth *auth)
2871 {
2872   return auth->unix_fd_negotiated;
2873 }
2874 
2875 /**
2876  * Queries whether the given auth mechanism is supported.
2877  *
2878  * @param auth the auth mechanism to query for
2879  * @returns #TRUE when auth mechanism is supported
2880  */
2881 dbus_bool_t
_dbus_auth_is_supported_mechanism(DBusString * name)2882 _dbus_auth_is_supported_mechanism (DBusString *name)
2883 {
2884   _dbus_assert (name != NULL);
2885 
2886   return find_mech (name, NULL) != NULL;
2887 }
2888 
2889 /**
2890  * Return a human-readable string containing all supported auth mechanisms.
2891  *
2892  * @param string to hold the supported auth mechanisms
2893  * @returns #FALSE on oom
2894  */
2895 dbus_bool_t
_dbus_auth_dump_supported_mechanisms(DBusString * buffer)2896 _dbus_auth_dump_supported_mechanisms (DBusString *buffer)
2897 {
2898   unsigned int i;
2899   _dbus_assert (buffer != NULL);
2900 
2901   for (i = 0; all_mechanisms[i].mechanism != NULL; i++)
2902     {
2903       if (i > 0)
2904         {
2905           if (!_dbus_string_append (buffer, ", "))
2906             return FALSE;
2907         }
2908       if (!_dbus_string_append (buffer, all_mechanisms[i].mechanism))
2909         return FALSE;
2910     }
2911   return TRUE;
2912 }
2913 
2914 /** @} */
2915 
2916 /* tests in dbus-auth-util.c */
2917