/**
 * A client-side 802.1x implementation supporting EAP/SIM
 *
 * 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) 2003, 2004 Chris Hessing
 * 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.
 */

/*******************************************************************
 * EAPOL Function implementations for supplicant
 * 
 * File: eapsim.c
 *
 * Authors: Chris.Hessing@utah.edu
 *
 * $Id: eapsim.c,v 1.20 2004/08/20 04:42:28 chessing Exp $
 * $Date: 2004/08/20 04:42:28 $
 * $Log: eapsim.c,v $
 * Revision 1.20  2004/08/20 04:42:28  chessing
 * Set all of the new scanning and WPA code to be disabled by default, so that a 1.0.1 release can be made.  Added additional error message output to AKA code.  Fixed a few memory leaks in the AKA code.
 *
 * Revision 1.19  2004/07/19 02:43:17  chessing
 *
 * Changed things to get rid of Linux specific pieces in the interface_data struct. Fixed up EAP-SIM and EAP-AKA to skip AVPs that we don't support.  (We print a mesage, and move on.)  Added the --enable-radiator-test option to configure EAP-AKA to use the test vectors included with Radiator's AKA module.  (To use this mode, no SIM card is required, but the PCSC library is still needed to build.  Also, some errors will be displayed.)
 *
 * Revision 1.18  2004/06/15 03:35:20  chessing
 *
 * New updates including fixes to LEAP (keying now works with wireless) and adding EAP-AKA.
 *
 * Revision 1.17  2004/06/15 03:22:31  chessing
 *
 * XSupplicant Release 1.0
 *
 *
 *******************************************************************/

/*******************************************************************
 *
 * The development of the EAP/SIM support was funded by Internet
 * Foundation Austria (http://www.nic.at/ipa)
 *
 *******************************************************************/


#ifdef EAP_SIM_ENABLE     // Only build this if it has been enabled.

#include <inttypes.h>
#include <openssl/hmac.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#include "winscard.h"
#include "interactive.h"
#include "profile.h"
#include "config.h"
#include "eap.h"
#include "eapsim.h"
#include "sm_handler.h"
#include "sim.h"
#include "xsup_debug.h"
#include "xsup_err.h"

char *do_sha1(char *tohash, int size)
{
  EVP_MD_CTX ctx;
  char *hash_ret;
  int evp_ret_len;

  if ((!tohash) || (size < 1))
    {
      debug_printf(DEBUG_NORMAL, "Invalid value passed to do_sha1()!\n");
      return NULL;
    }

  hash_ret = (char *)malloc(21);  // We should get 20 bytes returned.
  if (hash_ret == NULL)
    {
      printf("There was a malloc() error in eapsim.c with hash_ret!\n");
      return NULL;
    }
 
  EVP_DigestInit(&ctx, EVP_sha1());
  EVP_DigestUpdate(&ctx, tohash, size);
  EVP_DigestFinal(&ctx, hash_ret, (int *)&evp_ret_len);

  if (evp_ret_len != 20)
    {
      debug_printf(DEBUG_NORMAL, "Invalid result from OpenSSL SHA calls! (%s:%d)\n", __FUNCTION__, __LINE__);
      return NULL;
    }

  return hash_ret;
}

int eapsim_get_username(struct interface_data *thisint)
{
  char *imsi;  
  char realm[25], card_mode=0;
  char *readers, *username;
  struct config_eap_sim *userdata;
  struct generic_eap_data mydata;
  SCARDCONTEXT ctx;
  SCARDHANDLE hdl;

  if ((!thisint) || (!thisint->userdata) || (!thisint->userdata->methods) ||
      (!thisint->userdata->methods->method_data))
    {
      debug_printf(DEBUG_NORMAL, "Invalid interface structure passed to eapsim_get_username()!\n");
      return XEMALLOC;
    }

  userdata = (struct config_eap_sim *)thisint->userdata->methods->method_data;

  mydata.eap_conf_data = userdata;

  // Initalize our smartcard context, and get ready to authenticate.
  if (sm_handler_init_ctx(&ctx) != 0)
    {
      debug_printf(DEBUG_NORMAL, "Couldn't initialize smart card context!\n");
      return XESIMGENERR;
    }

  readers = sm_handler_get_readers(&ctx);
  if (readers == NULL) 
    {
      debug_printf(DEBUG_NORMAL, "Couldn't find any valid card readers!\n");
      return XESIMGENERR;
    }

  // Connect to the smart card.
  if (sm_handler_card_connect(&ctx, &hdl, readers) != 0)
    {
      debug_printf(DEBUG_NORMAL, "Error connecting to smart card reader!\n");
      return XESIMGENERR;
    }

  // Wait for up to 10 seconds for the smartcard to become ready.
  if (sm_handler_wait_card_ready(&hdl, 10) != 0)
    {
      debug_printf(DEBUG_NORMAL, "Smart Card wasn't ready after 10 seconds!\n");
      return XESIMGENERR;
    }

  imsi = sm_handler_2g_imsi(&hdl, card_mode, userdata->password);
  if (imsi == NULL)
    {
      debug_printf(DEBUG_NORMAL, "Error starting smart card, and getting IMSI!\n");
      return XESIMGENERR;
    }

  debug_printf(DEBUG_AUTHTYPES, "SIM IMSI : %s\n",imsi);

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

  thisint->userdata->identity = (char *)malloc(256);  
  if (thisint->userdata->identity == NULL) 
    {
      debug_printf(DEBUG_NORMAL, "Couldn't allocate memory for identity information!  (%s:%d)\n", __FUNCTION__, __LINE__);
      return XEMALLOC;
    }

  username = thisint->userdata->identity;
  userdata->username = username;
  bzero(username, 50);

  username[0] = '1';  // An IMSI should always start with a 1.
  strncpy(&username[1], imsi, 18);

  if (userdata->auto_realm == TRUE)
    {
      bzero(&realm, 25);
      sprintf((char *)&realm, "@mnc%c%c%c.mcc%c%c%c.owlan.org",
	      username[4], username[5], username[6], username[1], username[2],
	      username[3]);

      debug_printf(DEBUG_AUTHTYPES, "Realm Portion : %s\n",realm);
      strcat(username, realm);
    }

  // Close the smartcard, so that we know what state we are in.
  sm_handler_close_sc(&hdl, &ctx);

  free(imsi);
  imsi = NULL;

  free(readers);
  readers = NULL;

  debug_printf(DEBUG_AUTHTYPES, "Username is now : %s\n", username);

  return XENONE;
}

int eapsim_setup(struct generic_eap_data *thisint)
{
  struct eaptypedata *mydata;
  struct config_eap_sim *userdata;
  char *imsi;

  debug_printf(DEBUG_AUTHTYPES, "(EAP-SIM) Initalized\n");

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

  thisint->eap_data = (char *)malloc(sizeof(struct eaptypedata));
  if (thisint->eap_data == NULL)
    {
      debug_printf(DEBUG_NORMAL, "Couldn't allocate memory for EAP specific data! (%s:%d)\n", __FUNCTION__, __LINE__);
      return XEMALLOC;
    }

  mydata = (struct eaptypedata *)thisint->eap_data;
  userdata = (struct config_eap_sim *)thisint->eap_conf_data;

  mydata->workingversion = 0;
  mydata->numrands = 0;
  mydata->verlistlen = 0;
  mydata->verlist = NULL;
  mydata->nonce_mt = NULL;
  mydata->keyingMaterial = NULL;
  bzero(&mydata->triplet[0], 3*sizeof(struct triplets));

  thisint->eap_data = (void *)mydata;

  // Initalize our smartcard context, and get ready to authenticate.
  if (sm_handler_init_ctx(&mydata->scntx) != 0)
    {
      debug_printf(DEBUG_NORMAL, "Couldn't initialize smart card context!\n");
      return XESIMGENERR;
    }

  mydata->readers = sm_handler_get_readers(&mydata->scntx);
  if (mydata->readers == NULL) 
    {
      debug_printf(DEBUG_NORMAL, "Couldn't find any readers attached to the system!\n");
      return XESIMGENERR;
    }

  // Connect to the smart card.
  if (sm_handler_card_connect(&mydata->scntx, &mydata->shdl, mydata->readers) != 0)
    {
      debug_printf(DEBUG_NORMAL, "Error connecting to smart card reader!\n");
      return XESIMGENERR;
    }

  // Wait for up to 20 seconds for the smartcard to become ready.
  if (sm_handler_wait_card_ready(&mydata->shdl, 20) != 0)
    {
      debug_printf(DEBUG_NORMAL, "Smart Card wasn't ready after 20 seconds!\n");
      return XESIMGENERR;
    }

  imsi = sm_handler_2g_imsi(&mydata->shdl, mydata->card_mode, userdata->password);
  if (imsi == NULL)
    {
      debug_printf(DEBUG_NORMAL, "Error starting smart card, and getting IMSI!\n");
      return XESIMGENERR;
    }

  if (userdata->username == NULL)
    {
      userdata->username = imsi;
    } else {
      free(imsi);
      imsi = NULL;
    }

  return XENONE;
}

int eapsim_process(struct generic_eap_data *thisint, u_char *dataoffs,
		   int insize, u_char *out, int *outsize)
{
  int packet_offset, outptr, value16, retval;
  struct typelength *typelen;
  struct eaptypedata *mydata;
  char nsres[16], *username, mac_calc[16], K_int[16];
  struct config_eap_sim *userdata;

  if ((!thisint) || (!thisint->eap_data))
    {
      debug_printf(DEBUG_NORMAL, "Invalid interface struct passed in to eapsim_process()!\n");
      return XEMALLOC;
    }

  mydata = (struct eaptypedata *)thisint->eap_data;
  userdata = (struct config_eap_sim *)thisint->eap_conf_data;

  bzero(nsres, 16);

  if (!userdata)
    {
      debug_printf(DEBUG_NORMAL, "Invalid user data struct in eapsim_process()!\n");
      return XEMALLOC;
    }

  if ((thisint->tempPwd == NULL) && (userdata->password == NULL))
    {
      thisint->need_password = 1;
      thisint->eaptype = strdup("EAP-SIM");
      thisint->eapchallenge = NULL;
      
      *outsize = 0;
      return XENONE;
    }

  // Make sure we have something to process...
  if (dataoffs == NULL) return XENONE;

  if (userdata->username == NULL)
    {
      username = thisint->identity;
    } else {
      username = userdata->username;
    }

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

  *outsize = 0;
  bzero(&mac_calc[0], 16);

  switch (dataoffs[0])
    {
    case SIM_START:
      retval = sim_build_start(mydata, out, &outptr);
      if (retval != XENONE) return retval;
      packet_offset = 3;
     
      // Process SIM value fields.
      while (packet_offset < insize)
	{
	  switch (dataoffs[packet_offset])
	    {
	    case AT_MAC:
	      debug_printf(DEBUG_NORMAL, "You cannot have an AT_MAC in a Start packet!\n");
	      return XESIMNOATMAC;

	    case AT_ANY_ID_REQ:
	    case AT_FULLAUTH_ID_REQ:
	    case AT_PERMANENT_ID_REQ:
	      retval = sim_build_fullauth(username, dataoffs, &packet_offset, 
					  out, &outptr);
	      if (retval != XENONE) return retval;
	      break;
	      
	    case AT_VERSION_LIST:
	      retval = sim_at_version_list(username, mydata, dataoffs, 
					   &packet_offset, out, &outptr);
	      if (retval != XENONE) return retval;
	      break;
	      
	    default:
	      debug_printf(DEBUG_NORMAL, "Unknown SIM type! (%02X)\n",
			   dataoffs[packet_offset]);
	      return XESIMBADTYPE;
	    }
	}
      // Write the length in the response header.
      value16 = htons(outptr);
      memcpy((char *)&out[1], &value16, 2); 
      *outsize = (outptr);
      break;

    case SIM_CHALLENGE:
      debug_printf(DEBUG_AUTHTYPES, "Got SIM_CHALLENGE!\n");
      packet_offset = 3;

      typelen = (struct typelength *)&out[0];
      typelen->type = SIM_CHALLENGE;
      outptr = 3;

      while (packet_offset < insize)
	{
	  switch (dataoffs[packet_offset])
	    {
	    case AT_RAND:
	      retval = sim_do_at_rand(mydata, username, (char *)&nsres, 
				      dataoffs, &packet_offset, out, &outptr, 
				      &K_int[0]);
	      if (retval != XENONE) return retval;
	      break;

	    case AT_IV:
	      debug_printf(DEBUG_AUTHTYPES, "Got an IV (Not supported)\n");
	      sim_skip_not_implemented(dataoffs, &packet_offset);
	      break;

	    case AT_ENCR_DATA:
	      debug_printf(DEBUG_AUTHTYPES, "Got an AT_ENCR_DATA (Not supported)\n");
	      sim_skip_not_implemented(dataoffs, &packet_offset);
	      break;

	    case AT_MAC:
	      retval = sim_do_at_mac(thisint, mydata, dataoffs, insize, 
				     &packet_offset, out, &outptr, &K_int[0]);
	      if (retval != XENONE) return retval;
	      break;
	    }
	}

      if (mydata->workingversion == 1)
	{
	  debug_printf(DEBUG_NORMAL, "nsres = ");
	  debug_hex_printf(DEBUG_NORMAL, nsres, 12);

	  retval = sim_do_v1_response(thisint, out, &outptr, (char *)&nsres, 
				      &K_int[0]);
	  if (retval != XENONE) return retval;
	}

      value16 = htons(outptr);
      memcpy((char *)&out[1], &value16, 2);

      *outsize = outptr;
      break;
	  
    case SIM_NOTIFICATION:
      debug_printf(DEBUG_NORMAL, "Got SIM_NOTIFICATION! (Unsupported)\n");
      break;
      
    case SIM_REAUTHENTICATION:
      debug_printf(DEBUG_NORMAL, "Got SIM_REAUTHENTICATION! (Unsupported)\n");
      break;
      
    default:
      debug_printf(DEBUG_NORMAL, "Unknown SubType value! (%d)\n", 
		   dataoffs[0]);
      break;
    }
  out[2] = 0;

  return XENONE;
}

int eapsim_get_keys(struct interface_data *thisint)
{
  struct eaptypedata *mydata;

  if ((!thisint) || (!thisint->userdata) || (!thisint->userdata->activemethod)
      || (!thisint->userdata->activemethod->eap_data))
    {
      debug_printf(DEBUG_NORMAL, "Invalid interface structure passed to eapsim_get_keys()!\n");
      return XEMALLOC;
    }

  mydata = (struct eaptypedata *)thisint->userdata->activemethod->eap_data;
  if (thisint->keyingMaterial != NULL)
    {
      free(thisint->keyingMaterial);
    }

  thisint->keyingMaterial = (char *)malloc(64);
  if (thisint->keyingMaterial == NULL) 
    {
      debug_printf(DEBUG_NORMAL, "Couldn't allocate memory for keying material! (%s:%d)\n", __FUNCTION__, __LINE__);
      return XEMALLOC;
    }

  memcpy(thisint->keyingMaterial, mydata->keyingMaterial, 64);
  thisint->keyingLength = 32;

  return XENONE;
}

int eapsim_failed(struct generic_eap_data *thisint)
{
  struct config_eap_sim *userdata;

  if ((!thisint) || (!thisint->eap_conf_data))
    {
      debug_printf(DEBUG_AUTHTYPES, "No valid configuration information in EAP-SIM!  Nothing to do!\n");
      return XEMALLOC;
    }

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

#ifndef NO_PWD_RESET
  /*
  if (userdata->password != NULL)
    {
      free(userdata->password);
      userdata->password = NULL;
    }
  */
#endif

  return XENONE;
}

int eapsim_cleanup(struct generic_eap_data *thisint)
{
  struct eaptypedata *mydata;

  if (!thisint)
    {
      debug_printf(DEBUG_NORMAL, "Invalid data passed to %s!  (%s:%d)\n",
		   __FUNCTION__, __LINE__);
      return XEMALLOC;
    }

  debug_printf(DEBUG_AUTHTYPES, "(EAP-SIM) Cleaning up!\n");
  mydata = (struct eaptypedata *)thisint->eap_data;

  sm_handler_close_sc(&mydata->shdl, &mydata->scntx);
  return XENONE;
}

#endif
