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