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