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

/*******************************************************************
 * EAPPEAP Function implementations
 * 
 * File: eappeap.c
 *
 * Authors: Chris.Hessing@utah.edu
 *
 * $Id: eappeap.c,v 1.26 2004/07/15 04:15:37 chessing Exp $
 * $Date: 2004/07/15 04:15:37 $
 * $Log: eappeap.c,v $
 * Revision 1.26  2004/07/15 04:15:37  chessing
 *
 * True/false int values are now bit flags in a byte.  PEAP now calls back in to functions from eap.c for phase 2 methods.  This allows for any phase 1 EAP type to work.  This resulted in some major changes the functions in eap.c, and in peap_phase2.c.  PEAP has been tested using both MS-CHAPv2, and EAP-MD5 as inner types.  More types need to be tested, and enabled.
 *
 * Revision 1.25  2004/06/15 03:35:20  chessing
 *
 * New updates including fixes to LEAP (keying now works with wireless) and adding EAP-AKA.
 *
 * Revision 1.24  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 "eappeap.h"
#include "peap_phase2.h"
#include "interactive.h"


int eappeap_setup(struct generic_eap_data *thisint)
{
  struct tls_vars *mytls_vars;
  struct phase2_data *p2d;
  struct config_eap_peap *userdata;

  if (!thisint)
    {
      debug_printf(DEBUG_NORMAL, "Invalid interface struct passed to eappeap_setup()!\n");
      return XEMALLOC;
    }

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

  if (userdata == NULL)
    {
      debug_printf(DEBUG_NORMAL, "Userdata == NULL!  We cannot attempt to authenticate!\n");
      return XENOUSERDATA;
    }

  // 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 == NULL)
    {
      debug_printf(DEBUG_NORMAL, "Couldn't allocate memory for eap_data in PEAP!\n");
      return XEMALLOC;
    }

  memset(thisint->eap_data, 0, sizeof(struct tls_vars));
  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 = userdata->cncheck;
  mytls_vars->cnexact = userdata->cnexact;
  mytls_vars->resume = userdata->session_resume;
  mytls_vars->quickResponse = FALSE;
  mytls_vars->cert_loaded = FALSE;
  mytls_vars->verify_mode = SSL_VERIFY_PEER;

  mytls_vars->phase2data = (char *)malloc(sizeof(struct phase2_data));
  if (mytls_vars->phase2data == NULL) return XEMALLOC;
  memset(mytls_vars->phase2data, 0, sizeof(struct phase2_data));

  p2d = (struct phase2_data *)mytls_vars->phase2data;

  p2d->peap_version = 0;

  p2d->eapdata = NULL;

  debug_printf(DEBUG_EVERYTHING, "(EAP-PEAP) Initialized.\n");
  
  if (tls_funcs_init(thisint) != XENONE)
    {
      debug_printf(DEBUG_NORMAL, "Couldn't initialize OpenSSL!\n");
      return XETLSINIT;
    }

  if (userdata->root_cert == NULL)
    {
      debug_printf(DEBUG_NORMAL, "The root cert is set to NULL!  We cannot continue!\n");
      return XENOUSERDATA;
    }

  if (strcmp(userdata->root_cert, "NONE") == 0)
    {
      // We were told not to verify certificates.  Spew out a warning, and
      // then do it!
      mytls_vars->verify_mode = SSL_VERIFY_NONE;
      debug_printf(DEBUG_NORMAL, "****WARNING**** Turning off certificate verification is a *VERY* bad idea!  You should not use this mode outside of basic testing, as it will compromise the security of your connection!\n");
    } else {
      if (tls_funcs_load_root_certs(thisint, userdata->root_cert, 
				    userdata->root_dir, userdata->crl_dir) != XENONE)
	{
	  debug_printf(DEBUG_NORMAL, "Couldn't load root certificates!\n");
	  return XETLSINIT;
	}
    }

  if ((userdata->user_cert != NULL) && ((userdata->user_key_pass != NULL) ||
				   (thisint->tempPwd != NULL)))
    {
      debug_printf(DEBUG_NORMAL, "Using user certificate for PEAP!\n");
      tls_funcs_load_user_cert(thisint, userdata->user_cert, userdata->user_key,
			       userdata->user_key_pass, userdata->random_file);
      mytls_vars->cert_loaded = TRUE;
    }

  if (userdata->user_cert == NULL) mytls_vars->cert_loaded = TRUE;

  return XENONE;
}

int eappeap_process(struct generic_eap_data *thisint, u_char *dataoffs, 
		    int insize, u_char *outframe, int *outsize)
{
  struct config_eap_peap *userdata;
  struct tls_vars *mytls_vars;
  struct phase2_data *p2d;
  int peap_version;
  int retVal;

  if ((!thisint) || (!dataoffs) || (!outframe))
    {
      debug_printf(DEBUG_NORMAL, "Invalid parameters passed to eappeap_process()!\n");
      return XEMALLOC;
    }

  if (insize > 1520)
    {
      debug_printf(DEBUG_NORMAL, "Packet too large in eappeap_process()! Ignoring!\n");
      return XEBADPACKETSIZE;
    }

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

  if (!userdata)
    {
      debug_printf(DEBUG_NORMAL, "Invalid userdata structure in eappeap_process()!\n");
      return XENOUSERDATA;
    }

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

  if (!mytls_vars)
    {
      debug_printf(DEBUG_NORMAL, "Invalid EAP type data passed in to eappeap_process()!\n");
      return XEMALLOC;
    }

  p2d = (struct phase2_data *)mytls_vars->phase2data;

  if (!p2d)
    {
      debug_printf(DEBUG_NORMAL, "No phase 2 data available in eappeap_process()!\n");
      return XEMALLOC;
    }

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

  // PEAP is slightly different than others.  Since we don't *need* to have
  // a client certificate to make things work correctly, we may not need
  // a password here.
  if (userdata->user_cert != NULL)
    {
      if ((thisint->tempPwd == NULL) && (userdata->user_key_pass == NULL))
	{
	  thisint->need_password = 1;
	  thisint->eaptype = strdup("EAP-PEAP User Certificate");
	  thisint->eapchallenge = NULL;
	  
	  *outsize = 0;
	  return XENONE;
	}

      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;

	    // If we used the GUI to get a password, we need to free it
	    // so that phase 2 can make use of it.
	    if (thisint->tempPwd != NULL)
	      {
		free(thisint->tempPwd);
		thisint->tempPwd = NULL;
	      }
	  }
      }   
    }

  if (dataoffs == NULL) return XENONE;

/* PEAP adds some version bits to flags byte.  They need to be stripped out. */

  peap_version = ((uint8_t)dataoffs[0] & 0x03);  // Get the version #.

  set_peap_version(p2d, peap_version);  // Tell PEAP what version we want to use.
  dataoffs[0] = ((uint8_t)dataoffs[0] & 0xfc);  // Mask out the version bits.
  
  tls_funcs_decode_packet(thisint, dataoffs, insize,  outframe, outsize, 
			  (phase2_call)peap_do_phase2, userdata->chunk_size);

  // We need to reset the version bits, just in case we store this frame for 
  // use later.
  dataoffs[0] = dataoffs[0]+p2d->peap_version;

  if (*outsize <= 0)
    {
      debug_printf(DEBUG_AUTHTYPES, "Nothing returned from PEAP!\n");
      *outsize = 0;
      return 0;
    }
  
  // By the time we come out the first time, we should have decided on which
  // PEAP version we want to use.  So, set up the values needed to generate
  // the keying material.
  
  if (mytls_vars->sessionkeyconst == NULL)
    {
      switch (p2d->peap_version)
	{
	case PEAP_VERSION0:
	  debug_printf(DEBUG_AUTHTYPES, "Setting Key Constant for PEAP v0!\n");
	  mytls_vars->sessionkeyconst = (char *)malloc(PEAP_SESSION_KEY_CONST_SIZE);
	  if (mytls_vars->sessionkeyconst == NULL) return XEMALLOC;
	  
	  bzero(mytls_vars->sessionkeyconst, PEAP_SESSION_KEY_CONST_SIZE);
	  strncpy(mytls_vars->sessionkeyconst, PEAP_SESSION_KEY_CONST,
		  PEAP_SESSION_KEY_CONST_SIZE);
	  mytls_vars->sessionkeylen = PEAP_SESSION_KEY_CONST_SIZE;
	  break;
	  
	case PEAP_VERSION1:
	  debug_printf(DEBUG_AUTHTYPES, "Setting Key Constant for PEAP v1!\n");
	  mytls_vars->sessionkeyconst = (char *)malloc(PEAPv1_SESSION_KEY_CONST_SIZE);
	  if (mytls_vars->sessionkeyconst == NULL) return XEMALLOC;
	  
	  bzero(mytls_vars->sessionkeyconst, PEAPv1_SESSION_KEY_CONST_SIZE);
	  strncpy(mytls_vars->sessionkeyconst, PEAPv1_SESSION_KEY_CONST,
		  PEAPv1_SESSION_KEY_CONST_SIZE);
	  mytls_vars->sessionkeylen = PEAPv1_SESSION_KEY_CONST_SIZE;
	  break;
	  
	default:
	  debug_printf(DEBUG_NORMAL, "Unknown PEAP version!\n");
	  break;
	}
    }

  if (*outsize > 0)
    {
      outframe[0] = outframe[0]+p2d->peap_version;
    }

  return XENONE;
}

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

  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 eappeap_cleanup(struct generic_eap_data *thisint)
{
  struct tls_vars *mytls_vars;

  if (!thisint)
    {
      debug_printf(DEBUG_NORMAL, "Invalid interface struct passed to eappeap_cleanup()!\n");
      return XEMALLOC;
    }

  mytls_vars = (struct tls_vars *)thisint->eap_data;
  
  if (!mytls_vars)
    {
      debug_printf(DEBUG_NORMAL, "Invalid EAP type data in eappeap_cleanup()!\n");
      return XEMALLOC;
    }

  if (mytls_vars->phase2data != NULL)
    {
      struct phase2_data *p2d;
      p2d = (struct phase2_data *) mytls_vars->phase2data;
      free(p2d->eapdata);
      free(mytls_vars->phase2data);
    }
  tls_funcs_cleanup(thisint);

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

int eappeap_failed(struct generic_eap_data *thisint)
{
  if (!thisint)
    {
      debug_printf(DEBUG_NORMAL, "Invalid EAP data in eappeap_failed()!\n");
      return XEMALLOC;
    }

  // Let our phase 2 die out, if there is one.
  peap_phase2_failed(thisint);

  tls_funcs_failed(thisint);

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