Exemplo n.º 1
0
int SSL_use_certificate_file(SSL *ssl, const char *file, int type) {
  int reason_code;
  BIO *in;
  int ret = 0;
  X509 *x = NULL;

  in = BIO_new(BIO_s_file());
  if (in == NULL) {
    OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
    goto end;
  }

  if (BIO_read_filename(in, file) <= 0) {
    OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
    goto end;
  }

  if (type == SSL_FILETYPE_ASN1) {
    reason_code = ERR_R_ASN1_LIB;
    x = d2i_X509_bio(in, NULL);
  } else if (type == SSL_FILETYPE_PEM) {
    reason_code = ERR_R_PEM_LIB;
    x = PEM_read_bio_X509(in, NULL, ssl->ctx->default_passwd_callback,
                          ssl->ctx->default_passwd_callback_userdata);
  } else {
    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SSL_FILETYPE);
    goto end;
  }

  if (x == NULL) {
    OPENSSL_PUT_ERROR(SSL, reason_code);
    goto end;
  }

  ret = SSL_use_certificate(ssl, x);

end:
  X509_free(x);
  BIO_free(in);

  return ret;
}
Exemplo n.º 2
0
Arquivo: us894.c Projeto: DDvO/libest
/*
 * Null trusted CA chain when initializing server
 */
static void us894_test18 (void)
{
    BIO *certin, *keyin;
    X509 *x;
    EVP_PKEY *priv_key;
    int rv;
    EST_CTX *ctx;

    LOG_FUNC_NM;
    
    /*
     * Read the server cert
     */
    certin = BIO_new(BIO_s_file_internal());
    rv = BIO_read_filename(certin, US894_SERVER_CERT); 
    CU_ASSERT(rv > 0);
    x = PEM_read_bio_X509(certin, NULL, NULL, NULL);
    CU_ASSERT(x != NULL);
    BIO_free(certin);

    /*
     * Read the server key 
     */
    keyin = BIO_new(BIO_s_file_internal());
    rv = BIO_read_filename(keyin, US894_SERVER_KEY);
    CU_ASSERT(rv > 0);
    priv_key = PEM_read_bio_PrivateKey(keyin, NULL, NULL, NULL);
    CU_ASSERT(priv_key != NULL);
    BIO_free(keyin);

    /* 
     * Attempt to init EST proxy using NULL local CA chain
     */
    est_init_logger(EST_LOG_LVL_INFO, NULL);
    ctx = est_proxy_init(NULL, 0, NULL, 0, EST_CERT_FORMAT_PEM,
                         "testrealm", x, priv_key,
                         "estuser", "estpwd");
    CU_ASSERT(ctx == NULL);

    X509_free(x);
    EVP_PKEY_free(priv_key);
}
Exemplo n.º 3
0
/*
 * Read a bio that contains our certificate in "PEM" format,
 * possibly followed by a sequence of CA certificates that should be
 * sent to the peer in the Certificate message.
 */
static int
ssl_ctx_use_certificate_chain_bio(SSL_CTX *ctx, BIO *in)
{
	X509 *ca, *x = NULL;
	unsigned long err;
	int ret = 0;

	if ((x = PEM_read_bio_X509_AUX(in, NULL, ctx->default_passwd_callback,
	    ctx->default_passwd_callback_userdata)) == NULL) {
		SSLerrorx(ERR_R_PEM_LIB);
		goto err;
	}

	if (!SSL_CTX_use_certificate(ctx, x))
		goto err;

	if (!ssl_cert_set0_chain(ctx->internal->cert, NULL))
		goto err;

	/* Process any additional CA certificates. */
	while ((ca = PEM_read_bio_X509(in, NULL,
	    ctx->default_passwd_callback,
	    ctx->default_passwd_callback_userdata)) != NULL) {
		if (!ssl_cert_add0_chain_cert(ctx->internal->cert, ca)) {
			X509_free(ca);
			goto err;
		}
	}

	/* When the while loop ends, it's usually just EOF. */
	err = ERR_peek_last_error();
	if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
	    ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
		ERR_clear_error();
		ret = 1;
	}

 err:
	X509_free(x);

	return (ret);
}
Exemplo n.º 4
0
int SSL_use_certificate_file(SSL *ssl, const char *file, int type)
{
    int j;
    BIO *in;
    int ret = 0;
    X509 *x = NULL;

    in = BIO_new(BIO_s_file_internal());
    if (in == NULL) {
        SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE, ERR_R_BUF_LIB);
        goto end;
    }

    if (BIO_read_filename(in, file) <= 0) {
        SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE, ERR_R_SYS_LIB);
        goto end;
    }
    if (type == SSL_FILETYPE_ASN1) {
        j = ERR_R_ASN1_LIB;
        x = d2i_X509_bio(in, NULL);
    } else if (type == SSL_FILETYPE_PEM) {
        j = ERR_R_PEM_LIB;
        x = PEM_read_bio_X509(in, NULL, ssl->ctx->default_passwd_callback,
                              ssl->ctx->default_passwd_callback_userdata);
    } else {
        SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE, SSL_R_BAD_SSL_FILETYPE);
        goto end;
    }

    if (x == NULL) {
        SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE, j);
        goto end;
    }

    ret = SSL_use_certificate(ssl, x);
 end:
    if (x != NULL)
        X509_free(x);
    if (in != NULL)
        BIO_free(in);
    return (ret);
}
Exemplo n.º 5
0
X509 *https_open_cert(s8 *filepath)
{
	X509 *cert	   = NULL;
	BIO  *bio_cert = NULL;
	
	bio_cert = BIO_new_file(filepath, "r");
	if (!bio_cert)
	{
		return NULL;
	}
	cert = PEM_read_bio_X509(bio_cert, NULL, NULL, NULL);
	if (!cert)
	{
		(void)BIO_reset(bio_cert);
		cert = d2i_X509_bio(bio_cert, NULL);
	}
	BIO_free(bio_cert);

	return cert;   
}
Exemplo n.º 6
0
X509 *fileio_read_cert(const char *filename)
{
	X509 *cert = NULL;
	BIO *bio;

	bio = BIO_new_file(filename, "r");
	if (!bio)
		goto out;

	cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);

out:
	BIO_free_all(bio);
	if (!cert) {
		fprintf(stderr, "Can't load certificate from file '%s'\n",
				filename);
		ERR_print_errors_fp(stderr);
	}
	return cert;
}
Exemplo n.º 7
0
static EVP_PKEY *extract_pkey_from_x509(const char *x509_str) {
  X509 *x509 = NULL;
  EVP_PKEY *result = NULL;
  BIO *bio = BIO_new(BIO_s_mem());
  BIO_write(bio, x509_str, strlen(x509_str));
  x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
  if (x509 == NULL) {
    gpr_log(GPR_ERROR, "Unable to parse x509 cert.");
    goto end;
  }
  result = X509_get_pubkey(x509);
  if (result == NULL) {
    gpr_log(GPR_ERROR, "Cannot find public key in X509 cert.");
  }

end:
  BIO_free(bio);
  if (x509 != NULL) X509_free(x509);
  return result;
}
Exemplo n.º 8
0
/**
 * Parses X.509 PEM formatted certificate from file.
 * NB! This struct must be freed using X509_free() function from OpenSSL or
 * with X509_scope struct.
 *
 * @param path PEM formatted X.509 certificate file path.
 * @return returns certificate parsed from file.
 * @throws IOException throws exception if the file does not contain X.509
 *         PEM formatted certificate.
 */
X509* digidoc::X509Cert::loadX509(const std::string& path) throw(IOException)
{
    // Initialize OpenSSL file.
    BIO* file = BIO_new_file(path.c_str(), "rb"); BIO_scope fileScope(&file);
    if(file == NULL)
    {
        THROW_IOEXCEPTION("Failed to open X.509 certificate file '%s': %s",
                path.c_str(), ERR_reason_error_string(ERR_get_error()));
    }

    // Parse X.509 certificate from file.
    X509* cert = PEM_read_bio_X509(file, NULL, NULL, NULL);
    if(cert == NULL)
    {
        THROW_IOEXCEPTION("Failed to load X.509 certificate from file '%s': %s",
                path.c_str(), ERR_reason_error_string(ERR_get_error()));
    }

    return cert;
}
Exemplo n.º 9
0
int
SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type)
{
	int j;
	BIO *in;
	int ret = 0;
	X509 *x = NULL;

	in = BIO_new(BIO_s_file_internal());
	if (in == NULL) {
		SSLerrorx(ERR_R_BUF_LIB);
		goto end;
	}

	if (BIO_read_filename(in, file) <= 0) {
		SSLerrorx(ERR_R_SYS_LIB);
		goto end;
	}
	if (type == SSL_FILETYPE_ASN1) {
		j = ERR_R_ASN1_LIB;
		x = d2i_X509_bio(in, NULL);
	} else if (type == SSL_FILETYPE_PEM) {
		j = ERR_R_PEM_LIB;
		x = PEM_read_bio_X509(in, NULL, ctx->default_passwd_callback,
		    ctx->default_passwd_callback_userdata);
	} else {
		SSLerrorx(SSL_R_BAD_SSL_FILETYPE);
		goto end;
	}

	if (x == NULL) {
		SSLerrorx(j);
		goto end;
	}

	ret = SSL_CTX_use_certificate(ctx, x);
end:
	X509_free(x);
	BIO_free(in);
	return (ret);
}
Exemplo n.º 10
0
Handle<Certificate> Provider_System::getCertFromURI(Handle<std::string> uri, Handle<std::string> format){
	LOGGER_FN();

	try{
		BIO *bioFile = NULL;
		X509 *hcert = NULL;

		LOGGER_OPENSSL(BIO_new);
		bioFile = BIO_new(BIO_s_file());
		LOGGER_OPENSSL(BIO_read_filename);
		if (BIO_read_filename(bioFile, uri->c_str()) > 0){
			LOGGER_OPENSSL(BIO_seek);
			BIO_seek(bioFile, 0);

			if (strcmp(format->c_str(), "PEM") == 0){
				LOGGER_OPENSSL(PEM_read_bio_X509);
				hcert = PEM_read_bio_X509(bioFile, NULL, NULL, NULL);
			}
			else if (strcmp(format->c_str(), "DER") == 0){
				LOGGER_OPENSSL(d2i_X509_bio);
				hcert = d2i_X509_bio(bioFile, NULL);
			}
			else{
				THROW_EXCEPTION(0, Provider_System, NULL, "Unsupported format. Only PEM | DER");
			}
		}

		LOGGER_OPENSSL(BIO_free);
		BIO_free(bioFile);

		if (!hcert){
			THROW_EXCEPTION(0, Provider_System, NULL, "Unable decode cert from PEM/DER");
		}
		else{
			return new Certificate(hcert);
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, Provider_System, e, "Error get certificate from URI");
	}
}
Exemplo n.º 11
0
static int setCertFile(SSL_CTX *ctx, cchar *certFile)
{
    X509    *cert;
    BIO     *bio;
    char    *buf;
    int     rc;

    assert(ctx);
    assert(certFile);

    rc = -1;
    bio = 0;
    buf = 0;
    cert = 0;

    if (ctx == NULL) {
        return rc;
    }
    if ((buf = mprReadPathContents(certFile, NULL)) == 0) {
        mprLog("error openssl", 0, "Unable to read certificate %s", certFile);

    } else if ((bio = BIO_new_mem_buf(buf, -1)) == 0) {
        mprLog("error openssl", 0, "Unable to allocate memory for certificate %s", certFile);

    } else if ((cert = PEM_read_bio_X509(bio, NULL, 0, NULL)) == 0) {
        mprLog("error openssl", 0, "Unable to parse certificate %s", certFile);

    } else if (SSL_CTX_use_certificate(ctx, cert) != 1) {
        mprLog("error openssl", 0, "Unable to use certificate %s", certFile);
        
    } else {
        rc = 0;
    }
    if (bio) {
        BIO_free(bio);
    }
    if (cert) {
        X509_free(cert);
    }
    return rc;
}
Exemplo n.º 12
0
DWORD
DirCliPEMToX509(
    PCSTR  pszCert,
    X509** ppCert
    )
{
    DWORD dwError = 0;
    BIO *pBioMem = NULL;
    X509* pCert = NULL;

    pBioMem = BIO_new_mem_buf((PVOID) pszCert, -1);
    if ( pBioMem == NULL)
    {
        dwError = ERROR_OUTOFMEMORY;
        BAIL_ON_VMAFD_ERROR(dwError);
    }

    pCert  = PEM_read_bio_X509(pBioMem, NULL, NULL, NULL);
    if (pCert  == NULL)
    {
        dwError = ERROR_OPEN_FAILED;
        BAIL_ON_VMAFD_ERROR(dwError);
    }

    *ppCert = pCert;

cleanup:

    if (pBioMem)
    {
        BIO_free(pBioMem);
    }

    return dwError;

error:

    *ppCert = NULL;

    goto cleanup;
}
Exemplo n.º 13
0
static void InitializeDefaultCredentials()
{
	BIO *bio = BIO_new_mem_buf (PrivateMaterials, -1);
	assert (bio);

	if (DefaultPrivateKey) {
		// we may come here in a restart.
		EVP_PKEY_free (DefaultPrivateKey);
		DefaultPrivateKey = NULL;
	}
	PEM_read_bio_PrivateKey (bio, &DefaultPrivateKey, builtin_passwd_cb, 0);

	if (DefaultCertificate) {
		// we may come here in a restart.
		X509_free (DefaultCertificate);
		DefaultCertificate = NULL;
	}
	PEM_read_bio_X509 (bio, &DefaultCertificate, NULL, 0);

	BIO_free (bio);
}
Exemplo n.º 14
0
static X509 *ssl_load_cert(const char *cert_str)
{
    X509 *cert = NULL;
    BIO *in = NULL;
    if (!cert_str) {
        return NULL;
    }

    in = BIO_new_mem_buf((void *)cert_str, -1);

    if (!in) {
        return NULL;
    }

    cert = PEM_read_bio_X509(in, NULL, NULL, NULL);

    if (in) {
        BIO_free(in);
    }
    return cert;
}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
    ERR_load_crypto_strings();
    OpenSSL_add_all_algorithms();
#if !defined(OPENSSL_NO_ENGINE)
    /* Load all compiled-in ENGINEs */
    ENGINE_load_builtin_engines();
    ENGINE_register_all_ciphers();
    ENGINE_register_all_digests();
#endif

    {
        BIO *bio = BIO_new_mem_buf(RSA_CERTIFICATE, strlen(RSA_CERTIFICATE));
        X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
        assert(x509 != NULL || !!"failed to load certificate");
        BIO_free(bio);
        cert.len = i2d_X509(x509, &cert.base);
        X509_free(x509);
    }

    {
        BIO *bio = BIO_new_mem_buf(RSA_PRIVATE_KEY, strlen(RSA_PRIVATE_KEY));
        EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
        assert(pkey != NULL || !"failed to load private key");
        BIO_free(bio);
        ptls_openssl_init_sign_certificate(&cert_signer, pkey);
        EVP_PKEY_free(pkey);
    }

    subtest("next-packet-number", test_next_packet_number);
    subtest("ranges", test_ranges);
    subtest("frame", test_frame);
    subtest("maxsender", test_maxsender);
    subtest("ack", test_ack);
    subtest("simple", test_simple);
    subtest("stream-concurrency", test_stream_concurrency);
    subtest("loss", test_loss);

    return done_testing();
}
Exemplo n.º 16
0
/**
 * Read from a BIO, adding to the x509 store.
 */
static int
X509_STORE_load_bio(X509_STORE *ca_store, BIO *in) {
  int ret = 1;
  X509 *ca;
  int r;
  int found = 0;
  unsigned long err;

  while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {

    r = X509_STORE_add_cert(ca_store, ca);

    if (r == 0) {
      X509_free(ca);
      ret = 0;
      break;
    }

    found++;

    /**
     * The x509 cert object is reference counted by OpenSSL, so the STORE
     * keeps it alive after its been added.
     */
    X509_free(ca);
  }

  /* When the while loop ends, it's usually just EOF. */
  err = ERR_peek_last_error();
  if (found != 0 &&
      ERR_GET_LIB(err) == ERR_LIB_PEM &&
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
    ERR_clear_error();
  } else  {
    /* some real error */
    ret = 0;
  }

  return ret;
}
Exemplo n.º 17
0
X509 *SSL_read_X509(char* filename, X509 **x509, pem_password_cb *cb)
{
    X509 *rc;
    BIO *bioS;
    BIO *bioF;

    /* 1. try PEM (= DER+Base64+headers) */
    if ((bioS=BIO_new_file(filename, "r")) == NULL)
        return NULL;
    rc = PEM_read_bio_X509 (bioS, x509, cb, NULL);
    BIO_free(bioS);

    if (rc == NULL) {
        /* 2. try DER+Base64 */
        if ((bioS=BIO_new_file(filename, "r")) == NULL)
            return NULL;

        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 */
            if ((bioS=BIO_new_file(filename, "r")) == NULL)
                return NULL;
            rc = d2i_X509_bio(bioS, NULL);
            BIO_free(bioS);
        }
    }
    if (rc != NULL && x509 != NULL) {
        if (*x509 != NULL)
            X509_free(*x509);
        *x509 = rc;
    }
    return rc;
}
Exemplo n.º 18
0
/* Loads an in-memory PEM certificate chain into the SSL context. */
static tsi_result ssl_ctx_use_certificate_chain(
    SSL_CTX* context, const unsigned char* pem_cert_chain,
    size_t pem_cert_chain_size) {
  tsi_result result = TSI_OK;
  X509* certificate = NULL;
  BIO* pem = BIO_new_mem_buf((void*)pem_cert_chain, pem_cert_chain_size);
  if (pem == NULL) return TSI_OUT_OF_RESOURCES;

  do {
    certificate = PEM_read_bio_X509_AUX(pem, NULL, NULL, "");
    if (certificate == NULL) {
      result = TSI_INVALID_ARGUMENT;
      break;
    }
    if (!SSL_CTX_use_certificate(context, certificate)) {
      result = TSI_INVALID_ARGUMENT;
      break;
    }
    while (1) {
      X509* certificate_authority = PEM_read_bio_X509(pem, NULL, NULL, "");
      if (certificate_authority == NULL) {
        ERR_clear_error();
        break; /* Done reading. */
      }
      if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
        X509_free(certificate_authority);
        result = TSI_INVALID_ARGUMENT;
        break;
      }
      /* We don't need to free certificate_authority as its ownership has been
         transfered to the context. That is not the case for certificate though.
      */
    }
  } while (0);

  if (certificate != NULL) X509_free(certificate);
  BIO_free(pem);
  return result;
}
	static CURLcode ssl_ctx_function(CURL *curl, void *sslctx, void *parm)
	{
		X509_STORE *store;
		X509 *cert = nullptr;
		BIO *bio;
		
		bio = BIO_new_mem_buf(const_cast<char*>(NinjaParty::Cacerts), -1);
		while((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) != nullptr)
		{
			store = SSL_CTX_get_cert_store(static_cast<SSL_CTX*>(sslctx));

			if(X509_STORE_add_cert(store, cert) == 0)
			{
				// todo: log error adding certificate
				BIO_free(bio);
				return CURLE_SSL_CACERT;
			}
		}
		
		BIO_free(bio);
		return CURLE_OK;
	}
Exemplo n.º 20
0
embassy_t *pki_embassy_load_from_memory(char *certificate, char *privatekey, uint32_t serial)
{
	BIO *bio_memory = NULL;
	embassy_t *embassy;

	// create an empty embassy
	embassy = calloc(1, sizeof(embassy_t));

	// fetch the certificate in PEM format and convert to X509
	bio_memory = BIO_new_mem_buf(certificate, strlen(certificate));
	embassy->certificate = PEM_read_bio_X509(bio_memory, NULL, NULL, NULL);
	BIO_free(bio_memory);

	// fetch the private key in PEM format and convert to EVP
	bio_memory = BIO_new_mem_buf(privatekey, strlen(privatekey));
	embassy->keyring = PEM_read_bio_PrivateKey(bio_memory, NULL, NULL, NULL);
	BIO_free(bio_memory);

	embassy->serial = serial;

	return embassy;
}
Exemplo n.º 21
0
Arquivo: us894.c Projeto: DDvO/libest
/*
 * Null Server certificate private key when initializing server
 */
static void us894_test17 (void)
{
    unsigned char *cacerts = NULL;
    int cacerts_len = 0;
    BIO *certin;
    X509 *x;
    int rv;
    EST_CTX *ctx;

    LOG_FUNC_NM;
    
    /*
     * Read in the CA certificates
     */
    cacerts_len = read_binary_file(US894_CACERT, &cacerts);
    CU_ASSERT(cacerts_len > 0);

    /*
     * Read the server cert
     */
    certin = BIO_new(BIO_s_file_internal());
    rv = BIO_read_filename(certin, US894_SERVER_CERT); 
    CU_ASSERT(rv > 0);
    x = PEM_read_bio_X509(certin, NULL, NULL, NULL);
    CU_ASSERT(x != NULL);
    BIO_free(certin);

    /* 
     * Attempt to init EST proxy using NULL private key
     */
    est_init_logger(EST_LOG_LVL_INFO, NULL);
    ctx = est_proxy_init(cacerts, cacerts_len, cacerts, cacerts_len,
                         EST_CERT_FORMAT_PEM, 
                         "testrealm", x, NULL,
                         "estuser", "estpwd");
    CU_ASSERT(ctx == NULL);

    X509_free(x);
}
Exemplo n.º 22
0
bool cOpenSSLSocket::Init() {
	CRYPTO_malloc_init(); // Initialize malloc, free, etc for OpenSSL's use

	SSL_library_init(); // Initialize OpenSSL's SSL libraries

	SSL_load_error_strings(); // Load SSL error strings

	ERR_load_BIO_strings(); // Load BIO error strings

	OpenSSL_add_all_algorithms(); // Load all available encryption algorithms

	//! Load the certificates and config
	if ( FileSystem::FileExists( cSSLSocket::CertificatesPath ) ) {
		SafeDataPointer data;
		FileSystem::FileGet( cSSLSocket::CertificatesPath, data );

		if ( data.DataSize > 0 ) {
			BIO* mem = BIO_new(BIO_s_mem());

			BIO_puts( mem, (const char*) data.Data );

			while( true ) {
				X509 * cert = PEM_read_bio_X509(mem, NULL, 0, NULL);

				if (!cert)
					break;

				sCerts.push_back(cert);
			}

			BIO_free(mem);
		}

		eePRINTL( "Loaded certs from '%s': %d", cSSLSocket::CertificatesPath.c_str(), (int)sCerts.size() );
	}

	return true;
}
Exemplo n.º 23
0
SISCertificateChain* makeChain(const char* certData, EVP_PKEY** publicKey) {
	BIO* in = BIO_new_mem_buf((void*) certData, -1);
	BIO* out = BIO_new(BIO_s_mem());

	while (true) {
		X509* cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
		if (!cert) {
			unsigned long err = ERR_peek_last_error();
			int lib = ERR_GET_LIB(err);
			int func = ERR_GET_FUNC(err);
			int reason = ERR_GET_REASON(err);
			if (lib == ERR_LIB_PEM && func == PEM_F_PEM_READ_BIO && reason == PEM_R_NO_START_LINE)
				break;
			ERR_print_errors_fp(stderr);
			throw SignBadCert;
		}
		if (!*publicKey)
			*publicKey = X509_PUBKEY_get(X509_get_X509_PUBKEY(cert));
		i2d_X509_bio(out, cert);

		X509_OBJECT obj;
		obj.type = X509_LU_X509;
		obj.data.x509 = cert;
		X509_OBJECT_free_contents(&obj);
	}
	BIO_free_all(in);

	char* ptr;
	long length = BIO_get_mem_data(out, &ptr);
	if (length <= 0) {
		fprintf(stderr, "Bad certificate file\n");
		throw SignBadCert;
	}
	SISBlob* blob = new SISBlob((uint8_t*) ptr, length);
	BIO_free_all(out);

	return new SISCertificateChain(blob);
}
Exemplo n.º 24
0
/*
 * Based on SSL_CTX_use_certificate_file, return an x509 object for the
 * given file.
 */
static int
tls_ctx_read_certificate_file(SSL_CTX *ctx, const char *file, X509 **x509)
{
  int j;
  BIO *in;
  int ret=0;
  X509 *x=NULL;

  in=BIO_new(BIO_s_file_internal());
  if (in == NULL)
    {
      SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_BUF_LIB);
      goto end;
    }

  if (BIO_read_filename(in,file) <= 0)
    {
      SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_SYS_LIB);
      goto end;
    }

  x = PEM_read_bio_X509(in, NULL, ctx->default_passwd_callback,
    ctx->default_passwd_callback_userdata);
  if (x == NULL)
    {
      SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_PEM_LIB);
      goto end;
    }

 end:
  if (in != NULL)
    BIO_free(in);
  if (x509)
    *x509 = x;
  else if (x)
    X509_free (x);
  return(ret);
}
Exemplo n.º 25
0
//Get key from a cert file, return string
std::string get_key_from_certfile(const char* certfile) {
  BIO* certbio = NULL;
  certbio = BIO_new_file(certfile, "r");
  X509* cert = NULL;
  cert = PEM_read_bio_X509(certbio, NULL, NULL, NULL); 
  EVP_PKEY* key = NULL;
  key = X509_get_pubkey(cert);

  BIO* out = NULL;
  out = BIO_new(BIO_s_mem());
  PEM_write_bio_PUBKEY(out, key);

  std::string pubkey_str;
  for(;;) {
    char s[256];
    int l = BIO_read(out,s,sizeof(s));
    if(l <= 0) break;
    pubkey_str.append(s,l);;
  }

  EVP_PKEY_free(key);
  X509_free(cert);
  BIO_free_all(certbio);
  BIO_free_all(out);

  if(!pubkey_str.empty()) {
    std::size_t pos = pubkey_str.find("BEGIN PUBLIC KEY");
    if(pos != std::string::npos) {
      std::size_t pos1 = pubkey_str.find_first_of("---", pos);
      std::size_t pos2 = pubkey_str.find_first_not_of("-", pos1);
      std::size_t pos3 = pubkey_str.find_first_of("---", pos2);
      std::string str = pubkey_str.substr(pos2+1, pos3-pos2-2);
      return str;
    }
    return ("");
  }
  return pubkey_str;
}
Exemplo n.º 26
0
bud_error_t bud_config_load_ca_file(X509_STORE** store, const char* filename) {
  BIO* b;
  X509* x509;
  bud_error_t err;

  b = BIO_new_file(filename, "r");
  if (b == NULL)
    return bud_error_dstr(kBudErrLoadCert, filename);

  x509 = NULL;
  *store = X509_STORE_new();
  if (*store == NULL) {
    err = bud_error_dstr(kBudErrNoMem, "CA store");
    goto fatal;
  }

  while ((x509 = PEM_read_bio_X509(b, NULL, NULL, NULL)) != NULL) {
    if (x509 == NULL) {
      err = bud_error_dstr(kBudErrParseCert, filename);
      goto fatal;
    }

    if (X509_STORE_add_cert(*store, x509) != 1) {
      err = bud_error(kBudErrAddCert);
      goto fatal;
    }
    X509_free(x509);
    x509 = NULL;
  }

  err = bud_ok();

fatal:
  if (x509 != NULL)
    X509_free(x509);
  BIO_free_all(b);
  return bud_ok();
}
Exemplo n.º 27
0
static STACK_OF(X509) *load_certs_from_file(const char *filename)
{
    STACK_OF(X509) *certs;
    BIO *bio;
    X509 *x;

    bio = BIO_new_file(filename, "r");

    if (bio == NULL) {
        return NULL;
    }

    certs = sk_X509_new_null();
    if (certs == NULL) {
        BIO_free(bio);
        return NULL;
    }

    ERR_set_mark();
    do {
        x = PEM_read_bio_X509(bio, NULL, 0, NULL);
        if (x != NULL && !sk_X509_push(certs, x)) {
            sk_X509_pop_free(certs, X509_free);
            BIO_free(bio);
            return NULL;
        } else if (x == NULL) {
            /*
             * We probably just ran out of certs, so ignore any errors
             * generated
             */
            ERR_pop_to_mark();
        }
    } while (x != NULL);

    BIO_free(bio);

    return certs;
}
Exemplo n.º 28
0
static X509 *LoadCert(unsigned char *data, size_t len, CertFormat format)
{
	X509 *x509;
	BIO *bio = BIO_new_mem_buf(data, len);

	if (bio == NULL)
	{
		exit(1);
	}

	if (format == PEM)
	{
		x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
	}
	else
	{
		x509 = d2i_X509_bio(bio, NULL);
	}

	BIO_free(bio);

	return x509;
}
Exemplo n.º 29
0
void Certificate::LoadPem(std::string filename, std::string password)
{
	if(ssl_cert)
	{
		X509_free(ssl_cert);
		ssl_cert = NULL;
	}

	FILE* f = fopen(filename.c_str(), "r");
	if(!f)
		throw BadFile();

	// Get file size
	if(fseek(f, 0, SEEK_END))
		throw BadFile();
	size_t file_size = ftell(f);
	rewind(f);

	// Read the file
	char buf[file_size];
	if(fread(buf, file_size, 1, f) <= 0)
		throw BadFile();
	fclose(f);

	if(file_size > UINT_MAX)
		throw BadFile();

	BIO* raw_cert_bio = BIO_new_mem_buf(buf, (uint32_t)file_size);
	ssl_cert = PEM_read_bio_X509(raw_cert_bio, NULL, NULL, NULL);
	BIO_free(raw_cert_bio);

	if(!ssl_cert)
	{
		std::string str = std::string(ERR_error_string( ERR_get_error(), NULL));
		throw BadCertificate(str);
	}
}
Exemplo n.º 30
0
Arquivo: tcp.c Projeto: yfqian/libsvc
void
tcp_init1(const char *extra_ca, int init_ssl)
{
  if(init_ssl) {
    SSL_library_init();
    SSL_load_error_strings();

    int i, n = CRYPTO_num_locks();
    ssl_locks = malloc(sizeof(pthread_mutex_t) * n);
    for(i = 0; i < n; i++)
      pthread_mutex_init(&ssl_locks[i], NULL);

    CRYPTO_set_locking_callback(ssl_lock_fn);
    CRYPTO_set_id_callback(ssl_tid_fn);
  }

  ssl_ctx = SSL_CTX_new(SSLv23_client_method());

  if(!SSL_CTX_load_verify_locations(ssl_ctx, NULL, "/etc/ssl/certs"))
    exit(1);

  if(extra_ca != NULL) {
    BIO *cbio = BIO_new_mem_buf((char *)extra_ca, -1);
    X509 *cert = PEM_read_bio_X509(cbio, NULL, 0, NULL);
    BIO_free(cbio);

    if(cert == NULL) {
      fprintf(stderr, "Unable to load extra cert\n");
      exit(1);
    }

    X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
    X509_STORE_add_cert(store, cert);
  }

  SSL_CTX_set_verify_depth(ssl_ctx, 3);
}