Specify copyright holders in source files.
[platform/upstream/cryptsetup.git] / lib / utils_crypt.c
1 /*
2  * util_crypt - cipher utilities for cryptsetup
3  *
4  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
5  * Copyright (C) 2009-2011, 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 struct safe_allocation {
37         size_t  size;
38         char    data[0];
39 };
40
41 int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
42                               char *cipher_mode)
43 {
44         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
45                    cipher, cipher_mode) == 2) {
46                 if (!strcmp(cipher_mode, "plain"))
47                         strncpy(cipher_mode, "cbc-plain", 10);
48                 if (key_nums) {
49                         char *tmp = strchr(cipher, ':');
50                         *key_nums = tmp ? atoi(++tmp) : 1;
51                         if (!*key_nums)
52                                 return -EINVAL;
53                 }
54
55                 return 0;
56         }
57
58         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
59                 strncpy(cipher_mode, "cbc-plain", 10);
60                 if (key_nums)
61                         *key_nums = 1;
62                 return 0;
63         }
64
65         return -EINVAL;
66 }
67
68 /* safe allocations */
69 void *crypt_safe_alloc(size_t size)
70 {
71         struct safe_allocation *alloc;
72
73         if (!size)
74                 return NULL;
75
76         alloc = malloc(size + offsetof(struct safe_allocation, data));
77         if (!alloc)
78                 return NULL;
79
80         alloc->size = size;
81
82         return &alloc->data;
83 }
84
85 void crypt_safe_free(void *data)
86 {
87         struct safe_allocation *alloc;
88
89         if (!data)
90                 return;
91
92         alloc = data - offsetof(struct safe_allocation, data);
93
94         memset(data, 0, alloc->size);
95
96         alloc->size = 0x55aa55aa;
97         free(alloc);
98 }
99
100 void *crypt_safe_realloc(void *data, size_t size)
101 {
102         void *new_data;
103
104         new_data = crypt_safe_alloc(size);
105
106         if (new_data && data) {
107                 struct safe_allocation *alloc;
108
109                 alloc = data - offsetof(struct safe_allocation, data);
110
111                 if (size > alloc->size)
112                         size = alloc->size;
113
114                 memcpy(new_data, data, size);
115         }
116
117         crypt_safe_free(data);
118         return new_data;
119 }
120
121 /* Password reading helpers */
122 static int untimed_read(int fd, char *pass, size_t maxlen)
123 {
124         ssize_t i;
125
126         i = read(fd, pass, maxlen);
127         if (i > 0) {
128                 pass[i-1] = '\0';
129                 i = 0;
130         } else if (i == 0) { /* EOF */
131                 *pass = 0;
132                 i = -1;
133         }
134         return i;
135 }
136
137 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
138 {
139         struct timeval t;
140         fd_set fds;
141         int failed = -1;
142
143         FD_ZERO(&fds);
144         FD_SET(fd, &fds);
145         t.tv_sec = timeout;
146         t.tv_usec = 0;
147
148         if (select(fd+1, &fds, NULL, NULL, &t) > 0)
149                 failed = untimed_read(fd, pass, maxlen);
150
151         return failed;
152 }
153
154 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
155                 long timeout)
156 {
157         struct termios orig, tmp;
158         int failed = -1;
159         int infd = STDIN_FILENO, outfd;
160
161         if (maxlen < 1)
162                 goto out_err;
163
164         /* Read and write to /dev/tty if available */
165         if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
166                 infd = STDIN_FILENO;
167                 outfd = STDERR_FILENO;
168         }
169
170         if (tcgetattr(infd, &orig))
171                 goto out_err;
172
173         memcpy(&tmp, &orig, sizeof(tmp));
174         tmp.c_lflag &= ~ECHO;
175
176         if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
177                 goto out_err;
178
179         tcsetattr(infd, TCSAFLUSH, &tmp);
180         if (timeout)
181                 failed = timed_read(infd, pass, maxlen, timeout);
182         else
183                 failed = untimed_read(infd, pass, maxlen);
184         tcsetattr(infd, TCSAFLUSH, &orig);
185
186 out_err:
187         if (!failed && write(outfd, "\n", 1)) {};
188
189         if (infd != STDIN_FILENO)
190                 close(infd);
191         return failed;
192 }
193
194 /*
195  * Password reading behaviour matrix of get_key
196  * FIXME: rewrite this from scratch.
197  *                    p   v   n   h
198  * -----------------+---+---+---+---
199  * interactive      | Y | Y | Y | Inf
200  * from fd          | N | N | Y | Inf
201  * from binary file | N | N | N | Inf or options->key_size
202  *
203  * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
204  *
205  * Note: --key-file=- is interpreted as a read from a binary file (stdin)
206  */
207
208 int crypt_get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
209                   const char *key_file, int timeout, int verify,
210                   struct crypt_device *cd)
211 {
212         int fd = -1;
213         char *pass = NULL;
214         int read_horizon;
215         int regular_file = 0;
216         int read_stdin;
217         int r;
218         struct stat st;
219
220         /* Passphrase read from stdin? */
221         read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
222
223         /* read_horizon applies only for real keyfile, not stdin or terminal */
224         read_horizon = (key_file && !read_stdin) ? key_size : 0 /* until EOF */;
225
226         /* Setup file descriptior */
227         fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
228         if (fd < 0) {
229                 crypt_log(cd, CRYPT_LOG_ERROR,
230                           _("Failed to open key file.\n"));
231                 goto out_err;
232         }
233
234         /* Interactive case */
235         if(isatty(fd)) {
236                 int i;
237
238                 pass = crypt_safe_alloc(MAX_TTY_PASSWORD_LEN);
239                 if (!pass || interactive_pass(prompt, pass, MAX_TTY_PASSWORD_LEN, timeout)) {
240                         crypt_log(cd, CRYPT_LOG_ERROR,
241                                   _("Error reading passphrase from terminal.\n"));
242                         goto out_err;
243                 }
244                 if (verify) {
245                         char pass_verify[MAX_TTY_PASSWORD_LEN];
246                         i = interactive_pass(_("Verify passphrase: "), pass_verify, sizeof(pass_verify), timeout);
247                         if (i || strcmp(pass, pass_verify) != 0) {
248                                 crypt_log(cd, CRYPT_LOG_ERROR,
249                                  _("Passphrases do not match.\n"));
250                                 goto out_err;
251                         }
252                         memset(pass_verify, 0, sizeof(pass_verify));
253                 }
254                 *passLen = strlen(pass);
255                 *key = pass;
256         } else {
257                 /*
258                  * This is either a fd-input or a file, in neither case we can verify the input,
259                  * however we don't stop on new lines if it's a binary file.
260                  */
261                 int buflen, i;
262
263                 /* The following for control loop does an exhausting
264                  * read on the key material file, if requested with
265                  * key_size == 0, as it's done by LUKS. However, we
266                  * should warn the user, if it's a non-regular file,
267                  * such as /dev/random, because in this case, the loop
268                  * will read forever.
269                  */
270                 if(!read_stdin && read_horizon == 0) {
271                         if(stat(key_file, &st) < 0) {
272                                 crypt_log(cd, CRYPT_LOG_ERROR,
273                                         _("Failed to stat key file.\n"));
274                                 goto out_err;
275                         }
276                         if(!S_ISREG(st.st_mode))
277                                 crypt_log(cd, CRYPT_LOG_NORMAL,
278                                           _("Warning: exhausting read requested, but key file"
279                                             " is not a regular file, function might never return.\n"));
280                         else
281                                 regular_file = 1;
282                 }
283                 buflen = 0;
284                 for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
285                         if(i >= buflen - 1) {
286                                 buflen += 128;
287                                 pass = crypt_safe_realloc(pass, buflen);
288                                 if (!pass) {
289                                         crypt_log(cd, CRYPT_LOG_ERROR,
290                                                   _("Out of memory while reading passphrase.\n"));
291                                         goto out_err;
292                                 }
293                         }
294
295                         r = read(fd, pass + i, 1);
296                         if (r < 0) {
297                                 crypt_log(cd, CRYPT_LOG_ERROR,
298                                           _("Error reading passphrase.\n"));
299                                 goto out_err;
300                         }
301
302                         /* Stop on newline only if not requested read from keyfile */
303                         if(r == 0 || (!key_file && pass[i] == '\n'))
304                                 break;
305                 }
306                 /* Fail if piped input dies reading nothing */
307                 if(!i && !regular_file)
308                         goto out_err;
309                 pass[i] = 0;
310                 *key = pass;
311                 *passLen = i;
312         }
313         if(fd != STDIN_FILENO)
314                 close(fd);
315         return 0;
316
317 out_err:
318         if(fd >= 0 && fd != STDIN_FILENO)
319                 close(fd);
320         if(pass)
321                 crypt_safe_free(pass);
322         *key = NULL;
323         *passLen = 0;
324         return -EINVAL;
325 }