/**
 * A client-side 802.1x implementation supporting EAP/TLS
 *
 * This code is released under both the GPL version 2 and BSD licenses.
 * Either license may be used.  The respective licenses are found below.
 *
 * Copyright (C) 2002 Bryan D. Payne & Nick L. Petroni Jr.
 * All Rights Reserved
 *
 * --- GPL Version 2 License ---
 * 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; either version 2
 * of the License, or (at your option) any later version.
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * --- BSD License ---
 * 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.
 *  - All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *       This product includes software developed by the University of
 *       Maryland at College Park and its contributors.
 *  - Neither the name of the University 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 COPYRIGHT OWNER 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.
 */

/*******************************************************************
 * En/Decrypt Function implementations
 *
 * File: tls_crypt.c
 *
 * Authors: Chris.Hessing@utah.edu
 *
 * $Id: tls_crypt.c,v 1.10 2004/06/17 22:56:59 chessing Exp $
 * $Date: 2004/06/17 22:56:59 $
 * $Log: tls_crypt.c,v $
 * Revision 1.10  2004/06/17 22:56:59  chessing
 *
 * Fixed the problem where an attempt to execute an invalid program would result in a second instance of XSupplicant running.  (Which would then cause all kinds of interesting problems. ;)  Also added a bunch of additional debugging to the TLS code to try to resolve the strange stalls that sometimes happen in authentications that use TLS for phase 1.
 *
 * Revision 1.9  2004/06/15 03:22:32  chessing
 *
 * XSupplicant Release 1.0
 *
 *
 *******************************************************************/

#include <string.h>
#include <strings.h>
#include <openssl/ssl.h>
#include <stdint.h>
#include <netinet/in.h>

#include "config.h"
#include "profile.h"
#include "eap.h"
#include "eaptls.h"
#include "tls_funcs.h"
#include "../../xsup_debug.h"
#include "../../xsup_err.h"

u_char *tls_crypt_gen_keyblock(struct generic_eap_data *thisint, char *sesskey,
			      int sesskeylen)
{
  u_char seed[SSL3_RANDOM_SIZE*2];
  u_char *p = seed;
  struct tls_vars *mytls_vars;
  u_char *retblock;

  debug_printf(DEBUG_EVERYTHING, "Generating key block!\n");

  if ((!thisint) || (!thisint->eap_data))
    {
      debug_printf(DEBUG_NORMAL, "Invalid data passed in to tls_crypt_gen_keyblock()!\n");
      return NULL;
    }

  if (!sesskey)
    {
      debug_printf(DEBUG_NORMAL, "Invalid session constant!\n");
      return NULL;
    }

  mytls_vars = (struct tls_vars *)thisint->eap_data;

  if (!mytls_vars->ssl)
    {
      debug_printf(DEBUG_NORMAL, "No valid SSL context found!\n");
      return NULL;
    }

  debug_printf(DEBUG_EVERYTHING, "Using session key const of : %s\n",
	       sesskey);

  retblock = (u_char *)malloc(TLS_SESSION_KEY_SIZE);
  if (!retblock)
    return NULL;

  memcpy(p, mytls_vars->ssl->s3->client_random, SSL3_RANDOM_SIZE);
  p+= SSL3_RANDOM_SIZE;
  memcpy(p, mytls_vars->ssl->s3->server_random, SSL3_RANDOM_SIZE);
  tls_funcs_PRF(mytls_vars->ssl->session->master_key, 
		mytls_vars->ssl->session->master_key_length,
		sesskey, sesskeylen, seed, 
		SSL3_RANDOM_SIZE * 2, retblock, 
		TLS_SESSION_KEY_SIZE);

  return retblock;
}

// This function written by Danielle Brevi
int tls_crypt_decrypt(struct generic_eap_data *thisint, u_char *in_data, int in_size, u_char *out_data, int *out_size)
{
  struct tls_vars *mytls_vars;
  int rc=0;
  u_char p[1000];

  if ((!thisint) || (!thisint->eap_data) || (!in_data) || (!out_data) ||
      (!out_size))
    {
      debug_printf(DEBUG_NORMAL, "Invalid data passed in to tls_crypt_decrypt()!\n");
      return XEMALLOC;
    }

  mytls_vars = (struct tls_vars *)thisint->eap_data;
  bzero(p,1000);

  if (BIO_reset(mytls_vars->ssl_in) <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt.c, BIO_reset(mytls_vars->ssl_in) failed.\n");
      tls_funcs_process_error();
      return -1;
    }

  rc=BIO_write(mytls_vars->ssl_in, in_data, in_size);

  if (BIO_reset(mytls_vars->ssl_out) <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt.c, BIO_reset(mytls_vars->ssl_out) failed.\n");
      tls_funcs_process_error();
      return -1;
    }

  rc=SSL_read(mytls_vars->ssl, out_data, 1000);
  if (rc <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt.c, SSL_read(mytls_vars->ssl, out_data, 1000) failed.\n");
      tls_funcs_process_error();
      return -1;
    }

  *out_size = rc;

  return XENONE;
}


int tls_crypt_encrypt(struct generic_eap_data *thisint, u_char *in_data, int in_size, u_char *out_data, int *out_size)
{
  struct tls_vars *mytls_vars;
  int rc=0;
  u_char *p;
  int to_send_size = 0;
  uint64_t length;

  if ((!thisint) || (!thisint->eap_data) || (!in_data) || (!out_data))
    {
      debug_printf(DEBUG_NORMAL, "Invalid data passed in to tls_crypt_encrypt()!\n");
      return XEMALLOC;
    }

  mytls_vars = (struct tls_vars *)thisint->eap_data;

  // We need to modify this, to read more when there is more to be returned.
  p = (u_char *)malloc(1000);
  if (p == NULL)
    {
      debug_printf(DEBUG_NORMAL, "Error with malloc of \"p\" in tls_crypt_encrypt().\n");
      return -1;
    }

  bzero(p,1000);
  
  if (BIO_reset(mytls_vars->ssl_in) <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt.c, BIO_reset(mytls_vars->ssl_in) failed.\n");
      tls_funcs_process_error();
      return -1;
    }

  if (BIO_reset(mytls_vars->ssl_out) <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt.c, BIO_reset(mytls_vars->ssl_out) failed.\n");
      tls_funcs_process_error();
      return -1;
    }

  rc=SSL_write(mytls_vars->ssl, in_data, in_size);
  if (rc <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt.c, SSL_write in encrypt failed!\n");
      tls_funcs_process_error();
      return -1;
    }

  rc = BIO_read(mytls_vars->ssl_out, p, 1000);   // Allow largest possible read.
  if (rc <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt.c, BIO_read in encrypt failed!\n");
      tls_funcs_process_error();
      return -1;
    }

  to_send_size = rc;

  out_data[0] = EAPTLS_LENGTH_INCL;  // No more to send.
  length = ntohl(to_send_size+5);
  memcpy(&out_data[1], &length, 4);
  memcpy(&out_data[5], p, to_send_size);

  *out_size = to_send_size+5;
  if(p)
    {
      free(p);
      p = NULL;
    }
  return XENONE;
}

int tls_crypt_encrypt_nolen(struct generic_eap_data *thisint, u_char *in_data, int in_size, u_char *out_data, int *out_size)
{
  struct tls_vars *mytls_vars;
  int rc=0;
  u_char *p;
  int to_send_size = 0;

  if ((!thisint) || (!thisint->eap_data) || (!in_data) || (!out_data))
    {
      debug_printf(DEBUG_NORMAL, "Invalid data passed in to tls_crypt_encrypt()!\n");
      return XEMALLOC;
    }

  mytls_vars = (struct tls_vars *)thisint->eap_data;

  // We need to modify this, to read more when there is more to be returned.
  p = (u_char *)malloc(1000);
  if (p == NULL)
    {
      debug_printf(DEBUG_NORMAL, "Error with malloc of \"p\" in tls_crypt_encrypt().\n");
      return -1;
    }

  bzero(p,1000);
  
  if (BIO_reset(mytls_vars->ssl_in) <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt (nolen), BIO_reset failed in encrypt!\n");
      tls_funcs_process_error();
      return -1;
    }

  if (BIO_reset(mytls_vars->ssl_out) <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt (nolen), BIO_reset (2) failed in encrypt!\n");
      tls_funcs_process_error();
      return -1;
    }

  rc=SSL_write(mytls_vars->ssl, in_data, in_size);
  if (rc <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt (nolen), SSL_write failed in encrypt!\n");
      tls_funcs_process_error();
    }

  rc = BIO_read(mytls_vars->ssl_out, p, 1000);   // Allow largest possible read.
  if (rc <= 0)
    {
      debug_printf(DEBUG_NORMAL, "In tls_crypt (nolen), BIO_read failed in encrypt!\n");
      tls_funcs_process_error();
      return -1;
    }

  to_send_size = rc;

  out_data[0] = 0x00;  // No more to send.
  memcpy(&out_data[1], p, to_send_size);

  *out_size = to_send_size+1;
  if(p)
    {
      free(p);
      p = NULL;
    }
  return XENONE;
}
