d2394d8f32166879e0a77d5274e0c10ebe71b349
[claws.git] / src / passwordstore.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2016 The Claws Mail Team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  *
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #ifdef PASSWORD_CRYPTO_GNUTLS
26 # include <gnutls/gnutls.h>
27 # include <gnutls/crypto.h>
28 #endif
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32
33 #include "common/defs.h"
34 #include "common/utils.h"
35 #include "passwordstore.h"
36 #include "password.h"
37 #include "prefs_gtk.h"
38
39 static GSList *_password_store;
40
41 /* Finds password block of given type and name in the pwdstore. */
42 static PasswordBlock *_get_block(PasswordBlockType block_type,
43                 const gchar *block_name)
44 {
45         GSList *item;
46         PasswordBlock *block;
47
48         g_return_val_if_fail(block_type >= 0 && block_type < NUM_PWS_TYPES,
49                         NULL);
50         g_return_val_if_fail(block_name != NULL, NULL);
51
52         for (item = _password_store; item != NULL; item = item->next) {
53                 block = (PasswordBlock *)item->data;
54                 if (block->block_type == block_type &&
55                                 !strcmp(block->block_name, block_name))
56                         return block;
57         }
58
59         return NULL;
60 }
61
62 static gboolean _hash_equal_func(gconstpointer a, gconstpointer b)
63 {
64         if (g_strcmp0((const gchar *)a, (const gchar *)b) == 0)
65                 return TRUE;
66         return FALSE;
67 }
68
69 /* Creates a new, empty block and adds it to the pwdstore. */
70 static PasswordBlock *_new_block(PasswordBlockType block_type,
71                 const gchar *block_name)
72 {
73         PasswordBlock *block;
74
75         g_return_val_if_fail(block_type >= 0 && block_type < NUM_PWS_TYPES,
76                         NULL);
77         g_return_val_if_fail(block_name != NULL, NULL);
78
79         /* First check to see if the block doesn't already exist. */
80         if (_get_block(block_type, block_name)) {
81                 debug_print("Block (%d/%s) already exists.\n",
82                                 block_type, block_name);
83                 return NULL;
84         }
85
86         /* Let's create an empty block, and add it to pwdstore. */
87         block = g_new0(PasswordBlock, 1);
88         block->block_type = block_type;
89         block->block_name = g_strdup(block_name);
90         block->entries = g_hash_table_new_full(g_str_hash,
91                         (GEqualFunc)_hash_equal_func,
92                         g_free, g_free);
93         debug_print("Created password block (%d/%s)\n",
94                         block_type, block_name);
95
96         _password_store = g_slist_append(_password_store, block);
97
98         return block;
99 }
100
101 ///////////////////////////////////////////////////////////////
102
103 /* Stores a password. */
104 gboolean passwd_store_set(PasswordBlockType block_type,
105                 const gchar *block_name,
106                 const gchar *password_id,
107                 const gchar *password,
108                 gboolean encrypted)
109 {
110         const gchar *p = password;
111         PasswordBlock *block;
112         gchar *encrypted_password;
113
114         g_return_val_if_fail(block_type >= 0 && block_type < NUM_PWS_TYPES,
115                         FALSE);
116         g_return_val_if_fail(block_name != NULL, FALSE);
117         g_return_val_if_fail(password_id != NULL, FALSE);
118
119         /* Empty password string equals null password for us. */
120         if (strlen(password) == 0)
121                 p = NULL;
122
123         debug_print("%s password '%s' in block (%d/%s)%s\n",
124                         (p == NULL ? "Deleting" : "Storing"),
125                         password_id, block_type, block_name,
126                         (encrypted ? ", already encrypted" : "") );
127
128         // find correct block (create if needed)
129         if ((block = _get_block(block_type, block_name)) == NULL) {
130                 /* If caller wants to delete a password, and even its block
131                  * doesn't exist, we're done. */
132                 if (p == NULL)
133                         return TRUE;
134
135                 if ((block = _new_block(block_type, block_name)) == NULL) {
136                         debug_print("Could not create password block (%d/%s)\n",
137                                         block_type, block_name);
138                         return FALSE;
139                 }
140         }
141
142         if (p == NULL) {
143                 /* NULL password was passed to us, so delete the entry with
144                  * corresponding id */
145                 g_hash_table_remove(block->entries, password_id);
146         } else {
147                 if (!encrypted) {
148                         /* encrypt password before saving it */
149                         if ((encrypted_password =
150                                                 password_encrypt(p, NULL)) == NULL) {
151                                 debug_print("Could not encrypt password '%s' for block (%d/%s).\n",
152                                                 password_id, block_type, block_name);
153                                 return FALSE;
154                         }
155                 } else {
156                         /* password is already in encrypted form already */
157                         encrypted_password = g_strdup(p);
158                 }
159
160                 // add encrypted password to the block
161                 g_hash_table_insert(block->entries,
162                                 g_strdup(password_id),
163                                 encrypted_password);
164         }
165
166         return TRUE;
167 }
168
169 /* Retrieves a password. */
170 gchar *passwd_store_get(PasswordBlockType block_type,
171                 const gchar *block_name,
172                 const gchar *password_id)
173 {
174         PasswordBlock *block;
175         gchar *encrypted_password, *password;
176
177         g_return_val_if_fail(block_type >= 0 && block_type < NUM_PWS_TYPES,
178                         NULL);
179         g_return_val_if_fail(block_name != NULL, NULL);
180         g_return_val_if_fail(password_id != NULL, NULL);
181
182         debug_print("Getting password '%s' from block (%d/%s)\n",
183                         password_id, block_type, block_name);
184
185         // find correct block
186         if ((block = _get_block(block_type, block_name)) == NULL) {
187                 debug_print("Block (%d/%s) not found.\n", block_type, block_name);
188                 return NULL;
189         }
190
191         // grab pointer to encrypted password
192         if ((encrypted_password =
193                                 g_hash_table_lookup(block->entries, password_id)) == NULL) {
194                 debug_print("Password '%s' in block (%d/%s) not found.\n",
195                                 password_id, block_type, block_name);
196                 return NULL;
197         }
198
199         // decrypt password
200         if ((password =
201                                 password_decrypt(encrypted_password, NULL)) == NULL) {
202                 debug_print("Could not decrypt password '%s' for block (%d/%s).\n",
203                                 password_id, block_type, block_name);
204                 return NULL;
205         }
206
207         // return decrypted password
208         return password;
209 }
210
211 gboolean passwd_store_delete_block(PasswordBlockType block_type,
212                 const gchar *block_name)
213 {
214         PasswordBlock *block;
215
216         g_return_val_if_fail(block_type >= 0 && block_type < NUM_PWS_TYPES,
217                         FALSE);
218         g_return_val_if_fail(block_name != NULL, FALSE);
219
220         debug_print("Deleting block (%d/%s)\n", block_type, block_name);
221
222         // find correct block
223         if ((block = _get_block(block_type, block_name)) == NULL) {
224                 debug_print("Block (%d/%s) not found.\n", block_type, block_name);
225                 return FALSE;
226         }
227
228         g_hash_table_destroy(block->entries);
229         block->entries = NULL;
230         return TRUE;
231 }
232
233 gboolean passwd_store_set_account(gint account_id,
234                 const gchar *password_id,
235                 const gchar *password,
236                 gboolean encrypted)
237 {
238         gchar *uid = g_strdup_printf("%d", account_id);
239         gboolean ret = passwd_store_set(PWS_ACCOUNT, uid,
240                         password_id, password, encrypted);
241         g_free(uid);
242         return ret;
243 }
244
245 gchar *passwd_store_get_account(gint account_id,
246                 const gchar *password_id)
247 {
248         gchar *uid = g_strdup_printf("%d", account_id);
249         gchar *ret = passwd_store_get(PWS_ACCOUNT, uid, password_id);
250         g_free(uid);
251         return ret;
252 }
253
254 /* Reencrypts all stored passwords. */
255 void passwd_store_reencrypt_all(const gchar *old_mpwd,
256                 const gchar *new_mpwd)
257 {
258         PasswordBlock *block;
259         GSList *item;
260         GList *keys, *eitem;
261         gchar *encrypted_password, *decrypted_password, *key;
262
263         g_return_if_fail(old_mpwd != NULL);
264         g_return_if_fail(new_mpwd != NULL);
265
266         for (item = _password_store; item != NULL; item = item->next) {
267                 block = (PasswordBlock *)item->data;
268                 if (block == NULL)
269                         continue; /* Just in case. */
270
271                 debug_print("Reencrypting passwords in block (%d/%s).\n",
272                                 block->block_type, block->block_name);
273
274                 if (g_hash_table_size(block->entries) == 0)
275                         continue;
276
277                 keys = g_hash_table_get_keys(block->entries);
278                 for (eitem = keys; eitem != NULL; eitem = eitem->next) {
279                         key = (gchar *)eitem->data;
280                         if ((encrypted_password =
281                                                 g_hash_table_lookup(block->entries, key)) == NULL)
282                                 continue;
283
284                         if ((decrypted_password =
285                                                 password_decrypt(encrypted_password, old_mpwd)) == NULL) {
286                                 debug_print("Reencrypt: couldn't decrypt password for '%s'.\n", key);
287                                 continue;
288                         }
289
290                         encrypted_password = password_encrypt(decrypted_password, new_mpwd);
291                         memset(decrypted_password, 0, strlen(decrypted_password));
292                         g_free(decrypted_password);
293                         if (encrypted_password == NULL) {
294                                 debug_print("Reencrypt: couldn't encrypt password for '%s'.\n", key);
295                                 continue;
296                         }
297
298                         g_hash_table_insert(block->entries, g_strdup(key), encrypted_password);
299                 }
300
301                 g_list_free(keys);
302         }
303
304         debug_print("Reencrypting done.\n");
305 }
306
307 static gint _write_to_file(FILE *fp)
308 {
309         PasswordBlock *block;
310         GSList *item;
311         GList *keys, *eitem;
312         gchar *typestr, *line, *key, *pwd;
313
314         for (item = _password_store; item != NULL; item = item->next) {
315                 block = (PasswordBlock*)item->data;
316                 if (block == NULL)
317                         continue; /* Just in case. */
318
319                 /* Do not save empty blocks. */
320                 if (g_hash_table_size(block->entries) == 0)
321                         continue;
322
323                 /* Prepare the section header string and write it out. */
324                 typestr = NULL;
325                 if (block->block_type == PWS_CORE) {
326                         typestr = "core";
327                 } else if (block->block_type == PWS_ACCOUNT) {
328                         typestr = "account";
329                 } else if (block->block_type == PWS_PLUGIN) {
330                         typestr = "plugin";
331                 }
332                 line = g_strdup_printf("[%s:%s]\n", typestr, block->block_name);
333
334                 if (fputs(line, fp) == EOF) {
335                         FILE_OP_ERROR("password store", "fputs");
336                         g_free(line);
337                         return -1;
338                 }
339                 g_free(line);
340
341                 /* Now go through all passwords in the block and write each out. */
342                 keys = g_hash_table_get_keys(block->entries);
343                 for (eitem = keys; eitem != NULL; eitem = eitem->next) {
344                         key = (gchar *)eitem->data;
345                         if ((pwd = g_hash_table_lookup(block->entries, key)) == NULL)
346                                 continue;
347
348                         line = g_strdup_printf("%s %s\n", key, pwd);
349                         if (fputs(line, fp) == EOF) {
350                                 FILE_OP_ERROR("password store", "fputs");
351                                 g_free(line);
352                                 return -1;
353                         }
354                         g_free(line);
355                 }
356                 g_list_free(keys);
357
358                 if (item->next != NULL && fputs("\n", fp) == EOF) {
359                         FILE_OP_ERROR("password store", "fputs");
360                         return -1;
361                 }
362
363         }
364
365         return 1;
366 }
367
368 void passwd_store_write_config(void)
369 {
370         gchar *rcpath;
371         PrefFile *pfile;
372
373         debug_print("Writing password store...\n");
374
375         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
376                         PASSWORD_STORE_RC, NULL);
377
378         if ((pfile = prefs_write_open(rcpath)) == NULL) {
379                 g_warning("failed to open password store file for writing");
380                 g_free(rcpath);
381                 return;
382         }
383
384         g_free(rcpath);
385
386         if (_write_to_file(pfile->fp) < 0) {
387                 g_warning("failed to write password store to file");
388                 prefs_file_close_revert(pfile);
389         } else if (prefs_file_close(pfile) < 0) {
390                 g_warning("failed to properly close password store file after writing");
391         }
392 }
393
394 void passwd_store_read_config(void)
395 {
396         gchar *rcpath, *contents, **lines, **line, *typestr, *name;
397         GError *error = NULL;
398         guint i = 0;
399         PasswordBlock *block = NULL;
400         PasswordBlockType type;
401
402         // TODO: passwd_store_clear();
403
404         debug_print("Reading password store from file...\n");
405
406         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
407                         PASSWORD_STORE_RC, NULL);
408
409         if (!g_file_get_contents(rcpath, &contents, NULL, &error)) {
410                 g_warning("couldn't read password store from file: %s\n", error->message);
411                 g_error_free(error);
412                 g_free(rcpath);
413                 return;
414         }
415         g_free(rcpath);
416
417         lines = g_strsplit(contents, "\n", -1);
418
419         while (lines[i] != NULL) {
420                 if (*lines[i] == '[') {
421                         /* Beginning of a new block */
422                         line = g_strsplit_set(lines[i], "[:]", -1);
423                         if (line[0] != NULL && strlen(line[0]) == 0
424                                         && line[1] != NULL && strlen(line[1]) > 0
425                                         && line[2] != NULL && strlen(line[2]) > 0
426                                         && line[3] != NULL && strlen(line[3]) == 0) {
427                                 typestr = line[1];
428                                 name = line[2];
429                                 if (!strcmp(typestr, "core")) {
430                                         type = PWS_CORE;
431                                 } else if (!strcmp(typestr, "account")) {
432                                         type = PWS_ACCOUNT;
433                                 } else if (!strcmp(typestr, "plugin")) {
434                                         type = PWS_PLUGIN;
435                                 } else {
436                                         debug_print("Uknown password block type: '%s'\n", typestr);
437                                         g_strfreev(line);
438                                         i++; continue;
439                                 }
440
441                                 if ((block = _new_block(type, name)) == NULL) {
442                                         debug_print("Duplicate password block, ignoring: (%d/%s)\n",
443                                                         type, name);
444                                         g_strfreev(line);
445                                         i++; continue;
446                                 }
447                         }
448                         g_strfreev(line);
449                 } else if (strlen(lines[i]) > 0 && block != NULL) {
450                         /* If we have started a password block, test for a
451                          * "password_id = password" line. */
452                         line = g_strsplit(lines[i], " ", -1);
453                         if (line[0] != NULL && strlen(line[0]) > 0
454                                         && line[1] != NULL && strlen(line[1]) > 0
455                                         && line[2] == NULL) {
456                                 debug_print("Adding password '%s'\n", line[0]);
457                                 g_hash_table_insert(block->entries,
458                                                 g_strdup(line[0]), g_strdup(line[1]));
459                         }
460                         g_strfreev(line);
461                 }
462                 i++;
463         }
464         g_strfreev(lines);
465 }