/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

#include "vio_priv.h"

#ifdef HAVE_OPENSSL

// The following was auto-generated by openssl dhparam -C 2048
DH *get_dh2048()
	{
	static unsigned char dh2048_p[]={
		0xD8,0xA7,0xAC,0x07,0x20,0x27,0x05,0x00,0x8B,0xDC,0xD5,0xAC,
		0x22,0x0C,0x92,0xB1,0xE2,0x73,0x35,0x34,0xB4,0x1D,0x8E,0x92,
		0x37,0xE5,0x0D,0x03,0x07,0x05,0xE7,0xF5,0x36,0xA9,0x60,0xB5,
		0x30,0xDB,0x14,0xE7,0x9C,0xB2,0xA1,0xB0,0x0B,0xA6,0x8D,0x09,
		0xEB,0x63,0xAE,0x4B,0xC7,0x28,0x00,0xC8,0x04,0x35,0x85,0x68,
		0x2E,0xA7,0x4A,0xC4,0xE6,0xB9,0x6B,0x05,0x25,0x48,0x0E,0x90,
		0x44,0x1A,0x29,0x2A,0x93,0x93,0xDB,0xC6,0xB1,0x16,0x74,0xD4,
		0xE8,0x19,0xE3,0x4B,0xD5,0xA7,0xD5,0x03,0xE7,0x5A,0x98,0x9F,
		0xA5,0x93,0x7B,0x20,0x7E,0x56,0xCB,0x3F,0xCE,0xDD,0xCC,0x93,
		0x18,0xA1,0x62,0x8C,0x68,0x88,0x5F,0x48,0x6D,0x9F,0x6D,0x76,
		0x01,0x5F,0x80,0xD5,0x2E,0xEF,0x35,0xA3,0x4B,0x49,0xD5,0x19,
		0xA4,0xB4,0xCF,0x83,0xE3,0xE3,0xA3,0x14,0x68,0xB1,0x4B,0x4C,
		0x1B,0xCF,0x7C,0x6F,0x92,0x70,0xB5,0xC6,0x10,0xFD,0x45,0x90,
		0x8E,0x8A,0xA0,0x31,0x95,0x86,0xD6,0x97,0xE5,0xAB,0x77,0x8C,
		0x15,0xAB,0xBD,0x9F,0x23,0xD7,0xD7,0x54,0xCC,0xC6,0x7F,0x81,
		0x70,0xC0,0x35,0x3E,0x91,0xE3,0xA4,0xA5,0x95,0xF8,0xE5,0xFB,
		0x2A,0x00,0x80,0x7F,0x87,0x6F,0x11,0x02,0x6A,0xD4,0xE5,0xE7,
		0xAF,0xA4,0x8F,0x50,0x6A,0xA5,0x6A,0xB6,0x34,0x72,0xED,0x07,
		0x5B,0x17,0x5F,0x31,0x06,0xE3,0x93,0x95,0xED,0x4B,0x46,0x51,
		0x80,0xA9,0xA6,0xE6,0x75,0x7A,0x43,0x20,0x90,0x60,0x99,0x92,
		0xB6,0x58,0x08,0xCF,0x58,0x98,0x59,0x54,0x7C,0xE8,0xB1,0xCE,
		0x08,0x50,0x22,0x7B,
		};
	static unsigned char dh2048_g[]={
		0x02,
		};
	DH *dh;

	if ((dh=DH_new()) == NULL) return(NULL);
	dh->p=BN_bin2bn(dh2048_p,sizeof(dh2048_p),NULL);
	dh->g=BN_bin2bn(dh2048_g,sizeof(dh2048_g),NULL);
	if ((dh->p == NULL) || (dh->g == NULL))
		{ DH_free(dh); return(NULL); }
	return(dh);
	}


static void
report_errors()
{
  unsigned long	l;
  const char*	file;
  const char*	data;
  int		line,flags;

  DBUG_ENTER("report_errors");

  while ((l=ERR_get_error_line_data(&file,&line,&data,&flags)) != 0)
  {
#ifndef DBUG_OFF				/* Avoid warning */
    char buf[200];
    DBUG_PRINT("error", ("OpenSSL: %s:%s:%d:%s\n", ERR_error_string(l,buf),
			 file,line,(flags & ERR_TXT_STRING) ? data : "")) ;
#endif
  }
  DBUG_VOID_RETURN;
}

static const char*
ssl_error_string[] = 
{
  "No error",
  "Unable to get certificate",
  "Unable to get private key",
  "Private key does not match the certificate public key",
  "SSL_CTX_set_default_verify_paths failed",
  "Failed to set ciphers to use",
  "SSL_CTX_new failed"
};

const char*
sslGetErrString(enum enum_ssl_init_error e)
{
  DBUG_ASSERT(SSL_INITERR_NOERROR < e && e < SSL_INITERR_LASTERR);
  return ssl_error_string[e];
}

static int
vio_set_cert_stuff(SSL_CTX *ctx, const char *cert_file, const char *key_file,
                   enum enum_ssl_init_error* error)
{
  DBUG_ENTER("vio_set_cert_stuff");
  DBUG_PRINT("enter", ("ctx: 0x%lx  cert_file: %s  key_file: %s",
		       (long) ctx, cert_file, key_file));

  if (!cert_file &&  key_file)
    cert_file= key_file;
  
  if (!key_file &&  cert_file)
    key_file= cert_file;

  if (cert_file &&
      SSL_CTX_use_certificate_chain_file(ctx, cert_file) <= 0)
  {
    *error= SSL_INITERR_CERT;
    DBUG_PRINT("error",("%s from file '%s'", sslGetErrString(*error), cert_file));
    DBUG_EXECUTE("error", ERR_print_errors_fp(DBUG_FILE););
    fprintf(stderr, "SSL error: %s from '%s'\n", sslGetErrString(*error),
            cert_file);
    fflush(stderr);
    DBUG_RETURN(1);
  }

  if (key_file &&
      SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0)
  {
    *error= SSL_INITERR_KEY;
    DBUG_PRINT("error", ("%s from file '%s'", sslGetErrString(*error), key_file));
    DBUG_EXECUTE("error", ERR_print_errors_fp(DBUG_FILE););
    fprintf(stderr, "SSL error: %s from '%s'\n", sslGetErrString(*error),
            key_file);
    fflush(stderr);
    DBUG_RETURN(1);
  }

  /*
    If we are using DSA, we can copy the parameters from the private key
    Now we know that a key and cert have been set against the SSL context
  */
  if (cert_file && !SSL_CTX_check_private_key(ctx))
  {
    *error= SSL_INITERR_NOMATCH;
    DBUG_PRINT("error", ("%s",sslGetErrString(*error)));
    DBUG_EXECUTE("error", ERR_print_errors_fp(DBUG_FILE););
    fprintf(stderr, "SSL error: %s\n", sslGetErrString(*error));
    fflush(stderr);
    DBUG_RETURN(1);
  }

  DBUG_RETURN(0);
}

pthread_mutex_t ssl_init_mutex = PTHREAD_MUTEX_INITIALIZER;
static my_bool ssl_initialized = FALSE;

void ssl_start()
{
  pthread_mutex_lock(&ssl_init_mutex);
  if (ssl_initialized) {
    pthread_mutex_unlock(&ssl_init_mutex);
    return;
  }

  SSL_library_init();
  OpenSSL_add_all_algorithms();
  SSL_load_error_strings();

  ssl_initialized = TRUE;
  pthread_mutex_unlock(&ssl_init_mutex);
}

/************************ VioSSLFd **********************************/
static struct st_VioSSLFd *
new_VioSSLFd(const char *key_file, const char *cert_file,
             const char *ca_file, const char *ca_path,
             const char *cipher, my_bool is_client,
             enum enum_ssl_init_error *error,
             const char *crl_file, const char *crl_path)
{
  DH *dh;
  struct st_VioSSLFd *ssl_fd;
  DBUG_ENTER("new_VioSSLFd");
  DBUG_PRINT("enter",
             ("key_file: '%s'  cert_file: '%s'  ca_file: '%s'  ca_path: '%s'  "
              "cipher: '%s' crl_file: '%s' crl_path: '%s' ",
              key_file ? key_file : "NULL",
              cert_file ? cert_file : "NULL",
              ca_file ? ca_file : "NULL",
              ca_path ? ca_path : "NULL",
              cipher ? cipher : "NULL",
              crl_file ? crl_file : "NULL",
              crl_path ? crl_path : "NULL"));

  ssl_start();

  if (!(ssl_fd= ((struct st_VioSSLFd*)
                 my_malloc(sizeof(struct st_VioSSLFd),MYF(0)))))
    DBUG_RETURN(0);
  ssl_fd->owned = TRUE;

  if (!(ssl_fd->ssl_context= SSL_CTX_new(is_client ?
                                         SSLv23_client_method() :
                                         SSLv23_server_method())))
  {
    *error= SSL_INITERR_MEMFAIL;
    DBUG_PRINT("error", ("%s", sslGetErrString(*error)));
    report_errors();
    my_free(ssl_fd);
    DBUG_RETURN(0);
  }

  /*
    Set the ciphers that can be used
    NOTE: SSL_CTX_set_cipher_list will return 0 if
    none of the provided ciphers could be selected
  */
  if (cipher &&
      SSL_CTX_set_cipher_list(ssl_fd->ssl_context, cipher) == 0)
  {
    *error= SSL_INITERR_CIPHERS;
    DBUG_PRINT("error", ("%s", sslGetErrString(*error)));
    report_errors();
    free_vio_ssl_fd(ssl_fd);
    DBUG_RETURN(0);
  }

  /* There should be no pending errors at this point */
  DBUG_ASSERT(ERR_peek_error() == 0);

  /* Load certs from the trusted ca */
  if (SSL_CTX_load_verify_locations(ssl_fd->ssl_context, ca_file, ca_path) == 0)
  {
    DBUG_PRINT("warning", ("SSL_CTX_load_verify_locations failed"));
    if (ca_file || ca_path)
    {
      /* fail only if ca file or ca path were supplied and looking into 
         them fails. */
      *error= SSL_INITERR_BAD_PATHS;
      DBUG_PRINT("error", ("SSL_CTX_load_verify_locations failed : %s", 
                 sslGetErrString(*error)));
      report_errors();
      free_vio_ssl_fd(ssl_fd);
      DBUG_RETURN(0);
    }

    /* otherwise go use the defaults */
    if (SSL_CTX_set_default_verify_paths(ssl_fd->ssl_context) == 0)
    {
      *error= SSL_INITERR_BAD_PATHS;
      DBUG_PRINT("error", ("%s", sslGetErrString(*error)));
      report_errors();
      free_vio_ssl_fd(ssl_fd);
      DBUG_RETURN(0);
    }
  }

  /* SSL_CTX_load_verify_locations sometimes leaves the error stack
     not clear.  Let's clear it. */
  ERR_clear_error();

  if (crl_file || crl_path)
  {
#ifdef HAVE_YASSL
    DBUG_PRINT("warning", ("yaSSL doesn't support CRL"));
    DBUG_ASSERT(0);
#else
    X509_STORE *store= SSL_CTX_get_cert_store(ssl_fd->ssl_context);
    /* Load crls from the trusted ca */
    if (X509_STORE_load_locations(store, crl_file, crl_path) == 0 ||
        X509_STORE_set_flags(store,
                             X509_V_FLAG_CRL_CHECK | 
                             X509_V_FLAG_CRL_CHECK_ALL) == 0)
    {
      DBUG_PRINT("warning", ("X509_STORE_load_locations for CRL failed"));
      *error= SSL_INITERR_BAD_PATHS;
      DBUG_PRINT("error", ("%s", sslGetErrString(*error)));
      report_errors();
      free_vio_ssl_fd(ssl_fd);
      DBUG_RETURN(0);
    }
#endif
  }

  if (vio_set_cert_stuff(ssl_fd->ssl_context, cert_file, key_file, error))
  {
    DBUG_PRINT("error", ("vio_set_cert_stuff failed"));
    report_errors();
    free_vio_ssl_fd(ssl_fd);
    DBUG_RETURN(0);
  }

  /* DH stuff */
  dh=get_dh2048();
  SSL_CTX_set_tmp_dh(ssl_fd->ssl_context, dh);
  DH_free(dh);

#ifndef OPENSSL_NO_ECDH
  {
    /* Elliptic Curve */
    EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    if (ecdh) {
      SSL_CTX_set_tmp_ecdh(ssl_fd->ssl_context, ecdh);
      EC_KEY_free(ecdh);
    }
  }
#endif

  DBUG_PRINT("exit", ("OK 1"));

  DBUG_RETURN(ssl_fd);
}


/************************ VioSSLConnectorFd **********************************/
struct st_VioSSLFd *
new_VioSSLConnectorFd(const char *key_file, const char *cert_file,
                      const char *ca_file, const char *ca_path,
                      const char *cipher, enum enum_ssl_init_error* error,
                      const char *crl_file, const char *crl_path)
{
  struct st_VioSSLFd *ssl_fd;
  int verify= SSL_VERIFY_PEER;

  /*
    Turn off verification of servers certificate if both
    ca_file and ca_path is set to NULL
  */
  if (ca_file == 0 && ca_path == 0)
    verify= SSL_VERIFY_NONE;

  if (!(ssl_fd= new_VioSSLFd(key_file, cert_file, ca_file,
                             ca_path, cipher, TRUE, error,
                             crl_file, crl_path)))
  {
    return 0;
  }

  /* Init the VioSSLFd as a "connector" ie. the client side */

  SSL_CTX_set_verify(ssl_fd->ssl_context, verify, NULL);

  return ssl_fd;
}


/************************ VioSSLConnectorFdFromContext ************************/
struct st_VioSSLFd *
new_VioSSLConnectorFdFromContext(SSL_CTX* context,
                                 enum enum_ssl_init_error *error)
{
  struct st_VioSSLFd *ssl_fd;
  if (!(ssl_fd= ((struct st_VioSSLFd*)
                 my_malloc(sizeof(struct st_VioSSLFd),MYF(0))))) {
    *error = SSL_INITERR_MEMFAIL;
    return NULL;
  }
  ssl_fd->ssl_context = context;
  ssl_fd->owned = FALSE;

  return ssl_fd;
}


/************************ VioSSLAcceptorFd **********************************/
struct st_VioSSLFd *
new_VioSSLAcceptorFd(const char *key_file, const char *cert_file,
		     const char *ca_file, const char *ca_path,
		     const char *cipher, enum enum_ssl_init_error* error,
                     const char *crl_file, const char *crl_path)
{
  struct st_VioSSLFd *ssl_fd;
  int verify= SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
  if (!(ssl_fd= new_VioSSLFd(key_file, cert_file, ca_file,
                             ca_path, cipher, FALSE, error,
                             crl_file, crl_path)))
  {
    return 0;
  }
  /* Init the the VioSSLFd as a "acceptor" ie. the server side */

  /* Set max number of cached sessions, returns the previous size */
  SSL_CTX_sess_set_cache_size(ssl_fd->ssl_context, 128);

  SSL_CTX_set_verify(ssl_fd->ssl_context, verify, NULL);

  /*
    Set session_id - an identifier for this server session
    Use the ssl_fd pointer
   */
  SSL_CTX_set_session_id_context(ssl_fd->ssl_context,
				 (const unsigned char *)ssl_fd,
				 sizeof(ssl_fd));

  return ssl_fd;
}

void free_vio_ssl_fd(struct st_VioSSLFd *fd)
{
  if (fd->owned) {
    SSL_CTX_free(fd->ssl_context);
  }
  my_free(fd);
}
#endif /* HAVE_OPENSSL */
