Exemple #1
2
/*
This function take a user certificate and a private key in x509 format and
convert it into pkcs12 format. This function returns -1 if a problem occurs, 0 otherwise
*/
int convert_x509_to_p12(char *privkey, char *clicert, char *p12cert)
{
	X509      *cert;
        PKCS12    *p12;
        EVP_PKEY  *cert_privkey;
        FILE      *certfile, *keyfile, *p12file;
        int       bytes = 0;

	OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();

        /* Read the private key file */
        if ((cert_privkey = EVP_PKEY_new()) == NULL){
                printf("Error creating EVP_PKEY structure.\n");
		return -1;
	}
        if (! (keyfile = fopen(privkey, "r"))){
                printf("Error cant read certificate private key file.\n");
		return -1;
	}
        if (! (cert_privkey = PEM_read_PrivateKey(keyfile, NULL, NULL, NULL))){
                printf("Error loading certificate private key content.\n");
		return -1;
	}
        fclose(keyfile);

        /* Read the user certificate */
        if (! (certfile = fopen(clicert, "r"))){
                printf("Error cant read certificate file.\n");
		return -1;
	}
        if (! (cert = PEM_read_X509(certfile, NULL, NULL, NULL))){
                printf("Error loading cert into memory.\n");
		return -1;
	}
        fclose(certfile);

        /* Generate the p12 certificate */
        if ((p12 = PKCS12_new()) == NULL){
                printf("Error creating PKCS12 structure.\n");
		return -1;}
        p12 = PKCS12_create(NULL, NULL, cert_privkey, cert, NULL, 0, 0, 0, 0, 0);
        if ( p12 == NULL){
                printf("Error generating a valid PKCS12 certificate.\n");
		return -1;
	}
        if (! (p12file = fopen(p12cert, "w"))){
                printf("Error cant open pkcs12 certificate file for writing.\n");
		return -1;
	}
	bytes = i2d_PKCS12_fp(p12file, p12);
        if (bytes <= 0){
                printf("Error writing PKCS12 certificate.\n");
		return -1;
	}
        fclose(p12file);
        PKCS12_free(p12);
	X509_free(cert);
	EVP_PKEY_free(cert_privkey);

	return 0;
}
Exemple #2
0
SM_MEDIA_HANDLE Flash2AppSMGenerateHashOpen(void)
{
	SM_MEDIA_HANDLE h;

	h = (SM_MEDIA_HANDLE)malloc(sizeof(*h));
	if (h)
	{
		/* Just load the crypto library error strings,
		* SSL_load_error_strings() loads the crypto AND the SSL ones */
		/* SSL_load_error_strings();*/
		//ERR_load_crypto_strings();

		{
			FILE* fp;

			/* Read private key */
			fp = fopen(KEYF, "r");
			if (fp == NULL)
			{
				printf("error opening keyfile\n");
				free(h);
				return NULL;
			}

			h->pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
			fclose(fp);
		}


		if (h->pkey == NULL)
		{
			printf("error reading key\n");
			free(h);
			return NULL;
		}

		/* Do the signature */

		EVP_SignInit(&h->md_ctx, SM_HASH_FUNCTION);
	}

	return h;
}
Exemple #3
0
VALUE
ossl_pkey_new_from_file(VALUE filename)
{
    FILE *fp;
    EVP_PKEY *pkey;

    SafeStringValue(filename);
    if (!(fp = fopen(RSTRING_PTR(filename), "r"))) {
	ossl_raise(ePKeyError, "%s", strerror(errno));
    }

    pkey = PEM_read_PrivateKey(fp, NULL, ossl_pem_passwd_cb, NULL);
    fclose(fp);
    if (!pkey) {
	ossl_raise(ePKeyError, NULL);
    }

    return ossl_pkey_new(pkey);
}
Exemple #4
0
extern void *
crypto_read_private_key(const char *path)
{
	FILE     *fp = NULL;
	EVP_PKEY *pk = NULL;

	xassert(path != NULL);

	if (!(fp = fopen(path, "r")))
		return NULL;

	if (!PEM_read_PrivateKey(fp, &pk, NULL, NULL)) {
		fclose(fp);
		return NULL;
	}
	fclose(fp);

	return (void *) pk;
}
void signMessage(int message, char* keyfile, unsigned char* signature) {
	int err;
	unsigned int sig_len;
	static char data[100];
	EVP_MD_CTX md_ctx;
	EVP_PKEY* pkey;
	FILE * fp;
	X509 * x509;
	memset(&data, '\0', sizeof(data));
	sprintf(data, "%d", message);
	ERR_load_crypto_strings();
	/* Read private key */
	fp = fopen(keyfile, "r");
	if (fp == NULL) {
		perror("File error");
		printf("Key file not found\n");
		exit(1);
	}
	pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
	fclose(fp);

	if (pkey == NULL) {
		printf("Error in claiming private key\n");
		ERR_print_errors_fp (stderr);
		exit(1);
	}

	/* Do the signature */

	EVP_SignInit(&md_ctx, EVP_sha1());
	EVP_SignUpdate(&md_ctx, data, strlen(data));
	sig_len = sizeof(signature);
	err = EVP_SignFinal(&md_ctx, signature, &sig_len, pkey);
	if (err != 1) {
		printf("Error in signing\n");
		ERR_print_errors_fp(stderr);
		exit(1);
	}

	EVP_PKEY_free(pkey);

}
Exemple #6
0
bool SSL_CTX_use_PrivateKey_file(::SSL_CTX* ctx, const char* file, int /*type*/)
{
	FILE* f = dcpp_fopen(file, "r");
	if (!f)
	{
		return false;
	}
	
	::EVP_PKEY* tmpKey = nullptr;
	PEM_read_PrivateKey(f, &tmpKey, nullptr, nullptr);
	fclose(f);
	
	if (!tmpKey)
	{
		return false;
	}
	EVP_PKEY key(tmpKey);
	
	return SSL_CTX_use_PrivateKey(ctx, key) == SSL_SUCCESS;
}
Exemple #7
0
static int janus_dtls_load_keys(const char *server_pem, const char *server_key, const char *password,
		X509 **certificate, EVP_PKEY **private_key) {
	FILE *f = NULL;

	f = fopen(server_pem, "r");
	if(!f) {
		JANUS_LOG(LOG_FATAL, "Error opening certificate file\n");
		goto error;
	}
	*certificate = PEM_read_X509(f, NULL, NULL, NULL);
	if(!*certificate) {
		JANUS_LOG(LOG_FATAL, "PEM_read_X509 failed\n");
		goto error;
	}
	fclose(f);

	f = fopen(server_key, "r");
	if(!f) {
		JANUS_LOG(LOG_FATAL, "Error opening key file\n");
		goto error;
	}
	*private_key = PEM_read_PrivateKey(f, NULL, NULL, (void *)password);
	if(!*private_key) {
		JANUS_LOG(LOG_FATAL, "PEM_read_PrivateKey failed\n");
		goto error;
	}
	fclose(f);

	return 0;

error:
	if(*certificate) {
		X509_free(*certificate);
		*certificate = NULL;
	}
	if(*private_key) {
		EVP_PKEY_free(*private_key);
		*private_key = NULL;
	}
	return -1;
}
Exemple #8
0
int __fastcall util_from_pem(char* filename, struct util_cert* cert)
{
	FILE *pFile = NULL;

	if (filename == NULL) return -1;
	#ifdef WIN32 
		fopen_s(&pFile, filename,"rb");
	#else
		pFile = fopen(filename,"rb");
	#endif
	if (pFile == NULL) goto error;

	if ((cert->pkey = PEM_read_PrivateKey(pFile, NULL, 0, NULL)) == NULL) goto error;
	if ((cert->x509 = PEM_read_X509(pFile, NULL, 0, NULL)) == NULL) goto error;

	fclose(pFile);
	return 0;
error:
	if (pFile != NULL) fclose(pFile);
	return -1;
}
/* This function signs the buffer passed as argument, returns the length of the signature
 * else -1 on error
 * It leaves the sign in **sign_buf (which is allocated)
 */
int sign_hello(unsigned char* hello_buf,unsigned int hello_len,unsigned char** sign_buf){
	EVP_MD_CTX* ctx = NULL;
	unsigned int sign_len;
	EVP_PKEY* evp = EVP_PKEY_new();
	FILE* fp;
	*sign_buf = NULL;
	ctx = (EVP_MD_CTX*)calloc(1,sizeof(EVP_MD_CTX));
	EVP_MD_CTX_init(ctx);
	OpenSSL_add_all_algorithms();
	if((fp=fopen(PRIV_KEY,"r"))==NULL){
		goto fail;
	}
	if((evp=PEM_read_PrivateKey(fp,NULL,NULL,NULL))==NULL){
		goto fail;
	}
	*sign_buf = (unsigned char*)calloc(1,EVP_PKEY_size(evp));
   	if(EVP_SignInit(ctx,EVP_sha512())==0){
		goto fail;
	}
	if(EVP_SignUpdate(ctx,hello_buf,hello_len)==0){
		goto fail;
	}
	if(EVP_SignFinal(ctx,*sign_buf,&sign_len,evp)==0){
		goto fail;
	}
	
	EVP_MD_CTX_cleanup(ctx);
	free(ctx);
	EVP_PKEY_free(evp);
	return sign_len;
    
fail:
	EVP_MD_CTX_cleanup(ctx); 
	free(ctx);
	if (*sign_buf != NULL) {
		free(*sign_buf);
	}
	return -1;
}
Exemple #10
0
	void DtlsTransport::ReadCertificateAndPrivateKeyFromFiles()
	{
		MS_TRACE();

		FILE* file = nullptr;

		file = fopen(Settings::configuration.dtlsCertificateFile.c_str(), "r");
		if (!file)
		{
			MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno));
			goto error;
		}
		DtlsTransport::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
		if (!DtlsTransport::certificate)
		{
			LOG_OPENSSL_ERROR("PEM_read_X509() failed");
			goto error;
		}
		fclose(file);

		file = fopen(Settings::configuration.dtlsPrivateKeyFile.c_str(), "r");
		if (!file)
		{
			MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno));
			goto error;
		}
		DtlsTransport::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
		if (!DtlsTransport::privateKey)
		{
			LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed");
			goto error;
		}
		fclose(file);

		return;

	error:
		MS_THROW_ERROR("error reading DTLS certificate and private key PEM files");
	}
BOOL readCertificateHome(unsigned long hash, X509 **x509, EVP_PKEY **pkey)
{
    FILE * fcrt = NULL;
    FILE * fkey = NULL;
    bool result = false;

    char *buf1 = new char[4096];
    char *buf2 = new char[4096];
    if (! buf1 && buf2)
        return false;

    char* dir = get_current_dir_name();
    if(dir) {
        snprintf(buf1, 4095, "%s/.mDolphin/certs/%lx.%s", dir, hash, "crt");
        snprintf(buf2, 4095, "%s/.mDolphin/certs/%lx.%s", dir, hash, "key");
        free(dir);

        fcrt = fopen(buf1, "r");
        fkey = fopen(buf2, "r");
        if (fcrt == NULL || fkey == NULL){
            printf("No certificate or private key file!\n");
            goto err;
        } 

        if (PEM_read_X509(fcrt, x509, NULL, NULL) && PEM_read_PrivateKey(fkey, pkey, NULL, NULL))
            result = true;
        else
            ERR_clear_error();
err: 
        if (fcrt)  
            fclose(fcrt);
        if (fkey)  
            fclose(fkey);
    }
    delete[] buf1;
    delete[] buf2;
    return result;
}
Exemple #12
0
/* Reads in a private key from a PEM file. */
int read_key(EVP_PKEY **key, const char *filename, char *passwd)
{
	EVP_PKEY *k = NULL;
	FILE *fp = NULL;

	if (key == NULL)
		return OPENSSLCA_ERR_ARGS;

	fp = fopen(filename, "r");
	if (fp == NULL)
		return OPENSSLCA_ERR_KEY_OPEN;

	k = PEM_read_PrivateKey(fp, NULL, NULL, passwd);
	if (k == NULL) {
		fclose(fp);
		return OPENSSLCA_ERR_KEY_READ;
	}

	*key = k;
	fclose(fp);

	return OPENSSLCA_NO_ERR;
}
uint32 CRegProtocol::GetPublicKey(char *Name, 
                                EVP_PKEY **key)
{
    TU_RET err;
    FILE *fp;

    err = TU_ERROR_CRYPTO_FAILED;

    fp = fopen(NAME_BUF, "r");
    if(!fp)
    {
        err = TU_ERROR_FILEOPEN;
        goto EXIT;
    }

    if(!(*key = PEM_read_PUBKEY(fp, NULL, NULL, NULL)))
    {
        ERR_print_errors_fp(stdout);
        //If we can't read the Public key, try reading the pvt key. 
        //The above function might give an error if we use it to 
        //read a private key file
        rewind(fp);
        if(!(*key = PEM_read_PrivateKey(fp, NULL, NULL, NULL)))
        {
            ERR_print_errors_fp(stdout);
            goto EXIT_FILE;
        }
   }

    err = TU_SUCCESS;
    
EXIT_FILE:
    if(fp)
        fclose(fp);
EXIT:
    return err;
}
Exemple #14
0
static Eina_Bool
_ecore_con_ssl_server_privkey_add_openssl(Ecore_Con_Server *svr,
                                          const char       *key_file)
{
   FILE *fp = NULL;
   EVP_PKEY *privkey = NULL;

   if (!(fp = fopen(key_file, "r")))
     goto error;

   SSL_ERROR_CHECK_GOTO_ERROR(!(privkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL)));

   fclose(fp);
   SSL_ERROR_CHECK_GOTO_ERROR(SSL_CTX_use_PrivateKey(svr->ssl_ctx, privkey) < 1);
   SSL_ERROR_CHECK_GOTO_ERROR(SSL_CTX_check_private_key(svr->ssl_ctx) < 1);

   return EINA_TRUE;

error:
   if (fp)
     fclose(fp);
   _openssl_print_errors();
   return EINA_FALSE;
}
Exemple #15
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);
}
Exemple #16
0
int main(int argc, char **argv)
{
	FILE *fp;
	EVP_PKEY *pkey;
	X509 *cert;
	PKCS12 *p12;
	if (argc != 5) {
		fprintf(stderr, "Usage: pkwrite infile password name p12file\n");
		exit(1);
	}
	SSLeay_add_all_algorithms();
	ERR_load_crypto_strings();
	if (!(fp = fopen(argv[1], "r"))) {
		fprintf(stderr, "Error opening file %s\n", argv[1]);
		exit(1);
	}
	cert = PEM_read_X509(fp, NULL, NULL, NULL);
	rewind(fp);
	pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
	fclose(fp);
	p12 = PKCS12_create(argv[2], argv[3], pkey, cert, NULL, 0,0,0,0,0);
	if(!p12) {
		fprintf(stderr, "Error creating PKCS#12 structure\n");
		ERR_print_errors_fp(stderr);
		exit(1);
	}
	if (!(fp = fopen(argv[4], "wb"))) {
		fprintf(stderr, "Error opening file %s\n", argv[1]);
		ERR_print_errors_fp(stderr);
		exit(1);
	}
	i2d_PKCS12_fp(fp, p12);
	PKCS12_free(p12);
	fclose(fp);
	return 0;
}
char *uwsgi_rsa_sign(char *algo_key, char *message, size_t message_len, unsigned int *s_len) {

        // openssl could not be initialized
        if (!uwsgi.ssl_initialized) {
                uwsgi_ssl_init();
        }

        *s_len = 0;
        EVP_PKEY *pk = NULL;

        char *algo = uwsgi_str(algo_key);
        char *colon = strchr(algo, ':');
        if (!colon) {
                uwsgi_log("invalid RSA signature syntax, must be: <digest>:<pemfile>\n");
                free(algo);
                return NULL;
        }

        *colon = 0;
        char *keyfile = colon + 1;
        char *signature = NULL;

        FILE *kf = fopen(keyfile, "r");
        if (!kf) {
                uwsgi_error_open(keyfile);
                free(algo);
                return NULL;
        }

        if (PEM_read_PrivateKey(kf, &pk, NULL, NULL) == 0) {
                uwsgi_log("unable to load private key: %s\n", keyfile);
                free(algo);
                fclose(kf);
                return NULL;
        }

        fclose(kf);

        EVP_MD_CTX *ctx = EVP_MD_CTX_create();
        if (!ctx) {
                free(algo);
                EVP_PKEY_free(pk);
                return NULL;
        }

        const EVP_MD *md = EVP_get_digestbyname(algo);
        if (!md) {
                uwsgi_log("unknown digest algo: %s\n", algo);
                free(algo);
                EVP_PKEY_free(pk);
                EVP_MD_CTX_destroy(ctx);
                return NULL;
        }

        *s_len = EVP_PKEY_size(pk);
        signature = uwsgi_malloc(*s_len);

	if (EVP_SignInit_ex(ctx, md, NULL) == 0) {
                ERR_print_errors_fp(stderr);
                free(signature);
                signature = NULL;
                *s_len = 0;
                goto clear;
        }

        if (EVP_SignUpdate(ctx, message, message_len) == 0) {
                ERR_print_errors_fp(stderr);
                free(signature);
                signature = NULL;
                *s_len = 0;
                goto clear;
        }


        if (EVP_SignFinal(ctx, (unsigned char *) signature, s_len, pk) == 0) {
                ERR_print_errors_fp(stderr);
                free(signature);
                signature = NULL;
                *s_len = 0;
                goto clear;
        }

clear:
        free(algo);
        EVP_PKEY_free(pk);
        EVP_MD_CTX_destroy(ctx);
        return signature;

}
Exemple #18
0
int main()
{
    int err;
    int sig_len;
    unsigned char sig_buf[4096];
    static char certfile[] = "cert.pem";
    static char keyfile[] = "key.pem";
    static char data[] = "I owe you...";
    EVP_MD_CTX md_ctx;
    EVP_PKEY *pkey;
    FILE *fp;
    X509 *x509;

    /*
     * Just load the crypto library error strings, SSL_load_error_strings()
     * loads the crypto AND the SSL ones
     */
    /* SSL_load_error_strings(); */
    ERR_load_crypto_strings();

    /* Read private key */

    fp = fopen(keyfile, "r");
    if (fp == NULL)
        exit(1);
    pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
    fclose(fp);

    if (pkey == NULL) {
        ERR_print_errors_fp(stderr);
        exit(1);
    }

    /* Do the signature */

    EVP_SignInit(&md_ctx, EVP_sha1());
    EVP_SignUpdate(&md_ctx, data, strlen(data));
    sig_len = sizeof(sig_buf);
    err = EVP_SignFinal(&md_ctx, sig_buf, &sig_len, pkey);

    if (err != 1) {
        ERR_print_errors_fp(stderr);
        exit(1);
    }

    EVP_PKEY_free(pkey);

    /* Read public key */

    fp = fopen(certfile, "r");
    if (fp == NULL)
        exit(1);
    x509 = PEM_read_X509(fp, NULL, NULL, NULL);
    fclose(fp);

    if (x509 == NULL) {
        ERR_print_errors_fp(stderr);
        exit(1);
    }

    /* Get public key - eay */
    pkey = X509_get_pubkey(x509);
    if (pkey == NULL) {
        ERR_print_errors_fp(stderr);
        exit(1);
    }

    /* Verify the signature */

    EVP_VerifyInit(&md_ctx, EVP_sha1());
    EVP_VerifyUpdate(&md_ctx, data, strlen((char *)data));
    err = EVP_VerifyFinal(&md_ctx, sig_buf, sig_len, pkey);
    EVP_PKEY_free(pkey);

    if (err != 1) {
        ERR_print_errors_fp(stderr);
        exit(1);
    }
    printf("Signature Verified Ok.\n");
    return (0);
}
Exemple #19
0
/** Try to read the identity key from <b>identity_key_file</b>.  If no such
 * file exists and create_identity_key is set, make a new identity key and
 * store it.  Return 0 on success, nonzero on failure.
 */
static int
load_identity_key(void)
{
  file_status_t status = file_status(identity_key_file);
  FILE *f;

  if (make_new_id) {
    open_file_t *open_file = NULL;
    RSA *key;
    if (status != FN_NOENT) {
      log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
              "already exists.", identity_key_file);
      return 1;
    }
    log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
               IDENTITY_KEY_BITS);
    if (!(key = generate_key(IDENTITY_KEY_BITS))) {
      log_err(LD_GENERAL, "Couldn't generate identity key.");
      crypto_log_errors(LOG_ERR, "Generating identity key");
      return 1;
    }
    identity_key = EVP_PKEY_new();
    if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
      log_err(LD_GENERAL, "Couldn't assign identity key.");
      return 1;
    }

    if (!(f = start_writing_to_stdio_file(identity_key_file,
                                          OPEN_FLAGS_REPLACE | O_TEXT, 0400,
                                          &open_file)))
      return 1;

    /* Write the key to the file.  If passphrase is not set, takes it from
     * the terminal. */
    if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
                                       NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
                                       passphrase, (int)passphrase_len,
                                       NULL, NULL)) {
      log_err(LD_GENERAL, "Couldn't write identity key to %s",
              identity_key_file);
      crypto_log_errors(LOG_ERR, "Writing identity key");
      abort_writing_to_file(open_file);
      return 1;
    }
    finish_writing_to_file(open_file);
  } else {
    if (status != FN_FILE) {
      log_err(LD_GENERAL,
              "No identity key found in %s.  To specify a location "
              "for an identity key, use -i.  To generate a new identity key, "
              "use --create-identity-key.", identity_key_file);
      return 1;
    }

    if (!(f = fopen(identity_key_file, "r"))) {
      log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
              identity_key_file, strerror(errno));
      return 1;
    }

    /* Read the key.  If passphrase is not set, takes it from the terminal. */
    identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
    if (!identity_key) {
      log_err(LD_GENERAL, "Couldn't read identity key from %s",
              identity_key_file);
      return 1;
    }
    fclose(f);
  }
  return 0;
}
Exemple #20
0
int
read_key_pem(FILE *fp, PyObject **py_private_key_ndn,
             PyObject **py_public_key_ndn, PyObject **py_public_key_digest,
             int *public_key_digest_len,
             char *password)
{
        struct ndn_pkey *private_key = NULL;
	PyObject *py_private_key = NULL, *py_public_key = NULL;
	unsigned long err, reason;
	fpos_t fpos;
	int r;
	int public_only;

	r = fgetpos(fp, &fpos);
	JUMP_IF_NEG(r, errno_error);

        private_key = (struct ndn_pkey *)PEM_read_PrivateKey(fp, NULL, NULL, password);
	if (private_key) {
		public_only = 0;
		goto success;
	}

	err = ERR_get_error();
	reason = ERR_GET_REASON(err);

	/* 108 was meaning that start line isn't recognized */
	if (reason == 108) {
		r = fsetpos(fp, &fpos);
		JUMP_IF_NEG(r, errno_error);

		private_key = (struct ndn_pkey *)PEM_read_PUBKEY (fp, NULL, NULL, NULL);
		if (private_key) {
			public_only = 1;
			goto success;
		}

		err = ERR_get_error();
		reason = ERR_GET_REASON(err);
	}

	{
		char buf[256];

		ERR_error_string_n(err, buf, sizeof(buf));
		PyErr_Format(g_PyExc_NDNKeyError, "Unable to read Private Key: %s",
				buf);
		goto error;
	}

success:

	r = ndn_keypair(public_only, private_key, py_private_key_ndn,
			py_public_key_ndn);
	JUMP_IF_NEG(r, error);

	r = create_public_key_digest(private_key, py_public_key_digest,
			public_key_digest_len);
	JUMP_IF_NEG(r, error);

	return 0;

errno_error:
	PyErr_SetFromErrno(PyExc_IOError);
error:
	Py_XDECREF(py_private_key);
	Py_XDECREF(py_public_key);
	if (private_key)
		EVP_PKEY_free((EVP_PKEY *)private_key);
	return -1;
}
Exemple #21
0
static int ctx_set_cert(SSL_CTX *ctx, const char *cert, const char *key)
{
    FILE *fp = NULL;
    X509 *x509 = NULL;
    EVP_PKEY *pkey = NULL;
    int toret = 0;              /* Assume an error */

    /* cert */
    if (cert) {
        if ((fp = fopen(cert, "r")) == NULL) {
            fprintf(stderr, "Error opening cert file '%s'\n", cert);
            goto err;
        }
        if (!PEM_read_X509(fp, &x509, NULL, NULL)) {
            fprintf(stderr, "Error reading PEM cert from '%s'\n", cert);
            goto err;
        }
        if (!SSL_CTX_use_certificate(ctx, x509)) {
            fprintf(stderr, "Error, cert in '%s' can not be used\n", cert);
            goto err;
        }
        /* Clear the FILE* for reuse in the "key" code */
        fclose(fp);
        fp = NULL;
        fprintf(stderr, "Info, operating with cert in '%s'\n", cert);
        /*
         * If a cert was given without matching key, we assume the same file
         * contains the required key.
         */
        if (!key)
            key = cert;
    } else {
        if (key)
            fprintf(stderr, "Error, can't specify a key without a "
                    "corresponding certificate\n");
        else
            fprintf(stderr, "Error, ctx_set_cert called with " "NULLs!\n");
        goto err;
    }
    /* key */
    if (key) {
        if ((fp = fopen(key, "r")) == NULL) {
            fprintf(stderr, "Error opening key file '%s'\n", key);
            goto err;
        }
        if (!PEM_read_PrivateKey(fp, &pkey, NULL, NULL)) {
            fprintf(stderr, "Error reading PEM key from '%s'\n", key);
            goto err;
        }
        if (!SSL_CTX_use_PrivateKey(ctx, pkey)) {
            fprintf(stderr, "Error, key in '%s' can not be used\n", key);
            goto err;
        }
        fprintf(stderr, "Info, operating with key in '%s'\n", key);
    } else
        fprintf(stderr, "Info, operating without a cert or key\n");
    /* Success */
    toret = 1;
 err:
    if (x509)
        X509_free(x509);
    if (pkey)
        EVP_PKEY_free(pkey);
    if (fp)
        fclose(fp);
    return toret;
}
Exemple #22
0
/* ChangePasswordPEM() returns:
 * -1 Wrong password
 * 0  Changing password failed for unknown reason
 * 1  Password changed successfully
 */
int ChangePasswordPEM(HWND hwndDlg)
{
  char keyfile[MAX_PATH];
  char oldpsw[50];
  char newpsw[50];
  WCHAR oldpsw_unicode[50];
  WCHAR newpsw_unicode[50];
  FILE *fp;

  EVP_PKEY *privkey;
 
  /* Get filename, old_psw and new_psw from Dialog */
  GetDlgItemText(hwndDlg, TEXT_KEYFILE, keyfile, sizeof(keyfile) - 1); 
  GetDlgItemTextW(hwndDlg, EDIT_PSW_CURRENT, oldpsw_unicode, sizeof(oldpsw_unicode)/2 - 1); 
  GetDlgItemTextW(hwndDlg, EDIT_PSW_NEW, newpsw_unicode, sizeof(newpsw_unicode)/2 - 1); 

  /* Convert Unicode to ASCII (CP850) */
  ConvertUnicode2Ascii(oldpsw_unicode, oldpsw, sizeof(oldpsw));
  if (!ConvertUnicode2Ascii(newpsw_unicode, newpsw, sizeof(newpsw)))
    {
      ShowLocalizedMsg(GUI_NAME, ERR_INVALID_CHARS_IN_PSW, "");
      return(-1);
    }

  privkey = EVP_PKEY_new();

  /* Open old keyfile for reading */
  if (! (fp = fopen (keyfile, "r")))
    {
      /* can't open key file */
      ShowLocalizedMsg(GUI_NAME, ERR_OPEN_PRIVATE_KEY_FILE, keyfile);
      return(0);
    }

  /* Import old key */
  if (! (privkey = PEM_read_PrivateKey (fp, NULL, NULL, oldpsw)))
    {
      /* wrong password */
      ShowLocalizedMsg(GUI_NAME, ERR_OLD_PWD_INCORRECT, ""); 
      fclose(fp);
      return(-1);
    }

  fclose(fp);

  /* Open keyfile for writing */
  if (! (fp = fopen (keyfile, "w")))
    {
      /* can't open file rw */
      ShowLocalizedMsg(GUI_NAME, ERR_OPEN_WRITE_KEY, keyfile);
      EVP_PKEY_free(privkey);
      return(0);
    }
 
  /* Write new key to file */
  if (strlen(newpsw) == 0)
    {
      /* No passphrase */
      if ( !(PEM_write_PrivateKey(fp, privkey, \
                                  NULL, NULL,          /* Use NO encryption */
                                  0, 0, NULL)))
        {
          /* error writing new key */
          ShowLocalizedMsg(GUI_NAME, ERR_WRITE_NEW_KEY, keyfile);
          EVP_PKEY_free(privkey);
          fclose(fp);
          return(0);
        }
    }
  else
    {
      /* Use passphrase */
      if ( !(PEM_write_PrivateKey(fp, privkey, \
                                  EVP_des_ede3_cbc(),  /* Use 3DES encryption */
                                  newpsw, (int) strlen(newpsw), 0, NULL)))
        {
          /* can't write new key */
          ShowLocalizedMsg(GUI_NAME, ERR_WRITE_NEW_KEY, keyfile);
          EVP_PKEY_free(privkey);
          fclose(fp);
          return(0);
        }
    }

  EVP_PKEY_free(privkey);
  fclose(fp);

  /* signal success to user */
  ShowLocalizedMsg(GUI_NAME, INFO_PWD_CHANGED, "");
  return(1);
}
Exemple #23
0
int
easy_pkcs7_sign(const char *content, size_t len,
    char **signature, size_t *signature_len,
    const char *key_file, const char *cert_file)
{
	FILE *f;
	X509 *certificate;
	STACK_OF(X509) *c, *cert_chain;
	EVP_PKEY *private_key;
	char *tmp_sig;
	BIO *out, *in;
	PKCS7 *p7;
	int status;

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();

	status = -1;
	private_key = NULL;
	cert_chain = NULL;
	in = NULL;

	c = file_to_certs(cert_file);

	if (sk_X509_num(c) != 1) {
		warnx("More then one certificate in the certificate file");
		goto cleanup;
	}
	certificate = sk_X509_value(c, 0);

	/* Compute ex_kusage */
	X509_check_purpose(certificate, -1, 0);

	if (check_ca(certificate)) {
		warnx("CA keys are not valid for signatures");
		goto cleanup;
	}

	if (certificate->ex_xkusage != pkg_key_usage) {
		warnx("Certificate must have CODE SIGNING "
		    "and EMAIL PROTECTION property");
		goto cleanup;
	}

	if (cert_chain_file)
		cert_chain = file_to_certs(cert_chain_file);

	if ((f = fopen(key_file, "r")) == NULL) {
		warn("Failed to open private key file %s", key_file);
		goto cleanup;
	}
	private_key = PEM_read_PrivateKey(f, NULL, ssl_pass_cb, NULL);
	fclose(f);
	if (private_key == NULL) {
		warnx("Can't read private key: %s", key_file);
		goto cleanup;
	}

	if (X509_check_private_key(certificate, private_key) != 1) {
		warnx("The private key %s doesn't match the certificate %s",
		    key_file, cert_file);
		goto cleanup;
	}

	in = BIO_new_mem_buf(__UNCONST(content), len);

	p7 = PKCS7_sign(certificate, private_key, cert_chain, in, 
	    PKCS7_DETACHED|PKCS7_NOATTR|PKCS7_BINARY);
	if (p7 == NULL) {
		warnx("Failed to create signature structure");
		goto cleanup;
	}

	out = BIO_new(BIO_s_mem());
	PEM_write_bio_PKCS7(out, p7);
	*signature_len = BIO_get_mem_data(out, &tmp_sig);
	*signature = xmalloc(*signature_len);
	memcpy(*signature, tmp_sig, *signature_len);
	BIO_free_all(out);

	PKCS7_free(p7);

	status = 0;

cleanup:
	sk_X509_free(c);
	sk_X509_free(cert_chain);
	EVP_PKEY_free(private_key);
	BIO_free(in);

	return status;
}
Exemple #24
0
EAPI Eet_Key *
eet_identity_open(const char               *certificate_file,
                  const char               *private_key_file,
                  Eet_Key_Password_Callback cb)
{
#ifdef HAVE_SIGNATURE
   /* Signature declarations */
   Eet_Key *key = NULL;
# ifdef HAVE_GNUTLS
   /* Gnutls private declarations */
   Eina_File *f = NULL;
   void *data = NULL;
   gnutls_datum_t load_file = { NULL, 0 };
   char pass[1024];

   if (!emile_cipher_init()) return NULL;

   /* Init */
   if (!(key = malloc(sizeof(Eet_Key))))
     goto on_error;

   key->references = 1;

   if (gnutls_x509_crt_init(&(key->certificate)))
     goto on_error;

   if (gnutls_x509_privkey_init(&(key->private_key)))
     goto on_error;

   /* Mmap certificate_file */
   f = eina_file_open(certificate_file, 0);
   if (!f)
     goto on_error;

   /* let's make mmap safe and just get 0 pages for IO erro */
   eina_mmap_safety_enabled_set(EINA_TRUE);

   data = eina_file_map_all(f, EINA_FILE_SEQUENTIAL);
   if (!data) goto on_error;

   /* Import the certificate in Eet_Key structure */
   load_file.data = data;
   load_file.size = eina_file_size_get(f);
   if (gnutls_x509_crt_import(key->certificate, &load_file,
                              GNUTLS_X509_FMT_PEM) < 0)
     goto on_error;

   eina_file_map_free(f, data);

   /* Reset values */
   eina_file_close(f);
   f = NULL;
   data = NULL;
   load_file.data = NULL;
   load_file.size = 0;

   /* Mmap private_key_file */
   f = eina_file_open(private_key_file, 0);
   if (!f)
     goto on_error;

   /* let's make mmap safe and just get 0 pages for IO erro */
   eina_mmap_safety_enabled_set(EINA_TRUE);

   data = eina_file_map_all(f, EINA_FILE_SEQUENTIAL);
   if (!data)
     goto on_error;

   /* Import the private key in Eet_Key structure */
   load_file.data = data;
   load_file.size = eina_file_size_get(f);
   /* Try to directly import the PEM encoded private key */
   if (gnutls_x509_privkey_import(key->private_key, &load_file,
                                  GNUTLS_X509_FMT_PEM) < 0)
     {
        /* Else ask for the private key pass */
         if (cb && cb(pass, 1024, 0, NULL))
           {
     /* If pass then try to decode the pkcs 8 private key */
               if (gnutls_x509_privkey_import_pkcs8(key->private_key, &load_file,
                                                    GNUTLS_X509_FMT_PEM, pass, 0))
                 goto on_error;
           }
         else
         /* Else try to import the pkcs 8 private key without pass */
         if (gnutls_x509_privkey_import_pkcs8(key->private_key, &load_file,
                                              GNUTLS_X509_FMT_PEM, NULL, 1))
           goto on_error;
     }

   eina_file_map_free(f, data);
   eina_file_close(f);

   return key;

on_error:
   if (data) eina_file_map_free(f, data);
   if (f) eina_file_close(f);

   if (key)
     {
        if (key->certificate)
          gnutls_x509_crt_deinit(key->certificate);

        if (key->private_key)
          gnutls_x509_privkey_deinit(key->private_key);

        free(key);
     }

# else /* ifdef HAVE_GNUTLS */
   /* Openssl private declarations */
   FILE *fp;
   EVP_PKEY *pkey = NULL;
   X509 *cert = NULL;

   if (!emile_cipher_init()) return NULL;

   /* Load the X509 certificate in memory. */
   fp = fopen(certificate_file, "rb");
   if (!fp)
     return NULL;

   cert = PEM_read_X509(fp, NULL, NULL, NULL);
   fclose(fp);
   if (!cert)
     goto on_error;

   /* Check the presence of the public key. Just in case. */
   pkey = X509_get_pubkey(cert);
   if (!pkey)
     goto on_error;

   /* Load the private key in memory. */
   fp = fopen(private_key_file, "rb");
   if (!fp)
     goto on_error;

   pkey = PEM_read_PrivateKey(fp, NULL, cb, NULL);
   fclose(fp);
   if (!pkey)
     goto on_error;

   /* Load the certificate and the private key in Eet_Key structure */
   key = malloc(sizeof(Eet_Key));
   if (!key)
     goto on_error;

   key->references = 1;
   key->certificate = cert;
   key->private_key = pkey;

   return key;

on_error:
   if (cert)
     X509_free(cert);

   if (pkey)
     EVP_PKEY_free(pkey);

# endif /* ifdef HAVE_GNUTLS */
#else
   (void) certificate_file;
   (void) private_key_file;
   (void) cb;
#endif /* ifdef HAVE_SIGNATURE */
   return NULL;
}
Exemple #25
0
int main (int argc, const char *argv [])
{
	unsigned char *cert_file = NULL, *key_file = NULL;
	unsigned char *cert;
	unsigned char *key;
	size_t cert_len = 0, key_len = 0;
	X509 *cert_ptr = NULL;
	STACK_OF(X509) *chain;
	EVP_PKEY *pkey = NULL;
	FILE *fp;
	DDS_Credentials credential;
	
	/* Test DDS_Credentials in DDS_SSL_BASED format */

	fp = fopen (argv [1], "rb");

	chain = sk_X509_new_null ();

	while ((cert_ptr = PEM_read_X509(fp, NULL, NULL, NULL)) != NULL) 
		sk_X509_push (chain, cert_ptr);

	fp = fopen (argv [2], "rb");

	pkey = PEM_read_PrivateKey(fp ,NULL, NULL, NULL);

	credential.credentialKind = DDS_SSL_BASED;
	credential.info.sslData.certificate_list = chain;
	credential.info.sslData.private_key = pkey;

	sp_extract_pem (&credential,
			&cert, &cert_len,
			&key, &key_len);

	readFile (argv [1], &cert_file);
	readFile (argv [2], &key_file);

	if (!compare (cert_file, strlen (cert_file),
		      cert, cert_len)) {
		printf ("compare problem \r\n");
		exit (1);
	}
	if (!compare (key_file, strlen (key_file),
		      key, key_len)) {
		printf ("compare problem \r\n");
		exit (1);
	}

	free (cert);
	free (key);

	/* Test DDS_Credentials in DDS_DATA_BASED PEM format */

	credential.credentialKind = DDS_DATA_BASED;
	credential.info.data.private_key.format = DDS_FORMAT_PEM;
	credential.info.data.private_key.data = key_file;
	credential.info.data.private_key.length = strlen (key_file);
	credential.info.data.num_certificates = 1;
	credential.info.data.certificates [0].format = DDS_FORMAT_PEM;
	credential.info.data.certificates [0].data = cert_file;
	credential.info.data.certificates [0].length = strlen (cert_file);
	
	cert_len = 0;
	key_len = 0;

	sp_extract_pem (&credential,
			&cert, &cert_len,
			&key, &key_len);

	if (!compare (cert_file, strlen (cert_file),
		      cert, cert_len)) {
		printf ("compare problem \r\n");
		exit (1);
	}
	if (!compare (key_file, strlen (key_file),
		      key, key_len)) {
		printf ("compare problem \r\n");
		exit (1);
	}

	if (sp_add_credential (1, "fake_name", cert, cert_len,
			       key, key_len))
		exit (1);

	if (!sp_get_name (1))
		exit (1);

	if (!sp_get_cert (1, &cert_len))
		exit (1);

	if (!sp_get_key (1, &key_len))
		exit (1);

	if (sp_remove_credential (1))
		exit (1);

	free (cert_file);
	free (key_file);
	free (cert);
	free (key);

	sk_X509_free (chain);

	printf ("Test succeeded\r\n");
}
Exemple #26
0
int main(int argc, char **argv)
{ struct soap *soap;
  int server = 0;
  int text = 0;
  int port = 0;
  FILE *fd;
  double result;
  char *user;
  int runs = 1;
  /* create context */
  soap = soap_new();
  /* register wsse plugin */
  soap_register_plugin_arg(soap, soap_wsse, (void*)token_handler);
  /* options */
  if (argc >= 2)
  { if (strchr(argv[1], 'c'))
      soap_set_omode(soap, SOAP_IO_CHUNK);
    else if (strchr(argv[1], 'y'))
      soap_set_omode(soap, SOAP_IO_STORE);
    if (strchr(argv[1], 'i'))
      soap_set_omode(soap, SOAP_XML_INDENT);
    if (strchr(argv[1], 'n'))
      soap_set_omode(soap, SOAP_XML_CANONICAL);
    if (strchr(argv[1], 'a'))
      aes = 1;
    if (strchr(argv[1], 'o'))
      oaep = 1;
    if (strchr(argv[1], 'd'))
      sym = 1;
    if (strchr(argv[1], 'e'))
      enc = 1;
    if (strchr(argv[1], 'f'))
      addenc = 1;
    /* if (strchr(argv[1], 'F'))
      addenca = 1; */
    if (strchr(argv[1], 'h'))
      hmac = 1;
    if (strchr(argv[1], 'k'))
      nokey = 1;
    if (strchr(argv[1], 's'))
      server = 1;
    if (strchr(argv[1], 't'))
      text = 1;
    if (strchr(argv[1], 'g'))
      addsig = 1;
    if (strchr(argv[1], 'b'))
      nobody = 1;
    if (strchr(argv[1], 'x'))
      nohttp = 1;
    if (strchr(argv[1], 'z'))
      soap_set_mode(soap, SOAP_ENC_ZLIB);
    if (isdigit(argv[1][strlen(argv[1])-1]))
    { runs = argv[1][strlen(argv[1])-1] - '0';
      soap_set_mode(soap, SOAP_IO_KEEPALIVE);
    }
  }
  /* soap->actor = "..."; */ /* set only when required */
  user = getenv("USER");
  if (!user)
    user = "******";
  /* read RSA private key for signing */
  if ((fd = fopen("server.pem", "r")))
  { rsa_privk = PEM_read_PrivateKey(fd, NULL, NULL, (void*)"password");
    fclose(fd);
    if (!rsa_privk)
    { fprintf(stderr, "Could not read private RSA key from server.pem\n");
      exit(1);
    }
  }
  else
    fprintf(stderr, "Could not read server.pem\n");
  /* read certificate (more efficient is to keep certificate in memory)
     to obtain public key for encryption and signature verification */
  if ((fd = fopen("servercert.pem", "r")))
  { cert = PEM_read_X509(fd, NULL, NULL, NULL);
    fclose(fd);
    if (!cert)
    { fprintf(stderr, "Could not read certificate from servercert.pem\n");
      exit(1);
    }
  }
  else
    fprintf(stderr, "Could not read server.pem\n");
  rsa_pubk = X509_get_pubkey(cert);
  if (!rsa_pubk)
  { fprintf(stderr, "Could not get public key from certificate\n");
    exit(1);
  }
  /* port argument */
  if (argc >= 3)
    port = atoi(argv[2]);
  /* need cacert to verify certificates with CA (cacert.pem for testing and
     cacerts.pem for production, which contains the trusted CA certificates) */
  soap->cafile = "cacert.pem";
  /* server or client/ */
  if (server)
  { if (port)
    { /* stand-alone server serving messages over port */
      if (!soap_valid_socket(soap_bind(soap, NULL, port, 100)))
      { soap_print_fault(soap, stderr);
        exit(1);
      }
      printf("Server started at port %d\n", port);
      while (soap_valid_socket(soap_accept(soap)))
      { if (hmac)
          soap_wsse_verify_auto(soap, SOAP_SMD_HMAC_SHA1, hmac_key, sizeof(hmac_key));
        else if (nokey)
          soap_wsse_verify_auto(soap, SOAP_SMD_VRFY_RSA_SHA1, rsa_pubk, 0);
        else
          soap_wsse_verify_auto(soap, SOAP_SMD_NONE, NULL, 0);
        if (sym)
        { if (aes)
            soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_AES256_CBC, aes_key, sizeof(aes_key));
	  else
	    soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_DES_CBC, des_key, sizeof(des_key));
        }
        else if (enc)
          soap_wsse_decrypt_auto(soap, SOAP_MEC_ENV_DEC_DES_CBC, rsa_privk, 0);
        if (soap_serve(soap))
        { soap_wsse_delete_Security(soap);
          soap_print_fault(soap, stderr);
          soap_print_fault_location(soap, stderr);
        }
	soap_destroy(soap);
	soap_end(soap);
      }
      soap_print_fault(soap, stderr);
      exit(1);
    }
    else
    { /* CGI-style server serving messages over stdin/out */
      if (hmac)
        soap_wsse_verify_auto(soap, SOAP_SMD_HMAC_SHA1, hmac_key, sizeof(hmac_key));
      else if (nokey)
        soap_wsse_verify_auto(soap, SOAP_SMD_VRFY_RSA_SHA1, rsa_pubk, 0);
      else
        soap_wsse_verify_auto(soap, SOAP_SMD_NONE, NULL, 0);
      if (sym)
      { if (aes)
          soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_AES256_CBC, aes_key, sizeof(aes_key));
	else
	  soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_DES_CBC, des_key, sizeof(des_key));
      }
      else if (enc)
        soap_wsse_decrypt_auto(soap, SOAP_MEC_ENV_DEC_DES_CBC, rsa_privk, 0);
      if (soap_serve(soap))
      { soap_wsse_delete_Security(soap);
        soap_print_fault(soap, stderr);
        soap_print_fault_location(soap, stderr);
      }
      soap_destroy(soap);
      soap_end(soap);
    }
  }
  else /* client */
  { int run;
    char endpoint[80];
    /* ns1:test data */
    struct ns1__add a;
    struct ns1__sub b;
    a.a = 123;
    a.b = 456;
    b.a = 789;
    b.b = -99999;
    /* client sending messages to stdout or over port */
    if (port)
      sprintf(endpoint, "http://localhost:%d", port);
    else if (nohttp)
      strcpy(endpoint, "");
    else
      strcpy(endpoint, "http://");

    for (run = 0; run < runs; run++)
    {

    /* message lifetime of 60 seconds */
    soap_wsse_add_Timestamp(soap, "Time", 60);
    /* add user name with text or digest password */
    if (text)
      soap_wsse_add_UsernameTokenText(soap, "User", user, "userPass");
    else
      soap_wsse_add_UsernameTokenDigest(soap, "User", user, "userPass");
    if (sym)
    { if (aes)
      { /* symmetric encryption with AES */
        soap_wsse_add_EncryptedData_KeyInfo_KeyName(soap, "My AES Key");
        if (soap_wsse_encrypt_body(soap, SOAP_MEC_ENC_AES256_CBC, aes_key, sizeof(aes_key)))
          soap_print_fault(soap, stderr);
        soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_AES256_CBC, aes_key, sizeof(aes_key));
      }
      else
      { /* symmetric encryption with DES */
        soap_wsse_add_EncryptedData_KeyInfo_KeyName(soap, "My DES Key");
        if (soap_wsse_encrypt_body(soap, SOAP_MEC_ENC_DES_CBC, des_key, sizeof(des_key)))
          soap_print_fault(soap, stderr);
        soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_DES_CBC, des_key, sizeof(des_key));
      }
    }
    else if (addenc || addenca)
    { /* RSA encryption of the <ns1:add> element */
      const char *SubjectKeyId = NULL; /* set to non-NULL to use SubjectKeyIdentifier in Header rather than a full cert key */
      /* MUST set wsu:Id of the elements to encrypt */
      if (addenc) /* encrypt element <ns1:add> */
      { soap_wsse_set_wsu_id(soap, "ns1:add");
        if (soap_wsse_add_EncryptedKey_encrypt_only(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, SubjectKeyId, NULL, NULL, "ns1:add"))
          soap_print_fault(soap, stderr);
      }
      else /* encrypt element <a> */
      { soap_wsse_set_wsu_id(soap, "a");
        if (soap_wsse_add_EncryptedKey_encrypt_only(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, SubjectKeyId, NULL, NULL, "a"))
          soap_print_fault(soap, stderr);
      }
      soap_wsse_decrypt_auto(soap, SOAP_MEC_ENV_DEC_DES_CBC, rsa_privk, 0);
    }
    else if (enc)
    { /* RSA encryption of the SOAP Body */
      const char *SubjectKeyId = NULL; /* set to non-NULL to use SubjectKeyIdentifier in Header rather than a full cert key */
      if (oaep)
      { if (soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_AES256_CBC | SOAP_MEC_OAEP, "Cert", cert, SubjectKeyId, NULL, NULL))
          soap_print_fault(soap, stderr);
      }
      else if (aes)
      { if (soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_AES256_CBC, "Cert", cert, SubjectKeyId, NULL, NULL))
          soap_print_fault(soap, stderr);
      }
      else
      { if (soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, SubjectKeyId, NULL, NULL))
          soap_print_fault(soap, stderr);
      }
      soap_wsse_decrypt_auto(soap, SOAP_MEC_ENV_DEC_DES_CBC, rsa_privk, 0);
    }
    if (hmac)
    { /* symmetric signature */
      if (nobody)
        soap_wsse_sign(soap, SOAP_SMD_HMAC_SHA1, hmac_key, sizeof(hmac_key));
      else
        soap_wsse_sign_body(soap, SOAP_SMD_HMAC_SHA1, hmac_key, sizeof(hmac_key));
      /* WS-SecureConversation contect token */
      soap_wsse_add_SecurityContextToken(soap, "SCT", contextId);
    }
    else
    { if (nokey)
        soap_wsse_add_KeyInfo_KeyName(soap, "MyKey");
      else
      { soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert);
        soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token");
      }
      if (nobody || addsig) /* do not sign body */
        soap_wsse_sign(soap, SOAP_SMD_SIGN_RSA_SHA1, rsa_privk, 0);
      else
        soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_privk, 0);
    }
    /* enable automatic signature verification of server responses */
    if (hmac)
      soap_wsse_verify_auto(soap, SOAP_SMD_HMAC_SHA1, hmac_key, sizeof(hmac_key));
    else if (nokey)
      soap_wsse_verify_auto(soap, SOAP_SMD_VRFY_RSA_SHA1, rsa_pubk, 0);
    else
      soap_wsse_verify_auto(soap, SOAP_SMD_NONE, NULL, 0);
    /* sign the response message in unsigned body? If so, set wsu:Id */
    if (addsig)
    { soap_wsse_set_wsu_id(soap, "ns1:add");
      soap_wsse_sign_only(soap, "User ns1:add");
    }
    /* invoke the server. You can choose add, sub, mul, or div operations
     * that show different security aspects (intentional message rejections)
     * for demonstration purposes (see server operations below) */
    if (!soap_call_ns1__add(soap, endpoint, NULL, 1.0, 2.0, &result))
    { if (!soap_wsse_verify_Timestamp(soap))
      { const char *servername = soap_wsse_get_Username(soap);
        if (servername
	 && !strcmp(servername, "server")
         && !soap_wsse_verify_Password(soap, "serverPass"))
          printf("Result = %g\n", result);
        else
	{ fprintf(stderr, "Server authentication failed\n");
          soap_print_fault(soap, stderr);
        }
      }
      else
      { fprintf(stderr, "Server response expired\n");
        soap_print_fault(soap, stderr);
      }
    }
    else
    { soap_print_fault(soap, stderr);
      soap_print_fault_location(soap, stderr);
    }
    /* clean up security header */
    soap_wsse_delete_Security(soap);
    /* disable soap_wsse_verify_auto */
    soap_wsse_verify_done(soap);

  } /* run */

  }
  /* clean up keys */
  if (rsa_privk)
    EVP_PKEY_free(rsa_privk);
  if (rsa_pubk)
    EVP_PKEY_free(rsa_pubk);
  if (cert)
    X509_free(cert);
  /* clean up gSOAP engine */
  soap_destroy(soap);
  soap_end(soap);
  soap_done(soap);
  free(soap);
  /* done */
  return 0;
}
Exemple #27
0
DSA *PEM_read_DSAPrivateKey(FILE *fp, DSA **dsa, pem_password_cb *cb, void *u)
{
    EVP_PKEY *pktmp;
    pktmp = PEM_read_PrivateKey(fp, NULL, cb, u);
    return pkey_get_dsa(pktmp, dsa); /* will free pktmp */
}
Exemple #28
0
int
main(int argc, char **argv)
{
	int ch, error;
	bool Vflag = false, vflag = false;
	const char *certpath = NULL, *keypath = NULL, *outpath = NULL, *inpath = NULL;
	FILE *certfp = NULL, *keyfp = NULL;
	X509 *cert = NULL;
	EVP_PKEY *key = NULL;
	pid_t pid;
	int pipefds[2];

	while ((ch = getopt(argc, argv, "Vc:k:o:v")) != -1) {
		switch (ch) {
		case 'V':
			Vflag = true;
			break;
		case 'c':
			certpath = checked_strdup(optarg);
			break;
		case 'k':
			keypath = checked_strdup(optarg);
			break;
		case 'o':
			outpath = checked_strdup(optarg);
			break;
		case 'v':
			vflag = true;
			break;
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;
	if (argc != 1)
		usage();

	if (Vflag) {
		if (certpath != NULL)
			errx(1, "-V and -c are mutually exclusive");
		if (keypath != NULL)
			errx(1, "-V and -k are mutually exclusive");
		if (outpath != NULL)
			errx(1, "-V and -o are mutually exclusive");
	} else {
		if (certpath == NULL)
			errx(1, "-c option is mandatory");
		if (keypath == NULL)
			errx(1, "-k option is mandatory");
		if (outpath == NULL)
			errx(1, "-o option is mandatory");
	}

	inpath = argv[0];

	OPENSSL_config(NULL);
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();

	error = pipe(pipefds);
	if (error != 0)
		err(1, "pipe");

	pid = fork();
	if (pid < 0)
		err(1, "fork");

	if (pid == 0)
		return (child(inpath, outpath, pipefds[1], Vflag, vflag));

	if (!Vflag) {
		certfp = checked_fopen(certpath, "r");
		cert = PEM_read_X509(certfp, NULL, NULL, NULL);
		if (cert == NULL) {
			ERR_print_errors_fp(stderr);
			errx(1, "failed to load certificate from %s", certpath);
		}

		keyfp = checked_fopen(keypath, "r");
		key = PEM_read_PrivateKey(keyfp, NULL, NULL, NULL);
		if (key == NULL) {
			ERR_print_errors_fp(stderr);
			errx(1, "failed to load private key from %s", keypath);
		}

		sign(cert, key, pipefds[0]);
	}

	return (wait_for_child(pid));
}
Exemple #29
0
RSA *PEM_read_RSAPrivateKey(FILE *fp, RSA **rsa, pem_password_cb *cb, void *u)
{
    EVP_PKEY *pktmp;
    pktmp = PEM_read_PrivateKey(fp, NULL, cb, u);
    return pkey_get_rsa(pktmp, rsa);
}
Exemple #30
0
as_status
as_tls_context_setup(as_config_tls* tlscfg, as_tls_context* ctx, as_error* errp)
{
	// Clear the destination, in case we don't make it.
	ctx->ssl_ctx = NULL;
	ctx->pkey = NULL;
	ctx->cert_blacklist = NULL;
	ctx->log_session_info = tlscfg->log_session_info;
	ctx->for_login_only = tlscfg->for_login_only;

	as_tls_check_init();
	pthread_mutex_init(&ctx->lock, NULL);

	if (tlscfg->cert_blacklist) {
		ctx->cert_blacklist = cert_blacklist_read(tlscfg->cert_blacklist);

		if (! ctx->cert_blacklist) {
			as_tls_context_destroy(ctx);
			return as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
								   "Failed to read certificate blacklist: %s",
								   tlscfg->cert_blacklist);
		}
	}
	
	uint16_t protocols = AS_TLS_PROTOCOL_NONE;
	as_status status = protocols_parse(tlscfg, &protocols, errp);

	if (status != AEROSPIKE_OK) {
		as_tls_context_destroy(ctx);
		return status;
	}

	const SSL_METHOD* method = NULL;

	// If the selected protocol set is a single protocol we can use a specific method.
	if (protocols == AS_TLS_PROTOCOL_TLSV1) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
		method = TLS_client_method();
#else
		method = TLSv1_client_method();
#endif
	}
	else if (protocols == AS_TLS_PROTOCOL_TLSV1_1) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
		method = TLS_client_method();
#else
		method = TLSv1_1_client_method();
#endif
	}
	else if (protocols == AS_TLS_PROTOCOL_TLSV1_2) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
		method = TLS_client_method();
#else
		method = TLSv1_2_client_method();
#endif
	}
	else {
		// Multiple protocols are enabled, use a flexible method.
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
		method = TLS_client_method();
#else
		method = SSLv23_client_method();
#endif
	}

	ctx->ssl_ctx = SSL_CTX_new(method);

	if (ctx->ssl_ctx == NULL) {
		as_tls_context_destroy(ctx);

		unsigned long errcode = ERR_get_error();
		char errbuf[1024];
		ERR_error_string_n(errcode, errbuf, sizeof(errbuf));
		return as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
							   "Failed to create new TLS context: %s", errbuf);
	}

	/* always disable SSLv2, as per RFC 6176 */
    SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
	SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3);

	// Turn off non-enabled protocols.
	if (! (protocols & AS_TLS_PROTOCOL_TLSV1)) {
        SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1);
    }
	if (! (protocols & AS_TLS_PROTOCOL_TLSV1_1)) {
        SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1_1);
    }
	if (! (protocols & AS_TLS_PROTOCOL_TLSV1_2)) {
        SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1_2);
    }
	
	if (tlscfg->cafile || tlscfg->capath) {
		int rv = SSL_CTX_load_verify_locations(ctx->ssl_ctx, tlscfg->cafile, tlscfg->capath);

		if (rv != 1) {
			as_tls_context_destroy(ctx);

			char errbuf[1024];
			unsigned long errcode = ERR_get_error();

			if (errcode != 0) {
				ERR_error_string_n(errcode, errbuf, sizeof(errbuf));
				return as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
									   "Failed to load CAFile: %s", errbuf);
			}
			return as_error_set_message(errp, AEROSPIKE_ERR_TLS_ERROR,
										"Unknown failure loading CAFile");
		}
	}

	if (tlscfg->certfile) {
		int rv = SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, tlscfg->certfile);

		if (rv != 1) {
			// We seem to be seeing this bug:
			// https://groups.google.com/
			//          forum/#!topic/mailing.openssl.users/nRvRzmKnEQA
			// If the rv is not 1 check the error stack; if it doesn't have an
			// error assume we are OK.
			//
			unsigned long errcode = ERR_peek_error();

			if (errcode != SSL_ERROR_NONE) {
				// There *was* an error after all.
				as_tls_context_destroy(ctx);

				unsigned long errcode = ERR_get_error();
				char errbuf[1024];
				ERR_error_string_n(errcode, errbuf, sizeof(errbuf));
				return as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
									   "SSL_CTX_use_certificate_chain_file failed: %s",
									   errbuf);
			}
		}
	}

	if (tlscfg->keyfile) {
		bool ok = false;
		FILE *fh = fopen(tlscfg->keyfile, "r");

		if (fh == NULL) {
			as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
					"failed to open key file %s: %s", tlscfg->keyfile,
					strerror(errno));
		}
		else {
			EVP_PKEY *pkey = PEM_read_PrivateKey(fh, NULL, password_cb,
					tlscfg->keyfile_pw);

			if (pkey == NULL) {
				unsigned long errcode = ERR_get_error();

				if (ERR_GET_REASON(errcode) == PEM_R_BAD_PASSWORD_READ) {
					if (tlscfg->keyfile_pw == NULL) {
						as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
								"key file %s requires a password",
								tlscfg->keyfile);
					}
					else {
						as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
								"password for key file %s too long",
								tlscfg->keyfile);
					}
				}
				else if (ERR_GET_REASON(errcode) == EVP_R_BAD_DECRYPT) {
					as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
							"invalid password for key file %s",
							tlscfg->keyfile);
				}
				else {
					char errbuf[1024];
					ERR_error_string_n(errcode, errbuf, sizeof(errbuf));
					as_error_update(errp, AEROSPIKE_ERR_TLS_ERROR,
							"PEM_read_PrivateKey failed: %s", errbuf);
				}
			}
			else {
				ctx->pkey = pkey;
				SSL_CTX_use_PrivateKey(ctx->ssl_ctx, pkey);
				ok = true;
			}

			fclose(fh);
		}

		if (!ok) {
			as_tls_context_destroy(ctx);
			return AEROSPIKE_ERR_TLS_ERROR;
		}
	}

	if (tlscfg->cipher_suite) {
		int rv = SSL_CTX_set_cipher_list(ctx->ssl_ctx, tlscfg->cipher_suite);

		if (rv != 1) {
			as_tls_context_destroy(ctx);
			return as_error_set_message(errp, AEROSPIKE_ERR_TLS_ERROR,
										"no compatible cipher found");
		}
		// It's bogus that we have to create an SSL just to get the
		// cipher list, but SSL_CTX_get_ciphers doesn't appear to
		// exist ...
		SSL* ssl = SSL_new(ctx->ssl_ctx);

		for (int prio = 0; true; ++prio) {
			char const * cipherstr = SSL_get_cipher_list(ssl, prio);
			if (!cipherstr) {
				break;
			}
			as_log_info("cipher %d: %s", prio+1, cipherstr);
		}
		SSL_free(ssl);
	}

	if (tlscfg->crl_check || tlscfg->crl_check_all) {
		X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
		unsigned long flags = X509_V_FLAG_CRL_CHECK;

		if (tlscfg->crl_check_all) {
			flags |= X509_V_FLAG_CRL_CHECK_ALL;
		}

		X509_VERIFY_PARAM_set_flags(param, flags);
		SSL_CTX_set1_param(ctx->ssl_ctx, param);
		X509_VERIFY_PARAM_free(param);
	}

	SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, verify_callback);
	manage_sigpipe();
	return AEROSPIKE_OK;
}