1 /*
2  * COPYRIGHT (c) International Business Machines Corp. 2013-2017
3  *
4  * This program is provided under the terms of the Common Public License,
5  * version 1.0 (CPL-1.0). Any use, reproduction or distribution for this
6  * software constitutes recipient's acceptance of CPL-1.0 terms which can be
7  * found in the file LICENSE file or at
8  * https://opensource.org/licenses/cpl1.0.php
9  */
10 
11 #define _GNU_SOURCE
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <string.h>
16 #include <errno.h>
17 #include <openssl/hmac.h>
18 #include <openssl/evp.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <grp.h>
23 
24 #include "pkcs11types.h"
25 #include "defs.h"
26 #include "host_defs.h"
27 #include "h_extern.h"
28 #include "pbkdf.h"
29 #include "trace.h"
30 
31 
get_randombytes(unsigned char * output,int bytes)32 CK_RV get_randombytes(unsigned char *output, int bytes)
33 {
34     int ranfd;
35     int rlen;
36     int totallen = 0;
37 
38     ranfd = open("/dev/urandom", O_RDONLY);
39     if (ranfd >= 0) {
40         do {
41             rlen = read(ranfd, output + totallen, bytes - totallen);
42             if (rlen == -1) {
43                 close(ranfd);
44                 TRACE_ERROR("read failed: %s\n", strerror(errno));
45                 return CKR_FUNCTION_FAILED;
46             }
47             totallen += rlen;
48         } while (totallen < bytes);
49         close(ranfd);
50         return CKR_OK;
51     }
52 
53     return CKR_FUNCTION_FAILED;
54 }
55 
set_perms(int file)56 CK_RV set_perms(int file)
57 {
58     struct group *grp;
59 
60     if (fchmod(file, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) != 0) {
61         TRACE_ERROR("fchmod failed: %s\n", strerror(errno));
62         return CKR_FUNCTION_FAILED;
63     }
64 
65     grp = getgrnam(PKCS11GROUP);
66     if (grp) {
67         if (fchown(file, -1, grp->gr_gid) != 0) {
68             TRACE_ERROR("fchown failed: %s\n", strerror(errno));
69             return CKR_FUNCTION_FAILED;
70         }
71     } else {
72         TRACE_ERROR("getgrnam failed:%s\n", strerror(errno));
73         return CKR_FUNCTION_FAILED;
74     }
75 
76     return CKR_OK;
77 }
78 
encrypt_aes(CK_BYTE * inbuf,int inbuflen,CK_BYTE * dkey,CK_BYTE * iv,CK_BYTE * outbuf,int * outbuflen)79 CK_RV encrypt_aes(CK_BYTE * inbuf, int inbuflen, CK_BYTE * dkey,
80                   CK_BYTE * iv, CK_BYTE * outbuf, int *outbuflen)
81 {
82     const EVP_CIPHER *cipher = EVP_aes_256_cbc();
83     int tmplen;
84 
85 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
86     EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
87 
88     EVP_EncryptInit_ex(ctx, cipher, NULL, dkey, iv);
89     if (!EVP_EncryptUpdate(ctx, outbuf, outbuflen, inbuf, inbuflen)) {
90         TRACE_ERROR("EVP_EncryptUpdate failed.\n");
91         return CKR_FUNCTION_FAILED;
92     }
93     if (!EVP_EncryptFinal_ex(ctx, outbuf + (*outbuflen), &tmplen)) {
94         TRACE_ERROR("EVP_EncryptFinal failed.\n");
95         return CKR_FUNCTION_FAILED;
96     }
97 
98     *outbuflen = (*outbuflen) + tmplen;
99     EVP_CIPHER_CTX_free(ctx);
100 
101 #else
102     EVP_CIPHER_CTX ctx;
103     EVP_CIPHER_CTX_init(&ctx);
104 
105     EVP_EncryptInit_ex(&ctx, cipher, NULL, dkey, iv);
106     if (!EVP_EncryptUpdate(&ctx, outbuf, outbuflen, inbuf, inbuflen)) {
107         TRACE_ERROR("EVP_EncryptUpdate failed.\n");
108         return CKR_FUNCTION_FAILED;
109     }
110     if (!EVP_EncryptFinal_ex(&ctx, outbuf + (*outbuflen), &tmplen)) {
111         TRACE_ERROR("EVP_EncryptFinal failed.\n");
112         return CKR_FUNCTION_FAILED;
113     }
114 
115     *outbuflen = (*outbuflen) + tmplen;
116     EVP_CIPHER_CTX_cleanup(&ctx);
117 #endif
118 
119     return CKR_OK;
120 }
121 
decrypt_aes(CK_BYTE * inbuf,int inbuflen,CK_BYTE * dkey,CK_BYTE * iv,CK_BYTE * outbuf,int * outbuflen)122 CK_RV decrypt_aes(CK_BYTE * inbuf, int inbuflen, CK_BYTE * dkey,
123                   CK_BYTE * iv, CK_BYTE * outbuf, int *outbuflen)
124 {
125     int size;
126     const EVP_CIPHER *cipher = EVP_aes_256_cbc();
127 
128 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
129     EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
130 
131     EVP_DecryptInit_ex(ctx, cipher, NULL, dkey, iv);
132     if (!EVP_DecryptUpdate(ctx, outbuf, outbuflen, inbuf, inbuflen)) {
133         TRACE_ERROR("EVP_DecryptUpdate failed.\n");
134         return CKR_FUNCTION_FAILED;
135     }
136     if (!EVP_DecryptFinal_ex(ctx, outbuf + (*outbuflen), &size)) {
137         TRACE_ERROR("EVP_DecryptFinal failed.\n");
138         return CKR_FUNCTION_FAILED;
139     }
140 
141     /* total length of the decrypted data */
142     *outbuflen = (*outbuflen) + size;
143 
144     /* EVP_DecryptFinal removes any padding. The final length
145      * is the length of the decrypted data without padding.
146      */
147 
148     EVP_CIPHER_CTX_free(ctx);
149 
150 #else
151     EVP_CIPHER_CTX ctx;
152     EVP_CIPHER_CTX_init(&ctx);
153 
154     EVP_DecryptInit_ex(&ctx, cipher, NULL, dkey, iv);
155     if (!EVP_DecryptUpdate(&ctx, outbuf, outbuflen, inbuf, inbuflen)) {
156         TRACE_ERROR("EVP_DecryptUpdate failed.\n");
157         return CKR_FUNCTION_FAILED;
158     }
159     if (!EVP_DecryptFinal_ex(&ctx, outbuf + (*outbuflen), &size)) {
160         TRACE_ERROR("EVP_DecryptFinal failed.\n");
161         return CKR_FUNCTION_FAILED;
162     }
163 
164     /* total length of the decrypted data */
165     *outbuflen = (*outbuflen) + size;
166 
167     /* EVP_DecryptFinal removes any padding. The final length
168      * is the length of the decrypted data without padding.
169      */
170 
171     EVP_CIPHER_CTX_cleanup(&ctx);
172 #endif
173 
174     return CKR_OK;
175 }
176 
get_masterkey(CK_BYTE * pin,CK_ULONG pinlen,const char * fname,CK_BYTE * masterkey,int * len)177 CK_RV get_masterkey(CK_BYTE *pin, CK_ULONG pinlen, const char *fname,
178                     CK_BYTE *masterkey, int *len)
179 {
180     struct stat statbuf;
181     FILE *fp;
182     CK_ULONG_32 totallen, datasize, readsize;
183     int dkeysize;
184     CK_BYTE salt[SALTSIZE];
185     CK_BYTE dkey[AES_KEY_SIZE_256];
186     CK_BYTE outbuf[ENCRYPT_SIZE];
187     CK_RV rc = CKR_OK;
188     size_t ret;
189 
190     /* see if the file exists */
191     if ((stat(fname, &statbuf) < 0) && (errno == ENOENT)) {
192         TRACE_ERROR("stat() failed: File does not exist.\n");
193         return CKR_FUNCTION_FAILED;
194     }
195 
196     /* open the file */
197     fp = fopen(fname, "r");
198     if (fp == NULL) {
199         TRACE_ERROR("fopen failed\n");
200         return CKR_FUNCTION_FAILED;
201     }
202 
203     ret = fread(&totallen, sizeof(CK_ULONG_32), 1, fp);
204     if (ret != 1) {
205         fclose(fp);
206         TRACE_ERROR("fread failed.\n");
207         return CKR_FUNCTION_FAILED;
208     }
209 
210     ret = fread(salt, SALTSIZE, 1, fp);
211     if (ret != 1) {
212         fclose(fp);
213         TRACE_ERROR("fread failed.\n");
214         return CKR_FUNCTION_FAILED;
215     }
216 
217     /* get length of encryted data */
218     datasize = totallen - SALTSIZE;
219     readsize = fread(outbuf, datasize, 1, fp);
220     if (readsize != 1) {
221         TRACE_ERROR("Could not get encrypted data in %s.\n", fname);
222         fclose(fp);
223         return CKR_FUNCTION_FAILED;
224     }
225 
226     fclose(fp);
227 
228     /* now derive the key using the salt and PIN */
229     dkeysize = AES_KEY_SIZE_256;
230     rc = pbkdf(pin, pinlen, salt, dkey, dkeysize);
231     if (rc != CKR_OK) {
232         TRACE_DEBUG("pbkdf(): Failed to derive a key.\n");
233         return CKR_FUNCTION_FAILED;
234     }
235 
236     /* decrypt the masterkey */
237     /* re-use salt for iv */
238     rc = decrypt_aes(outbuf, datasize, dkey, salt, masterkey, len);
239     if (rc != CKR_OK) {
240         TRACE_DEBUG("Failed to decrypt the racf pwd.\n");
241         return CKR_FUNCTION_FAILED;
242     }
243 
244     /* make sure len is equal to our masterkey size. */
245     if (*len != AES_KEY_SIZE_256) {
246         TRACE_ERROR("Decrypted key is invalid.\n");
247         return CKR_FUNCTION_FAILED;
248     }
249 
250     return rc;
251 }
252 
get_racf(CK_BYTE * masterkey,CK_ULONG mklen,CK_BYTE * racfpwd,int * racflen)253 CK_RV get_racf(CK_BYTE * masterkey, CK_ULONG mklen, CK_BYTE * racfpwd,
254                int *racflen)
255 {
256     struct stat statbuf;
257     CK_BYTE outbuf[ENCRYPT_SIZE];
258     CK_BYTE iv[AES_INIT_VECTOR_SIZE];
259     int len, datasize, readsize;
260     FILE *fp;
261     CK_RV rc;
262 
263     UNUSED(mklen);
264 
265     /* see if the file exists ... */
266     if ((stat(RACFFILE, &statbuf) < 0) && (errno == ENOENT)) {
267         TRACE_ERROR("File does not exist.\n");
268         return CKR_FUNCTION_FAILED;
269     }
270 
271     /* if file exists, open it */
272     fp = fopen(RACFFILE, "r");
273     if (fp == NULL) {
274         TRACE_ERROR("fopen failed\n");
275         return CKR_FUNCTION_FAILED;
276     }
277 
278     readsize = fread(&len, sizeof(CK_ULONG_32), 1, fp);
279     if (readsize != 1) {
280         TRACE_ERROR("fread failed\n");
281         fclose(fp);
282         return CKR_FUNCTION_FAILED;
283     }
284 
285     readsize = fread(iv, AES_INIT_VECTOR_SIZE, 1, fp);
286     if (readsize != 1) {
287         TRACE_ERROR("fread failed\n");
288         fclose(fp);
289         return CKR_FUNCTION_FAILED;
290     }
291 
292     /* get length of encryted data */
293     datasize = len - AES_INIT_VECTOR_SIZE;
294     readsize = fread(outbuf, datasize, 1, fp);
295     if (readsize != 1) {
296         TRACE_ERROR("Could not get encrypted data in %s.\n", RACFFILE);
297         fclose(fp);
298         return CKR_FUNCTION_FAILED;
299     }
300     fclose(fp);
301 
302     /* decrypt the data using the masterkey */
303     rc = decrypt_aes(outbuf, datasize, masterkey, iv, racfpwd, racflen);
304 
305     /* terminate the decrypted string. */
306     memset(racfpwd + (*racflen), 0, 1);
307 
308     if (rc != CKR_OK) {
309         TRACE_DEBUG("Failed to decrypt the racf pwd.\n");
310         return CKR_FUNCTION_FAILED;
311     }
312 
313     return CKR_OK;
314 }
315 
pbkdf(CK_BYTE * password,CK_ULONG len,CK_BYTE * salt,CK_BYTE * dkey,CK_ULONG klen)316 CK_RV pbkdf(CK_BYTE * password, CK_ULONG len, CK_BYTE * salt, CK_BYTE * dkey,
317             CK_ULONG klen)
318 {
319 
320     unsigned char hash[SHA256_HASH_SIZE];
321     unsigned char hash_block[SHA256_HASH_SIZE];
322     unsigned char *result;
323     unsigned int r, num_of_blocks;
324     unsigned int count, hashlen;
325     CK_ULONG rc = CKR_OK;
326     unsigned int i, j;
327     int k;
328 
329     /* check inputs */
330     if (!password || !salt) {
331         TRACE_ERROR("Invalid function argument(s).\n");
332         return CKR_FUNCTION_FAILED;
333     }
334 
335     /* check length of key.. for now only 32 byte keys */
336     if (klen != DKEYLEN) {
337         TRACE_ERROR("Only support 32 byte keys.\n");
338         return CKR_FUNCTION_FAILED;
339     }
340 
341     /* SP 800-132 recommends a minimum iteration count of 1000.
342      * so lets try that for now...
343      */
344     count = 1000;
345 
346     hashlen = SHA256_HASH_SIZE;
347 
348     /* Calculate amount of blocks in klen.
349      * SP 800-132: len = [kLen / hLen] (rounded up).
350      *             r = kLen - (len - 1) * hLen;
351      */
352     if (klen < SHA256_HASH_SIZE) {
353         num_of_blocks = 1;
354         r = klen;
355     } else {
356         num_of_blocks = klen / SHA256_HASH_SIZE;
357         /* round up by adding another block if there is a modulus */
358         if ((klen % SHA256_HASH_SIZE) != 0)
359             num_of_blocks++;
360         r = klen - (num_of_blocks - 1) * SHA256_HASH_SIZE;
361     }
362 
363     /* SP 800-132: For i = 1 to len */
364     for (i = 1; i <= num_of_blocks; i++) {
365 
366         /* SP 800-132: Ti = 0; */
367         memset(hash_block, 0, SHA256_HASH_SIZE);
368 
369         /* SP 800-132: U0 = S || Int(i); */
370         memset(hash, 0, SHA256_HASH_SIZE);
371         memcpy(hash, salt, SALTSIZE);
372         hash[SALTSIZE] = i;
373         hashlen = SALTSIZE + 1;
374 
375         /* SP 800-132: For j = 1 to C */
376         for (j = 1; j <= count; j++) {
377             /* SP 800-132: Uj = HMAC(P, U(j-1)); */
378             result =
379                 HMAC(EVP_sha256(), password, len, hash, hashlen, NULL, NULL);
380             if (result == NULL) {
381                 TRACE_ERROR("Failed to compute the hmac.\n");
382                 rc = CKR_FUNCTION_FAILED;
383                 goto out;
384             }
385 
386             /* SP 800-132: Ti = Ti Exclusive_OR Uj; */
387             for (k = 0; k < SHA256_HASH_SIZE; k++)
388                 hash_block[k] ^= hash[k];
389 
390             /* prep U(j-1) for next iteration */
391             memcpy(hash, result, SHA256_HASH_SIZE);
392             hashlen = SHA256_HASH_SIZE;
393         }
394 
395         /* SP 800-132: derived_key =
396          *   hash_block(1)||hash_block(2)||hash_block(num_of_blocks)<0...r-1>
397          * This means num_of_blocks are needed to concatencate
398          * together to make the derived key.
399          * However, if the derived key length is not a multiple of the
400          * HASH_SIZE, then we only need some of the data in the last hash_block.
401          * So, if there is an r, then only copy r bytes from last hash_block
402          * to the derived_key.
403          */
404         if ((i == num_of_blocks) && (r != 0))
405             memcpy(dkey, hash_block, r);
406         else
407             memcpy(dkey, hash_block, SHA256_HASH_SIZE);
408 
409     }
410 
411 out:
412     return rc;
413 }
414 
secure_racf(CK_BYTE * racf,CK_ULONG racflen,CK_BYTE * key,CK_ULONG keylen)415 CK_RV secure_racf(CK_BYTE * racf, CK_ULONG racflen, CK_BYTE * key,
416                   CK_ULONG keylen)
417 {
418     CK_RV rc = CKR_OK;
419     CK_BYTE iv[AES_INIT_VECTOR_SIZE];
420     FILE *fp;
421     CK_BYTE output[ENCRYPT_SIZE];
422     CK_ULONG_32 totallen;
423     int outputlen;
424 
425     UNUSED(keylen);
426 
427     /* generate an iv... */
428     if ((get_randombytes(iv, AES_INIT_VECTOR_SIZE)) != CKR_OK) {
429         TRACE_DEBUG("Could not generate an iv.\n");
430         return CKR_FUNCTION_FAILED;
431     }
432 
433     /* encrypt the racf passwd using the masterkey */
434     rc = encrypt_aes(racf, racflen, key, iv, output, &outputlen);
435     if (rc != 0) {
436         TRACE_DEBUG("Failed to encrypt racf pwd.\n");
437         return CKR_FUNCTION_FAILED;
438     }
439 
440     /* store the following in the RACF file:
441      * 1. total length = v + encrypted data
442      * 2. iv
443      * 3. encrypted data
444      */
445 
446     /* get the total length */
447     totallen = outputlen + AES_INIT_VECTOR_SIZE;
448 
449     fp = fopen(RACFFILE, "w");
450     if (!fp) {
451         TRACE_ERROR("fopen failed: %s\n", strerror(errno));
452         return CKR_FUNCTION_FAILED;
453     }
454 
455     /* set permisions on the file */
456     rc = set_perms(fileno(fp));
457     if (rc != 0) {
458         TRACE_ERROR("Failed to set permissions on RACF file.\n");
459         fclose(fp);
460         return CKR_FUNCTION_FAILED;
461     }
462 
463     /* write the info to the file */
464     (void) fwrite(&totallen, sizeof(CK_ULONG_32), 1, fp);
465     (void) fwrite(iv, AES_INIT_VECTOR_SIZE, 1, fp);
466     (void) fwrite(output, outputlen, 1, fp);
467 
468     fclose(fp);
469 
470     return rc;
471 }
472 
secure_masterkey(CK_BYTE * masterkey,CK_ULONG len,CK_BYTE * pin,CK_ULONG pinlen,const char * fname)473 CK_RV secure_masterkey(CK_BYTE * masterkey, CK_ULONG len, CK_BYTE * pin,
474                        CK_ULONG pinlen, const char *fname)
475 {
476     CK_RV rc = CKR_OK;
477     CK_BYTE salt[SALTSIZE];
478     CK_BYTE dkey[AES_KEY_SIZE_256];
479     CK_ULONG_32 totallen, dkey_size;
480     int outputlen;
481     CK_BYTE output[ENCRYPT_SIZE];
482     FILE *fp;
483 
484     memset(salt, 0, SALTSIZE);
485     memset(dkey, 0, AES_KEY_SIZE_256);
486     dkey_size = AES_KEY_SIZE_256;
487 
488     /* get a salt for the password based key derivation function. */
489     if ((get_randombytes(salt, SALTSIZE)) != CKR_OK) {
490         TRACE_DEBUG("Could not get a salt for pbkdf.\n");
491         return CKR_FUNCTION_FAILED;
492     }
493 
494     /* get a 32 byte key */
495     rc = pbkdf(pin, pinlen, salt, dkey, dkey_size);
496     if (rc != 0) {
497         TRACE_DEBUG("Failed to derive a key for encryption.\n");
498         return CKR_FUNCTION_FAILED;
499     }
500 
501     /* encrypt the masterkey using the derived key */
502     /* re-use the salt for the iv... */
503     rc = encrypt_aes(masterkey, len, dkey, salt, output, &outputlen);
504     if (rc != 0) {
505         TRACE_DEBUG("Failed to encrypt masterkey.\n");
506         return CKR_FUNCTION_FAILED;
507     }
508 
509     /* write the encrypted masterkey to named file */
510     /* store the following:
511      * 1. total length = salt + encrypted data
512      * 2. salt (always SALTSIZE)
513      * 3. encrypted data
514      */
515 
516     /* get the total length */
517     totallen = outputlen + SALTSIZE;
518 
519     fp = fopen(fname, "w");
520     if (!fp) {
521         TRACE_ERROR("fopen failed: %s\n", strerror(errno));
522         return CKR_FUNCTION_FAILED;
523     }
524 
525     /* set permisions on the file */
526     rc = set_perms(fileno(fp));
527     if (rc != 0) {
528         TRACE_ERROR("Failed to set permissions on encrypted file.\n");
529         fclose(fp);
530         return CKR_FUNCTION_FAILED;
531     }
532 
533     /* write the info to the file */
534     (void) fwrite(&totallen, sizeof(CK_ULONG_32), 1, fp);
535     (void) fwrite(salt, SALTSIZE, 1, fp);
536     (void) fwrite(output, outputlen, 1, fp);
537 
538     fclose(fp);
539 
540     return rc;
541 }
542