source: libabac/abac_openssl.c @ 80a0f3f

Last change on this file since 80a0f3f was 80a0f3f, checked in by Kyle <khaefner@…>, 7 years ago

initial commit

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