/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "ssl_locl.h"
#include <openssl/bio.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
static int ssl_set_cert(CERT *c, X509 *x509);
static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey);
int SSL_use_certificate(SSL *ssl, X509 *x)
{
int rv;
if (x == NULL) {
SSLerr(SSL_F_SSL_USE_CERTIFICATE, ERR_R_PASSED_NULL_PARAMETER);
return (0);
}
rv = ssl_security_cert(ssl, NULL, x, 0, 1);
if (rv != 1) {
SSLerr(SSL_F_SSL_USE_CERTIFICATE, rv);
return 0;
}
return (ssl_set_cert(ssl->cert, x));
}
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());
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:
X509_free(x);
BIO_free(in);
return (ret);
}
int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len)
{
X509 *x;
int ret;
x = d2i_X509(NULL, &d, (long)len);
if (x == NULL) {
SSLerr(SSL_F_SSL_USE_CERTIFICATE_ASN1, ERR_R_ASN1_LIB);
return (0);
}
ret = SSL_use_certificate(ssl, x);
X509_free(x);
return (ret);
}
#ifndef OPENSSL_NO_RSA
int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa)
{
EVP_PKEY *pkey;
int ret;
if (rsa == NULL) {
SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY, ERR_R_PASSED_NULL_PARAMETER);
return (0);
}
if ((pkey = EVP_PKEY_new()) == NULL) {
SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY, ERR_R_EVP_LIB);
return (0);
}
RSA_up_ref(rsa);
if (EVP_PKEY_assign_RSA(pkey, rsa) <= 0) {
RSA_free(rsa);
EVP_PKEY_free(pkey);
return 0;
}
ret = ssl_set_pkey(ssl->cert, pkey);
EVP_PKEY_free(pkey);
return (ret);
}
#endif
static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey)
{
int i;
i = ssl_cert_type(NULL, pkey);
if (i < 0) {
SSLerr(SSL_F_SSL_SET_PKEY, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
return (0);
}
if (c->pkeys[i].x509 != NULL) {
EVP_PKEY *pktmp;
pktmp = X509_get0_pubkey(c->pkeys[i].x509);
if