/**
 * 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.
 */

/*******************************************************************
 * EAPTLS (RFC 2716) Function implementations
 * 
 * File: eaptls.c
 *
 * Authors: Chris.Hessing@utah.edu
 *
 * $Id: eaptls.c,v 1.27 2004/06/15 03:35:21 chessing Exp $
 * $Date: 2004/06/15 03:35:21 $
 * $Log: eaptls.c,v $
 * Revision 1.27  2004/06/15 03:35:21  chessing
 *
 * New updates including fixes to LEAP (keying now works with wireless) and adding EAP-AKA.
 *
 * Revision 1.26  2004/06/15 03:22:31  chessing
 *
 * XSupplicant Release 1.0
 *
 *
 *******************************************************************/

#include <string.h>
#include "profile.h"
#include "config.h"
#include "xsup_debug.h"
#include "xsup_err.h"
#include "frame_structs.h"
#include "eap_types/tls/eaptls.h"
#include "eap_types/tls/tls_funcs.h"
#include "eap.h"
#include "interactive.h"

int eaptls_setup(struct generic_eap_data *thisint)
{
  struct tls_vars *mytls_vars;
  int retVal;
  struct config_eap_tls *userdata;

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

  userdata = (struct config_eap_tls *)thisint->eap_conf_data;

  retVal = XENONE;

  // First, set up the structure to hold all of our instance specific
  // variables.
  thisint->eap_data = (char *)malloc(sizeof(struct tls_vars));
  if (!thisint->eap_data) return XEMALLOC;

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

  // Set our variables to NULL.
  mytls_vars->ctx = NULL;
  mytls_vars->ssl = NULL;
  mytls_vars->ssl_in = NULL;
  mytls_vars->ssl_out = NULL;
  mytls_vars->tlsoutdata = NULL;
  mytls_vars->tlsoutsize = 0;
  mytls_vars->tlsoutptr = 0;
  mytls_vars->cncheck = NULL;    // NO
  mytls_vars->cnexact = 0;
  mytls_vars->phase = 0;         // This has no meaning for TLS.
  mytls_vars->resume = userdata->session_resume;
  mytls_vars->resuming = 0;
  mytls_vars->quickResponse = FALSE;
  mytls_vars->cert_loaded = FALSE;
  mytls_vars->verify_mode = SSL_VERIFY_PEER;  // We don't want the option of
                                              // not checking certs here!  It
                                              // would be a *SERIOUSLY* bad
                                              // idea!

  mytls_vars->sessionkeyconst = (char *)malloc(TLS_SESSION_KEY_CONST_SIZE);
  if (mytls_vars->sessionkeyconst == NULL) return XEMALLOC;

  strncpy(mytls_vars->sessionkeyconst, TLS_SESSION_KEY_CONST,
	  TLS_SESSION_KEY_CONST_SIZE);

  mytls_vars->sessionkeylen = TLS_SESSION_KEY_CONST_SIZE;

  debug_printf(DEBUG_EVERYTHING, "(EAP-TLS) Initialized.\n");
  
  if ((retVal = tls_funcs_init(thisint))!=XENONE)
    {
      debug_printf(DEBUG_NORMAL, "Error initializing TLS functions!\n");
      return retVal;
    }
 
  if ((retVal = tls_funcs_load_root_certs(thisint, userdata->root_cert,
					  userdata->root_dir, userdata->crl_dir))!=XENONE)
    {
      debug_printf(DEBUG_NORMAL, "Error loading root certificate!\n");
      return retVal;
    }

  if (userdata->user_key_pass != NULL)
    {
      if ((retVal = tls_funcs_load_user_cert(thisint, userdata->user_cert, 
					     userdata->user_key,
					     userdata->user_key_pass,
					     userdata->random_file))!=XENONE)
	{
	  debug_printf(DEBUG_NORMAL, "Error loading user certificate!\n");
	  return retVal;
	} else {

	  // Otherwise, the certificate is loaded.
	  mytls_vars->cert_loaded = TRUE;

	  // We really don't need to free tempPwd here, since TLS won't have
	  // a second phase.  But, we do it anyway, just to keep things
	  // consistant.
	  if (thisint->tempPwd != NULL)
	    {
	      free(thisint->tempPwd);
	      thisint->tempPwd = NULL;
	    }
	}
    }

  if (tls_funcs_load_random(thisint, userdata->random_file) != XENONE)
    {
      debug_printf(DEBUG_NORMAL, "Failed to load random data\n");
      return -1;
    }

  return XENONE;
}

int eaptls_process(struct generic_eap_data *thisint, u_char *dataoffs, 
		   int insize, u_char *outframe, int *outsize)
{
  struct config_eap_tls *userdata;
  struct tls_vars *mytls_vars;
  int retVal;

  if ((!thisint) || (!thisint->eap_conf_data) || (!outframe) || (!thisint->eap_data))
    {
      debug_printf(DEBUG_NORMAL, "Invalid data passed to eaptls_process()!\n");
      return XEMALLOC;
    }

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

  // The state machine wants to know if we have anything else to say.
  // We may be waiting for the server to send us more information, or
  // we may need to send a request to the GUI for a password, and wait
  // for an answer.
  
  if (mytls_vars->cert_loaded == FALSE)
    {
      if ((thisint->tempPwd == NULL) && (userdata->user_key_pass == NULL))
	{
	  thisint->need_password = 1;
	  thisint->eaptype = strdup("EAP-TLS User Certificate");
	  thisint->eapchallenge = NULL;

	  *outsize = 0;

	  return XENONE;
	}

      if ((userdata->user_key_pass == NULL) && (thisint->tempPwd != NULL))
	{
	  userdata->user_key_pass = thisint->tempPwd;
	  thisint->tempPwd = NULL;
	}

      if ((mytls_vars->cert_loaded == FALSE) && ((thisint->tempPwd != NULL) ||
						 (userdata->user_key_pass != NULL)))
      {
	// Load the user certificate.
	if ((retVal = tls_funcs_load_user_cert(thisint, userdata->user_cert, 
					       userdata->user_key,
					       userdata->user_key_pass,
					       userdata->random_file))!=XENONE)
	  {
	    debug_printf(DEBUG_NORMAL, "Error loading user certificate!\n");
	    return retVal;
	  } else {

	    // Otherwise, the certificate is loaded.
	    mytls_vars->cert_loaded = TRUE;
	  }
      }  
    }

  // Make sure we have something to process...
  if (dataoffs == NULL) return XENONE;
  
  retVal=tls_funcs_decode_packet(thisint, dataoffs, insize, outframe, outsize, 
				 NULL, userdata->chunk_size);

  return retVal;
}

int eaptls_get_keys(struct interface_data *thisint)
{
  if (!thisint)
    {
      debug_printf(DEBUG_NORMAL, "Invalid interface struct passed to eaptls_get_keys()!\n");
      return -1;
    }

  if (thisint->keyingMaterial != NULL)
    {
      free(thisint->keyingMaterial);
    }

  thisint->keyingMaterial = tls_funcs_gen_keyblock(thisint->userdata->activemethod);
  thisint->keyingLength = 32;
  
  if (thisint->keyingMaterial == NULL) return -1;
  return 0;
}

int eaptls_cleanup(struct generic_eap_data *thisint)
{
  struct tls_vars *mytls_vars;

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

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

  if (mytls_vars->sessionkeyconst) free(mytls_vars->sessionkeyconst);

  if (mytls_vars) free(mytls_vars);

  debug_printf(DEBUG_EVERYTHING, "(EAP-TLS) Cleaned up.\n");
  return XENONE;
}

int eaptls_failed(struct generic_eap_data *thisint)
{
  struct tls_vars *mytls_vars;

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

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

  debug_printf(DEBUG_EVERYTHING, "(EAP-TLS) Failed. Resetting.\n");
  return XENONE;
}
