Allow empty cipher (cipher_null).
[platform/upstream/cryptsetup.git] / lib / utils_crypt.c
1 /*
2  * utils_crypt - cipher utilities for cryptsetup
3  *
4  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
5  * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * version 2 as published by the Free Software Foundation.
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, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include <stdlib.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <termios.h>
31
32 #include "libcryptsetup.h"
33 #include "nls.h"
34 #include "utils_crypt.h"
35
36 #define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
37 #define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)
38
39 struct safe_allocation {
40         size_t  size;
41         char    data[0];
42 };
43
44 int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
45                               char *cipher_mode)
46 {
47         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
48                    cipher, cipher_mode) == 2) {
49                 if (!strcmp(cipher_mode, "plain"))
50                         strncpy(cipher_mode, "cbc-plain", 10);
51                 if (key_nums) {
52                         char *tmp = strchr(cipher, ':');
53                         *key_nums = tmp ? atoi(++tmp) : 1;
54                         if (!*key_nums)
55                                 return -EINVAL;
56                 }
57
58                 return 0;
59         }
60
61         /* Short version for "empty" cipher */
62         if (!strcmp(s, "null")) {
63                 strncpy(cipher, "cipher_null", MAX_CIPHER_LEN);
64                 strncpy(cipher_mode, "ecb-null", 9);
65                 if (key_nums)
66                         *key_nums = 0;
67                 return 0;
68         }
69
70         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
71                 strncpy(cipher_mode, "cbc-plain", 10);
72                 if (key_nums)
73                         *key_nums = 1;
74                 return 0;
75         }
76
77         return -EINVAL;
78 }
79
80 /* safe allocations */
81 void *crypt_safe_alloc(size_t size)
82 {
83         struct safe_allocation *alloc;
84
85         if (!size)
86                 return NULL;
87
88         alloc = malloc(size + offsetof(struct safe_allocation, data));
89         if (!alloc)
90                 return NULL;
91
92         alloc->size = size;
93
94         return &alloc->data;
95 }
96
97 void crypt_safe_free(void *data)
98 {
99         struct safe_allocation *alloc;
100
101         if (!data)
102                 return;
103
104         alloc = (struct safe_allocation *)
105                 ((char *)data - offsetof(struct safe_allocation, data));
106
107         memset(data, 0, alloc->size);
108
109         alloc->size = 0x55aa55aa;
110         free(alloc);
111 }
112
113 void *crypt_safe_realloc(void *data, size_t size)
114 {
115         struct safe_allocation *alloc;
116         void *new_data;
117
118         new_data = crypt_safe_alloc(size);
119
120         if (new_data && data) {
121
122                 alloc = (struct safe_allocation *)
123                         ((char *)data - offsetof(struct safe_allocation, data));
124
125                 if (size > alloc->size)
126                         size = alloc->size;
127
128                 memcpy(new_data, data, size);
129         }
130
131         crypt_safe_free(data);
132         return new_data;
133 }
134
135 /* Password reading helpers */
136 static int untimed_read(int fd, char *pass, size_t maxlen)
137 {
138         ssize_t i;
139
140         i = read(fd, pass, maxlen);
141         if (i > 0) {
142                 pass[i-1] = '\0';
143                 i = 0;
144         } else if (i == 0) { /* EOF */
145                 *pass = 0;
146                 i = -1;
147         }
148         return i;
149 }
150
151 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
152 {
153         struct timeval t;
154         fd_set fds;
155         int failed = -1;
156
157         FD_ZERO(&fds);
158         FD_SET(fd, &fds);
159         t.tv_sec = timeout;
160         t.tv_usec = 0;
161
162         if (select(fd+1, &fds, NULL, NULL, &t) > 0)
163                 failed = untimed_read(fd, pass, maxlen);
164
165         return failed;
166 }
167
168 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
169                 long timeout)
170 {
171         struct termios orig, tmp;
172         int failed = -1;
173         int infd = STDIN_FILENO, outfd;
174
175         if (maxlen < 1)
176                 goto out_err;
177
178         /* Read and write to /dev/tty if available */
179         if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
180                 infd = STDIN_FILENO;
181                 outfd = STDERR_FILENO;
182         }
183
184         if (tcgetattr(infd, &orig))
185                 goto out_err;
186
187         memcpy(&tmp, &orig, sizeof(tmp));
188         tmp.c_lflag &= ~ECHO;
189
190         if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
191                 goto out_err;
192
193         tcsetattr(infd, TCSAFLUSH, &tmp);
194         if (timeout)
195                 failed = timed_read(infd, pass, maxlen, timeout);
196         else
197                 failed = untimed_read(infd, pass, maxlen);
198         tcsetattr(infd, TCSAFLUSH, &orig);
199
200 out_err:
201         if (!failed && write(outfd, "\n", 1)) {};
202
203         if (infd != STDIN_FILENO)
204                 close(infd);
205         return failed;
206 }
207
208 static int crypt_get_key_tty(const char *prompt,
209                              char **key, size_t *key_size,
210                              int timeout, int verify,
211                              struct crypt_device *cd)
212 {
213         int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
214         int r = -EINVAL;
215         char *pass = NULL, *pass_verify = NULL;
216
217         log_dbg("Interactive passphrase entry requested.");
218
219         pass = crypt_safe_alloc(key_size_max + 1);
220         if (!pass) {
221                 log_err(cd, _("Out of memory while reading passphrase.\n"));
222                 return -ENOMEM;
223         }
224
225         if (interactive_pass(prompt, pass, key_size_max, timeout)) {
226                 log_err(cd, _("Error reading passphrase from terminal.\n"));
227                 goto out_err;
228         }
229         pass[key_size_max] = '\0';
230
231         if (verify) {
232                 pass_verify = crypt_safe_alloc(key_size_max);
233                 if (!pass_verify) {
234                         log_err(cd, _("Out of memory while reading passphrase.\n"));
235                         r = -ENOMEM;
236                         goto out_err;
237                 }
238
239                 if (interactive_pass(_("Verify passphrase: "),
240                     pass_verify, key_size_max, timeout)) {
241                         log_err(cd, _("Error reading passphrase from terminal.\n"));
242                         goto out_err;
243                 }
244
245                 if (strncmp(pass, pass_verify, key_size_max)) {
246                         log_err(cd, _("Passphrases do not match.\n"));
247                         r = -EPERM;
248                         goto out_err;
249                 }
250         }
251
252         *key = pass;
253         *key_size = strlen(pass);
254         r = 0;
255 out_err:
256         crypt_safe_free(pass_verify);
257         if (r)
258                 crypt_safe_free(pass);
259         return r;
260 }
261
262 /*
263  * Note: --key-file=- is interpreted as a read from a binary file (stdin)
264  * key_size_max == 0 means detect maximum according to input type (tty/file)
265  * timeout and verify options only applies to tty input
266  */
267 int crypt_get_key(const char *prompt,
268                   char **key, size_t *key_size,
269                   size_t keyfile_offset, size_t keyfile_size_max,
270                   const char *key_file, int timeout, int verify,
271                   struct crypt_device *cd)
272 {
273         int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
274         int r = -EINVAL;
275         char *pass = NULL, tmp;
276         size_t buflen, i, file_read_size;
277         struct stat st;
278
279         *key = NULL;
280         *key_size = 0;
281
282         /* Passphrase read from stdin? */
283         read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
284
285         if (read_stdin && isatty(STDIN_FILENO)) {
286                 if (keyfile_offset) {
287                         log_err(cd, _("Cannot use offset with terminal input.\n"));
288                         return -EINVAL;
289                 }
290                 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
291         }
292
293         if (read_stdin)
294                 log_dbg("STDIN descriptor passphrase entry requested.");
295         else
296                 log_dbg("File descriptor passphrase entry requested.");
297
298         /* If not requsted otherwise, we limit input to prevent memory exhaustion */
299         if (keyfile_size_max == 0) {
300                 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
301                 unlimited_read = 1;
302         }
303
304         fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
305         if (fd < 0) {
306                 log_err(cd, _("Failed to open key file.\n"));
307                 return -EINVAL;
308         }
309
310         /* use 4k for buffer (page divisor but avoid huge pages) */
311         buflen = 4096 - sizeof(struct safe_allocation);
312         regular_file = 0;
313         if(!read_stdin) {
314                 if(stat(key_file, &st) < 0) {
315                         log_err(cd, _("Failed to stat key file.\n"));
316                         goto out_err;
317                 }
318                 if(S_ISREG(st.st_mode)) {
319                         regular_file = 1;
320                         file_read_size = (size_t)st.st_size;
321
322                         if (keyfile_offset > file_read_size) {
323                                 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
324                                 goto out_err;
325                         }
326                         file_read_size -= keyfile_offset;
327
328                         /* known keyfile size, alloc it in one step */
329                         if (file_read_size >= keyfile_size_max)
330                                 buflen = keyfile_size_max;
331                         else if (file_read_size)
332                                 buflen = file_read_size;
333                 }
334         }
335
336         pass = crypt_safe_alloc(buflen);
337         if (!pass) {
338                 log_err(cd, _("Out of memory while reading passphrase.\n"));
339                 goto out_err;
340         }
341
342         /* Discard keyfile_offset bytes on input */
343         for(i = 0; i < keyfile_offset; i++)
344                 if (read(fd, &tmp, 1) != 1) {
345                         log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
346                         goto out_err;
347                 }
348
349         for(i = 0; i < keyfile_size_max; i++) {
350                 if(i == buflen) {
351                         buflen += 4096;
352                         pass = crypt_safe_realloc(pass, buflen);
353                         if (!pass) {
354                                 log_err(cd, _("Out of memory while reading passphrase.\n"));
355                                 r = -ENOMEM;
356                                 goto out_err;
357                         }
358                 }
359
360                 char_read = read(fd, &pass[i], 1);
361                 if (char_read < 0) {
362                         log_err(cd, _("Error reading passphrase.\n"));
363                         goto out_err;
364                 }
365
366                 /* Stop on newline only if not requested read from keyfile */
367                 if(char_read == 0 || (!key_file && pass[i] == '\n'))
368                         break;
369         }
370
371         /* Fail if piped input dies reading nothing */
372         if(!i && !regular_file) {
373                 log_dbg("Nothing read on input.");
374                 r = -EPIPE;
375                 goto out_err;
376         }
377
378         /* Fail if we exceeded internal default (no specified size) */
379         if (unlimited_read && i == keyfile_size_max) {
380                 log_err(cd, _("Maximum keyfile size exceeded.\n"));
381                 goto out_err;
382         }
383
384         if (!unlimited_read && i != keyfile_size_max) {
385                 log_err(cd, _("Cannot read requested amount of data.\n"));
386                 goto out_err;
387         }
388
389         *key = pass;
390         *key_size = i;
391         r = 0;
392 out_err:
393         if(fd != STDIN_FILENO)
394                 close(fd);
395
396         if (r)
397                 crypt_safe_free(pass);
398         return r;
399 }