Пример #1
0
void
read_ca_cert(void) {
	/* Read CA cert file */
	if (!c_flag || !(cafile = fopen(c_char, "r"))) {
		fprintf(stderr, "%s: cannot open CA cert file\n", pname);
		exit (SCEP_PKISTATUS_FILE);
	}
	if (!PEM_read_X509(cafile, &cacert, NULL, NULL)) {
		fprintf(stderr, "%s: error while reading CA cert\n", pname);
		ERR_print_errors_fp(stderr);
		exit (SCEP_PKISTATUS_FILE);
	}
	fclose(cafile);

	/* Read enc CA cert */ 
	if (e_flag) {
		if (!(cafile = fopen(e_char, "r"))) {
			fprintf(stderr, "%s: cannot open enc CA cert file\n",
				pname);
			exit (SCEP_PKISTATUS_FILE);
		}
		if (!PEM_read_X509(cafile, &encert, NULL, NULL)) {
			fprintf(stderr,"%s: error while reading enc CA cert\n",
				pname);
			ERR_print_errors_fp(stderr);
			exit (SCEP_PKISTATUS_FILE);
		}
		fclose(cafile);
	}
}
Пример #2
0
/* Make sure the certificate exists and extract the public key from it.
 *
 * returns: true if it can get the public key, false otherwise */
static bool get_pubkey(void)
{
	fp_pubkey = fopen(CERTNAME, "re");
	if (!fp_pubkey) {
		fprintf(stderr, "Failed fopen %s\n", CERTNAME);
		goto error;
	}

	cert = PEM_read_X509(fp_pubkey, NULL, NULL, NULL);
	if (!cert) {
		fprintf(stderr, "Failed PEM_read_X509() for %s\n", CERTNAME);
		goto error;
	}

	pkey = X509_get_pubkey(cert);
	if (!pkey) {
		fprintf(stderr, "Failed X509_get_pubkey() for %s\n", CERTNAME);
		X509_free(cert);
		goto error;
	}
	return true;
error:
	ERR_print_errors_fp(stderr);
	return false;
}
Пример #3
0
void read_public_key(drown_ctx * dctx, char *filename)
{
    // Read file
    FILE * fp = fopen(filename, "r");
    MY_ASSERT(fp != NULL, "can't open certificate file");

    // Read cert
    X509 *cert = PEM_read_X509(fp, NULL, NULL, NULL);
    MY_ASSERT(cert != NULL, "file is not a certificate");

    // Read public key
    EVP_PKEY * pkey = X509_get_pubkey(cert);
    MY_ASSERT(pkey != NULL, "can't get public key from certificate");

    // Check RSA key
    MY_ASSERT(pkey->type == EVP_PKEY_RSA, "public key is not RSA");
    MY_ASSERT(EVP_PKEY_bits(pkey) == 2048, "only RSA-2048 is supported for now");

    // Read RSA key
    RSA *rsa = EVP_PKEY_get1_RSA(pkey);

    // Copy the public key
    BN_copy(dctx->n, rsa->n);
    BN_copy(dctx->e, rsa->e);

    RSA_free(rsa);
    EVP_PKEY_free(pkey);
    X509_free(cert);
    fclose(fp);
}
Пример #4
0
static int certificate_verify_callback(int preverify_ok, X509_STORE_CTX * ctx) {
    char fnm[FILE_PATH_SIZE];
    DIR * dir = NULL;
    int err = 0;
    int found = 0;

    snprintf(fnm, sizeof(fnm), "%s/ssl", tcf_dir);
    if (!err && (dir = opendir(fnm)) == NULL) err = errno;
    while (!err && !found) {
        int l = 0;
        X509 * cert = NULL;
        FILE * fp = NULL;
        struct dirent * ent = readdir(dir);
        if (ent == NULL) break;
        l = strlen(ent->d_name);
        if (l < 5 || strcmp(ent->d_name + l -5 , ".cert") != 0) continue;
        snprintf(fnm, sizeof(fnm), "%s/ssl/%s", tcf_dir, ent->d_name);
        if (!err && (fp = fopen(fnm, "r")) == NULL) err = errno;
        if (!err && (cert = PEM_read_X509(fp, NULL, NULL, NULL)) == NULL) err = set_ssl_errno();
        if (!err && fclose(fp) != 0) err = errno;
        if (!err && X509_cmp(X509_STORE_CTX_get_current_cert(ctx), cert) == 0) found = 1;
    }
    if (dir != NULL && closedir(dir) < 0 && !err) err = errno;
    if (err) trace(LOG_ALWAYS, "Cannot read certificate %s: %s", fnm, errno_to_str(err));
    else if (!found) trace(LOG_ALWAYS, "Authentication failure: invalid certificate");
    return err == 0 && found;
}
Пример #5
0
void test1()
{
  char *       filename = "server/server.crt";
  X509 *       x509 = NULL;
  X509 *       rc = NULL;
  FILE *       fp = NULL;
  X509_NAME *  name = NULL;
  char         buf[1024];
  int          nid = NID_undef;
  size_t       name_len = 0;
  char         cnbuf[1024];

  assert( (fp = fopen(filename,"rb")) != NULL );
  assert( (rc = PEM_read_X509(fp, &x509, (pem_password_cb *)0, NULL)) != NULL );
  assert( (name = X509_get_subject_name(x509)) != NULL );

  X509_NAME_oneline(X509_get_subject_name(x509), buf, sizeof(buf));
  assert( strcmp(buf,"/C=HU/ST=Hungary/L=Budapest/O=BeckGround Ltd./[email protected]/[email protected]") == 0 );
  printf("%s\n",buf);

  assert( (nid = OBJ_txt2nid("commonName")) != NID_undef );
  assert( (name_len = X509_NAME_get_text_by_NID(name, nid, cnbuf, sizeof(cnbuf))) > 0 );
  assert( strcmp(cnbuf,"*****@*****.**") == 0 );
  printf("%s\n",cnbuf);

  X509_free(x509);
  rc = x509 = NULL;
  fclose( fp );
}
Пример #6
0
gchar *
CertKey_ComputeCertPemFileHash(const gchar *certPemFile) // IN
{
   FILE *file;
   gchar *hash = NULL;
   X509 *cert = NULL;
   gchar *err = NULL;

   file = fopen(certPemFile, "r");
   if (!file) {
      Error("Failed to open %s: %s.\n", certPemFile, strerror(errno));
      goto exit;
   }

   cert = PEM_read_X509(file, NULL, NULL, NULL);
   if (!cert) {
      Error("Error reading certificate file %s: %s.\n",
            certPemFile, GetSSLError(&err));
      goto exit;
   }

   hash = g_strdup_printf("%08lx", X509_subject_name_hash(cert));

exit:
   if (file) {
      fclose(file);
   }
   X509_free(cert);
   g_free(err);

   return hash;
}
Пример #7
0
int main(int argc, char* args[]) {
	if(argc == 1) {
		printf("Usage: %s [OPTIONS] [FILE]\n\n", args[0]);
		printf("Options:\n\t-u\t Print UNIX timestamp\n\n");
		return 1;
	}

	FILE *pemFile = fopen(args[argc-1], "r");
	if(!pemFile) {
		fprintf(stderr, "Could not open file \"%s\"\n", args[argc-1]);
		return 1;
	}

	X509 *cert = PEM_read_X509(pemFile, NULL, NULL, NULL);
	if(!cert) {
		fprintf(stderr, "Could not read PEM format\n");
		return 1;
	}

	char notAfterStr[BUFLEN];

	ASN1_TIME *notAfter = X509_get_notAfter(cert);

	if(strcmp(args[1], "-u") == 0) {
		convertAsn1ToTimestamp(notAfter, notAfterStr);
	} else {
		convertAsn1ToString(notAfter, notAfterStr);
	}

	printf("%s\n", notAfterStr);

	return 0;
}
Пример #8
0
int main(int argc, char **argv)
{
	X509 *cert;
	FILE *inf;
	int i, count;
	X509_EXTENSION *ext;
	X509V3_add_standard_extensions();
	ERR_load_crypto_strings();
	if(!argv[1]) {
		fprintf(stderr, "Usage v3prin cert.pem\n");
		exit(1);
	}
	if(!(inf = fopen(argv[1], "r"))) {
		fprintf(stderr, "Can't open %s\n", argv[1]);
		exit(1);
	}
	if(!(cert = PEM_read_X509(inf, NULL, NULL))) {
		fprintf(stderr, "Can't read certificate %s\n", argv[1]);
		ERR_print_errors_fp(stderr);
		exit(1);
	}
	fclose(inf);
	count = X509_get_ext_count(cert);
	printf("%d extensions\n", count);
	for(i = 0; i < count; i++) {
		ext = X509_get_ext(cert, i);
		printf("%s\n", OBJ_nid2ln(OBJ_obj2nid(ext->object)));
		if(!X509V3_EXT_print_fp(stdout, ext, 0, 0)) ERR_print_errors_fp(stderr);
		printf("\n");
		
	}
	return 0;
}
Пример #9
0
static void load_cacert(X509** cacert, const char* certpem)
{
	FILE* f = fopen(certpem, "r");
	assert(f != NULL);
	PEM_read_X509(f, cacert, NULL, NULL);
	fclose(f);
}
Пример #10
0
wi_x509_t * wi_x509_init_with_pem_file(wi_x509_t *x509, wi_string_t *path) {
	FILE		*fp;
	
	fp = fopen(wi_string_cstring(path), "r");
	
	if(!fp) {
		wi_error_set_errno(errno);
		
		wi_release(x509);
		
		return NULL;
	}
	
	x509->x509 = PEM_read_X509(fp, NULL, NULL, NULL);
	
	fclose(fp);
	
	if(!x509->x509) {
		wi_error_set_openssl_error();
		
		wi_release(x509);
		
		return NULL;
	}
	
	return x509;
}
Пример #11
0
static int
SSL_CTX_use_certificate_file_with_check(
	SSL_CTX *ctx, 
	char *file, 
	int type)
{
	FILE *fp;
	X509 *x509;
	X509_STORE_CTX *sctx;
	int ret;
	ret = SSL_CTX_use_certificate_file(ctx, file, type);
	if(!ret) return ret;
	if(!(fp = fopen(file, "r"))) {
		return -1;
	}
	x509 = PEM_read_X509(fp, NULL, NULL, NULL);
	if(!x509){
		rewind(fp);
		x509 = d2i_X509_fp(fp, NULL);
	}
	fclose(fp);
	if(!x509) return -1;
	X509_STORE_add_cert(ctx->cert_store, x509);
	sctx = X509_STORE_CTX_new();
	X509_STORE_CTX_init(sctx, ctx->cert_store, x509, NULL);
	X509_STORE_CTX_set_verify_cb(sctx, LocalVerifyCallBack);
	X509_verify_cert(sctx);
	X509_STORE_CTX_free(sctx);
	CheckValidPeriod(x509);
	return ret;
}
Пример #12
0
/*
 * Load CA certificate and private key from current dir
 */
static int load_ca(char * ca_name, identity * ca)
{
    FILE * f ;
    RSA  * rsa ;
    char filename[FIELD_SZ+1] ;

    sprintf(filename, "%s.crt", ca_name);
    if ((f=fopen(filename, "r"))==NULL) {
        fprintf(stderr, "Cannot find: %s\n", filename);
        return -1 ; 
    }
    ca->cert = PEM_read_X509(f, NULL, NULL, NULL);
    fclose(f);

    sprintf(filename, "%s.key", ca_name);
    if ((f=fopen(filename, "r"))==NULL) {
        return -1 ; 
    }
    rsa = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL);
    fclose(f);

    ca->key = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(ca->key, rsa);

    if (!X509_check_private_key(ca->cert, ca->key)) {
        fprintf(stderr, "CA certificate and private key do not match\n");
        return -1 ;
    }
    return 0;
}
Пример #13
0
int main(int argc, char *argv[]) {
    X509 *cert;
    X509_STORE *store;
    X509_LOOKUP *lookup;
    X509_STORE_CTX *verify_ctx;
    FILE *fp;

    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    /* frist read the client certificate */
    if (!(fp = fopen(CLIENT_CERT, "r"))) {
        int_error("Error reading client certificate file");
    }
    if (!(cert = PEM_read_X509(fp, NULL, NULL, NULL))) {
        int_error("Error reading client certificate in file");
    }
    fclose(fp);

    /* create the cert store and set the verify callback */
    if (!(store = X509_STORE_new())) {
        int_error("Error creating X509_STORE_CTX object");
    }
    X509_STORE_set_verify_cb_func(store, verify_callback);

    /* load the CA certificates and CRLs */
    if (X509_STORE_load_locations(store, CA_FILE, CA_DIR) != 1) {
        int_error("Error loading the CA file or directory");
    }
    if (X509_STORE_set_default_paths(store) != 1) {
        int_error("Error loading the system-wide CA certificates");
    }
    if (!(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()))) {
        int_error("Error creating X509_LOOKUP object");
    }
    if (X509_load_crl_file(lookup, CRL_FILE, X509_FILETYPE_PEM) != 1) {
        int_error("Error reading the CRL file");
    }

    /* set the flags of the store so that the CRLs are consulted */
    X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);

    /* create a verification context and initialize it */
    if (!(verify_ctx = X509_STORE_CTX_new())) {
        int_error("Error creating X509_STORE_CTX object");
    }
    if (X509_STORE_CTX_init(verify_ctx, store, cert, NULL) != 1) {
        int_error("Error initializing verification context");
    }

    /* verify the certificate */
    if (X509_verify_cert(verify_ctx) != 1) {
        int_error("Error verifying the certificate");
    }
    else {
        printf("Certificate verified correctly!\n");
    }
    return 0;
}
Пример #14
0
int main(int argc, char **argv)
{
	LHASH *conf;
	X509 *cert;
	FILE *inf;
	char *conf_file;
	int i;
	int count;
	X509_EXTENSION *ext;
	X509V3_add_standard_extensions();
	ERR_load_crypto_strings();
	if(!argv[1]) {
		fprintf(stderr, "Usage: v3conf cert.pem [file.cnf]\n");
		exit(1);
	}
	conf_file = argv[2];
	if(!conf_file) conf_file = "test.cnf";
	conf = CONF_load(NULL, "test.cnf", NULL);
	if(!conf) {
		fprintf(stderr, "Error opening Config file %s\n", conf_file);
		ERR_print_errors_fp(stderr);
		exit(1);
	}

	inf = fopen(argv[1], "r");
	if(!inf) {
		fprintf(stderr, "Can't open certificate file %s\n", argv[1]);
		exit(1);
	}
	cert = PEM_read_X509(inf, NULL, NULL);
	if(!cert) {
		fprintf(stderr, "Error reading certificate file %s\n", argv[1]);
		exit(1);
	}
	fclose(inf);

	sk_pop_free(cert->cert_info->extensions, X509_EXTENSION_free);
	cert->cert_info->extensions = NULL;

	if(!X509V3_EXT_add_conf(conf, NULL, "test_section", cert)) {
		fprintf(stderr, "Error adding extensions\n");
		ERR_print_errors_fp(stderr);
		exit(1);
	}

	count = X509_get_ext_count(cert);
	printf("%d extensions\n", count);
	for(i = 0; i < count; i++) {
		ext = X509_get_ext(cert, i);
		printf("%s", OBJ_nid2ln(OBJ_obj2nid(ext->object)));
		if(ext->critical) printf(",critical:\n");
		else printf(":\n");
		X509V3_EXT_print_fp(stdout, ext, 0, 0);
		printf("\n");
		
	}
	return 0;
}
Пример #15
0
static X509 *get_cert_from_file(char *filename) {
    X509 *c;
    FILE *f = fopen(filename, "r");
    if (! f )
      return NULL;
    c = PEM_read_X509(f, NULL, NULL, NULL);
    fclose(f);
    return c;
}
Пример #16
0
/*
 * Check if the SSL/TLS certificate exists in the certificates file.
 */
int
check_cert(X509 *pcert, unsigned char *pmd, unsigned int *pmdlen)
{
	int n, r;
	FILE *fd;
	char b;
	char *certf;
	X509 *cert;
	unsigned char md[EVP_MAX_MD_SIZE];
	unsigned int mdlen;

	r = 0;
	cert = NULL;

	n = snprintf(&b, 1, "%s/%s", env.home, PATHNAME_CERTS);

	if (env.pathmax != -1 && n > env.pathmax)
		fatal(ERROR_PATHNAME,
		    "pathname limit %ld exceeded: %d\n", env.pathmax, n);

	certf = (char *)xmalloc((n + 1) * sizeof(char));
	snprintf(certf, n + 1, "%s/%s", env.home, PATHNAME_CERTS);

	if (!exists_file(certf)) {
		xfree(certf);
		return 0;
	}

	fd = fopen(certf, "r");

	xfree(certf);

	if (fd == NULL)
		return -1;

	while ((cert = PEM_read_X509(fd, &cert, NULL, NULL)) != NULL) {
		if (X509_subject_name_cmp(cert, pcert) != 0 ||
		    X509_issuer_name_cmp(cert, pcert) != 0)
			continue;

		if (!X509_digest(cert, EVP_md5(), md, &mdlen) ||
		    *pmdlen != mdlen)
			continue;

		if (memcmp(pmd, md, mdlen) != 0) {
			r = -1;
			break;
		}
		r = 1;
		break;
	}

	fclose(fd);
	X509_free(cert);

	return r;
}
Пример #17
0
/**
 * rsa_get_pub_key() - read a public key from a .crt file
 *
 * @keydir:	Directory containins the key
 * @name	Name of key file (will have a .crt extension)
 * @rsap	Returns RSA object, or NULL on failure
 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
 */
static int rsa_get_pub_key(const char *keydir, const char *name, RSA **rsap)
{
	char path[1024];
	EVP_PKEY *key;
	X509 *cert;
	RSA *rsa;
	FILE *f;
	int ret;

	*rsap = NULL;
	snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
	f = fopen(path, "r");
	if (!f) {
		fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
			path, strerror(errno));
		return -EACCES;
	}

	/* Read the certificate */
	cert = NULL;
	if (!PEM_read_X509(f, &cert, NULL, NULL)) {
		rsa_err("Couldn't read certificate");
		ret = -EINVAL;
		goto err_cert;
	}

	/* Get the public key from the certificate. */
	key = X509_get_pubkey(cert);
	if (!key) {
		rsa_err("Couldn't read public key\n");
		ret = -EINVAL;
		goto err_pubkey;
	}

	/* Convert to a RSA_style key. */
	rsa = EVP_PKEY_get1_RSA(key);
	if (!rsa) {
		rsa_err("Couldn't convert to a RSA style key");
		ret = -EINVAL;
		goto err_rsa;
	}
	fclose(f);
	EVP_PKEY_free(key);
	X509_free(cert);
	*rsap = rsa;

	return 0;

err_rsa:
	EVP_PKEY_free(key);
err_pubkey:
	X509_free(cert);
err_cert:
	fclose(f);
	return ret;
}
Пример #18
0
X509 *SSL_read_X509(FILE *fp, X509 **x509, int (*cb)(char *, int, int, void*))
#endif
{
    X509 *rc;
    BIO *bioS;
    BIO *bioF;

    /* 1. try PEM (= DER+Base64+headers) */
#if SSL_LIBRARY_VERSION < 0x00904000
    rc = PEM_read_X509(fp, x509, cb);
#else
    rc = PEM_read_X509(fp, x509, cb, NULL);
#endif
    if (rc == NULL) {
        /* 2. try DER+Base64 */
        fseek(fp, 0L, SEEK_SET);
        if ((bioS = BIO_new(BIO_s_fd())) == NULL)
            return NULL;
        BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
        if ((bioF = BIO_new(BIO_f_base64())) == NULL) {
            BIO_free(bioS);
            return NULL;
        }
        bioS = BIO_push(bioF, bioS);
        rc = d2i_X509_bio(bioS, NULL);
        BIO_free_all(bioS);
        if (rc == NULL) {
            /* 3. try plain DER */
            fseek(fp, 0L, SEEK_SET);
            if ((bioS = BIO_new(BIO_s_fd())) == NULL)
                return NULL;
            BIO_set_fd(bioS, fileno(fp), BIO_NOCLOSE);
            rc = d2i_X509_bio(bioS, NULL);
            BIO_free(bioS);
        }
    }
    if (rc != NULL && x509 != NULL) {
        if (*x509 != NULL)
            X509_free(*x509);
        *x509 = rc;
    }
    return rc;
}
Пример #19
0
X509 getX509(const char* file)
{
	::X509* ret = nullptr;
	FILE* f = dcpp_fopen(file, "r");
	if (f)
	{
		PEM_read_X509(f, &ret, nullptr, nullptr);
		fclose(f);
	}
	return X509(ret);
}
Пример #20
0
static int load_cert(const char* keyDirectory) {
  char certificateFilePath[4096];
  sprintf(certificateFilePath, "%s/%s", keyDirectory, CERTIFICATE_FILE_NAME);

  char keyFilePath[4096];
  sprintf(&keyFilePath[0], "%s/%s", keyDirectory, KEY_FILE_NAME);

  FILE *fd = fopen(certificateFilePath, "r");
  if (fd == NULL) {
    printf("Generating certificate...");
    CERT_KEY_PAIR cert = mkcert_generate();
    printf("done\n");

    char p12FilePath[4096];
    sprintf(p12FilePath, "%s/%s", keyDirectory, P12_FILE_NAME);

    mkcert_save(certificateFilePath, p12FilePath, keyFilePath, cert);
    mkcert_free(cert);
    fd = fopen(certificateFilePath, "r");
  }

  if (fd == NULL) {
    gs_error = "Can't open certificate file";
    return GS_FAILED;
  }

  if (!(cert = PEM_read_X509(fd, NULL, NULL, NULL))) {
    gs_error = "Error loading cert into memory";
    return GS_FAILED;
  }

  rewind(fd);

  int c;
  int length = 0;
  while ((c = fgetc(fd)) != EOF) {
    sprintf(cert_hex + length, "%02x", c);
    length += 2;
  }
  cert_hex[length] = 0;

  fclose(fd);

  fd = fopen(keyFilePath, "r");
  if (fd == NULL) {
    gs_error = "Error loading key into memory";
    return GS_FAILED;
  }

  PEM_read_PrivateKey(fd, &privateKey, NULL, NULL);
  fclose(fd);

  return GS_OK;
}
Пример #21
0
struct soap* init_soap(void) {
  FILE *fd = NULL;
  struct soap* soap = NULL;
  char passwd[10] = {'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'};

  soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  soap_ssl_init();
  //  soap_register_plugin(soap, plugin); // register plugin
  soap_register_plugin(soap, soap_wsse);

  fd = fopen("secrets", "r");
  if (fd) {
    fgets(passwd, 10, fd);
    fclose(fd);
    if (passwd == NULL) {
      perror("Unable to read password for X509 certificate.");
      return NULL;
    }
  } else {
    perror("Unable to open secrets file");
    return NULL;
  }

  fd = fopen("DMOPEN_100014_PRIVATE.pem", "r");
  if (fd) {
    rsa_private_key = PEM_read_PrivateKey(fd, NULL, NULL, passwd);
    fclose(fd);
    if (rsa_private_key == NULL) {
      perror("Error reading private key");
      return NULL;
    }
  } else {
    perror("Unable to open Private X509 .pem file");
    return NULL;
  }

  fd = fopen("DMOPEN_100014.pem", "r");
  if (fd) {
    cert = PEM_read_X509(fd, NULL, NULL, NULL);
    fclose(fd);
    if (cert == NULL) {
      perror("Error reading certificate file");
      return NULL;
    }
  } else {
    perror("Unable to open publix X509 .pem file");
    return NULL;
  }

  return soap;
}
Пример #22
0
// *****************************************************************************
// *                                                                           *
// * Function: ReadPublicCertificate                                           *
// *                                                                           *
// * Reads and stores the contents of the Public certificate and extracts      *
// * the expiry date                                                           *
// *****************************************************************************
// *                                                                           *
// * Parameters:                                                               *
// *  None                                                                     *
// *                                                                           *
// * Returns:                                                                  *
// *                                                                           *
// *  True if Success, else false                                              *
// *                                                                           *
// * Updates Global variables                                                  *
// *****************************************************************************
static bool ReadPublicCertificate()
{
    int ret = 0;
    struct stat file_stats;

    // Get the Certificate directory and the filename
    if (!setup_already_done)
      SetupCertFilename();

    if (0 != stat(pubkey_file, &file_stats))
      return false;   // failed to read file info

    FILE *pFile = fopen(pubkey_file, "r");

    if (pFile == NULL)
      return false;

    cert_data_len = file_stats.st_size;
    
    if (cert_data)
      delete [] cert_data;

    cert_data = new char[cert_data_len + 1];
    cert_data_len = (long) fread(cert_data, 1, cert_data_len, pFile);
    cert_data[cert_data_len] = 0;

    if ( cert_data_len != file_stats.st_size )
    {
      fclose(pFile);
      return false;
    }

    cert_timestamp = file_stats.st_mtime;

    // Extract the Expiry Date

    fclose(pFile);
    pFile = fopen(pubkey_file, "r");

    X509 *certificate = PEM_read_X509(pFile, NULL, 0, NULL);
    strncpy((char*) cert_expdate, (char*) (X509_get_notAfter(certificate)->data), EXPDATESIZE);
    cert_expdate[EXPDATESIZE] = 0;


    X509_free(certificate);
    fclose(pFile);

    return true;

}
Пример #23
0
void
read_cert(X509** cert, char* filename) {
        FILE *file;
	if (!(file = fopen(filename, "r"))) {
	        fprintf(stderr, "%s: cannot open cert file %s\n", pname, filename);
		exit (SCEP_PKISTATUS_FILE);
	}
	if (!PEM_read_X509(file, cert, NULL, NULL)) {
	        fprintf(stderr, "%s: error while reading cert %s\n", pname, filename);
		ERR_print_errors_fp(stderr);
		exit (SCEP_PKISTATUS_FILE);
	}
	fclose(file);
}
Пример #24
0
void openssl_pkcs12_cert()
{
	FILE *tmpfile;
	PKCS12 *pkcs12s;
	EVP_PKEY *certprk;
	X509 *cscert, *cacert;
	STACK_OF(X509) * cacerts;

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();

	certprk = EVP_PKEY_new();
	tmpfile = fopen(PKEYF, "r");
	certprk = PEM_read_PrivateKey(tmpfile, NULL, NULL, NULL);
	fclose(tmpfile);

	tmpfile = fopen(PCERTF, "r");
	cscert = PEM_read_X509(tmpfile, NULL, NULL, NULL);
	fclose(tmpfile);

	tmpfile = fopen(RCERTF, "r");
	cacert = PEM_read_X509(tmpfile, NULL, NULL, NULL);
	fclose(tmpfile);

	pkcs12s = PKCS12_new();
	cacerts = sk_X509_new_null();
	sk_X509_push(cacerts, cacert);
	pkcs12s = PKCS12_create("beike2012", "mypkcs12", certprk, cscert,
							cacerts, 0, 0, 0, 0, 0);
	tmpfile = fopen(PKCS12F, "w");
	if (i2d_PKCS12_fp(tmpfile, pkcs12s) <= 0)
		openssl_error_show("i2d_PKCS12_fp", 1);
	fclose(tmpfile);
	sk_X509_free(cacerts);
	PKCS12_free(pkcs12s);
}
Пример #25
0
static X509 *
load_X509_from_file(const char *filepath)
{
    FILE *certfile = NULL;
    X509 *cert = NULL;

    certfile = fopen(filepath, "r");
    if (certfile == NULL) {
        return NULL;
    }
    cert = PEM_read_X509(certfile, NULL, NULL, NULL);
    fclose(certfile);

    return cert;
}
Пример #26
0
static int check_certificate_by_digest (X509 *peercert)
{
  unsigned char peermd[EVP_MAX_MD_SIZE];
  unsigned int peermdlen;
  X509 *cert = NULL;
  int pass = 0;
  FILE *fp;

  /* expiration check */
  if (option (OPTSSLVERIFYDATES) != MUTT_NO)
  {
    if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0)
    {
      dprint (2, (debugfile, "Server certificate is not yet valid\n"));
      mutt_error (_("Server certificate is not yet valid"));
      mutt_sleep (2);
      return 0;
    }
    if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0)
    {
      dprint (2, (debugfile, "Server certificate has expired"));
      mutt_error (_("Server certificate has expired"));
      mutt_sleep (2);
      return 0;
    }
  }

  if ((fp = fopen (SslCertFile, "rt")) == NULL)
    return 0;

  if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
  {
    safe_fclose (&fp);
    return 0;
  }

  while ((cert = PEM_read_X509 (fp, &cert, NULL, NULL)) != NULL)
  {
    pass = compare_certificates (cert, peercert, peermd, peermdlen) ? 0 : 1;

    if (pass)
      break;
  }
  X509_free (cert);
  safe_fclose (&fp);

  return pass;
}
Пример #27
0
void test_wiener(void)
{
  X509 *crt;
  RSA *rsa;
  FILE *fp = fopen("wiener_test.crt", "r");

  if (!fp) exit(EXIT_FAILURE);
  crt = PEM_read_X509(fp, NULL, 0, NULL);
  if (!crt) {
    exit(EXIT_FAILURE);
  }

  rsa = X509_get_pubkey(crt)->pkey.rsa;
  /* assert(WienerQuestion.test(crt)); */
  assert(WienerQuestion.ask_rsa(rsa));
}
CertificatePtr RevocationCheckerBase::loadPEMFile(const char* fileName)
{
    DPL::ScopedFClose fd(fopen(fileName, "rb"));

    // no such file, return NULL
    if (!fd.Get()) {
        return CertificatePtr();
    }

    // create a new X509 certificate basing on file
    CertificatePtr cert(new Certificate(PEM_read_X509(fd.Get(),
                                                      NULL,
                                                      NULL,
                                                      NULL)));
    return cert;
}
Пример #29
0
char* getSerial()
{
	char* id = malloc(20);
	char *str, *ptr;
	FILE* fp;
	X509* x509;

	char deviceid[11];
	ERR_load_crypto_strings();

	fp = fopen(ODI_CERT_FILE, "r");
	if (NULL == fp)
	{
		printf("Error opening file: %s\n", ODI_CERT_FILE);
	}
	x509 = PEM_read_X509(fp, NULL, NULL, NULL);
	fclose(fp);
	if (x509 == NULL)
	{
		printf("error reading certificate\n");
		return 0;
	}
	str = X509_NAME_oneline(X509_get_subject_name(x509), 0, 0);
	if (str)
	{
		ptr = strstr(str, "/CN=");
		if (ptr)
		{
			if (strlen(ptr) == 14)
			{
				strcpy(deviceid, ptr + 4);
				sprintf(id, "%s", deviceid);
			}
			else
			{
				printf("error parsing unit certificate - invalid device id\n");
			}
		}
		else
		{
			printf("error parsing unit certificate - can't find CN\n");
		}
	}
	OPENSSL_free(str);
	X509_free(x509);
	return id;
}
Пример #30
0
int main(int argc, char *argv[])
{
    int error_code = 0;

    if(2 > argc)
    {
        printf("args is error\n");
        error_code = 2;
        goto end;
    }

    char *certfile = argv[1];
    FILE *fpem = NULL;
    X509 *cert = NULL;

    if( !( fpem = fopen( certfile, "r" ))) 
    {
        printf("Couldn't open the PEM file: %s\n", certfile);
        error_code = 3;
        goto end;
    }

    if( !( cert = PEM_read_X509( fpem, NULL, NULL, NULL ))) 
    {
        printf( "Failed to read the PEM file: %s\n",certfile );
        error_code = 4;
        goto end;
    }
    if(fpem)
    {
        fclose(fpem);
    }

	error_code = get_subject(cert);

    error_code = get_subjectAltName(cert);
   
end:

    if(cert)
    {
        X509_free(cert);
    }

  return error_code;
}