/**
 * A client-side 802.1x implementation supporting EAP/AKA
 *
 * 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: aka.c
 *
 * Authors: Chris.Hessing@utah.edu
 *
 * $Id: aka.c,v 1.3 2004/08/20 04:42:28 chessing Exp $
 * $Date: 2004/08/20 04:42:28 $
 * $Log: aka.c,v $
 * Revision 1.3  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.2  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.1  2004/06/15 03:35:19  chessing
 *
 * New updates including fixes to LEAP (keying now works with wireless) and adding EAP-AKA.
 *
 *
 *******************************************************************/

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

#ifdef EAP_SIM_ENABLE

#include <inttypes.h>
#include <string.h>
#include <openssl/hmac.h>
#include <openssl/sha.h>

#include "winscard.h"
#include "profile.h"
#include "config.h"
#include "eap.h"
#include "../sim/eapsim.h"
#include "eapaka.h"
#include "xsup_debug.h"
#include "xsup_err.h"
#include "../sim/sm_handler.h"
#include "../sim/fips.h"

char *do_sha1(char *tohash, int size);

int aka_do_at_rand(struct aka_eaptypedata *mydata, u_char *dataoffs, 
		   int *packet_offset)
{
  struct typelengthres *typelenres;

  debug_printf(DEBUG_AUTHTYPES, "Got an AT_RAND.\n");
  typelenres = (struct typelengthres *)&dataoffs[*packet_offset];
  *packet_offset+=4;
  
  memcpy(mydata->random_num, &dataoffs[*packet_offset], 16);
  debug_printf(DEBUG_AUTHTYPES, "Random = ");
  debug_hex_printf(DEBUG_AUTHTYPES, mydata->random_num, 16);
  *packet_offset+=16;

  return XENONE;
}

int aka_skip_not_implemented(u_char *dataoffs, int *packet_offset)
{
  struct typelengthres *typelenres;

  typelenres = (struct typelengthres *)&dataoffs[*packet_offset];
  debug_printf(DEBUG_NORMAL, "Skipping unknown type! (%02X)\n", typelenres->type);
  *packet_offset+= (typelenres->length * 4);

  return XENONE;
}

int aka_do_at_autn(struct aka_eaptypedata *mydata, u_char *dataoffs,
		   int *packet_offset)
{
  struct typelengthres *typelenres;

  debug_printf(DEBUG_AUTHTYPES, "Got AT_AUTN!\n");
  typelenres = (struct typelengthres *)&dataoffs[*packet_offset];
  *packet_offset+=4;

  memcpy(mydata->autn, &dataoffs[*packet_offset], 16);
  debug_printf(DEBUG_AUTHTYPES, "AUTN = ");
  debug_hex_printf(DEBUG_AUTHTYPES, mydata->autn, 16);
  *packet_offset+=16;

  return XENONE;
}

int aka_do_at_mac(struct generic_eap_data *thisint, 
		  struct aka_eaptypedata *mydata, u_char *dataoffs, int insize,
		  int *packet_offset, char *username)
{
  int saved_offset, reslen, i, value16;
  unsigned char auts[16], sres[16], ck[16], *keydata, mac_val[16];
  unsigned char mac_calc[20], ik[16], *mk, kc[16], *tohash, *framecpy;

  debug_printf(DEBUG_AUTHTYPES, "Got an AT_MAC\n");
  
  saved_offset = (*packet_offset);

#ifndef RADIATOR_TEST  
  //First thing we need to do, is get our ik & ck.
  if (sm_handler_do_3g_auth(&mydata->shdl, mydata->card_mode,
			    mydata->random_num, mydata->autn,
			    (unsigned char *)&auts, 
			    (unsigned char *)&reslen, 
			    (unsigned char *)&sres, 
			    (unsigned char *)&ck, (unsigned char *)&ik,
			    (unsigned char *)&kc) == -2)
    {
      // We have a sync failure.  So, return it.
      return XEAKASYNCFAIL;
    }
#else
  // Copy in the fake vectors that Radiator uses.
  memcpy(sres, "2222222222222222", 16);
  memcpy(ik, "3333333333333333", 16);
  memcpy(ck, "4444444444444444", 16);
#endif
 
  debug_printf(DEBUG_AUTHTYPES, "SRES = ");
  debug_hex_printf(DEBUG_AUTHTYPES, sres, 16);
  debug_printf(DEBUG_AUTHTYPES, "CK = ");
  debug_hex_printf(DEBUG_AUTHTYPES, ck, 16);
  debug_printf(DEBUG_AUTHTYPES, "IK = ");
  debug_hex_printf(DEBUG_AUTHTYPES, ik, 16);

  tohash = (char *)malloc(strlen(username)+33);  // IK & CK are 16 bytes.
  if (!tohash)
    {
      debug_printf(DEBUG_NORMAL, "Couldn't allocate memory for hash string!\n");
      return XEMALLOC;
    }
  bzero(tohash, (strlen(username)+33));
  
  strncpy(tohash, username, strlen(username));
  memcpy((char *)&tohash[strlen(username)], (char *)&ik, 16);
  memcpy((char *)&tohash[strlen(username)+16], (char *)&ck, 16);
  
  mk = do_sha1((char *)&tohash[0], (strlen(username)+32));

  if (mk == NULL)
    {
      debug_printf(DEBUG_NORMAL, "An MK couldn't be created!  Authentication cannot be completed! (%s:%d)\n", __FUNCTION__, __LINE__);
      return XESIMGENERR;
    }

  free(tohash);
  tohash = NULL;
  
  debug_printf(DEBUG_AUTHTYPES, "MK = ");
  debug_hex_printf(DEBUG_AUTHTYPES, mk, 20);
  
  keydata = (char *)malloc(80);
  if (keydata == NULL) 
    {
      debug_printf(DEBUG_NORMAL, "Couldn't allocate memory for keydata! (%s:%d)\n",
		   __FUNCTION__, __LINE__);
      return XEMALLOC;
    }
  
  bzero(keydata, 80);
  
  // Next, put the mk in to the fips prng.
  fips186_2_prng(mk, 20, NULL, 0, (char *)&keydata[0], 80);

  free(mk);
  mk = NULL;
  
  memcpy(mydata->K_encr, keydata, 16);
  debug_printf(DEBUG_AUTHTYPES, "K_encr = ");
  debug_hex_printf(DEBUG_AUTHTYPES, mydata->K_encr, 16);
  
  memcpy(mydata->K_aut, (char *)&keydata[16], 16);
  debug_printf(DEBUG_AUTHTYPES, "K_aut = ");
  debug_hex_printf(DEBUG_AUTHTYPES, mydata->K_aut, 16);
  
  memcpy(mydata->msk, (char *)&keydata[32], 8);
  debug_printf(DEBUG_AUTHTYPES, "MSK = ");
  debug_hex_printf(DEBUG_AUTHTYPES, mydata->msk, 8);
  
  memcpy(mydata->emsk, (char *)&keydata[40], 8);
  debug_printf(DEBUG_AUTHTYPES, "EMSK = ");
  debug_hex_printf(DEBUG_AUTHTYPES, mydata->emsk, 8);
  
  memcpy(&mac_val[0], &dataoffs[(*packet_offset)+4], 16);
  
  debug_printf(DEBUG_AUTHTYPES, "MAC = ");
  debug_hex_printf(DEBUG_AUTHTYPES, (char *)&mac_val[0], 16);
  
  debug_printf(DEBUG_AUTHTYPES, "Packet : \n");
  debug_hex_dump(DEBUG_AUTHTYPES, dataoffs, insize);

  free(keydata);
  keydata = NULL;
  
  // Now, we need a copy of the frame to work against.
  framecpy = (char *)malloc(insize+5);
  if (framecpy == NULL) return XEMALLOC;
  
  framecpy[0] = 1;   // It was a request.
  framecpy[1] = thisint->eapid;
  value16 = insize + 5;
  value16 = htons(value16);
  
  memcpy((char *)&framecpy[2], &value16, 2);
  framecpy[4] = EAP_TYPE_AKA;
  
  memcpy((char *)&framecpy[5], dataoffs, insize);
  
  // Zero out the mac.
  bzero((char *)&framecpy[(*packet_offset)+4+5], 16);
  debug_printf(DEBUG_AUTHTYPES, "Frame to hash : \n");
  debug_hex_dump(DEBUG_AUTHTYPES, framecpy, insize+5);

  HMAC(EVP_sha1(), mydata->K_aut, 16, framecpy, 
       (insize+5), (char *)&mac_calc[0], &i);

  debug_printf(DEBUG_AUTHTYPES, "mac_calc = ");
  debug_hex_printf(DEBUG_AUTHTYPES, &mac_calc[0], 16);
  
  free(framecpy);
  framecpy = NULL;
  
  *packet_offset+=20;
  
  if (memcmp(&mac_calc[0], &mac_val[0], 16) != 0)
    {
      debug_printf(DEBUG_NORMAL, "ERROR : AT_MAC failed MAC check!\n");
      debug_printf(DEBUG_AUTHTYPES, "mac_calc = ");
      debug_hex_printf(DEBUG_AUTHTYPES, &mac_calc[0], 16);
      debug_printf(DEBUG_AUTHTYPES, "mac_val  = ");
      debug_hex_printf(DEBUG_AUTHTYPES, &mac_val[0], 16);
      return XESIMBADMAC;
    }

  return XENONE;
}

int aka_do_sync_fail(struct aka_eaptypedata *mydata, u_char *out, int *outsize)
{
  struct typelength *typelen;
  struct typelengthres *typelenres;
  int outptr = 0;

  debug_printf(DEBUG_AUTHTYPES, "Building AKA Sync Failure!\n");

  // Since a sync failure is it's own packet, and not an AV pair inside of
  // a packet, we ignore anything that may already be in there, and start
  // over.
  typelen = (struct typelength *)&out[0];

  typelen->type = AKA_SYNC_FAILURE;
  typelen->length = 0;
  outptr = 3;
  
  typelenres = (struct typelengthres *)&out[outptr];
  outptr+=4;

  typelenres->type = AT_AUTN;
  typelenres->length = 5;
  typelenres->reserved = 0;

  memcpy(&out[outptr], mydata->autn, 16);
  outptr+=16;

  *outsize = outptr;
  
  return XENONE;
}


#endif
