Migrate SpamReport passwords to password store correctly.
[claws.git] / src / password.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 #if defined G_OS_UNIX
34 #include <fcntl.h>
35 #include <unistd.h>
36 #elif defined G_OS_WIN32
37 #include <windows.h>
38 #include <wincrypt.h>
39 #endif
40
41 #include "common/passcrypt.h"
42 #include "common/plugin.h"
43 #include "common/utils.h"
44 #include "account.h"
45 #include "alertpanel.h"
46 #include "inputdialog.h"
47 #include "password.h"
48 #include "passwordstore.h"
49 #include "prefs_common.h"
50
51 #ifndef PASSWORD_CRYPTO_OLD
52 static gchar *_master_passphrase = NULL;
53
54 static const gchar *master_passphrase()
55 {
56         gchar *input;
57         gboolean end = FALSE;
58
59         if (!prefs_common_get_prefs()->use_master_passphrase) {
60                 return PASSCRYPT_KEY;
61         }
62
63         if (_master_passphrase != NULL) {
64                 debug_print("Master passphrase is in memory, offering it.\n");
65                 return _master_passphrase;
66         }
67
68         while (!end) {
69                 input = input_dialog_with_invisible(_("Input master passphrase"),
70                                 _("Input master passphrase"), NULL);
71
72                 if (input == NULL) {
73                         debug_print("Cancel pressed at master passphrase dialog.\n");
74                         break;
75                 }
76
77                 if (master_passphrase_is_correct(input)) {
78                         debug_print("Entered master passphrase seems to be correct, remembering it.\n");
79                         _master_passphrase = input;
80                         end = TRUE;
81                 } else {
82                         alertpanel_error(_("Incorrect master passphrase."));
83                 }
84         }
85
86         return _master_passphrase;
87 }
88
89 const gboolean master_passphrase_is_set()
90 {
91         if (prefs_common_get_prefs()->master_passphrase_hash == NULL
92                         || strlen(prefs_common_get_prefs()->master_passphrase_hash) == 0)
93                 return FALSE;
94
95         return TRUE;
96 }
97
98 const gboolean master_passphrase_is_correct(const gchar *input)
99 {
100         gchar *hash;
101         gchar **tokens;
102         gchar *stored_hash = prefs_common_get_prefs()->master_passphrase_hash;
103         const GChecksumType hashtype = G_CHECKSUM_SHA256;
104         const gssize hashlen = g_checksum_type_get_length(hashtype);
105         gssize stored_len;
106
107         g_return_val_if_fail(input != NULL, FALSE);
108
109         if (stored_hash == NULL)
110                 return FALSE;
111
112         tokens = g_strsplit_set(stored_hash, "{}", 3);
113         if (strlen(tokens[0]) != 0 ||
114                         strcmp(tokens[1], "SHA-256") ||
115                         strlen(tokens[2]) == 0) {
116                 debug_print("Mangled master_passphrase_hash in config, can not use it.\n");
117                 g_strfreev(tokens);
118                 return FALSE;
119         }
120
121         stored_hash = tokens[2];
122         stored_len = strlen(stored_hash);
123         g_return_val_if_fail(stored_len == 2*hashlen, FALSE);
124
125         hash = g_compute_checksum_for_string(hashtype, input, -1);
126
127         if (!strncasecmp(hash, stored_hash, stored_len)) {
128                 g_free(hash);
129                 g_strfreev(tokens);
130                 return TRUE;
131         }
132         g_strfreev(tokens);
133         g_free(hash);
134
135         return FALSE;
136 }
137
138 gboolean master_passphrase_is_entered()
139 {
140         return (_master_passphrase == NULL) ? FALSE : TRUE;
141 }
142
143 void master_passphrase_forget()
144 {
145         /* If master passphrase is currently in memory (entered by user),
146          * get rid of it. User will have to enter the new one again. */
147         if (_master_passphrase != NULL) {
148                 memset(_master_passphrase, 0, strlen(_master_passphrase));
149                 g_free(_master_passphrase);
150                 _master_passphrase = NULL;
151         }
152 }
153
154 void master_passphrase_change(const gchar *oldp, const gchar *newp)
155 {
156         const GChecksumType hashtype = G_CHECKSUM_SHA256;
157         gchar *hash;
158
159         if (oldp == NULL) {
160                 /* If oldp is NULL, make sure the user has to enter the
161                  * current master passphrase before being able to change it. */
162                 master_passphrase_forget();
163                 oldp = master_passphrase();
164         }
165         g_return_if_fail(oldp != NULL);
166
167         /* Update master passphrase hash in prefs */
168         if (prefs_common_get_prefs()->master_passphrase_hash != NULL)
169                 g_free(prefs_common_get_prefs()->master_passphrase_hash);
170
171         if (newp != NULL) {
172                 debug_print("Storing hash of new master passphrase\n");
173                 hash = g_compute_checksum_for_string(hashtype, newp, -1);
174                 prefs_common_get_prefs()->master_passphrase_hash =
175                         g_strconcat("{SHA-256}", hash, NULL);
176                 g_free(hash);
177         } else {
178                 debug_print("Setting master_passphrase_hash to NULL\n");
179                 prefs_common_get_prefs()->master_passphrase_hash = NULL;
180         }
181
182         /* Now go over all accounts, reencrypting their passwords using
183          * the new master passphrase. */
184
185         if (oldp == NULL)
186                 oldp = PASSCRYPT_KEY;
187         if (newp == NULL)
188                 newp = PASSCRYPT_KEY;
189
190         debug_print("Reencrypting all account passwords...\n");
191         passwd_store_reencrypt_all(oldp, newp);
192
193         /* Now reencrypt all plugins passwords fields 
194          * FIXME: Unloaded plugins won't be able to update their stored passwords
195          */
196         plugins_master_passphrase_change(oldp, newp);
197
198         master_passphrase_forget();
199 }
200 #endif
201
202 gchar *password_encrypt_old(const gchar *password)
203 {
204         if (!password || strlen(password) == 0) {
205                 return NULL;
206         }
207
208         gchar *encrypted = g_strdup(password);
209         gchar *encoded, *result;
210         gsize len = strlen(password);
211
212         passcrypt_encrypt(encrypted, len);
213         encoded = g_base64_encode(encrypted, len);
214         g_free(encrypted);
215         result = g_strconcat("!", encoded, NULL);
216         g_free(encoded);
217
218         return result;
219 }
220
221 gchar *password_decrypt_old(const gchar *password)
222 {
223         if (!password || strlen(password) == 0) {
224                 return NULL;
225         }
226
227         if (*password != '!' || strlen(password) < 2) {
228                 return NULL;
229         }
230
231         gsize len;
232         gchar *decrypted = g_base64_decode(password + 1, &len);
233
234         passcrypt_decrypt(decrypted, len);
235         return decrypted;
236 }
237
238 #ifdef PASSWORD_CRYPTO_GNUTLS
239 #define BUFSIZE 128
240
241 /* Since we can't count on having GnuTLS new enough to have
242  * gnutls_cipher_get_iv_size(), we hardcode the IV length for now. */
243 #define IVLEN 16
244
245 gchar *password_encrypt_gnutls(const gchar *password,
246                 const gchar *encryption_passphrase)
247 {
248         /* Another, slightly inferior combination is AES-128-CBC + SHA-256.
249          * Any block cipher in CBC mode with keysize N and a hash algo with
250          * digest length 2*N would do. */
251         gnutls_cipher_algorithm_t algo = GNUTLS_CIPHER_AES_256_CBC;
252         gnutls_digest_algorithm_t digest = GNUTLS_DIG_SHA512;
253         gnutls_cipher_hd_t handle;
254         gnutls_datum_t key, iv;
255         int keylen, digestlen, blocklen, ret, i;
256         unsigned char hashbuf[BUFSIZE], *buf, *encbuf, *base, *output;
257 #if defined G_OS_UNIX
258         int rnd;
259 #elif defined G_OS_WIN32
260         HCRYPTPROV rnd;
261 #endif
262
263         g_return_val_if_fail(password != NULL, NULL);
264         g_return_val_if_fail(encryption_passphrase != NULL, NULL);
265
266 /*      ivlen = gnutls_cipher_get_iv_size(algo);*/
267         keylen = gnutls_cipher_get_key_size(algo);
268         blocklen = gnutls_cipher_get_block_size(algo);
269         digestlen = gnutls_hash_get_len(digest);
270
271         /* Prepare key for cipher - first half of hash of passkey XORed with
272          * the second. */
273         memset(&hashbuf, 0, BUFSIZE);
274         if ((ret = gnutls_hash_fast(digest, encryption_passphrase,
275                                         strlen(encryption_passphrase), &hashbuf)) < 0) {
276                 debug_print("Hashing passkey failed: %s\n", gnutls_strerror(ret));
277                 return NULL;
278         }
279         for (i = 0; i < digestlen/2; i++) {
280                 hashbuf[i] = hashbuf[i] ^ hashbuf[i+digestlen/2];
281         }
282
283         key.data = malloc(keylen);
284         memcpy(key.data, &hashbuf, keylen);
285         key.size = keylen;
286
287         /* Prepare our source of random data. */
288 #if defined G_OS_UNIX
289         rnd = open("/dev/urandom", O_RDONLY);
290         if (rnd == -1) {
291                 perror("fopen on /dev/urandom");
292 #elif defined G_OS_WIN32
293         if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
294                         !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
295                 debug_print("Could not acquire a CSP handle.\n");
296 #endif
297                 g_free(key.data);
298                 return NULL;
299         }
300
301         /* Prepare random IV for cipher */
302         iv.data = malloc(IVLEN);
303         iv.size = IVLEN;
304 #if defined G_OS_UNIX
305         ret = read(rnd, iv.data, IVLEN);
306         if (ret != IVLEN) {
307                 perror("read into iv");
308                 close(rnd);
309 #elif defined G_OS_WIN32
310         if (!CryptGenRandom(rnd, IVLEN, iv.data)) {
311                 debug_print("Could not read random data for IV\n");
312                 CryptReleaseContext(rnd, 0);
313 #endif
314                 g_free(key.data);
315                 g_free(iv.data);
316                 return NULL;
317         }
318
319         /* Initialize the encryption */
320         ret = gnutls_cipher_init(&handle, algo, &key, &iv);
321         if (ret < 0) {
322                 g_free(key.data);
323                 g_free(iv.data);
324 #if defined G_OS_UNIX
325                 close(rnd);
326 #elif defined G_OS_WIN32
327                 CryptReleaseContext(rnd, 0);
328 #endif
329                 return NULL;
330         }
331
332         /* Fill buf with one block of random data, our password, pad the
333          * rest with zero bytes. */
334         buf = malloc(BUFSIZE + blocklen);
335         memset(buf, 0, BUFSIZE);
336 #if defined G_OS_UNIX
337         ret = read(rnd, buf, blocklen);
338         if (ret != blocklen) {
339                 perror("read into buffer");
340                 close(rnd);
341 #elif defined G_OS_WIN32
342         if (!CryptGenRandom(rnd, blocklen, buf)) {
343                 debug_print("Could not read random data for IV\n");
344                 CryptReleaseContext(rnd, 0);
345 #endif
346                 g_free(buf);
347                 g_free(key.data);
348                 g_free(iv.data);
349                 gnutls_cipher_deinit(handle);
350                 return NULL;
351         }
352
353         /* We don't need any more random data. */
354 #if defined G_OS_UNIX
355         close(rnd);
356 #elif defined G_OS_WIN32
357         CryptReleaseContext(rnd, 0);
358 #endif
359
360         memcpy(buf + blocklen, password, strlen(password));
361
362         /* Encrypt into encbuf */
363         encbuf = malloc(BUFSIZE + blocklen);
364         memset(encbuf, 0, BUFSIZE + blocklen);
365         ret = gnutls_cipher_encrypt2(handle, buf, BUFSIZE + blocklen,
366                         encbuf, BUFSIZE + blocklen);
367         if (ret < 0) {
368                 g_free(key.data);
369                 g_free(iv.data);
370                 g_free(buf);
371                 g_free(encbuf);
372                 gnutls_cipher_deinit(handle);
373                 return NULL;
374         }
375
376         /* Cleanup */
377         gnutls_cipher_deinit(handle);
378         g_free(key.data);
379         g_free(iv.data);
380         g_free(buf);
381
382         /* And finally prepare the resulting string:
383          * "{algorithm}base64encodedciphertext" */
384         base = g_base64_encode(encbuf, BUFSIZE);
385         g_free(encbuf);
386         output = g_strdup_printf("{%s}%s", gnutls_cipher_get_name(algo), base);
387         g_free(base);
388
389         return output;
390 }
391
392 gchar *password_decrypt_gnutls(const gchar *password,
393                 const gchar *decryption_passphrase)
394 {
395         gchar **tokens, *tmp;
396         gnutls_cipher_algorithm_t algo;
397         gnutls_digest_algorithm_t digest = GNUTLS_DIG_UNKNOWN;
398         gnutls_cipher_hd_t handle;
399         gnutls_datum_t key, iv;
400         int keylen, digestlen, blocklen, ret, i;
401         gsize len;
402         unsigned char hashbuf[BUFSIZE], *buf;
403 #if defined G_OS_UNIX
404         int rnd;
405 #elif defined G_OS_WIN32
406         HCRYPTPROV rnd;
407 #endif
408
409         g_return_val_if_fail(password != NULL, NULL);
410         g_return_val_if_fail(decryption_passphrase != NULL, NULL);
411
412         tokens = g_strsplit_set(password, "{}", 3);
413
414         /* Parse the string, retrieving algorithm and encrypted data.
415          * We expect "{algorithm}base64encodedciphertext". */
416         if (strlen(tokens[0]) != 0 ||
417                         (algo = gnutls_cipher_get_id(tokens[1])) == GNUTLS_CIPHER_UNKNOWN ||
418                         strlen(tokens[2]) == 0)
419                 return NULL;
420
421         /* Our hash algo needs to have digest length twice as long as our
422          * cipher algo's key length. */
423         if (algo == GNUTLS_CIPHER_AES_256_CBC) {
424                 debug_print("Using AES-256-CBC + SHA-512 for decryption\n");
425                 digest = GNUTLS_DIG_SHA512;
426         } else if (algo == GNUTLS_CIPHER_AES_128_CBC) {
427                 debug_print("Using AES-128-CBC + SHA-256 for decryption\n");
428                 digest = GNUTLS_DIG_SHA256;
429         }
430         if (digest == GNUTLS_DIG_UNKNOWN) {
431                 debug_print("Password is encrypted with unsupported cipher, giving up.\n");
432                 g_strfreev(tokens);
433                 return NULL;
434         }
435
436 /*      ivlen = gnutls_cipher_get_iv_size(algo); */
437         keylen = gnutls_cipher_get_key_size(algo);
438         blocklen = gnutls_cipher_get_block_size(algo);
439         digestlen = gnutls_hash_get_len(digest);
440
441         /* Prepare key for cipher - first half of hash of passkey XORed with
442          * the second. AES-256 has key length 32 and length of SHA-512 hash
443          * is exactly twice that, 64. */
444         memset(&hashbuf, 0, BUFSIZE);
445         if ((ret = gnutls_hash_fast(digest, decryption_passphrase,
446                                         strlen(decryption_passphrase), &hashbuf)) < 0) {
447                 debug_print("Hashing passkey failed: %s\n", gnutls_strerror(ret));
448                 g_strfreev(tokens);
449                 return NULL;
450         }
451         for (i = 0; i < digestlen/2; i++) {
452                 hashbuf[i] = hashbuf[i] ^ hashbuf[i+digestlen/2];
453         }
454
455         key.data = malloc(keylen);
456         memcpy(key.data, &hashbuf, keylen);
457         key.size = keylen;
458
459         /* Prepare our source of random data. */
460 #if defined G_OS_UNIX
461         rnd = open("/dev/urandom", O_RDONLY);
462         if (rnd == -1) {
463                 perror("fopen on /dev/urandom");
464 #elif defined G_OS_WIN32
465         if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
466                         !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
467                 debug_print("Could not acquire a CSP handle.\n");
468 #endif
469                 g_free(key.data);
470                 g_strfreev(tokens);
471                 return NULL;
472         }
473
474         /* Prepare random IV for cipher */
475         iv.data = malloc(IVLEN);
476         iv.size = IVLEN;
477 #if defined G_OS_UNIX
478         ret = read(rnd, iv.data, IVLEN);
479         if (ret != IVLEN) {
480                 perror("read into iv");
481                 close(rnd);
482 #elif defined G_OS_WIN32
483         if (!CryptGenRandom(rnd, IVLEN, iv.data)) {
484                 debug_print("Could not read random data for IV\n");
485                 CryptReleaseContext(rnd, 0);
486 #endif
487                 g_free(key.data);
488                 g_free(iv.data);
489                 g_strfreev(tokens);
490                 return NULL;
491         }
492
493         /* We don't need any more random data. */
494 #if defined G_OS_UNIX
495         close(rnd);
496 #elif defined G_OS_WIN32
497         CryptReleaseContext(rnd, 0);
498 #endif
499
500         /* Prepare encrypted password string for decryption. */
501         tmp = g_base64_decode(tokens[2], &len);
502         g_strfreev(tokens);
503
504         /* Initialize the decryption */
505         ret = gnutls_cipher_init(&handle, algo, &key, &iv);
506         if (ret < 0) {
507                 debug_print("Cipher init failed: %s\n", gnutls_strerror(ret));
508                 g_free(key.data);
509                 g_free(iv.data);
510                 return NULL;
511         }
512
513         buf = malloc(BUFSIZE + blocklen);
514         memset(buf, 0, BUFSIZE + blocklen);
515         ret = gnutls_cipher_decrypt2(handle, tmp, len,
516                         buf, BUFSIZE + blocklen);
517         if (ret < 0) {
518                 debug_print("Decryption failed: %s\n", gnutls_strerror(ret));
519                 g_free(key.data);
520                 g_free(iv.data);
521                 g_free(buf);
522                 gnutls_cipher_deinit(handle);
523                 return NULL;
524         }
525
526         /* Cleanup */
527         gnutls_cipher_deinit(handle);
528         g_free(key.data);
529         g_free(iv.data);
530
531         tmp = g_strndup(buf + blocklen, MIN(strlen(buf + blocklen), BUFSIZE));
532         g_free(buf);
533         return tmp;
534 }
535
536 #undef BUFSIZE
537
538 #endif
539
540 gchar *password_encrypt(const gchar *password,
541                 const gchar *encryption_passphrase)
542 {
543         if (password == NULL || strlen(password) == 0) {
544                 return NULL;
545         }
546
547 #ifndef PASSWORD_CRYPTO_OLD
548         if (encryption_passphrase == NULL)
549                 encryption_passphrase = master_passphrase();
550
551         return password_encrypt_real(password, encryption_passphrase);
552 #else
553         return password_encrypt_old(password);
554 #endif
555 }
556
557 gchar *password_decrypt(const gchar *password,
558                 const gchar *decryption_passphrase)
559 {
560         if (password == NULL || strlen(password) == 0) {
561                 return NULL;
562         }
563
564         /* First, check if the password was possibly decrypted using old,
565          * obsolete method */
566         if (*password == '!') {
567                 debug_print("Trying to decrypt password using the old method...\n");
568                 return password_decrypt_old(password);
569         }
570
571         /* Try available crypto backend */
572 #ifndef PASSWORD_CRYPTO_OLD
573         if (decryption_passphrase == NULL)
574                 decryption_passphrase = master_passphrase();
575
576         if (*password == '{') {
577                 debug_print("Trying to decrypt password...\n");
578                 return password_decrypt_real(password, decryption_passphrase);
579         }
580 #endif
581
582         /* Fallback, in case the configuration is really old and
583          * stored password in plaintext */
584         debug_print("Assuming password was stored plaintext, returning it unchanged\n");
585         return g_strdup(password);
586 }