GnuCash  5.6-150-g038405b370+
gnc-keyring.c
1 /*
2  * gnc-keyring.c -- utility functions to store and retrieve passwords.
3  *
4  * Copyright (C) 2010 Geert Janssens <janssens.geert@telenet.be>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, contact:
18  *
19  * Free Software Foundation Voice: +1-617-542-5942
20  * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652
21  * Boston, MA 02110-1301, USA gnu@gnu.org
22  */
23 
24 #include <config.h>
25 #include <glib/gi18n.h>
26 #include "qof.h"
27 #include "gnc-ui.h"
28 #include "gnc-keyring.h"
29 #ifdef HAVE_LIBSECRET
30 #include <libsecret/secret.h>
31 #elif HAVE_GNOME_KEYRING
32 #define GNOME_KEYRING_DEPRECATED
33 #define GNOME_KEYRING_DEPRECATED_FOR(x)
34 #include <gnome-keyring.h>
35 #endif
36 #ifdef HAVE_OSX_KEYCHAIN
37 #include <Security/Security.h>
38 #include <CoreFoundation/CoreFoundation.h>
39 #endif
40 
41 /* This static indicates the debugging module that this .o belongs to. */
42 G_GNUC_UNUSED static QofLogModule log_module = GNC_MOD_GUI;
43 
44 #ifdef HAVE_LIBSECRET
45 const SecretSchema* gnucash_get_secret_schema(void) G_GNUC_CONST;
46 const SecretSchema* gnucash_get_secret_schema(void)
47 {
48  static const SecretSchema secret_schema = {
49  "org.gnucash.password", SECRET_SCHEMA_NONE,
50  {
51  { "protocol", SECRET_SCHEMA_ATTRIBUTE_STRING },
52  { "server", SECRET_SCHEMA_ATTRIBUTE_STRING },
53  { "port", SECRET_SCHEMA_ATTRIBUTE_INTEGER },
54  { "user", SECRET_SCHEMA_ATTRIBUTE_STRING },
55  { "NULL", 0 },
56  }
57  };
58 
59  return &secret_schema;
60 }
61 
62 #define SECRET_SCHEMA_GNUCASH gnucash_get_secret_schema()
63 #endif
64 
65 #ifdef HAVE_OSX_KEYCHAIN
66 /* Log an OSStatus from the macOS keychain as a readable message. */
67 static void
68 log_osx_keychain_error (const gchar *context, OSStatus status)
69 {
70  CFStringRef osx_resultstring = SecCopyErrorMessageString (status, NULL);
71  char resultstring[256] = "";
72  if (osx_resultstring)
73  {
74  CFStringGetCString (osx_resultstring, resultstring,
75  sizeof resultstring, kCFStringEncodingUTF8);
76  CFRelease (osx_resultstring);
77  }
78  PWARN ("OS X keychain error in %s (status %d): %s",
79  context, (int) status, resultstring);
80 }
81 
82 /* Add a UTF-8 string value under key to a keychain query dictionary. */
83 static void
84 cfdict_set_string_UTF8 (CFMutableDictionaryRef dict, CFStringRef key,
85  const gchar *value_UTF8)
86 {
87  CFStringRef str = CFStringCreateWithCString (NULL, value_UTF8,
88  kCFStringEncodingUTF8);
89  CFDictionarySetValue (dict, key, str);
90  CFRelease (str);
91 }
92 
93 /* Build the dictionary that identifies one internet-password item. The access
94  * method ("mysql"/"postgres") is stored as the security domain because it is not
95  * a valid keychain protocol. kSecUseDataProtectionKeychain is deliberately not
96  * set, so the items stay in the file-based login keychain where earlier GnuCash
97  * releases stored them. */
98 static CFMutableDictionaryRef
99 osx_keychain_query (const gchar *access_method, const gchar *server,
100  guint32 port, const gchar *service, const gchar *user)
101 {
102  CFMutableDictionaryRef query =
103  CFDictionaryCreateMutable (NULL, 0, &kCFTypeDictionaryKeyCallBacks,
104  &kCFTypeDictionaryValueCallBacks);
105  CFDictionarySetValue (query, kSecClass, kSecClassInternetPassword);
106  cfdict_set_string_UTF8 (query, kSecAttrServer, server);
107  cfdict_set_string_UTF8 (query, kSecAttrSecurityDomain, access_method);
108  cfdict_set_string_UTF8 (query, kSecAttrAccount, user);
109  cfdict_set_string_UTF8 (query, kSecAttrPath, service);
110  if (port != 0)
111  {
112  CFNumberRef num = CFNumberCreate (NULL, kCFNumberSInt32Type, &port);
113  CFDictionarySetValue (query, kSecAttrPort, num);
114  CFRelease (num);
115  }
116  return query;
117 }
118 
119 /* Return the password stored for these coordinates, or NULL if none; the caller
120  * frees it with g_free(). A clean miss returns NULL silently; a genuine error
121  * is logged. */
122 static gchar *
123 find_osx_keychain_password (const gchar *access_method, const gchar *server,
124  guint32 port, const gchar *service,
125  const gchar *user)
126 {
127  gchar *password = NULL;
128  CFDataRef data = NULL;
129  CFMutableDictionaryRef query =
130  osx_keychain_query (access_method, server, port, service, user);
131  OSStatus status;
132 
133  CFDictionarySetValue (query, kSecMatchLimit, kSecMatchLimitOne);
134  CFDictionarySetValue (query, kSecReturnData, kCFBooleanTrue);
135  status = SecItemCopyMatching (query, (CFTypeRef *) &data);
136  if (status == errSecSuccess && data)
137  {
138  password = g_strndup ((const gchar *) CFDataGetBytePtr (data),
139  CFDataGetLength (data));
140  }
141  else if (status != errSecItemNotFound)
142  log_osx_keychain_error ("find_osx_keychain_password", status);
143  if (data)
144  CFRelease (data);
145  CFRelease (query);
146  return password;
147 }
148 
149 /* Store the password for these coordinates, adding a new item or updating the
150  * existing one in place. */
151 static OSStatus
152 store_osx_keychain_password (const gchar *access_method, const gchar *server,
153  guint32 port, const gchar *service,
154  const gchar *user, const gchar *password)
155 {
156  CFMutableDictionaryRef query =
157  osx_keychain_query (access_method, server, port, service, user);
158  CFDataRef pw = CFDataCreate (NULL, (const UInt8 *) password,
159  strlen (password));
160  OSStatus status = SecItemCopyMatching (query, NULL);
161 
162  /* A bare SecItemAdd fails with errSecDuplicateItem
163  * if an item exists. */
164  if (status == errSecItemNotFound)
165  {
166  /* new item path */
167  CFDictionarySetValue (query, kSecValueData, pw);
168  status = SecItemAdd (query, NULL);
169  }
170  else if (status == errSecSuccess)
171  {
172  /* update item path */
173  CFMutableDictionaryRef attrs =
174  CFDictionaryCreateMutable (NULL, 1, &kCFTypeDictionaryKeyCallBacks,
175  &kCFTypeDictionaryValueCallBacks);
176  CFDictionarySetValue (attrs, kSecValueData, pw);
177  status = SecItemUpdate (query, attrs);
178  CFRelease (attrs);
179  }
180  CFRelease (pw);
181  CFRelease (query);
182  return status;
183 }
184 #endif /* HAVE_OSX_KEYCHAIN */
185 
186 #if defined(HAVE_LIBSECRET) || defined(HAVE_GNOME_KEYRING) || defined(HAVE_OSX_KEYCHAIN)
187 /* Return a copy of the password currently stored in the keyring for these
188  * coordinates, or NULL if none is stored; the caller frees it with g_free().
189  * Unlike gnc_keyring_get_password() this performs no user interaction. */
190 static gchar *
191 keyring_lookup_password (const gchar *access_method, const gchar *server,
192  guint32 port, const gchar *service, const gchar *user)
193 {
194  gchar *stored = NULL;
195 #ifdef HAVE_LIBSECRET
196  GError *error = NULL;
197  gchar *found;
198  if (port == 0)
199  found = secret_password_lookup_sync (SECRET_SCHEMA_GNUCASH, NULL, &error,
200  "protocol", access_method,
201  "server", server,
202  "user", user,
203  NULL);
204  else
205  found = secret_password_lookup_sync (SECRET_SCHEMA_GNUCASH, NULL, &error,
206  "protocol", access_method,
207  "server", server,
208  "port", port,
209  "user", user,
210  NULL);
211  if (found)
212  {
213  stored = g_strdup (found);
214  secret_password_free (found);
215  }
216  if (error)
217  g_error_free (error);
218 #elif HAVE_GNOME_KEYRING
219  GList *found_list = NULL;
220  if (gnome_keyring_find_network_password_sync
221  (user, NULL, server, service, access_method, NULL, port,
222  &found_list) == GNOME_KEYRING_RESULT_OK && found_list)
223  {
224  GnomeKeyringNetworkPasswordData *found = found_list->data;
225  if (found->password)
226  stored = g_strdup (found->password);
227  }
228  if (found_list)
229  gnome_keyring_network_password_list_free (found_list);
230 #endif
231 #ifdef HAVE_OSX_KEYCHAIN
232  stored = find_osx_keychain_password (access_method, server, port, service,
233  user);
234 #endif
235  return stored;
236 }
237 #endif /* any keyring backend */
238 
239 void gnc_keyring_set_password (const gchar *access_method,
240  const gchar *server,
241  guint32 port,
242  const gchar *service,
243  const gchar *user,
244  const gchar* password)
245 {
246 #if defined(HAVE_LIBSECRET) || defined(HAVE_GNOME_KEYRING) || defined(HAVE_OSX_KEYCHAIN)
247  gchar *stored;
248  gboolean unchanged;
249 
250  g_return_if_fail (access_method != NULL && server != NULL &&
251  service != NULL && user != NULL && password != NULL);
252 
253  /* Only (re)write the keyring when the stored password is missing or has
254  * actually changed. */
255  stored = keyring_lookup_password (access_method, server, port, service, user);
256  unchanged = (g_strcmp0 (stored, password) == 0);
257  g_free (stored);
258  if (unchanged)
259  return;
260 #endif
261 
262 #ifdef HAVE_LIBSECRET
263  GError* error = NULL;
264  gchar* label = NULL;
265 
266  label = g_strdup_printf("GnuCash password for %s://%s@%s", access_method, user, server);
267 
268  if (port == 0)
269  secret_password_store_sync (SECRET_SCHEMA_GNUCASH, SECRET_COLLECTION_DEFAULT,
270  label, password, NULL, &error,
271  "protocol", access_method,
272  "server", server,
273  "user", user,
274  NULL);
275  else
276  secret_password_store_sync (SECRET_SCHEMA_GNUCASH, SECRET_COLLECTION_DEFAULT,
277  label, password, NULL, &error,
278  "protocol", access_method,
279  "server", server,
280  "port", port,
281  "user", user,
282  NULL);
283 
284  g_free(label);
285 
286  if (error != NULL)
287  {
288  PWARN ("libsecret error: %s", error->message);
289  PWARN ("The user will be prompted for a password again next time.");
290  g_error_free(error);
291  }
292 #elif HAVE_GNOME_KEYRING
293  GnomeKeyringResult gkr_result;
294  guint32 item_id = 0;
295 
296  gkr_result = gnome_keyring_set_network_password_sync
297  (NULL, user, NULL, server, service,
298  access_method, NULL, port, password, &item_id);
299 
300  if (gkr_result != GNOME_KEYRING_RESULT_OK)
301  {
302  PWARN ("Gnome-keyring error: %s",
303  gnome_keyring_result_to_message(gkr_result));
304  PWARN ("The user will be prompted for a password again next time.");
305  }
306 #endif /* HAVE_GNOME_KEYRING */
307 #ifdef HAVE_OSX_KEYCHAIN
308  OSStatus status;
309 
310  status = store_osx_keychain_password (access_method, server, port,
311  service, user, password);
312  if (status != errSecSuccess)
313  {
314  log_osx_keychain_error ("gnc_keyring_set_password", status);
315  PWARN ("The user will be prompted for a password again next time.");
316  }
317 #endif /* HAVE_OSX_KEYCHAIN */
318 }
319 
320 
321 gboolean gnc_keyring_get_password ( GtkWidget *parent,
322  const gchar *access_method,
323  const gchar *server,
324  guint32 port,
325  const gchar *service,
326  gchar **user,
327  gchar **password)
328 {
329  gboolean password_found = FALSE;
330  gchar *db_path, *heading;
331 #ifdef HAVE_LIBSECRET
332  GError* error = NULL;
333  char* libsecret_password;
334 #elif HAVE_GNOME_KEYRING
335  GnomeKeyringResult gkr_result;
336  GList *found_list = NULL;
337  GnomeKeyringNetworkPasswordData *found;
338 #endif
339 
340  g_return_val_if_fail (user != NULL, FALSE);
341  g_return_val_if_fail (password != NULL, FALSE);
342 
343  *password = NULL;
344 
345 #ifdef HAVE_LIBSECRET
346  /* Workaround for https://bugs.gnucash.org/show_bug.cgi?id=746873
347  * and by extension for https://bugs.gnucash.org/show_bug.cgi?id=748625
348  * Store a dummy password and delete it again. This forces libsecret
349  * to open the keychain, where only a call to secret_password_lookup_sync
350  * sometimes fails to do so. More details can be found in the bug reports
351  * referenced above. */
352  secret_password_store_sync (SECRET_SCHEMA_GNUCASH, SECRET_COLLECTION_DEFAULT,
353  "Dummy password", "dummy", NULL, &error,
354  "protocol", PROJECT_NAME,
355  "server", PROJECT_NAME,
356  "user", PROJECT_NAME,
357  NULL);
358  secret_password_clear_sync (SECRET_SCHEMA_GNUCASH, NULL, &error,
359  "protocol", PROJECT_NAME,
360  "server", PROJECT_NAME,
361  "user", PROJECT_NAME,
362  NULL);
363 
364  /* Note: only use the port attribute if it was set by the user. */
365  if (port == 0)
366  libsecret_password = secret_password_lookup_sync (SECRET_SCHEMA_GNUCASH, NULL, &error,
367  "protocol", access_method,
368  "server", server,
369  "user", *user,
370  NULL);
371  else
372  libsecret_password = secret_password_lookup_sync (SECRET_SCHEMA_GNUCASH, NULL, &error,
373  "protocol", access_method,
374  "server", server,
375  "port", port,
376  "user", *user,
377  NULL);
378 
379  if (libsecret_password != NULL) {
380  *password = g_strdup (libsecret_password);
381  secret_password_free (libsecret_password);
382  return TRUE;
383  }
384 
385  /* No password found yet. Perhaps it was written with a port equal to 0.
386  * Gnucash versions prior to 2.6.7 did this unfortunately... */
387  libsecret_password = secret_password_lookup_sync (SECRET_SCHEMA_GNUCASH, NULL, &error,
388  "protocol", access_method,
389  "server", server,
390  "port", 0,
391  "user", *user,
392  NULL);
393 
394  if (libsecret_password != NULL) {
395  *password = g_strdup (libsecret_password);
396  secret_password_free (libsecret_password);
397 
398  /* Ok, got an password with 0 port.
399  Store a copy in a more recent gnucash style. */
400  gnc_keyring_set_password(access_method, server, port, service, *user, *password);
401  return TRUE;
402  }
403 
404  /* No password was found while querying libsecret using the gnucash schema,
405  Look for a password stored via gnome-keyring instead */
406  if (port == 0)
407  libsecret_password = secret_password_lookup_sync (SECRET_SCHEMA_COMPAT_NETWORK, NULL, &error,
408  "protocol", access_method,
409  "server", server,
410  "object", service,
411  "user", *user,
412  NULL);
413  else
414  libsecret_password = secret_password_lookup_sync (SECRET_SCHEMA_COMPAT_NETWORK, NULL, &error,
415  "protocol", access_method,
416  "server", server,
417  "port", port,
418  "object", service,
419  "user", *user,
420  NULL);
421 
422  if (libsecret_password != NULL) {
423  *password = g_strdup (libsecret_password);
424  secret_password_free (libsecret_password);
425 
426  /* Ok, got an old gnome-keyring password.
427  * Store a copy of it in a libsecret compatible format. */
428  gnc_keyring_set_password(access_method, server, port, service, *user, *password);
429  return TRUE;
430  }
431 
432  /* Something went wrong while attempting to access libsecret
433  * Log the error message and carry on... */
434  if (error != NULL) {
435  PWARN ("libsecret access failed: %s.", error->message);
436  g_error_free(error);
437  }
438 
439 #elif HAVE_GNOME_KEYRING
440  gkr_result = gnome_keyring_find_network_password_sync
441  ( *user, NULL, server, service,
442  access_method, NULL, port, &found_list );
443 
444  if (gkr_result == GNOME_KEYRING_RESULT_OK)
445  {
446  found = (GnomeKeyringNetworkPasswordData *) found_list->data;
447  if (found->password)
448  *password = g_strdup(found->password);
449  gnome_keyring_network_password_list_free(found_list);
450  return TRUE;
451  }
452 
453  /* Something went wrong while attempting to access libsecret
454  * Log the error message and carry on... */
455  PWARN ("Gnome-keyring access failed: %s.",
456  gnome_keyring_result_to_message(gkr_result));
457  gnome_keyring_network_password_list_free(found_list);
458 #endif /* HAVE_LIBSECRET or HAVE_GNOME_KEYRING */
459 
460 #ifdef HAVE_OSX_KEYCHAIN
461  if (*user != NULL)
462  {
463  *password = find_osx_keychain_password (access_method, server, port,
464  service, *user);
465  if (*password != NULL)
466  return TRUE;
467  }
468 #endif /* HAVE_OSX_KEYCHAIN */
469 
470  /* If we got here, either no proper password store is
471  * available on this system, or we couldn't retrieve
472  * a password from it. In both cases, just ask the user
473  * to enter one
474  */
475 
476  if ( port == 0 )
477  db_path = g_strdup_printf ( "%s://%s/%s", access_method, server, service );
478  else
479  db_path = g_strdup_printf ( "%s://%s:%d/%s", access_method, server, port, service );
480  heading = g_strdup_printf ( /* Translators: %s is a path to a database or any other url,
481  like mysql://user@server.somewhere/somedb, https://www.somequotes.com/thequotes */
482  _("Enter a user name and password to connect to: %s"),
483  db_path );
484 
485  password_found = gnc_get_username_password ( parent, heading,
486  *user, NULL,
487  user, password );
488  g_free ( db_path );
489  g_free ( heading );
490 
491  if ( password_found )
492  {
493  /* User entered new user/password information
494  * Let's try to add it to a password store.
495  */
496  gchar *newuser = g_strdup( *user );
497  gchar *newpassword = g_strdup( *password );
498  gnc_keyring_set_password ( access_method,
499  server,
500  port,
501  service,
502  newuser,
503  newpassword );
504  g_free ( newuser );
505  g_free ( newpassword );
506  }
507 
508  return password_found;
509 }
Functions to save and retrieve passwords.
#define PWARN(format, args...)
Log a warning.
Definition: qoflog.h:250
void gnc_keyring_set_password(const gchar *access_method, const gchar *server, guint32 port, const gchar *service, const gchar *user, const gchar *password)
Attempt to store a password in some trusted keystore.
Definition: gnc-keyring.c:239
gboolean gnc_keyring_get_password(GtkWidget *parent, const gchar *access_method, const gchar *server, guint32 port, const gchar *service, gchar **user, gchar **password)
Attempt to retrieve a password to connect to a remote service.
Definition: gnc-keyring.c:321