xref: /vim-8.2.3635/src/crypt.c (revision cc7ff3fc)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * crypt.c: Generic encryption support.
12  */
13 #include "vim.h"
14 
15 #if defined(FEAT_CRYPT) || defined(PROTO)
16 /*
17  * Optional encryption support.
18  * Mohsin Ahmed, [email protected], 1998-09-24
19  * Based on zip/crypt sources.
20  * Refactored by David Leadbeater, 2014.
21  *
22  * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
23  * most countries.  There are a few exceptions, but that still should not be a
24  * problem since this code was originally created in Europe and India.
25  *
26  * Blowfish addition originally made by Mohsin Ahmed,
27  * http://www.cs.albany.edu/~mosh 2010-03-14
28  * Based on blowfish by Bruce Schneier (http://www.schneier.com/blowfish.html)
29  * and sha256 by Christophe Devine.
30  */
31 
32 typedef struct {
33     char    *name;	/* encryption name as used in 'cryptmethod' */
34     char    *magic;	/* magic bytes stored in file header */
35     int	    salt_len;	/* length of salt, or 0 when not using salt */
36     int	    seed_len;	/* length of seed, or 0 when not using salt */
37     int	    works_inplace; /* encryption/decryption can be done in-place */
38     int	    whole_undofile; /* whole undo file is encrypted */
39 
40     /* Optional function pointer for a self-test. */
41     int (* self_test_fn)();
42 
43     /* Function pointer for initializing encryption/decription. */
44     void (* init_fn)(cryptstate_T *state, char_u *key,
45 		      char_u *salt, int salt_len, char_u *seed, int seed_len);
46 
47     /* Function pointers for encoding/decoding from one buffer into another.
48      * Optional, however, these or the _buffer ones should be configured. */
49     void (*encode_fn)(cryptstate_T *state, char_u *from, size_t len,
50 								  char_u *to);
51     void (*decode_fn)(cryptstate_T *state, char_u *from, size_t len,
52 								  char_u *to);
53 
54     /* Function pointers for encoding and decoding, can buffer data if needed.
55      * Optional (however, these or the above should be configured). */
56     long (*encode_buffer_fn)(cryptstate_T *state, char_u *from, size_t len,
57 							     char_u **newptr);
58     long (*decode_buffer_fn)(cryptstate_T *state, char_u *from, size_t len,
59 							     char_u **newptr);
60 
61     /* Function pointers for in-place encoding and decoding, used for
62      * crypt_*_inplace(). "from" and "to" arguments will be equal.
63      * These may be the same as decode_fn and encode_fn above, however an
64      * algorithm may implement them in a way that is not interchangeable with
65      * the crypt_(en|de)code() interface (for example because it wishes to add
66      * padding to files).
67      * This method is used for swap and undo files which have a rigid format.
68      */
69     void (*encode_inplace_fn)(cryptstate_T *state, char_u *p1, size_t len,
70 								  char_u *p2);
71     void (*decode_inplace_fn)(cryptstate_T *state, char_u *p1, size_t len,
72 								  char_u *p2);
73 } cryptmethod_T;
74 
75 /* index is method_nr of cryptstate_T, CRYPT_M_* */
76 static cryptmethod_T cryptmethods[CRYPT_M_COUNT] = {
77     /* PK_Zip; very weak */
78     {
79 	"zip",
80 	"VimCrypt~01!",
81 	0,
82 	0,
83 	TRUE,
84 	FALSE,
85 	NULL,
86 	crypt_zip_init,
87 	crypt_zip_encode, crypt_zip_decode,
88 	NULL, NULL,
89 	crypt_zip_encode, crypt_zip_decode,
90     },
91 
92     /* Blowfish/CFB + SHA-256 custom key derivation; implementation issues. */
93     {
94 	"blowfish",
95 	"VimCrypt~02!",
96 	8,
97 	8,
98 	TRUE,
99 	FALSE,
100 	blowfish_self_test,
101 	crypt_blowfish_init,
102 	crypt_blowfish_encode, crypt_blowfish_decode,
103 	NULL, NULL,
104 	crypt_blowfish_encode, crypt_blowfish_decode,
105     },
106 
107     /* Blowfish/CFB + SHA-256 custom key derivation; fixed. */
108     {
109 	"blowfish2",
110 	"VimCrypt~03!",
111 	8,
112 	8,
113 	TRUE,
114 	TRUE,
115 	blowfish_self_test,
116 	crypt_blowfish_init,
117 	crypt_blowfish_encode, crypt_blowfish_decode,
118 	NULL, NULL,
119 	crypt_blowfish_encode, crypt_blowfish_decode,
120     },
121 };
122 
123 #define CRYPT_MAGIC_LEN	12	/* cannot change */
124 static char	crypt_magic_head[] = "VimCrypt~";
125 
126 /*
127  * Return int value for crypt method name.
128  * 0 for "zip", the old method.  Also for any non-valid value.
129  * 1 for "blowfish".
130  * 2 for "blowfish2".
131  */
132     int
133 crypt_method_nr_from_name(name)
134     char_u  *name;
135 {
136     int i;
137 
138     for (i = 0; i < CRYPT_M_COUNT; ++i)
139 	if (STRCMP(name, cryptmethods[i].name) == 0)
140 	    return i;
141     return 0;
142 }
143 
144 /*
145  * Get the crypt method used for a file from "ptr[len]", the magic text at the
146  * start of the file.
147  * Returns -1 when no encryption used.
148  */
149     int
150 crypt_method_nr_from_magic(ptr, len)
151     char  *ptr;
152     int   len;
153 {
154     int i;
155 
156     if (len < CRYPT_MAGIC_LEN)
157 	return -1;
158 
159     for (i = 0; i < CRYPT_M_COUNT; i++)
160 	if (memcmp(ptr, cryptmethods[i].magic, CRYPT_MAGIC_LEN) == 0)
161 	    return i;
162 
163     i = (int)STRLEN(crypt_magic_head);
164     if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
165 	EMSG(_("E821: File is encrypted with unknown method"));
166 
167     return -1;
168 }
169 
170 /*
171  * Return TRUE if the crypt method for "method_nr" can be done in-place.
172  */
173     int
174 crypt_works_inplace(state)
175     cryptstate_T *state;
176 {
177     return cryptmethods[state->method_nr].works_inplace;
178 }
179 
180 /*
181  * Get the crypt method for buffer "buf" as a number.
182  */
183     int
184 crypt_get_method_nr(buf)
185     buf_T *buf;
186 {
187     return crypt_method_nr_from_name(*buf->b_p_cm == NUL ? p_cm : buf->b_p_cm);
188 }
189 
190 /*
191  * Return TRUE when the buffer uses an encryption method that encrypts the
192  * whole undo file, not only the text.
193  */
194     int
195 crypt_whole_undofile(method_nr)
196     int method_nr;
197 {
198     return cryptmethods[method_nr].whole_undofile;
199 }
200 
201 /*
202  * Get crypt method specifc length of the file header in bytes.
203  */
204     int
205 crypt_get_header_len(method_nr)
206     int method_nr;
207 {
208     return CRYPT_MAGIC_LEN
209 	+ cryptmethods[method_nr].salt_len
210 	+ cryptmethods[method_nr].seed_len;
211 }
212 
213 /*
214  * Set the crypt method for buffer "buf" to "method_nr" using the int value as
215  * returned by crypt_method_nr_from_name().
216  */
217     void
218 crypt_set_cm_option(buf, method_nr)
219     buf_T   *buf;
220     int	    method_nr;
221 {
222     free_string_option(buf->b_p_cm);
223     buf->b_p_cm = vim_strsave((char_u *)cryptmethods[method_nr].name);
224 }
225 
226 /*
227  * If the crypt method for the current buffer has a self-test, run it and
228  * return OK/FAIL.
229  */
230     int
231 crypt_self_test()
232 {
233     int method_nr = crypt_get_method_nr(curbuf);
234 
235     if (cryptmethods[method_nr].self_test_fn == NULL)
236 	return OK;
237     return cryptmethods[method_nr].self_test_fn();
238 }
239 
240 /*
241  * Allocate a crypt state and initialize it.
242  */
243     cryptstate_T *
244 crypt_create(method_nr, key, salt, salt_len, seed, seed_len)
245     int		method_nr;
246     char_u	*key;
247     char_u	*salt;
248     int		salt_len;
249     char_u	*seed;
250     int		seed_len;
251 {
252     cryptstate_T *state = (cryptstate_T *)alloc((int)sizeof(cryptstate_T));
253 
254     state->method_nr = method_nr;
255     cryptmethods[method_nr].init_fn(state, key, salt, salt_len, seed, seed_len);
256     return state;
257 }
258 
259 /*
260  * Allocate a crypt state from a file header and initialize it.
261  * Assumes that header contains at least the number of bytes that
262  * crypt_get_header_len() returns for "method_nr".
263  */
264     cryptstate_T *
265 crypt_create_from_header(method_nr, key, header)
266     int		method_nr;
267     char_u	*key;
268     char_u	*header;
269 {
270     char_u	*salt = NULL;
271     char_u	*seed = NULL;
272     int		salt_len = cryptmethods[method_nr].salt_len;
273     int		seed_len = cryptmethods[method_nr].seed_len;
274 
275     if (salt_len > 0)
276 	salt = header + CRYPT_MAGIC_LEN;
277     if (seed_len > 0)
278 	seed = header + CRYPT_MAGIC_LEN + salt_len;
279 
280     return crypt_create(method_nr, key, salt, salt_len, seed, seed_len);
281 }
282 
283 /*
284  * Read the crypt method specific header data from "fp".
285  * Return an allocated cryptstate_T or NULL on error.
286  */
287     cryptstate_T *
288 crypt_create_from_file(fp, key)
289     FILE    *fp;
290     char_u  *key;
291 {
292     int		method_nr;
293     int		header_len;
294     char	magic_buffer[CRYPT_MAGIC_LEN];
295     char_u	*buffer;
296     cryptstate_T *state;
297 
298     if (fread(magic_buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
299 	return NULL;
300     method_nr = crypt_method_nr_from_magic(magic_buffer, CRYPT_MAGIC_LEN);
301     if (method_nr < 0)
302 	return NULL;
303 
304     header_len = crypt_get_header_len(method_nr);
305     if ((buffer = alloc(header_len)) == NULL)
306 	return NULL;
307     mch_memmove(buffer, magic_buffer, CRYPT_MAGIC_LEN);
308     if (header_len > CRYPT_MAGIC_LEN
309 	    && fread(buffer + CRYPT_MAGIC_LEN,
310 				    header_len - CRYPT_MAGIC_LEN, 1, fp) != 1)
311     {
312 	vim_free(buffer);
313 	return NULL;
314     }
315 
316     state = crypt_create_from_header(method_nr, key, buffer);
317     vim_free(buffer);
318     return state;
319 }
320 
321 /*
322  * Allocate a cryptstate_T for writing and initialize it with "key".
323  * Allocates and fills in the header and stores it in "header", setting
324  * "header_len".  The header may include salt and seed, depending on
325  * cryptmethod.  Caller must free header.
326  * Returns the state or NULL on failure.
327  */
328     cryptstate_T *
329 crypt_create_for_writing(method_nr, key, header, header_len)
330     int	    method_nr;
331     char_u  *key;
332     char_u  **header;
333     int	    *header_len;
334 {
335     int	    len = crypt_get_header_len(method_nr);
336     char_u  *salt = NULL;
337     char_u  *seed = NULL;
338     int	    salt_len = cryptmethods[method_nr].salt_len;
339     int	    seed_len = cryptmethods[method_nr].seed_len;
340     cryptstate_T *state;
341 
342     *header_len = len;
343     *header = alloc(len);
344     if (*header == NULL)
345 	return NULL;
346 
347     mch_memmove(*header, cryptmethods[method_nr].magic, CRYPT_MAGIC_LEN);
348     if (salt_len > 0 || seed_len > 0)
349     {
350 	if (salt_len > 0)
351 	    salt = *header + CRYPT_MAGIC_LEN;
352 	if (seed_len > 0)
353 	    seed = *header + CRYPT_MAGIC_LEN + salt_len;
354 
355 	/* TODO: Should this be crypt method specific? (Probably not worth
356 	 * it).  sha2_seed is pretty bad for large amounts of entropy, so make
357 	 * that into something which is suitable for anything. */
358 	sha2_seed(salt, salt_len, seed, seed_len);
359     }
360 
361     state = crypt_create(method_nr, key, salt, salt_len, seed, seed_len);
362     if (state == NULL)
363     {
364 	vim_free(*header);
365 	*header = NULL;
366     }
367     return state;
368 }
369 
370 /*
371  * Free the crypt state.
372  */
373     void
374 crypt_free_state(state)
375     cryptstate_T	*state;
376 {
377     vim_free(state->method_state);
378     vim_free(state);
379 }
380 
381 /*
382  * Encode "from[len]" and store the result in a newly allocated buffer, which
383  * is stored in "newptr".
384  * Return number of bytes in "newptr", 0 for need more or -1 on error.
385  */
386     long
387 crypt_encode_alloc(state, from, len, newptr)
388     cryptstate_T *state;
389     char_u	*from;
390     size_t	len;
391     char_u	**newptr;
392 {
393     cryptmethod_T *method = &cryptmethods[state->method_nr];
394 
395     if (method->encode_buffer_fn != NULL)
396 	/* Has buffer function, pass through. */
397 	return method->encode_buffer_fn(state, from, len, newptr);
398     if (len == 0)
399 	/* Not buffering, just return EOF. */
400 	return (long)len;
401 
402     *newptr = alloc((long)len);
403     if (*newptr == NULL)
404 	return -1;
405     method->encode_fn(state, from, len, *newptr);
406     return (long)len;
407 }
408 
409 /*
410  * Decrypt "ptr[len]" and store the result in a newly allocated buffer, which
411  * is stored in "newptr".
412  * Return number of bytes in "newptr", 0 for need more or -1 on error.
413  */
414     long
415 crypt_decode_alloc(state, ptr, len, newptr)
416     cryptstate_T *state;
417     char_u	*ptr;
418     long	len;
419     char_u      **newptr;
420 {
421     cryptmethod_T *method = &cryptmethods[state->method_nr];
422 
423     if (method->decode_buffer_fn != NULL)
424 	/* Has buffer function, pass through. */
425 	return method->decode_buffer_fn(state, ptr, len, newptr);
426 
427     if (len == 0)
428 	/* Not buffering, just return EOF. */
429 	return len;
430 
431     *newptr = alloc(len);
432     if (*newptr == NULL)
433 	return -1;
434     method->decode_fn(state, ptr, len, *newptr);
435     return len;
436 }
437 
438 /*
439  * Encrypting "from[len]" into "to[len]".
440  */
441     void
442 crypt_encode(state, from, len, to)
443     cryptstate_T *state;
444     char_u	*from;
445     size_t	len;
446     char_u	*to;
447 {
448     cryptmethods[state->method_nr].encode_fn(state, from, len, to);
449 }
450 
451 /*
452  * decrypting "from[len]" into "to[len]".
453  */
454     void
455 crypt_decode(state, from, len, to)
456     cryptstate_T *state;
457     char_u	*from;
458     size_t	len;
459     char_u	*to;
460 {
461     cryptmethods[state->method_nr].decode_fn(state, from, len, to);
462 }
463 
464 /*
465  * Simple inplace encryption, modifies "buf[len]" in place.
466  */
467     void
468 crypt_encode_inplace(state, buf, len)
469     cryptstate_T *state;
470     char_u	*buf;
471     size_t	len;
472 {
473     cryptmethods[state->method_nr].encode_inplace_fn(state, buf, len, buf);
474 }
475 
476 /*
477  * Simple inplace decryption, modifies "buf[len]" in place.
478  */
479     void
480 crypt_decode_inplace(state, buf, len)
481     cryptstate_T *state;
482     char_u	*buf;
483     size_t	len;
484 {
485     cryptmethods[state->method_nr].decode_inplace_fn(state, buf, len, buf);
486 }
487 
488 /*
489  * Free an allocated crypt key.  Clear the text to make sure it doesn't stay
490  * in memory anywhere.
491  */
492     void
493 crypt_free_key(key)
494     char_u *key;
495 {
496     char_u *p;
497 
498     if (key != NULL)
499     {
500 	for (p = key; *p != NUL; ++p)
501 	    *p = 0;
502 	vim_free(key);
503     }
504 }
505 
506 /*
507  * Check the crypt method and give a warning if it's outdated.
508  */
509     void
510 crypt_check_method(method)
511     int method;
512 {
513     if (method < CRYPT_M_BF2)
514     {
515 	msg_scroll = TRUE;
516 	MSG(_("Warning: Using a weak encryption method; see :help 'cm'"));
517     }
518 }
519 
520     void
521 crypt_check_current_method()
522 {
523     crypt_check_method(crypt_get_method_nr(curbuf));
524 }
525 
526 /*
527  * Ask the user for a crypt key.
528  * When "store" is TRUE, the new key is stored in the 'key' option, and the
529  * 'key' option value is returned: Don't free it.
530  * When "store" is FALSE, the typed key is returned in allocated memory.
531  * Returns NULL on failure.
532  */
533     char_u *
534 crypt_get_key(store, twice)
535     int		store;
536     int		twice;	    /* Ask for the key twice. */
537 {
538     char_u	*p1, *p2 = NULL;
539     int		round;
540 
541     for (round = 0; ; ++round)
542     {
543 	cmdline_star = TRUE;
544 	cmdline_row = msg_row;
545 	p1 = getcmdline_prompt(NUL, round == 0
546 		? (char_u *)_("Enter encryption key: ")
547 		: (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
548 		NULL);
549 	cmdline_star = FALSE;
550 
551 	if (p1 == NULL)
552 	    break;
553 
554 	if (round == twice)
555 	{
556 	    if (p2 != NULL && STRCMP(p1, p2) != 0)
557 	    {
558 		MSG(_("Keys don't match!"));
559 		crypt_free_key(p1);
560 		crypt_free_key(p2);
561 		p2 = NULL;
562 		round = -1;		/* do it again */
563 		continue;
564 	    }
565 
566 	    if (store)
567 	    {
568 		set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
569 		crypt_free_key(p1);
570 		p1 = curbuf->b_p_key;
571 	    }
572 	    break;
573 	}
574 	p2 = p1;
575     }
576 
577     /* since the user typed this, no need to wait for return */
578     if (msg_didout)
579 	msg_putchar('\n');
580     need_wait_return = FALSE;
581     msg_didout = FALSE;
582 
583     crypt_free_key(p2);
584     return p1;
585 }
586 
587 
588 /*
589  * Append a message to IObuff for the encryption/decryption method being used.
590  */
591     void
592 crypt_append_msg(buf)
593     buf_T *buf;
594 {
595     if (crypt_get_method_nr(buf) == 0)
596 	STRCAT(IObuff, _("[crypted]"));
597     else
598     {
599 	STRCAT(IObuff, "[");
600 	STRCAT(IObuff, *buf->b_p_cm == NUL ? p_cm : buf->b_p_cm);
601 	STRCAT(IObuff, "]");
602     }
603 }
604 
605 #endif /* FEAT_CRYPT */
606