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