1 /*
2  * This file is a work of a US government employee and as such is in the Public domain.
3  * Simson L. Garfinkel, March 12, 2012
4  */
5 
6 
7 #include "affconfig.h"
8 #include "afflib.h"
9 #include "afflib_i.h"
10 #include "utils.h"
11 
12 #ifdef HAVE_OPENSSL_PEM_H
13 #include <openssl/pem.h>
14 #include <openssl/bio.h>
15 #endif
16 
17 #ifdef HAVE_STL
18 #include <vector>
19 #include <set>
20 #include <string>
21 using namespace std;
22 #endif
23 
24 #ifdef HAVE_CSTRING
25 #include <cstring>
26 #endif
27 
28 /* Support OpenSSL before 1.1.0 */
29 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
30 #define EVP_MD_CTX_new EVP_MD_CTX_create
31 #define EVP_MD_CTX_free EVP_MD_CTX_destroy
32 #endif
33 
34 
35 /****************************************************************
36  *** LOW LEVEL ROUTINES
37  ****************************************************************/
38 
39 /**
40  * Returns TRUE if the segment named 'buf' has the suffixi indicating
41  * that it is an encrypted segment.
42  */
af_is_encrypted_segment(const char * segname)43 int af_is_encrypted_segment(const char *segname){
44     if(strcmp(segname,AF_AFFKEY)==0) return 1;
45     if(aff::ends_with(segname,AF_AES256_SUFFIX)) return 1;
46     if(strncmp(segname,AF_AFFKEY_EVP,strlen(AF_AFFKEY_EVP)-1)==0) return 1;
47     return 0;
48 }
49 
50 /**
51  * Returns TRUE if the segment named 'buf' has the suffix indicating
52  * that it is a signature segment.
53  *
54  * @param segname - segment to check
55  */
af_is_signature_segment(const char * segname)56 int af_is_signature_segment(const char *segname){
57     int num = 0;
58     char cc;
59     if(aff::ends_with(segname,AF_SIG256_SUFFIX)) return 1;
60     if(sscanf(segname,"affbom%d%c",&num,&cc)==1) return 1; // it's a bom segment
61     return 0;
62 }
63 
64 
65 /****************************************************************
66  *** AES ENCRYPTION LAYER
67  ****************************************************************/
68 
69 static const char *aff_cannot_sign = "AFFLIB: OpenSSL does not have SHA256! "\
70     "AFF segments cannot be signed. "\
71     "See http://www.afflib.org/requirements.php for additional information.";
72 
af_crypto_allocate(AFFILE * af)73 void af_crypto_allocate(AFFILE *af)
74 {
75     af->crypto = (struct af_crypto *)calloc(sizeof(struct af_crypto),1); // give space
76 }
77 
78 
79 /** compute SHA256.
80  * Return 0 if success, -1 if error.
81  */
af_SHA256(const unsigned char * data,size_t datalen,unsigned char md[32])82 int af_SHA256(const unsigned char *data,size_t datalen,unsigned char md[32])
83 {
84     const EVP_MD *sha256 = EVP_get_digestbyname("SHA256");
85     if(!sha256) return -1;
86 
87     uint32_t sha256_buflen = 32;
88     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
89     EVP_DigestInit(ctx,sha256);
90     EVP_DigestUpdate(ctx,data,datalen);
91     if(EVP_DigestFinal(ctx,md,&sha256_buflen)!=1){ // EVP_DigestFinal returns 1 for success
92 	EVP_MD_CTX_free(ctx);
93 	return -1;
94     }
95     EVP_MD_CTX_free(ctx);
96     return 0;
97 }
98 
af_crypto_deallocate(AFFILE * af)99 void af_crypto_deallocate(AFFILE *af)
100 {
101 #ifdef AES_BLOCK_SIZE
102     memset(&af->crypto->ekey,0,sizeof(af->crypto->ekey));
103     memset(&af->crypto->dkey,0,sizeof(af->crypto->dkey));
104 #endif
105 #ifdef HAVE_PEM_READ_BIO_RSA_PUBKEY
106     if(af->crypto->sign_privkey){
107 	EVP_PKEY_free(af->crypto->sign_privkey);
108 	af->crypto->sign_privkey = 0;
109     }
110     if(af->crypto->sign_pubkey){
111 	EVP_PKEY_free(af->crypto->sign_pubkey);
112 	af->crypto->sign_pubkey = 0;
113     }
114     if(af->crypto->sign_cert){
115 	X509_free(af->crypto->sign_cert);
116 	af->crypto->sign_cert = 0;
117     }
118 #endif
119     free(af->crypto);
120     af->crypto = 0;
121 }
122 
123 
af_set_aes_key(AFFILE * af,const unsigned char * userKey,const int bits)124 int af_set_aes_key(AFFILE *af,const unsigned char *userKey,const int bits)
125 {
126 #ifdef HAVE_AES_ENCRYPT
127     if(af->crypto->sealing_key_set){
128 	if(userKey==0){			// key was set and it is being cleared
129 	    af->crypto->sealing_key_set = 0;
130 	    return 0;
131 	}
132 	return AF_ERROR_KEY_SET;		// key is already set
133     }
134     int r;
135     r = AES_set_encrypt_key(userKey,bits,&af->crypto->ekey);
136     if(r) return r;
137 
138     r = AES_set_decrypt_key(userKey,bits,&af->crypto->dkey);
139     if(r) return r;
140 
141     af->crypto->sealing_key_set = 1;
142     af->crypto->auto_encrypt = 1;	// default
143     af->crypto->auto_decrypt = 1;	// default
144     af_invalidate_vni_cache(af);	// invalidate the cache, because now we can read encrypted values
145     return 0;
146 #else
147     return AF_ERROR_NO_AES;
148 #endif
149 }
150 
151 
152 
153 /**
154  * Take an unencrypted AFFKEY, encrypt it with the SHA256 of the passphrase,
155  * and save it in the appropriate segment.
156  */
157 
af_save_aes_key_with_passphrase(AFFILE * af,const char * passphrase,const u_char affkey[32])158 int af_save_aes_key_with_passphrase(AFFILE *af,const char *passphrase, const u_char affkey[32])
159 {
160 #if defined(HAVE_AES_ENCRYPT)
161     if(af->crypto->sealing_key_set) return AF_ERROR_KEY_SET;		// already enabled
162 
163     /* Make an encrypted copy of the AFFkey */
164     unsigned char passphrase_hash[32];
165     af_SHA256((const unsigned char *)passphrase, strlen(passphrase), passphrase_hash);
166 
167     struct affkey affkey_seg;
168     assert(sizeof(affkey_seg)==AFFKEY_SIZE);
169     memset((unsigned char *)&affkey_seg,0,sizeof(affkey_seg));
170 
171     uint32_t version_number = htonl(1);	// version 1
172     memcpy(affkey_seg.version,(u_char *)&version_number,4);
173     memcpy(affkey_seg.affkey_aes256,affkey,32);
174 
175     /* Use the hash to encrypt the key and all zeros */
176     AES_KEY ekey;
177     AES_set_encrypt_key(passphrase_hash,256,&ekey);
178     AES_encrypt(affkey_seg.affkey_aes256,
179 		affkey_seg.affkey_aes256,&ekey);
180     AES_encrypt(affkey_seg.affkey_aes256+AES_BLOCK_SIZE,
181 		affkey_seg.affkey_aes256+AES_BLOCK_SIZE,&ekey);
182     AES_encrypt(affkey_seg.zeros_aes256,affkey_seg.zeros_aes256,&ekey);
183 
184     /* Write this to a segment */
185     if(af_update_seg(af,AF_AFFKEY,0,(const u_char *)&affkey_seg,sizeof(affkey_seg))) return -1;
186     memset((unsigned char *)&affkey_seg,0,sizeof(affkey_seg)); // erase the temp data
187     return 0;
188 #endif
189 #if !defined(HAVE_AES_ENCRYPT)
190     return AF_ERROR_NO_AES;
191 #endif
192 }
193 
194 /** MacOS 10.5 with GCC 4.0.1 packed affkey at 52 bytes.
195  ** Linux GCC 4.1.2 packed affkey at 56 bytes. It should be 52 bytes
196  ** --- 4 bytes for the version number, 32 bytes for the affkey, 16 bytes for encryption of zeros.
197  ** original code specified the version as uint32_t version:32, for which the
198  ** compiler allocated 64 bits...
199  ** So this code needs to be willing to accept a 52-byte or 56-byte affkey.
200  **/
201 /* Legacy - this version of the structure was improperly used in AFFLIB prior to
202  * 3.1.6. Unfortunately, the structure didn't pack properly, resulting in some images
203  * in which the affkey structure was too large.
204  */
205 struct affkey_legacy {
206     uint32_t version:32;
207     u_char affkey_aes256[32]; // AFF key encrypted with SHA-256 of passphrase
208                               // encrypted as two codebooks in a row; no need for CBC
209     u_char zeros_aes256[16];  // all zeros encrypted with SHA-256 of passphrase
210 };
211 
af_get_aes_key_from_passphrase(AFFILE * af,const char * passphrase,unsigned char affkey[32])212 int  af_get_aes_key_from_passphrase(AFFILE *af,const char *passphrase,
213 					   unsigned char affkey[32])
214 {
215 #if defined(HAVE_AES_ENCRYPT)
216     if(af->crypto->sealing_key_set) return AF_ERROR_KEY_SET;		// already enabled
217 
218     /* Get the segment with the key in it. It should be AFFKEY_SIZE
219      * but there are a few images out there with the wrong key size due
220      * to a compiler packing bug. Automatically handle those.
221      */
222     struct affkey affkey_seg;		// in-memory copy
223     u_char kbuf[1024];
224     size_t klen=sizeof(kbuf);
225     uint32_t version;
226     int kversion=0;
227 
228     /* Try to get the segment */
229     if(af_get_seg(af,AF_AFFKEY,0,kbuf,&klen)) return AF_ERROR_AFFKEY_NOT_EXIST;
230 
231     if(sizeof(affkey_seg)==klen){
232 	// On-disk structure is correct; copy it over
233 	memcpy(&affkey_seg,kbuf,klen);
234 	memcpy((char *)&version,affkey_seg.version,4);
235 	kversion = ntohl(version);
236     } else {
237 	// Try to figure it out manually
238 	memcpy((char *)&version,kbuf,4);
239 	kversion = ntohl(version);
240 	memcpy(affkey_seg.affkey_aes256,kbuf+4,sizeof(affkey_seg.affkey_aes256));
241 	memcpy(affkey_seg.zeros_aes256,kbuf+36,sizeof(affkey_seg.zeros_aes256));
242     }
243 
244     /* make sure version is correct */
245     if(kversion != 1){
246 	errno = EINVAL;
247 	return AF_ERROR_AFFKEY_WRONG_VERSION;
248     }
249 
250     /* hash the passphrase */
251     unsigned char passphrase_hash[32];
252     if(af_SHA256((const unsigned char *)passphrase,strlen(passphrase), passphrase_hash)){
253 	return AF_ERROR_NO_SHA256;
254     }
255 
256     /* Try to decrypt the key */
257 
258     AES_KEY dkey;
259     AES_set_decrypt_key(passphrase_hash,256,&dkey);
260     AES_decrypt(affkey_seg.affkey_aes256,
261 		affkey_seg.affkey_aes256,&dkey);
262     AES_decrypt(affkey_seg.affkey_aes256+AES_BLOCK_SIZE,
263 		affkey_seg.affkey_aes256+AES_BLOCK_SIZE,&dkey);
264     AES_decrypt(affkey_seg.zeros_aes256,affkey_seg.zeros_aes256,&dkey);
265 
266     /* See if its zero? */
267     for(u_int i=0;i<sizeof(affkey_seg.zeros_aes256);i++){
268 	if(affkey_seg.zeros_aes256[i]) return AF_ERROR_WRONG_PASSPHRASE;
269     }
270 
271 
272     memcpy(affkey,affkey_seg.affkey_aes256,32);    /* copy out the result */
273     memset((unsigned char *)&affkey_seg,0,sizeof(affkey_seg)); // erase the temp data
274     return 0;
275 #endif
276 #if !defined(HAVE_AES_ENCRYPT)
277     return AF_ERROR_NO_AES;
278 #endif
279 }
280 
281 /**
282  * make a random affkey and encrypt it with passphrase.
283  */
af_establish_aes_passphrase(AFFILE * af,const char * passphrase)284 int  af_establish_aes_passphrase(AFFILE *af,const char *passphrase)
285 {
286 #ifdef HAVE_AES_ENCRYPT
287     if(af->crypto->sealing_key_set) return AF_ERROR_KEY_SET;		// already enabled
288 
289     /* Can only establish a passphrase if the encryption segment doesn't exist */
290     if(af_get_seg(af,AF_AFFKEY,0,0,0)==0) return AF_ERROR_AFFKEY_EXISTS;
291 
292     /* Check to make sure it wasn't public key encrypted */
293     char segname[AF_MAX_NAME_LEN];
294     snprintf(segname,sizeof(segname),AF_AFFKEY_EVP,0);
295     if(af_get_seg(af,segname,0,0,0)==0) return AF_ERROR_AFFKEY_EXISTS;
296 
297     /* Okay; make a random key and encrypt it with the passphrase */
298     unsigned char affkey[32];
299     int r = RAND_bytes(affkey,sizeof(affkey)); // makes a random key; with REAL random bytes
300     if(r!=1) return AF_ERROR_RNG_FAIL; // pretty bad...
301 
302     /* I have the key, now save it */
303     r = af_save_aes_key_with_passphrase(af,passphrase,affkey);
304     memset(affkey,0,sizeof(affkey)); /* Erase the encryption key in memory */
305     return r;
306 #else
307     return AF_ERROR_NO_AES;
308 #endif
309 }
310 
311 
312 /** Like the one above, this public interface actually wipes the key after it is created.
313  * @param passphrase - Passphrae, use NULL to erase the encryption key.
314  *                     This can only be done if the file is opened read-only.
315  */
af_use_aes_passphrase(AFFILE * af,const char * passphrase)316 int  af_use_aes_passphrase(AFFILE *af,const char *passphrase)
317 {
318     af_invalidate_vni_cache(af);
319     if(passphrase==0 && !(af->openflags & O_RDWR)){
320 	af->crypto->sealing_key_set = 0;
321 	return 0;
322     }
323 
324     if(af->crypto->sealing_key_set) return AF_ERROR_KEY_SET;		// already enabled
325 
326     unsigned char affkey[32];
327     int r = af_get_aes_key_from_passphrase(af,passphrase,affkey);
328     if(r) return r;			  // wrong keyphrase
329     r = af_set_aes_key(af,affkey,256);    /* Set the encryption key */
330     memset(affkey,0,sizeof(affkey)); /* Erase the encryption key in memory */
331     return r;
332 }
333 
334 
335 /* gets the key with the old phrase and then changes it to the new one */
af_change_aes_passphrase(AFFILE * af,const char * oldphrase,const char * newphrase)336 int  af_change_aes_passphrase(AFFILE *af,const char *oldphrase,const char *newphrase)
337 {
338     if(af->crypto->sealing_key_set) return AF_ERROR_KEY_SET;		// already enabled
339 
340     unsigned char affkey[32];
341     int r = af_get_aes_key_from_passphrase(af,oldphrase,affkey);
342 
343     if(r) return r;
344     r = af_save_aes_key_with_passphrase(af,newphrase,affkey);
345     memset(affkey,0,sizeof(affkey));	// erase the temp data
346     return r;
347 }
348 
349 
af_has_encrypted_segments(AFFILE * af)350 int af_has_encrypted_segments(AFFILE *af)
351 {
352     struct af_vnode_info vni;
353     af_vstat(af,&vni);
354     return vni.segment_count_encrypted>0;
355 }
356 
357 /**
358  * Returns true if there are segments that cannot be decrypted
359  * (other than key segments)
360  */
af_cannot_decrypt(AFFILE * af)361 int af_cannot_decrypt(AFFILE *af){
362     if(af_has_encrypted_segments(af)==0) return 0; // no encrypted segments to decrypt
363     /* Now start at the beginning and see if any segments are read which are encrypted.
364      * If they are encrypted, then we don't have the encryption key.
365      */
366     if(af_rewind_seg(af)) return -1;
367     char segname[AF_MAX_NAME_LEN];
368     memset(segname,0,sizeof(segname));
369     while(af_get_next_seg(af,segname,sizeof(segname),0,0,0)==0){
370 	if(aff::ends_with(segname,AF_AES256_SUFFIX)) return 1; // we shouldn't see these.
371     }
372     return 0;
373 }
374 
375 /****************************************************************
376  ***
377  *** Signature Routines
378  ***
379  ****************************************************************/
380 
381 /** See if the public key and private key match by dial a trial encryption and decryption.
382  *
383  * @param pubkey
384  * @param privkey
385  * @returns 0 if successful, -1 if failure.
386  */
check_keys(EVP_PKEY * privkey,EVP_PKEY * pubkey)387 static int check_keys(EVP_PKEY *privkey,EVP_PKEY *pubkey)
388 {
389     char ptext[16];			/* plaintext of a 128-bit message */
390     unsigned char sig[1024];		/* signature; bigger than needed */
391     uint32_t siglen = sizeof(sig);	/* length of signature */
392 
393     const EVP_MD *sha256 = EVP_get_digestbyname("SHA256");
394     if(!sha256) return -1;		// no SHA256.
395 
396     EVP_MD_CTX *md = EVP_MD_CTX_new();	/* EVP message digest */
397 
398     /* make the plaintext message */
399     memset(ptext,0,sizeof(ptext));
400     strcpy(ptext,"Test Message");
401     EVP_SignInit(md,sha256);
402     EVP_SignUpdate(md,ptext,sizeof(ptext));
403     EVP_SignFinal(md,sig,&siglen,privkey);
404 
405     /* Verify the message */
406     EVP_VerifyInit(md,sha256);
407     EVP_VerifyUpdate(md,ptext,sizeof(ptext));
408     if(EVP_VerifyFinal(md,sig,siglen,pubkey)!=1){
409 	EVP_MD_CTX_free(md);
410 	return -3;
411     }
412     EVP_MD_CTX_free(md);
413     return 0;
414 }
415 
416 
417 /**
418  * af_set_sign_files:
419  *
420  * Load the private key & certificate, make sure they are matched, and
421  * write to the AFF.  This requirest not just AES256, but EVP_SHA256
422  * because we use the openSSL signature functions.
423  *
424  * @param af - The open AFFILE
425  * @param keyfile - The filename of the key file to read
426  * @param certfile - The filename of the certificate file to read
427  */
428 
429 
af_set_sign_files(AFFILE * af,const char * keyfile,const char * certfile)430 int  af_set_sign_files(AFFILE *af,const char *keyfile,const char *certfile)
431 {
432     const EVP_MD *sha256 = EVP_get_digestbyname("SHA256");
433     if(!sha256){
434 	(*af->error_reporter)(aff_cannot_sign);
435 	return AF_ERROR_NO_SHA256;			//
436     }
437 
438     BIO *bp = BIO_new_file(keyfile,"r");
439     if(!bp) return -1;
440     af->crypto->sign_privkey = PEM_read_bio_PrivateKey(bp,0,0,NULL);
441     BIO_free(bp);
442     if(!af->crypto->sign_privkey) return -2;	// can't decode keyfile
443 
444     bp = BIO_new_file(certfile,"r");
445     if(!bp) return -1;
446     PEM_read_bio_X509(bp,&af->crypto->sign_cert,0,0);
447     if(af->crypto->sign_cert==0){
448 	EVP_PKEY_free(af->crypto->sign_privkey);
449 	af->crypto->sign_privkey = 0;
450 	return -3;
451     }
452     af->crypto->sign_pubkey = X509_get_pubkey(af->crypto->sign_cert);
453     BIO_free(bp);
454 
455     if(check_keys(af->crypto->sign_privkey,af->crypto->sign_pubkey)){
456 	/* private key doesn't match certificate */
457 	EVP_PKEY_free(af->crypto->sign_privkey); af->crypto->sign_privkey = 0;
458 	EVP_PKEY_free(af->crypto->sign_pubkey);  af->crypto->sign_pubkey = 0;
459 	return -4;
460     }
461 
462     /* Looks good; save the cert in a segment */
463     BIO *xbp = BIO_new(BIO_s_mem());	// where we are writing
464     PEM_write_bio_X509(xbp,af->crypto->sign_cert);
465     af_update_seg_frombio(af,AF_SIGN256_CERT,0,xbp);
466     BIO_free(xbp);
467     return 0;
468 }
469 
470 /* Sign the segment with the signing key.  Signatures are calculated
471  * by taking the SHA256 of the following concatenated together:
472  * segment name
473  * segment arg (in network byte order)
474  * segment data
475  */
af_sign_seg3(AFFILE * af,const char * segname,uint32_t arg,const unsigned char * data,uint32_t datalen,uint32_t signmode)476 int af_sign_seg3(AFFILE *af,const char *segname,
477 		 uint32_t arg,const unsigned char *data,uint32_t datalen,
478 		 uint32_t signmode)
479 {
480     const EVP_MD *sha256 = EVP_get_digestbyname("SHA256");
481     if(!sha256){
482 	(*af->error_reporter)(aff_cannot_sign);
483 	return AF_ERROR_NO_SHA256;			//
484     }
485 
486 
487     if(af->crypto->sign_privkey==0) return -1;		// can't sign; no signing key
488 
489     if(strlen(segname)+strlen(AF_SIG256_SUFFIX)+1 > AF_MAX_NAME_LEN) return -1;	// too long
490 
491     char signed_segname[AF_MAX_NAME_LEN];
492     strlcpy(signed_segname,segname,AF_MAX_NAME_LEN);
493     strlcat(signed_segname,AF_SIG256_SUFFIX,AF_MAX_NAME_LEN);
494 
495     if(signmode==AF_SIGNATURE_DELETE){
496 	af_del_seg(af,signed_segname);
497 	return 0;
498     }
499 
500     uint32_t arg_net = htonl(arg);
501     unsigned char sig[1024];		/* signature; bigger than needed */
502     uint32_t siglen = sizeof(sig);	/* length of signature */
503 
504     EVP_MD_CTX *md = EVP_MD_CTX_new();	/* EVP message digest */
505     EVP_SignInit(md,sha256);
506     EVP_SignUpdate(md,(const unsigned char *)segname,strlen(segname)+1);
507     EVP_SignUpdate(md,(const unsigned char *)&arg_net,sizeof(arg_net));
508     EVP_SignUpdate(md,data,datalen);
509     EVP_SignFinal(md,sig,&siglen,af->crypto->sign_privkey);
510     EVP_MD_CTX_free(md);
511     return (*af->v->update_seg)(af,signed_segname,signmode,sig,siglen);
512 }
513 
514 
af_sign_seg(AFFILE * af,const char * segname)515 int af_sign_seg(AFFILE *af,const char *segname)
516 {
517     size_t datalen = 0;
518 
519     /* Now get the data to verify */
520     if(af_get_seg(af,segname,0,0,&datalen)){
521 	return AF_ERROR_SIG_DATAREAD_ERROR; // can't read the segment length
522     }
523 
524     /* Now read the segment */
525     unsigned char *data=(unsigned char *)malloc(datalen);
526     if(data==0) return AF_ERROR_SIG_MALLOC;
527 
528     uint32_t arg=0;
529     if(af_get_seg(af,segname,&arg,data,&datalen)){
530 	free(data);
531 	return AF_ERROR_SIG_DATAREAD_ERROR; // can't read the segment length
532     }
533 
534     /* Note: it woudl be wrong to detect pages and sign them in mode1, because we don't really
535      * have access to the uncompressed data...
536      */
537     int r = af_sign_seg3(af,segname,arg,data,datalen,AF_SIGNATURE_MODE0);
538     free(data);
539     return r;
540 }
541 
542 
543 #ifdef HAVE_STL
544 /** Returns number of segments that were signed.
545  * Returns -1 if there is an error.
546  */
af_sign_all_unsigned_segments(AFFILE * af)547 int af_sign_all_unsigned_segments(AFFILE *af)
548 {
549     vector<string> segs;
550     set<string>sigs;
551     char name[AF_MAX_NAME_LEN];
552     int count=0;
553 
554     /* Get a list of all the segments and all the signatures */
555     if(af_rewind_seg(af)) return -1;
556     while(af_get_next_seg(af,name,sizeof(name),0,0,0)==0){
557 	if(name[0]==0) continue;	// don't sign the empty segments
558 	if(aff::ends_with(name,AF_SIG256_SUFFIX)==0){
559 	    segs.push_back(name);
560 	}
561 	else{
562 	    sigs.insert(name);
563 	}
564     }
565     /* Sign the ones that are unsigned. */
566     for(vector<string>::const_iterator s = segs.begin();
567 	s != segs.end();
568 	s++){
569 	/* Compute name of the signature */
570 	string signame = *s + AF_SIG256_SUFFIX;
571 	if(sigs.find(signame) == sigs.end()){
572 	    if(af_sign_seg(af,s->c_str())){
573 		(*af->error_reporter)("AFFLIB: Could not sign segment '%s'",s->c_str());
574 		return -1;
575 	    }
576 	    count++;
577 	}
578     }
579     return count;
580 }
581 #endif
582 
583 /* Verify a segment against a particular signature and public key */
af_hash_verify_seg2(AFFILE * af,const char * segname,u_char * sigbuf_,size_t sigbuf_len_,int sigmode)584 int af_hash_verify_seg2(AFFILE *af,const char *segname,u_char *sigbuf_,size_t sigbuf_len_,int sigmode)
585 {
586     const EVP_MD *sha256 = EVP_get_digestbyname("SHA256");
587     if(!sha256){
588 	(*af->error_reporter)(aff_cannot_sign);
589 	return AF_ERROR_NO_SHA256;			//
590     }
591 
592     /* Now get the data to verify */
593     size_t seglen = 0;
594     unsigned char *segbuf = 0;
595     uint32_t arg=0;
596 
597     /* Do we need to get the page */
598     if(sigmode==AF_SIGNATURE_MODE1){
599 	int64_t pagenumber = af_segname_page_number(segname);
600 	if(pagenumber>=0){
601 	    seglen = af_page_size(af);
602 	    segbuf    = (unsigned char *)malloc(seglen);
603 	    if(segbuf==0) return AF_ERROR_SIG_MALLOC;
604 	    if(af_get_page(af,pagenumber,segbuf,&seglen)){
605 		free(segbuf);
606 		return -1;
607 	    }
608 	}
609     }
610     if(segbuf==0){			// get the raw segment
611 	if(af_get_seg(af,segname,0,0,&seglen)){
612 	    return AF_ERROR_SIG_DATAREAD_ERROR; // can't read the segment length
613 	}
614 
615 	/* Now read the segment */
616 	segbuf=(unsigned char *)malloc(seglen);
617 	if(segbuf==0) return AF_ERROR_SIG_MALLOC;
618 
619 	if(af_get_seg(af,segname,&arg,segbuf,&seglen)){
620 	    free(segbuf);
621 	    return AF_ERROR_SIG_DATAREAD_ERROR; // can't read the segment length
622 	}
623     }
624 
625     /* Verify the signature*/
626     uint8_t sigbuf[1024];
627     uint32_t sigbuf_len = sizeof(sigbuf);
628     uint32_t arg_net = htonl(arg);
629     EVP_MD_CTX *md = EVP_MD_CTX_new();	/* EVP message digest */
630     EVP_DigestInit(md,sha256);
631     EVP_DigestUpdate(md,(const unsigned char *)segname,strlen(segname)+1);
632     EVP_DigestUpdate(md,(const unsigned char *)&arg_net,sizeof(arg_net));
633     EVP_DigestUpdate(md,segbuf,seglen);
634     EVP_DigestFinal(md,sigbuf,&sigbuf_len);
635     EVP_MD_CTX_free(md);
636     int r = memcmp(sigbuf,sigbuf_,sigbuf_len);
637     if(sigbuf_len != sigbuf_len_) r = -1; // doesn't match
638     free(segbuf);
639 
640     if(r==0) return 0;			// verifies
641     return AF_ERROR_SIG_BAD;		// doesn't verify
642 }
643 
644 /* Verify a segment against a particular signature and public key */
af_sig_verify_seg2(AFFILE * af,const char * segname,EVP_PKEY *,u_char * sigbuf,size_t sigbuf_len,int sigmode)645 int af_sig_verify_seg2(AFFILE *af,const char *segname,EVP_PKEY * /*pubkey*/,u_char *sigbuf,size_t sigbuf_len,int sigmode)
646 {
647     const EVP_MD *sha256 = EVP_get_digestbyname("SHA256");
648     if(!sha256){
649 	(*af->error_reporter)(aff_cannot_sign);
650 	return AF_ERROR_NO_SHA256;			//
651     }
652 
653 
654     /* Now get the data to verify */
655     size_t seglen = 0;
656     unsigned char *segbuf = 0;
657     uint32_t arg=0;
658 
659     /* Do we need to get the page */
660     if(sigmode==AF_SIGNATURE_MODE1){
661 	int64_t pagenumber = af_segname_page_number(segname);
662 	if(pagenumber>=0){
663 	    seglen = af_page_size(af);
664 	    segbuf    = (unsigned char *)malloc(seglen);
665 	    if(segbuf==0) return AF_ERROR_SIG_MALLOC;
666 	    if(af_get_page(af,pagenumber,segbuf,&seglen)){
667 		free(segbuf);
668 		return -1;
669 	    }
670 	}
671     }
672     if(segbuf==0){			// get the raw segment
673 	if(af_get_seg(af,segname,0,0,&seglen)){
674 	    return AF_ERROR_SIG_DATAREAD_ERROR; // can't read the segment length
675 	}
676 
677 	/* Now read the segment */
678 	segbuf=(unsigned char *)malloc(seglen);
679 	if(segbuf==0) return AF_ERROR_SIG_MALLOC;
680 
681 	if(af_get_seg(af,segname,&arg,segbuf,&seglen)){
682 	    free(segbuf);
683 	    return AF_ERROR_SIG_DATAREAD_ERROR; // can't read the segment length
684 	}
685     }
686 
687     /* Verify the signature*/
688     uint32_t arg_net = htonl(arg);
689     EVP_MD_CTX *md = EVP_MD_CTX_new();	/* EVP message digest */
690     EVP_VerifyInit(md,sha256);
691     EVP_VerifyUpdate(md,(const unsigned char *)segname,strlen(segname)+1);
692     EVP_VerifyUpdate(md,(const unsigned char *)&arg_net,sizeof(arg_net));
693     EVP_VerifyUpdate(md,segbuf,seglen);
694     EVP_MD_CTX_free(md);
695     int r = EVP_VerifyFinal(md,sigbuf,sigbuf_len,af->crypto->sign_pubkey);
696     free(segbuf);
697 
698     if(r==1) return 0;			// verifies
699     return AF_ERROR_SIG_BAD;		// doesn't verify
700 }
701 
702 
703 
af_sig_verify_seg(AFFILE * af,const char * segname)704 int af_sig_verify_seg(AFFILE *af,const char *segname)
705 {
706 #ifdef USE_AFFSIGS
707     if(aff::ends_with(segname,AF_SIG256_SUFFIX)){
708 	return AF_ERROR_SIG_SIG_SEG; 			// don't verify the signature segments
709     }
710 
711     /* Need the public key if I don't have it */
712     if(af->crypto->sign_pubkey==0){
713 	unsigned char certbuf[65536];
714 	size_t certbuf_len = sizeof(certbuf);
715 	if(af_get_seg(af,AF_SIGN256_CERT,0,certbuf,&certbuf_len)!=0){
716 	    return AF_ERROR_SIG_NO_CERT;
717 	}
718 	af->crypto->sign_cert = 0;
719 	BIO *cert_bio = BIO_new_mem_buf(certbuf,certbuf_len);
720 	PEM_read_bio_X509(cert_bio,&af->crypto->sign_cert,0,0);
721 	BIO_free(cert_bio);
722 	af->crypto->sign_pubkey = X509_get_pubkey(af->crypto->sign_cert);
723     }
724 
725     /* Figure out the signature segment name */
726     char sigseg[AF_MAX_NAME_LEN + 1 + sizeof(AF_SIG256_SUFFIX)];
727     strlcpy(sigseg,segname,sizeof(sigseg));
728     strlcat(sigseg,AF_SIG256_SUFFIX,sizeof(sigseg));
729 
730     /* Get the signature (it says how we need to handle the data) */
731     unsigned char sigbuf[2048];		// big enough to hold any conceivable signature
732     size_t sigbuf_len=sizeof(sigbuf);
733     uint32_t sigmode=0;
734     if(af_get_seg(af,sigseg,&sigmode,sigbuf,&sigbuf_len)){
735 	return AF_ERROR_SIG_READ_ERROR;
736     }
737 
738     return af_sig_verify_seg2(af,segname,af->crypto->sign_pubkey,sigbuf,sigbuf_len,sigmode);
739 #else
740     return AF_ERROR_SIG_NOT_COMPILED;				// sig support not compiled in
741 #endif
742 }
743 
744 /****************************************************************
745  *** PUBLIC KEY ENCRYPION ROUTINES
746  ****************************************************************/
747 
748 /**
749  * af_set_seal_certfiles
750  *
751  * Specifies the certific file(s) to use for creating a new affkey.
752  * If an affkey is already on the disk, this returns with an error.
753  *
754  * @param af - The open AFFILE
755  * @param certfile - The filename of the certificate file to read
756  */
757 
af_set_seal_certificates(AFFILE * af,const char * certfiles[],int numcertfiles)758 int  af_set_seal_certificates(AFFILE *af,const char *certfiles[],int numcertfiles)
759 {
760     const EVP_MD *sha256 = EVP_get_digestbyname("SHA256");
761     if(!sha256){
762 	(*af->error_reporter)(aff_cannot_sign);
763 	return AF_ERROR_NO_SHA256;			//
764     }
765 
766     char evp0[AF_MAX_NAME_LEN];		// segment where we will store the encrypted session key
767     snprintf(evp0,sizeof(evp0),AF_AFFKEY_EVP,0);
768 
769     /* If an affkey has not been created, create one if there is a public key(s)...
770      * todo: this should probably see if there is ANY evp segment.
771      */
772     if(af_get_seg(af,evp0,0,0,0)==0) return -1; // make sure no encrypted EVP exists
773     if(af_get_seg(af,AF_AFFKEY,0,0,0)==0) return -1; // make sure no passphrase exists
774     if(certfiles==0 || numcertfiles==0) return -1;   // make sure the user supplied a certificate
775 
776     /* First make the affkey */
777     unsigned char affkey[32];
778     int r = RAND_bytes(affkey,sizeof(affkey));
779     if(r!=1) return AF_ERROR_RNG_FAIL; // pretty bad...
780 
781     af_seal_affkey_using_certificates(af, certfiles, numcertfiles, affkey);
782     return 0;
783 }
784 
785 /**
786  * af_seal_affkey_using_certificates
787  *
788  * Encrypt the provided affkey.
789  *
790  *
791  */
792 
af_seal_affkey_using_certificates(AFFILE * af,const char * certfiles[],int numcertfiles,unsigned char affkey[32])793 int  af_seal_affkey_using_certificates(AFFILE *af,const char *certfiles[],int numcertfiles, unsigned char affkey[32])
794 {
795     /* Repeat for each public key.. */
796     int r;
797     for(int i=0;i<numcertfiles;i++){
798 
799 	EVP_PKEY	*seal_pubkey=0;		// encrypting public key (for encrypting the affkey)
800 	X509	*seal_cert=0;		// encrypting certificate that was used...
801 
802 	BIO *bp = BIO_new_file(certfiles[i],"r");
803 	if(!bp) return -1;
804 	PEM_read_bio_X509(bp,&seal_cert,0,0);
805 	BIO_free(bp);
806 	if(seal_cert==0){
807 	    return -2;
808 	}
809 	seal_pubkey = X509_get_pubkey(seal_cert);
810 
811 	/* Create the next encrypted key. First make a copy of it... */
812 	unsigned char affkey_copy[32];
813 	memcpy(affkey_copy,affkey,32);
814 
815 	EVP_CIPHER_CTX *cipher_ctx = EVP_CIPHER_CTX_new();
816 
817 	/* IV */
818 	unsigned char iv[EVP_MAX_IV_LENGTH];
819 	r = RAND_bytes(iv, EVP_MAX_IV_LENGTH); /* make a random iv */
820 	if(r!=1) return AF_ERROR_RNG_FAIL; // pretty bad...
821 
822 	/* EK */
823 	unsigned char *ek=0;
824 	unsigned char *ek_array[1];
825 
826 	int ek_size = EVP_PKEY_size(seal_pubkey);
827 	ek = (unsigned char *)malloc(ek_size);
828 	ek_array[0] = ek;
829 
830 	/* Destination for encrypted AFF key */
831 	unsigned char encrypted_affkey[1024];
832 	int encrypted_bytes = 0;
833 	memset(encrypted_affkey,0,sizeof(encrypted_affkey));
834 
835 	r = EVP_SealInit(cipher_ctx,EVP_aes_256_cbc(),ek_array,&ek_size,&iv[0],&seal_pubkey,1);
836 	if(r!=1){
837 	    EVP_CIPHER_CTX_free(cipher_ctx);
838 	    return -10;		// bad
839 	}
840 
841 	r = EVP_SealUpdate(cipher_ctx,encrypted_affkey,&encrypted_bytes,affkey_copy,sizeof(affkey_copy));
842 	if(r!=1){
843 	    EVP_CIPHER_CTX_free(cipher_ctx);
844 	    return -11;		// bad
845 	}
846 
847 	int total_encrypted_bytes = encrypted_bytes;
848 	r = EVP_SealFinal(cipher_ctx,encrypted_affkey+total_encrypted_bytes,&encrypted_bytes);
849 	if(r!=1){
850 	    EVP_CIPHER_CTX_free(cipher_ctx);
851 	    return -12;
852 	}
853 
854 	EVP_CIPHER_CTX_free(cipher_ctx);
855 
856 	total_encrypted_bytes += encrypted_bytes;
857 
858 	/* Now we need to combine the IV, encrypted key, and the encrypted aff key onto a single structure
859 	 * and write it out
860 	 */
861 	const int int1 = sizeof(int)*1;
862 	const int int2 = sizeof(int)*2;
863 	const int int3 = sizeof(int)*3;
864 	const int buflen = int3+EVP_MAX_IV_LENGTH+ek_size+total_encrypted_bytes;
865 	unsigned char *buf = (unsigned char *)malloc(buflen);
866 	*(u_int *)(buf)      = htonl(1); // version 1.0
867 	*(u_int *)(buf+int1) = htonl(ek_size);
868 	*(u_int *)(buf+int2) = htonl(total_encrypted_bytes);
869 	memcpy(buf+int3,iv,EVP_MAX_IV_LENGTH);
870 	memcpy(buf+int3+EVP_MAX_IV_LENGTH,ek,ek_size);
871 	memcpy(buf+int3+EVP_MAX_IV_LENGTH+ek_size,encrypted_affkey,total_encrypted_bytes);
872 
873 	/* Write this into the seg */
874 	char segname[AF_MAX_NAME_LEN];
875 	snprintf(segname,sizeof(segname),AF_AFFKEY_EVP,i);
876 	if(af_update_segf(af,segname,0,buf,buflen,AF_SIGFLAG_NOSEAL)){
877 	    return -1;		// update seg failed?
878 	}
879 	EVP_PKEY_free(seal_pubkey);
880 	seal_pubkey = 0;
881 	memset(affkey_copy,0,sizeof(affkey_copy)); // overwrite
882 	memset(buf,0,buflen);	// overwrite
883 	free(buf);
884     }
885     /* Start using this key */
886     if(af_set_aes_key(af,affkey,256)) return -100; // hm. That's weird.
887     return 0;				       // good to go
888 }
889 
890 
891 
892 /**
893  * Given a private key in a file:
894  *  1 - Scan all of the encrypted AFFKEYs to see if any can be decrypted.
895  *  2 - When the one is found that can be decrypted, put the AFFKEY in a buffer
896  *  3 - Return that buffer.
897  *
898  * @param af The open AFFILE
899  * @param private_keyfile  - The filename of the key file to read
900  * @param affkey - The decrypted AFFkey (output)
901  *
902  * Load the private and/or public key files.
903  * Try to decrypt the affkey with the private key.p
904  *
905  */
906 
af_get_affkey_using_keyfile(AFFILE * af,const char * private_keyfile,u_char affkey[32])907 int af_get_affkey_using_keyfile(AFFILE *af, const char *private_keyfile,u_char affkey[32])
908 {
909     if(!private_keyfile) return -1;
910     BIO *bp = BIO_new_file(private_keyfile,"r");
911     if(!bp) return -2;
912     EVP_PKEY *seal_privkey = PEM_read_bio_PrivateKey(bp,0,0,0);
913     BIO_free(bp);
914     if(!seal_privkey) return -3;
915 
916     int i = 0;
917     int ret = -1;			// return code; set to 0 when successful
918     while(i<1000 && ret!=0){ // hopefully there aren't more than 1000 keys...
919 	char segname[AF_MAX_NAME_LEN];
920 
921 	sprintf(segname,AF_AFFKEY_EVP,i++);
922 	size_t buflen=0;
923 	if(af_get_seg(af,segname,0,0,&buflen)){
924 	    return -1;		// guess none of the keys work
925 	}
926 	unsigned char *buf = (unsigned char *)malloc(buflen);
927 	if(buf==0) return -1;		// malloc failed
928 	if(af_get_seg(af,segname,0,buf,&buflen)){
929 	    free(buf);
930 	    return -1;		// could not get the segment
931 	}
932 
933 	/* Try to get and decrypt the segment */
934 	unsigned char *decrypted = 0;	//
935 	if (*(u_int *)buf == htonl(1)){	// check to see if the encrypted EVP is rev 1
936 	    /* Handle rev 1 */
937 	    const u_int int1 = sizeof(int)*1; // offset #1
938 	    const u_int int2 = sizeof(int)*2; // offset #2
939 	    const u_int int3 = sizeof(int)*3; // offset #3
940 	    int ek_size               = ntohl(*(u_int *)(buf+int1));
941 	    int total_encrypted_bytes = ntohl(*(u_int *)(buf+int2));
942 	    if(int3+EVP_MAX_IV_LENGTH+ek_size+total_encrypted_bytes != buflen){
943 		goto next;
944 	    }
945 	    unsigned char *iv = buf+int3;
946 	    unsigned char *ek = buf+int3+EVP_MAX_IV_LENGTH;
947 	    unsigned char *encrypted_affkey = buf+int3+EVP_MAX_IV_LENGTH+ek_size;
948 
949 	    /* Now let's see if we can decode it*/
950 	    EVP_CIPHER_CTX *cipher_ctx = EVP_CIPHER_CTX_new();
951 	    int r = EVP_OpenInit(cipher_ctx,EVP_aes_256_cbc(),ek,ek_size,iv,seal_privkey);
952 	    if(r==1){
953 		/* allocate a buffer for the decrypted data */
954 		decrypted = (unsigned char *)malloc(total_encrypted_bytes);
955 		if(!decrypted){
956 		    EVP_CIPHER_CTX_free(cipher_ctx);
957 		    return -1; // shouldn't fail
958 		}
959 
960 		int decrypted_len;
961 		r = EVP_OpenUpdate(cipher_ctx,decrypted,&decrypted_len,encrypted_affkey,total_encrypted_bytes);
962 		if(r==1){
963 		    /* OpenSSL requires that we call EVP_OpenFinal to finish the decryption */
964 		    unsigned char *decrypted2 = decrypted+decrypted_len; // where the decryption continues
965 		    int decrypted2_len = 0;
966 		    r = EVP_OpenFinal(cipher_ctx,decrypted2,&decrypted2_len);
967 		    if(r==1){
968 			memcpy(affkey,decrypted,32);
969 			ret = 0;		// successful return
970 		    }
971 		}
972 		memset(decrypted,0,total_encrypted_bytes); // overwrite our temp buffer
973 		free(decrypted);
974 	    }
975 	    EVP_CIPHER_CTX_free(cipher_ctx);
976 	}
977     next:;
978 	free(buf);
979     }
980     return ret;				// return the code
981 }
982 
983 
984 /**
985  *
986  * Given a private key in a file:
987  *  1 - Scan all of the encrypted AFFKEYs to see if any can be decrypted.
988  *  2 - When the one is found that can be decrypted, put the AFFKEY in a buffer
989  *  3 - Set that buffer to be the active AFFKEY so that the AFF file can be read and written.
990  *
991  * @param af - The open AFFILE
992  * @param private_keyfile  - The filename of the key file to read
993  * @param certfile - The filename of the certificate file to read
994  */
995 
af_set_unseal_keyfile(AFFILE * af,const char * private_keyfile)996 int  af_set_unseal_keyfile(AFFILE *af,const char *private_keyfile)
997 {
998     u_char affkey[32];			// place to put the decrypted affkey
999     if(af_get_affkey_using_keyfile(af,private_keyfile,affkey)){
1000 	return -1;			// couldn't get the affkey
1001     }
1002     /* It decrypted. Looks like we got an AFF key */
1003     return af_set_aes_key(af,affkey,256);
1004 }
1005