/*
 * Host AP (software wireless LAN access point) user space daemon for
 * Host AP kernel driver / IEEE 802.1X Authenticator
 * Copyright (c) 2002, Jouni Malinen <jkmaline@cc.hut.fi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation. See README and COPYING for
 * more details.
 */

/* TODO:
 * add support for RADIUS Accounting
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <assert.h>
#include <sys/time.h>

#include <sys/socket.h>
#include <asm/types.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>   /* The L2 protocols */
#include <linux/if_arp.h>


#include "hostapd.h"
#include "ieee802_1x.h"
#include "radius.h"
#include "eapol_sm.h"
#include "md5.h"
#include "rc4.h"


static void ieee802_1x_send(hostapd *hapd, struct sta_info *sta, u8 type,
			    u8 *data, size_t datalen)
{
	char *buf;
	struct ieee80211_hdr *hdr;
	struct ieee802_1x_hdr *xhdr;
	size_t len;
	u8 *pos;

	len = sizeof(*hdr) + sizeof(rfc1042_header) + 2 + sizeof(*xhdr) +
		datalen;
	buf = (char *) malloc(len);
	if (buf == NULL) {
		printf("malloc() failed for ieee802_1x_send\n");
		return;
	}

	memset(buf, 0, len);

	hdr = (struct ieee80211_hdr *) buf;
	hdr->frame_control =
		IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
	hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
	memcpy(hdr->IEEE80211_DA_FROMDS, sta->addr, ETH_ALEN);
	memcpy(hdr->IEEE80211_BSSID_FROMDS, hapd->own_addr, ETH_ALEN);
	memcpy(hdr->IEEE80211_SA_FROMDS, hapd->own_addr, ETH_ALEN);

	pos = (u8 *) (hdr + 1);
	memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
	pos += sizeof(rfc1042_header);

	*((u16 *) pos) = htons(ETH_P_PAE);
	pos += 2;

	xhdr = (struct ieee802_1x_hdr *) pos;
	xhdr->version = EAPOL_VERSION;
	xhdr->type = type;
	xhdr->length = htons(datalen);

	if (datalen > 0 && data != NULL)
		memcpy(xhdr + 1, data, datalen);

	if (send(hapd->sock, buf, len, 0) < 0)
		perror("ieee802_1x_send: send");

	free(buf);
}


void ieee802_1x_set_sta_authorized(hostapd *hapd, struct sta_info *sta,
				   int authorized)
{
	struct prism2_hostapd_param param;

	memset(&param, 0, sizeof(param));
	param.cmd = PRISM2_HOSTAPD_SET_FLAGS_STA;
	memcpy(param.sta_addr, sta->addr, ETH_ALEN);
	if (authorized) {
		sta->flags |= WLAN_STA_AUTHORIZED;
		param.u.set_flags_sta.flags_or = WLAN_STA_AUTHORIZED;
		param.u.set_flags_sta.flags_and = ~0;
		printf("IEEE 802.1X: Authorizing station " MACSTR "\n",
		       MAC2STR(sta->addr));
	} else {
		sta->flags &= ~WLAN_STA_AUTHORIZED;
		param.u.set_flags_sta.flags_and = ~WLAN_STA_AUTHORIZED;
		printf("IEEE 802.1X: Unauthorizing station " MACSTR "\n",
		       MAC2STR(sta->addr));
	}

	if (hostapd_ioctl(hapd, &param))
		printf("Could not set station flags for kernel driver.\n");
}


void ieee802_1x_request_identity(hostapd *hapd, struct sta_info *sta, u8 id)
{
	char *buf;
	struct eap_hdr *eap;
	int extra, tlen;
	u8 *pos;

	if (hapd->eap_req_id_text)
		extra = strlen(hapd->eap_req_id_text);
	else
		extra = 0;

	tlen = sizeof(*eap) + 1 + extra;

	buf = (char *) malloc(tlen);
	if (buf == NULL) {
		printf("Could not allocate memory for identity request\n");
		return;
	}

	memset(buf, 0, tlen);

	eap = (struct eap_hdr *) buf;
	eap->code = EAP_CODE_REQUEST;
	eap->identifier = id;
	eap->length = htons(tlen);
	pos = (u8 *) (eap + 1);
	*pos++ = EAP_TYPE_IDENTITY;
	if (hapd->eap_req_id_text)
		memcpy(pos, hapd->eap_req_id_text, extra);

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("IEEE 802.1X: Sending EAP Request-Identity to " MACSTR
		       " (identifier %d)\n", MAC2STR(sta->addr),
		       eap->identifier);
	ieee802_1x_send(hapd, sta, IEEE802_1X_TYPE_EAP_PACKET, buf, tlen);
	free(buf);
}


void ieee802_1x_tx_canned_eap(hostapd *hapd, struct sta_info *sta, u8 id,
			      int success)
{
	struct eap_hdr eap;

	memset(&eap, 0, sizeof(eap));

	eap.code = success ? EAP_CODE_SUCCESS : EAP_CODE_FAILURE;
	eap.identifier = id;
	eap.length = htons(sizeof(eap));

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("IEEE 802.1X: Sending canned EAP packet %s to " MACSTR
		       " (identifier %d)\n", success ? "SUCCESS" : "FAILURE",
		       MAC2STR(sta->addr), eap.identifier);
	ieee802_1x_send(hapd, sta, IEEE802_1X_TYPE_EAP_PACKET, (u8 *) &eap,
			sizeof(eap));
}


void ieee802_1x_tx_req(hostapd *hapd, struct sta_info *sta, u8 id)
{
	struct eap_hdr *eap;

	if (sta->last_eap_radius == NULL) {
		printf("Error: TxReq called for station " MACSTR ", but there "
		       "is no EAP request from the authentication server\n",
		       MAC2STR(sta->addr));
		return;
	}

	eap = (struct eap_hdr *) sta->last_eap_radius;
	if (eap->identifier != id) {
		printf("IEEE 802.1X: TxReq(%d) - changing id from %d\n",
		       id, eap->identifier);
		eap->identifier = id;
	}

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("IEEE 802.1X: Sending EAP Packet to " MACSTR
		       " (identifier %d)\n", MAC2STR(sta->addr), id);
	ieee802_1x_send(hapd, sta, IEEE802_1X_TYPE_EAP_PACKET,
			sta->last_eap_radius, sta->last_eap_radius_len);
}


static void ieee802_1x_tx_key_one(hostapd *hapd, struct sta_info *sta,
				  int index, int broadcast,
				  u8 *key_data, size_t key_len)
{
	u8 *buf, *ekey;
	struct ieee802_1x_hdr *hdr;
	struct ieee802_1x_eapol_key *key;
	struct timeval now;
	size_t len, ekey_len;

	len = sizeof(*key) + key_len;
	buf = malloc(sizeof(*hdr) + len);
	if (buf == NULL)
		return;

	memset(buf, 0, sizeof(*hdr) + len);
	hdr = (struct ieee802_1x_hdr *) buf;
	key = (struct ieee802_1x_eapol_key *) (hdr + 1);
	key->type = EAPOL_KEY_TYPE_RC4;
	key->key_length = htons(key_len);

	/* FIX: might use proper 64-bit NTP timestamp */
	gettimeofday(&now, NULL);
	if (sizeof(now) > sizeof(key->replay_counter))
		memcpy(key->replay_counter,
		       ((u8 *) &now) + sizeof(now) -
		       sizeof(key->replay_counter),
		       sizeof(key->replay_counter));
	else
		memcpy(key->replay_counter, (u8 *) &now, sizeof(now));

	if (hostapd_get_rand(key->key_iv, sizeof(key->key_iv))) {
		printf("Could not get random numbers\n");
		free(buf);
		return;
	}

	key->key_index = index | (broadcast ? 0 : BIT(7));

	/* Key is encrypted using "Key-IV + sta->eapol_key_crypt" as the
	 * RC4-key */
	memcpy((u8 *) (key + 1), key_data, key_len);
	ekey_len = sizeof(key->key_iv) + sta->eapol_key_crypt_len;
	ekey = malloc(ekey_len);
	if (ekey == NULL) {
		printf("Could not encrypt key\n");
		free(buf);
		return;
	}
	memcpy(ekey, key->key_iv, sizeof(key->key_iv));
	memcpy(ekey + sizeof(key->key_iv), sta->eapol_key_crypt,
	       sta->eapol_key_crypt_len);
	rc4((u8 *) (key + 1), key_len, ekey, ekey_len);
	free(ekey);

	/* This header is needed here for HMAC-MD5, but it will be regenerated
	 * in ieee802_1x_send() */
	hdr->version = EAPOL_VERSION;
	hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
	hdr->length = htons(len);
	hmac_md5(sta->eapol_key_sign, sta->eapol_key_sign_len,
		 buf, sizeof(*hdr) + len,
		 key->key_signature);

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("IEEE 802.1X: Sending EAPOL-Key to " MACSTR
		       " (%s index=%d)\n", MAC2STR(sta->addr),
		       broadcast ? "broadcast" : "unicast", index);
	ieee802_1x_send(hapd, sta, IEEE802_1X_TYPE_EAPOL_KEY, (u8 *) key, len);
	free(buf);
}


void ieee802_1x_tx_key(hostapd *hapd, struct sta_info *sta, u8 id)
{
	if (!sta->eapol_key_sign || !sta->eapol_key_crypt)
		return;

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("IEEE 802.1X: Sending EAPOL-Key(s) to " MACSTR
		       " (identifier %d)\n", MAC2STR(sta->addr), id);

	if (hapd->default_wep_key)
		ieee802_1x_tx_key_one(hapd, sta, hapd->default_wep_key_idx, 1,
				      hapd->default_wep_key,
				      hapd->default_wep_key_len);

	if (hapd->individual_wep_key_len > 0) {
		u8 *ikey;
		ikey = malloc(hapd->individual_wep_key_len);
		if (ikey == NULL ||
		    hostapd_get_rand(ikey, hapd->individual_wep_key_len)) {
			printf("Could not generate random individual WEP "
			       "key.\n");
			free(ikey);
			return;
		}

		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			hostapd_hexdump("Individual WEP key",
					ikey, hapd->individual_wep_key_len);

		ieee802_1x_tx_key_one(hapd, sta, 0, 0, ikey,
				      hapd->individual_wep_key_len);

		if (hostapd_set_encryption(hapd, "WEP", sta->addr, 0, ikey,
					   hapd->individual_wep_key_len)) {
			printf("Could not set individual WEP encryption.\n");
		}

		free(ikey);
	}
}


/* This is just a minimal authentication server for testing the authenticator.
 * It accepts anything, i.e., no keys are needed and this should not be used
 * for anything else than testing.
 * Real implementation would forward the packet to an external authentication
 * server in ieee802_1x_send_resp_to_server() */

static void minimal_auth_serv_reply(u8 id, struct sta_info *sta, u8 eap_code)
{
	struct eap_hdr *eap;

	sta->eapol_sm->be_auth.idFromServer = id;

	if (sta->last_eap_radius)
		free(sta->last_eap_radius);

	sta->last_eap_radius = malloc(sizeof(*eap));
	if (sta->last_eap_radius == NULL) {
		printf("minimal_auth_serv_reply: could not add EAP data\n");
		return;
	}
	sta->last_eap_radius_len = sizeof(*eap);

	eap = (struct eap_hdr *) sta->last_eap_radius;
	memset(eap, 0, sizeof(*eap));
	eap->code = eap_code;
	eap->identifier = id;
	eap->length = sizeof(*eap);
}


static void minimal_auth_serv(hostapd *hapd, struct sta_info *sta,
			      u8 *data, size_t len)
{
	struct eap_hdr *eap;
	u8 *pos;
	size_t left;
	int i;
	static u8 id = 0;

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("Minimal Authentication Server\n");

	if (len < sizeof(*eap)) {
		printf("Too short packet for minimal auth serv\n");
		goto fail;
	}

	eap = (struct eap_hdr *) data;
	if (eap->code != EAP_CODE_RESPONSE) {
		printf("Invalid EAP code (%d) in minimal auth serv\n",
		       eap->code);
		goto fail;
	}

	pos = (u8 *) (eap + 1);
	left = len - sizeof(*eap);
	if (*pos != EAP_TYPE_IDENTITY) {
		printf("Invalid EAP Response type (%d) in minimal auth serv\n",
		       *pos);
		goto fail;
	}

	pos++;
	left--;

	printf("Minimal Authentication Server: station " MACSTR
	       " EAP Response-Identity: (len=%d) '", MAC2STR(sta->addr), len);
	for (i = 0; i < left; i++)
		print_char(pos[i]);
	printf("'\n");

	minimal_auth_serv_reply(id++, sta, EAP_CODE_SUCCESS);
	sta->eapol_sm->be_auth.aSuccess = TRUE;
	eapol_sm_step(sta->eapol_sm);
	return;

 fail:
	minimal_auth_serv_reply(id++, sta, EAP_CODE_FAILURE);
	sta->eapol_sm->be_auth.aFail = TRUE;
	eapol_sm_step(sta->eapol_sm);
}


static void ieee802_1x_encapsulate_radius(hostapd *hapd, struct sta_info *sta,
					  u8 *eap, size_t len)
{
	struct radius_msg *msg;
	char buf[128];

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("Encapsulating EAP message into a RADIUS packet\n");

	sta->radius_identifier = hapd->next_radius_identifier++;
	msg = radius_msg_new(RADIUS_CODE_ACCESS_REQUEST,
			     sta->radius_identifier);
	if (msg == NULL) {
		printf("Could not create net RADIUS packet\n");
		return;
	}

	radius_msg_make_authenticator(msg, (u8 *) sta, sizeof(sta));

	if (sta->identity &&
	    !radius_msg_add_attr(msg, RADIUS_ATTR_USER_NAME,
				 sta->identity, sta->identity_len)) {
		printf("Could not add User-Name\n");
		goto fail;
	}

	if (!radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IP_ADDRESS,
				 (u8 *) &hapd->own_ip_addr, 4)) {
		printf("Could not add NAS-IP-Address\n");
		goto fail;
	}

	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_NAS_PORT, sta->aid)) {
		printf("Could not add NAS-Port\n");
		goto fail;
	}

	snprintf(buf, sizeof(buf), "%02X-%02X-%02X-%02X-%02X-%02X:%s",
		 MAC2STR(hapd->own_addr), hapd->ssid);
	if (!radius_msg_add_attr(msg, RADIUS_ATTR_CALLED_STATION_ID,
				 buf, strlen(buf))) {
		printf("Could not add Called-Station-Id\n");
		goto fail;
	}

	snprintf(buf, sizeof(buf), "%02X-%02X-%02X-%02X-%02X-%02X",
		 MAC2STR(sta->addr));
	if (!radius_msg_add_attr(msg, RADIUS_ATTR_CALLING_STATION_ID,
				 buf, strlen(buf))) {
		printf("Could not add Calling-Station-Id\n");
		goto fail;
	}

	/* TODO: should probably check MTU from driver config; 2304 is max for
	 * IEEE 802.11 */
	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_FRAMED_MTU, 2304)) {
		printf("Could not add Framed-MTU\n");
		goto fail;
	}

	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_NAS_PORT_TYPE,
				       RADIUS_NAS_PORT_TYPE_IEEE_802_11)) {
		printf("Could not add NAS-Port-Type\n");
		goto fail;
	}

	snprintf(buf, sizeof(buf), "CONNECT 11Mbps 802.11b");
	if (!radius_msg_add_attr(msg, RADIUS_ATTR_CONNECT_INFO,
				 buf, strlen(buf))) {
		printf("Could not add Connect-Info\n");
		goto fail;
	}

	if (eap && !radius_msg_add_eap(msg, eap, len)) {
		printf("Could not add EAP-Message\n");
		goto fail;
	}

	if (sta->last_recv_radius &&
	    radius_msg_copy_attr(msg, sta->last_recv_radius,
				 RADIUS_ATTR_STATE) < 0) {
		printf("Could not copy State attribute from previous "
		       "Access-Challenge\n");
		goto fail;
	}

	/* This adds Message-Authenticator, if shared secret is configured */
	radius_msg_finish(msg, hapd->auth_server_shared_secret,
			  hapd->auth_server_shared_secret_len);

	if (sta->last_sent_radius) {
		radius_msg_free(sta->last_sent_radius);
		free(sta->last_sent_radius);
	}
	sta->last_sent_radius = msg;

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("Sending RADIUS message to authentication server\n");
	if (hapd->debug >= HOSTAPD_DEBUG_MSGDUMPS)
		radius_msg_dump(msg);

	if (send(hapd->auth_serv_sock, msg->buf, msg->buf_used, 0) < 0) {
		perror("ieee802_1x_encapsulate_radius: send");
		printf("Could not send message to RADIUS server\n");
	}

	return;

 fail:
	radius_msg_free(msg);
	free(msg);
}


static char *eap_type_text(u8 type)
{
	switch (type) {
	case EAP_TYPE_IDENTITY: return "Identity";
	case EAP_TYPE_NOTIFICATION: return "Notification";
	case EAP_TYPE_NAK: return "Nak";
	case EAP_TYPE_MD5_CHALLENGE: return "MD5-Challenge";
	case EAP_TYPE_ONE_TIME_PASSWORD: return "One-Time Password";
	case EAP_TYPE_GENERIC_TOKEN_CARD: return "Generic Token Card";
	case EAP_TYPE_TLS: return "TLS";
	default: return "Unknown";
	}
}


static void handle_eap_response(hostapd *hapd, struct sta_info *sta,
				struct eap_hdr *eap, u8 *data, size_t len)
{
	u8 type;

	assert(sta->eapol_sm != NULL);

	if (eap->identifier != sta->eapol_sm->currentId) {
		printf("EAP Identifier of the Response-Identity from " MACSTR
		       " does not match (was %d, expected %d)\n",
		       MAC2STR(sta->addr), eap->identifier,
		       sta->eapol_sm->currentId);
		return;
	}

	if (len < 1) {
		printf("   too short response data\n");
		return;
	}

	if (sta->last_eap_supp != NULL)
		free(sta->last_eap_supp);
	sta->last_eap_supp_len = sizeof(*eap) + len;
	sta->last_eap_supp = (u8 *) malloc(sta->last_eap_supp_len);
	if (sta->last_eap_supp == NULL) {
		printf("Could not alloc memory for last EAP Response\n");
		return;
	}
	memcpy(sta->last_eap_supp, eap, sizeof(*eap));
	memcpy(sta->last_eap_supp + sizeof(*eap), data, len);

	type = data[0];
	data++;
	len--;

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("   EAP Response-%s\n", eap_type_text(type));

	if (type == EAP_TYPE_IDENTITY) {
		sta->eapol_sm->auth_pae.rxRespId = TRUE;

		/* Save station identity for future RADIUS packets */
		if (sta->identity)
			free(sta->identity);
		sta->identity = (u8 *) malloc(len);
		if (sta->identity) {
			memcpy(sta->identity, data, len);
			sta->identity_len = len;
		}
	} else {
		if (type != EAP_TYPE_NAK)
			sta->eapol_sm->be_auth.
				backendNonNakResponsesFromSupplicant++;
		sta->eapol_sm->be_auth.rxResp = TRUE;
	}
}


/* Process incoming EAP packet from Supplicant */
static void handle_eap(hostapd *hapd, struct sta_info *sta, u8 *buf,
		       size_t len)
{
	struct eap_hdr *eap;
	u16 eap_len;

	if (len < sizeof(*eap)) {
		printf("   too short EAP packet\n");
		return;
	}

	eap = (struct eap_hdr *) buf;

	eap_len = ntohs(eap->length);
	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("   EAP: code=%d identifier=%d length=%d",
		       eap->code, eap->identifier, eap_len);
	if (eap_len < sizeof(*eap)) {
		printf("   Invalid EAP length\n");
		return;
	} else if (eap_len > len) {
		printf("   Too short frame to contain this EAP packet\n");
		return;
	} else if (eap_len < len) {
		printf("   Ignoring %d extra bytes after EAP packet\n",
		       len - eap_len);
	}

	eap_len -= sizeof(*eap);

	switch (eap->code) {
	case EAP_CODE_REQUEST:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf(" (request)\n");
		return;
	case EAP_CODE_RESPONSE:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf(" (response)\n");
		handle_eap_response(hapd, sta, eap, (u8 *) (eap + 1), eap_len);
		break;
	case EAP_CODE_SUCCESS:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf(" (request)\n");
		return;
	case EAP_CODE_FAILURE:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf(" (failure)\n");
		return;
	default:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf(" (unknown code)\n");
		return;
	}
}


/* Process the EAPOL frames from the Supplicant */
void ieee802_1x_receive(hostapd *hapd, u8 *sa, u8 *buf, size_t len)
{
	struct sta_info *sta;
	struct ieee802_1x_hdr *hdr;
	u16 datalen;

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("IEEE 802.1X: %d bytes from " MACSTR "\n", len,
		       MAC2STR(sa));
	sta = ap_get_sta(hapd, sa);
	if (!sta) {
		printf("   no station information available\n");
		return;
	}

	if (len < sizeof(*hdr)) {
		printf("   too short IEEE 802.1X packet\n");
		return;
	}

	hdr = (struct ieee802_1x_hdr *) buf;
	datalen = ntohs(hdr->length);
	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("   IEEE 802.1X: version=%d type=%d length=%d\n",
		       hdr->version, hdr->type, datalen);

	if (len - sizeof(*hdr) < datalen) {
		printf("   frame too short for this IEEE 802.1X packet\n");
		return;
	}
	if (len - sizeof(*hdr) > datalen) {
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf("   ignoring %d extra octets after IEEE 802.1X "
			       "packet\n", len - sizeof(*hdr) - datalen);
	}

	if (!sta->eapol_sm) {
		sta->eapol_sm = eapol_sm_alloc(hapd, sta);
		if (!sta->eapol_sm)
			return;
	}

	/* since we support version 1, we can ignore version field and proceed
	 * as specified in version 1 standard [IEEE Std 802.1X-2001, 7.5.5] */

	switch (hdr->type) {
	case IEEE802_1X_TYPE_EAP_PACKET:
		handle_eap(hapd, sta, (u8 *) (hdr + 1), datalen);
		break;

	case IEEE802_1X_TYPE_EAPOL_START:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf("   EAPOL-Start\n");
		sta->eapol_sm->auth_pae.eapStart = TRUE;
		eapol_sm_step(sta->eapol_sm);
		break;

	case IEEE802_1X_TYPE_EAPOL_LOGOFF:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf("   EAPOL-Logoff\n");
		sta->eapol_sm->auth_pae.eapLogoff = TRUE;
		eapol_sm_step(sta->eapol_sm);
		break;

	case IEEE802_1X_TYPE_EAPOL_KEY:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf("   EAPOL-Key\n");
		if (!(sta->flags & WLAN_STA_AUTHORIZED)) {
			printf("   Dropped key data from unauthorized "
			       "Supplicant\n");
			break;
		}
		break;

	case IEEE802_1X_TYPE_EAPOL_ENCAPSULATED_ASF_ALERT:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf("   EAPOL-Encapsulated-ASF-Alert\n");
		/* TODO: implement support for this; show data */
		break;

	default:
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
			printf("   unknown IEEE 802.1X packet type\n");
		break;
	}

	eapol_sm_step(sta->eapol_sm);
}


void ieee802_1x_new_station(hostapd *hapd, struct sta_info *sta)
{
	if (sta->eapol_sm) {
		sta->eapol_sm->portEnabled = TRUE;
		return;
	}

	printf("IEEE 802.1X: Start authentication for new station " MACSTR
	       "\n", MAC2STR(sta->addr));
	sta->eapol_sm = eapol_sm_alloc(hapd, sta);
}


void ieee802_1x_free_station(struct sta_info *sta)
{
	if (sta->last_recv_radius) {
		radius_msg_free(sta->last_recv_radius);
		free(sta->last_recv_radius);
	}
	if (sta->last_sent_radius) {
		radius_msg_free(sta->last_sent_radius);
		free(sta->last_sent_radius);
	}

	if (sta->last_eap_supp)
		free(sta->last_eap_supp);
	if (sta->last_eap_radius)
		free(sta->last_eap_radius);

	if (sta->identity)
		free(sta->identity);

	free(sta->eapol_key_sign);
	free(sta->eapol_key_crypt);

	eapol_sm_free(sta->eapol_sm);
}


static void ieee802_1x_decapsulate_radius(hostapd *hapd, struct sta_info *sta,
					  u8 type)
{
	char *eap;
	size_t len;
	struct eap_hdr *hdr;

	if (sta->last_recv_radius == NULL)
		return;

	eap = radius_msg_get_eap(sta->last_recv_radius, &len);
	if (eap == NULL) {
		printf("Could not extra EAP-Message from RADIUS message\n");
		return;
	}

	if (len < sizeof(*hdr)) {
		printf("Too short EAP packet received from authentication "
		       "server\n");
		free(eap);
		return;
	}

	hdr = (struct eap_hdr *) eap;
	sta->eapol_sm->be_auth.idFromServer = hdr->identifier;

	if (sta->last_eap_radius)
		free(sta->last_eap_radius);
	sta->last_eap_radius = eap;
	sta->last_eap_radius_len = len;
}


static void ieee802_1x_get_keys(hostapd *hapd, struct sta_info *sta,
				struct radius_msg *msg)
{
	struct radius_ms_mppe_keys *keys;

	keys = radius_msg_get_ms_keys(msg,
				      sta->last_sent_radius,
				      hapd->auth_server_shared_secret,
				      hapd->auth_server_shared_secret_len);

	if (keys) {
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL && keys->send) {
			int i;
			printf("MS-MPPE-Send-Key (len=%d):", keys->send_len);
			for (i = 0; i < keys->send_len; i++)
				printf(" %02x", keys->send[i]);
			printf("\n");
		}
		if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL && keys->recv) {
			int i;
			printf("MS-MPPE-Recv-Key (len=%d):", keys->recv_len);
			for (i = 0; i < keys->recv_len; i++)
				printf(" %02x", keys->recv[i]);
			printf("\n");
		}

		if (keys->send && keys->recv) {
			free(sta->eapol_key_sign);
			free(sta->eapol_key_crypt);
			sta->eapol_key_sign = keys->send;
			sta->eapol_key_sign_len = keys->send_len;
			sta->eapol_key_crypt = keys->recv;
			sta->eapol_key_crypt_len = keys->recv_len;
			/* TODO: add support for individual station keys */
			if (hapd->default_wep_key) {
				sta->eapol_sm->auth_key_tx.keyAvailable = TRUE;
				sta->eapol_sm->auth_key_tx.keyTxEnabled = TRUE;
			}
		} else {
			free(keys->send);
			free(keys->recv);
		}
		free(keys);
	}
}


/* Process the RADIUS frames from Authentication Server */
void ieee802_1x_receive_auth(hostapd *hapd, u8 *buf, size_t len)
{
	struct radius_msg *msg;
	struct sta_info *sta;
	char *reason = NULL;

	msg = radius_msg_parse(buf, len);
	if (msg == NULL) {
		printf("Parsing incoming RADIUS frame failed\n");
		return;
	}

	sta = ap_get_sta_radius_identifier(hapd, msg->hdr->identifier);
	if (sta == NULL) {
		reason = "Could not find matching station for this RADIUS "
		       "message";
		goto drop;
	}

	/* FIX: require Message-Authenticator only in messages containing
	 * EAP-Message; Access-Reject might not have this.. */

	if (radius_msg_verify(msg, hapd->auth_server_shared_secret,
			      hapd->auth_server_shared_secret_len,
			      sta->last_sent_radius)) {
		printf("Incoming RADIUS packet did not have correct "
		       "Message-Authenticator - dropped\n");
		return;
	}

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("Received RADIUS message\n");
	if (hapd->debug >= HOSTAPD_DEBUG_MSGDUMPS)
		radius_msg_dump(msg);

	if (msg->hdr->code != RADIUS_CODE_ACCESS_ACCEPT &&
	    msg->hdr->code != RADIUS_CODE_ACCESS_REJECT &&
	    msg->hdr->code != RADIUS_CODE_ACCESS_CHALLENGE) {
		reason = "Unknown RADIUS message code\n";
		goto drop;
	}

	sta->radius_identifier = -1;
	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("RADIUS packet matching with station " MACSTR "\n",
		       MAC2STR(sta->addr));

	if (sta->last_recv_radius) {
		radius_msg_free(sta->last_recv_radius);
		free(sta->last_recv_radius);
	}

	sta->last_recv_radius = msg;

	switch (msg->hdr->code) {
	case RADIUS_CODE_ACCESS_ACCEPT:
		sta->eapol_sm->be_auth.aSuccess = TRUE;
		ieee802_1x_get_keys(hapd, sta, msg);
		break;
	case RADIUS_CODE_ACCESS_REJECT:
		sta->eapol_sm->be_auth.aFail = TRUE;
		break;
	case RADIUS_CODE_ACCESS_CHALLENGE:
		sta->eapol_sm->be_auth.aReq = TRUE;
		break;
	}

	ieee802_1x_decapsulate_radius(hapd, sta, msg->hdr->code);

	/* Last sent radius message is not needed anymore */
	if (sta->last_sent_radius) {
		radius_msg_free(sta->last_sent_radius);
		free(sta->last_sent_radius);
		sta->last_sent_radius = NULL;
	}

	eapol_sm_step(sta->eapol_sm);

	return;

 drop:
	printf("Dropped RADIUS message: %s\n", reason);
	radius_msg_free(msg);
	free(msg);
}


/* Handler for EAPOL Backend Authentication state machine sendRespToServer.
 * Forward the EAP Response from Supplicant to Authentication Server. */
void ieee802_1x_send_resp_to_server(hostapd *hapd, struct sta_info *sta)
{
	if (hapd->minimal_eap)
		minimal_auth_serv(hapd, sta, sta->last_eap_supp,
				  sta->last_eap_supp_len);
	else
		ieee802_1x_encapsulate_radius(hapd, sta, sta->last_eap_supp,
					      sta->last_eap_supp_len);
}


void ieee802_1x_set_port_enabled(hostapd *hapd, struct sta_info *sta,
				 int enabled)
{
	if (!sta->eapol_sm)
		return;

	if (hapd->debug >= HOSTAPD_DEBUG_MINIMAL)
		printf("IEEE 802.1X: station " MACSTR " port %s\n",
		       MAC2STR(sta->addr), enabled ? "enabled" : "disabled");
	sta->eapol_sm->portEnabled = enabled ? TRUE : FALSE;
	eapol_sm_step(sta->eapol_sm);
}


#ifdef HOSTAPD_DUMP_STATE
void ieee802_1x_dump_state(FILE *f, const char *prefix, struct sta_info *sta)
{
	fprintf(f, "%sIEEE 802.1X:\n", prefix);

	if (sta->identity) {
		int i;
		fprintf(f, "%sidentity=", prefix);
		for (i = 0; i < sta->identity_len; i++)
			fprint_char(f, sta->identity[i]);
		fprintf(f, "\n");
	}

	fprintf(f, "%scached_packets=%s%s%s%s\n", prefix,
		sta->last_recv_radius ? "[RX RADIUS]" : "",
		sta->last_sent_radius ? "[TX RADIUS]" : "",
		sta->last_eap_radius ? "[EAP RADIUS]" : "",
		sta->last_eap_supp ? "[EAP SUPPLICANT]" : "");

	if (sta->eapol_sm)
		eapol_sm_dump_state(f, prefix, sta->eapol_sm);
}
#endif /* HOSTAPD_DUMP_STATE */
