source: libabac/abac_openssl.c @ 23bc596

abac0-leak
Last change on this file since 23bc596 was 23bc596, checked in by Ted Faber <faber@…>, 10 years ago

Pass -Wall on Ubuntu

  • Property mode set to 100644
File size: 17.2 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    if(debug) 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    (void) 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        if(debug) 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    (void) BIO_flush(mbio);
199
200    if( !PEM_read_bio_X509(mbio,&n509,0,NULL)) {
201        if(debug) ERR_print_errors_fp (stderr);
202        return NULL;
203    } 
204
205    BIO_free_all(mbio);
206
207    return n509;
208}
209
210int abac_write_id_to_fp(X509 *cert, FILE *fp)
211{
212    assert(cert);
213
214    if(!PEM_write_X509(fp,cert)) {
215        if(debug) ERR_print_errors_fp (stderr);
216        return 1;
217    }
218    return 0;
219}
220
221/* make stringfy a private key PEM struct */
222unsigned char *abac_string_privkey(EVP_PKEY *key)
223{
224    unsigned char *ptr=NULL;
225    unsigned char *tmp=NULL;
226
227    assert(key);
228
229    BIO *mbio=BIO_new(BIO_s_mem());
230    /* PEM_write_PrivateKey(fp,key,NULL,NULL,0,_potato_cb, "privateKey to file"); */
231    PEM_write_bio_PrivateKey(mbio,key,NULL,NULL,0,_potato_cb,"stringify privateKey");
232    (void) BIO_flush(mbio);
233    int len=(int)BIO_ctrl(mbio,BIO_CTRL_INFO,0,tmp);
234
235    if(debug) fprintf(stderr,"CHUNKING PrivateKey... %d\n",len);
236
237    if(len) {
238        ptr=(unsigned char *)malloc(sizeof(unsigned char *)*(len+1));
239        int ret=BIO_read(mbio, (void *)ptr, len);
240        if(ret==0)
241            fprintf(stderr," abac_string_privkey failed!!\n");
242        ptr[len]='\0';
243    }
244    BIO_free_all(mbio);
245    return ptr;
246}
247
248/* make stringfy a x509 PEM struct */
249unsigned char *abac_string_cert(X509 *cert) {
250    unsigned char *ptr=NULL;
251    unsigned char *tmp=NULL;
252
253    assert(cert);
254
255    BIO *mbio=BIO_new(BIO_s_mem());
256    PEM_write_bio_X509(mbio,cert);
257    (void) BIO_flush(mbio);
258    int len=(int)BIO_ctrl(mbio,BIO_CTRL_INFO,0,tmp);
259    if(debug) fprintf(stderr,"CHUNKING X509... %d\n",len);
260
261    if(len) {
262        ptr=(unsigned char *)malloc(sizeof(unsigned char *)*(len+1));
263        int ret=BIO_read(mbio, (void *)ptr, len);
264        if(ret==0)
265            fprintf(stderr," abac_string_cert failed!!\n");
266        ptr[len]='\0';
267    }
268   
269    BIO_free_all(mbio);
270    return ptr;
271}
272
273
274/* not used, sign data with privkey 
275static int _sign_with_privkey(EVP_PKEY *privkey, char *data,
276unsigned char* signed_buf)
277{
278  int err;
279  unsigned int signed_len;
280  EVP_MD_CTX     md_ctx;
281
282  EVP_SignInit   (&md_ctx, EVP_md5());
283  EVP_SignUpdate (&md_ctx, data, strlen(data));
284  signed_len = sizeof(signed_buf);
285  err = EVP_SignFinal (&md_ctx,
286                       signed_buf,
287                       &signed_len,
288                       privkey);
289  if (err != 1) {
290      if(debug) ERR_print_errors_fp (stderr);
291      return 1;
292  }
293  return 0;
294}
295**/
296
297/* nost used, verify the signature..
298static int _verify_with_pubkey(EVP_PKEY *pubkey, char *data,
299unsigned char* signed_buf )
300{
301  int err;
302  int signed_len;
303  EVP_MD_CTX     md_ctx;
304
305  EVP_VerifyInit   (&md_ctx, EVP_sha1());
306  EVP_VerifyUpdate (&md_ctx, data, strlen((char*)data));
307  signed_len=sizeof(signed_buf);
308  err = EVP_VerifyFinal (&md_ctx,
309                         signed_buf,
310                         signed_len,
311                         pubkey);
312
313  if (err != 1) {
314        if(debug) ERR_print_errors_fp (stderr);
315        return 1;
316  }
317  fprintf(stderr, "Signature Verified Ok.\n");
318  return 0;
319}
320***/
321
322
323#define PWLEN 128
324/* EVP_PKEY *PEM_read_PrivateKey(FILE *,EVP_PKEY **,pem_cb *,void *) */
325int _potato_cb(char *buf, int sz, int rwflag, void *u)
326{
327   int len;
328   char *prompt=NULL;
329   int rc;
330   if(u)
331       rc=asprintf(&prompt,"Enter passphrase for %s:", (char *)u);
332       else rc=asprintf(&prompt,"Enter passphrase :");
333    if ( rc == -1 ) return 0;
334   char *secret = malloc(PWLEN);
335   memset(secret, '\0', PWLEN);
336   if(!secret) {
337        perror("malloc()");
338        free(prompt);
339        return 0;
340   }
341   if (readpassphrase( prompt, secret, PWLEN, RPP_ECHO_OFF) == NULL) {
342       perror("readpassphrase()");
343       memset(secret, '\0', PWLEN);
344       len=0;
345       } else {
346           len=strlen(secret);
347           memcpy(buf, secret, len);
348           memset(secret, '\0', len);
349   }
350   free(secret);
351   free(prompt);
352   return len;
353}
354
355EVP_PKEY *abac_load_privkey_from_chunk(unsigned char *chunk_ptr, int chunk_len)
356{
357    EVP_PKEY *nkey=NULL;
358    BIO *mbio=BIO_new(BIO_s_mem());
359
360    BIO_write(mbio,chunk_ptr,chunk_len);
361    (void) BIO_flush(mbio);
362
363    PEM_read_bio_PrivateKey(mbio,&nkey,NULL,NULL);
364
365    BIO_free_all(mbio);
366
367    if (nkey == NULL) {
368        if(debug) ERR_print_errors_fp (stderr);
369        return NULL;
370    }
371    return nkey;
372}
373
374EVP_PKEY *abac_load_privkey_from_fp(FILE *fp)
375{
376    assert(fp);
377
378    EVP_PKEY *privkey = PEM_read_PrivateKey(fp, NULL, _potato_cb, "privateKey from file");
379
380    if (privkey == NULL) {
381        if(debug) ERR_print_errors_fp (stderr);
382        return NULL;
383    }
384    return privkey;
385}
386
387/* not adding passphrase */
388int abac_write_privkey_to_fp(EVP_PKEY *key, FILE *fp) {
389    assert(key);
390
391    if(!PEM_write_PrivateKey(fp,key,NULL,NULL,0,NULL, NULL)) {
392        if(debug) ERR_print_errors_fp (stderr);
393        return 1;
394    }
395    return 0;
396}
397
398/* adding passphrase */
399int abac_write_encrypt_privkey_to_fp(EVP_PKEY *key, FILE *fp) {
400    assert(key);
401
402    if(!PEM_write_PrivateKey(fp,key,NULL,NULL,0,_potato_cb, "privateKey to file")) {
403        if(debug) ERR_print_errors_fp (stderr);
404        return 1;
405    }
406    return 0;
407}
408
409EVP_PKEY *extract_pubkey_from_cert(X509 *cert)
410{
411    EVP_PKEY *pubkey=X509_get_pubkey(cert);
412    return pubkey;
413}
414
415
416/** not used,
417static void _callback(int p, int n, void *arg)
418{
419    char c='B';
420
421    if (p == 0) c='.';
422    if (p == 1) c='+';
423    if (p == 2) c='*';
424    if (p == 3) c='\n';
425    fputc(c,stderr);
426}
427***/
428
429/*
430RSA *RSA_generate_key(int num, unsigned long e,
431   void (*callback)(int,int,void *), void *cb_arg);
432The exponent is an odd number, typically 3, 17 or 65537
433*/
434EVP_PKEY* abac_generate_key()
435{
436    EVP_PKEY *pk=NULL;
437    int keysize=2048;
438
439    if((pk=EVP_PKEY_new()) == NULL){
440        if(debug) ERR_print_errors_fp (stderr);
441        return NULL;
442    }
443
444//    RSA *rsa=RSA_generate_key(keysize,RSA_F4,_callback,NULL);
445    RSA *rsa=RSA_generate_key(keysize,RSA_F4,NULL,NULL); 
446    if (!EVP_PKEY_assign_RSA(pk,rsa)) {
447        if(debug) ERR_print_errors_fp (stderr);
448        return NULL;
449    }
450    rsa=NULL;
451
452    return pk;
453}
454
455/* Add extension using V3 code: we can set the config file as NULL
456 * because we wont reference any other sections.
457 */
458static int _add_ext(X509 *cert, int nid, char *value)
459{
460    X509_EXTENSION *ex;
461    X509V3_CTX ctx;
462    /* This sets the 'context' of the extensions. */
463    /* No configuration database */
464    X509V3_set_ctx_nodb(&ctx);
465    /* Issuer and subject certs: both the target since it is self signed,
466     * no request and no CRL
467     */
468    X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
469    ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
470    if (!ex)
471        return 0;
472
473    X509_add_ext(cert,ex,-1);
474    X509_EXTENSION_free(ex);
475    return 1;
476}
477
478
479/**
480 * Generate ID certificate.
481 *
482 * validity is measured in seconds (as of 0.2.0)
483 */
484X509 *abac_generate_cert(EVP_PKEY *pkey, char *cn, long validity) {
485
486    /* must have a privkey before generating an ID cert */
487    assert(pkey);
488    X509 *cert=NULL;
489    unsigned char *serial=abac_generate_serial();
490    BIGNUM *bn=_make_bn_from_string(serial);
491
492    if((cert=X509_new()) == NULL)
493            goto error;
494
495    if(validity == 0) validity=(long)(60*60*24*(365));
496
497    X509_set_version(cert,2);
498
499    BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert));
500    /* this is prone to problem with very big days on 32 bit machines,
501       In newer openssl, can migrate to X509_time_adj_ex */ 
502    X509_gmtime_adj(X509_get_notBefore(cert),0);
503    X509_gmtime_adj(X509_get_notAfter(cert),validity);
504    X509_set_pubkey(cert,pkey);
505
506    X509_NAME *name=X509_get_subject_name(cert);
507
508    if(!name) goto error;
509
510    /* This function creates and adds the entry, working out the
511     * correct string type and performing checks on its length.
512     */
513    if(!(X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (unsigned char *)cn, -1, -1, 0)))
514        goto error; // fail to add cn to cert
515
516    /* Self signed, set the issuer name to be the same as the subject. */
517    if(!(X509_set_issuer_name(cert,name)))
518        goto error; // fail to set issuer name on cert
519
520    /* Add various extensions: standard extensions */
521    if(!(_add_ext(cert, NID_basic_constraints, "critical,CA:TRUE")))
522        goto error; // fail to set basic constraint
523    if(!(_add_ext(cert, NID_key_usage, "critical,keyCertSign,cRLSign")))
524        goto error; // fail to set key usage
525    if(!(_add_ext(cert, NID_subject_key_identifier, "hash")))
526        goto error; // fail to set subject key identifier
527    if(!(_add_ext(cert, NID_authority_key_identifier, "keyid:always")))
528        goto error; // fail to set authority key identifier (self-signing)
529
530    /* make sure it is signed */
531    if (!X509_sign(cert,pkey,EVP_sha1()))
532        goto error;
533
534    if(serial) free(serial);
535    if(bn) BN_free(bn);
536    return cert;
537
538error:
539    if(cert) X509_free(cert);
540    if(serial) free(serial);
541    if(bn) BN_free(bn);
542    return NULL;
543}
544
545/*** not used,
546static char *_time_in_string(ASN1_TIME *tm)
547{
548    char *ptr=NULL;
549    BIO *mbio=BIO_new(BIO_s_mem());
550    ASN1_TIME_print(mbio, tm);
551    BIO_flush(mbio);
552    int len=BIO_number_written(mbio);
553    ptr=(char *) malloc(sizeof(char *)*(len+1));
554    int ret=BIO_read(mbio, (void *)ptr, len);
555
556    BIO_free_all(mbio);
557    if(ret)
558        return ptr;
559        else return NULL;
560}
561***/
562
563
564/* atime->data, YYmmddHHMMSS or YYYYmmddHHMMSSZZ
565 *  V_ASN1_UTCTIME, V_ASN1_GENERALIZEDTIME
566 */
567static int _convert_time(struct tm *ttime, ASN1_TIME *atime) {
568    assert(atime); assert(atime->data);
569
570    int type=atime->type;
571    int len=strlen((char *)atime->data);
572    if(len==0) return 0;
573
574    char *astring=strndup((char *)atime->data,len);
575
576    /* setting ttime structure */
577    if (type == V_ASN1_UTCTIME) {
578           strptime(astring, "%y%m%d%H%M%S", ttime);
579        } else {
580        if (type == V_ASN1_GENERALIZEDTIME)
581           strptime(astring, "%Y%m%d%H%M%S", ttime);
582           else fprintf(stderr,"ERROR,.. unknown type in ASN1_TIME struct\n");
583    }
584
585    if(debug) {
586        char *tstring=asctime(ttime);
587        fprintf(stderr,"PPP final time string is %s\n",tstring);
588    }
589    return 1;
590}
591
592/* check whether the cert is still valid or not and also extract what its
593   not_before and not_after field, 0 is okay, 1 is not */
594int abac_check_validity(X509 *cert, struct tm *not_before, struct tm *not_after) {
595    assert(cert);
596
597    int valid=0;
598    int ret=0;
599    memset(not_before, 0, sizeof(struct tm));
600    memset(not_after, 0, sizeof(struct tm));
601    ASN1_TIME *notAfter= X509_get_notAfter(cert);
602    ASN1_TIME *notBefore=X509_get_notBefore(cert);
603
604    ret=_convert_time(not_before, notBefore);
605    if(ret==0) return 1;
606    ret=_convert_time(not_after, notAfter);
607    if(ret==0) return 1;
608
609    if((X509_cmp_current_time(notBefore) >=0) ||
610                  (X509_cmp_current_time(notAfter) <=0) )
611      valid=1;
612
613    if(valid) return 0;
614       else return 1;
615}
616
617/* check if cert is still valid at current time, 1 for yes, 0 for no*/
618int abac_still_valid(X509 *cert)
619{
620    ASN1_TIME *notAfter= X509_get_notAfter(cert);
621    ASN1_TIME *notBefore=X509_get_notBefore(cert);
622    if(0) {
623        fprintf(stderr,"((X509_cmp_current_time(notBefore) is %d\n", 
624                                  X509_cmp_current_time(notBefore));
625        fprintf(stderr,"((X509_cmp_current_time(notAfter) is %d\n", 
626                                  X509_cmp_current_time(notAfter));
627    }
628    if((X509_cmp_current_time(notBefore) >=0) ||
629                   (X509_cmp_current_time(notAfter) <=0) )
630      return 0;
631    return 1;
632}
633
634char *abac_get_cn(X509 *cert)
635{
636   X509_NAME *nptr=X509_get_subject_name (cert);
637   int pos=X509_NAME_get_index_by_NID(nptr, NID_commonName,-1);
638   X509_NAME_ENTRY *ent=X509_NAME_get_entry(nptr,pos); 
639   ASN1_STRING *adata=X509_NAME_ENTRY_get_data(ent);
640   unsigned char *val=ASN1_STRING_data(adata);
641   if(debug) fprintf(stderr," cn:(%zu)(%s)\n", strlen((char *)val), val);
642   return (char *) val;
643}
644
645char *abac_get_serial(X509 *cert)
646{
647   char *ret=NULL;
648   ASN1_INTEGER *num=X509_get_serialNumber(cert);
649   BIGNUM *bnser=ASN1_INTEGER_to_BN(num,NULL);
650   int n=BN_num_bytes(bnser);
651   unsigned char buf[n];
652   int b=BN_bn2bin(bnser,buf);
653   if(debug) { 
654       fprintf(stderr," extract serial number:->(%d)",b);
655       BN_print_fp(stderr,bnser);
656   } 
657   if(n)
658       ret=strndup((char *)buf,n);
659   return ret;
660}
661
662char *abac_get_subject(X509 *cert) 
663{
664   char *ptr=X509_NAME_oneline(X509_get_subject_name(cert),0,0);
665   return ptr;
666}
667
668char *abac_get_issuer(X509 *cert) 
669{   
670   char *ptr=X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
671   return ptr;
672}
673
674//  success: malloc'd calculated SHA1 of the key (as per RFC3280)
675//  fail: NULL
676unsigned char *abac_get_keyid(X509 *cert)
677{
678    char digest[SHA_DIGEST_LENGTH]; /* SSL computed key digest */
679    /* ASCII (UTF-8 compatible) text for the digest */
680    unsigned char *sha=(unsigned char *) malloc(2*SHA_DIGEST_LENGTH+1);
681    int i;  /* Scratch */
682
683    if ( !sha) return NULL;
684
685    if ( !X509_pubkey_digest(cert, EVP_sha1(), (unsigned char *)digest, NULL)) {
686        free(sha);
687        return NULL;
688    }
689
690    /* Translate to ASCII */
691    for ( i = 0; i < SHA_DIGEST_LENGTH; i++)
692        snprintf((char *) sha+2*i, 3, "%02x", digest[i] & 0xff);
693    sha[2*SHA_DIGEST_LENGTH] = '\0';
694
695    if(debug) fprintf(stderr,"SHA1 -> %s\n",sha);
696    return sha;
697}
Note: See TracBrowser for help on using the repository browser.