source: libabac/abac_openssl.c @ bfaec48

abac0-leakabac0-meimei-idmei-rt0-ntvf-new-xml
Last change on this file since bfaec48 was bfaec48, checked in by Ted Faber <faber@…>, 11 years ago

Generate keyids from certificates without the X509v3 Subject Key Identifier extesnion.

  • Property mode set to 100644
File size: 16.6 KB
Line 
1
2/* abac_openssl.c */
3
4#define _GNU_SOURCE
5#include <stdio.h>
6#include <stdlib.h>
7#include <assert.h>
8#include <ctype.h>
9#include <unistd.h>
10
11#include <fcntl.h>
12#include <sys/types.h>
13#include <sys/stat.h>
14#include <sys/mman.h>
15#include <time.h>
16
17#include <stdbool.h>
18
19#include <openssl/conf.h>
20#include <openssl/x509.h>
21#include <openssl/x509v3.h>
22#include <openssl/x509_vfy.h>
23
24#include <openssl/rsa.h>
25#include <openssl/evp.h>
26#include <openssl/err.h>
27#include <openssl/pem.h>
28#include <openssl/ssl.h>
29#include <openssl/sha.h>
30#include <openssl/rand.h>
31
32
33#ifdef HAVE_READPASSPHRASE
34# include <readpassphrase.h>
35#else
36# include "compat/readpassphrase.h"
37#endif
38
39static int debug=0;
40
41int _potato_cb(char *buf, int sz, int rwflag, void *u);
42
43/***********************************************************************/
44int init_openssl() {
45    ERR_load_crypto_strings();
46    OpenSSL_add_all_algorithms();
47    return 0;
48}
49
50int deinit_openssl() {
51    CRYPTO_cleanup_all_ex_data();
52    return 0;
53}
54
55/* int RAND_bytes(unsigned char *buf, int num); */
56unsigned char *abac_generate_serial() {
57    unsigned char *serial=(unsigned char *) malloc(sizeof(unsigned char)*8);
58
59    memset(serial, '\0', 8);
60
61    if(!RAND_bytes(serial,8)) {
62        fprintf(stderr,"RAT, RAN^D out of seeds!!!\n");
63        assert(0);
64    }
65    // zap leading 0's
66    while (serial[0] == 0)
67        RAND_bytes(&serial[0],1);
68
69    RAND_cleanup();
70    return serial;
71}
72
73
74static BIGNUM *_make_bn_from_string(unsigned char *str)
75{
76    assert(str);
77    BIGNUM *tmp;
78    tmp=BN_bin2bn(str,8,NULL);
79/* BN_print_fp(stderr,tmp); */
80    int n=BN_num_bytes(tmp);
81    if(n) return tmp;
82        return NULL;
83}
84
85unsigned char *_encode_m64(unsigned char *orig_ptr, int orig_len)
86{
87    BIO *mbio,*b64bio,*bio;
88
89    unsigned char *m64_ptr=NULL;
90    int m64_len=0;
91
92    unsigned char *ptr=NULL;
93
94    if(orig_len==0) return NULL;
95
96    /*bio pointing at b64->mem, the base64 bio encodes on
97      write and decodes on read */
98    mbio=BIO_new(BIO_s_mem());
99    b64bio=BIO_new(BIO_f_base64());
100    bio=BIO_push(b64bio,mbio);
101
102    BIO_write(bio,orig_ptr,orig_len);
103
104    /* We need to 'flush' things to push out the encoding of the
105    * last few bytes.  There is special encoding if it is not a
106    * multiple of 3
107    */
108    BIO_flush(bio);
109
110    /* pointer to the data and the number of elements. */
111    m64_len=(int)BIO_ctrl(mbio,BIO_CTRL_INFO,0,ptr);
112
113    if(m64_len!=0) {
114       m64_ptr=malloc(m64_len+1);
115       if(m64_ptr) {
116           strcpy((char *)m64_ptr, (char *)ptr);
117           } else { 
118               fprintf(stderr,"ERROR: malloc failed\n");
119       }
120    }
121
122    /* This call will walk the chain freeing all the BIOs */
123    BIO_free_all(bio);
124    return m64_ptr;
125}
126
127unsigned char *_decode_m64(unsigned char *m64_ptr, int m64_len)
128{
129    unsigned char *orig_ptr=NULL;
130    int orig_len=0;
131
132    BIO *b64bio, *mbio, *bio;
133    char *ptr=NULL;
134
135    if(m64_len==0) return NULL;
136
137    ptr = (char *)malloc(sizeof(char)*m64_len);
138    memset(ptr, '\0', m64_len);
139
140    b64bio = BIO_new(BIO_f_base64());
141    mbio = BIO_new_mem_buf(m64_ptr, m64_len);
142    bio = BIO_push(b64bio, mbio);
143
144    orig_len=BIO_read(bio, ptr, m64_len);
145   
146    if(orig_len) {
147        orig_ptr=malloc(orig_len+1);
148        if(orig_ptr)
149            strcpy((char *)orig_ptr, ptr);
150            else fprintf(stderr,"ERROR: malloc failed..\n");
151    }
152
153    BIO_free_all(bio);
154    return orig_ptr;
155}
156
157/*** not used
158static char *_read_blob_from_file(char *fname, int *len)
159{
160    struct stat sb;
161    char *dptr=NULL;
162
163    int fd = open(fname, O_RDONLY);
164    if (fd == -1) { return NULL; }
165    if(stat(fname, &sb) == -1) {
166        close(fd);
167        return NULL;
168    }
169    dptr= (char *)mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
170    close(fd);
171
172    if(dptr == MAP_FAILED) {
173        return NULL;
174    }
175    *len=sb.st_size;
176    return dptr;
177}
178***/
179
180/* Read ID in PEM */
181X509 *abac_load_id_from_fp(FILE *fp)
182{
183    X509 *cert=PEM_read_X509(fp,NULL,NULL,NULL);
184
185    if (cert == NULL) {
186        ERR_print_errors_fp (stderr);
187        return NULL;
188    }
189    return cert;
190}
191
192X509 *abac_load_id_from_chunk(unsigned char *chunk_ptr, int chunk_len)
193{
194    X509 *n509=NULL;
195    BIO *mbio=BIO_new(BIO_s_mem());
196
197    BIO_write(mbio,chunk_ptr,chunk_len);
198    BIO_flush(mbio);
199
200    PEM_read_bio_X509(mbio,&n509,NULL,NULL);
201
202    BIO_free_all(mbio);
203
204    if (n509 == NULL) {
205        ERR_print_errors_fp (stderr);
206        return NULL;
207    }
208    return n509;
209}
210
211int abac_write_id_to_fp(X509 *cert, FILE *fp)
212{
213    assert(cert);
214
215    if(!PEM_write_X509(fp,cert)) {
216        ERR_print_errors_fp (stderr);
217        return 1;
218    }
219    return 0;
220}
221
222/* make stringfy a private key PEM struct */
223unsigned char *abac_string_privkey(EVP_PKEY *key)
224{
225    unsigned char *ptr=NULL;
226    unsigned char *tmp=NULL;
227
228    assert(key);
229
230    BIO *mbio=BIO_new(BIO_s_mem());
231    /* PEM_write_PrivateKey(fp,key,NULL,NULL,0,_potato_cb, "privateKey to file"); */
232    PEM_write_bio_PrivateKey(mbio,key,NULL,NULL,0,_potato_cb,"stringify privateKey");
233    BIO_flush(mbio);
234    int len=(int)BIO_ctrl(mbio,BIO_CTRL_INFO,0,tmp);
235
236    if(debug) fprintf(stderr,"CHUNKING PrivateKey... %d\n",len);
237
238    if(len) {
239        ptr=(unsigned char *)malloc(sizeof(unsigned char *)*(len+1));
240        int ret=BIO_read(mbio, (void *)ptr, len);
241        if(ret==0)
242            fprintf(stderr," abac_string_privkey failed!!\n");
243        ptr[len]='\0';
244    }
245    BIO_free_all(mbio);
246    return ptr;
247}
248
249/* make stringfy a x509 PEM struct */
250unsigned char *abac_string_cert(X509 *cert) {
251    unsigned char *ptr=NULL;
252    unsigned char *tmp=NULL;
253
254    assert(cert);
255
256    BIO *mbio=BIO_new(BIO_s_mem());
257    PEM_write_bio_X509(mbio,cert);
258    BIO_flush(mbio);
259    int len=(int)BIO_ctrl(mbio,BIO_CTRL_INFO,0,tmp);
260    if(debug) fprintf(stderr,"CHUNKING X509... %d\n",len);
261
262    if(len) {
263        ptr=(unsigned char *)malloc(sizeof(unsigned char *)*(len+1));
264        int ret=BIO_read(mbio, (void *)ptr, len);
265        if(ret==0)
266            fprintf(stderr," abac_string_cert failed!!\n");
267        ptr[len]='\0';
268    }
269   
270    BIO_free_all(mbio);
271    return ptr;
272}
273
274
275/* not used, sign data with privkey 
276static int _sign_with_privkey(EVP_PKEY *privkey, char *data,
277unsigned char* signed_buf)
278{
279  int err;
280  unsigned int signed_len;
281  EVP_MD_CTX     md_ctx;
282
283  EVP_SignInit   (&md_ctx, EVP_md5());
284  EVP_SignUpdate (&md_ctx, data, strlen(data));
285  signed_len = sizeof(signed_buf);
286  err = EVP_SignFinal (&md_ctx,
287                       signed_buf,
288                       &signed_len,
289                       privkey);
290  if (err != 1) {
291      ERR_print_errors_fp (stderr);
292      return 1;
293  }
294  return 0;
295}
296**/
297
298/* nost used, verify the signature..
299static int _verify_with_pubkey(EVP_PKEY *pubkey, char *data,
300unsigned char* signed_buf )
301{
302  int err;
303  int signed_len;
304  EVP_MD_CTX     md_ctx;
305
306  EVP_VerifyInit   (&md_ctx, EVP_sha1());
307  EVP_VerifyUpdate (&md_ctx, data, strlen((char*)data));
308  signed_len=sizeof(signed_buf);
309  err = EVP_VerifyFinal (&md_ctx,
310                         signed_buf,
311                         signed_len,
312                         pubkey);
313
314  if (err != 1) {
315        ERR_print_errors_fp (stderr);
316        return 1;
317  }
318  fprintf(stderr, "Signature Verified Ok.\n");
319  return 0;
320}
321***/
322
323
324#define PWLEN 128
325/* EVP_PKEY *PEM_read_PrivateKey(FILE *,EVP_PKEY **,pem_cb *,void *) */
326int _potato_cb(char *buf, int sz, int rwflag, void *u)
327{
328   int len;
329   char *prompt=NULL;
330   if(u)
331       asprintf(&prompt,"Enter passphrase for %s:", (char *)u);
332       else asprintf(&prompt,"Enter passphrase :");
333   char *secret = malloc(PWLEN);
334   memset(secret, '\0', PWLEN);
335   if(!secret) {
336        perror("malloc()");
337        free(prompt);
338        return 0;
339   }
340   if (readpassphrase( prompt, secret, PWLEN, RPP_ECHO_OFF) == NULL) {
341       perror("readpassphrase()");
342       memset(secret, '\0', PWLEN);
343       len=0;
344       } else {
345           len=strlen(secret);
346           memcpy(buf, secret, len);
347           memset(secret, '\0', len);
348   }
349   free(secret);
350   free(prompt);
351   return len;
352}
353
354EVP_PKEY *abac_load_privkey_from_fp(FILE *fp)
355{
356    assert(fp);
357
358    EVP_PKEY *privkey = PEM_read_PrivateKey(fp, NULL, _potato_cb, "privateKey from file");
359
360    if (privkey == NULL) {
361        ERR_print_errors_fp (stderr);
362        return NULL;
363    }
364    return privkey;
365}
366
367/* not adding passphrase */
368int abac_write_privkey_to_fp(EVP_PKEY *key, FILE *fp) {
369    assert(key);
370
371    if(!PEM_write_PrivateKey(fp,key,NULL,NULL,0,NULL, NULL)) {
372        ERR_print_errors_fp (stderr);
373        return 1;
374    }
375    return 0;
376}
377
378/* adding passphrase */
379int abac_write_encrypt_privkey_to_fp(EVP_PKEY *key, FILE *fp) {
380    assert(key);
381
382    if(!PEM_write_PrivateKey(fp,key,NULL,NULL,0,_potato_cb, "privateKey to file")) {
383        ERR_print_errors_fp (stderr);
384        return 1;
385    }
386    return 0;
387}
388
389EVP_PKEY *extract_pubkey_from_cert(X509 *cert)
390{
391    EVP_PKEY *pubkey=X509_get_pubkey(cert);
392    return pubkey;
393}
394
395
396/** not used,
397static void _callback(int p, int n, void *arg)
398{
399    char c='B';
400
401    if (p == 0) c='.';
402    if (p == 1) c='+';
403    if (p == 2) c='*';
404    if (p == 3) c='\n';
405    fputc(c,stderr);
406}
407***/
408
409/*
410RSA *RSA_generate_key(int num, unsigned long e,
411   void (*callback)(int,int,void *), void *cb_arg);
412The exponent is an odd number, typically 3, 17 or 65537
413*/
414EVP_PKEY* abac_generate_key()
415{
416    EVP_PKEY *pk=NULL;
417    int keysize=2048;
418
419    if((pk=EVP_PKEY_new()) == NULL){
420        ERR_print_errors_fp (stderr);
421        return NULL;
422    }
423
424//    RSA *rsa=RSA_generate_key(keysize,RSA_F4,_callback,NULL);
425    RSA *rsa=RSA_generate_key(keysize,RSA_F4,NULL,NULL); 
426    if (!EVP_PKEY_assign_RSA(pk,rsa)) {
427        ERR_print_errors_fp (stderr);
428        return NULL;
429    }
430    rsa=NULL;
431
432    return pk;
433}
434
435/* Add extension using V3 code: we can set the config file as NULL
436 * because we wont reference any other sections.
437 */
438static int _add_ext(X509 *cert, int nid, char *value)
439{
440    X509_EXTENSION *ex;
441    X509V3_CTX ctx;
442    /* This sets the 'context' of the extensions. */
443    /* No configuration database */
444    X509V3_set_ctx_nodb(&ctx);
445    /* Issuer and subject certs: both the target since it is self signed,
446     * no request and no CRL
447     */
448    X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
449    ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
450    if (!ex)
451        return 0;
452
453    X509_add_ext(cert,ex,-1);
454    X509_EXTENSION_free(ex);
455    return 1;
456}
457
458
459/**
460 * Generate ID certificate.
461 *
462 * validity is measured in seconds (as of 0.2.0)
463 */
464X509 *abac_generate_cert(EVP_PKEY *pkey, char *cn, long validity) {
465
466    /* must have a privkey before generating an ID cert */
467    assert(pkey);
468    X509 *cert=NULL;
469
470    if((cert=X509_new()) == NULL)
471            goto error;
472
473    unsigned char *serial=abac_generate_serial();
474
475    if(validity == 0) validity=(long)(60*60*24*(365));
476
477    X509_set_version(cert,2);
478
479    BIGNUM *bn=_make_bn_from_string(serial);
480    BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert));
481    /* this is prone to problem with very big days on 32 bit machines,
482       In newer openssl, can migrate to X509_time_adj_ex */ 
483    X509_gmtime_adj(X509_get_notBefore(cert),0);
484    X509_gmtime_adj(X509_get_notAfter(cert),validity);
485    X509_set_pubkey(cert,pkey);
486
487    X509_NAME *name=X509_get_subject_name(cert);
488
489    if(!name) goto error;
490
491    /* This function creates and adds the entry, working out the
492     * correct string type and performing checks on its length.
493     */
494    if(!(X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (unsigned char *)cn, -1, -1, 0)))
495        goto error; // fail to add cn to cert
496
497    /* Self signed, set the issuer name to be the same as the subject. */
498    if(!(X509_set_issuer_name(cert,name)))
499        goto error; // fail to set issuer name on cert
500
501    /* Add various extensions: standard extensions */
502    if(!(_add_ext(cert, NID_basic_constraints, "critical,CA:TRUE")))
503        goto error; // fail to set basic constraint
504    if(!(_add_ext(cert, NID_key_usage, "critical,keyCertSign,cRLSign")))
505        goto error; // fail to set key usage
506    if(!(_add_ext(cert, NID_subject_key_identifier, "hash")))
507        goto error; // fail to set subject key identifier
508    if(!(_add_ext(cert, NID_authority_key_identifier, "keyid:always")))
509        goto error; // fail to set authority key identifier (self-signing)
510
511    /* make sure it is signed */
512    if (!X509_sign(cert,pkey,EVP_sha1()))
513        goto error;
514
515    return cert;
516
517error:
518    if(cert) X509_free(cert);
519    if(serial) free(serial);
520    if(bn) BN_free(bn);
521    return NULL;
522}
523
524/*** not used,
525static char *_time_in_string(ASN1_TIME *tm)
526{
527    char *ptr=NULL;
528    BIO *mbio=BIO_new(BIO_s_mem());
529    ASN1_TIME_print(mbio, tm);
530    BIO_flush(mbio);
531    int len=BIO_number_written(mbio);
532    ptr=(char *) malloc(sizeof(char *)*(len+1));
533    int ret=BIO_read(mbio, (void *)ptr, len);
534
535    BIO_free_all(mbio);
536    if(ret)
537        return ptr;
538        else return NULL;
539}
540***/
541
542
543/* atime->data, YYmmddHHMMSS or YYYYmmddHHMMSSZZ
544 *  V_ASN1_UTCTIME, V_ASN1_GENERALIZEDTIME
545 */
546static int _convert_time(struct tm *ttime, ASN1_TIME *atime) {
547    assert(atime); assert(atime->data);
548
549    int type=atime->type;
550    int len=strlen((char *)atime->data);
551    if(len==0) return 0;
552
553    char *astring=strndup((char *)atime->data,len);
554
555    /* setting ttime structure */
556    if (type == V_ASN1_UTCTIME) {
557           strptime(astring, "%y%m%d%H%M%S", ttime);
558        } else {
559        if (type == V_ASN1_GENERALIZEDTIME)
560           strptime(astring, "%Y%m%d%H%M%S", ttime);
561           else fprintf(stderr,"ERROR,.. unknown type in ASN1_TIME struct\n");
562    }
563
564    if(debug) {
565        char *tstring=asctime(ttime);
566        fprintf(stderr,"PPP final time string is %s\n",tstring);
567    }
568    return 1;
569}
570
571/* check whether the cert is still valid or not and also extract what its
572   not_before and not_after field, 0 is okay, 1 is not */
573int abac_check_validity(X509 *cert, struct tm *not_before, struct tm *not_after) {
574    assert(cert);
575
576    int valid=0;
577    int ret=0;
578    memset(not_before, 0, sizeof(struct tm));
579    memset(not_after, 0, sizeof(struct tm));
580    ASN1_TIME *notAfter= X509_get_notAfter(cert);
581    ASN1_TIME *notBefore=X509_get_notBefore(cert);
582
583    ret=_convert_time(not_before, notBefore);
584    if(ret==0) return 1;
585    ret=_convert_time(not_after, notAfter);
586    if(ret==0) return 1;
587
588    if((X509_cmp_current_time(notBefore) >=0) ||
589                  (X509_cmp_current_time(notAfter) <=0) )
590      valid=1;
591
592    if(valid) return 0;
593       else return 1;
594}
595
596/* check if cert is still valid at current time, 1 for yes, 0 for no*/
597int abac_still_valid(X509 *cert)
598{
599    ASN1_TIME *notAfter= X509_get_notAfter(cert);
600    ASN1_TIME *notBefore=X509_get_notBefore(cert);
601    if(0) {
602        fprintf(stderr,"((X509_cmp_current_time(notBefore) is %d\n", 
603                                  X509_cmp_current_time(notBefore));
604        fprintf(stderr,"((X509_cmp_current_time(notAfter) is %d\n", 
605                                  X509_cmp_current_time(notAfter));
606    }
607    if((X509_cmp_current_time(notBefore) >=0) ||
608                   (X509_cmp_current_time(notAfter) <=0) )
609      return 0;
610    return 1;
611}
612
613char *abac_get_cn(X509 *cert)
614{
615   X509_NAME *nptr=X509_get_subject_name (cert);
616   int pos=X509_NAME_get_index_by_NID(nptr, NID_commonName,-1);
617   X509_NAME_ENTRY *ent=X509_NAME_get_entry(nptr,pos); 
618   ASN1_STRING *adata=X509_NAME_ENTRY_get_data(ent);
619   unsigned char *val=ASN1_STRING_data(adata);
620   if(debug) fprintf(stderr," cn:(%d)(%s)\n", strlen((char *)val), val);
621   return (char *) val;
622}
623
624char *abac_get_serial(X509 *cert)
625{
626   char *ret=NULL;
627   ASN1_INTEGER *num=X509_get_serialNumber(cert);
628   BIGNUM *bnser=ASN1_INTEGER_to_BN(num,NULL);
629   int n=BN_num_bytes(bnser);
630   unsigned char buf[n];
631   int b=BN_bn2bin(bnser,buf);
632   if(debug) { 
633       fprintf(stderr," extract serial number:->(%d)",b);
634       BN_print_fp(stderr,bnser);
635   } 
636   if(n)
637       ret=strndup((char *)buf,n);
638   return ret;
639}
640
641char *abac_get_subject(X509 *cert) 
642{
643   char *ptr=X509_NAME_oneline(X509_get_subject_name(cert),0,0);
644   return ptr;
645}
646
647char *abac_get_issuer(X509 *cert) 
648{   
649   char *ptr=X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
650   return ptr;
651}
652
653//  success: malloc'd calculated SHA1 of the key (as per RFC3280)
654//  fail: NULL
655unsigned char *abac_get_keyid(X509 *cert)
656{
657    char digest[SHA_DIGEST_LENGTH]; /* SSL computed key digest */
658    /* ASCII (UTF-8 compatible) text for the digest */
659    unsigned char *sha=(unsigned char *) malloc(2*SHA_DIGEST_LENGTH+1);
660    int i;  /* Scratch */
661
662    if ( !sha) return NULL;
663
664    if ( !X509_pubkey_digest(cert, EVP_sha1(), digest, NULL)) {
665        free(sha);
666        return NULL;
667    }
668
669    /* Translate to ASCII */
670    for ( i = 0; i < SHA_DIGEST_LENGTH; i++)
671        snprintf((char *) sha+2*i, 3, "%02x", digest[i] & 0xff);
672    sha[2*SHA_DIGEST_LENGTH] = '\0';
673
674    if(debug) fprintf(stderr,"SHA1 -> %s\n",sha);
675    return sha;
676}
Note: See TracBrowser for help on using the repository browser.