/* Copyright (C) 2009-2014, Martin Johansson <martin@fatbob.nu>
   Copyright (C) 2005-2014, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Developers nor the names of its contributors may
     be used to endorse or promote products derived from this software without
     specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#include "conf.h"
#include "log.h"
#include "memory.h"
#include "ssl.h"

/*
 * OpenSSL interface
 */

#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
#include <openssl/safestack.h>
#include <openssl/opensslv.h>
#ifndef OPENSSL_NO_EC
#include <openssl/ec.h>
#endif

static SSL_CTX *context;

static char const * ciphers = "EECDH+AESGCM:EDH+aRSA+AESGCM:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:AES256-SHA:AES128-SHA";

static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx);

static int SSL_add_ext(X509 * crt, int nid, char *value) {
	X509_EXTENSION *ex;
	X509V3_CTX ctx;
	X509V3_set_ctx_nodb(&ctx);
	X509V3_set_ctx(&ctx, crt, crt, NULL, NULL, 0);
	ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
	if (!ex)
		return 0;

	X509_add_ext(crt, ex, -1);
	X509_EXTENSION_free(ex);
	return 1;
}

static X509 *SSL_readcert(char *certfile)
{
	FILE *fp;
	X509 *x509;

	/* open the certificate file */
	fp = fopen(certfile, "r");
	if (fp == NULL) {
		Log_warn("Unable to open the X509 file %s for reading.", certfile);
		return NULL;
	}

	/* allocate memory for the cert structure */
	x509 = X509_new();

	if (PEM_read_X509(fp, &x509, NULL, NULL) == 0) {
		/* error reading the x509 information - check the error stack */
		Log_warn("Error trying to read X509 info.");
		fclose(fp);
		X509_free(x509);
		return NULL;
	}
	fclose(fp);
	return x509;
}

static void SSL_writecert(char *certfile, X509 *x509)
{
	FILE *fp;

	/* open the private key file */
	fp = fopen(certfile, "w");
	if (fp == NULL) {
		Log_warn("Unable to open the X509 file %s for writing", certfile);
		return;
	}
	if (PEM_write_X509(fp, x509) == 0) {
		Log_warn("Error trying to write X509 info.");
	}
	fclose(fp);
}

static void SSL_writekey(char *keyfile, RSA *rsa)
{
	FILE *fp;

	/* open the private key file for reading */
	fp = fopen(keyfile, "w");
	if (fp == NULL) {
		Log_warn("Unable to open the private key file %s for writing.", keyfile);
		return;
	}

	if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
		Log_warn("Error trying to write private key");
	}
	fclose(fp);
}


static EVP_PKEY *SSL_generate_cert_and_key(char *key, char *crt)
{
	BIGNUM *e = NULL;
	RSA *rsa;
	EVP_PKEY *pkey;
	X509 *x509;
	
	Log_info("Generating new server certificate.");
	
	x509 = X509_new();
	if (!x509)
		goto err_out;
	pkey = EVP_PKEY_new();
	if (!pkey)
		goto err_out;
	rsa = RSA_new();
	if (!rsa)
		goto err_out;
	e = BN_new();
	if (!e)
		goto err_out;
		
	BN_set_word(e, RSA_F4);
	RSA_generate_key_ex(rsa, 2048, e, NULL);
	EVP_PKEY_assign_RSA(pkey, rsa);
	
	X509_set_version(x509, 2);
	ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
	X509_gmtime_adj(X509_get_notBefore(x509), 0);
	X509_gmtime_adj(X509_get_notAfter(x509), 60 * 60 * 24 * 365 * 20);
#else
	X509_gmtime_adj(X509_getm_notBefore(x509), 0);
	X509_gmtime_adj(X509_getm_notAfter(x509), 60 * 60 * 24 * 365 * 20);
#endif
	X509_set_pubkey(x509, pkey);
	
	X509_NAME *name = X509_get_subject_name(x509);
	
	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
	X509_set_issuer_name(x509, name);
	SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
	SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
	SSL_add_ext(x509, NID_subject_key_identifier, "hash");
	SSL_add_ext(x509, NID_netscape_comment, "Generated from uMurmur");
	
	X509_sign(x509, pkey, EVP_sha1());
	
	SSL_writecert(crt, x509);
	SSL_writekey(key, rsa);
	
	SSL_CTX_use_certificate(context, x509);

	if (e)
		BN_free(e);
	if (x509)
		X509_free(x509);
	/* RSA is free'd with EVP_PKEY_free() later */
	
	return pkey;
err_out:
	if (e)
		BN_free(e);
	if (x509)
		X509_free(x509);
	if (rsa)
		RSA_free(rsa);
	if (pkey)
		EVP_PKEY_free(pkey);
	Log_fatal("Failed to generate key and/or certificate.");
	return NULL;
}

static bool_t file_exists(const char *filename)
{
       return (access(filename, F_OK) == 0);
}

static void SSL_initializeCert(void)
{
	char *crt = (char *)getStrConf(CERTIFICATE);
	char *key = (char *)getStrConf(KEY);
	FILE *fp;
	EVP_PKEY *pkey = NULL;
	
	if (context) {
		bool_t did_load_cert = SSL_CTX_use_certificate_chain_file(context, crt);

		fp = fopen(key, "r");
		
		if (fp == NULL)
		    Log_warn("Unable to open the private key file %s for reading.", key);
		else
		    pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
		
		if (pkey == NULL || !did_load_cert) {
			/* Do not generate new certificate if either private key or
			 * certificate file (or both) already exists, even though one
			 * (or both) of them is invalid or inaccessible. */
			if (file_exists(key) || file_exists(crt))
				Log_fatal("Key and/or certificate file present but invalid or inaccessible. Exiting.");
			
			pkey = SSL_generate_cert_and_key(key, crt);
		}
		
		SSL_CTX_use_PrivateKey(context, pkey);

		if (pkey)
			EVP_PKEY_free(pkey);
	} else {
		Log_fatal("Failed to initialize TLS context.");
	}

}

void SSLi_init(void)
{
	SSL *ssl;
	int i, offset = 0, cipherstringlen = 0;
	STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
	const SSL_CIPHER *cipher;
	char *cipherstring;

#if OPENSSL_VERSION_NUMBER < 0x10100000L
	SSL_library_init();
	OpenSSL_add_all_algorithms();
	SSL_load_error_strings();
	ERR_load_crypto_strings();

	context = SSL_CTX_new(SSLv23_server_method());
	SSL_CTX_set_options(context, SSL_OP_NO_SSLv2);
	SSL_CTX_set_options(context, SSL_OP_NO_SSLv3);
#else
	context = SSL_CTX_new(TLS_server_method());
	SSL_CTX_set_min_proto_version(context, TLS1_VERSION);
#endif
	if (context == NULL)
		Log_fatal("Could not initialize OpenSSL.");
	SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
	SSL_CTX_set_cipher_list(context, ciphers);
#ifndef OPENSSL_NO_EC
	EC_KEY *ecdhkey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
	SSL_CTX_set_tmp_ecdh(context, ecdhkey);
	EC_KEY_free(ecdhkey);
#endif
	
	char const * sslCAPath = getStrConf(CAPATH);
	if(sslCAPath != NULL)
	{
		SSL_CTX_load_verify_locations(context, NULL, sslCAPath);
	}

	SSL_initializeCert();

	/* Set cipher list */
	ssl = SSL_new(context);
	cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
	cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();

	for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
		if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
			sk_SSL_CIPHER_push(cipherlist_new, cipher);
		}
	}
	Log_debug("List of ciphers:");
	if (cipherlist_new) {
		for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
			Log_debug("%s", SSL_CIPHER_get_name(cipher));
			cipherstringlen += strlen(SSL_CIPHER_get_name(cipher)) + 1;
		}
		cipherstring = Memory_safeMalloc(1, cipherstringlen + 1);
		for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
			offset += sprintf(cipherstring + offset, "%s:", SSL_CIPHER_get_name(cipher));
		}
	}

	if (cipherlist_new)
		sk_SSL_CIPHER_free(cipherlist_new);

	if (strlen(cipherstring) == 0)
		Log_fatal("No suitable ciphers found!");

	if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
		Log_fatal("Failed to set cipher list!");

	free(cipherstring);

	SSL_CTX_set_verify(context, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
	                   verify_callback);

	SSL_free(ssl);
	Log_info("OpenSSL library initialized (version: %s)", OPENSSL_VERSION_TEXT);

}

void SSLi_deinit(void)
{
	SSL_CTX_free(context);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
	EVP_cleanup();
#endif
}

int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
{
	int rc;
	rc = SSL_accept(ssl);
	if (rc < 0) {
		if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
			SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
			Log_debug("SSL not ready");
			return 0;
		} else {
			Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
			return -1;
		}
	}
	*SSLready = true;
	return 0;
}

SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
{
	SSL *ssl;

	*SSLready = false;
	ssl = SSL_new(context);
	SSL_set_fd(ssl, *fd);
	if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
		SSL_free(ssl);
		return NULL;
	}
	return ssl;
}

/* Create SHA1 of last certificate in the peer's chain. */
bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
{
	X509 *x509;
	uint8_t *buf, *p;
	int len;

	x509 = SSL_get_peer_certificate(ssl);
	if (!x509) {
		return false;
	}

	len = i2d_X509(x509, NULL);
	buf = Memory_safeMalloc(1, len);

	p = buf;
	i2d_X509(x509, &p);

	SHA1(buf, len, hash);
	free(buf);
	return true;
}

void SSLi_closeconnection(SSL_handle_t *ssl)
{
	SSL_free(ssl);
}

void SSLi_shutdown(SSL_handle_t *ssl)
{
	SSL_shutdown(ssl);
}

int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
{
	return SSL_read(ssl, buf, len);
}

int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
{
	return SSL_write(ssl, buf, len);
}

int SSLi_get_error(SSL_handle_t *ssl, int code)
{
	return SSL_get_error(ssl, code);
}

bool_t SSLi_data_pending(SSL_handle_t *ssl)
{
	return SSL_pending(ssl);
}

void SSLi_free(SSL_handle_t *ssl)
{
	SSL_free(ssl);
}

static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
	char    buf[256];
	X509   *err_cert;
	int     err, depth;
	SSL    *ssl;

    err_cert = X509_STORE_CTX_get_current_cert(ctx);
    err = X509_STORE_CTX_get_error(ctx);
    depth = X509_STORE_CTX_get_error_depth(ctx);

    ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
    X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);

    if (depth > 5) {
        preverify_ok = 0;
        err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
        X509_STORE_CTX_set_error(ctx, err);
    }
    if (!preverify_ok) {
	    Log_warn("SSL: verify error:num=%d:%s:depth=%d:%s\n", err,
	             X509_verify_cert_error_string(err), depth, buf);
    }
    /*
     * At this point, err contains the last verification error. We can use
     * it for something special
     */
    if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
	    X509_NAME_oneline(X509_get_issuer_name(err_cert), buf, 256);
	    Log_warn("issuer= %s", buf);
    }
    return 1;
}
