M7350v7_en_gpl

This commit is contained in:
T
2024-09-09 08:59:52 +00:00
parent f75098198c
commit 46ba6f09ec
1372 changed files with 1231198 additions and 1184 deletions

View File

@ -0,0 +1 @@
include $(call all-subdir-makefiles)

View File

@ -0,0 +1,41 @@
#include "1x_types.h"
struct Auth_Pae_tag;
struct Global_Params_tag;
#define LIB1X_ACCT_REASON_USER_REQUEST 1
#define LIB1X_ACCT_REASON_LOST_CARRIER 2
#define LIB1X_ACCT_REASON_LOST_SERVICE 3
#define LIB1X_ACCT_REASON_IDLE_TIMEOUT 4
#define LIB1X_ACCT_REASON_SESSION_TIMEOUT 5
#define LIB1X_ACCT_REASON_ADMIN_RESET 6
#define LIB1X_ACCT_REASON_ADMIN_REBOOT 7
typedef struct ACCT_SM_tag
{
int terminate_cause;
int status;
u_long elapsedSessionTime;
u_long sessionId;
int serverTimeout;
int maxReq;
int reqCount;
int aWhile;
BOOLEAN waitRespond;
unsigned long tx_packets; // == transmited packets
unsigned long rx_packets; // == received packets
unsigned long tx_bytes; // == transmited bytes
unsigned long rx_bytes; // == received bytes
} Acct_SM;
void lib1x_acctsm( Global_Params * global);
void lib1x_acctsm_init(Acct_SM * acct_sm, int maxReq, int aWhile);
BOOLEAN lib1x_acctsm_request( struct Global_Params_tag * global, int iAction, int iTerminateCause);
int lib1x_acct_request( struct Auth_Pae_tag * auth_pae, unsigned int msg_type, int iTerminateCause);
void lib1x_acct_UCS4_TO_UTF8(u_long ud, u_char * pucUTF8, u_long * ulUTF8Len);
void lib1x_acct_MAC_TO_DASH_ASCII(u_char * pucInput, u_long ulInput, u_char * pucOutput, u_long * ulOutputLen);
u_long lib1x_acct_maperr_wlan2acct(u_long ulReason);
int lib1x_acctsm_sendReqToServer( Global_Params * global);

View File

@ -0,0 +1,270 @@
#ifndef LIB1x_AUTH_PAE_H
#define LIB1x_AUTH_PAE_H
#include "1x_types.h"
#include "1x_common.h"
#include "1x_ethernet.h"
#include "1x_reauth_sm.h"
#include "1x_bauth_sm.h"
#include "1x_cdsm.h"
#include "1x_krc_sm.h"
#include "1x_kxsm.h"
#include "1x_ptsm.h"
#include "1x_acct_sm.h"
//#include "1x_radius.h"
#include <stdio.h>
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : auth_pae.h
// Programmer : Arunesh Mishra
//
// Contains declarations for Authenticator PAE
// state machine.
// Refer 8.5.4.1 page 53 in the IEEE 802.1x spec.
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#define LIB1X_AP_QUIET_PERIOD 60 // seconds
//#define LIB1X_AP_REAUTHMAX 20 // attempts
#define LIB1X_AP_REAUTHMAX 3
#define LIB1X_AP_NAKMAX 4 // received times
//#define LIB1X_AP_TXPERIOD 30 // seconds
#define LIB1X_AP_TXPERIOD 5 // seconds
#define LIB1X_AP_SENDBUFLEN 1600
#define LIB1X_ACCTING_SENDBUFLEN 1600
#define MAX_EAP_BUFFER 10
// The reauthentication period
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
struct pktbuf
{
u_char * pkt;
u_short length; // -1 indicates no packet is stored in this slot
u_char eap_code;
u_char eap_id;
u_char eaprr_type; // = 255 if not valid i.e. the EAP packet is not a request/response pkt
};
struct Global_Params_tag;
struct Auth_Pae_tag
{
// The machine state
AUTH_PAE_STATE state;
// The Variables.
BOOLEAN eapLogoff;
BOOLEAN eapStart;
PORT_MODE_TYPE portMode;
int reAuthCount;
int nakCount;
BOOLEAN rxRespId;
BOOLEAN isSuppPresent; // true if we have a supp to communicate with
// The constants
int quietPeriod;
int reAuthMax;
int txPeriod;
// A listing of the other state machines we are going to use.
// TODO something about the port timers machine.
PT_SM * port_timers;
// Reauthentication Timer State Machine
Reauth_SM * reauth_sm;
// Backend Authentication State Machine
Bauth_SM * bauth_sm;
// Controlled Directions State Machine
CtrlDirSM * ctrl_sm;
// Key Receive State Machine
Krc_SM * krc_sm;
// Authenticator Key Transmit State Machine
Auth_KeyxmitSM * keyxmit_sm;
// Accouting State Machine
Acct_SM * acct_sm;
u_char * sendBuffer;
int sendbuflen;
u_char * acct_sendBuffer;
int acct_sendbuflen;
BOOLEAN sendreplyready; /* signals that the reply is ready for authentication message*/
BOOLEAN sendhandshakeready; /* signals that the reply is ready for key management message */
struct lib1x_eap * send_eapptr; /* used to communicate the start of eap pkt in sendbuf */
//u_char oursvr_addr[ETHER_ADDRLEN]; // ethernet address of the server interface
//u_char oursupp_addr[ETHER_ADDRLEN]; // ethernet address of the supplicant interface
u_char supp_addr[ETHER_ADDRLEN];
//u_char svr_addr[ETHER_ADDRLEN];
struct Global_Params_tag * global;
struct pktbuf fromsupp; // buffers of length one to store latest packet from
struct pktbuf fromsvr; // supplicant / server
//struct lib1x_nal_intfdesc * network_svr;
//struct lib1x_nal_intfdesc * network_supp;
FILE * debugsm;
//struct in_addr ourip_inaddr, svrip_inaddr;
//u_short udp_ourport, udp_svrport;
struct radius_info * rinfo; /* structure for radius related bookkeeping with respect
to sending packets to the radius server*/
struct sockaddr_in radsvraddr;
int udpsock;
struct lib1x_radius_const * rconst;
};
typedef struct Auth_Pae_tag Auth_Pae;
typedef struct lib1x_packet lib1x_packet_tag;
typedef struct lib1x_nal_intfdesc lib1x_nal_intfdesc_tag;
#ifdef START_AUTH_IN_LIB
typedef struct auth_param {
int encryption; // 2:WPA, 4:WPA2, 6:both
int wpaCipher; // 1:TKIP, 2:AES, 3:both
#ifdef RTL_WPA2
int wpa2Cipher; // 1:TKIP, 2:AES, 3:both
#endif
unsigned char ssid[40];
unsigned char psk[64];
int role; // 0:AP, 1:infra-client, 2:adhoc
int terminate; // 0:run, 1:terminate
} auth_param_t;
#endif // START_AUTH_IN_LIB
// Now the function declarations follow:
//-----------------------------------------------------
// Initialization Function
//-----------------------------------------------------
int lib1x_init_authRSNConfig(
Dot1x_Authenticator * auth);
int lib1x_init_authGlobal(
Dot1x_Authenticator * auth);
int lib1x_init_authTimer(
Dot1x_Authenticator * auth);
TxRx_Params * lib1x_init(
u_char * oursvr_addr,
u_char * svr_addr ,
u_char * oursupp_addr,
u_char * ourip_addr,
u_char * svrip_addr,
u_short udp_ourport,
u_short udp_svrport ,
u_char *dev_svr,
u_char * dev_supp);
Global_Params * lib1x_init_authenticator(
Dot1x_Authenticator * auth,
TxRx_Params * dev_txrx);
TxRx_Params * lib1x_init_txrx(
Dot1x_Authenticator *auth,
u_char * oursvr_addr,
u_char * svr_addr,
u_char * oursupp_addr,
u_char * ourip_addr,
u_char * svrip_addr,
u_short udp_ourport,
u_short udp_svrport,
#ifdef RTL_RADIUS_2SET
u_char * svrip_addr2,
u_short udp_svrport2,
u_char * acctip_addr2,
u_short udp_acctport2,
#endif
u_char * acctip_addr,
u_short udp_acctport,
u_char * dev_svr,
u_char * dev_supp);
int lib1x_init_auth(
Dot1x_Authenticator * auth);
//-----------------------------------------------------
// For 802.11 authentication and key management
//-----------------------------------------------------
void lib1x_get_NumSTA( Dot1x_Authenticator * auth);
int lib1x_do_authenticator( Dot1x_Authenticator * auth);
void lib1x_auth_process(Dot1x_Authenticator * auth );
void lib1x_reset_authenticator(Global_Params * global);
int lib1x_timer_authenticator(int signum);
//-----------------------------------------------------
// Porcedures for processing data
//-----------------------------------------------------
void lib1x_authsm_capture_supp( Global_Params *, lib1x_nal_intfdesc_tag * nal, lib1x_packet_tag * );
void lib1x_authsm_capture_svr( Global_Params *, lib1x_nal_intfdesc_tag * nal, lib1x_packet_tag * );
int lib1x_capture_control(Global_Params * global, lib1x_nal_intfdesc_tag * nal, lib1x_packet_tag * spkt);
//-----------------------------------------------------
// Procedure called by key management state machine
//-----------------------------------------------------
void lib1x_akmsm_Timer_proc(Dot1x_Authenticator * auth);
//-----------------------------------------------------
// packet xmit routines.
//-----------------------------------------------------
void lib1x_auth_txCannedSuccess( Auth_Pae * auth_pae, int identifier );
void lib1x_auth_txCannedFail( Auth_Pae * auth_pae, int identifier );
void lib1x_auth_txReqId( Auth_Pae * auth_pae, int identifier );
void lib1x_authsm_dump( FILE * fdesc, Auth_Pae * auth_pae );
//-----------------------------------------------------
// sta table management function
//-----------------------------------------------------
int lib1x_search_supp(Dot1x_Authenticator * auth , lib1x_packet_tag * spkt, u_char inttype);
int lib1x_insert_supp(Dot1x_Authenticator *auth, u_char * supp_addr);
int lib1x_del_supp(Dot1x_Authenticator *auth, u_char * supp_addr);
#endif

View File

@ -0,0 +1,63 @@
#ifndef LIB1x_BAUTH_SM_H
#define LIB1x_BAUTH_SM_H
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_bauth_sm.h
// Programmer : Arunesh Mishra
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#define LIB1X_BSM_SUPPTIMEOUT 30
#define LIB1X_BSM_SVRTIMEOUT 30
#define LIB1X_BSM_MAXREQ 2
#include <stdio.h>
struct Auth_Pae_tag;
struct Global_Params_tag;
typedef struct Bauth_SM_tag
{
BAUTH_SM_STATE state;
int reqCount;
// A counter used to determine how many EAP Request packets
// have been sent to the Supplicant without receiving a response.
BOOLEAN rxResp; // if a EAPOL PDU of type EAP packet rcvd from supp carrying a Request
BOOLEAN aSuccess; // if Accept pkt recvd from Auth Server
BOOLEAN aFail; // true if reject pkt rcvd from auth svr.
BOOLEAN aReq; // true if eap req pkt rcvd frm auth svr.
int idFromServer; // most recent EAP success, failure or req pkt rcvd frm auth svr.
int suppTimeout;
int serverTimeout;
int maxReq;
FILE * debugsm;
} Bauth_SM;
// The functions exported.
void lib1x_bauthsm_init( Bauth_SM * bauth_sm, int maxReq, int aWhile );
void lib1x_bauthsm( struct Auth_Pae_tag * , struct Global_Params_tag * , Bauth_SM * );
BOOLEAN lib1x_trans_bauthsm( struct Auth_Pae_tag * , struct Global_Params_tag *, Bauth_SM * );
void lib1x_exec_bauthsm( struct Auth_Pae_tag * , struct Global_Params_tag * , Bauth_SM * );
void lib1x_bauthsm_abortAuth();
#endif

View File

@ -0,0 +1,42 @@
#ifndef LIB1x_CDSM_H
#define LIB1x_CDSM_H
#include "1x_types.h"
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : auth_pae.h
// Programmer : Arunesh Mishra
//
// H file for Controlled Directions State Machine
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
struct Auth_Pae_tag;
struct Global_Params_tag; /* These have been defined in 1x_common.h */
typedef struct CtrlDirSM_tag
{
CTRL_SM_STATE state;
DIRECTION adminControlledDirections;
DIRECTION operControlledDirections;
BOOLEAN bridgeDetected;
} CtrlDirSM;
void lib1x_cdsm_init( CtrlDirSM * ctrl_sm );
void lib1x_trans_cdsm( struct Auth_Pae_tag * auth_params, struct Global_Params_tag * global, CtrlDirSM * dirsm);
#endif

View File

@ -0,0 +1,690 @@
#ifndef LIB1x_COMMON_H
#define LIB1x_COMMON_H
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : common.h
// Programmer : Arunesh Mishra
//
// Contains all common declarations and definitions.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
#include<assert.h>
#include<stdarg.h>
#include<sys/types.h>
#include<stdio.h>
#include <syslog.h> // david+2006-03-31, for add event to syslog
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "rtk_arch.h"
#ifndef RTL_WPA_CLIENT
#if !defined(CONFIG_RTL8186_TR) && !defined(CONFIG_RTL865X_AC)
#define RTL_WPA_CLIENT
//#define DBG_WPA_CLIENT
#endif
#endif
#ifdef _RTL_WPA_WINDOWS
#else
#include "1x_types.h"
#include "1x_ethernet.h"
#include "1x_kmsm_keydef.h"
#endif
#ifdef RTL_WPA2
#include "1x_list.h"
#endif
#if defined(CONFIG_RTL8186_TR) || defined(CONFIG_RTL865X_SC) || defined(CONFIG_RTL865X_AC) || defined(CONFIG_RTL865X_KLD)
#define _NOTICE "tag:NOTICE;log_num:13;msg:"
#define _CMD "exlog /tmp/log_web.lck /tmp/log_web"
#define LOG_MSG_NOTICE(fmt, args...) { \
char tmpbuf[400]; \
sprintf(tmpbuf, "%s \"%s" fmt "\"", _CMD, _NOTICE, ## args); \
system(tmpbuf); \
}
#endif
#ifdef CONFIG_IEEE80211W
union PN48 {
unsigned long long val48;
struct {
unsigned char TSC7;
unsigned char TSC6;
unsigned char TSC5;
unsigned char TSC4;
unsigned char TSC3;
unsigned char TSC2;
unsigned char TSC1;
unsigned char TSC0;
} _byte_;
};
#endif /* CONFIG_IEEE80211W */
#ifdef CONFIG_RTL_802_1X_CLIENT_SUPPORT
typedef enum { EAP_MD5=0, EAP_TLS=1, EAP_PEAP=2 } EAP_TYPE_T;
typedef enum { INSIDE_MSCHAPV2=0 } INSIDE_TYPE_T;
typedef enum { PHYBAND_OFF=0, PHYBAND_2G=1, PHYBAND_5G=2 } PHYBAND_TYPE_T;
#define MAX_EAP_USER_ID_LEN 64
#define MAX_RS_USER_NAME_LEN 64
#define MAX_RS_USER_PASS_LEN 64
#define MAX_RS_USER_CERT_PASS_LEN 64
//#define RS_USER_CERT (TOP_CONFIG_DIR "/1x/client.pem")
#define RS_USER_CERT_2G (TOP_CONFIG_DIR "/1x/client_2g.pem")
#define RS_USER_CERT_5G (TOP_CONFIG_DIR "/1x/client_5g.pem")
//#define RS_ROOT_CERT (TOP_CONFIG_DIR "/1x/ca.pem")
#define RS_ROOT_CERT_2G (TOP_CONFIG_DIR "/1x/ca_2g.pem")
#define RS_ROOT_CERT_5G (TOP_CONFIG_DIR "/1x/ca_5g.pem")
//#define XSUP_CONF_FILE (TOP_CONFIG_DIR "/1x/1x.conf")
#define XSUP_CONF_FILE_NAME_FMT (TOP_CONFIG_DIR "/1x/1x-%s.conf")
//#define XSUP_CONF_MODULE_FILE (TOP_CONFIG_DIR "/1x/1x_module.conf")
#define XSUP_MD5_CONF_MODULE_FILE (TOP_CONFIG_DIR "/1x/1x_module_md5.conf")
#define XSUP_TLS_CONF_MODULE_FILE (TOP_CONFIG_DIR "/1x/1x_module_tls.conf")
#define XSUP_PEAP_CONF_MODULE_FILE (TOP_CONFIG_DIR "/1x/1x_module_peap.conf")
#endif
#define MAX_RS_NAS_PORT_ID_LEN 64
#define IP_ADDRSIZE 50
#define INC(X) { (X) = (X) + 1; if (X > 255) X = 0; /*write(1, "\n[INC]\n", sizeof("\n[INC]\n"));*/};
#define MESS_BUF_SIZE 512
#define MESS_DBG_AUTH 1
#define MESS_DBG_AUTHSM 9
#define MESS_DBG_AUTHNET 8
#define MESS_DBG_KRCSM 5
#define MESS_DBG_KXSM 6
#define MESS_DBG_SUPP 2
#define MESS_DBG_NAL 7
#define MESS_DBG_BSM 10
#define MESS_DBG_RAD 11
#define MESS_DBG_PTSM 13
#define MESS_AUTH_LOG 4
#define MESS_ERROR_OK 16
#define MESS_ERROR_FATAL 17
#define MESS_DBG_SPECIAL 12
#define MESS_DBG_DAEMON 18
#define MESS_DBG_KEY_MANAGE 19
#define MESS_DBG_CONTROL 20 //2003-06-13
#define MESS_DBG_RSNINFO 21
#define MESS_DBG_CONFIG 22
#define MESS_DBG_ACCT 23
#define MESS_DBG_FIFO 24
#define MAX_SUPPLICANT 32
#define MAX_RCV_FIFO 2048
//#define LIB1X_RAD_SHARED 100
#define LIB1X_AUTH_INDEX 0xfff
struct PKT_LSTNR_tag;
struct PKT_XMIT_tag;
//---- Basic Timer Unit in useconds ----
//#define LIB1X_BASIC_TIMER_UNIT 100000
// kenny
//#define LIB1X_BASIC_TIMER_UNIT 1000000
#define LIB1X_BASIC_TIMER_UNIT 100000
#define SECONDS_TO_TIMERCOUNT(x) ((x*1000000)/LIB1X_BASIC_TIMER_UNIT)
#define USECONDS_TO_TIMERCOUNT(x) (x/LIB1X_BASIC_TIMER_UNIT)
// use the following macro to replace usleep interrupt by timer
#define LIB_USLEEP(x) {\
int i;\
for(i=0; i < USECONDS_TO_TIMERCOUNT(x) ; i++)\
if(usleep(x) == 0)\
break;\
}
#define INC_GLOBAL_SESSION_ID(X) ((X==0xffffffff)?X=0:X++)
typedef struct Timers_tag
{
int authWhile;
// Used by the Supplicant PAE to determine how long to wait for
// a response from the Authenticator.
int aWhile;
// Used by the Backend Authentication state machine in order to
// determine timeout conditions in the exchanges between the
// Authenticator and Supplicant or Auth Server.
int heldWhile;
// Used by Supplicant state machine to define periods of time
// during which it will not attempt to acquire an Authenticator.
int quietWhile;
// During this period Authenticator will not acquire supplicant.
int reAuthWhen;
// A timer used by the Reauthentication Timer state machine in
// order to determine when re-authentication of the Supplicant
// takes place.
int startWhen;
// Used by Supplicant PAE state machine to determine when an
// EAPOL start PDU is to be transmitted.
int txWhen;
} Timers;
struct Auth_Pae_tag;
struct Supp_Pae_tag; // these here to make "# includes" consistent
struct lib1x_ptsm;
//-----------------------------------------------------------------------
// RSN Related
//-----------------------------------------------------------------------
#define DOT11_MAX_ALGORITHMS 0x0a
typedef struct _DOT11_AlgoElement
{
u_long Index;
u_long AlgoId;
BOOLEAN Enabled;
}DOT11_AlgoElement;
typedef struct _DOT11_AlgoSuit
{
u_long NumOfAlgo;
DOT11_AlgoElement AlgoTable[DOT11_MAX_ALGORITHMS];
}DOT11_AlgoSuit;
typedef struct _DOT11_RSN_AUTHENTICATOR_VARIABLE
{
//RSN related variable
OCTET_STRING AuthInfoElement;
BOOLEAN isSupportUnicastCipher;
BOOLEAN isSupportMulticastCipher;
BOOLEAN isSupportPreAuthentication;
BOOLEAN isSupportPairwiseAsDefaultKey;
BOOLEAN Dot1xEnabled;
BOOLEAN MacAuthEnabled;
BOOLEAN RSNEnabled;
#ifdef RTL_WPA2
BOOLEAN WPAEnabled;
BOOLEAN WPA2Enabled;
#endif
BOOLEAN TSNEnabled;
int WepMode;
int NumOfUnicastCipher;
int NumOfAuthCipher;
DOT11_AlgoSuit UniCastCipherSuit;
#ifdef RTL_WPA2
DOT11_AlgoSuit WPA2UniCastCipherSuit;
#endif
DOT11_AlgoSuit MulticastCipherSuit;
DOT11_AlgoSuit AuthenticationSuit;
u_char NumOfRxTSC;
u_char MulticastCipher;
u_char AuthKeyMethod;
#ifdef CONFIG_IEEE80211W
enum mfp_options ieee80211w;
/* dot11AssociationSAQueryMaximumTimeout (in TUs) */
unsigned int assoc_sa_query_max_timeout;
/* dot11AssociationSAQueryRetryTimeout (in TUs) */
int assoc_sa_query_retry_timeout;
#endif /* CONFIG_IEEE80211W */
#ifdef HS2_SUPPORT
unsigned char bOSEN; // OSU Server-Only Authenticated L2 Encryption Network
#endif
u_char PassPhrase[64];
// size is not enough because in PasswordHash(), it will use 40 bytes long. 2005-8-8 david
// u_char PassPhraseKey[32];
u_char PassPhraseKey[40];
char ssid[64];
#ifdef RTL_RADIUS_2SET
BOOLEAN rs2MacAuthEnabled;
#endif
}DOT11_RSN_AUTHENTICATOR_VARIABLE;
typedef struct _DOT11_RSN_SUPPLICANT_VARIABLE{
OCTET_STRING SuppInfoElement;
BOOLEAN isSuppSupportUnicastCipher;
BOOLEAN isSuppSupportMulticastCipher;
BOOLEAN isSuppSupportPreAuthentication;
BOOLEAN isSuppSupportPairwiseAsDefaultKey;
BOOLEAN RSNEnabled;
#ifdef RTL_WPA2
BOOLEAN isPreAuth;
BOOLEAN WPAEnabled;
BOOLEAN WPA2Enabled;
BOOLEAN PMKCached;
struct _WPA2_PMKSA_Node* cached_pmk_node;
#endif
u_char UnicastCipher;
u_char MulticastCipher;
#ifdef CONFIG_IEEE80211W
u_char mgmt_group_cipher;
#endif /* CONFIG_IEEE80211W */
u_char NumOfRxTSC;
DOT11_AlgoSuit AuthSupportUnicastCipherSuit;
DOT11_AlgoSuit AuthSupportAuthenticationCipherSuit;
BOOLEAN isAuthSupportPreAuthentication;
BOOLEAN isAuthSupportPairwiseAsDefaultKey;
u_char AuthSupportMaxNumOfRxTSC;
}DOT11_RSN_SUPPLICANT_VARIABLE;
//-----------------------------------------------------------------------------
// Radius Key for RSN802dot1x or nonRSN802dot1x
//-----------------------------------------------------------------------------
#define RADIUS_KEY_LEN 64
typedef enum _RADIUS_KEY_STATUS
{
MPPE_SDRCKEY_NONAVALIABLE = 0x00,
MPPE_SENDKEY_AVALIABLE = 0x01,
MPPE_RECVKEY_AVALIABLE = 0x02,
MPPE_SDRCKEY_AVALIABLE = 0x03,
}RADIUS_KEY_STATUS;
typedef struct _RADIUS_KEY
{
RADIUS_KEY_STATUS Status;
OCTET_STRING SendKey;
OCTET_STRING RecvKey;
}RADIUS_KEY;
//Added to support WPA
struct Auth_PairwiseKeyManage_tag;
struct Supp_PairwiseKeyManage_tag;
struct Auth_GroupKeyManage_tag;
struct _Dot1x_Authenticator;
struct _Dot1x_Client;
//End Added
typedef struct _Dot11RSNConfigEntry {
//dot11RSNConfigIndex InterfaceIndexOrZero,
int Version;
int PairwiseKeysSupported;
OCTET_STRING MulticastCipher;
int GroupRekeyMethod;
u_long GroupRekeyTime;
u_long GroupRekeyPackets;
BOOLEAN GroupRekeyStrict;
OCTET_STRING PSKValue;
//u_char* PSKPassPhrase DisplayString,
BOOLEAN TSNEnabled;
u_long GroupMasterRekeyTime;
u_long GroupUpdateTimeOut;
u_long GroupUpdateCount;
u_long PairwiseUpdateTimeOut;
u_long PairwiseUpdateCount;
}Dot11RSNConfigEntry;
typedef struct Global_Params_tag
{
BOOLEAN authAbort;
BOOLEAN authFail;
BOOLEAN authStart;
BOOLEAN authTimeout;
BOOLEAN authSuccess;
int currentId; // Id for current authentication session
BOOLEAN initialize;
PORT_MODE_TYPE portControl;
BOOLEAN portEnabled;
PORT_STATUS_TYPE portStatus;
BOOLEAN reAuthenticate;
int receivedId;
PORT_STATUS_TYPE suppStatus;
struct lib1x_ptsm * timers;
//ROLE currentRole;
int index;
struct Auth_Pae_tag * theAuthenticator;
struct Supp_Pae_tag * theSupplicant;
struct TxRx_Params_tag * TxRx;
//Added to support WPA
struct Auth_PairwiseKeyManage_tag *akm_sm;
struct Supp_PairwiseKeyManage_tag *skm_sm;
OCTET_STRING EAPOLMsgRecvd; //The Overall 802.1x message
OCTET_STRING EAPOLMsgSend; //The Overall 802.1x message
OCTET_STRING EapolKeyMsgRecvd; //The start point of eapol-key payload
OCTET_STRING EapolKeyMsgSend;
int AuthKeyMethod;
RADIUS_KEY RadiusKey;
BOOLEAN PreshareKeyAvaliable;
#ifdef RTL_WPA2
// kenny PMK_LEN should be enough
u_char PSK[PMK_LEN];
#else
u_char PSK[PMK_LEN * 2];
#endif
u_char MaxRetryCounts;
u_char EventId;
BOOLEAN portSecure;
u_char DescriptorType; //initialize to 254 in RSN
u_char KeyDescriptorVer;
u_char CurrentAddress[ETHER_ADDRLEN];
BOOLEAN bMacAuthEnabled;
#ifdef CONFIG_IEEE80211W
BOOLEAN mgmt_frame_prot;
#endif /* CONFIG_IEEE80211W */
//RSNIE related variable
struct _DOT11_RSN_SUPPLICANT_VARIABLE RSNVariable;
Dot11RSNConfigEntry Dot11RSNConfig;
struct _Dot1x_Authenticator *auth;
//End Added WPA
} Global_Params;
typedef struct TxRx_Params_tag
{
u_char oursvr_addr[ETHER_ADDRLEN]; // ethernet address of the server interface
u_char oursupp_addr[ETHER_ADDRLEN]; // ethernet address of the supplicant interface
//u_char supp_addr[ETHER_ADDRLEN];
u_char svr_addr[ETHER_ADDRLEN];
// Device name
u_char * device_supp;
u_char * device_svr;
char * device_wlan0;
// Interface to three daemon (1)ethernet (2)wireless (3)driver
struct lib1x_nal_intfdesc * network_svr;
struct lib1x_nal_intfdesc * network_supp;
#ifdef RTL_WPA2_PREAUTH
struct lib1x_nal_intfdesc * network_ds; // via the DS, i.e. eth0 or br0?
#endif
int fd_control;
FILE * debugsm;
struct in_addr ourip_inaddr, svrip_inaddr, acctip_inaddr;
u_short udp_ourport;
u_short udp_svrport;
u_short udp_acctport;
struct sockaddr_in radsvraddr;
struct sockaddr_in acctsvraddr;
#ifdef RTL_RADIUS_2SET
struct lib1x_nal_intfdesc * network_svr2;
struct in_addr svrip_inaddr2;
u_short udp_svrport2;
struct sockaddr_in radsvraddr2;
u_short flag_replaced;
struct in_addr acctip_inaddr2;
u_short udp_acctport2;
struct sockaddr_in acctsvraddr2;
#endif
u_char GlobalRadId;
// Added to support fifo architecture
int readfifo;
int dummyfd;
u_char RecvBuf[MAX_RCV_FIFO];
OCTET_STRING RListenFIFO;
} TxRx_Params;
typedef enum { DISABLE, ENABLE } Switch;
typedef struct _Dot1x_Supplicant
{
int index;
BOOLEAN isEnable;
BOOLEAN isEAPCapable;
//unsigned char addr[ETHER_ADDRLEN];
Global_Params *global;
} Dot1x_Supplicant;
#if 0
typedef struct
{
unsigned short aid;
unsigned char addr[6];
unsigned long tx_packets;
unsigned long rx_packets;
unsigned long expired_time; // 10 msec unit
unsigned short flags;
unsigned char TxOperaRate;
unsigned char rssi;
unsigned long link_time; // 1 sec unit
unsigned long tx_fail;
} RTL_STA_INFO;
#endif
typedef struct _sta_info_2_web {
unsigned short aid;
unsigned char addr[6];
unsigned long tx_packets;
unsigned long rx_packets;
unsigned long expired_time; // 10 msec unit
unsigned short flags;
unsigned char TxOperaRate;
unsigned char rssi;
unsigned long link_time; // 1 sec unit
unsigned long tx_fail;
unsigned long tx_bytes;
unsigned long rx_bytes;
unsigned char resv[8];
} sta_info_2_web;
#define RTL_STA_INFO sta_info_2_web
typedef struct _Dot1x_Authenticator
{
int MaxSupplicant;
int NumOfSupplicant;
ROLE currentRole;
TxRx_Params *GlobalTxRx;
Dot1x_Supplicant *Supp[MAX_SUPPLICANT];
OCTET_STRING RadShared; /* NAS and RADIUS */
OCTET_STRING AcctShared;
LARGE_INTEGER Dot1xKeyReplayCounter;
u_long UsePassphrase;
u_long AuthTimerCount;
u_long KeyManageTimerCount;
u_long SessionInfoTimerCount; // Abocom
u_long IgnoreEAPOLStartCounter;
u_char svrip[IP_ADDRSIZE+1];
u_short udp_svrport;
#ifdef RTL_RADIUS_2SET
u_short use_2nd_rad;
u_char svrip2[IP_ADDRSIZE+1];
u_short udp_svrport2;
OCTET_STRING RadShared2;
u_char acctip2[IP_ADDRSIZE+1];
u_short udp_acctport2;
OCTET_STRING AcctShared2;
#endif
u_char acctip[IP_ADDRSIZE+1];
u_short udp_acctport;
u_char WepGroupKey[32];
//Added to support WPA
struct Auth_GroupKeyManage_tag *gk_sm;
OCTET32_INTEGER Counter;
u_char CurrentAddress[ETHER_ADDRLEN];
DOT11_RSN_AUTHENTICATOR_VARIABLE RSNVariable;
Dot11RSNConfigEntry Dot11RSNConfig;
u_char IoctlBuf[1024];
u_long IoctlBufLen;
BOOLEAN IoctlFlag;
//end Added
//Accounting
u_long InterimTimeout;
BOOLEAN SessionTimeoutEnabled;
BOOLEAN IdleTimeoutEnabled;
BOOLEAN AccountingEnabled;
BOOLEAN UpdateInterimEnabled;
u_long GlobalSessionId;
Dot1x_Supplicant *authGlobal;
// david, fix to 128. If support sta is greater than 128 in wlan driver,
// this value need be modified.
// RTL_STA_INFO StaInfo[MAX_SUPPLICANT+1];
RTL_STA_INFO StaInfo[128+1];
//-------------------------------------------------------------------------
//Server config
u_long rsMaxReq;
u_long rsAWhile;
u_long rsReAuthTO;
u_long accountRsMaxReq;
u_long accountRsAWhile;
#ifdef RTL_WPA_CLIENT
struct _Dot1x_Client *client;
#endif
#ifdef RTL_WPA2
struct list_head pmk_cache;
#endif
#ifdef CONFIG_RTL_802_1X_CLIENT_SUPPORT
char eapType;
char eapInsideType;
char eapUserId[MAX_EAP_USER_ID_LEN+1];
char rsUserName[MAX_RS_USER_NAME_LEN+1];
char rsUserPasswd[MAX_RS_USER_PASS_LEN+1];
char rsUserCertPasswd[MAX_RS_USER_CERT_PASS_LEN+1];
char rsBandSel;
#endif
#ifdef CONFIG_RTL8196C_AP_HCM
unsigned char hostmac[13];
unsigned int if_index;
#endif
char rsNasPortId[MAX_RS_NAS_PORT_ID_LEN];
} Dot1x_Authenticator;
void lib1x_print_etheraddr( char * s, u_char * addr );
#ifndef DEBUG_DISABLE //sc_yang
void lib1x_message( int type, char * msg, ... );
void lib1x_hexdump( FILE * fdesc, u_char * pkt, int numBytes );
void lib1x_totext_authpaestate( FILE * fdesc, AUTH_PAE_STATE state );
void lib1x_totext_bauthsmstate( FILE * fdesc, BAUTH_SM_STATE state );
void lib1x_chardump( FILE * fdesc, u_char * pkt, int numBytes );
void lib1x_hexdump2(int type, char *fun, u_char *buf, int size, char *comment);
void lib1x_PrintAddr(u_char *ucAddr);
void DUMP_GLOBAL_PARAMS( Global_Params *g, u_char *exp );
#else
#define lib1x_message(type, msg...) do{}while(0)
#define lib1x_hexdump(a, b, c) do{}while(0)
#define lib1x_totext_authpaestate(a, b) do{}while(0)
#define lib1x_totext_bauthsmstate(a, b) do{}while(0)
#define lib1x_chardump(a, b, c) do{}while(0)
#define lib1x_hexdump2(a, b, c, e , f) do{}while(0)
#define lib1x_PrintAddr(a) do{}while(0)
#define DUMP_GLOBAL_PARAMS(a, b) do{}while(0)
#endif
#ifdef CONFIG_IEEE80211W
#define PMFDEBUG(fmt, args...) printf("[%s %d]"fmt,__FUNCTION__,__LINE__,## args)
//#define PMFDEBUG(fmt, args...)
#endif /* CONFIG_IEEE80211W */
//sc_yang
extern void * lib1x_global_signal_info;
// This variable points to struct lib1x_ptsm , the port timers state machine struct,
// because we need the signal handler to access some global variable.
extern u_char dev_supp[]; // david+2006-03-31, for add event to syslog
#ifdef _ABOCOM
#define ABOCOM_ADD_STA 0
#define ABOCOM_DEL_STA 1
void lib1x_abocom(u_char *pucAddr, int ulCommandType);
#endif
#define lib1x_Little_S2N(s,c) (*((c) )=(unsigned char)(((s))&0xff), \
*((c)+1)=(unsigned char)(((s)>>8)&0xff))
#define lib1x_Little_N2S(c,s) s = 0,\
(s =((unsigned long)(*((c) ))), \
s|=( (unsigned long) (*((c)+1))<<8) )
#define lib1x_S2N(s,c) (*((c) )=(unsigned char)(((s)>>8)&0xff), \
*((c)+1)=(unsigned char)(((s) )&0xff))
#define lib1x_N2S(c,s) s = 0,\
(s =((unsigned long)(*((c) )))<<8, \
s|=((unsigned long)(*((c)+1))))
#define lib1x_L2N(l,c) (*((c) )=(unsigned char)(((l)>>24)&0xff), \
*((c)+1)=(unsigned char)(((l)>>16)&0xff), \
*((c)+2)=(unsigned char)(((l)>> 8)&0xff), \
*((c)+3)=(unsigned char)(((l) )&0xff))
#define lib1x_N2L(c,l) l = 0,\
(l =((unsigned long)(*((c) )))<<24, \
l|=((unsigned long)(*((c)+1)))<<16, \
l|=((unsigned long)(*((c)+2)))<< 8, \
l|=((unsigned long)(*((c)+3))))
//----------------------------------------------------------------
// 1x_kmsm_prf.c
//----------------------------------------------------------------
int PasswordHash (
char *password,
int passwordlength,
unsigned char *ssid,
int ssidlength,
unsigned char *output);
#ifdef RTL_WPA2
//----------------------------------------------------------------
// PMK Cache
//----------------------------------------------------------------
struct _WPA2_PMKSA
{
u_char pmkid[PMKID_LEN];
// u_char aa[6]; // Authenticator MAC Address
u_char pmk[PMK_LEN];
// u_long lifetime;
u_char akmp;
u_char spa[ETHER_ADDRLEN]; // Supplicant MAC Address
};
struct _WPA2_PMKSA_Node
{
struct list_head node;
struct _WPA2_PMKSA pmksa;
};
#endif /* RTL_WPA2 */
#endif /* LIB1x_COMMON_H */

View File

@ -0,0 +1,95 @@
#ifndef _CONFIG_PARSE_H
#define _CONFIG_PARSE_H
#define CONFIG_PARSE_TAG 80
#define CONFIG_PARSE_VALUE 80
typedef enum { ERROR_FILE_NOTEXIST = -1, ERROR_UNDEFINE_PARAMETER = -2,
ERROR_UNDEFINE_TAG = -3 } CONFIG_ERROR_ID;
#define CFG_STRERROR_FILE_NOTEXIST "Configuration file not exist"
#define CFG_STRERROR_UNDEFINE_PARAMETER "Undefine parameter in configuration file"
#define CFG_STRERROR_UNDEFINE_TAG "Undefine tag in configuration file"
typedef enum { tagUnicastCipher = 0, tagMulticastCipher = 1, tagAuthKeyMethod = 2} CONFIG_TAG_TABLE;
char ConfigTag[][32] =
{
"ssid",
"encryption",
"enable1x",
"enableMacAuth",
"supportNonWpaClient",
"wepKey",
"wepGroupKey",
"authentication",
"unicastCipher",
#ifdef RTL_WPA2
"wpa2UnicastCipher",
"enablePreAuth",
#endif
"usePassphrase",
"groupRekeyTime",
"psk",
"rsPort",
"rsIP",
"rsPassword",
#ifdef RTL_RADIUS_2SET
"rs2Port",
"rs2IP",
"rs2Password",
"rs2enableMacAuth",
#endif
#ifdef CONFIG_RTL_802_1X_CLIENT_SUPPORT
"eapType",
"eapInsideType",
"eapUserId",
"rsUserName",
"rsUserPasswd",
"rsUserCertPasswd",
"rsBandSel",
#endif
"rsMaxReq",
"rsAWhile",
"rsNasId",
"rsReAuthTO",
"accountRsEnabled",
"accountRsPort",
"accountRsIP",
"accountRsPassword",
#ifdef RTL_RADIUS_2SET
"accountRs2Port",
"accountRs2IP",
"accountRs2Password",
#endif
"accountRsMaxReq",
"accountRsAWhile",
"accountRsUpdateEnabled",
"accountRsUpdateTime",
#ifdef CONFIG_RTL8196C_AP_HCM
"hostmac",
#endif
#ifdef CONFIG_IEEE80211W
"ieee80211w",
"sha256",
#endif /* CONFIG_IEEE80211W */
"NasPortId",
};
/**
* Reads a tag out of a file in the form
* tag = value
*
* return 0 on success -1 on fail
*/
int configParse(char *, /* File name */
char *, /* Tag */
char * /* value */
);
#endif /* _CONFIG_PARSE_H_ */
/*** EOF ***/

View File

@ -0,0 +1,24 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_eap.h
// Programmer : Arunesh Mishra
//
// Extensible Authentication Protocol routines
// H FILE
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
#ifndef 1X_EAP_H
#define 1X_EAP_H
#endif

View File

@ -0,0 +1,114 @@
#ifndef LIB1x_EAPOL_H
#define LIB1x_EAPOL_H
//#include <libnet.h>
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_eapol.h
// Programmer : Arunesh Mishra
//
// This contains the EAPOL packet routine
// declarations.
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
#define LIB1X_EAPOL_HDRLEN 4 // Just the header Note:
// is different from struct
#define LIB1X_EAPOL_LOGOFF 2 //0000 0010B
#define LIB1X_EAPOL_EAPPKT 0 //0000 0000B
#define LIB1X_EAPOL_START 1 //0000 0001B
#define LIB1X_EAPOL_KEY 3 //0000 0011B
#define LIB1X_EAPOL_ENCASFALERT 4 //0000 0100B
#ifdef _DATA_PATH
#define REALTEK_802dot1x_TYPE 0xcc
#endif
#define LIB1X_EAP_REQUEST 1
#define LIB1X_EAP_RESPONSE 2
#define LIB1X_EAP_SUCCESS 3
#define LIB1X_EAP_FAILURE 4
#define LIB1X_EAP_HDRLEN 4
#define LIB1X_EAP_RRIDENTITY 1
#define LIB1X_EAP_RRNOTIF 2
#define LIB1X_EAP_RRNAK 3
#define LIB1X_EAP_RRMD5 4
#define LIB1X_EAP_RROTP 5
#define LIB1X_EAP_RRGEN 6
#define LIB1x_EAP_RRLEN 1
#define LIB1X_EAPOL_VER 1 //00000001B
#define LIB1X_EAPOLKEY_HDRLEN 44
#define LIB1X_RC_LEN 8
#define LIB1X_IV_LEN 16
#define LIB1X_MIC_LEN 16
#define LIB1X_KEY_TYPE_RC4 1
#pragma pack (1) // Set our value.
struct lib1x_eapol
{
// u_short ether_type; // not including this here .. it overlaps with the ethernet header.
u_char protocol_version;
u_char packet_type; // This makes it odd in number !
u_short packet_body_length;
};
struct lib1x_eap
{
u_char code; // Identifies the type of EAP packet.
u_char identifier; // Aids in matching responses with requests.
u_short length; // Length of EAP packet including code, id, len, data fields
};
#define EAPOL_PAIRWISE_KEY 0x80
#define EAPOL_GROUP_KEY 0
#define EAPOL_PAIRWISE_INDEX 0x3
#define EAPOL_GROUP_INDEX 0x0
struct lib1x_eapolkey_dot1x
{
u_char type;
u_short length;
u_char counter[LIB1X_RC_LEN];
u_char iv[LIB1X_IV_LEN];
u_char index;
u_char mic[LIB1X_MIC_LEN];
u_char material[1];
};
struct lib1x_eap_rr
{
u_char type; // The bytes after this are the data corresponding to the RR type
};
void lib1x_construct_eapol_frame( struct lib1x_eapol * the_header, u_char * packet );
//sc_yang
#pragma pack () // Set our value.
#endif

View File

@ -0,0 +1,36 @@
#ifndef LIB1X_ETHERNET_H
#define LIB1X_ETHERNET_H
#include <sys/types.h>
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : lib1x_ethernet.h
// Programmer : Arunesh Mishra
// Contains some declarations for the 802.3 ethernet.
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#define ETHER_ADDRLEN 6
#define ETHER_HDRLEN 14
#define LIB1X_ETHER_EAPOL_TYPE 0x888E
#ifdef RTL_WPA2_PREAUTH
#define PREAUTH_ETHER_EAPOL_TYPE 0x88C7
#endif
#define LIB1X_ETHER_IP 0x800
struct lib1x_ethernet
{
u_char ether_dhost[ETHER_ADDRLEN]; /* destination ethernet address */
u_char ether_shost[ETHER_ADDRLEN]; /* source ethernet address */
u_short ether_type; /* packet type ID */
};
#endif

View File

@ -0,0 +1,34 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "rtk_arch.h"
//#define DAEMON_FIFO "/root/802.1x/open1x/src/FIFO/daemon_fifo"
#ifdef _DAEMON_SIDE
#define DAEMON_FIFO (TOP_CONFIG_DIR "/auth-%s.fifo")
#else
//sc_yang for dual mode
#define DAEMON_FIFO (TOP_CONFIG_DIR "/auth-%s.fifo")
#endif
#ifdef _LISTEN_SIDE
#define LISTEN_FIFO "fifo.dat"
#else
#define LISTEN_FIFO "fifo.dat"
#endif
#define MAXLINE 20000
#define RWFIFOSIZE 1600 // jimmylin: org: 160, for passing EAP packet by event queue
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
/* default permission for new files */
#define FIFO_TYPE_WLISTEN 0x01
#define FIFO_TYPE_DLISTEN 0x02
#define FIFO_TYPE_RLISTEN 0x03
#define FIFO_HEADER_LEN 5

View File

@ -0,0 +1,260 @@
#ifdef _RTL_WPA_WINDOWS
typedef unsigned short u_short;
typedef unsigned char u_char;
#else
#include <sys/types.h>
#endif
#include "1x_common.h"
#define NONE -1
#define CIPHER_WEP40 0
//#define CIPHER_TKIP 1
#define CIPHER_AESCCMP 2
#define CIPHER_AESWRAP 3
#define CIPHER_WEP104 4
#define IEEE802_1X 0
#define ELEMENTID 0xdd
#define GROUPFLAG 0x02
#define REPLAYBITSSHIFT 2
#define REPLAYBITS 0x03
struct InfoElement {
u_char Elementid;
u_char length;
u_char oui[4];
u_short version;
u_char multicast[4];
u_short ucount;
struct {
u_char oui[4];
}unicast[1]; // the rest is variable so need to
// overlay ieauth structure
};
struct _ieauth {
u_short acount;
struct {
u_char oui[4];
}auth[1];
};
//---- Error number is the negative value
//---- that follows 802/11i D3.0 Failure Association Request reason code ----
typedef enum{ERROR_BUFFER_TOO_SMALL = -1, ERROR_INVALID_PARA = -2, ERROR_INVALID_RSNIE = -13,
ERROR_INVALID_MULTICASTCIPHER = -18, ERROR_INVALID_UNICASTCIPHER = -19,
ERROR_INVALID_AUTHKEYMANAGE = -20,
ERROR_UNSUPPORTED_RSNEVERSION = -21, ERROR_INVALID_CAPABILITIES = -22
#ifdef CONFIG_IEEE80211W
,ERROR_MGMT_FRAME_PROTECTION_VIOLATION = -31
#endif /* CONFIG_IEEE80211W */
}INFO_ERROR;
#define RSN_STRERROR_BUFFER_TOO_SMALL "Input Buffer too small"
#define RSN_STRERROR_INVALID_PARAMETER "Invalid RSNIE Parameter"
#define RSN_STRERROR_INVALID_RSNIE "Invalid RSNIE"
#define RSN_STRERROR_INVALID_MULTICASTCIPHER "Multicast Cipher is not valid"
#define RSN_STRERROR_INVALID_UNICASTCIPHER "Unicast Cipher is not valid"
#define RSN_STRERROR_INVALID_AUTHKEYMANAGE "Authentication Key Management Protocol is not valid"
#define RSN_STRERROR_UNSUPPORTED_RSNEVERSION "Unsupported RSNE version"
#define RSN_STRERROR_INVALID_CAPABILITIES "Invalid RSNE Capabilities"
#ifdef CONFIG_IEEE80211W
#define RSN_STRERROR_MGMT_FRAME_PROTECTION_VIOLATION "Robust management frame policy violation"
#endif /* CONFIG_IEEE80211W */
#define RSN_ELEMENT_ID 221
#ifdef RTL_WPA2
#define WPA_ELEMENT_ID 0xDD
#define WPA2_ELEMENT_ID 0x30
#endif
#define RSN_VER1 0x01
//#define DOT11_MAX_CIPHER_ALGORITHMS 0x0a
typedef struct _DOT11_RSN_IE_HEADER {
u_char ElementID;
u_char Length;
u_char OUI[4];
u_short Version;
}DOT11_RSN_IE_HEADER;
#ifdef RTL_WPA2
#define WPA2_ELEMENT_ID 0x30
typedef struct _DOT11_WPA2_IE_HEADER {
u_char ElementID;
u_char Length;
u_short Version;
}DOT11_WPA2_IE_HEADER;
#endif
typedef struct _DOT11_RSN_IE_SUITE{
u_char OUI[3];
u_char Type;
}DOT11_RSN_IE_SUITE;
typedef struct _DOT11_RSN_IE_COUNT_SUITE{
u_short SuiteCount;
DOT11_RSN_IE_SUITE dot11RSNIESuite[DOT11_MAX_ALGORITHMS];
}DOT11_RSN_IE_COUNT_SUITE, *PDOT11_RSN_IE_COUNT_SUITE;
typedef union _DOT11_RSN_CAPABILITY{
u_short shortData;
u_char charData[2];
#if 0
#ifdef RTL_WPA2
struct
{
#ifdef CONFIG_IEEE80211W
u_short MFPC:1; // B7
u_short MFPR:1; // B6
#else
u_short Reserved1:2; // B7 B6
#endif /* CONFIG_IEEE80211W */
u_short GtksaReplayCounter:2; // B5 B4
u_short PtksaReplayCounter:2; // B3 B2
u_short NoPairwise:1; // B1
u_short PreAuthentication:1; // B0
u_short Reserved2:8;
}field;
#else
struct
{
u_short PreAuthentication:1;
u_short PairwiseAsDefaultKey:1;
u_short NumOfReplayCounter:2;
u_short Reserved:12;
}field;
#endif
#endif //if 0
#ifdef RTL_WPA2
struct
{
#ifdef LIBNET_BIG_ENDIAN
#ifdef CONFIG_IEEE80211W
unsigned short MFPC:1; // B7
unsigned short MFPR:1; // B6
#else
unsigned short Reserved1:2; // B7 B6
#endif
unsigned short GtksaReplayCounter:2; // B5 B4
unsigned short PtksaReplayCounter:2; // B3 B2
unsigned short NoPairwise:1; // B1
unsigned short PreAuthentication:1; // B0
unsigned short Reserved2:8;
#else
unsigned short PreAuthentication:1; // B0
unsigned short NoPairwise:1; // B1
unsigned short PtksaReplayCounter:2; // B3 B2
unsigned short GtksaReplayCounter:2; // B5 B4
#ifdef CONFIG_IEEE80211W
unsigned short MFPR:1; // B6
unsigned short MFPC:1; // B7
#else
unsigned short Reserved1:2; // B7 B6
#endif
unsigned short Reserved2:8;
#endif
}field;
#else
struct
{
#ifdef LIBNET_BIG_ENDIAN
unsigned short PreAuthentication:1;
unsigned short PairwiseAsDefaultKey:1;
unsigned short NumOfReplayCounter:2;
unsigned short Reserved:12;
#else
unsigned short Reserved1:4;
unsigned short NumOfReplayCounter:2;
unsigned short PairwiseAsDefaultKey:1;
unsigned short PreAuthentication:1;
unsigned short Reserved2:8;
#endif
}field;
#endif
}DOT11_RSN_CAPABILITY;
#define DOT11_NUM_ENTRY 0x0a
//-------------------------------------------------
//-- Unicast Cipher Suite configuration table
//-------------------------------------------------
//--dot11RSNConfigUnicastCiphersEntry OBJECT-TYPE
//"The table entry, indexed by the interface index (or all interfaces) and the unicast cipher."
//-- dot11RSNConfigUnicastCiphersTable OBJECT-TYPE
//"This table lists the unicast ciphers supported by this entity.
//It allows enabling and disabling of each unicast cipher by network management.
//The Unicast Cipher Suite list in the RSN Information Element is formed using the information in this table."
typedef struct _Dot11RSNConfigUnicastCiphersEntry
{
u_long Index;
OCTET_STRING Cipher; //It consists of an OUI (the three most significant octets) and a cipher suite identifier (the least significant octet)."
BOOLEAN Enabled;
}Dot11RSNConfigUnicastCiphersEntry;
typedef struct _Dot11RSNConfigUnicastCiphersTable
{
u_long NumEntry;
Dot11RSNConfigUnicastCiphersEntry Table[DOT11_NUM_ENTRY];
}Dot11RSNConfigUnicastCiphersTable;
//-----------------------------------------------------------
// The Authentication Suites Table
//-----------------------------------------------------------
//----dot11RSNConfigAuthenticationSuitesEntry OBJECT-TYPE
//"An entry (row) in the dot11RSNConfigAuthenticationSuitesTable."
//----dot11RSNConfigAuthenticationSuitesTable OBJECT-TYPE
//"This table lists the authentication suites supported by this entity.
//Each authentication suite can be individually enabled and disabled.
//The Authentication Suite List in the RSN IE is formed using the information in this table."
typedef struct _Dot11RSNConfigAuthenticationSuitesEntry
{
u_long Index;
OCTET_STRING Suite; //It consists of an OUI (the three most significant octets) and a cipher suite identifier (the least significant octet). "
BOOLEAN Enabled;
}Dot11RSNConfigAuthenticationSuitesEntry;
typedef struct _Dot11RSNConfigAuthenticationSuitesTable{
u_long NumEntry;
Dot11RSNConfigUnicastCiphersEntry Table[DOT11_NUM_ENTRY];
}Dot11RSNConfigAuthenticationSuitesTable;
char * lib1x_authRSN_err(int err);
int lib1x_authRSN_constructIE(Dot1x_Authenticator * auth,
u_char * pucOut,
int * usOutLen,
BOOLEAN bAttachIEHeader);
int lib1x_authRSN_parseIE(Dot1x_Authenticator * auth,
Global_Params * global,
u_char * pucIE, u_long ulIELength);
//int lib1x_authRSN_parseIE(Dot1x_Authenticator * auth,
// Global_Params * global,
// u_char * pucIE, u_long ulIELength);
#ifdef RTL_WPA2
int lib1x_authRSN_match(Dot1x_Authenticator * auth, Global_Params * global, BOOLEAN bWPA2);
#else
int lib1x_authRSN_match(Dot1x_Authenticator * auth, Global_Params * global);
#endif

View File

@ -0,0 +1,637 @@
/************************* 802.1x Message ***************************/
/*
* Reason code for Disconnect
*/
typedef enum _ReasonCode{
unspec_reason = 0x01,
auth_not_valid = 0x02,
deauth_lv_ss = 0x03,
inactivity = 0x04,
ap_overload = 0x05,
class2_err = 0x06,
class3_err = 0x07,
disas_lv_ss = 0x08,
asoc_not_auth = 0x09,
#ifdef _RTL_WPA_UNIX
RSN_invalid_info_element = 13,
RSN_MIC_failure = 14,
RSN_4_way_handshake_timeout = 15,
RSN_diff_info_element = 17,
RSN_multicast_cipher_not_valid = 18,
RSN_unicast_cipher_not_valid = 19,
RSN_AKMP_not_valid = 20,
RSN_unsupported_RSNE_version = 21,
RSN_invalid_RSNE_capabilities = 22,
RSN_ieee_802dot1x_failed = 23,
//belowing are Realtek definition
RSN_PMK_not_avaliable = 24,
#endif
expire = 30,
session_timeout = 31,
acct_idle_timeout = 32,
acct_user_request = 33
}ReasonCode;
/*
* Data structure for ioctl with driver
*/
#define MAXRSNIELEN 128
#define MacAddrLen 6
#ifdef WIFI_SIMPLE_CONFIG
#define PROBEIELEN 128
#endif
typedef unsigned char DOT11_KEY_RSC[8];
typedef enum{
DOT11_KeyType_Group = 0,
DOT11_KeyType_Pairwise = 1
#ifdef CONFIG_IEEE80211W
,DOT11_KeyType_IGTK = 2
#endif /* CONFIG_IEEE80211W */
}DOT11_KEY_TYPE;
typedef enum{
DOT11_KeyUsage_ENC,
DOT11_KeyUsage_MIC
}DOT11_KEY_USAGE;
typedef enum{
DOT11_Role_Auth,
DOT11_Role_Supp
}DOT11_ROLE;
typedef enum{
DOT11_VARIABLE_MACEnable,
DOT11_VARIABLE_SystemAuthControl,
DOT11_VARIABLE_AuthControlledPortStatus,
DOT11_VARIABLE_AuthControlledPortControl,
DOT11_VARIABLE_AuthenticationType,
DOT11_VARIABLE_KeyManagement,
DOT11_VARIABLE_MulticastCipher,
DOT11_VARIABLE_UnicastCipher
} DOT11_VARIABLE_TYPE;
typedef enum{
DOT11_SysAuthControl_Disabled,
DOT11_SysAuthControl_Enabled
} DOT11_SYSTEM_AUTHENTICATION_CONTROL;
typedef enum{
DOT11_PortControl_ForceUnauthorized,
DOT11_PortControl_ForceAuthorized,
DOT11_PortControl_Auto
} DOT11_PORT_CONTROL;
typedef enum{
DOT11_PortStatus_Unauthorized,
DOT11_PortStatus_Authorized
}DOT11_PORT_STATUS;
typedef enum{
DOT11_Association_Fail,
DOT11_Association_Success
}DOT11_ASSOCIATION_RESULT;
typedef enum{
DOT11_AuthKeyType_RSNReserved = 0,
DOT11_AuthKeyType_RSN = 1,
DOT11_AuthKeyType_RSNPSK = 2,
DOT11_AuthKeyType_NonRSN802dot1x = 3,
#ifdef CONFIG_IEEE80211W
DOT11_AuthKeyType_802_1X_SHA256 = 5,
DOT11_AuthKeyType_PSK_SHA256 = 6,
#endif /* CONFIG_IEEE80211W */
DOT11_AuthKeyType_PRERSN = 255,
} DOT11_AUTHKEY_TYPE;
typedef enum{
DOT11_Ioctl_Query = 0,
DOT11_Ioctl_Set = 1,
} DOT11_Ioctl_Flag;
typedef enum{
DOT11_ENC_NONE = 0,
DOT11_ENC_WEP40 = 1,
DOT11_ENC_TKIP = 2,
DOT11_ENC_WRAP = 3,
DOT11_ENC_CCMP = 4,
DOT11_ENC_WEP104= 5,
#ifdef CONFIG_IEEE80211W
DOT11_ENC_BIP = 6,
DOT11_ENC_NOGA = 7, //Group addressed traffic not allowed
#endif /* CONFIG_IEEE80211W */
DOT11_ENC_UNKNOWN = 255,
} DOT11_ENC_ALGO;
typedef enum{
DOT11_EVENT_NO_EVENT = 1,
DOT11_EVENT_REQUEST = 2,
DOT11_EVENT_ASSOCIATION_IND = 3,
DOT11_EVENT_ASSOCIATION_RSP = 4,
DOT11_EVENT_AUTHENTICATION_IND = 5,
DOT11_EVENT_REAUTHENTICATION_IND = 6,
DOT11_EVENT_DEAUTHENTICATION_IND = 7,
DOT11_EVENT_DISASSOCIATION_IND = 8,
DOT11_EVENT_DISCONNECT_REQ = 9,
DOT11_EVENT_SET_802DOT11 = 10,
DOT11_EVENT_SET_KEY = 11,
DOT11_EVENT_SET_PORT = 12,
DOT11_EVENT_DELETE_KEY = 13,
DOT11_EVENT_SET_RSNIE = 14,
DOT11_EVENT_GKEY_TSC = 15,
DOT11_EVENT_MIC_FAILURE = 16,
DOT11_EVENT_ASSOCIATION_INFO = 17,
DOT11_EVENT_INIT_QUEUE = 18,
DOT11_EVENT_EAPOLSTART = 19,
//2003-07-30 ------------
DOT11_EVENT_ACC_SET_EXPIREDTIME = 31,
DOT11_EVENT_ACC_QUERY_STATS = 32,
DOT11_EVENT_ACC_QUERY_STATS_ALL = 33,
//-----------------------
// --- 2003-08-04 ---
DOT11_EVENT_REASSOCIATION_IND = 34,
DOT11_EVENT_REASSOCIATION_RSP = 35,
//-----------------------
DOT11_EVENT_STA_QUERY_BSSID = 36,
DOT11_EVENT_STA_QUERY_SSID = 37,
// jimmylin: pass EAP packet by event queue
DOT11_EVENT_EAP_PACKET = 41,
#ifdef RTL_WPA2
DOT11_EVENT_EAPOLSTART_PREAUTH = 45,
DOT11_EVENT_EAP_PACKET_PREAUTH = 46,
#endif
#ifdef RTL_WPA2_CLIENT
DOT11_EVENT_WPA2_MULTICAST_CIPHER = 47,
#endif
DOT11_EVENT_WPA_MULTICAST_CIPHER = 48,
#ifdef AUTO_CONFIG
DOT11_EVENT_AUTOCONF_ASSOCIATION_IND = 50,
DOT11_EVENT_AUTOCONF_ASSOCIATION_CONFIRM = 51,
DOT11_EVENT_AUTOCONF_PACKET = 52,
DOT11_EVENT_AUTOCONF_LINK_IND = 53,
#endif
#ifdef WIFI_SIMPLE_CONFIG
DOT11_EVENT_WSC_SET_IE = 55,
DOT11_EVENT_WSC_PROBE_REQ_IND = 56,
DOT11_EVENT_WSC_PIN_IND = 57,
DOT11_EVENT_WSC_ASSOC_REQ_IE_IND = 58,
/* WPS2DOTX ; support Assigned MAC Addr,Assigned SSID,dymanic change STA's PIN code, 2011-0505 */
DOT11_EVENT_WSC_SET_MY_PIN = 102,
DOT11_EVENT_WSC_SPEC_SSID = 103,
DOT11_EVENT_WSC_SPEC_MAC_IND = 104,
/* WPS2DOTX ;support Assigned MAC Addr,Assigned SSID,dymanic change STA's PIN code, 2011-0505 */
#ifdef CONFIG_IWPRIV_INTF
DOT11_EVENT_WSC_START_IND = 70,
//EV_MODE, EV_STATUS, EV_MEHOD, EV_STEP, EV_OOB
DOT11_EVENT_WSC_MODE_IND = 71,
DOT11_EVENT_WSC_STATUS_IND = 72,
DOT11_EVENT_WSC_METHOD_IND = 73,
DOT11_EVENT_WSC_STEP_IND = 74,
DOT11_EVENT_WSC_OOB_IND = 75,
#endif //ifdef CONFIG_IWPRIV_INTF
#endif
/*WPS2DOTX*/
#ifdef CONFIG_IEEE80211W
DOT11_EVENT_SET_PMF = 120,
DOT11_EVENT_GET_IGTK_PN = 121,
#endif /* CONFIG_IEEE80211W */
DOT11_EVENT_MAX = 200,
} DOT11_EVENT;
/* -------------------- MESSAGE DATA STRUCTURE--------------------- */
typedef struct _DOT11_GENERAL{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char *Data;
}DOT11_GENERAL;
typedef struct _DOT11_NOEVENT{
unsigned char EventId;
unsigned char IsMoreEvent;
}DOT11_NO_EVENT;
typedef struct _DOT11_REQUEST{
unsigned char EventId;
}DOT11_REQUEST;
#ifdef RTL_WPA2_CLIENT
typedef struct _DOT11_WPA2_MULTICAST_CIPHER{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char MulticastCipher;
}DOT11_WPA2_MULTICAST_CIPHER;
#endif /* RTL_WPA2_CLIENT */
typedef struct _DOT11_WPA_MULTICAST_CIPHER{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char MulticastCipher;
}DOT11_WPA_MULTICAST_CIPHER;
typedef struct _DOT11_ASSOCIATION_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned short RSNIELen;
char RSNIE[MAXRSNIELEN];
}DOT11_ASSOCIATION_IND;
typedef struct _DOT11_ASSOCIATION_RSP{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned char Status;
}DOT11_ASSOCIATION_RSP;
// --- 2003-08-04 ---
typedef struct _DOT11_REASSOCIATION_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned short RSNIELen;
char RSNIE[MAXRSNIELEN];
char OldAPaddr[MacAddrLen];
}DOT11_REASSOCIATION_IND;
typedef struct _DOT11_REASSOCIATION_RSP{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned char Status;
char CurrAPaddr[MacAddrLen];
}DOT11_REASSOCIATIIN_RSP;
// --- ---------- ---
typedef struct _DOT11_AUTHENTICATION_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
}DOT11_AUTHENTICATION_IND;
typedef struct _DOT11_REAUTHENTICATION_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
}DOT11_REAUTHENTICATION_IND;
typedef struct _DOT11_DEAUTHENTICATION_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned long tx_packets; // == transmited packets
unsigned long rx_packets; // == received packets
unsigned long tx_bytes; // == transmited bytes
unsigned long rx_bytes; // == received bytes
unsigned long Reason;
}DOT11_DEAUTHENTICATION_IND;
typedef struct _DOT11_DISASSOCIATION_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned long tx_packets; // == transmited packets
unsigned long rx_packets; // == received packets
unsigned long tx_bytes; // == transmited bytes
unsigned long rx_bytes; // == received bytes
unsigned long Reason;
}DOT11_DISASSOCIATION_IND;
#ifdef CONFIG_IEEE80211W
typedef struct _DOT11_SET_11W_Flags {
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char macAddr[MacAddrLen];
unsigned char isPMF;
}DOT11_SET_11W_Flags;
#endif /* CONFIG_IEEE80211W */
typedef struct _DOT11_DISCONNECT_REQ{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned short Reason;
char MACAddr[MacAddrLen];
}DOT11_DISCONNECT_REQ;
typedef struct _DOT11_SET_802DOT11{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char VariableType;
unsigned char VariableValue;
char MACAddr[MacAddrLen];
}DOT11_SET_802DOT11;
typedef struct _DOT11_SET_KEY{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned long KeyIndex;
unsigned long KeyLen;
unsigned char KeyType;
unsigned char EncType;
unsigned char MACAddr[MacAddrLen];
DOT11_KEY_RSC KeyRSC;
unsigned char KeyMaterial[64];
}DOT11_SET_KEY;
typedef struct _DOT11_SETPORT{
unsigned char EventId;
unsigned char PortStatus;
unsigned char PortType;
unsigned char MACAddr[MacAddrLen];
}DOT11_SETPORT;
typedef struct _DOT11_DELETE_KEY{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned char KeyType;
}DOT11_DELETE_KEY;
typedef struct _DOT11_SET_RSNIE{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned short Flag;
unsigned short RSNIELen;
char RSNIE[MAXRSNIELEN];
}DOT11_SET_RSNIE;
typedef struct _DOT11_GKEY_TSC{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char KeyTSC[8];
}DOT11_GKEY_TSC;
#ifdef RTL_WPA_CLIENT
typedef struct _DOT11_STA_QUERY_BSSID{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned long IsValid;
char Bssid[MacAddrLen];
}DOT11_STA_QUERY_BSSID;
typedef struct _DOT11_STA_QUERY_SSID{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned long IsValid;
char ssid[32];
int ssid_len;
}DOT11_STA_QUERY_SSID;
#endif
typedef struct _DOT11_MIC_FAILURE{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
}DOT11_MIC_FAILURE;
typedef struct _DOT11_EAPOL_START{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
}DOT11_EAPOL_START;
//2003-07-30 --------------
typedef struct _DOT11_SET_EXPIREDTIME{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char MACAddr[MacAddrLen];
unsigned long ExpireTime;
}DOT11_SET_EXPIREDTIME;
typedef struct _DOT11_QUERY_STATS{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char MACAddr[MacAddrLen];
unsigned long IsSuccess;
unsigned long tx_packets; // == transmited packets
unsigned long rx_packets; // == received packets
unsigned long tx_bytes; // == transmited bytes
unsigned long rx_bytes; // == received bytes
}DOT11_QUERY_STATS;
//-------------------------
typedef struct _DOT11_EAP_PACKET{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned short packet_len;
unsigned char packet[1550];
}DOT11_EAP_PACKET;
#ifdef WIFI_SIMPLE_CONFIG
typedef struct _DOT11_WSC_PIN_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char code[256];
} DOT11_WSC_PIN_IND;
typedef struct _DOT11_WSC_ASSOC_IND{
unsigned char EventId;
unsigned char IsMoreEvent;
char MACAddr[MacAddrLen];
unsigned short AssocIELen;
char AssocIE[PROBEIELEN];
unsigned char wscIE_included;
}DOT11_WSC_ASSOC_IND;
#endif
#define DOT11_AI_REQFI_CAPABILITIES 1
#define DOT11_AI_REQFI_LISTENINTERVAL 2
#define DOT11_AI_REQFI_CURRENTAPADDRESS 4
#define DOT11_AI_RESFI_CAPABILITIES 1
#define DOT11_AI_RESFI_STATUSCODE 2
#define DOT11_AI_RESFI_ASSOCIATIONID 4
typedef struct _DOT11_ASSOCIATION_INFORMATION
{
unsigned char EventId;
unsigned char IsMoreEvent;
unsigned char SupplicantAddress[MacAddrLen];
u_long Length;
u_short AvailableRequestFixedIEs;
struct _DOT11_AI_REQFI {
u_short Capabilities;
u_short ListenInterval;
char CurrentAPAddress[MacAddrLen];
} RequestFixedIEs;
u_long RequestIELength;
u_long OffsetRequestIEs;
u_short AvailableResponseFixedIEs;
struct _DOT11_AI_RESFI {
u_short Capabilities;
u_short StatusCode;
u_short AssociationId;
} ResponseFixedIEs;
u_long ResponseIELength;
u_long OffsetResponseIEs;
} DOT11_ASSOCIATION_INFORMATION, *PDOT11_ASSOCIATION_INFORMATION;
typedef struct _DOT11_INIT_QUEUE
{
unsigned char EventId;
unsigned char IsMoreEvent;
} DOT11_INIT_QUEUE, *PDOT11_INIT_QUEUE;
//------------------------------------------------------------
// For Key mapping key definition
//------------------------------------------------------------
//#define HW_CAM_CONFIG
#ifdef HW_CAM_CONFIG
struct rtl_priv_args
{
unsigned char arg_val;
unsigned char arg_name[16];
unsigned char arg_length;
};
#define PRIV_CMD_AP_KEYMAP_OPERATION 1
#define PRIV_CMD_AP_KEYMAP_MAC_ADDRESS 2
#define PRIV_CMD_AP_KEYMAP_KEY40 3
#define PRIV_CMD_AP_KEYMAP_KEY104 4
#define PRIV_CMD_AP_KEYMAP_KEY_INDEX 5
#define PRIV_CMD_AP_KEYMAP_KEY_TYPE 6
#define PRIV_CMD_AP_KEYMAP_KEY_VALID 7
static struct rtl_priv_args priv_cmd_keymap_args[] =
{
{ PRIV_CMD_AP_KEYMAP_OPERATION, "KMOP", 4 },
{ PRIV_CMD_AP_KEYMAP_MAC_ADDRESS, "KMAR", 4 },
{ PRIV_CMD_AP_KEYMAP_KEY40, "KMKEY40", 7 },
{ PRIV_CMD_AP_KEYMAP_KEY104, "KMKEY104", 8 },
{ PRIV_CMD_AP_KEYMAP_KEY_INDEX, "KMIDX", 5 },
{ PRIV_CMD_AP_KEYMAP_KEY_TYPE, "KMTYPE", 6 },
{ PRIV_CMD_AP_KEYMAP_KEY_VALID, "KMVALID", 7 }
};
#define KEYMAP_OPERATION_GET 0
#define KEYMAP_OPERATION_SET 1
#define KEYMAP_VALID_OFF 0
#define KEYMAP_VALID_ON 1
static struct rtl_priv_args rtl_priv_kmop_args[] =
{
{ KEYMAP_OPERATION_GET, "get", 3 },
{ KEYMAP_OPERATION_SET, "set", 3 }
};
#define WEP_MODE_OFF 0
#define WEP_MODE_ON_40 1
#define WEP_MODE_ON_104 2
static struct rtl_priv_args rtl_priv_wepmode_args[] =
{
{ WEP_MODE_OFF, "off", 3 },
{ WEP_MODE_ON_40, "wep40", 5 },
{ WEP_MODE_ON_104, "wep104", 6 }
};
static struct rtl_priv_args rtl_priv_kmvalid_args[] =
{
{ KEYMAP_VALID_ON, "on", 2 },
{ KEYMAP_VALID_OFF, "off", 3 }
};
#endif
//End of HW_CAM_CONFIG
//----------------------------------------------------------
/*-------------------- Function Definition ---------------*/
//use [ifdef] to exclude the following function definition
//in compile of dlisten
#include "1x_types.h"
#include "1x_common.h"
#ifdef RTL_WPA_CLIENT
#include "1x_supp_pae.h"
#endif
#define SIOCGIWIND 0x89ff
#define SIOCKEYMAP 0x89f9
#define SIOCGIWRTLSTAINFO 0x8B30
int lib1x_control_init();
int lib1x_control_STADisconnect(Global_Params *global, u_short reason);
int lib1x_control_RemovePTK(Global_Params *global, int keytype);
int lib1x_control_QueryRSC(Global_Params * global, OCTET_STRING * gRSC);
int lib1x_control_QuerySTA(Global_Params * global);
int lib1x_control_Query_All_Sta_Info(Dot1x_Authenticator * auth);
#ifdef RTL_WPA2
/*
event_id: DOT11_EVENT_ASSOCIATION_IND or DOT11_EVENT_REASSOCIATION_IND
*/
int lib1x_control_AssociationRsp(Global_Params * global, int result, int event_id);
#else
int lib1x_control_AssociationRsp(Global_Params * global, int result);
#endif
//int lib1x_control_SetRSNIE(Global_Params * global, int role);
int lib1x_control_RSNIE(Dot1x_Authenticator * auth, u_char flag);
int lib1x_control_SetPTK(Global_Params * global);
int lib1x_control_SetGTK(Global_Params * global);
int lib1x_control_SetPORT(Global_Params * global, u_char status);
int lib1x_control_SetExpiredTime(Global_Params * global, u_long ulExpireTime);
int lib1x_control_Set802dot1x(Global_Params * global, u_char var_type, u_char var_val);
int lib1x_control_InitQueue(Dot1x_Authenticator * auth);
int lib1x_control_KeyMapping(Global_Params * global, u_char operation, u_char keytype, u_char keyvalid);
int lib1x_control_IndicateMICFail(Dot1x_Authenticator * auth, u_char *mac);
int lib1x_control_Poll(Dot1x_Authenticator * auth);
#ifdef RTL_WPA_CLIENT
int lib1x_control_STA_QUERY_BSSID(Supp_Global * pGlobal);
int lib1x_control_STA_QUERY_SSID(Supp_Global * pGlobal, unsigned char *pSSID);
int lib1x_control_STA_SetPTK(Supp_Global * pGlobal);
int lib1x_control_STA_SetPORT(Supp_Global * pGlobal, u_char status);
int lib1x_control_STA_SetGTK(Supp_Global * pGlobal, u_char * pucKey, int iKeyId);
int lib1x_control_AuthDisconnect(Dot1x_Authenticator * auth, u_char *pucMacAddr, u_short reason);
#endif

View File

@ -0,0 +1,217 @@
#ifndef LIB1X_KMSM_H
#define LIB1X_KMSM_H
#include "1x_common.h"
#define TRUE 1
#define FALSE 0
#define SWAP(a, b) { tmp = b; b = a; a = tmp;}
#define NumGroupKey 4
#define REJECT_EAPOLSTART_COUNTER 3
typedef enum {SUCCESS = 0, ERROR_NULL_PSK = -1, ERROR_TIMEOUT = -2, ERROR_MIC_FAIL = -3,
ERROR_SET_PTK = -4, ERROR_NONEEQUL_REPLAYCOUNTER = -5,
ERROR_EQUALSMALLER_REPLAYCOUNTER = -6, ERROR_NONEQUAL_NONCE = -7, ERROR_AESKEYWRAP_MIC_FAIL = -8,
ERROR_LARGER_REPLAYCOUNTER = -9, ERROR_UNMATCHED_GROUPKEY_LEN = -10,
#ifdef RTL_WPA2_CLIENT
ERROR_NONEQUAL_RSNIE = -11, ERROR_RECV_4WAY_MESSAGE2_AGAIN = -12, ERROR_PMKID_PSK = -13, ERROR_PMKID_TLS = -14, ERROR_SECOND_RSNIE = -15} KMSM_ERROR_ID;
#else
ERROR_NONEQUAL_RSNIE = -11, ERROR_RECV_4WAY_MESSAGE2_AGAIN = -12} KMSM_ERROR_ID;
#endif
#define KM_STRERROR_NULL_PSK "NUUL Pairwise Share Key"
#define KM_STRERROR_TIMEOUT "Time Out"
#define KM_STRERROR_MIC_FAIL "MIC Failure"
#define KM_STRERROR_SET_PTK "Fail to set Pairwise Transient Key"
#define KM_STRERROR_NONEEQUL_REPLAYCOUNTER "Non Equal Replay "
#define KM_STRERROR_EQUALSMALLER_REPLAYCOUNTER "Equal/Smaller Replay "
#define KM_STRERROR_NONEQUAL_NONCE "Non Equal Nonce received in 3rd Message"
#define KM_STRERROR_AESKEYWRAP_MIC_FAIL "AES_WRAP MIC Fail"
#define KM_STRERROR_LARGER_REPLAYCOUNTER "Larger Replay "
#define KM_STRERROR_UNMATCHED_GROUPKEY_LEN "Invalid Group key length received"
#define KM_STRERROR_NONEQUAL_RSNIE "Non Equal RSN Information Element received"
typedef enum { akmsm_DEAUTHENTICATE, akmsm_DISCONNECTED, akmsm_INITIALIZE, \
akmsm_AUTHENTICATION, akmsm_INITPMK, akmsm_INITPSK, \
akmsm_PTKSTART, akmsm_PTKINITNEGOTIATING, \
akmsm_PTKINITDONE, akmsm_UPDATEKEYS, akmsm_MICFAILURE,\
akmsm_SETKEYS, akmsm_SETKEYSDONE, \
// Added states that are not in IEEE 802.11i/D3.0 8.5.6.1
// but appears in state machine diagram in Figure 53(p.113)
akmsm_DISCONNECT, akmsm_AUTHENTICATION2, aksm_INITPSK, aksm_PTKINITDONE, \
akmsm_INTEGRITYFAILURE, \
// Added states
akmsm_ERRORHANDLE} AUTH_PAIRWISEKEY_STATE;
typedef enum {gkmsm_REKEYNEGOTIATING, gkmsm_REKEYESTABLISHED, gkmsm_KEYERROR} AUTH_GROUPKEY_STATE;
typedef enum {
akmsm_EVENT_NoEvent,
akmsm_EVENT_AssociationRequest, akmsm_EVENT_ReAssociationRequest,
akmsm_EVENT_AuthenticationRequest, akmsm_EVENT_ReAuthenticationRequest,
akmsm_EVENT_AuthenticationSuccess,
akmsm_EVENT_Disconnect, akmsm_EVENT_DeauthenticationRequest, akmsm_EVENT_Init, akmsm_EVENT_Disassociate,
akmsm_EVENT_IntegrityFailure, akmsm_EVENT_EAPOLKeyRecvd,
akmsm_EVENT_TimeOut}Auth_Key_Manage_Event;
struct Global_Params_tag;
typedef struct Auth_GroupKeyManage_tag
{
// The Variables.
BOOLEAN GTKAuthenticator;
int GKeyDoneStations;
BOOLEAN GTKRekey;
BOOLEAN GInitAKeys;
BOOLEAN GInitDone;
BOOLEAN GUpdateStationKeys;
//int GNoStations; //== auth->NumOfSupplicant
BOOLEAN GkeyReady;
BOOLEAN GKeyFailure; //added by Emily
OCTET_STRING GNonce;
u_char GTK[NumGroupKey][GTK_LEN];
u_char GMK[GMK_LEN];
int GN;
int GM;
#ifdef CONFIG_IEEE80211W
unsigned char IGTK[2][IGTK_LEN];
int GN_igtk, GM_igtk;
union PN48 IGTK_PN;
#endif //CONFIG_IEEE80211W
u_long GRekeyCounts;
BOOLEAN GResetCounter;
}AGKeyManage_SM;
typedef struct Auth_PairwiseKeyManage_tag
{
// The machine state
AUTH_PAIRWISEKEY_STATE state;
AUTH_GROUPKEY_STATE gstate;
// The Variables.
//802.1x related variable
BOOLEAN eapStart;
u_long SessionTimeout;
u_long SessionTimeoutCounter;
u_long SessionTimeoutEnabled;
u_long IdleTimeout;
u_long IdleTimeoutCounter;
u_long IdleTimeoutEnabled;
u_long InterimTimeout;
u_long InterimTimeoutCounter;
u_long InterimTimeoutEnabled;
//-----------Event
BOOLEAN AuthenticationRequest;
BOOLEAN ReAuthenticationRequest;
BOOLEAN DeauthenticationRequest;
BOOLEAN Disconnect;
BOOLEAN Init;
BOOLEAN Pair;
BOOLEAN RadiusKeyAvailable;
BOOLEAN EAPOLKeyReceived;
BOOLEAN EAPOLKeySend; //added by Emily
BOOLEAN TimeoutEvt;
int TimeoutCtr;
//sc_yang
int TickCnt;
BOOLEAN L2Failure;
BOOLEAN MICVerified;
BOOLEAN IntegrityFailed;
BOOLEAN PInitAKeys;
//int ; //sc_yang
OCTET_STRING ANonce;
OCTET_STRING SNonce; //added by Emily
u_char PMK[PMK_LEN];
#ifdef RTL_WPA2
u_char PMKID[PMKID_LEN];
#endif
u_char PTK[PTK_LEN];
OCTET_STRING SuppInfoElement;
OCTET_STRING AuthInfoElement;
LARGE_INTEGER CurrentReplayCounter;
LARGE_INTEGER ReplayCounterStarted; // david+1-11-2007
u_short ErrorRsn;
struct Global_Params_tag *global;
BOOLEAN IfCalcMIC;
BOOLEAN bWaitForPacket;
int IgnoreEAPOLStartCounter;
//Abocom
/*
u_long SessionTimeout;
u_long IdleTimeout;
u_long InterimTimeout;
u_long SessionTimeoutCounter;
u_long IdleTimeoutCounter;
u_long InterimTimeoutCounter;
*/
}APKeyManage_SM;
int lib1x_akmsm_SendEAPOL_proc(Global_Params * global);
int lib1x_akmsm_ProcessEAPOL_proc(Global_Params * global);
int lib1x_akmsm_trans( Global_Params * global);
void lib1x_akmsm_execute( Global_Params * global);
void lib1x_akmsm_dump(Global_Params * global );
void lib1x_skmsm_execute( Global_Params * global);
int lib1x_skmsm_ProcessEAPOL_proc(Global_Params * global);
void lib1x_akmsm_EAPOLStart_Timer_proc(Dot1x_Authenticator * auth);
void lib1x_akmsm_Account_Timer_proc(Dot1x_Authenticator * auth);
int lib1x_akmsm_Disconnect( Global_Params * global);
int MIN(u_char * ucStr1, u_char * ucStr2, u_long ulLen);
void CalcPTK(u_char *addr1, u_char *addr2, u_char *nonce1,
u_char *nonce2, u_char * keyin, int keyinlen,
u_char * keyout, int keyoutlen
#ifdef CONFIG_IEEE80211W
,int use_sha256
#endif /* CONFIG_IEEE80211W */
);
void GenNonce(u_char * nonce, u_char * szRandom);
char * KM_STRERR(int err);
void KeyDump(char *fun, u_char *buf, int siz, char *comment);
OCTET32_INTEGER * INCOctet32_INTEGER(OCTET32_INTEGER * x);
int _tmain();
#endif //LIB1X_KMSM_H

View File

@ -0,0 +1,409 @@
#ifndef LIB1X_KMSM_EAPOLKEY_H
#define LIB1X_KMSM_EAPOLKEY_H
#include <string.h>
#ifdef _RTL_WPA_WINDOWS
typedef unsigned short u_short;
typedef unsigned char u_char;
typedef unsigned long u_long;
} OCTET_STRING, *POCTET_STRING, EAPOL_KEY;
#else
#include <sys/types.h>
#include "1x_kmsm_keydef.h"
#include "1x_types.h"
#endif
//original in 1x_ether.h and 1x_eapol.h
#define ETHER_HDRLEN 14
#define LIB1X_EAPOL_HDRLEN 4
#define ETHER_ADDRLEN 6
#ifdef CONFIG_IEEE80211W
#define GMK_EXPANSION_CONST "Group key expansion"
#define GMK_EXPANSION_CONST_SIZE 19
#define RANDOM_EXPANSION_CONST "Init Counter"
#define RANDOM_EXPANSION_CONST_SIZE 12
#define IGMK_EXPANSION_CONST "IGTK key expansion"
#define IGMK_EXPANSION_CONST_SIZE 18
#endif /* CONFIG_IEEE80211W */
//size of the field in information element
/*
#define PMK_LEN 32
#define PTK_LEN 64
#define PTK_LEN_TKIP 64
#define PTK_LEN_NO_TKIP 48 //for CCMP, WRAP, WEP
#define PTK_LEN_CCMP 48
#define PTK_LEN_WRAP 48
#define PTK_LEN_WEP 48
#define PTK_LEN_EAPOLMIC 16
#define PTK_LEN_EAPOLENC 16
#define GMK_LEN 32
#define GTK_LEN 32
#define GTK_LEN_TKIP 32 //32 for TKIP and 16 for CCMP, WRAP, WEP
#define GTK_LEN_NO_TKIP 16
#define GTK_LEN_CCMP 16
#define GTK_LEN_WRAP 16
#define GTK_LEN_WEP 16
#define INFO_ELEMENT_SIZE 128
#define MAX_EAPOLMSG_LEN 512
#define MAX_EAPOLKEYMSG_LEN MAX_EAPOLMSG_LEN - (ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN)
#define EAPOLMSG_HDRLEN 95 //EAPOL-key payload length without KeyData
#define KEY_RC_LEN 8
#define KEY_NONCE_LEN 32
#define KEY_IV_LEN 16
#define KEY_RSC_LEN 8
#define KEY_ID_LEN 8
#define KEY_MIC_LEN 16
#define KEY_MATERIAL_LEN 2
#define DescTypePos 0
#define KeyInfoPos 1
#define KeyLenPos 3
#define ReplayCounterPos 5
#define KeyNoncePos 13
#define KeyIVPos 45
#define KeyRSCPos 61
#define KeyIDPos 69
#define KeyMICPos 77
#define KeyDataLenPos 93
#define KeyDataPos 95
*/
/*-----------------------------------------------------------------------------
Network and machine byte oder conversion
Macro definition
-------------------------------------------------------------------------------*/
// david --------------------------------------------------
// marked by chilong
//#ifdef AUTH_BIG_ENDIAN
// !!NOTES: chilong
// we define AUTH_BIG_ENDIAN instead of BIG_ENDIAN
// because kernel header in directory "[root_dir]/mipsel-linux/sys-include/netinet/in.h"
// has defined BIG_ENDIAN
#define long2net(l,c) (*((c) )=(unsigned char)(((l)>>24)&0xff), \
*((c)+1)=(unsigned char)(((l)>>16)&0xff), \
*((c)+2)=(unsigned char)(((l)>> 8)&0xff), \
*((c)+3)=(unsigned char)(((l) )&0xff))
#define net2long(c,l) (l =((unsigned long)(*((c) )))<<24, \
l|=((unsigned long)(*((c)+1)))<<16, \
l|=((unsigned long)(*((c)+2)))<< 8, \
l|=((unsigned long)(*((c)+3))))
#define short2net(s,c) (*((c))=(unsigned char)(((s)>> 8)&0xff), \
*((c)+1)=(unsigned char)(((s) )&0xff))
#define net2short(c,s) (s =((unsigned short)(*((c))))<< 8, \
s|=((unsigned short)(*((c)+1))))
//#else
//#define long2net(l,c) (*((unsigned long *)c) = l)
//#define net2long(c,l) (l = *((unsigned long *)c))
//#define short2net(s,c) (*((unsigned short *)c) = s)
//#define net2short(c,s) (s = *((unsigned short *)c))
//#endif
//------------------------------------------------------
//-------------------------------------------------
#define lint2net(l,c) (long2net((l).HighPart, c) , long2net((l).LowPart, c+4))
#define net2lint(c,l) (net2long(c, (l).HighPart) , net2long(c+4, (l).LowPart))
/*-----------------------------------------------------------------------------
LargeInteger
Inline Function definition
Macro definition
-------------------------------------------------------------------------------*/
#define LargeIntegerOverflow(x) ((x).field.HighPart == 0xffffffff) && \
((x).field.LowPart == 0xffffffff)
#define LargeIntegerZero(x) memset(&(x).charData, 0, 8);
/*-----------------------------------------------------------------------------
Octet16Integer
Inline Function definition
Macro definition
-------------------------------------------------------------------------------*/
#define Octet16IntegerOverflow(x) LargeIntegerOverflow((x).field.HighPart) && \
LargeIntegerOverflow((x).field.LowPart)
#define Octet16IntegerZero(x) memset(&(x).charData, 0, 16);
/*-----------------------------------------------------------------------------
EAPOLKey field process
Inline Function definition
Macro definition
-------------------------------------------------------------------------------*/
inline
OCTET_STRING SubStr(OCTET_STRING f, u_short s,u_short l);
#define SetSubStr(f,a,l) memcpy((f).Octet+(l), (a).Octet, (a).Length)
#define GetKeyInfo0(f, mask) ( ((f).Octet[KeyInfoPos + 1] & (mask)) ? 1 :0)
#define SetKeyInfo0(f,mask,b) ( (f).Octet[KeyInfoPos + 1] = ((f).Octet[KeyInfoPos + 1] & ~(mask)) | ( (b)?(mask):0x0) )
#define GetKeyInfo1(f, mask) ( ((f).Octet[KeyInfoPos] & (mask)) ? 1 :0)
#define SetKeyInfo1(f,mask,b) ( (f).Octet[KeyInfoPos] = ((f).Octet[KeyInfoPos] & ~(mask)) | ( (b)?(mask):0x0) )
// EAPOLKey
#define Message_DescType(f) ((f).Octet[DescTypePos])
#define Message_setDescType(f, type) ((f).Octet[DescTypePos] = (type))
// Key Information Filed
#define Message_KeyDescVer(f) ((f).Octet[KeyInfoPos+1] & 0x07)//(f.Octet[KeyInfoPos+1] & 0x01) | (f.Octet[KeyInfoPos+1] & 0x02) <<1 | (f.Octet[KeyInfoPos+1] & 0x04) <<2
#define Message_setKeyDescVer(f, v) ((f).Octet[KeyInfoPos+1] &= 0xf8) , (f).Octet[KeyInfoPos+1] |= ((v) & 0x07)//(f.Octet[KeyInfoPos+1] |= ((v&0x01)<<7 | (v&0x02)<<6 | (v&0x04)<<5) )
#define Message_KeyType(f) GetKeyInfo0(f,0x08)
#define Message_setKeyType(f, b) SetKeyInfo0(f,0x08,b)
#define Message_KeyIndex(f) (((f).Octet[KeyInfoPos+1] & 0x30) >> 4)//(f.Octet[KeyInfoPos+1] & 0x20) | (f.Octet[KeyInfoPos+1] & 0x10) <<1
#define Message_setKeyIndex(f, v) ((f).Octet[KeyInfoPos+1] &= 0xcf), (f).Octet[KeyInfoPos+1] |= (((v)<<4) & 0x07)//(f.Octet[KeyInfoPos+1] |= ( (v&0x01)<<5 | (v&0x02)<<4) )
#define Message_Install(f) GetKeyInfo0(f,0x40)
#define Message_setInstall(f, b) SetKeyInfo0(f,0x40,b)
#define Message_KeyAck(f) GetKeyInfo0(f,0x80)
#define Message_setKeyAck(f, b) SetKeyInfo0(f,0x80,b)
#define Message_KeyMIC(f) GetKeyInfo1(f,0x01)
#define Message_setKeyMIC(f, b) SetKeyInfo1(f,0x01,b)
#define Message_Secure(f) GetKeyInfo1(f,0x02)
#define Message_setSecure(f, b) SetKeyInfo1(f,0x02,b)
#define Message_Error(f) GetKeyInfo1(f,0x04)
#define Message_setError(f, b) SetKeyInfo1(f,0x04,b)
#define Message_Request(f) GetKeyInfo1(f,0x08)
#define Message_setRequest(f, b) SetKeyInfo1(f,0x08,b)
#define Message_Reserved(f) ((f).Octet[KeyInfoPos] & 0xf0)
#define Message_setReserved(f, v) ((f).Octet[KeyInfoPos] |= ((v)<<4&0xff))
#define Message_KeyLength(f) ((u_short)((f).Octet[KeyLenPos] <<8) + (u_short)((f).Octet[KeyLenPos+1]))
#define Message_setKeyLength(f, v) ((f).Octet[KeyLenPos] = ((v)&0xff00) >>8 , (f).Octet[KeyLenPos+1] = ((v)&0x00ff))
/* Replay Counter process function */
#define DEFAULT_KEY_REPLAY_COUNTER_LONG 0xffffffff
#define Message_DefaultReplayCounter(li) ((li.field.HighPart == DEFAULT_KEY_REPLAY_COUNTER_LONG) && (li.field.LowPart == DEFAULT_KEY_REPLAY_COUNTER_LONG) ) ?1:0
#define Message_ReplayCounter(f) SubStr(f, ReplayCounterPos, KEY_RC_LEN)
#define Message_CopyReplayCounter(f1, f2) memcpy(f1.Octet + ReplayCounterPos, f2.Octet + ReplayCounterPos, KEY_RC_LEN)
void Message_ReplayCounter_OC2LI(OCTET_STRING f, LARGE_INTEGER * li);
void ReplayCounter_OC2LI(OCTET_STRING f, LARGE_INTEGER * li);
int Message_EqualReplayCounter(LARGE_INTEGER li1, OCTET_STRING f);
int Message_SmallerEqualReplayCounter(LARGE_INTEGER li1, OCTET_STRING f);
int Message_LargerReplayCounter(LARGE_INTEGER li1, OCTET_STRING f);
void Message_setReplayCounter(OCTET_STRING f, u_long h, u_long l);
//#define SetNonce(x,y) memcpy(x.Octet, y.charData, 32);
void SetNonce(OCTET_STRING osDst, OCTET32_INTEGER oc32Counter);
#define Message_KeyNonce(f) SubStr((f),KeyNoncePos,KEY_NONCE_LEN)
#define Message_setKeyNonce(f, v) SetSubStr((f), (v), KeyNoncePos)
#define Message_EqualKeyNonce(f1, f2) (memcmp((f1).Octet + KeyNoncePos, (f2).Octet, KEY_NONCE_LEN)? 0:1)
#define Message_KeyIV(f) Substr((f), KeyIVPos, KEY_IV_LEN)
#define Message_setKeyIV(f, v) SetSubStr((f), (v), KeyIVPos)
#define Message_KeyRSC(f) Substr((f), KeyRSCPos, KEY_RSC_LEN)
#define Message_setKeyRSC(f, v) SetSubStr((f), (v), KeyRSCPos)
#define Message_KeyID(f) Substr((f), KeyIDPos, KEY_ID_LEN)
#define Message_setKeyID(f, v) SetSubStr((f), (v), KeyIDPos)
#define Message_MIC(f) Substr((f), KeyMICPos, KEY_MIC_LEN)
#define Message_setMIC(f, v) SetSubStr((f), (v), KeyMICPos)
#define Message_clearMIC(f) memset((f).Octet+KeyMICPos, 0, KEY_MIC_LEN)
#define Message_KeyDataLength(f) ((u_short)((f).Octet[KeyDataLenPos] <<8) + (u_short)((f).Octet[KeyDataLenPos+1]))
#define Message_setKeyDataLength(f, v) ((f).Octet[KeyDataLenPos] = ((v)&0xff00) >>8 , (f).Octet[KeyDataLenPos+1] = ((v)&0x00ff))
#define Message_KeyData(f, l) SubStr((f), KeyDataPos, (l))
#define Message_setKeyData(f, v) SetSubStr((f), (v), KeyDataPos);
#define Message_EqualRSNIE(f1 , f2, l) (memcmp((f1).Octet, (f2).Octet, (l)) ? 0:1)
#define Message_ReturnKeyDataLength(f) ((f).Length - (ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN + EAPOLMSG_HDRLEN))
typedef union _KeyInfo
{
u_short shortData;
u_char charData[2];
struct
{
u_short KeyDescVersion:3;
u_short KeyType:1;
u_short KeyIndex:2;
u_short Install:1;
u_short KeyAck:1;
u_short KeyMIC:1;
u_short Secure:1;
u_short Error:1;
u_short Request:1;
u_short Reserved:4;
}field;
}KeyInfo;
#define KeyInfo_KeyDescVersion(f) ( ((KeyInfo *)((f).Octet)) ->field.KeyDescVersion)
#define KeyInfo_KeyType(f) ( ((KeyInfo *)((f).Octet)) ->field.KeyType)
#define KeyInfo_KeyIndex(f) ( ((KeyInfo *)((f).Octet)) ->field.KeyIndex)
#define KeyInfo_Install(f) ( ((KeyInfo *)((f).Octet)) ->field.Install)
#define KeyInfo_KeyAck(f) ( ((KeyInfo *)((f).Octet)) ->field.KeyAck)
#define KeyInfo_KeyMic(f) ( ((KeyInfo *)((f).Octet)) ->field.KeyMic)
#define KeyInfo_Secure(f) ( ((KeyInfo *)((f).Octet)) ->field.Secure)
#define KeyInfo_Error(f) ( ((KeyInfo *)((f).Octet)) ->field.Error)
#define KeyInfo_Request(f) ( ((KeyInfo *)((f).Octet)) ->field.Request)
#define KeyInfo_Reserved(f) ( ((KeyInfo *)((f).Octet)) ->field.Reserved)
struct _LIB1X_EAPOL_KEY
{
u_char key_desc_ver;
//KeyInfo key_info;
u_char key_info[2];
u_char key_len[sizeof(u_short)];
u_char key_replay_counter[KEY_RC_LEN];
u_char key_nounce[KEY_NONCE_LEN];
u_char key_iv[KEY_IV_LEN];
u_char key_rsc[KEY_RSC_LEN];
u_char key_id[KEY_ID_LEN];
u_char key_mic[KEY_MIC_LEN];
u_char key_data_len[KEY_MATERIAL_LEN];
u_char *key_data;
};
typedef struct _LIB1X_EAPOL_KEY lib1x_eapol_key;
//---------------------------------------------------------------------
// Definition for 1x_kmsm_eapolkey.c
//---------------------------------------------------------------------
void INCLargeInteger(
LARGE_INTEGER * x);
void ReplayCounter_LI2OC(
OCTET_STRING f,
LARGE_INTEGER * li);
void EncGTK(
Global_Params * global,
u_char *kek,
int keklen,
u_char *key,
int keylen,
u_char *out,
u_short *outlen);
int CheckMIC(
OCTET_STRING EAPOLMsgRecvd,
u_char *key,
int keylen);
#ifdef RTL_WPA2
void CalcPMKID(
char* pmkid,
char* pmk,
char* aa,
char* spa
#ifdef CONFIG_IEEE80211W
,int use_sha256
#endif /* CONFIG_IEEE80211W */
);
#endif
void CalcMIC(
OCTET_STRING EAPOLMsgSend,
int algo,
u_char *key,
int keylen);
void CalcGTK(
u_char *addr,
u_char *nonce,
u_char * keyin,
int keyinlen,
u_char * keyout,
int keyoutlen
#ifdef CONFIG_IEEE80211W
,u_char * label
#endif /* CONFIG_IEEE80211W */
);
int DecGTK(
OCTET_STRING EAPOLMsgRecvd,
u_char *kek,
int keklen,
int keylen,
u_char *kout,
int kout_len);
#ifdef RTL_WPA2
void SetEAPOL_KEYIV(
OCTET_STRING ocDst,
OCTET32_INTEGER oc32Counter);
#endif
//------------------------------------------------------------------------
// Definition file for 1x_kmsm_hmac.c
//------------------------------------------------------------------------
void hmac_sha(
unsigned char* k, /* secret key */
int lk, /* length of the key in bytes */
unsigned char* d, /* data */
int ld, /* length of data in bytes */
unsigned char* out, /* output buffer, at least "t" bytes */
int t
);
void hmac_sha1(
unsigned char *text,
int text_len,
unsigned char *key,
int key_len,
unsigned char *digest);
void
hmac_md5(
unsigned char *text,
int text_len,
unsigned char *key,
int key_len,
void * digest);
//------------------------------------------------------------------------
// Definition file for 1x_kmsm_prf.c
//------------------------------------------------------------------------
void i_PRF(
unsigned char* secret,
int secret_len,
unsigned char* prefix,
int prefix_len,
unsigned char* random,
int random_len,
unsigned char* digest, // caller digest to be filled in
int digest_len // in byte
);
//------------------------------------------------------------------------
// Definition file for 1x_kmsm_aes.c
//------------------------------------------------------------------------
typedef unsigned char u08b; /* an 8 bit unsigned character type */
typedef unsigned short u16b; /* a 16 bit unsigned integer type */
typedef unsigned long u32b; /* a 32 bit unsigned integer type */
void AES_WRAP(
u08b * plain,
int plain_len,
u08b * iv,
int iv_len,
u08b * kek,
int kek_len,
u08b *cipher,
u16b *cipher_len);
void AES_UnWRAP(
u08b * cipher,
int cipher_len,
u08b * kek,
int kek_len,
u08b * plain,
int plain_len);
#endif

View File

@ -0,0 +1,51 @@
#define PMK_LEN 32
#ifdef RTL_WPA2
#define PMKID_LEN 16
#endif
#define PTK_LEN 64
#define PTK_LEN_TKIP 64
#define PTK_LEN_NO_TKIP 48 //for CCMP, WRAP, WEP
#define PTK_LEN_CCMP 48
#define PTK_LEN_WRAP 48
#define PTK_LEN_WEP 48
#define PTK_LEN_EAPOLMIC 16
#define PTK_LEN_EAPOLENC 16
#define GMK_LEN 32
#define GTK_LEN 32
#define GTK_LEN_TKIP 32 //32 for TKIP and 16 for CCMP, WRAP, WEP
#define GTK_LEN_NO_TKIP 16
#define GTK_LEN_CCMP 16
#define GTK_LEN_WRAP 16
#define GTK_LEN_WEP 16
#ifdef CONFIG_IEEE80211W
#define IGTK_LEN 16
#endif /* CONFIG_IEEE80211W */
#define INFO_ELEMENT_SIZE 128
#define MAX_EAPOLMSG_LEN 512
#define MAX_EAPOLKEYMSG_LEN MAX_EAPOLMSG_LEN - (ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN)
#define EAPOLMSG_HDRLEN 95 //EAPOL-key payload length without KeyData
#define KEY_RC_LEN 8
#define KEY_NONCE_LEN 32
#define KEY_IV_LEN 16
#define KEY_RSC_LEN 8
#define KEY_ID_LEN 8
#define KEY_MIC_LEN 16
#define KEY_MATERIAL_LEN 2
#define DescTypePos 0
#define KeyInfoPos 1
#define KeyLenPos 3
#define ReplayCounterPos 5
#define KeyNoncePos 13
#define KeyIVPos 45
#define KeyRSCPos 61
#define KeyIDPos 69
#define KeyMICPos 77
#define KeyDataLenPos 93
#define KeyDataPos 95

View File

@ -0,0 +1,35 @@
#ifndef LIB1X_KRC_SM_H
#define LIB1X_KRC_SM_H
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_krc_sm.h
// Programmer : Arunesh Mishra
// The Key Receive State Machine
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
typedef struct Krc_SM_tag
{
KRC_SM state;
BOOLEAN rxKey;
} Krc_SM;
void lib1x_krcsm_processKey();
void lib1x_krcsm_init( Krc_SM * krc_sm );
void lib1x_trans_krcsm( Global_Params * global, Krc_SM * krc_sm );
#endif

View File

@ -0,0 +1,42 @@
#ifndef LIB1x_KXSM_H
#define LIB1x_KXSM_H
#include "1x_types.h"
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_kxsm.h
// Programmer : Arunesh Mishra
//
// H file Key Transmit State Machine.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
struct Auth_Pae_tag;
struct Global_Params_tag;
typedef struct Auth_keyxmitSM_tag
{
AUTH_KEYSM state;
BOOLEAN keyAvailable;
// Constants
BOOLEAN keyTxEnabled;
} Auth_KeyxmitSM;
void lib1x_trans_kxsm( struct Auth_Pae_tag * auth_pae, struct Global_Params_tag * global, Auth_KeyxmitSM * key_sm );
void lib1x_kxsm_init( Auth_KeyxmitSM * key_sm );
void lib1x_kxsm_key_transmit( struct Auth_Pae_tag * auth_pae, struct Global_Params_tag * global, Auth_KeyxmitSM * key_sm );
void lib1x_authxmitsm_txKey( struct Auth_Pae_tag * auth_pae, int currentId);
#endif

View File

@ -0,0 +1,181 @@
#ifndef LIB1x_LIST_H
#define LIB1x_LIST_H
//----------------------------------------------------------------
// list from Linux kernel List /include/linux/list.h
//----------------------------------------------------------------
// #include <linux/prefetch.h>
static inline void prefetch(const void *x) {;}
/*
* Simple doubly linked list implementation.
*
* Some of the internal functions ("__xxx") are useful when
* manipulating whole lists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
#define INIT_LIST_HEAD(ptr) do { \
(ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static __inline__ void __list_add(struct list_head * new,
struct list_head * prev,
struct list_head * next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
/**
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static __inline__ void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
/**
* list_add_tail - add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static __inline__ void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static __inline__ void __list_del(struct list_head * prev,
struct list_head * next)
{
next->prev = prev;
prev->next = next;
}
/**
* list_del - deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty on entry does not return true after this, the entry is in an undefined state.
*/
static __inline__ void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
}
/**
* list_del_init - deletes entry from list and reinitialize it.
* @entry: the element to delete from the list.
*/
static __inline__ void list_del_init(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
INIT_LIST_HEAD(entry);
}
/**
* list_empty - tests whether a list is empty
* @head: the list to test.
*/
static __inline__ int list_empty(struct list_head *head)
{
return head->next == head;
}
/**
* list_splice - join two lists
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static __inline__ void list_splice(struct list_head *list, struct list_head *head)
{
struct list_head *first = list->next;
if (first != list) {
struct list_head *last = list->prev;
struct list_head *at = head->next;
first->prev = head;
head->next = first;
last->next = at;
at->prev = last;
}
}
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next, prefetch(pos->next); pos != (head); \
pos = pos->next, prefetch(pos->next))
/**
* list_for_each_safe - iterate over a list safe against removal of list entry
* @pos: the &struct list_head to use as a loop counter.
* @n: another &struct list_head to use as temporary storage
* @head: the head for your list.
*/
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)
/**
* list_for_each_prev - iterate over a list in reverse order
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \
pos = pos->prev, prefetch(pos->prev))
#endif /* LIB1x_LIST_H */

View File

@ -0,0 +1,182 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_nal.h
// Programmer : Arunesh Mishra
// Declarations for the Network Abstraction Layer
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#ifndef LIB1X_NAL_H
#define LIB1X_NAL_H
#include <sys/types.h>
#ifdef _ON_RTL8181_TARGET
//#include <pcap.h>
#else
//#include <pcap/pcap.h>
#endif
#include "libnet.h"
//#include "/usr/include/libnet.h"
#include "1x_types.h"
#include "1x_common.h"
#include "1x_ethernet.h"
#include "1x_auth_pae.h"
#include <sys/socket.h>
#include <features.h> /* for the glibc version number */
#if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1
#include <netpacket/packet.h>
#include <net/ethernet.h> /* the L2 protocols */
#else
#include <asm/types.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h> /* The L2 protocols */
#endif
#include <sys/ioctl.h>
#include <net/if.h>
#include <errno.h>
// The address types
#define LIB1X_NAL_MACADDR 1
#define LIB1X_NAL_IPADDR 2
// Interface types.
#define LIB1X_NAL_IT_ETHLAN 1
#define LIB1X_NAL_IT_WLAN 2
#define LIB1X_MAXDEVLEN IFNAMSIZ + 10 /* be safe */
//#define LIB1X_MAXEAPLEN 5500
#define LIB1X_MAXEAPLEN 1600 //sc_yang
// This structure defines an "address". This could
// be an IP address or a MAC address, thus doing it
// this way gives us a "generic" interface.
struct lib1x_nal_addr
{
unsigned char * addr;
int len;
int addr_type;
};
// Abstracts the notion of an interface, which could be a socket
// or an actual device
struct lib1x_nal_intdev
{
unsigned char * interface;
int type;
};
/* Generic packet struct .. passed to the handler */
struct lib1x_packet
{
u_char *data;
int caplen;
};
// We shall use the Berkeley Packet Capture Utility.
#define LIB1X_LSTNR_PROMISCMODE 1
#define LIB1X_LSTNR_SNAPLEN 2500 // I guess we need the entire packet.
#define LIB1X_LSTNR_RDTIMEOUT 1000 // Just using what the tcpdump guys used !
#define LIB1X_IT_PKTSOCK 1
#define LIB1X_IT_UDPSOCK 2
#define LIB1X_IT_CTLSOCK 3
#define LIB1X_IT_UDPSOCK_AUTH 1
#define LIB1X_IT_UDPSOCK_ACCT 2
#if 0 //sc_yang
void lib1x_nal_pcappkt_handler( u_char * lib1x_data, const struct pcap_pkthdr * packet_header, const u_char * the_packet );
struct lib1x_nal_intfdesc;
typedef void lib1x_nal_genpkt_handler( Global_Params * , struct lib1x_nal_intfdesc * , struct lib1x_packet * );
#endif
// Interface descriptor
struct lib1x_nal_intfdesc
{
//1. The listener datastructures
#if 0 //sc_yang
pcap_t * pcap_desc;
u_char p_errbuf[PCAP_ERRBUF_SIZE + 1];
#endif
BOOLEAN promisc_mode;
int snaplen;
int read_timeout;
int pf_sock; // socket : PF_PACKET since libpcap needs to get discarded
// struct lib1x_nal_intdev * device;
u_char device[ LIB1X_MAXDEVLEN + 1];
#if 0
lib1x_nal_genpkt_handler * packet_handler; /* not using currently, it is dynamic */
#endif
struct sockaddr_ll sock_device;
u_char * packet_buffer;
struct lib1x_packet packet;
//2. The Xmitter datastructures
struct libnet_link_int * libnet_desc;
u_char l_errbuf[LIBNET_ERRBUF_SIZE];
//3. general ..
u_char ouraddr[ ETHER_ADDRLEN ];
u_char inttype; /* interface type, packet socket or udp socket */
/*4. If we are having a UDP authentication socket */
int udpsock;
#ifdef CONFIG_RTL8196C_AP_HCM
int inband_channel;
unsigned int if_index;
unsigned char host_mac[13];
#endif
struct sockaddr_in *radsvraddr;
/*5. If we are having a UDP accouting socket */
int acctsock;
struct sockaddr_in *acctsvraddr;
};
struct lib1x_nal_intfdesc * lib1x_nal_initialize( u_char * intdev , u_char * ouraddr, u_char inttype);
BOOLEAN lib1x_nal_send( struct lib1x_nal_intfdesc * desc, char * packet , int size);
// david
//void lib1x_nal_receivepoll( Dot1x_Authenticator * auth, struct lib1x_nal_intfdesc * desc , lib1x_nal_genpkt_handler * pkt_handler, u_char * info);
//void lib1x_nal_receivefifo(Dot1x_Authenticator * auth);
#if 0
int lib1x_nal_receivepoll( Dot1x_Authenticator * auth, struct lib1x_nal_intfdesc * desc , lib1x_nal_genpkt_handler * pkt_handler, u_char * info);
int lib1x_nal_receivefifo(Dot1x_Authenticator * auth);
#endif
int lib1x_nal_receive(Dot1x_Authenticator * auth);
void lib1x_nal_close( struct lib1x_nal_intfdesc * desc );
//pcap_t * lib1x_nal_setup_pcap( struct lib1x_nal_intfdesc * nd );
int lib1x_nal_connect( struct lib1x_nal_intfdesc * desc, /*u_short udp_ourport,*/ struct sockaddr_in *svraddr , int addrlen, int udpsock_type);
#endif

View File

@ -0,0 +1,21 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : common.h
// Programmer : Arunesh Mishra
//
// Contains all common declarations and definitions.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
//--------------------------------------------------
#ifndef LIB1X_PARSER_H
#define LIB1X_PARSER_H
void lib1x_parsePrint( FILE * fdesc, Auth_Pae * auth_pae, struct lib1x_packet * spkt )
#endif

View File

@ -0,0 +1,58 @@
//#ifndef 1X_PKT_LISTENER_H
//#define 1X_PKT_LISTENER_H
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_pkt_listener.h
// Programmer : Arunesh Mishra
//
// Contains code for packet listening.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
// We shall use the Berkeley Packet Capture Utility.
#include <sys/types.h>
#include <pcap.h>
#include "1x_types.h"
#include "1x_common.h"
#define LIB1X_LSTNR_PROMISCMODE 1
#define LIB1X_LSTNR_SNAPLEN 1500 // I guess we need the entire packet.
#define LIB1X_LSTNR_RDTIMEOUT 1000 // Just using what the tcpdump guys used !
typedef struct PKT_LSTNR_tag
{
pcap_t * pkt_desc;
u_char error_buf[PCAP_ERRBUF_SIZE + 1];
BOOLEAN promisc_mode;
int snaplen;
int read_timeout;
char *device;
pcap_handler packet_handler;
Global_Params * global;
} PKT_LSTNR;
void lib1x_pktlst_packet_handler( u_char * lib1x_data , const struct pcap_pkthdr * packet_header,
const u_char * the_packet);
PKT_LSTNR * lib1x_pktlst_init( char * device , Global_Params * global );
void lib1x_pktlst_process( PKT_LSTNR * listener );
//#endif

View File

@ -0,0 +1,33 @@
#ifndef 1X_PKT_XMIT_H
#define 1X_PKT_XMIT_H
#include <libnet.h>
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_pkt_xmit.h
// Programmer : Arunesh Mishra
// Structure for libnet.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
typedef struct PKT_XMIT_tag
{
struct libnet_link_int * network;
u_char *device;
u_char errbuf[LIBNET_ERRBUF_SIZE];
Global_Params * global;
} PKT_XMIT;
#endif

View File

@ -0,0 +1,50 @@
#ifndef LIB1x_PTSM_H
#define LIB1x_PTSM_H
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_ptsm.h
// Programmer : Arunesh Mishra
//
// Port timers state machine H file.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
struct lib1x_ptsm
{
int authWhile;
// authwhile is a timer used by supp to wait for a resp from
// authenticator before timing out.
int aWhile;
// timer used by backend auth state machine.
int heldWhile;
//timer for supp - during which it does not attempt to authenticate
int quietWhile;
// timer used by auth sm during which it does not acquire a supp.
int reAuthWhen;
// reauthentication timer state machine = reAuthPeriod.
int startWhen;
// timer for supp - EAPOL start message
int txWhen;
// used by auth sm
};
void lib1x_ptsm_alarm( int signum );
void lib1x_ptsm_initialize( Global_Params * global, struct lib1x_ptsm * ptsm );
void lib1x_ptsm_timer(Dot1x_Authenticator * auth);
typedef struct lib1x_ptsm PT_SM;
#endif

View File

@ -0,0 +1,310 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_radius.h
// Programmer : Arunesh Mishra
//
// BASIC RADIUS PROXY
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//
//--------------------------------------------------
#ifndef LIB1X_RADIUS_H
#define LIB1X_RADIUS_H
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "1x_nal.h"
#define LIB1X_ETH_IP 0x0800 /* Internet Protocol packet */
#define LIB1X_RAD_ACCREQ 1 // Access Request
#define LIB1X_RAD_ACCACT 2 // Access Accept
#define LIB1X_RAD_ACCREJ 3 // Access Reject
#define LIB1X_RAD_ACCCHL 11 // Access Challenge
#define LIB1X_RAD_ACCTREQ 4 // Account Request
#define LIB1X_RAD_ACCTRSP 5 // Account Respond
#if 0 // move define to makefile
#define LIB1X_LIL_ENDIAN
#endif
#define LIB1X_IPHDRLEN 20 // Assume for now TODO
#define LIB1X_UDPHDRLEN 8
#define LIB1X_RADHDRLEN 20 // RADIUS Header length
#define LIB1X_RADATTRLEN 2 // length of attr field without data part
/* RADIUS attribute definitions. Also from RFC 2138 */
#define LIB1X_RAD_USER_NAME 1
#define LIB1X_RAD_PASSWORD 2
#define LIB1X_RAD_NAS_IP_ADDRESS 4
#define LIB1X_RAD_NAS_PORT 5
#define LIB1X_RAD_SERVICE_TYPE 6
#define LIB1X_RAD_FRAMED_MTU 12
#define LIB1X_RAD_REPLY_MESSAGE 18
#define LIB1X_RAD_STATE 24
#define LIB1X_RAD_VENDOR_SPECIFIC 26
#define LIB1X_RAD_SESSION_TIMEOUT 27
#define LIB1X_RAD_IDLE_TIMEOUT 28
#define LIB1X_RAD_CALLED_STID 30
#define LIB1X_RAD_CALLING_STID 31
#define LIB1X_RAD_NAS_IDENTIFIER 32
#define LIB1X_RAD_NAS_PORTTYPE 61
#define LIB1X_RAD_CONNECTINFO 77
#define LIB1X_RAD_EAP_MESSAGE 79 // eap message .. from RFC 2869
#define LIB1X_RAD_MESS_AUTH 80 // Message Authenticator
#define LIB1X_RAD_NAS_PORT_ID 83
//Accounting related
#define LIB1X_RAD_ACCT_STATUS_TYPE 40
#define LIB1X_RAD_ACCT_DELAY_TIME 41
#define LIB1X_RAD_ACCT_INPUT_OCTETS 42
#define LIB1X_RAD_ACCT_OUTPUT_OCTETS 43
#define LIB1X_RAD_ACCT_SESSION_ID 44
#define LIB1X_RAD_ACCT_AUTHENTIC 45
#define LIB1X_RAD_ACCT_SESSION_TIME 46
#define LIB1X_RAD_ACCT_INPUT_PACKETS 47
#define LIB1X_RAD_ACCT_OUTPUT_PACKETS 48
#define LIB1X_RAD_ACCT_TERMINATE_CAUSE 49
#define LIB1X_RAD_ACCT_INPUT_GIGAWORDS 52
#define LIB1X_RAD_ACCT_OUTPUT_GIGAWORDS 53
#define LIB1X_RAD_ACCT_INTERIM_TIMEOUT 85
/* Radius vendor specific definition from RFC 2548
Microsoft Vendor-specific RADIUS attributes */
#define LIB1X_RADVENDOR_MS 311 // 0x00000137
#define LIB1X_RADVENDOR_MS_MPPE_SEND_KEY 16
#define LIB1X_RADVENDOR_MS_MPPE_RECV_KEY 17
#define LIB1X_RADVENDOR_MS_MPPE_ENCRYPTION_POLICY 7
#define LIB1X_RADVENDOR_MS_MPPE_ENCRYPTION_TYPES 8
/* Accounting related Attribute */
#define LIB1X_RADACCT_STATUS_TYPE_START 1
#define LIB1X_RADACCT_STATUS_TYPE_STOP 2
#define LIB1X_RADACCT_STATUS_TYPE_INTERIM_UPDATE 3
#define LIB1X_RADACCT_STATUS_TYPE_ACCOUNTING_ON 7
#define LIB1X_RADACCT_STATUS_TYPE_ACCOUNTING_OFF 8
#define LIB1X_RADACCT_AUTHENTIC_RADIUS 1
#define LIB1X_RADACCT_AUTHENTIC_LOCAL 2
#define LIB1X_RADACCT_AUTHENTIC_REMOTE 3
#define LIB1X_RADACCT_TERMINATE_CAUSE_USER_REQUEST 1
#define LIB1X_RADACCT_TERMINATE_CAUSE_LOST_CARRIER 2
#define LIB1X_RADACCT_TERMINATE_CAUSE_LOST_SERVICE 3
#define LIB1X_RADACCT_TERMINATE_CAUSE_IDLE_TIMEOUT 4
#define LIB1X_RADACCT_TERMINATE_CAUSE_SESSION_TIMEOUT 5
#define LIB1X_RADACCT_TERMINATE_CAUSE_ADMIN_RESET 6
#define LIB1X_RADACCT_TERMINATE_CAUSE_ADMIN_REBOOT 7
#define LIB1X_RADACCT_TERMINATE_CAUSE_PORT_ERROR 8
#define LIB1X_RADACCT_TERMINATE_CAUSE_NAS_ERROR 9
#define LIB1X_RADACCT_TERMINATE_CAUSE_NAS_REQUEST 10
#define LIB1X_RADACCT_TERMINATE_CAUSE_NAS_REBOOT 11
#define LIB1X_RADACCT_TERMINATE_CAUSE_PORT_INNEEDED 12
#define LIB1X_RADACCT_TERMINATE_CAUSE_PORT_PREEMPTED 13
#define LIB1X_RADACCT_TERMINATE_CAUSE_PORT_SUSPENDED 14
#define LIB1X_RADACCT_TERMINATE_CAUSE_SERVICE_UNAVAILABLE 15
#define LIB1X_RADACCT_TERMINATE_CAUSE_CALLBACK 16
#define LIB1X_RADACCT_TERMINATE_CAUSE_USER_ERROR 17
#define LIB1X_RADACCT_TERMINATE_CAUSE_HOST_REQUEST 18
#define LIB1X_RADACCT_ACTION_ACCOUNT_START 1
#define LIB1X_RADACCT_ACTION_ACCOUNT_STOP 2
#define LIB1X_RADACCT_ACTION_ACCOUNT_ON 3
#define LIB1X_RADACCT_ACTION_INTERIM_UPDATE 4
#define LIB1X_RADACCT_ACTION_TERMINATE_CAUSE 5
#define LIB1X_RAD_ACCT_STATUS_ON 1
#define LIB1X_RAD_AUTH_MAC_AUTHENTICATION 2
#define LIB1X_IPPROTO_UDP 17
#define LIB1X_80211_NAS_PORTTYPE 19 /* port type for 802.11 */
#define LIB1X_RADACCT_ACCT_ON_USER_NAME "ACCT_ON"
#define LIB1X_RAD_SERVICE_TYPE_FRAMED 2
#pragma pack(1)
#define LIB1X_CKSUM_CARRY(x) \
(x = (x >> 16) + (x & 0xffff), (~(x + (x >> 16)) & 0xffff))
#define LIB1X_INC_RAD_IDENTIFIER(x) ((x==255)?x=0:x++)
//Abocom
//#define LIB1X_DEAFULT_SESSION_TIMEOUT 0x1
//#define LIB1X_DEFAULT_IDLE_TIMEOUT 0x2
//#define LIB1X_DEFAULT_INTERIM_TIMEOUT 0x3
#define LIB1X_DEAFULT_SESSION_TIMEOUT 0xffffffff
#define LIB1X_DEFAULT_IDLE_TIMEOUT 0xffffffff
#define LIB1X_DEFAULT_INTERIM_TIMEOUT 0xffffffff
struct lib1x_radiushdr
{
u_char code;
u_char identifier;
u_short length;
u_char authenticator_str[16];
};
struct lib1x_radiusattr
{
u_char type;
u_char length; // is the lengh of entire attribute including the type and length fields
};
struct lib1x_radius_vendorattr
{
u_char type;
u_char length;
u_char * string;
};
struct lib1x_udphdr
{
u_short sport; /* soure port */
u_short dport; /* destination port */
u_short len; /* length */
u_short sum; /* checksum */
};
struct lib1x_radiuspkt /* this struct is used for parsing only */
{
u_char s_ethaddr[6];
u_char d_ethaddr[6];
struct in_addr ip_src, ip_dst; /* source and dest address */
u_short dst_port, src_port;
struct lib1x_radiushdr *rhdr; // pointer to the radius start in the packet
};
struct lib1x_radius_const /* this struct is used for cosntructing packets */
{
u_char * pkt;
struct lib1x_radiushdr * rhdr;
u_short pktlen; /* length of the complete packet */
u_char * ptr_messauth;
int * nas_porttype;
};
#if 0 // move define to makefile
#ifdef _ON_RTL8181_TARGET
#undef LIB1X_LIL_ENDIAN
#endif
#endif
struct lib1x_iphdr
{
#ifdef LIB1X_LIL_ENDIAN
u_char ip_hl:4, /* header length */
ip_v:4; /* version */
#endif
#ifdef LIB1X_BIG_ENDIAN
u_char ip_v:4, /* version */
ip_hl:4; /* header length */
#endif
u_char ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off;
#ifndef IP_RF
#define IP_RF 0x8000 /* reserved fragment flag */
#endif
#ifndef IP_DF
#define IP_DF 0x4000 /* dont fragment flag */
#endif
#ifndef IP_MF
#define IP_MF 0x2000 /* more fragments flag */
#endif
#ifndef IP_OFFMASK
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
#endif
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src, ip_dst; /* source and dest address */
};
#define LIB1X_FRMSUPP_RESPID 1
#define LIB1X_FRMSUPP_RESPOTH 2
#define LIB1X_RAD_SHARED 64
#define MAX_NAS_ID_LEN 50 //sc_yang
struct radius_info /* one struct for radius related bookkeeping */
{
u_char req_authenticator[16];
u_char mess_authenticator[16];
u_char identifier; /* the identifier field in a radius packet */
/* needs to be changed for every unique packet */
u_char * global_identifier;
u_char eap_message_frmsupp[ LIB1X_MAXEAPLEN ]; /* defined in 1x_nal.h */
u_char eap_messtype_frmsupp; /* we store the received eap message from supp*/
int eap_messlen_frmsupp;
u_char eap_message_frmserver[ LIB1X_MAXEAPLEN ]; /* defined in 1x_nal.h */
u_char eap_messtype_frmserver; /* store the eap mess from server */
int eap_messlen_frmserver;
//u_char rad_shared[LIB1X_RAD_SHARED]; /* NAS and RADIUS */
u_char username[80]; /* the username attribute is what the supplicant sends in */
/* response to eap request/identity packet */
u_char username_len; /* length of the username attribute */
u_char nas_identifier[MAX_NAS_ID_LEN]; /* string identifying the Authenticator TODO .. this is so static now ! */
u_char connectinfo[50]; /* = "CONNECT 11 Mbps 802.11b" */
u_char radius_state[ LIB1X_MAXEAPLEN ]; /* State attribute .. needs to be copied back */
BOOLEAN rad_stateavailable; /* available or not */
u_short rad_statelength; /* length of the State attribute .. type 24 */
};
struct Auth_Pae_tag;
void lib1x_create_reqauth( struct Auth_Pae_tag * auth_pae );
u_short lib1x_ip_check(u_short *addr, int len);
void lib1x_do_checksum_udp(u_char *buf, int len);
void lib1x_do_checksum_ip(u_char *buf, int len);
int lib1x_in_cksum(u_short *addr, int len);
void lib1x_radconst_finalize( struct lib1x_radius_const * rconst );
void lib1x_create_messauth( struct Auth_Pae_tag * auth_pae, struct lib1x_radius_const * rconst, u_char * messauth);
void lib1x_radconst_addattr( struct lib1x_radius_const * rconst, u_char attrtype, u_char attrlen, u_char * attrdata );
void lib1x_rad_eapresp_svr( struct Auth_Pae_tag * auth_pae, struct lib1x_packet * srcpkt, int msgtype);
void lib1x_rad_eapresp_supp( struct Auth_Pae_tag * auth_pae, struct lib1x_packet * pkt);
struct lib1x_radius_const * lib1x_radconst_create( struct Auth_Pae_tag * auth_pae, u_char * pkt , u_char rcode, u_char rid, int udp_type);
int lib1x_rad_vendor_attr(Global_Params * global, u_char * rattr_ptr,int length
);
void lib1x_hmac_md5(unsigned char* text, int text_len, unsigned char* key,int key_len, caddr_t digest);
void lib1x_radconst_addEAPMessAttr( struct lib1x_radius_const * rconst, int attrlen, u_char * attrdata );
void lib1x_radconst_calradlength( struct lib1x_radius_const * rconst );
//Accounting
void lib1x_rad_session_timeout(Global_Params * global, u_char * rattr_ptr, int length);
void lib1x_rad_idle_timeout(Global_Params * global, u_char * rattr_ptr, int length);
void lib1x_rad_interim_timeout(Global_Params * global, u_char * rattr_ptr, int length);
void lib1x_rad_special_type( Auth_Pae * auth_pae, u_long ulRequestType);
void lib1x_create_reqauth_acct(Auth_Pae * auth_pae, struct lib1x_radius_const * rconst);
//MAC Authentication
int lib1x_radpassword_create( Auth_Pae * auth_pae, u_char* pucPassword, u_long ulPasswordLength);
//sc_yang
#pragma pack()
#endif

View File

@ -0,0 +1,36 @@
#ifndef LIB1x_REAUTH_SM_H
#define LIB1x_REAUTH_SM_H
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_reauth_sm.h
// Programmer : Arunesh Mishra
// Reauthentication Timer State Machine.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
#include "1x_common.h"
#define LIB1X_RSM_REAUTHPERIOD 3600 //seconds
typedef struct Reauth_SM_tag
{
REAUTH_SM_STATE state;
// These are just constants as far as the ReauthSM goes.
int reAuthPeriod;
int reAuthEnabled;
} Reauth_SM;
void lib1x_reauthsm_init( Reauth_SM * reauth_sm , int reAuthTO );
void lib1x_trans_reauthsm( Global_Params * global , Reauth_SM * reauth_sm );
#endif

View File

@ -0,0 +1,222 @@
#ifndef LIB1X_SUPP_PAE_H
#define LIB1X_SUPP_PAE_H
#include "1x_common.h"
//#include "1x_nal.h"
#include "1x_types.h"
#include "1x_kmsm.h"
#include "1x_auth_pae.h"
#define LIB1X_SUPP_AUTHPERIOD 30
#define LIB1X_SUPP_HELDPERIOD 60
#define LIB1X_SUPP_STARTPERIOD 30
#define LIB1X_SUPP_MAXSTART 3
typedef enum {
skmsm_INITIALIZE,
skmsm_DISCONNECTED,
skmsm_AUTHENTICATION,
skmsm_STAKEYSTART,
skmsm_KEYUPDATE,
} SUPP_KMSM_STATE;
typedef enum {
skmsm_EVENT_AuthenticationRequest,
skmsm_EVENT_IntegrityFailure,
skmsm_EVENT_Updatekeys,
skmsm_EVENT_EAPOLKeyRecvd,
skmsm_EVENT_AuthenticationFailed,
skmsm_EVENT_DeauthenticationRequest,
skmsm_EVENT_Init,
} SUPP_KEY_MANAGE_EVENT;
struct Supp_Global_tag;
struct Supp_Kmsm_tag;
typedef struct Supp_Pae_Params_tag
{
SUPP_KMSM_STATE skmsm_state;
struct Supp_Global_tag *global;
u_char * sendBuffer;
int sendbuflen;
u_char auth_addr[ETHER_ADDRLEN];
} Supp_Pae_Params;
typedef struct Supp_Global_tag
{
// Pointer to Global Variable
Dot1x_Authenticator *auth;
struct TxRx_Params_tag * TxRx;
// Pointer to State machine
Supp_Pae_Params *supp_pae;
struct Supp_Kmsm_tag *supp_kmsm;
// Processing EAPOL Packet
OCTET_STRING EAPOLMsgRecvd; //The Overall 802.1x message
OCTET_STRING EAPOLMsgSend; //The Overall 802.1x message
OCTET_STRING EapolKeyMsgRecvd; //The start point of eapol-key payload
OCTET_STRING EapolKeyMsgSend;
//Timer related variable
u_long ConstTimerCount;
// Key handshake related
u_char DescriptorType;
u_char KeyDescriptorVer;
int AuthKeyMethod;
//RSNIE related variable
struct _DOT11_RSN_SUPPLICANT_VARIABLE RSNVariable;
} Supp_Global;
typedef struct _Dot1x_Client
{
Dot1x_Authenticator *auth;
Supp_Global *global;
Supp_Pae_Params *supp_pae;
}Dot1x_Client;
typedef struct Supp_Kmsm_tag{
LARGE_INTEGER CurrentReplayCounter;
OCTET_STRING ANonce;
OCTET_STRING SNonce;
u_char PMK[PMK_LEN];
#ifdef RTL_WPA2_CLIENT
u_char PMKID[PMKID_LEN];
#endif
u_char PTK[PTK_LEN];
u_char GTK[NumGroupKey][GTK_LEN];
#ifdef RTL_WPA2_CLIENT
u_char GTK_KEYID;
#endif
OCTET32_INTEGER Counter;
BOOLEAN bIsSetKey;
#ifdef RTL_WPA2_CLIENT
BOOLEAN bIsSetGTK;
#endif
BOOLEAN bAuthProgressing;
//Retry Mechanism
//u_long TimeCtr;
//u_long ConstTimeCtrPeriod;
u_long TimeoutCtr;
u_long PairwiseUpdateCount;
BOOLEAN bWaitForPacket;
// Key handshake related
OCTET_STRING SuppInfoElement;
OCTET_STRING AuthInfoElement;
// jimmylin 20050824
BOOLEAN bIsHndshkDone;
} Supp_Kmsm;
Supp_Global * lib1x_init_supp(
Dot1x_Authenticator * pAuth,
Dot1x_Client *pClient);
void lib1x_supp_timer_proc(
Dot1x_Client *pClient);
void lib1x_reset_supp(
Supp_Global * pGlobal);
void lib1x_do_supplicant(
Dot1x_Authenticator * pAuth,
Supp_Global * pGlobal);
void lib1x_suppsm_capture_auth(
Supp_Global * pGlobal,
lib1x_nal_intfdesc_tag * nal,
lib1x_packet_tag * spkt);
void lib1x_suppsm_capture_control(
Supp_Global * pGlobal,
lib1x_nal_intfdesc_tag * nal,
lib1x_packet_tag * spkt );
int lib1x_skmsm_EAPOLKeyRecvd(
Supp_Global * pGlobal);
void lib1x_skmsm_EAPOLKeySend(
Supp_Global * pGlobal);
void lib1x_supp_timer_proc(
Dot1x_Client *pClient);
/*
typedef struct Supp_PairwiseKeyManage_tag
{
// The machine state
SUPP_KEYSTATE state;
// The Variables.
BOOLEAN AuthenticationRequest;
BOOLEAN ReAuthenticationRequest;
BOOLEAN DeauthenticationRequest;
BOOLEAN RadiusKeyAvailable;
BOOLEAN EAPOLKeyReceived;
BOOLEAN EAPOLKeySend; //added by Emily
BOOLEAN TimeoutEvt;
int TimeoutCtr;
BOOLEAN L2Failure;
BOOLEAN MICVerified;
BOOLEAN IntegrityFailed;
BOOLEAN PInitAKeys;
OCTET_STRING ANonce;
OCTET_STRING SNonce; //added by Emily
OCTET_STRING GNonce; //added by Emily
u_char PMK[PMK_LEN];
u_char PTK[PTK_LEN];
OCTET_STRING SuppInfoElement;
LARGE_INTEGER CurrentReplayCounter;
u_char ErrorNo;
struct Global_Params_tag *global;
u_char GTK[NumGroupKey][GMK_LEN];
int GN;
int GM;
int ErroKeyType;
OCTET32_INTEGER Counter;
// Added variables that are not in IEEE 802.11i/D3.0 8.5.6.2
// but appears in state machine diagram in Figure 53(p.113)
BOOLEAN Disconnect;
BOOLEAN Init;
BOOLEAN Pair;
// The constants
}SPKeyManage_SM;
*/
#endif

View File

@ -0,0 +1,125 @@
#ifndef LIB1x_TYPES_H
#define LIB1x_TYPES_H
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : common.h
// Programmer : Arunesh Mishra
//
// Contains all declarations of all common types.
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#ifdef _RTL_WPA_WINDOWS
typedef unsigned char u_char;
typedef unsinged short u_short;
typedef unsinged long u_long;
#else
#include <sys/types.h>
#endif
typedef enum { apsm_Initialize, apsm_Disconnected, apsm_Connecting, apsm_Authenticating, apsm_Authenticated, apsm_Aborting,
apsm_Held, apsm_Force_Auth, apsm_Force_Unauth } AUTH_PAE_STATE;
typedef enum { kxsm_No_Key_Transmit, kxsm_Key_Transmit } AUTH_KEYSM;
typedef enum { pmt_ForceUnauthorized, pmt_ForceAuthorized, pmt_Auto } PORT_MODE_TYPE;
typedef enum { pst_Unauthorized, pst_Authorized } PORT_STATUS_TYPE;
typedef enum { basm_Request, basm_Response, basm_Success, basm_Fail, basm_Timeout, basm_Idle, basm_Initialize } BAUTH_SM_STATE;
typedef enum { cdsm_Force_Both, cdsm_In_Or_Both } CTRL_SM_STATE;
typedef enum { dir_Both, dir_In } DIRECTION;
typedef enum { spsm_Logoff, spsm_Disconnected, spsm_Held, spsm_Authenticated, spsm_Connecting, spsm_Acquired, spsm_Authenticating } SUPP_PAE_STATE;
typedef enum { resm_Initialize, resm_Reauthenticate } REAUTH_SM_STATE;
typedef enum { krcsm_No_Key_Receive, krcsm_Key_Receive } KRC_SM;
// david
//typedef enum { role_Authenticator, role_Supplicant } ROLE;
typedef enum { role_Authenticator, role_Supplicant_infra, role_Supplicant_adhoc, role_wds } ROLE;
typedef enum { acctsm_Acct_No_Action, acctsm_Acct_Start, acctsm_Acct_Stop, acctsm_Acct_On, acctsm_Interim_On, acctsm_Terminate_Cause } ACCT_SM;
typedef enum { acctsm_Start, acctsm_Stop } ACCT_SM_STATE;
typedef enum { akmsm_status_NotInDriverTable, akmsm_status_Idle , akmsm_status_NotIdle } AKM_SM_STATUS;
#ifdef CONFIG_IEEE80211W
enum mfp_options {
NO_MGMT_FRAME_PROTECTION = 0,
MGMT_FRAME_PROTECTION_OPTIONAL = 1,
MGMT_FRAME_PROTECTION_REQUIRED = 2
};
#endif /* CONFIG_IEEE80211W */
typedef int BOOLEAN;
#define FALSE 0
#define TRUE 1
//Added to support WPA
#ifdef CONFIG_IEEE80211W
typedef enum { key_desc_ver1 = 1, key_desc_ver2 = 2, key_desc_ver3 = 3 } KeyDescVer;
#else
typedef enum { key_desc_ver1 = 1, key_desc_ver2 = 2 } KeyDescVer;
#endif /* CONFIG_IEEE80211W */
#ifdef RTL_WPA2
typedef enum { desc_type_WPA2 = 2, desc_type_RSN = 254 } DescTypeRSN;
#else
typedef enum { desc_type_RSN = 254 } DescTypeRSN;
#endif
typedef enum { type_Group = 0, type_Pairwise = 1 } KeyType;
//
typedef struct _OCTET_STRING
{
#ifdef RTL_WPA2
u_char * Octet;
#else
char * Octet;
#endif
int Length;
}OCTET_STRING;
typedef union _LARGE_INTEGER {
u_char charData[8];
struct{
u_long HighPart;
u_long LowPart;
}field;
} LARGE_INTEGER, *PLARGE_INTEGER;
typedef union _OCTET16_INTEGER {
u_char charData[16];
struct{
LARGE_INTEGER HighPart;
LARGE_INTEGER LowPart;
}field;
} OCTET16_INTEGER;
typedef union _OCTET32_INTEGER {
u_char charData[32];
struct{
OCTET16_INTEGER HighPart;
OCTET16_INTEGER LowPart;
}field;
}OCTET32_INTEGER;
#endif

View File

@ -0,0 +1,264 @@
/*-
* Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* This code is derived from the Stanford/CMU enet packet filter,
* (net/enet.c) distributed as part of 4.3BSD, and code contributed
* to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
* Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. 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 REGENTS 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 REGENTS 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.
*
* @(#)bpf.h 7.1 (Berkeley) 5/7/91
*
* @(#) $Header: /cvs/AP/rtl865x/AP/auth/include/bpf.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $ (LBL)
*/
#ifndef BPF_MAJOR_VERSION
/* BSD style release date */
#define BPF_RELEASE 199606
typedef int bpf_int32;
typedef u_int bpf_u_int32;
/*
* Alignment macros. BPF_WORDALIGN rounds up to the next
* even multiple of BPF_ALIGNMENT.
*/
#define BPF_ALIGNMENT sizeof(bpf_int32)
#define BPF_WORDALIGN(x) (((x)+(BPF_ALIGNMENT-1))&~(BPF_ALIGNMENT-1))
#define BPF_MAXINSNS 512
#define BPF_MAXBUFSIZE 0x8000
#define BPF_MINBUFSIZE 32
/*
* Structure for BIOCSETF.
*/
struct bpf_program {
u_int bf_len;
struct bpf_insn *bf_insns;
};
/*
* Struct returned by BIOCGSTATS.
*/
struct bpf_stat {
u_int bs_recv; /* number of packets received */
u_int bs_drop; /* number of packets dropped */
};
/*
* Struct return by BIOCVERSION. This represents the version number of
* the filter language described by the instruction encodings below.
* bpf understands a program iff kernel_major == filter_major &&
* kernel_minor >= filter_minor, that is, if the value returned by the
* running kernel has the same major number and a minor number equal
* equal to or less than the filter being downloaded. Otherwise, the
* results are undefined, meaning an error may be returned or packets
* may be accepted haphazardly.
* It has nothing to do with the source code version.
*/
struct bpf_version {
u_short bv_major;
u_short bv_minor;
};
/* Current version number of filter architecture. */
#define BPF_MAJOR_VERSION 1
#define BPF_MINOR_VERSION 1
/*
* BPF ioctls
*
* The first set is for compatibility with Sun's pcc style
* header files. If your using gcc, we assume that you
* have run fixincludes so the latter set should work.
*/
#if (defined(sun) || defined(ibm032)) && !defined(__GNUC__)
#define BIOCGBLEN _IOR(B,102, u_int)
#define BIOCSBLEN _IOWR(B,102, u_int)
#define BIOCSETF _IOW(B,103, struct bpf_program)
#define BIOCFLUSH _IO(B,104)
#define BIOCPROMISC _IO(B,105)
#define BIOCGDLT _IOR(B,106, u_int)
#define BIOCGETIF _IOR(B,107, struct ifreq)
#define BIOCSETIF _IOW(B,108, struct ifreq)
#define BIOCSRTIMEOUT _IOW(B,109, struct timeval)
#define BIOCGRTIMEOUT _IOR(B,110, struct timeval)
#define BIOCGSTATS _IOR(B,111, struct bpf_stat)
#define BIOCIMMEDIATE _IOW(B,112, u_int)
#define BIOCVERSION _IOR(B,113, struct bpf_version)
#define BIOCSTCPF _IOW(B,114, struct bpf_program)
#define BIOCSUDPF _IOW(B,115, struct bpf_program)
#else
#define BIOCGBLEN _IOR('B',102, u_int)
#define BIOCSBLEN _IOWR('B',102, u_int)
#define BIOCSETF _IOW('B',103, struct bpf_program)
#define BIOCFLUSH _IO('B',104)
#define BIOCPROMISC _IO('B',105)
#define BIOCGDLT _IOR('B',106, u_int)
#define BIOCGETIF _IOR('B',107, struct ifreq)
#define BIOCSETIF _IOW('B',108, struct ifreq)
#define BIOCSRTIMEOUT _IOW('B',109, struct timeval)
#define BIOCGRTIMEOUT _IOR('B',110, struct timeval)
#define BIOCGSTATS _IOR('B',111, struct bpf_stat)
#define BIOCIMMEDIATE _IOW('B',112, u_int)
#define BIOCVERSION _IOR('B',113, struct bpf_version)
#define BIOCSTCPF _IOW('B',114, struct bpf_program)
#define BIOCSUDPF _IOW('B',115, struct bpf_program)
#endif
/*
* Structure prepended to each packet.
*/
struct bpf_hdr {
struct timeval bh_tstamp; /* time stamp */
bpf_u_int32 bh_caplen; /* length of captured portion */
bpf_u_int32 bh_datalen; /* original length of packet */
u_short bh_hdrlen; /* length of bpf header (this struct
plus alignment padding) */
};
/*
* Because the structure above is not a multiple of 4 bytes, some compilers
* will insist on inserting padding; hence, sizeof(struct bpf_hdr) won't work.
* Only the kernel needs to know about it; applications use bh_hdrlen.
*/
#ifdef KERNEL
#define SIZEOF_BPF_HDR 18
#endif
/*
* Data-link level type codes.
*/
#define DLT_NULL 0 /* no link-layer encapsulation */
#define DLT_EN10MB 1 /* Ethernet (10Mb) */
#define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */
#define DLT_AX25 3 /* Amateur Radio AX.25 */
#define DLT_PRONET 4 /* Proteon ProNET Token Ring */
#define DLT_CHAOS 5 /* Chaos */
#define DLT_IEEE802 6 /* IEEE 802 Networks */
#define DLT_ARCNET 7 /* ARCNET */
#define DLT_SLIP 8 /* Serial Line IP */
#define DLT_PPP 9 /* Point-to-point Protocol */
#define DLT_FDDI 10 /* FDDI */
#define DLT_ATM_RFC1483 11 /* LLC/SNAP encapsulated atm */
#define DLT_RAW 12 /* raw IP */
#define DLT_SLIP_BSDOS 13 /* BSD/OS Serial Line IP */
#define DLT_PPP_BSDOS 14 /* BSD/OS Point-to-point Protocol */
/*
* The instruction encondings.
*/
/* instruction classes */
#define BPF_CLASS(code) ((code) & 0x07)
#define BPF_LD 0x00
#define BPF_LDX 0x01
#define BPF_ST 0x02
#define BPF_STX 0x03
#define BPF_ALU 0x04
#define BPF_JMP 0x05
#define BPF_RET 0x06
#define BPF_MISC 0x07
/* ld/ldx fields */
#define BPF_SIZE(code) ((code) & 0x18)
#define BPF_W 0x00
#define BPF_H 0x08
#define BPF_B 0x10
#define BPF_MODE(code) ((code) & 0xe0)
#define BPF_IMM 0x00
#define BPF_ABS 0x20
#define BPF_IND 0x40
#define BPF_MEM 0x60
#define BPF_LEN 0x80
#define BPF_MSH 0xa0
/* alu/jmp fields */
#define BPF_OP(code) ((code) & 0xf0)
#define BPF_ADD 0x00
#define BPF_SUB 0x10
#define BPF_MUL 0x20
#define BPF_DIV 0x30
#define BPF_OR 0x40
#define BPF_AND 0x50
#define BPF_LSH 0x60
#define BPF_RSH 0x70
#define BPF_NEG 0x80
#define BPF_JA 0x00
#define BPF_JEQ 0x10
#define BPF_JGT 0x20
#define BPF_JGE 0x30
#define BPF_JSET 0x40
#define BPF_SRC(code) ((code) & 0x08)
#define BPF_K 0x00
#define BPF_X 0x08
/* ret - BPF_K and BPF_X also apply */
#define BPF_RVAL(code) ((code) & 0x18)
#define BPF_A 0x10
/* misc */
#define BPF_MISCOP(code) ((code) & 0xf8)
#define BPF_TAX 0x00
#define BPF_TXA 0x80
/*
* The instruction data structure.
*/
struct bpf_insn {
u_short code;
u_char jt;
u_char jf;
bpf_int32 k;
};
/*
* Macros for insn array initializers.
*/
#define BPF_STMT(code, k) { (u_short)(code), 0, 0, k }
#define BPF_JUMP(code, k, jt, jf) { (u_short)(code), jt, jf, k }
#ifdef KERNEL
extern u_int bpf_filter();
extern void bpfattach();
extern void bpf_tap();
extern void bpf_mtap();
#else
#if __STDC__
extern u_int bpf_filter(struct bpf_insn *, u_char *, u_int, u_int);
#endif
#endif
/*
* Number of scratch memory words (for BPF_LD|BPF_MEM and BPF_ST).
*/
#define BPF_MEMWORDS 16
#endif

View File

@ -0,0 +1,47 @@
/* include/config.h. Generated automatically by configure. */
/* include/config.h.in. Generated automatically from configure.in by autoheader. */
/* Define to empty if the keyword does not work. */
/* #undef const */
/* #undef LIBNET_BSDISH_OS */
/* #undef LIBNET_BSD_BYTE_SWAP */
/* #undef DLPI_DEV_PREFIX */
/* #undef HAVE_DEV_DLPI */
/* #undef HAVE_SOCKADDR_SA_LEN */
/* #undef HAVE_SOLARIS */
/* #undef HAVE_DLPI */
/* #undef HAVE_PF_PACKET */
/* #undef HAVE_STRUCT_IP_CSUM */
#define HAVE_LIB_PCAP 1
/* #undef LBL_ALIGN */
/* #undef STUPID_SOLARIS_CHECKSUM_BUG */
#define _BSD_SOURCE 1
#define __BSD_SOURCE 1
#define __FAVOR_BSD 1
#if 0 // move define to Makefile
#undef LIBNET_LIL_ENDIAN
#define LIBNET_BIG_ENDIAN 1
/*#define LIBNET_LIL_ENDIAN 1*/
#endif
/* Define if you have the strerror function. */
#define HAVE_STRERROR 1
/* Define if you have the <net/ethernet.h> header file. */
#define HAVE_NET_ETHERNET_H 1
/* Define if you have the <sys/bufmod.h> header file. */
/* #undef HAVE_SYS_BUFMOD_H */
/* Define if you have the <sys/dlpi_ext.h> header file. */
/* #undef HAVE_SYS_DLPI_EXT_H */
/* Define if you have the <sys/sockio.h> header file. */
/* #undef HAVE_SYS_SOCKIO_H */
/* Define if you have the nsl library (-lnsl). */
/* #undef HAVE_LIBNSL */
/* Define if you have the socket library (-lsocket). */
/* #undef HAVE_LIBSOCKET */

View File

@ -0,0 +1,97 @@
/*
* $Id: libnet.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
*
* libnet.h - Network routine library header file
*
* Copyright (c) 1998 - 2001 Mike D. Schiffman <mike@infonexus.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*/
#ifndef __LIBNET_H
#define __LIBNET_H
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#if defined(HAVE_SYS_SOCKIO_H) && !defined(SIOCGIFADDR)
#include <sys/sockio.h>
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <net/if.h>
#ifndef __linux__
#include <netinet/ip_var.h>
#else /* __linux__ */
//#ifdef HAVE_NET_ETHERNET_H
//#include <net/ethernet.h>
//#endif /* HAVE_NET_ETHERNET_H */
#if defined(__GLIBC__) && (__GLIBC__)
#include <netinet/if_ether.h>
#else
#include <linux/if_ether.h>
#endif
#endif /* __linux__ */
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#if defined(__linux__) && (!defined(__GLIBC__) || !(__GLIBC__))
/*
* We get multiple definitions of IGMP_AGE_THRESHOLD if we include netinet.
*/
//#include <linux/igmp.h> acli
#else
#include <netinet/igmp.h>
#endif
#include <arpa/inet.h>
#include <sys/time.h>
#include <netdb.h>
#include <errno.h>
#include <assert.h>
#include "./libnet/libnet-headers.h"
#include "./libnet/libnet-structures.h"
#include "./libnet/libnet-macros.h"
#include "./libnet/libnet-asn1.h"
#include "./libnet/libnet-functions.h"
#include "./libnet/libnet-ospf.h"
#define LIBNET_VERSION "1.0.2a"
#if (!LIBNET_LIL_ENDIAN && !LIBNET_BIG_ENDIAN)
#error "byte order has not been specified, you'll need to #define either LIBNET_LIL_ENDIAN or LIBNET_BIG_ENDIAN. See the documentation regarding the libnet-config script."
#endif
#endif /* __LIBNET_H */
/* EOF */

View File

@ -0,0 +1,251 @@
/*
* $Id: libnet-asn1.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
*
* libnet-asn1.h - Network routine library ASN.1 header file
*
* Definitions for Abstract Syntax Notation One, ASN.1
* As defined in ISO/IS 8824 and ISO/IS 8825
*
* Copyright 1988, 1989 by Carnegie Mellon University
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of CMU not be
* used in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
* CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
* ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*
* Copyright (c) 1998 - 2001 Mike D. Schiffman <mike@infonexus.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#ifndef __LIBNET_ASN1_H
#define __LIBNET_ASN1_H
#ifndef EIGHTBIT_SUBIDS
typedef u_long oid;
#define MAX_SUBID 0xFFFFFFFF
#else
typedef u_char oid;
#define MAX_SUBID 0xFF
#endif
#define MAX_OID_LEN 64 /* max subid's in an oid */
#define ASN_BOOLEAN (0x01)
#define ASN_INTEGER (0x02)
#define ASN_BIT_STR (0x03)
#define ASN_OCTET_STR (0x04)
#define ASN_NULL (0x05)
#define ASN_OBJECT_ID (0x06)
#define ASN_SEQUENCE (0x10)
#define ASN_SET (0x11)
#define ASN_UNIVERSAL (0x00)
#define ASN_APPLICATION (0x40)
#define ASN_CONTEXT (0x80)
#define ASN_PRIVATE (0xC0)
#define ASN_PRIMITIVE (0x00)
#define ASN_CONSTRUCTOR (0x20)
#define ASN_LONG_LEN (0x80)
#define ASN_EXTENSION_ID (0x1F)
#define ASN_BIT8 (0x80)
#define IS_CONSTRUCTOR(byte) ((byte) & ASN_CONSTRUCTOR)
#define IS_EXTENSION_ID(byte) (((byte) & ASN_EXTENSION_ID) = ASN_EXTENSION_ID)
/*
* All of the build_asn1_* (build_asn1_length being an exception) functions
* take the same first 3 arguments:
*
* u_char *data: This is a pointer to the start of the data object to be
* manipulated.
* int *datalen: This is a pointer to the number of valid bytes following
* "data". This should be not be exceeded in any function.
* Upon exiting a function, this value will reflect the
* changed "data" and then refer to the new number of valid
* bytes until the end of "data".
* u_char type: The ASN.1 object type.
*/
/*
* Builds an ASN object containing an integer.
*
* Returns NULL upon error or a pointer to the first byte past the end of
* this object (the start of the next object).
*/
u_char *
libnet_build_asn1_int(
u_char *, /* Pointer to the output buffer */
int *, /* Number of valid bytes left in the buffer */
u_char, /* ASN object type */
long *, /* Pointer to a long integer */
int /* Size of a long integer */
);
/*
* Builds an ASN object containing an unsigned integer.
*
* Returns NULL upon error or a pointer to the first byte past the end of
* this object (the start of the next object).
*/
u_char *
libnet_build_asn1_uint(
u_char *, /* Pointer to the output buffer */
int *, /* Number of valid bytes left in the buffer */
u_char, /* ASN object type */
u_long *, /* Pointer to an unsigned long integer */
int /* Size of a long integer */
);
/*
* Builds an ASN object containing an octect string.
*
* Returns NULL upon error or a pointer to the first byte past the end of
* this object (the start of the next object).
*/
u_char *
libnet_build_asn1_string(
u_char *, /* Pointer to the output buffer */
int *, /* Number of valid bytes left in the buffer */
u_char, /* ASN object type */
u_char *, /* Pointer to a string to be built into an object */
int /* Size of the string */
);
/*
* Builds an ASN header for an object with the ID and length specified. This
* only works on data types < 30, i.e. no extension octets. The maximum
* length is 0xFFFF;
*
* Returns a pointer to the first byte of the contents of this object or
* NULL upon error
*/
u_char *
libnet_build_asn1_header(
u_char *, /* Pointer to the start of the object */
int *, /* Number of valid bytes left in buffer */
u_char, /* ASN object type */
int /* ASN object length */
);
u_char *
libnet_build_asn1_length(
u_char *, /* Pointer to start of object */
int *, /* Number of valid bytes in buffer */
int /* Length of object */
);
/*
* Builds an ASN header for a sequence with the ID and length specified.
*
* This only works on data types < 30, i.e. no extension octets.
* The maximum length is 0xFFFF;
*
* Returns a pointer to the first byte of the contents of this object.
* Returns NULL on any error.
*/
u_char *
libnet_build_asn1_sequence(
u_char *,
int *,
u_char,
int
);
/*
* Builds an ASN object identifier object containing the input string.
*
* Returns NULL upon error or a pointer to the first byte past the end of
* this object (the start of the next object).
*/
u_char *
libnet_build_asn1_objid(
u_char *,
int *,
u_char,
oid *,
int
);
/*
* Builds an ASN null object.
*
* Returns NULL upon error or a pointer to the first byte past the end of
* this object (the start of the next object).
*/
u_char *
libnet_build_asn1_null(
u_char *,
int *,
u_char
);
/*
* Builds an ASN bitstring.
*
* Returns NULL upon error or a pointer to the first byte past the end of
* this object (the start of the next object).
*/
u_char *
libnet_build_asn1_bitstring(
u_char *,
int *,
u_char,
u_char *, /* Pointer to the input buffer */
int /* Length of the input buffer */
);
#endif /* __LIBNET_ASN1_H */
/* EOF */

View File

@ -0,0 +1,658 @@
/*
* $Id: libnet-functions.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
*
* libnet-functions.h - Network routine library function prototype header file
*
* Copyright (c) 1998 - 2001 Mike D. Schiffman <mike@infonexus.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*/
#ifndef __LIBNET_FUNCTIONS_H
#define __LIBNET_FUNCTIONS_H
int /* 1 if good, -1 if bad */
libnet_plist_chain_new(
struct libnet_plist_chain **, /* pointer to the head of the list */
char * /* token list pointer */
);
int /* 1 if more nodes, 0 if not */
libnet_plist_chain_next_pair(
struct libnet_plist_chain *, /* pointer to the head of the list */
u_short *, /* holds bport */
u_short * /* holds eport */
);
int
libnet_plist_chain_dump(
struct libnet_plist_chain * /* pointer to the head of the list */
);
u_char *
libnet_plist_chain_dump_string(
struct libnet_plist_chain * /* pointer to the head of the list */
);
int
libnet_plist_chain_free(
struct libnet_plist_chain * /* pointer to the head of the list */
);
/*
* Standard error handling code.
*/
void
libnet_error(
int, /* severity */
char *, /* error message */
... /* varargs */
);
/*
* Seeds the pseudorandom number generator with gettimeofday.
*/
int
libnet_seed_prand();
/*
* Returns a psuedorandom positive integer.
*/
u_long
libnet_get_prand(
int /* One of the PR* constants */
);
/*
* Calculates IPv4 family checksum on packet headers.
*/
int /* 1 on success, -1 on failure */
libnet_do_checksum(
u_char *, /* Pointer to the packet buffer */
int, /* Protocol */
int /* Packet size */
);
/*
* Network byte order into IP address
* Previous versions had a memory leak (returned a strdup'd pointer -- strdup
* has an implicit malloc which wasn't getting freed). This static var hack
* thingy was used to preserve existing code without having to change much.
* You can simply use the return value of the function directly allowing you
* to write tighter, more obvious code (rather then having to do allocate an
* additional buffer for the output).
* Thanks to Red for the idea.
*/
u_char * /* Pointer to hostname or dotted decimal IP address */
libnet_host_lookup(
u_long, /* Network byte ordered (big endian) IP address */
u_short /* Use domain names or no */
);
/*
* Network byte order into IP address
* Threadsafe version.
*/
void
libnet_host_lookup_r(
u_long, /* Network byte ordered (big endian) IP address */
u_short, /* Use domain names or no */
u_char * /* Pointer to hostname or dotted decimal IP address */
);
/*
* IP address into network byte order
*/
u_long /* Network byte ordered IP address or -1 on error */
libnet_name_resolve(
u_char *, /* Pointer the hostname or dotted decimal IP address */
u_short /* Use domain names or no */
);
/*
* IP checksum wrapper.
*/
u_short /* Standard IP checksum of header and data */
libnet_ip_check(
u_short *, /* Pointer to the buffer to be summed */
int /* Packet length */
);
/*
* IP checksum.
*/
int /* Standard IP checksum */
libnet_in_cksum(
u_short *, /* Pointer to the buffer to be summed */
int /* Packet length */
);
/*
* Opens a socket for writing raw IP datagrams to. Set IP_HDRINCL to let the
* kernel know we've got it all under control.
*/
int /* Opened file desciptor, or -1 on error */
libnet_open_raw_sock(
int /* Protocol of raw socket (from /etc/protocols) */
);
int /* 1 upon success, or -1 on error */
libnet_close_raw_sock(
int /* File descriptor */
);
int
libnet_select_device(
struct sockaddr_in *,
char **,
char *
);
/*
* Ethernet packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_ethernet(
u_char *, /* Pointer to a 6 byte ethernet address */
u_char *, /* Pointer to a 6 byte ethernet address */
u_short, /* Packet IP type */
const u_char *, /* Payload (or NULL) */
int, /* Payload size */
u_char * /* Packet header buffer */
);
/*
* ARP packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_arp(
u_short, /* hardware address type */
u_short, /* protocol address type */
u_char, /* hardware address length */
u_char, /* protocol address length */
u_short, /* ARP operation type */
u_char *, /* sender hardware address */
u_char *, /* sender protocol address */
u_char *, /* target hardware address */
u_char *, /* target protocol address */
const u_char *, /* payload or NULL if none */
int, /* payload length */
u_char * /* packet buffer memory */
);
/*
* TCP packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_tcp(
u_short, /* Source port */
u_short, /* Destination port */
u_long, /* Sequence Number */
u_long, /* Acknowledgement Number */
u_char, /* Control bits */
u_short, /* Advertised Window Size */
u_short, /* Urgent Pointer */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
/*
* UDP packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_udp(
u_short, /* Source port */
u_short, /* Destination port */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
/*
* ICMP_ECHO packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_icmp_echo(
u_char, /* icmp type */
u_char, /* icmp code */
u_short, /* id */
u_short, /* sequence number */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
/*
* ICMP_MASK packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_icmp_mask(
u_char, /* icmp type */
u_char, /* icmp code */
u_short, /* id */
u_short, /* sequence number */
u_long, /* address mask */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
/*
* ICMP_UNREACH packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_icmp_unreach(
u_char, /* icmp type */
u_char, /* icmp code */
u_short, /* Original Length of packet data */
u_char, /* Original IP tos */
u_short, /* Original IP ID */
u_short, /* Original Fragmentation flags and offset */
u_char, /* Original TTL */
u_char, /* Original Protocol */
u_long, /* Original Source IP Address */
u_long, /* Original Destination IP Address */
const u_char *, /* Pointer to original packet data (or NULL) */
int, /* Packet payload size (or 0) */
u_char * /* Pointer to packet header memory */
);
/*
* ICMP_REDIRECT packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_icmp_redirect(
u_char, /* icmp type */
u_char, /* icmp code */
u_long, /* Gateway host that should be used */
u_short, /* Original Length of packet data */
u_char, /* Original IP tos */
u_short, /* Original IP ID */
u_short, /* Original Fragmentation flags and offset */
u_char, /* Original TTL */
u_char, /* Original Protocol */
u_long, /* Original Source IP Address */
u_long, /* Original Destination IP Address */
const u_char *, /* Pointer to original packet data (or NULL) */
int, /* Packet payload size (or 0) */
u_char * /* Pointer to packet header memory */
);
/*
* ICMP_TIMXCEED packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_icmp_timeexceed(
u_char, /* icmp type */
u_char, /* icmp code */
u_short, /* Original Length of packet data */
u_char, /* Original IP tos */
u_short, /* Original IP ID */
u_short, /* Original Fragmentation flags and offset */
u_char, /* Original TTL */
u_char, /* Original Protocol */
u_long, /* Original Source IP Address */
u_long, /* Original Destination IP Address */
const u_char *, /* Pointer to original packet data (or NULL) */
int, /* Packet payload size (or 0) */
u_char * /* Pointer to packet header memory */
);
/*
* ICMP_TIMESTAMP packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_icmp_timestamp(
u_char, /* icmp type */
u_char, /* icmp code */
u_short, /* id */
u_short, /* sequence number */
n_time, /* original timestamp */
n_time, /* receive timestamp */
n_time, /* transmit timestamp */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
/*
* IGMP packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_igmp(
u_char, /* igmp type */
u_char, /* igmp code */
u_long, /* ip addr */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
/*
* IPv4 packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_ip(
u_short, /* Length of packet data */
u_char, /* IP tos */
u_short, /* IP ID */
u_short, /* Fragmentation flags and offset */
u_char, /* TTL */
u_char, /* Protocol */
u_long, /* Source IP Address */
u_long, /* Destination IP Address */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_ipv4(
u_short, /* Length of packet data */
u_char, /* IP tos */
u_short, /* IP ID */
u_short, /* Fragmentation flags and offset */
u_char, /* TTL */
u_char, /* Protocol */
u_long, /* Source IP Address */
u_long, /* Destination IP Address */
const u_char *, /* Pointer to packet data (or NULL) */
int, /* Packet payload size */
u_char * /* Pointer to packet header memory */
);
/*
* DNS pacekt assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_dns(
u_short, /* Packet ID */
u_short, /* Flags */
u_short, /* Number of questions */
u_short, /* Number of answer resource records */
u_short, /* Number of authority resource records */
u_short, /* Number of additional resource records */
const u_char *, /* Payload (or NULL) */
int, /* Payload size */
u_char * /* Header memory */
);
/*
* RIP packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_rip(
u_char, /* Command */
u_char, /* Version */
u_short, /* Zero (v1) or Routing Domain (v2) */
u_short, /* Address family */
u_short, /* Zero (v1) or Route Tag (v2) */
u_long, /* IP address */
u_long, /* Zero (v1) or Subnet Mask (v2) */
u_long, /* Zero (v1) or Next hop IP address (v2) */
u_long, /* Metric */
const u_char *, /* Payload (or NULL) */
int, /* Payload size */
u_char * /* Header memory */
);
/*
* VRRP packet assembler.
*/
int /* -1 on failure (null buf passed in), 1 on success */
libnet_build_vrrp(
u_char,
u_char,
u_char,
u_char,
u_char,
const u_char *, /* Payload (or NULL) */
int, /* Payload size */
u_char * /* Header memory */
);
int
libnet_init_vrrp_packet(size_t,
u_char **,
u_char
);
/*
* Insert IP options to a prebuilt IP packet.
*/
int /* 1 on success, -1 on failure */
libnet_insert_ipo(
struct ipoption *, /* Pointer to the ip options structure */
u_char, /* IP option list size */
u_char * /* Pointer to packet buf */
);
/*
* Insert TCP options to a prebuilt IP packet.
*/
int /* 1 on success, -1 on failure */
libnet_insert_tcpo(
struct tcpoption *, /* Pointer to the tcp options structure */
u_char, /* TCP option list size */
u_char * /* Pointer to packet buf */
);
/*
* Writes a prebuild IP packet to the network with a supplied raw socket.
* To write a link layer packet, use the write_link_layer function.
*/
int /* number of bytes written if successful, -1 on error */
libnet_write_ip(
int sock, /* Previously opened raw socket */
u_char *, /* Pointer a complete IP datagram */
int /* Packet size */
);
/*
* Writes a prebuild IP/ethernet packet to the network with a supplied
* link_layer interface. To write just an IP packet, use the write_link_layer
* function.
*/
int /* number of bytes written if successful, -1 on error */
libnet_write_link_layer(
struct libnet_link_int *, /* Pointer to a link interface structure */
const char *, /* Pointer to the device */
u_char *, /* Pointer the u_char buf (the packet)to be written */
int /* Packet length */
);
/*
* Opens a link layer interface. Analogous to open_raw_sock.
*/
struct libnet_link_int * /* Pointer to a link layer interface struct */
libnet_open_link_interface(
char *, /* Device name */
char * /* Error buffer */
);
int /* 1 on success, -1 on failure */
libnet_close_link_interface(
struct libnet_link_int * /* Pointer to a link layer interface struct */
);
char * /* String error message */
ll_strerror(
int /* Errno */
);
/*
* Returns the IP address of the interface.
*/
u_long /* 0 upon error, address upon success */
libnet_get_ipaddr(
struct libnet_link_int *, /* Pointer to a link interface structure */
const char *, /* Device */
char * /* Error buf */
);
/*
* Returns the MAC address of the interface.
*/
struct ether_addr * /* 0 upon error, address upon success */
libnet_get_hwaddr(
struct libnet_link_int *, /* Pointer to a link interface structure */
const char *, /* Device */
char * /* Error buf */
);
/*
* Simple interface for initializing a packet.
* Basically a malloc wrapper.
*/
int /* -1 on error, 1 on ok */
libnet_init_packet(
int, /* 0 and we make a good guess, otherwise you choose. */
u_char ** /* Pointer to the pointer to the packet */
);
/*
* Simple interface for destoying a packet.
* Don't call this without a corresponding call to init_packet() first.
*/
int /* -1 if arena is NULL, 1 if ok */
libnet_destroy_packet(
u_char ** /* Pointer to the packet addr. */
);
/*
* Memory pool initialization routine.
*/
int
libnet_init_packet_arena(
struct libnet_arena **, /* Pointer to an arena pointer */
int, /* 0 and we make a good guess, otherwise you choose. */
u_short
);
/*
* Returns the next chunk of memory from the pool.
*/
u_char *
libnet_next_packet_from_arena(
struct libnet_arena **, /* Pointer to an arena pointer */
int /* 0 and we make a good guess, otherwise you choose. */
);
/*
* Memory pool destructor routine.
*/
int /* -1 if arena is NULL, 1 if ok */
libnet_destroy_packet_arena(
struct libnet_arena ** /* Pointer to an arena pointer */
);
/*
* More or less taken from tcpdump code.
*/
void
libnet_hex_dump(
u_char *, /* Packet to be dumped */
int, /* Packet size (in bytes */
int, /* To swap or not to swap */
FILE * /* Stream pointer to dump to */
);
#endif /* __LIBNET_FUNCTIONS_H */
/* EOF */

View File

@ -0,0 +1,525 @@
/*
* $Id: libnet-headers.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
*
* libnet-headers.h - Network routine library headers header file
*
* Copyright (c) 1998 - 2001 Mike D. Schiffman <mike@infonexus.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*/
#ifndef __LIBNET_HEADERS_H
#define __LIBNET_HEADERS_H
/*
* Standard (IPv4) header sizes in bytes.
*/
#define LIBNET_ARP_H 0x1c /* ARP header: 28 bytes */
#define LIBNET_DNS_H 0xc /* DNS header base: 12 bytes */
#define LIBNET_ETH_H 0xe /* Etherner header: 14 bytes */
#define LIBNET_ICMP_H 0x4 /* ICMP header base: 4 bytes */
#define LIBNET_ICMP_ECHO_H 0x8 /* ICMP_ECHO header: 8 bytes */
#define LIBNET_ICMP_MASK_H 0xc /* ICMP_MASK header: 12 bytes */
#define LIBNET_ICMP_UNREACH_H 0x8 /* ICMP_UNREACH header: 8 bytes */
#define LIBNET_ICMP_TIMXCEED_H 0x8 /* ICMP_TIMXCEED header: 8 bytes */
#define LIBNET_ICMP_REDIRECT_H 0x8 /* ICMP_REDIRECT header: 8 bytes */
#define LIBNET_ICMP_TS_H 0x14 /* ICMP_TIMESTAMP headr:20 bytes */
#define LIBNET_IGMP_H 0x8 /* IGMP header: 8 bytes */
#define LIBNET_IP_H 0x14 /* IP header: 20 bytes */
/* See libnet-ospf.h for OSPF related header sizes */
#define LIBNET_RIP_H 0x18 /* RIP header base: 24 bytes */
#define LIBNET_TCP_H 0x14 /* TCP header: 20 bytes */
#define LIBNET_UDP_H 0x8 /* UDP header: 8 bytes */
#define LIBNET_VRRP_H 0x8 /* VRRP header: 8 bytes */
/*
* Concession to legacy naming scheme.
*/
#define ARP_H LIBNET_ARP_H
#define DNS_H LIBNET_DNS_H
#define ETH_H LIBNET_ETH_H
#define ICMP_H LIBNET_ICMP_H
#define ICMP_ECHO_H LIBNET_ICMP_ECHO_H
#define ICMP_MASK_H LIBNET_ICMP_MASK_H
#define ICMP_UNREACH_H LIBNET_ICMP_UNREACH_H
#define ICMP_TIMXCEED_H LIBNET_ICMP_TIMXCEED_H
#define ICMP_REDIRECT_H LIBNET_ICMP_REDIRECT_H
#define ICMP_TS_H LIBNET_ICMP_TS_H
#define IGMP_H LIBNET_IGMP_H
#define IP_H LIBNET_IP_H
#define RIP_H LIBNET_RIP_H
#define TCP_H LIBNET_TCP_H
#define UDP_H LIBNET_UDP_H
/*
* IPv4 packet header prototype.
*/
struct libnet_ip_hdr
{
#if (LIBNET_LIL_ENDIAN)
u_char ip_hl:4, /* header length */
ip_v:4; /* version */
#endif
#if (LIBNET_BIG_ENDIAN)
u_char ip_v:4, /* version */
ip_hl:4; /* header length */
#endif
u_char ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off;
#ifndef IP_RF
#define IP_RF 0x8000 /* reserved fragment flag */
#endif
#ifndef IP_DF
#define IP_DF 0x4000 /* dont fragment flag */
#endif
#ifndef IP_MF
#define IP_MF 0x2000 /* more fragments flag */
#endif
#ifndef IP_OFFMASK
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
#endif
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src, ip_dst; /* source and dest address */
};
/*
* TCP packet header prototype.
*/
struct libnet_tcp_hdr
{
u_short th_sport; /* source port */
u_short th_dport; /* destination port */
u_long th_seq; /* sequence number */
u_long th_ack; /* acknowledgement number */
#if (LIBNET_LIL_ENDIAN)
u_char th_x2:4, /* (unused) */
th_off:4; /* data offset */
#endif
#if (LIBNET_BIG_ENDIAN)
u_char th_off:4, /* data offset */
th_x2:4; /* (unused) */
#endif
u_char th_flags; /* control flags */
#ifndef TH_FIN
#define TH_FIN 0x01
#endif
#ifndef TH_SYN
#define TH_SYN 0x02
#endif
#ifndef TH_RST
#define TH_RST 0x04
#endif
#ifndef TH_PUSH
#define TH_PUSH 0x08
#endif
#ifndef TH_ACK
#define TH_ACK 0x10
#endif
#ifndef TH_URG
#define TH_URG 0x20
#endif
u_short th_win; /* window */
u_short th_sum; /* checksum */
u_short th_urp; /* urgent pointer */
};
/*
* UDP packet header prototype.
*/
struct libnet_udp_hdr
{
u_short uh_sport; /* soure port */
u_short uh_dport; /* destination port */
u_short uh_ulen; /* length */
u_short uh_sum; /* checksum */
};
/*
* ICMP packet header prototype.
*/
struct libnet_icmp_hdr
{
u_char icmp_type;
/*
* ICMP types.
*/
#ifndef ICMP_ECHOREPLY
#define ICMP_ECHOREPLY 0
#endif
#ifndef ICMP_UNREACH
#define ICMP_UNREACH 3
#endif
#ifndef ICMP_SOURCEQUENCH
#define ICMP_SOURCEQUENCH 4
#endif
#ifndef ICMP_REDIRECT
#define ICMP_REDIRECT 5
#endif
#ifndef ICMP_ECHO
#define ICMP_ECHO 8
#endif
#ifndef ICMP_ROUTERADVERT
#define ICMP_ROUTERADVERT 9
#endif
#ifndef ICMP_ROUTERSOLICIT
#define ICMP_ROUTERSOLICIT 10
#endif
#ifndef ICMP_TIMXCEED
#define ICMP_TIMXCEED 11
#endif
#ifndef ICMP_PARAMPROB
#define ICMP_PARAMPROB 12
#endif
#ifndef ICMP_TSTAMP
#define ICMP_TSTAMP 13
#endif
#ifndef ICMP_TSTAMPREPLY
#define ICMP_TSTAMPREPLY 14
#endif
#ifndef ICMP_IREQ
#define ICMP_IREQ 15
#endif
#ifndef ICMP_IREQREPLY
#define ICMP_IREQREPLY 16
#endif
#ifndef ICMP_MASKREQ
#define ICMP_MASKREQ 17
#endif
#ifndef ICMP_MASKREPLY
#define ICMP_MASKREPLY 18
#endif
u_char icmp_code;
/*
* ICMP codes.
*/
#ifndef ICMP_UNREACH_NET
#define ICMP_UNREACH_NET 0
#endif
#ifndef ICMP_UNREACH_HOST
#define ICMP_UNREACH_HOST 1
#endif
#ifndef ICMP_UNREACH_PROTOCOL
#define ICMP_UNREACH_PROTOCOL 2
#endif
#ifndef ICMP_UNREACH_PORT
#define ICMP_UNREACH_PORT 3
#endif
#ifndef ICMP_UNREACH_NEEDFRAG
#define ICMP_UNREACH_NEEDFRAG 4
#endif
#ifndef ICMP_UNREACH_SRCFAIL
#define ICMP_UNREACH_SRCFAIL 5
#endif
#ifndef ICMP_UNREACH_NET_UNKNOWN
#define ICMP_UNREACH_NET_UNKNOWN 6
#endif
#ifndef ICMP_UNREACH_HOST_UNKNOWN
#define ICMP_UNREACH_HOST_UNKNOWN 7
#endif
#ifndef ICMP_UNREACH_ISOLATED
#define ICMP_UNREACH_ISOLATED 8
#endif
#ifndef ICMP_UNREACH_NET_PROHIB
#define ICMP_UNREACH_NET_PROHIB 9
#endif
#ifndef ICMP_UNREACH_HOST_PROHIB
#define ICMP_UNREACH_HOST_PROHIB 10
#endif
#ifndef ICMP_UNREACH_TOSNET
#define ICMP_UNREACH_TOSNET 11
#endif
#ifndef ICMP_UNREACH_TOSHOST
#define ICMP_UNREACH_TOSHOST 12
#endif
#ifndef ICMP_UNREACH_FILTER_PROHIB
#define ICMP_UNREACH_FILTER_PROHIB 13
#endif
#ifndef ICMP_UNREACH_HOST_PRECEDENCE
#define ICMP_UNREACH_HOST_PRECEDENCE 14
#endif
#ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF
#define ICMP_UNREACH_PRECEDENCE_CUTOFF 15
#endif
#ifndef ICMP_REDIRECT_NET
#define ICMP_REDIRECT_NET 0
#endif
#ifndef ICMP_REDIRECT_HOST
#define ICMP_REDIRECT_HOST 1
#endif
#ifndef ICMP_REDIRECT_TOSNET
#define ICMP_REDIRECT_TOSNET 2
#endif
#ifndef ICMP_REDIRECT_TOSHOST
#define ICMP_REDIRECT_TOSHOST 3
#endif
#ifndef ICMP_TIMXCEED_INTRANS
#define ICMP_TIMXCEED_INTRANS 0
#endif
#ifndef ICMP_TIMXCEED_REASS
#define ICMP_TIMXCEED_REASS 1
#endif
#ifndef ICMP_PARAMPROB_OPTABSENT
#define ICMP_PARAMPROB_OPTABSENT 1
#endif
u_short icmp_sum;
union
{
struct
{
u_short id;
u_short seq;
}echo;
#undef icmp_id
#undef icmp_seq
#define icmp_id hun.echo.id
#define icmp_seq hun.echo.seq
u_long gateway;
struct
{
u_short pad;
u_short mtu;
}frag;
}hun;
union
{
struct
{
n_time its_otime;
n_time its_rtime;
n_time its_ttime;
}ts;
struct
{
struct ip idi_ip;
/* options and then 64 bits of data */
}ip;
u_long mask;
char data[1];
#undef icmp_mask
#define icmp_mask dun.mask
#undef icmp_data
#define icmp_data dun.data
#undef icmp_otime
#define icmp_otime dun.ts.its_otime
#undef icmp_rtime
#define icmp_rtime dun.ts.its_rtime
#undef icmp_ttime
#define icmp_ttime dun.ts.its_ttime
}dun;
};
/*
* IGMP header.
*/
struct libnet_igmp_hdr
{
u_char igmp_type;
#ifndef IGMP_MEMBERSHIP_QUERY
#define IGMP_MEMBERSHIP_QUERY 0x11 /* membership query */
#endif
#ifndef IGMP_V1_MEMBERSHIP_REPORT
#define IGMP_V1_MEMBERSHIP_REPORT 0x12 /* Ver. 1 membership report */
#endif
#ifndef IGMP_V2_MEMBERSHIP_REPORT
#define IGMP_V2_MEMBERSHIP_REPORT 0x16 /* Ver. 2 membership report */
#endif
#ifndef IGMP_LEAVE_GROUP
#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */
#endif
u_char igmp_code;
u_short igmp_sum;
struct in_addr igmp_group;
};
/*
* Ethernet packet header prototype. Too many O/S's define this differently.
* Easy enough to solve that and define it here.
*/
struct libnet_ethernet_hdr
{
#ifndef ETHER_ADDR_LEN
#define ETHER_ADDR_LEN 6
#endif
u_char ether_dhost[ETHER_ADDR_LEN]; /* destination ethernet address */
u_char ether_shost[ETHER_ADDR_LEN]; /* source ethernet address */
u_short ether_type; /* packet type ID */
};
#define ETHERTYPE_PUP 0x0200 /* PUP protocol */
#define ETHERTYPE_IP 0x0800 /* IP protocol */
#define ETHERTYPE_ARP 0x0806 /* Addr. resolution protocol */
#define ETHERTYPE_REVARP 0x8035 /* reverse Addr. resolution protocol */
#define ETHERTYPE_VLAN 0x8100 /* IEEE 802.1Q VLAN tagging */
#define ETHERTYPE_LOOPBACK 0x9000 /* used to test interfaces */
#ifndef __ANDROID__
#if !defined(__GLIBC__) || (!__GLIBC__)
struct ether_addr
{
u_char ether_addr_octet[6];
};
#endif
#endif
/*
* ARP packet header prototype. Too many O/S's define this differently.
* Easy enough to solve that and define it here.
*/
struct libnet_arp_hdr
{
u_short ar_hrd; /* format of hardware address */
#define ARPHRD_ETHER 1 /* ethernet hardware format */
u_short ar_pro; /* format of protocol address */
u_char ar_hln; /* length of hardware address */
u_char ar_pln; /* length of protocol addres */
u_short ar_op; /* operation type */
#define ARPOP_REQUEST 1 /* req to resolve address */
#define ARPOP_REPLY 2 /* resp to previous request */
#define ARPOP_REVREQUEST 3 /* req protocol address given hardware */
#define ARPOP_REVREPLY 4 /* resp giving protocol address */
#define ARPOP_INVREQUEST 8 /* req to identify peer */
#define ARPOP_INVREPLY 9 /* resp identifying peer */
/*
* These should implementation defined but I've hardcoded eth/IP.
*/
u_char ar_sha[6]; /* sender hardware address */
u_char ar_spa[4]; /* sender protocol address */
u_char ar_tha[6]; /* target hardware address */
u_char ar_tpa[4]; /* target protocol address */
};
/*
* Base DNS header.
*/
struct libnet_dns_hdr
{
u_short id; /* DNS packet ID */
u_short flags; /* DNS flags */
u_short num_q; /* Number of questions */
u_short num_answ_rr; /* Number of answer resource records */
u_short num_auth_rr; /* Number of authority resource records */
u_short num_addi_rr; /* Number of additional resource records */
};
/*
* Base RIP (routing information protocol) header.
*/
struct libnet_rip_hdr
{
u_char cmd; /* RIP command */
#define RIPCMD_REQUEST 1 /* want info */
#define RIPCMD_RESPONSE 2 /* responding to request */
#define RIPCMD_TRACEON 3 /* turn tracing on */
#define RIPCMD_TRACEOFF 4 /* turn it off */
#define RIPCMD_POLL 5 /* like request, but anyone answers */
#define RIPCMD_POLLENTRY 6 /* like poll, but for entire entry */
#define RIPCMD_MAX 7
u_char ver; /* RIP version */
#define RIPVER_0 0
#define RIPVER_1 1
#define RIPVER_2 2
u_short rd; /* Zero (v1) or Routing Domain (v2) */
u_short af; /* Address family */
u_short rt; /* Zero (v1) or Route Tag (v2) */
u_long addr; /* IP address */
u_long mask; /* Zero (v1) or Subnet Mask (v2) */
u_long next_hop; /* Zero (v1) or Next hop IP address (v2) */
u_long metric; /* Metric */
};
/*
* VRRP packet header prototype.
*/
#ifndef IPPROTO_VRRP
#define IPPROTO_VRRP 112
#endif
struct libnet_vrrp_hdr
{
#if (LIBNET_LIL_ENDIAN)
u_char vrrp_v:4, /* protocol version */
vrrp_t:4; /* packet type */
#endif
#if (LIBNET_BIG_ENDIAN)
u_char vrrp_t:4, /* packet type */
vrrp_v:4; /* protocol version */
#endif
#define LIBNET_VRRP_TYPE_ADVERT 0x1
u_char vrrp_vrouter_id; /* virtual router id */
u_char vrrp_priority; /* priority */
u_char vrrp_ip_count; /* number of IP addresses */
u_char vrrp_auth_type; /* authorization type */
#define LIBNET_VRRP_AUTH_NONE 0x1
#define LIBNET_VRRP_AUTH_PASSWD 0x2
#define LIBNET_VRRP_AUTH_IPAH 0x3
u_char vrrp_advert_int; /* advertisement interval */
u_short vrrp_sum; /* checksum */
};
#if 0
struct libnet_snmp_hdr
{
/* ASN.1 BER support first */
};
#endif
/*
* TCP options structure.
*/
struct tcpoption
{
u_char tcpopt_list[MAX_IPOPTLEN];
};
#ifdef __linux__
/*
* Linux has a radically different IP options structure from BSD.
*/
struct ipoption
{
struct in_addr ipopt_dst; /* first-hop dst if source routed */
char ipopt_list[MAX_IPOPTLEN]; /* options proper */
};
#endif
#endif /* __LIBNET_HEADERS_H */
/* EOF */

View File

@ -0,0 +1,146 @@
/*
* $Id: libnet-macros.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
*
* libnet-macros.h - Network routine library macro header file
*
* Copyright (c) 1998 - 2001 Mike D. Schiffman <mike@infonexus.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*/
#ifndef __LIBNET_MACROS_H
#define __LIBNET_MACROS_H
/*
* for libnet_hostlookup
*/
#define LIBNET_DONT_RESOLVE 0
#define LIBNET_RESOLVE 1
/*
* prand constants
*/
#define LIBNET_PR2 0
#define LIBNET_PR8 1
#define LIBNET_PR16 2
#define LIBNET_PRu16 3
#define LIBNET_PR32 4
#define LIBNET_PRu32 5
#define LIBNET_PRAND_MAX 0xffffffff
/*
* Concession to legacy naming scheme
*/
#define PR2 LIBNET_PR2
#define PR8 LIBNET_PR8
#define PR16 LIBNET_PR16
#define PRu16 LIBNET_PRu16
#define PR32 LIBNET_PR32
#define PRu32 LIBNET_PRu32
#define PRAND_MAX LIBNET_PRAND_MAX
/*
* Misc packet sizes for malloc
*/
#define LIBNET_PACKET LIBNET_IP_H + LIBNET_TCP_H /* IP, UDP or TCP */
#define LIBNET_OPTS 0x34 /* options! options! options! */
#define LIBNET_MAX_PACKET 0xffff /* as big as we can get */
/*
* Error handling constants.
*/
#define LIBNET_ERR_WARNING 1
#define LIBNET_ERR_CRITICAL 2
#define LIBNET_ERR_FATAL 3
/*
* Concession to legacy naming scheme
*/
#define LN_ERR_WARNING LIBNET_ERR_WARNING
#define LN_ERR_CRITICAL LIBNET_ERR_CRITICAL
#define LN_ERR_FATAL LIBNET_ERR_FATAL
#define LIBNET_ERRBUF_SIZE 256
/*
* Some BSD variants have this endianess problem.
*/
#if (LIBNET_BSD_BYTE_SWAP)
#define FIX(n) ntohs(n)
#define UNFIX(n) htons(n)
#else
#define FIX(n) (n)
#define UNFIX(n) (n)
#endif
/*
* Arena stuff
*/
#define LIBNET_GET_ARENA_SIZE(a) (a.size)
#define LIBNET_GET_ARENA_REMAINING_BYTES(a) (a.size - a.current)
/*
* Checksum stuff
*/
#define LIBNET_CKSUM_CARRY(x) \
(x = (x >> 16) + (x & 0xffff), (~(x + (x >> 16)) & 0xffff))
/*
* OSPF stuff
*/
#define LIBNET_OSPF_AUTHCPY(x,y) memcpy((u_char *)x, (u_char *)y, sizeof(y))
#define LIBNET_OSPF_CKSUMBUF(x,y) memcpy((u_char *)x, (u_char *)y, sizeof(y))
/*
* Not all systems have IFF_LOOPBACK
* Used by if_addr.c
*/
#ifdef IFF_LOOPBACK
#define LIBNET_ISLOOPBACK(p) ((p)->ifr_flags & IFF_LOOPBACK)
#else
#define LIBNET_ISLOOPBACK(p) (strcmp((p)->ifr_name, "lo0") == 0)
#endif
#define LIBNET_PRINT_ETH_ADDR(e) \
{ \
int i = 0; \
for (i = 0; i < 6; i++) \
{ \
printf("%x", e.ether_addr_octet[i]); \
if (i != 5) \
{ \
printf(":"); \
} \
} \
printf("\n"); \
}
#endif /* __LIBNET_MACROS_H */
/* EOF */

View File

@ -0,0 +1,394 @@
/*
* $Id: libnet-ospf.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
*
* libnet-ospf.h - Network routine library headers header file
*
* Copyright (c) 1999 Andrew Reiter <areiter@bindview.com>
* Bindview Development
*
* Copyright (c) 1998 - 2001 Mike D. Schiffman <mike@infonexus.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*/
#ifndef __LIBNET_OSPF_H
#define __LIBNET_OSPF_H
#include <sys/types.h>
/*
* Not all OSes define this in /etc/protocols.. ie, solaris...
*/
#ifndef IPPROTO_OSPF
#define IPPROTO_OSPF 89
#endif
#define IPPROTO_OSPF_LSA 890 /* Made this up. Hope it's unused */
#define OSPFVERSION 2
#define LIBNET_MODX 4102 /* Used in LSA checksum */
/*
* OSPF header lengths.
*/
#define LIBNET_OSPF_H 0x10 /* 16 bytes */
#define LIBNET_HELLO_H 0x18 /* 24 bytes */
#define LIBNET_DBD_H 0x8 /* 8 bytes */
#define LIBNET_LSR_H 0xc /* 12 bytes */
#define LIBNET_LSU_H 0x4 /* 4 bytes */
#define LIBNET_LSA_H 0x14 /* 20 bytes */
#define LIBNET_AUTH_H 0x8 /* 8 bytes */
#define LIBNET_OSPF_CKSUM 0x10 /* 16 bytes */
/*
* Link State packet format lengths.
*/
#define LIBNET_LS_RTR_LEN 0x10 /* 16 bytes */
#define LIBNET_LS_NET_LEN 0x8 /* 8 bytes */
#define LIBNET_LS_SUM_LEN 0xc /* 12 bytes */
#define LIBNET_LS_AS_EXT_LEN 0x10 /* 16 bytes */
/*
* OSPFv2 Packet Header.
*/
struct libnet_ospf_hdr
{
u_char ospf_v; /* version */
u_char ospf_type; /* type */
#define LIBNET_OSPF_UMD 0 /* UMd monitoring packet */
#define LIBNET_OSPF_HELLO 1 /* HELLO packet */
#define LIBNET_OSPF_DBD 2 /* DataBase Description Packet */
#define LIBNET_OSPF_LSR 3 /* Link State Request Packet */
#define LIBNET_OSPF_LSU 4 /* Link State Update Packet */
#define LIBNET_OSPF_LSA 5 /* Link State Acknowledgement Packet */
u_short ospf_len; /* length */
struct in_addr ospf_rtr_id; /* source router ID */
struct in_addr ospf_area_id; /* roam ID */
u_short ospf_cksum; /* checksum */
u_short ospf_auth_type; /* authentication type */
#define LIBNET_OSPF_AUTH_NULL 0 /* Null password */
#define LIBNET_OSPF_AUTH_SIMPLE 1 /* Simple, plaintext, 8 char password */
#define LIBNET_OSPF_AUTH_MD5 2 /* MD5 */
};
/*
* OSPF authentication header.
*/
struct libnet_auth_hdr
{
u_short ospf_auth_null; /* NULL */
u_char ospf_auth_keyid; /* Authentication Key ID */
u_char ospf_auth_len; /* Auth data length */
u_int ospf_auth_seq; /* Cryptographic sequence number */
};
/*
* Options used in multiple OSPF packets.
* More info can be found in section A.2 of RFC 2328.
*/
#define LIBNET_OPT_EBIT 0x02 /* Describes the way AS-external-LSAs are flooded */
#define LIBNET_OPT_MCBIT 0x04 /* Whether or not IP multicast dgrams are fwdd */
#define LIBNET_OPT_NPBIT 0x08 /* Describes handling of type-7 LSAs */
#define LIBNET_OPT_EABIT 0x10 /* rtr's willingness to send/recv EA-LSAs */
#define LIBNET_OPT_DCBIT 0x20 /* Describes handling of demand circuits */
/*
* OSPF HELLO Packet Header.
*/
struct libnet_ospf_hello_hdr
{
struct in_addr hello_nmask; /* Netmask associated with the interface */
u_short hello_intrvl; /* Num of seconds between routers last packet */
u_char hello_opts; /* Options for HELLO packets (look above) */
u_char hello_rtr_pri; /* Router's priority (if 0, can't be backup) */
u_int hello_dead_intvl; /* # of secs a router is silent till deemed down */
struct in_addr hello_des_rtr; /* Designated router on the network */
struct in_addr hello_bkup_rtr; /* Backup router */
struct in_addr hello_nbr; /* neighbor router, memcpy more as needed */
};
/*
* Database Description header.
*/
struct libnet_dbd_hdr
{
u_short dbd_mtu_len; /* Max length of IP dgram that this 'if' can use */
u_char dbd_opts; /* DBD packet options (look above) */
u_char dbd_type; /* Type of exchange occurring (look below) */
#define LIBNET_DBD_IBIT 0x01 /* Init Bit */
#define LIBNET_DBD_MBIT 0x02 /* Says more DBD packets are to come */
#define LIBNET_DBD_MSBIT 0x04 /* If 1, sender is the master in the exchnge */
u_int dbd_seq; /* DBD sequence number */
};
/*
* Used for the LS type field in all LS* headers.
*/
#define LIBNET_LS_TYPE_RTR 1 /* Router-LSA */
#define LIBNET_LS_TYPE_NET 2 /* Network-LSA */
#define LIBNET_LS_TYPE_IP 3 /* Summary-LSA (IP Network) */
#define LIBNET_LS_TYPE_ASBR 4 /* Summary-LSA (ASBR) */
#define LIBNET_LS_TYPE_ASEXT 5 /* AS-External-LSA */
/*
* Link State Request header.
*/
struct libnet_lsr_hdr
{
u_int lsr_type; /* Type of LS being requested (see below) */
u_int lsr_lsid; /* Link State ID */
struct in_addr lsr_adrtr; /* advertising router (memcpy more as needed) */
};
/*
* Link State Update header.
*/
struct libnet_lsu_hdr
{
u_int lsu_num; /* Number of LSAs that will be broadcasted */
};
/*
* Link State Acknowledgement header.
*/
struct libnet_lsa_hdr
{
u_short lsa_age; /* Time in seconds since the LSA was originated */
u_char lsa_opts; /* Look above for OPTS_* */
u_char lsa_type; /* Look below for LS_TYPE_* */
u_int lsa_id; /* Link State ID */
struct in_addr lsa_adv; /* Router ID of Advertising router */
u_int lsa_seq; /* LSA sequence number to detect old/bad ones */
u_char lsa_cksum[2]; /* "Fletcher Checksum" of all fields minus age */
u_short lsa_len; /* Length in bytes including the 20 byte header */
};
/*
* Router LSA data format
*
* Other stuff for TOS can be added for backward compatability, for this
* version, only OSPFv2 is being FULLY supported.
*/
struct libnet_rtr_lsa_hdr
{
u_short rtr_flags; /* Set to help describe packet */
#define LIBNET_RTR_FLAGS_W 0x0100 /* W bit */
#define LIBNET_RTR_FLAGS_E 0x0200 /* E bit */
#define LIBNET_RTR_FLAGS_B 0x0400 /* B bit */
u_short rtr_num; /* Number of links within that packet */
u_int rtr_link_id; /* Describes link_data (look below) */
#define LIBNET_LINK_ID_NBR_ID 1 /* Neighbors router ID, also can be 4 */
#define LIBNET_LINK_ID_IP_DES 2 /* IP address of designated router */
#define LIBNET_LINK_ID_SUB 3 /* IP subnet number */
u_int rtr_link_data; /* Depending on link_id, info is here */
u_char rtr_type; /* Description of router link */
#define LIBNET_RTR_TYPE_PTP 1 /* Point-To-Point */
#define LIBNET_RTR_TYPE_TRANS 2 /* Connection to a "transit network" */
#define LIBNET_RTR_TYPE_STUB 3 /* Connectin to a "stub network" */
#define RTR_TYPE_VRTL 4 /* Connects to a "virtual link" */
u_char rtr_tos_num; /* Number of different TOS metrics for this link */
u_short rtr_metric; /* The "cost" of using this link */
};
/*
* Network LSA data format.
*/
struct libnet_net_lsa_hdr
{
struct in_addr net_nmask; /* Netmask for that network */
u_int net_rtr_id; /* ID of router attached to that network */
};
/*
* Summary LSA data format.
*/
struct libnet_sum_lsa_hdr
{
struct in_addr sum_nmask; /* Netmask of destination IP address */
u_int sum_metric; /* Same as in rtr_lsa (&0xfff to use last 24bit) */
u_int sum_tos_metric; /* first 8bits are TOS, 24bits are TOS Metric */
};
/*
* AS External LSA data format.
* & 0xfff logic operator for as_metric to get last 24bits.
*/
struct libnet_as_lsa_hdr
{
struct in_addr as_nmask; /* Netmask for advertised destination */
u_int as_metric; /* May have to set E bit in first 8bits */
#define LIBNET_AS_E_BIT_ON 0x80000000 /* as_metric */
struct in_addr as_fwd_addr; /* Forwarding address */
u_int as_rte_tag; /* External route tag */
};
int
libnet_build_ospf(
u_short,
u_char,
u_long,
u_long,
u_short,
const char *,
int,
u_char *
);
int
libnet_build_ospf_hello(
u_long,
u_short,
u_char,
u_char,
u_int,
u_long,
u_long,
u_long,
const char *,
int,
u_char *
);
int
libnet_build_ospf_dbd(
u_short,
u_char,
u_char,
u_int,
const char *,
int,
u_char *
);
int
libnet_build_ospf_lsr(
u_int,
u_int,
u_long,
const char *,
int,
u_char *
);
int
libnet_build_ospf_lsu(
u_int,
const char *,
int,
u_char *
);
int
libnet_build_ospf_lsa(
u_short,
u_char,
u_char,
u_int,
u_long,
u_int,
u_short,
const char *,
int,
u_char *
);
int
libnet_build_ospf_lsa_rtr(
u_short,
u_short,
u_int,
u_int,
u_char,
u_char,
u_short,
const char *,
int,
u_char *
);
int
libnet_build_ospf_lsa_net(
u_long,
u_int,
const char *,
int,
u_char *
);
int
libnet_build_ospf_lsa_sum(
u_long,
u_int,
u_int,
const char *,
int,
u_char *
);
int
libnet_build_ospf_lsa_as(
u_long,
u_int,
u_long,
u_int,
const char *,
int,
u_char *
);
void
libnet_ospf_lsa_checksum(
u_char *,
int
);
#endif /* __LIBNET_OSPF_H */

View File

@ -0,0 +1,84 @@
/*
* $Id: libnet-structures.h,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
*
* libnet-structures.h - Network routine library structures header file
*
* Copyright (c) 1998 - 2001 Mike D. Schiffman <mike@infonexus.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*/
#ifndef __LIBNET_STRUCTURES_H
#define __LIBNET_STRUCTURES_H
/*
* Port list chain structure
*/
struct libnet_plist_chain
{
u_short node; /* node number */
u_short bport; /* beggining port */
u_short eport; /* terminating port */
u_char id; /* global array offset */
struct libnet_plist_chain *next; /* next node in the list */
};
/*
* Low level packet interface struct
*/
struct libnet_link_int
{
int fd; /* link layer file descriptor */
int linktype; /* link type */
int linkoffset; /* link header size (offset till network layer) */
u_char *device; /* device name */
};
/*
* Arena structure.
*/
struct libnet_arena
{
int tag; /* arena tag */
u_char *memory_pool; /* the memory */
u_long current; /* the current amount of memory allocated */
u_long size; /* the size of the pool in bytes */
};
/*
* Interface selection stuff
*/
struct libnet_ifaddr_list
{
u_long addr;
char *device;
};
#endif /* __LIBNET_STRUCTURES_H */
/* EOF */

View File

@ -0,0 +1,27 @@
//For Visual C++ usage
/*
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__83F96D0E_074B_4A74_91DB_10A69F2F3871__INCLUDED_)
#define AFX_STDAFX_H__83F96D0E_074B_4A74_91DB_10A69F2F3871__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

View File

@ -0,0 +1,611 @@
#include "1x_common.h"
#include "1x_auth_pae.h"
#include "1x_nal.h"
#include "1x_radius.h"
#include "1x_ioctl.h"
#include "1x_kmsm.h"
#ifdef __ANDROID__
#include <err.h>
#else
#include <error.h>
#endif
#include <string.h>
void lib1x_acctsm_init(Acct_SM * acct_sm, int maxReq, int aWhile)
{
acct_sm->status = acctsm_Stop;
acct_sm->elapsedSessionTime = 0;
acct_sm->reqCount = 0;
acct_sm->waitRespond = FALSE;
acct_sm->serverTimeout = aWhile;
acct_sm->maxReq = maxReq;
}
void lib1x_acctsm( Global_Params * global)
{
struct Auth_Pae_tag * auth_pae = global->theAuthenticator;
Acct_SM * acct_sm = auth_pae->acct_sm;
/*
lib1x_message(MESS_DBG_ACCT, "\n-----------\nlib1x_acctsm\n-----------");
lib1x_message(MESS_DBG_ACCT, "waitRespond = %d", acct_sm->waitRespond);
lib1x_message(MESS_DBG_ACCT, "aWhile = %d", acct_sm->aWhile);
lib1x_message(MESS_DBG_ACCT, "reqCount = %d", acct_sm->reqCount);
lib1x_message(MESS_DBG_ACCT, "maxReq = %d", acct_sm->maxReq);
*/
if(acct_sm->waitRespond )
{
if(acct_sm->aWhile >=0 )
{
acct_sm->aWhile--;
}
else
{
if(acct_sm->reqCount <= acct_sm->maxReq)
{
acct_sm->reqCount++;
lib1x_acctsm_sendReqToServer( global );
acct_sm->aWhile = acct_sm->serverTimeout;
}else
{
acct_sm->aWhile = acct_sm->serverTimeout;
acct_sm->waitRespond = FALSE;
}
}
}
}
BOOLEAN lib1x_acctsm_request( struct Global_Params_tag * global, int iAction, int iTerminateCause)
{
struct Auth_Pae_tag * auth_pae = global->theAuthenticator;
Acct_SM * acct_sm = auth_pae->acct_sm;
switch(iAction)
{
case acctsm_Acct_Start:
lib1x_message(MESS_DBG_ACCT,"acctsm_Acct_Start\n");
//reauthenticaton through eapol-start (not association request) do not send Acct-Start
if(acct_sm->status == acctsm_Stop)
{
acct_sm->status = acctsm_Start;
acct_sm->sessionId = global->auth->GlobalSessionId;
lib1x_message(MESS_DBG_ACCT, "==============================================\n");
lib1x_message(MESS_DBG_ACCT, "global->auth->GlobalSessionId = %d\n", global->auth->GlobalSessionId);
lib1x_message(MESS_DBG_ACCT, "==============================================\n");
lib1x_acct_request( auth_pae, LIB1X_RADACCT_ACTION_ACCOUNT_START, 0);
global->auth->GlobalSessionId++;
}
break;
case acctsm_Acct_Stop:
lib1x_message(MESS_DBG_ACCT,"acctsm_Acct_Stop\n");
if(acct_sm->status == acctsm_Start)
{
lib1x_acct_request( auth_pae, LIB1X_RADACCT_ACTION_ACCOUNT_STOP, iTerminateCause);
acct_sm->status = acctsm_Stop;
}
break;
case acctsm_Acct_On:
lib1x_acct_request( auth_pae, LIB1X_RADACCT_ACTION_ACCOUNT_ON, 0);
break;
case acctsm_Interim_On:
if(acct_sm->status == acctsm_Start)
{
lib1x_acct_request( auth_pae, LIB1X_RADACCT_ACTION_INTERIM_UPDATE, 0);
}
break;
}
//acct_sm->action = acctsm_Acct_No_Action;
return TRUE;
}
BOOLEAN lib1x_nal_send_acct( Auth_Pae * auth_pae, struct lib1x_nal_intfdesc * desc, char * packet , int size)
{
int num_sent = 0;
Acct_SM * acct_sm = auth_pae->acct_sm;
//lib1x_hexdump2(MESS_DBG_NAL, "lib1x_nal_send", packet, size, "Send Out Packet");
if ( desc->inttype == LIB1X_IT_PKTSOCK )
{
// if ( size > 1499 ) size = 1499; /* needed for ethernet only if you are not handling fragmentation */
if ( desc->libnet_desc == NULL )
lib1x_message( MESS_ERROR_FATAL, "%s: Descriptor contains invalid network identifier.", __func__);
num_sent = libnet_write_link_layer( desc->libnet_desc, (char *)desc->device ,
(u_char *)packet, size );
lib1x_message(MESS_DBG_NAL, "libnet_write_link_layer send packets %d\n", num_sent);
}
else
{
num_sent = send( desc->acctsock, (void*) packet, size, 0); /* flags = 0 */
acct_sm->waitRespond = TRUE;
acct_sm->aWhile = acct_sm->serverTimeout;
lib1x_message( MESS_DBG_SPECIAL, "%s: Sending Accounting UDP packet.", __func__);
}
if ( num_sent != size )
{
lib1x_message( MESS_ERROR_OK, "%s: Mismatch in send size!", __func__);
lib1x_message( MESS_ERROR_FATAL," NUM_SENT : %d . actual %d", num_sent, size );
return FALSE;
}
return TRUE;
}
int lib1x_acctsm_sendReqToServer( Global_Params * global)
{
Auth_Pae * auth_pae;
int size;
u_char * sendptr;
auth_pae = global->theAuthenticator;
lib1x_message( MESS_DBG_ACCT, " lib1x_acctsm_sendReqToServer================.");
//if ( auth_pae->sendreplyready )
{
/* temporary hack to use udp sockets TODO*/
sendptr = auth_pae->acct_sendBuffer + ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN;
size = auth_pae->acct_sendbuflen;
size -= ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN;
lib1x_nal_send_acct( auth_pae, auth_pae->global->TxRx->network_svr, (char *)sendptr, size );
lib1x_message( MESS_DBG_ACCT, " Sending Accouting information to server.");
//auth_pae->sendreplyready = FALSE;
}
return TRUE;
}
int lib1x_acct_request( Auth_Pae * auth_pae, unsigned int msg_type, int iTerminateCause)
{
struct radius_info * rinfo;
struct lib1x_radius_const * rconst;
Acct_SM * acct_sm = auth_pae->acct_sm;
int nas_port;
int nas_port_type;
u_char szAttr[4];
u_char szUTF8[6];
u_long ulUTF8Len;
u_char szOutput[64];
u_long ulOutput;
struct timeval tv;
struct timezone tz;
int val;
char *src;
nas_port = 0;
nas_port_type = LIB1X_80211_NAS_PORTTYPE; // IEEE 802.11
rinfo = auth_pae->rinfo; // get a handle
lib1x_message(MESS_DBG_ACCT, "Send Acct-Request to Radius Server");
rinfo->username_len = strlen((char *)rinfo->username);
auth_pae->global->TxRx->GlobalRadId ++;
rinfo->identifier = auth_pae->global->TxRx->GlobalRadId;
lib1x_create_reqauth( auth_pae );
//---- create the Accouting Request to radius server :
rconst = lib1x_radconst_create( auth_pae, auth_pae->acct_sendBuffer , LIB1X_RAD_ACCTREQ, rinfo->identifier,LIB1X_IT_UDPSOCK_ACCT);
if ( rinfo->username_len != 0 )
lib1x_radconst_addattr( rconst, LIB1X_RAD_USER_NAME , rinfo->username_len, rinfo->username);
if(msg_type != LIB1X_RADACCT_ACTION_ACCOUNT_ON)
{
// SCMARK
//lib1x_radconst_addattr( rconst, LIB1X_RAD_NAS_PORTTYPE, 4, (u_char * ) & nas_port_type ); //TODO
val = htonl( nas_port_type );
// SCMOD
lib1x_radconst_addattr( rconst, LIB1X_RAD_NAS_PORTTYPE, 4, (u_char * ) & val ); //TODO
src = (char *) rconst->nas_porttype;
memcpy( src, &val, sizeof(int) ); // jimmylin modify for unaligned access
//*( rconst->nas_porttype ) = htonl( nas_port_type );
//lib1x_radconst_addattr( rconst, LIB1X_RAD_CONNECTINFO, strlen( rinfo->connectinfo), rinfo->connectinfo );
lib1x_acct_UCS4_TO_UTF8( auth_pae->acct_sm->sessionId, (u_char*)szUTF8, &ulUTF8Len);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_SESSION_ID, ulUTF8Len, szUTF8);
}
//lib1x_message(MESS_DBG_ACCT, "==============================================\n");
//lib1x_message(MESS_DBG_ACCT, "auth_pae->acct_sm->sessionId = %d\n", auth_pae->acct_sm->sessionId);
//lib1x_hexdump2(MESS_DBG_ACCT, "lib1x_acct_request", szUTF8, ulUTF8Len, "Session-ID");
//lib1x_message(MESS_DBG_ACCT, "==============================================\n");
// Accounting Information
switch(msg_type)
{
case LIB1X_RADACCT_ACTION_ACCOUNT_START:
lib1x_L2N(LIB1X_RADACCT_STATUS_TYPE_START, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_STATUS_TYPE, 4, szAttr);
lib1x_L2N(LIB1X_RADACCT_AUTHENTIC_RADIUS, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_AUTHENTIC, 4, szAttr);
lib1x_message(MESS_DBG_ACCT, "LIB1X_RADACCT_ACTION_ACCOUNT_START");
break;
case LIB1X_RADACCT_ACTION_ACCOUNT_STOP:
lib1x_L2N(LIB1X_RADACCT_STATUS_TYPE_STOP, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_STATUS_TYPE, 4, szAttr);
//lib1x_control_QuerySTA(auth_pae->global, &Query_Stat);
lib1x_L2N(acct_sm->rx_bytes, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_INPUT_OCTETS, 4, szAttr);
lib1x_L2N(acct_sm->tx_bytes, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_OUTPUT_OCTETS, 4, szAttr);
lib1x_L2N(acct_sm->rx_packets, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_INPUT_PACKETS, 4, szAttr);
lib1x_L2N(acct_sm->tx_packets, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_OUTPUT_PACKETS, 4, szAttr);
//lib1x_L2N(0, szAttr);
//lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_INPUT_GIGAWORDS, 4, szAttr);
//lib1x_L2N(0, szAttr);
//lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_OUTPUT_GIGAWORDS, 4, szAttr);
lib1x_L2N(auth_pae->acct_sm->elapsedSessionTime, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_SESSION_TIME, 4, szAttr);
//ulTerminateCause = lib1x_acct_maperr_wlan2acct(auth_pae->global->akm_sm->ErrorRsn);
lib1x_L2N(iTerminateCause, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_TERMINATE_CAUSE, 4, szAttr);
lib1x_message(MESS_DBG_ACCT, "LIB1X_RADACCT_ACTION_ACCOUNT_STOP");
break;
case LIB1X_RADACCT_ACTION_ACCOUNT_ON:
lib1x_L2N(LIB1X_RADACCT_STATUS_TYPE_ACCOUNTING_ON, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_STATUS_TYPE, 4, szAttr);
//Use random number as session id
gettimeofday(&tv, &tz);
tv.tv_sec ^= getpid();
lib1x_acct_UCS4_TO_UTF8(tv.tv_sec, (u_char*)szOutput, &ulOutput);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_SESSION_ID, ulOutput, szOutput);
break;
case LIB1X_RADACCT_ACTION_INTERIM_UPDATE:
lib1x_L2N(LIB1X_RADACCT_STATUS_TYPE_INTERIM_UPDATE, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_STATUS_TYPE, 4, szAttr);
lib1x_control_QuerySTA(auth_pae->global);
//lib1x_message(MESS_DBG_ACCT, "tx_packets= %d", Query_Stat.tx_packets);
//lib1x_message(MESS_DBG_ACCT, "rx_packets= %d", Query_Stat.rx_packets);
//lib1x_message(MESS_DBG_ACCT, "tx_bytes= %d", Query_Stat.tx_bytes);
//lib1x_message(MESS_DBG_ACCT, "rx_bytes= %d", Query_Stat.rx_bytes);
lib1x_message(MESS_DBG_ACCT, "tx_packets= %d", auth_pae->global->theAuthenticator->acct_sm->tx_packets);
lib1x_message(MESS_DBG_ACCT, "rx_packets= %d", auth_pae->global->theAuthenticator->acct_sm->rx_packets);
lib1x_message(MESS_DBG_ACCT, "tx_bytes= %d", auth_pae->global->theAuthenticator->acct_sm->tx_bytes);
lib1x_message(MESS_DBG_ACCT, "rx_bytes= %d", auth_pae->global->theAuthenticator->acct_sm->rx_bytes);
lib1x_L2N(acct_sm->rx_bytes, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_INPUT_OCTETS, 4, szAttr);
lib1x_L2N(acct_sm->tx_bytes, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_OUTPUT_OCTETS, 4, szAttr);
lib1x_L2N(acct_sm->rx_packets, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_INPUT_PACKETS, 4, szAttr);
lib1x_L2N(acct_sm->tx_packets, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_OUTPUT_PACKETS, 4, szAttr);
//lib1x_L2N(0, szAttr);
//lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_INPUT_GIGAWORDS, 4, szAttr);
//lib1x_L2N(0, szAttr);
//lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_OUTPUT_GIGAWORDS, 4, szAttr);
lib1x_L2N(auth_pae->acct_sm->elapsedSessionTime, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_SESSION_TIME, 4, szAttr);
lib1x_message(MESS_DBG_ACCT, "LIB1X_RADACCT_ACTION_INTERIM_UPDATE");
break;
case LIB1X_RADACCT_ACTION_TERMINATE_CAUSE:
lib1x_L2N(iTerminateCause, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RADACCT_ACTION_TERMINATE_CAUSE, 4, szAttr);
lib1x_message(MESS_DBG_ACCT, "LIB1X_RADACCT_ACTION_TERMINATE_CAUSE");
break;
}
lib1x_radconst_addattr( rconst, LIB1X_RAD_NAS_IP_ADDRESS, 4, (u_char* ) &auth_pae->global->TxRx->ourip_inaddr );
if ( strlen(auth_pae->global->auth->rsNasPortId) )
lib1x_radconst_addattr( rconst, LIB1X_RAD_NAS_PORT_ID, strlen(auth_pae->global->auth->rsNasPortId), auth_pae->global->auth->rsNasPortId);
if(msg_type != LIB1X_RADACCT_ACTION_ACCOUNT_ON)
{
lib1x_radconst_addattr( rconst, LIB1X_RAD_NAS_PORT, 4, (u_char * ) & nas_port);
lib1x_radconst_addattr( rconst, LIB1X_RAD_NAS_IDENTIFIER, strlen((char *)rinfo->nas_identifier), rinfo->nas_identifier );
lib1x_L2N(0, szAttr);
lib1x_radconst_addattr( rconst, LIB1X_RAD_ACCT_DELAY_TIME, 4, szAttr);
#ifndef _ABOCOM
lib1x_print_etheraddr( (char *)szOutput, auth_pae->global->TxRx->oursvr_addr );
#else
lib1x_acct_MAC_TO_DASH_ASCII(auth_pae->global->TxRx->oursvr_addr, MacAddrLen, szOutput, &ulOutput);
#endif
lib1x_radconst_addattr( rconst, LIB1X_RAD_CALLED_STID, strlen((char *)szOutput), szOutput );
#ifndef _ABOCOM
lib1x_print_etheraddr( (char *)szOutput, auth_pae->supp_addr );
#else
lib1x_acct_MAC_TO_DASH_ASCII(auth_pae->supp_addr, MacAddrLen, szOutput, &ulOutput);
#endif
lib1x_radconst_addattr( rconst, LIB1X_RAD_CALLING_STID, strlen((char *)szOutput), szOutput );
}
lib1x_radconst_calradlength( rconst );
lib1x_create_reqauth_acct(auth_pae, rconst);
auth_pae->acct_sendbuflen = rconst->pktlen;
auth_pae->sendreplyready = TRUE;
lib1x_acctsm_sendReqToServer( auth_pae->global);
return TRUE;
}
u_long lib1x_acct_maperr_wlan2acct(u_long ulReason)
{
u_long retVal = unspec_reason;
switch(ulReason)
{
case unspec_reason:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case auth_not_valid:
retVal = LIB1X_ACCT_REASON_LOST_CARRIER;
break;
case deauth_lv_ss:
retVal = LIB1X_ACCT_REASON_LOST_CARRIER;
break;
case inactivity:
retVal = LIB1X_ACCT_REASON_IDLE_TIMEOUT;
break;
case ap_overload:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case class2_err:
retVal = LIB1X_ACCT_REASON_LOST_CARRIER;
break;
case class3_err:
retVal = LIB1X_ACCT_REASON_LOST_CARRIER;
break;
case disas_lv_ss:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case asoc_not_auth:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_invalid_info_element:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_MIC_failure:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_4_way_handshake_timeout:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_diff_info_element:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_multicast_cipher_not_valid:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_unicast_cipher_not_valid:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_AKMP_not_valid:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_unsupported_RSNE_version:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_invalid_RSNE_capabilities:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case RSN_ieee_802dot1x_failed:
retVal = LIB1X_ACCT_REASON_LOST_SERVICE;
break;
case session_timeout:
retVal = LIB1X_ACCT_REASON_SESSION_TIMEOUT;
}
return retVal;
}
void lib1x_acct_UCS4_TO_UTF8(u_long ud, u_char * pucUTF8, u_long * ulUTF8Len)
{
//From Unicode UCS-4 to UTF-8:
//Start with the Unicode number expressed as a decimal number and call this ud.
if( ud <128) //(7F hex)
{
*ulUTF8Len = 1;
pucUTF8[0] = (u_char)ud;
}
if( ud >=128 && ud<=2047)// (7FF hex) then UTF-8 is 2 bytes long.
{
*ulUTF8Len = 2;
pucUTF8[0] = 192 + (ud / 64);
pucUTF8[1] = 128 + (ud % 64);
}
if( ud >=2048 && ud<=65535)// (FFFF hex) then UTF-8 is 3 bytes long.
{
*ulUTF8Len = 3;
pucUTF8[0] = 224 + (ud / 4096);
pucUTF8[1] = 128 + ((ud / 64) % 64);
pucUTF8[2] = 128 + (ud % 64);
}
if( ud >=65536 && ud<=2097151)// (1FFFFF hex) then UTF-8 is 4 bytes long.
{
*ulUTF8Len = 4;
pucUTF8[0] = 240 + (ud / 262144);
pucUTF8[1] = 128 + ((ud / 4096) % 64);
pucUTF8[2] = 128 + ((ud / 64) % 64);
pucUTF8[3] = 128 + (ud % 64);
}
if( ud >=2097152 && ud<=67108863)// (3FFFFFF hex) then UTF-8 is 5 bytes long.
{
*ulUTF8Len = 5;
pucUTF8[0] = 248 + (ud / 16777216);
pucUTF8[1] = 128 + ((ud / 262144) % 64);
pucUTF8[2] = 128 + ((ud / 4096) % 64);
pucUTF8[3] = 128 + ((ud / 64) % 64);
pucUTF8[4] = 128 + (ud % 64);
}
if( ud >=67108864 && ud<=2147483647)// (7FFFFFFF hex) then UTF-8 is 6 bytes long.
{
*ulUTF8Len = 6;
pucUTF8[0] = 252 + (ud / 1073741824);
pucUTF8[1] = 128 + ((ud / 16777216) % 64);
pucUTF8[2] = 128 + ((ud / 262144) % 64);
pucUTF8[3] = 128 + ((ud / 4096) % 64);
pucUTF8[4] = 128 + ((ud / 64) % 64);
pucUTF8[5] = 128 + (ud % 64);
}
}
#ifndef COMPACK_SIZE
void lib1x_acct_MAC_TO_UTF8(u_char * pucInput, u_long ulInput, u_char * pucOutput, u_long * ulOutputLen)
{
//From Unicode UCS-4 to UTF-8:
//Start with the Unicode number expressed as a decimal number and call this ud.
u_long ulIndex;
int i = 0;
u_long ulOutLen = 0;
for(ulIndex = 0;ulIndex < ulInput; ulIndex++)
{
printf("ulIndex = %d\n", (int)ulIndex);
if(pucInput[ulIndex] < 128)
{
pucOutput[i++] = pucInput[ulIndex];
ulOutLen++;
}
else
{
pucOutput[i++] = 192 + (pucInput[ulIndex] / 64);
pucOutput[i++] = 128 + (pucInput[ulIndex] % 64);
ulOutLen +=2;
}
printf("ulOutputLen = %d\n", (int)ulOutLen);
}
*ulOutputLen = ulOutLen;
printf("ulOutputLen = %d\n", (int)*ulOutputLen);
}
#endif
void lib1x_acct_MAC_TO_DASH_ASCII(u_char * pucInput, u_long ulInput, u_char * pucOutput, u_long * ulOutputLen)
{
//From Unicode UCS-4 to UTF-8:
//Start with the Unicode number expressed as a decimal number and call this ud.
/*
u_long ulIndex;
int i = 0;
u_long ulOutLen = 0;
for(ulIndex = 0;ulIndex < ulInput; ulIndex++)
{
pucOutput[i++] = ((pucInput[ulIndex]& 0xf0)>>4) + 0x30;
pucOutput[i++] = ((pucInput[ulIndex]& 0x0f)) + 0x30;
ulOutLen +=2;
}
*ulOutputLen = ulOutLen;
*/
sprintf((char *)pucOutput,"%02x-%02x-%02x-%02x-%02x-%02x", pucInput[0], pucInput[1], pucInput[2],
pucInput[3], pucInput[4], pucInput[5] );
*ulOutputLen = 17;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,470 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_bauth_sm.c
// Programmer : Arunesh Mishra
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
// Implementation of the Backend Authentication State Machine.
//--------------------------------------------------
#include "1x_common.h"
#include "1x_auth_pae.h"
#include "1x_eapol.h"
#include "1x_nal.h"
#include "1x_radius.h"
#include "1x_bauth_sm.h"
// Some funtion prototype decls
void lib1x_exec_bauthsm_request( Auth_Pae * , Global_Params * , Bauth_SM * );
void lib1x_exec_bauthsm_response( Auth_Pae * , Global_Params * , Bauth_SM * );
void lib1x_exec_bauthsm_success( Auth_Pae * , Global_Params * , Bauth_SM * );
void lib1x_exec_bauthsm_fail( Auth_Pae * , Global_Params * , Bauth_SM * );
void lib1x_exec_bauthsm_timeout( Auth_Pae * , Global_Params * , Bauth_SM * );
void lib1x_exec_bauthsm_idle( Auth_Pae * , Global_Params * , Bauth_SM * );
void lib1x_exec_bauthsm_initialize( Auth_Pae * , Global_Params * , Bauth_SM * );
void lib1x_bauthsm_txReq( Global_Params * global, int identifier );
void lib1x_bauthsm_sendRespToServer( Global_Params * global, int identifier );
int lib1x_acctsm_sendReqToServer( Global_Params * global);
//--------------------------------------------------
// Initialize it.
//--------------------------------------------------
void lib1x_bauthsm_init( Bauth_SM * bauth_sm, int maxReq, int aWhile )
{
assert( bauth_sm != NULL );
bauth_sm->state = basm_Initialize;
bauth_sm->reqCount = 0;
bauth_sm->rxResp = FALSE;
bauth_sm->aSuccess = FALSE;
bauth_sm->aFail = FALSE;
bauth_sm->aReq = FALSE;
bauth_sm->idFromServer = -1; // Neg value = invalid value
// These are the constants initialized to their respective default values.
bauth_sm->suppTimeout = aWhile;
bauth_sm->serverTimeout = aWhile;
bauth_sm->maxReq = maxReq;
}
//--------------------------------------------------
// Handles transitions and inits for the transitions.
//--------------------------------------------------
void lib1x_bauthsm( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
BOOLEAN transitionDone;
transitionDone = lib1x_trans_bauthsm( auth_pae, global, bauth_sm );
if ( transitionDone )
{
lib1x_exec_bauthsm( auth_pae, global, bauth_sm );
}
}
//--------------------------------------------------
// lib1x_trans_bauthsm :
// This function implements a single transition for the Backend Authentication
// State Machine. .. but not the initialization !!
//--------------------------------------------------
BOOLEAN lib1x_trans_bauthsm( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
// Global Transitions first !
if ( ( global->portControl != pmt_Auto ) || ( global->initialize ) || ( global->authAbort ) )
{
bauth_sm->state = basm_Initialize;
return TRUE;
}
switch ( bauth_sm->state )
{
case basm_Request :
if ( bauth_sm->rxResp )
{
bauth_sm->state = basm_Response;
return TRUE;
}
if ( ( global->timers->aWhile == 0 ) && ( bauth_sm->reqCount != bauth_sm->maxReq ) )
{
// No change in state
return TRUE;
}
if ( ( global->timers->aWhile == 0 ) && ( bauth_sm->reqCount >= bauth_sm->maxReq ) )
{
bauth_sm->state = basm_Timeout;
return TRUE;
}
break;
case basm_Response:
//added by Emily 2003/11/26
if ( bauth_sm->rxResp )
{
bauth_sm->state = basm_Response;
return TRUE;
}
if ( bauth_sm->aReq )
{
bauth_sm->state = basm_Request;
return TRUE;
}
if ( global->timers->aWhile == 0 )
{
bauth_sm->state = basm_Timeout;
return TRUE;
}
if ( bauth_sm->aFail )
{
bauth_sm->state = basm_Fail;
return TRUE;
}
if ( bauth_sm->aSuccess )
{
bauth_sm->state = basm_Success;
return TRUE;
}
break;
case basm_Success:
bauth_sm->state = basm_Idle ; // Unconditional Transfer !
return TRUE;
break;
case basm_Timeout:
bauth_sm->state = basm_Idle ; // Unconditional Transfer !
return TRUE;
break;
case basm_Initialize:
bauth_sm->state = basm_Idle ; // Unconditional Transfer !
return TRUE;
break;
case basm_Fail:
bauth_sm->state = basm_Idle ; // Unconditional Transfer !
return TRUE;
break;
case basm_Idle:
if ( global->authStart )
{
bauth_sm->state = basm_Response;
return TRUE;
}
break;
}
return FALSE;
}
//--------------------------------------------------
// lib1x_exec_bauthsm:
// This function implements the init functions that have to be executed on
// entry to a state.
//--------------------------------------------------
void lib1x_exec_bauthsm( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
switch ( bauth_sm->state )
{
case basm_Request :
lib1x_exec_bauthsm_request( auth_pae, global, bauth_sm );
break;
case basm_Response:
lib1x_exec_bauthsm_response( auth_pae, global, bauth_sm );
break;
case basm_Success:
lib1x_exec_bauthsm_success( auth_pae, global, bauth_sm );
break;
case basm_Timeout:
lib1x_exec_bauthsm_timeout( auth_pae, global, bauth_sm );
break;
case basm_Initialize:
lib1x_exec_bauthsm_initialize( auth_pae, global, bauth_sm );
break;
case basm_Fail:
lib1x_exec_bauthsm_fail( auth_pae, global, bauth_sm );
break;
case basm_Idle:
lib1x_exec_bauthsm_idle( auth_pae, global, bauth_sm );
break;
}
}
// Inits for the request state.
void lib1x_exec_bauthsm_request( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
lib1x_message(MESS_DBG_SPECIAL,"BAUTHSM> Entering REQ state.");
global->currentId = bauth_sm->idFromServer;
lib1x_bauthsm_txReq( global, global->currentId ); // TODO
global->timers->aWhile = bauth_sm->suppTimeout;
bauth_sm->reqCount ++;
}
// Response state inits.
void lib1x_exec_bauthsm_response( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
lib1x_message(MESS_DBG_SPECIAL,"BAUTHSM> Entering RESPONSE state.");
bauth_sm->aReq = bauth_sm->aSuccess = FALSE;
global->authTimeout = FALSE;
bauth_sm->rxResp = bauth_sm->aFail = FALSE;
global->timers->aWhile = bauth_sm->serverTimeout;
bauth_sm->reqCount = 0;
lib1x_bauthsm_sendRespToServer(global, global->currentId); // TODO
}
// Success state inits.
void lib1x_exec_bauthsm_success( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
global->currentId = bauth_sm->idFromServer;
lib1x_auth_txCannedSuccess( auth_pae, global->currentId ); //TODO
global->authSuccess = TRUE;
lib1x_message( MESS_DBG_SPECIAL,"BAUTHSM> SUCCESS STATE.");
}
// Fail state inits.
void lib1x_exec_bauthsm_fail( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
global->currentId = bauth_sm->idFromServer;
lib1x_auth_txCannedFail( auth_pae, global->currentId ); // TODO
global->authFail = TRUE;
}
// Timeout state inits.
void lib1x_exec_bauthsm_timeout( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
if ( global->portStatus == pst_Unauthorized )
{
lib1x_auth_txCannedFail( auth_pae, global->currentId ); //TODO
}
global->authTimeout = TRUE;
}
// Idle state inits.
void lib1x_exec_bauthsm_idle( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
global->authStart = FALSE;
bauth_sm->reqCount = 0;
}
// Initialize state inits.
void lib1x_exec_bauthsm_initialize( Auth_Pae * auth_pae, Global_Params * global, Bauth_SM * bauth_sm )
{
lib1x_bauthsm_abortAuth(); //TODO
global->authAbort = FALSE;
}
//----------------------------------------
// lib1x_bauthsm_abortAuth()
// TODO
// bauthsm releases any system resources and
// informs auth sm of auth abort.
//----------------------------------------
void lib1x_bauthsm_abortAuth()
{
lib1x_message(MESS_ERROR_OK,"Backend Authentication SM: abortAuth: Authentication Aborted.");
}
//----------------------------------------
// txReq(x): EAPOL frame of type
// EAP Request
//----------------------------------------
void lib1x_bauthsm_txReq( Global_Params * global, int identifier )
{
struct lib1x_eapol * eapol;
struct lib1x_eap * eap;
struct lib1x_ethernet * eth_hdr;
Auth_Pae * auth_pae;
int size;
u_char * packet;
struct pktbuf * bufpkt;
struct lib1x_packet printPkt;
// Note: Every time this authpae sends a packet the SAME send buffer is used.
//
auth_pae = global->theAuthenticator;
if ( auth_pae->sendreplyready ) /* if we prefabricated */
{
packet = auth_pae->sendBuffer;
size = auth_pae->sendbuflen;
lib1x_message(MESS_DBG_BSM, "Sending PREFABRICATED EAP packet to SUPPLICANT");
printPkt.data = auth_pae->sendBuffer;
printPkt.caplen = size;
#ifdef RTL_WPA2_PREAUTH
if (global->RSNVariable.isPreAuth) {
lib1x_nal_send(auth_pae->global->TxRx->network_ds, (char *)auth_pae->sendBuffer, size );
} else
lib1x_nal_send(auth_pae->global->TxRx->network_supp, (char *)auth_pae->sendBuffer, size );
#else
lib1x_nal_send(auth_pae->global->TxRx->network_supp, (char *)auth_pae->sendBuffer, size );
#endif
auth_pae->sendreplyready = FALSE;
return;
}
else lib1x_message(MESS_ERROR_FATAL," Attempt to send non-prefabricated packet");
packet = auth_pae->sendBuffer;
bufpkt = & auth_pae->fromsvr; // i.e. to supplicant
if ( bufpkt->length <= 0 )
{
lib1x_message(MESS_ERROR_OK," lib1x_bauthsm_txReq: Request for Xmit .. but no packet buffered !");
return;
}
size = ETHER_HDRLEN + sizeof( struct lib1x_eapol ) + sizeof( struct lib1x_eap ) + 1 + bufpkt->length;
if ( size >= LIB1X_AP_SENDBUFLEN ) size = LIB1X_AP_SENDBUFLEN - 1 ;
bzero( auth_pae->sendBuffer, size );
eth_hdr = ( struct lib1x_ethernet * ) packet;
memcpy ( eth_hdr->ether_dhost , auth_pae->supp_addr, ETHER_ADDRLEN );
memcpy ( eth_hdr->ether_shost , auth_pae->global->TxRx->oursupp_addr, ETHER_ADDRLEN );
eapol = ( struct lib1x_eapol * ) ( packet + ETHER_HDRLEN ) ;
// We subtract 2 because of the common type field
#ifdef RTL_WPA2_PREAUTH
if (global->RSNVariable.isPreAuth)
eth_hdr->ether_type = htons(PREAUTH_ETHER_EAPOL_TYPE);
else
eth_hdr->ether_type = htons(LIB1X_ETHER_EAPOL_TYPE);
#else
eth_hdr->ether_type = htons(LIB1X_ETHER_EAPOL_TYPE);
#endif
eapol->protocol_version = LIB1X_EAPOL_VER;
eapol->packet_type = LIB1X_EAPOL_EAPPKT;
eap = (struct lib1x_eap * ) ( ( (u_char *) eapol) + LIB1X_EAPOL_HDRLEN );
eap->code = LIB1X_EAP_REQUEST;
eap->identifier = identifier;
eap->length = htons( LIB1X_EAP_HDRLEN + bufpkt->length );
eapol->packet_body_length = htons( LIB1X_EAP_HDRLEN + bufpkt->length );
memcpy( ( ( u_char *) eap ) + LIB1X_EAP_HDRLEN, bufpkt->pkt, bufpkt->length );
lib1x_message(MESS_DBG_AUTH, "Sending Request EAP packet to Supplicant");
#ifdef RTL_WPA2_PREAUTH
if (global->RSNVariable.isPreAuth) {
lib1x_nal_send( auth_pae->global->TxRx->network_ds, (char *)auth_pae->sendBuffer, size );
} else
lib1x_nal_send( auth_pae->global->TxRx->network_supp, (char *)auth_pae->sendBuffer, size );
#else
lib1x_nal_send( auth_pae->global->TxRx->network_supp, (char *)auth_pae->sendBuffer, size );
#endif
}
//----------------------------------------
// sendRespToServer(x): frame of type
// EAP Response to server
//----------------------------------------
void lib1x_bauthsm_sendRespToServer( Global_Params * global, int identifier )
{
struct lib1x_eapol * eapol;
struct lib1x_eap * eap;
struct lib1x_ethernet * eth_hdr;
Auth_Pae * auth_pae;
int size;
u_char * packet;
struct pktbuf * bufpkt;
struct lib1x_packet printPkt;
u_char * sendptr;
// Note: Every time this authpae sends a packet the SAME send buffer is used.
//
auth_pae = global->theAuthenticator;
if ( auth_pae->sendreplyready )
{
packet = auth_pae->sendBuffer;
size = auth_pae->sendbuflen;
lib1x_message(MESS_DBG_BSM, "Sending PREFABRICATED EAP packet to Server");
printPkt.data = auth_pae->sendBuffer;
printPkt.caplen = size;
/* temporary hack to use udp sockets TODO*/
sendptr = auth_pae->sendBuffer + ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN;
size -= ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN;
lib1x_nal_send( auth_pae->global->TxRx->network_svr, (char *)sendptr, size );
lib1x_message( MESS_DBG_BSM, " Sending RADIUS EAP Response to server.");
auth_pae->sendreplyready = FALSE;
return;
}
else lib1x_message(MESS_ERROR_FATAL," Attempt to send non-prefabricated packet");
packet = auth_pae->sendBuffer;
bufpkt = &auth_pae->fromsupp; // i.e. to server
if ( bufpkt->length <= 0 )
{
lib1x_message(MESS_ERROR_OK," lib1x_bauthsm_sendRespToServer: Request for Xmit .. but no packet buffered !");
return;
}
size = ETHER_HDRLEN + sizeof( struct lib1x_eapol ) + sizeof( struct lib1x_eap ) + 1 + bufpkt->length;
if ( size >= LIB1X_AP_SENDBUFLEN ) size = LIB1X_AP_SENDBUFLEN - 1 ;
bzero( auth_pae->sendBuffer, size );
eth_hdr = ( struct lib1x_ethernet * ) packet;
memcpy ( eth_hdr->ether_dhost , auth_pae->global->TxRx->svr_addr, ETHER_ADDRLEN );
memcpy ( eth_hdr->ether_shost , auth_pae->global->TxRx->oursvr_addr, ETHER_ADDRLEN );
eapol = ( struct lib1x_eapol * ) ( packet + ETHER_HDRLEN ) ;
// We subtract 2 because of the common type field
eth_hdr->ether_type = htons(LIB1X_ETHER_EAPOL_TYPE);
eapol->protocol_version = LIB1X_EAPOL_VER;
eapol->packet_type = LIB1X_EAPOL_EAPPKT;
eap = (struct lib1x_eap * ) ( ( (u_char *) eapol) + LIB1X_EAPOL_HDRLEN );
eap->code = LIB1X_EAP_REQUEST;
eap->identifier = identifier;
eap->length = LIB1X_EAP_HDRLEN + bufpkt->length;
eapol->packet_body_length = LIB1X_EAP_HDRLEN + bufpkt->length;
memcpy( ( ( u_char *) eap ) + LIB1X_EAP_HDRLEN, bufpkt->pkt, bufpkt->length );
lib1x_message(MESS_DBG_AUTH, "Sending Response EAP packet to Server");
lib1x_nal_send( auth_pae->global->TxRx->network_svr, (char *)auth_pae->sendBuffer, size );
}

View File

@ -0,0 +1,80 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_cdsm.c
// Programmer : Arunesh Mishra
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
// Controlled Directions State Machine
//--------------------------------------------------
#include "1x_common.h"
#include "1x_auth_pae.h"
#include "1x_cdsm.h"
#include <stddef.h>
//--------------------------------------------------
// init function for the Controlled Directions State Machine.
//--------------------------------------------------
void lib1x_cdsm_init( CtrlDirSM * ctrl_sm )
{
assert( ctrl_sm != NULL );
ctrl_sm->state = cdsm_In_Or_Both;
ctrl_sm->adminControlledDirections = dir_Both; // TODO: Not sure .. how this would be initialised.
ctrl_sm->operControlledDirections = dir_Both;
}
//--------------------------------------------------
// lib1x_trans_dirsm :
// One transition of the Controlled Directions State Machine and also the initializations
//--------------------------------------------------
void lib1x_trans_cdsm( Auth_Pae * auth_pae, Global_Params * global, CtrlDirSM * dirsm)
{
if ( dirsm->state == cdsm_Force_Both )
{
if ( global->initialize )
{
dirsm->state = cdsm_In_Or_Both;
dirsm->operControlledDirections = dirsm->adminControlledDirections;
return;
}
if ( global->portEnabled && !dirsm->bridgeDetected )
{
dirsm->state = cdsm_In_Or_Both;
dirsm->operControlledDirections = dirsm->adminControlledDirections;
return;
}
}
if ( dirsm->state == cdsm_In_Or_Both )
{
if ( dirsm->operControlledDirections != dirsm->adminControlledDirections )
{
// Same state again but perform initializations
dirsm->operControlledDirections = dirsm->adminControlledDirections;
return;
}
if ( !global->portEnabled || dirsm->bridgeDetected )
{
dirsm->state = cdsm_Force_Both;
dirsm->operControlledDirections = dir_Both;
}
}
}

View File

@ -0,0 +1,353 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_common.c
// Programmer : Arunesh Mishra
// Common routines
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
#ifdef _RTL_WPA_WINDOWS
#else
#include "1x_common.h"
#endif
#include <stdio.h>
//#define ALLOW_ERR_OK
//#define ALLOW_ERR_FATAL
//#define ALLOW_DBG_AUTH /* state machines et al */
//#define ALLOW_DBG_AUTHSM
//#define ALLOW_DBG_AUTHNET /* the network packets part of authenticator */
//#define ALLOW_DBG_KRCSM
//#define ALLOW_DBG_KXSM
//#define ALLOW_AUTH_LOG
//#define ALLOW_DBG_NAL
//#define ALLOW_DBG_BSM
//#define ALLOW_DBG_RAD
//#define ALLOW_DBG_SPECIAL
//#define ALLOW_DBG_DAEMON
//#define ALLOW_DBG_KEY_MANAGE
//#define ALLOW_DBG_CONTROL
//#define ALLOW_DBG_PTSM
//#define ALLOW_DBG_RSNINFO
//#define ALLOW_DBG_CONFIG
//#define ALLOW_DBG_ACCT
//#define ALLOW_DBG_FIFO
//#define ALLOW_DBG_SUPP
#ifndef DEBUG_DISABLE
// Message printing routine.
//--------------------------------------------------
void lib1x_message( int type, char * msg, ... )
{
va_list ap;
static char buf[MESS_BUF_SIZE]; // made static for optimization
va_start(ap, msg);
vsnprintf(buf, sizeof(buf) - 1, msg, ap);
switch( type )
{
#ifdef ALLOW_ERR_OK
case MESS_ERROR_OK:
printf("\n ERROR OK: %s", buf);
break;
#endif
#ifdef ALLOW_ERR_FATAL
case MESS_ERROR_FATAL:
fprintf(stderr, "\n FATAL :%s", buf );
//exit(0);
break;
#endif
#ifdef ALLOW_DBG_AUTH
case MESS_DBG_AUTH:
fprintf(stderr, "\n Authenticator: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_AUTHNET
case MESS_DBG_AUTHNET:
fprintf(stderr, "\n Auth Network : %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_AUTHSM
case MESS_DBG_AUTHSM:
fprintf(stderr, "\n Auth States: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_KRCSM
case MESS_DBG_KRCSM:
fprintf(stderr, "\n Key Receive State Machine: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_KXSM
case MESS_DBG_KXSM:
fprintf(stderr, "\n Key Transmit State Machine: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_AUTH_LOG
case MESS_AUTH_LOG:
fprintf(stderr, "\n Authenticator Log: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_NAL
case MESS_DBG_NAL:
fprintf(stderr, "\n NAL DEBUG: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_BSM
case MESS_DBG_BSM:
fprintf(stderr, "\n Bauthsm DEBUG: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_RAD
case MESS_DBG_RAD:
fprintf(stderr, "\n Radius DEBUG: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_PTSM
case MESS_DBG_PTSM:
printf("\n PTSM Debuf: %s", buf);
break;
#endif
#ifdef ALLOW_DBG_DAEMON
case MESS_DBG_DAEMON:
fprintf(stderr, "\n DAEMON DEBUG: %s",buf );
fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_SPECIAL
case MESS_DBG_SPECIAL:
printf("\n Special Debug:%s\n", buf);
break;
#endif
#ifdef ALLOW_DBG_KEY_MANAGE
case MESS_DBG_KEY_MANAGE:
printf("\n Key Management DEBUG: %s", buf);
break;
#endif
#ifdef ALLOW_DBG_CONTROL
case MESS_DBG_CONTROL:
printf("\n Control Debug: %s", buf);
//fprintf(stderr, "\n CONTROL DEBUG: %s",buf );
//fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_RSNINFO
case MESS_DBG_RSNINFO:
printf("\n RSNINFO Debug: %s", buf);
//fprintf(stderr, "\n CONTROL DEBUG: %s",buf );
//fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_CONFIG
case MESS_DBG_CONFIG:
printf("\n Config Debug: %s", buf);
//fprintf(stderr, "\n CONTROL DEBUG: %s",buf );
//fflush(stderr);
break;
#endif
#ifdef ALLOW_DBG_ACCT
case MESS_DBG_ACCT:
printf("\n Acct Debug: %s", buf);
break;
#endif
#ifdef ALLOW_DBG_FIFO
case MESS_DBG_FIFO:
printf("\n Fifo Debug: %s", buf);
break;
#endif
#ifdef ALLOW_DBG_SUPP
case MESS_DBG_SUPP:
printf("\n SUPP Debug: %s", buf);
break;
#endif
}
va_end(ap);
}
/* better pass argument as a multiple of eight */
void lib1x_hexdump( FILE * fdesc, u_char * pkt, int numBytes )
{
int i;
fprintf( fdesc, "\n\n Packet Dump \n");
for ( i = 0; i < numBytes; i += 8 )
{
fprintf(fdesc, " %02X : %02X %02X %02X %02X %02X %02X %02X %02X \n", i, pkt[i], pkt[i+1], pkt[i+2], pkt[i+3],
pkt[i+4], pkt[i+5], pkt[i+6], pkt[i+7] );
}
fprintf(fdesc, "\n\n");
}
void lib1x_totext_authpaestate( FILE * fdesc, AUTH_PAE_STATE state )
{
switch( state )
{
case apsm_Initialize :fprintf(fdesc, "Initialize"); break;
case apsm_Disconnected :fprintf(fdesc, "Disconnected"); break;
case apsm_Connecting :fprintf(fdesc, "Connecting"); break;
case apsm_Authenticating :fprintf(fdesc, "Authenticating"); break;
case apsm_Authenticated :fprintf(fdesc, "Authenticated"); break;
case apsm_Aborting :fprintf(fdesc, "Aborting"); break;
case apsm_Held :fprintf(fdesc, "Held"); break;
case apsm_Force_Auth :fprintf(fdesc, "Force_Auth"); break;
case apsm_Force_Unauth :fprintf(fdesc, "Force_Unauth"); break;
}
}
void lib1x_totext_bauthsmstate( FILE * fdesc, BAUTH_SM_STATE state )
{
switch( state )
{
case basm_Request :fprintf(fdesc, "Request "); break;
case basm_Response :fprintf(fdesc, "Response "); break;
case basm_Success :fprintf(fdesc, "Success"); break;
case basm_Fail :fprintf(fdesc, "Fail"); break;
case basm_Timeout :fprintf(fdesc, "Timeout"); break;
case basm_Idle :fprintf(fdesc, "Idle"); break;
case basm_Initialize :fprintf(fdesc, "Initialize"); break;
}
}
void lib1x_chardump( FILE * fdesc, u_char * pkt, int numBytes )
{
int i;
fprintf( fdesc, "\n\n Packet Dump : CHAR\n");
for ( i = 0; i < numBytes; i += 8 )
{
fprintf(fdesc, " %02X : %02X '%c' %02X '%c' %02X '%c' %02X '%c' %02X '%c' %02X '%c' %02X '%c' %02X '%c' \n", i, pkt[i], pkt[i], pkt[i+1], pkt[i+ 1], pkt[i+2], pkt[i+2], pkt[i+3], pkt[i+3],
pkt[i+4],pkt[i+4], pkt[i+5],pkt[i+5], pkt[i+6],pkt[i+6], pkt[i+7], pkt[i+7] );
}
fprintf(fdesc, "\n\n");
}
void lib1x_hexdump2(int type, char *fun, u_char *buf, int size, char *comment)
{
int i;
lib1x_message(type, "$$ %s $$: %s", fun, comment);
if(type)
{
if (buf != NULL /*&& EAPOL_DEBUG >=2 */) {
lib1x_message(type, "\tMessage is %d bytes %x hex", size, size);
for (i = 0; i < size; i++) {
if (i % 16 == 0) printf("\n\t\t");
printf("%2x ", *(buf+i));
}
}
printf("\n");
}
}
void lib1x_PrintAddr(u_char * ucAddr)
{
#ifdef ALLOW_DBG_SPECIAL
int i;
for(i=0 ;i<6; i++)
printf("%2x ", *(ucAddr+i));
printf("\n");
#endif
}
#ifdef _ABOCOM
void lib1x_abocom(u_char *pucAddr, int ulCommandType)
{
u_char szCommand[256];
memset(szCommand, 0, sizeof szCommand);
switch(ulCommandType)
{
case ABOCOM_ADD_STA:
sprintf(szCommand, "acl -a %02x:%02x:%02x:%02x:%02x:%02x",
pucAddr[0], pucAddr[1], pucAddr[2], pucAddr[3], pucAddr[4], pucAddr[5]);
break;
case ABOCOM_DEL_STA:
sprintf(szCommand, "acl -d %02x:%02x:%02x:%02x:%02x:%02x",
pucAddr[0], pucAddr[1], pucAddr[2], pucAddr[3], pucAddr[4], pucAddr[5]);
break;
}
printf("\n============================================\n");
printf(szCommand);
printf("\n==========================================\n");
system(szCommand);
}
#endif
#define PRINT_BOOLEAN(s,val) printf("%s = %s\n", s, (val)?"TRUE":"FALSE" );
#define PRINT_INT(s,val) printf("%s = %d\n", s, val);
void DUMP_GLOBAL_PARAMS( Global_Params *g, u_char *exp )
{
u_char *p = g->CurrentAddress;
printf("- %s - %02x:%02x:%02x:%02x:%02x:%02x -\n", exp, p[0], p[1], p[2], p[3], p[4], p[5]);
printf("g->authStart = %d\n", g->authStart );
printf("g->authSuccess = %d\n", g->authSuccess );
printf("g->currentId = %d\n", g->currentId );
printf("g->portEnabled = %d\n", g->portEnabled );
printf("g->receivedId = %d\n", g->receivedId );
printf("g->reAuthenticate = %d\n", g->reAuthenticate );
printf("g->AuthKeyMethod = %d\n", g->AuthKeyMethod );
printf("g->PreshareKeyAvaliable = %d\n", g->PreshareKeyAvaliable );
printf("g->MaxRetryCounts = %d\n", g->MaxRetryCounts );
printf("g->EventId = %d\n", g->EventId );
printf("g->portSecure = %d\n", g->portSecure );
printf("g->DescriptorType = %d\n", g->DescriptorType );
printf("g->KeyDescriptorVer = %d\n", g->KeyDescriptorVer );
}
#endif
void lib1x_print_etheraddr( char * s, u_char * addr )
{
sprintf(s,"%02x%02x%02x%02x%02x%02x", addr[0], addr[1], addr[2], addr[3], addr[4],
addr[5] );
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_eap.c
// Programmer : Arunesh Mishra
//
// Extensible Authentication Protocol routines
// RFC 2284 : http://www.ietf.org
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#include "1x_eap.h"

View File

@ -0,0 +1,82 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_eapol.c
// Programmer : Arunesh Mishra
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#include "1x_eapol.h"
//--------------------------------------------------
// lib1x_construct_eapol_frame :
// This manually constucts the ethernet frame
// We cannot use libnet routines for some obvious
// reasons ..maybe someday this will find its way
// there
//--------------------------------------------------
void lib1x_construct_eapol_frame( Lib1x_Eapol_Header * the_header , u_char * packet , u_char * eapol_body, u_char * eapol_body_length)
{
int packet_size;
struct libnet_ethernet_hdr eth_hdr;
if ( the_header == NULL )
{
// Error handling here
printf("lib1x_construct_eapol_frame: Fatal .. received null argument ");
exit(1);
}
packet_size = LIB1x_EAPOL_HDR_LEN + LIBNET_ETH_H + the_header->packet_body_length_int ;
// Get memory for the packet
if (libnet_init_packet( packet_size, &packet) == -1 )
{
libnet_error( LIBNET_ERR_FATAL, "libnet_init_packet failed\n");
}
if ( the_header->eth_dst == NULL || the_header->eth_src == NULL )
{
// Error handling here
printf("lib1x_construct_eapol_frame: Fatal .. received null argument ");
exit(1);
}
// The best place to put eapol header construction would be in libnet itself !!!
// No idea what type of ethernet packet this is.
//
// Build the entire packet here ::
if (!buf)
{
printf("lib1x_construct_eapol_frame: Fatal .. received null argument ");
exit (1);
}
memcpy(eth_hdr.ether_dhost, the_header->eth_dst, the_header->eth_dst_len); /* destination address */
memcpy(eth_hdr.ether_shost, the_header->eth_src, the_header->eth_src_len); /* source address */
eth_hdr.ether_type = htons(ETHERTYPE_IP); /* packet type : TODO incorrect currently */
memcpy(packet + LIBNET_ETH_H, the_header, LIB1x_EAPOL_HDR_LEN);
memcpy(packet + LIBNET_ETH_H + LIB1X_EAPOL_HDR_LEN , eapol_body, eapol_body_length);
memcpy(packet, &eth_hdr, sizeof(eth_hdr));
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,820 @@
/* This is an independent implementation of the encryption algorithm: */
/* */
/* RIJNDAEL by Joan Daemen and Vincent Rijmen */
/* */
/* which is a candidate algorithm in the Advanced Encryption Standard */
/* programme of the US National Institute of Standards and Technology. */
/* */
/* Copyright in this implementation is held by Dr B R Gladman but I */
/* hereby give permission for its free direct or derivative use subject */
/* to acknowledgment of its origin and compliance with any conditions */
/* that the originators of the algorithm place on its exploitation. */
/* */
/* Dr Brian Gladman (gladman@seven77.demon.co.uk) 14th January 1999 */
#include "stdafx.h"
#include <time.h>
#include <string.h>
#include <assert.h>
/*#include "aes_defs.h" */
#ifdef _SHOW_
#define _VERBOSE_ 1
#elif !defined(_VERBOSE_)
#define _VERBOSE_ 0
#endif
// david, move define to Makefile
// kenny
//#define BIG_ENDIAN 1
#if defined(__BORLANDC__) /* show what compiler we used */
#define COMPILER_ID "Borland"
//#define LITTLE_ENDIAN 1
// modified by chilong
//move define to Makefile
//#define AUTH_LITTLE_ENDIAN 1
#elif defined(_MSC_VER)
#define COMPILER_ID "Microsoft"
//#define LITTLE_ENDIAN 1
// modified by chilong
//move define to Makefile
//#define AUTH_LITTLE_ENDIAN 1
#elif defined(__GNUC__)
#define COMPILER_ID "GNU"
/* marked by chilong
#ifndef BIG_ENDIAN // assume gcc = little-endian, unless told otherwise
#define LITTLE_ENDIAN 1
#endif
*/
// modified by chilong
//move define to Makefile
//#ifndef AUTH_BIG_ENDIAN // assume gcc = little-endian, unless told otherwise
//#define AUTH_LITTLE_ENDIAN 1
//#endif
// modified by chilong
#else /* assume big endian, if compiler is unknown */
#define COMPILER_ID "Unknown"
#endif
/* 1. Standard types for AES cryptography source code */
typedef unsigned char u08b; /* an 8 bit unsigned character type */
typedef unsigned short u16b; /* a 16 bit unsigned integer type */
typedef unsigned long u32b; /* a 32 bit unsigned integer type */
#ifndef _RTL_WPA_WINDOW
typedef int bool;
#endif
/* 2. Standard interface for AES cryptographic routines */
/* These are all based on 32-bit unsigned values and will therefore */
/* require endian conversions for big-endian architectures */
#ifdef __cplusplus
extern "C"
{
#endif
u32b * AES_SetKey (const u32b in_key[ ], const u32b key_len);
void AES_Encrypt(const u32b in_blk[4], u32b out_blk[4]);
void AES_Decrypt(const u32b in_blk[4], u32b out_blk[4]);
#ifdef __cplusplus
};
#endif
/* 3. Basic macros for speeding up generic operations */
/* Circular rotate of 32 bit values */
#ifdef _MSC_VER
#include <stdlib.h>
#pragma intrinsic(_lrotr,_lrotl)
#define rotr(x,n) _lrotr(x,n)
#define rotl(x,n) _lrotl(x,n)
#else
#define rotr(x,n) (((x) >> ((int)(n))) | ((x) << (32 - (int)(n))))
#define rotl(x,n) (((x) << ((int)(n))) | ((x) >> (32 - (int)(n))))
#endif
/* Extract byte from a 32 bit quantity (little endian notation) */
#define byte(x,n) ((u08b)((x) >> (8 * n)))
/* For inverting byte order in input/output 32 bit words, if needed */
// #ifdef LITTLE_ENDIAN
// modified by chilong
#ifdef AUTH_LITTLE_ENDIAN
#define bswap(x) (x)
#else
#define bswap(x) ((rotl((x), 8) & 0x00ff00ff) | (rotr((x), 8) & 0xff00ff00))
#endif
//end of aes_def.h
/*------------------ DLW debug code */
#if _VERBOSE_
#include <stdio.h>
int rNum;
void ShowBlk(const u32b *b,int final)
{
int i,j;
u32b x;
u08b a;
printf("%s %2d: ",(final) ? "Final" : "Round",rNum++);
for (i=0;i<4;i++)
{
printf(" ");
x = b[i]; /* always used internally as "little-endian" */
for (j=0;j<4;j++)
{
a = byte(x,j);
printf(" %02X",a);
}
}
printf("\n");
}
void ShowKeySched(const u32b *key,int cnt,const char *hdrMsg)
{
int i,j;
u32b x;
u08b a;
printf("%s\n",hdrMsg);
for (i=0;i<4*cnt;i++)
{
x = key[i]; /* key always used as "little-endian" */
printf(" ");
for (j=0;j<4;j++)
{
a = byte(x,j);
printf(" %02X",a);
}
if ((i%4) == 3) printf("\n");
}
}
#define SetR(r) { rNum = r; }
#else
#define ShowBlk(b,f)
#define SetR(r)
#define ShowKeySched(key,cnt,hdrMsg)
#endif
/*---------------- end of DLW debug */
#define LARGE_TABLES
u08b pow_tab[256];
u08b log_tab[256];
u08b sbx_tab[256];
u08b isb_tab[256];
u32b rco_tab[ 10];
u32b ft_tab[4][256];
u32b it_tab[4][256];
#ifdef LARGE_TABLES
u32b fl_tab[4][256];
u32b il_tab[4][256];
#endif
u32b tab_gen = 0;
u32b k_len;
u32b e_key[60];
u32b d_key[60];
#define ff_mult(a,b) (a && b ? pow_tab[(log_tab[a] + log_tab[b]) % 255] : 0)
#define f_rn(bo, bi, n, k) \
bo[n] = ft_tab[0][byte(bi[n],0)] ^ \
ft_tab[1][byte(bi[(n + 1) & 3],1)] ^ \
ft_tab[2][byte(bi[(n + 2) & 3],2)] ^ \
ft_tab[3][byte(bi[(n + 3) & 3],3)] ^ *(k + n)
#define i_rn(bo, bi, n, k) \
bo[n] = it_tab[0][byte(bi[n],0)] ^ \
it_tab[1][byte(bi[(n + 3) & 3],1)] ^ \
it_tab[2][byte(bi[(n + 2) & 3],2)] ^ \
it_tab[3][byte(bi[(n + 1) & 3],3)] ^ *(k + n)
#ifdef LARGE_TABLES
#define ls_box(x) \
( fl_tab[0][byte(x, 0)] ^ \
fl_tab[1][byte(x, 1)] ^ \
fl_tab[2][byte(x, 2)] ^ \
fl_tab[3][byte(x, 3)] )
#define f_rl(bo, bi, n, k) \
bo[n] = fl_tab[0][byte(bi[n],0)] ^ \
fl_tab[1][byte(bi[(n + 1) & 3],1)] ^ \
fl_tab[2][byte(bi[(n + 2) & 3],2)] ^ \
fl_tab[3][byte(bi[(n + 3) & 3],3)] ^ *(k + n)
#define i_rl(bo, bi, n, k) \
bo[n] = il_tab[0][byte(bi[n],0)] ^ \
il_tab[1][byte(bi[(n + 3) & 3],1)] ^ \
il_tab[2][byte(bi[(n + 2) & 3],2)] ^ \
il_tab[3][byte(bi[(n + 1) & 3],3)] ^ *(k + n)
#else
#define ls_box(x) \
((u32b)sbx_tab[byte(x, 0)] << 0) ^ \
((u32b)sbx_tab[byte(x, 1)] << 8) ^ \
((u32b)sbx_tab[byte(x, 2)] << 16) ^ \
((u32b)sbx_tab[byte(x, 3)] << 24)
#define f_rl(bo, bi, n, k) \
bo[n] = (u32b)sbx_tab[byte(bi[n],0)] ^ \
rotl(((u32b)sbx_tab[byte(bi[(n + 1) & 3],1)]), 8) ^ \
rotl(((u32b)sbx_tab[byte(bi[(n + 2) & 3],2)]), 16) ^ \
rotl(((u32b)sbx_tab[byte(bi[(n + 3) & 3],3)]), 24) ^ *(k + n)
#define i_rl(bo, bi, n, k) \
bo[n] = (u32b)isb_tab[byte(bi[n],0)] ^ \
rotl(((u32b)isb_tab[byte(bi[(n + 3) & 3],1)]), 8) ^ \
rotl(((u32b)isb_tab[byte(bi[(n + 2) & 3],2)]), 16) ^ \
rotl(((u32b)isb_tab[byte(bi[(n + 1) & 3],3)]), 24) ^ *(k + n)
#endif
void gen_tabs(void)
{ u32b i, t;
u08b p, q;
/* log and power tables for GF(2**8) finite field with */
/* 0x11b as modular polynomial - the simplest prmitive */
/* root is 0x11, used here to generate the tables */
for(i = 0,p = 1; i < 256; ++i)
{
pow_tab[i] = (u08b)p; log_tab[p] = (u08b)i;
p = p ^ (p << 1) ^ (p & 0x80 ? 0x01b : 0);
}
log_tab[1] = 0; p = 1;
for(i = 0; i < 10; ++i)
{
rco_tab[i] = p;
p = (p << 1) ^ (p & 0x80 ? 0x1b : 0);
}
/* note that the affine byte transformation matrix in */
/* rijndael specification is in big endian format with */
/* bit 0 as the most significant bit. In the remainder */
/* of the specification the bits are numbered from the */
/* least significant end of a byte. */
for(i = 0; i < 256; ++i)
{
p = (i ? pow_tab[255 - log_tab[i]] : 0); q = p;
q = (q >> 7) | (q << 1); p ^= q;
q = (q >> 7) | (q << 1); p ^= q;
q = (q >> 7) | (q << 1); p ^= q;
q = (q >> 7) | (q << 1); p ^= q ^ 0x63;
sbx_tab[i] = (u08b)p; isb_tab[p] = (u08b)i;
}
for(i = 0; i < 256; ++i)
{
p = sbx_tab[i];
#ifdef LARGE_TABLES
t = p; fl_tab[0][i] = t;
fl_tab[1][i] = rotl(t, 8);
fl_tab[2][i] = rotl(t, 16);
fl_tab[3][i] = rotl(t, 24);
#endif
t = ((u32b)ff_mult(2, p)) |
((u32b)p << 8) |
((u32b)p << 16) |
((u32b)ff_mult(3, p) << 24);
ft_tab[0][i] = t;
ft_tab[1][i] = rotl(t, 8);
ft_tab[2][i] = rotl(t, 16);
ft_tab[3][i] = rotl(t, 24);
p = isb_tab[i];
#ifdef LARGE_TABLES
t = p; il_tab[0][i] = t;
il_tab[1][i] = rotl(t, 8);
il_tab[2][i] = rotl(t, 16);
il_tab[3][i] = rotl(t, 24);
#endif
t = ((u32b)ff_mult(14, p)) |
((u32b)ff_mult( 9, p) << 8) |
((u32b)ff_mult(13, p) << 16) |
((u32b)ff_mult(11, p) << 24);
it_tab[0][i] = t;
it_tab[1][i] = rotl(t, 8);
it_tab[2][i] = rotl(t, 16);
it_tab[3][i] = rotl(t, 24);
#if _VERBOSE_
if (i<4) /* helpful for debugging on new platform */
{ /* (compare with results from known platform) */
if (i==0)
printf("%8s : %08X %08X %08X %08X\n","rco_tab",
rco_tab[0],rco_tab[1],rco_tab[2],rco_tab[3]);
#define _ShowTab(tName) printf("%8s[%d]: %08X %08X %08X %08X\n",#tName,i, \
tName[0][i],tName[1][i],tName[2][i],tName[3][i]);
_ShowTab(it_tab);
_ShowTab(ft_tab);
#ifdef LARGE_TABLES
_ShowTab(il_tab);
_ShowTab(fl_tab);
#endif
}
#endif
}
tab_gen = 1;
};
#define star_x(x) (((x) & 0x7f7f7f7f) << 1) ^ ((((x) & 0x80808080) >> 7) * 0x1b)
#define imix_col(y,x) \
u = star_x(x); \
v = star_x(u); \
w = star_x(v); \
t = w ^ (x); \
(y) = u ^ v ^ w; \
(y) ^= rotr(u ^ t, 8) ^ \
rotr(v ^ t, 16) ^ \
rotr(t,24)
/* initialise the key schedule from the user supplied key */
#define loop4(i) \
{ t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \
t ^= e_key[4 * i]; e_key[4 * i + 4] = t; \
t ^= e_key[4 * i + 1]; e_key[4 * i + 5] = t; \
t ^= e_key[4 * i + 2]; e_key[4 * i + 6] = t; \
t ^= e_key[4 * i + 3]; e_key[4 * i + 7] = t; \
}
#define loop6(i) \
{ t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \
t ^= e_key[6 * i]; e_key[6 * i + 6] = t; \
t ^= e_key[6 * i + 1]; e_key[6 * i + 7] = t; \
t ^= e_key[6 * i + 2]; e_key[6 * i + 8] = t; \
t ^= e_key[6 * i + 3]; e_key[6 * i + 9] = t; \
t ^= e_key[6 * i + 4]; e_key[6 * i + 10] = t; \
t ^= e_key[6 * i + 5]; e_key[6 * i + 11] = t; \
}
#define loop8(i) \
{ t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \
t ^= e_key[8 * i]; e_key[8 * i + 8] = t; \
t ^= e_key[8 * i + 1]; e_key[8 * i + 9] = t; \
t ^= e_key[8 * i + 2]; e_key[8 * i + 10] = t; \
t ^= e_key[8 * i + 3]; e_key[8 * i + 11] = t; \
t = e_key[8 * i + 4] ^ ls_box(t); \
e_key[8 * i + 12] = t; \
t ^= e_key[8 * i + 5]; e_key[8 * i + 13] = t; \
t ^= e_key[8 * i + 6]; e_key[8 * i + 14] = t; \
t ^= e_key[8 * i + 7]; e_key[8 * i + 15] = t; \
}
u32b *AES_SetKey(const u32b in_key[], const u32b key_len)
{ u32b i, t, u, v, w;
if(!tab_gen)
gen_tabs();
k_len = (key_len + 31) / 32;
for (i=0;i<k_len;i++)
e_key[i] = bswap(in_key[i]);
t = e_key[k_len-1];
switch(k_len)
{
case 4: for(i = 0; i < 10; ++i)
loop4(i);
break;
case 6: for(i = 0; i < 8; ++i)
loop6(i);
break;
case 8: for(i = 0; i < 7; ++i)
loop8(i);
break;
}
d_key[0] = e_key[0]; d_key[1] = e_key[1];
d_key[2] = e_key[2]; d_key[3] = e_key[3];
for(i = 4; i < 4 * k_len + 24; ++i)
{
imix_col(d_key[i], e_key[i]);
}
ShowKeySched(e_key,4,"Encryption key schedule:");
ShowKeySched(d_key,4,"Decryption key schedule:");
return e_key;
};
/* encrypt a block of text */
#define f_nround(bo, bi, k) \
f_rn(bo, bi, 0, k); \
f_rn(bo, bi, 1, k); \
f_rn(bo, bi, 2, k); \
f_rn(bo, bi, 3, k); \
ShowBlk(bo,0); \
k += 4
#define f_lround(bo, bi, k) \
f_rl(bo, bi, 0, k); \
f_rl(bo, bi, 1, k); \
f_rl(bo, bi, 2, k); \
f_rl(bo, bi, 3, k); \
ShowBlk(bo,1);
void AES_Encrypt(const u32b in_blk[4], u32b out_blk[4])
{ u32b b0[4], b1[4], *kp;
b0[0] = bswap(in_blk[0]) ^ e_key[0];
b0[1] = bswap(in_blk[1]) ^ e_key[1];
b0[2] = bswap(in_blk[2]) ^ e_key[2];
b0[3] = bswap(in_blk[3]) ^ e_key[3];
SetR(1); ShowBlk(b0,0);
kp = e_key + 4;
if(k_len > 6)
{
f_nround(b1, b0, kp); f_nround(b0, b1, kp);
}
if(k_len > 4)
{
f_nround(b1, b0, kp); f_nround(b0, b1, kp);
}
f_nround(b1, b0, kp); f_nround(b0, b1, kp);
f_nround(b1, b0, kp); f_nround(b0, b1, kp);
f_nround(b1, b0, kp); f_nround(b0, b1, kp);
f_nround(b1, b0, kp); f_nround(b0, b1, kp);
f_nround(b1, b0, kp); f_lround(b0, b1, kp);
out_blk[0] = bswap(b0[0]);
out_blk[1] = bswap(b0[1]);
out_blk[2] = bswap(b0[2]);
out_blk[3] = bswap(b0[3]);
};
/* decrypt a block of text */
#define i_nround(bo, bi, k) \
i_rn(bo, bi, 0, k); \
i_rn(bo, bi, 1, k); \
i_rn(bo, bi, 2, k); \
i_rn(bo, bi, 3, k); \
k -= 4
#define i_lround(bo, bi, k) \
i_rl(bo, bi, 0, k); \
i_rl(bo, bi, 1, k); \
i_rl(bo, bi, 2, k); \
i_rl(bo, bi, 3, k)
void AES_Decrypt(const u32b in_blk[4], u32b out_blk[4])
{ u32b b0[4], b1[4], *kp;
b0[0] = bswap(in_blk[0]) ^ e_key[4 * k_len + 24];
b0[1] = bswap(in_blk[1]) ^ e_key[4 * k_len + 25];
b0[2] = bswap(in_blk[2]) ^ e_key[4 * k_len + 26];
b0[3] = bswap(in_blk[3]) ^ e_key[4 * k_len + 27];
kp = d_key + 4 * (k_len + 5);
if(k_len > 6)
{
i_nround(b1, b0, kp); i_nround(b0, b1, kp);
}
if(k_len > 4)
{
i_nround(b1, b0, kp); i_nround(b0, b1, kp);
}
i_nround(b1, b0, kp); i_nround(b0, b1, kp);
i_nround(b1, b0, kp); i_nround(b0, b1, kp);
i_nround(b1, b0, kp); i_nround(b0, b1, kp);
i_nround(b1, b0, kp); i_nround(b0, b1, kp);
i_nround(b1, b0, kp); i_lround(b0, b1, kp);
out_blk[0] = bswap(b0[0]);
out_blk[1] = bswap(b0[1]);
out_blk[2] = bswap(b0[2]);
out_blk[3] = bswap(b0[3]);
};
#define AES_BLOCK_SIZE 16
static void gf_mulx(unsigned char *pad)
{
int i, carry;
carry = pad[0] & 0x80;
for (i = 0; i < AES_BLOCK_SIZE - 1; i++)
pad[i] = (pad[i] << 1) | (pad[i + 1] >> 7);
pad[AES_BLOCK_SIZE - 1] <<= 1;
if (carry)
pad[AES_BLOCK_SIZE - 1] ^= 0x87;
}
/**
* omac1_aes_128_vector - One-Key CBC MAC (OMAC1) hash with AES-128
* @key: 128-bit key for the hash operation
* @num_elem: Number of elements in the data vector
* @addr: Pointers to the data areas
* @len: Lengths of the data blocks
* @mac: Buffer for MAC (128 bits, i.e., 16 bytes)
* Returns: 0 on success, -1 on failure
*
* This is a mode for using block cipher (AES in this case) for authentication.
* OMAC1 was standardized with the name CMAC by NIST in a Special Publication
* (SP) 800-38B.
*/
int omac1_aes_128_vector(const unsigned char *key, int num_elem,
const unsigned char *addr[], const int *len, unsigned char *mac)
{
void *ctx;
unsigned char cbc[AES_BLOCK_SIZE], pad[AES_BLOCK_SIZE];
const unsigned char *pos, *end;
int i, e, left, total_len;
ctx = AES_SetKey(key, 128);
if (ctx == NULL)
return -1;
memset(cbc, 0, AES_BLOCK_SIZE);
total_len = 0;
for (e = 0; e < num_elem; e++)
total_len += len[e];
left = total_len;
e = 0;
pos = addr[0];
end = pos + len[0];
while (left >= AES_BLOCK_SIZE) {
for (i = 0; i < AES_BLOCK_SIZE; i++) {
cbc[i] ^= *pos++;
if (pos >= end) {
e++;
pos = addr[e];
end = pos + len[e];
}
}
if (left > AES_BLOCK_SIZE)
AES_Encrypt(cbc, cbc);
left -= AES_BLOCK_SIZE;
}
memset(pad, 0, AES_BLOCK_SIZE);
AES_Encrypt(pad, pad);
gf_mulx(pad);
if (left || total_len == 0) {
for (i = 0; i < left; i++) {
cbc[i] ^= *pos++;
if (pos >= end) {
e++;
pos = addr[e];
end = pos + len[e];
}
}
cbc[left] ^= 0x80;
gf_mulx(pad);
}
for (i = 0; i < AES_BLOCK_SIZE; i++)
pad[i] ^= cbc[i];
AES_Encrypt(pad, mac);
return 0;
}
/**
* omac1_aes_128 - One-Key CBC MAC (OMAC1) hash with AES-128 (aka AES-CMAC)
* @key: 128-bit key for the hash operation
* @data: Data buffer for which a MAC is determined
* @data_len: Length of data buffer in bytes
* @mac: Buffer for MAC (128 bits, i.e., 16 bytes)
* Returns: 0 on success, -1 on failure
*
* This is a mode for using block cipher (AES in this case) for authentication.
* OMAC1 was standardized with the name CMAC by NIST in a Special Publication
* (SP) 800-38B.
*/
int omac1_aes_128(const unsigned char *key, const unsigned char *data, int data_len, unsigned char *mac)
{
return omac1_aes_128_vector(key, 1, &data, &data_len, mac);
}
enum
{
BLK_SIZE = 16, // # octets in an AES block
MAX_PACKET = 3*512, // largest packet size
N_RESERVED = 0, // reserved nonce octet value
A_DATA = 0x40, // the Adata bit in the flags
M_SHIFT = 3, // how much to shift the 3-bit M field
L_SHIFT = 0, // how much to shift the 3-bit L field
L_SIZE = 2 // size of the l(m) length field (in octets)
};
typedef union _block // AES cipher block
{
u32b x[BLK_SIZE/4]; // access as 8-bit octets or 32-bit words
u08b b[BLK_SIZE];
}block;
typedef struct _packet
{
bool encrypted; // TRUE if encrypted
u08b TA[6]; // xmit address
int micLength; // # octets of MIC appended to plaintext (M)
int clrCount; // # cleartext octets covered by MIC
u32b pktNum[2]; // unique packet sequence number (like WEP IV)
block key; // the encryption key (K)
int length; // # octets in data[]
u08b data[MAX_PACKET+2*BLK_SIZE]; // packet contents
}packet;
/*
input : 256 bits, 32 bytes, 4 block for TKIP
128 bits, 16 bytes, 2 block for CCMP, WRAP, and WEP
up to 32 block for WPA2
output: 8 bytes MIC | Wraped key data
*/
#define BLOCKSIZE8 8
void AES_WRAP(u08b * plain, int plain_len,
u08b * iv, int iv_len,
u08b * kek, int kek_len,
u08b *cipher, u16b *cipher_len)
{
int i, j, k, nblock = plain_len/BLOCKSIZE8;
#ifdef RTL_WPA2
u08b R[32][BLOCKSIZE8], A[BLOCKSIZE8], xor[BLOCKSIZE8];
#else
u08b R[4][BLOCKSIZE8], A[BLOCKSIZE8], xor[BLOCKSIZE8];
#endif
packet p;
block m,x;
memcpy(&p.key.b , kek, kek_len);
AES_SetKey(p.key.x, BLK_SIZE*8); // run the key schedule
//Initialize Variable
memcpy(A, iv, BLOCKSIZE8);
for(i = 0; i < nblock ; i++)
memcpy(&R[i], plain + i*BLOCKSIZE8, BLOCKSIZE8);
//Caalculate Intermediate Values
for(j = 0 ; j < 6 ; j++ )
for (i = 0 ; i < nblock ; i++)
{
memcpy(&m.b, A, BLOCKSIZE8);
memcpy((&m.b[0]) + BLOCKSIZE8, &(R[i]), BLOCKSIZE8);
// => B = AES(K, A|R[i])
AES_Encrypt(m.x,x.x);
// => A = MSB(64,B) ^t where t = (n*j) + i
memset(xor, 0, sizeof xor);
xor[7] |= ((nblock * j) + i + 1);
for(k = 0 ; k < 8 ; k++)
A[k] = x.b[k] ^ xor[k];
// => R[i] = LSB(64,B)
for(k = 0 ; k < 8 ; k++)
R[i][k] = x.b[k + BLOCKSIZE8];
}
//Output the result
memcpy(cipher, A, BLOCKSIZE8);
for(i = 0; i<nblock ; i++)
memcpy(cipher + (i+1)*BLOCKSIZE8, &R[i], BLOCKSIZE8);
*cipher_len = plain_len + BLOCKSIZE8;
}
void AES_UnWRAP(u08b * cipher, int cipher_len,
u08b * kek, int kek_len,
u08b * plain, int plain_len)
{
int i, j, k, nblock = (cipher_len/BLOCKSIZE8) - 1;
#ifdef RTL_WPA2
if (nblock > 32) {
printf("AES_UnWRAP Error: cipher len exceeds!\n");
return;
}
u08b R[32][BLOCKSIZE8], A[BLOCKSIZE8], xor[BLOCKSIZE8];
#else
if (nblock > 4) {
printf("AES_UnWRAP Error: cipher len exceeds!\n");
return;
}
u08b R[4][BLOCKSIZE8], A[BLOCKSIZE8], xor[BLOCKSIZE8];
#endif
packet p;
block m,x;
if ((plain_len < BLOCKSIZE8) || (plain_len < cipher_len)) {
printf("AES_UnWRAP Error: cipher len exceeds plain len!\n");
return;
}
memcpy(&p.key.b , kek, kek_len);
AES_SetKey(p.key.x, BLK_SIZE*8); // run the key schedule
//Initialize Variable
memcpy(A, cipher, BLOCKSIZE8);
for(i = 0; i < nblock ; i++)
memcpy(&R[i], cipher + (i+1)*BLOCKSIZE8, BLOCKSIZE8);
//Compute internediate Value
for(j=5 ; j>=0 ; j--)
for(i= nblock-1 ; i>=0 ; i--)
{
// => B = AES-1((A^t) |R[i])
memset(xor, 0, sizeof xor);
xor[7] |= ((nblock * j) + i + 1);
for(k = 0 ; k < 8 ; k++)
x.b[k] = A[k] ^ xor[k];
memcpy((&x.b[0]) + BLOCKSIZE8, &(R[i]), BLOCKSIZE8);
AES_Decrypt(x.x,m.x);
memcpy(A, &m.b[0], BLOCKSIZE8);
//for(k=0 ; k<BLOCKSIZE8 ; k++)
// A[k] = m.b[k];
for(k=0 ; k<BLOCKSIZE8 ; k++)
R[i][k] = m.b[k + BLOCKSIZE8];
}
memcpy(plain, A, BLOCKSIZE8);
for(i = 0; i < nblock ; i++)
memcpy(plain + (i+1)*BLOCKSIZE8, &R[i], BLOCKSIZE8);
}
#ifndef COMPACK_SIZE
void TestAESWRAP()
{
unsigned char kek[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
unsigned char plaintext[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
unsigned char cipher[16+ 8];
/*
unsigned char iv[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6};
unsigned char plaintext1[] ={0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};
AES_WRAP(plaintext, 16,
iv, 8,
kek, 16,
cipher);
*/
AES_UnWRAP(cipher, 24,
kek, 16,
plaintext, 24);
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,820 @@
#include "stdafx.h"
#include "stdlib.h"
#include "string.h"
//#include <openssl/md5.h>
//#include <openssl/rc4.h>
#include "1x_rc4.h"
#include <time.h>
#include "1x_eapol.h"
#include "1x_kmsm.h"
#include "1x_kmsm_eapolkey.h"
#ifdef RTL_WPA2_CLIENT
#include "1x_supp_pae.h"
#endif
#define PMK_EXPANSION_CONST "Pairwise key expansion"
#define PMK_EXPANSION_CONST_SIZE 22
#ifdef RTL_WPA2
#define PMKID_NAME_CONST "PMK Name"
#define PMKID_NAME_CONST_SIZE 8
#endif /* RTL_WPA2 */
#define GMK_EXPANSION_CONST "Group key expansion"
#define GMK_EXPANSION_CONST_SIZE 19
#define RANDOM_EXPANSION_CONST "Init Counter"
#define RANDOM_EXPANSION_CONST_SIZE 12
#define EAPOLKEY_DEBUG 2
int MIN(u_char * ucStr1, u_char * ucStr2, u_long ulLen)
{
int i;
for(i=0 ; i<ulLen ; i++)
{
//printf("i=%d, 1=%x, 2=%x\n", i, ucStr1[i], ucStr2[i]);
if((u_char)ucStr1[i] < (u_char)ucStr2[i])
return -1;
else if((u_char)ucStr1[i] > (u_char)ucStr2[i])
return 1;
else if(i == ulLen - 1)
return 0;
else
continue;
}
return 0;
}
void PrintHex(u_char *str, u_char *buf, int size);
char * KM_STRERR(int err)
{
switch(err)
{
case ERROR_NULL_PSK:
return KM_STRERROR_NULL_PSK;
case ERROR_TIMEOUT:
return KM_STRERROR_TIMEOUT;
case ERROR_MIC_FAIL:
return KM_STRERROR_MIC_FAIL;
case ERROR_SET_PTK:
return KM_STRERROR_SET_PTK;
case ERROR_NONEEQUL_REPLAYCOUNTER:
return KM_STRERROR_NONEEQUL_REPLAYCOUNTER;
case ERROR_EQUALSMALLER_REPLAYCOUNTER:
return KM_STRERROR_EQUALSMALLER_REPLAYCOUNTER;
case ERROR_NONEQUAL_NONCE:
return KM_STRERROR_NONEQUAL_NONCE;
case ERROR_AESKEYWRAP_MIC_FAIL:
return KM_STRERROR_AESKEYWRAP_MIC_FAIL;
case ERROR_LARGER_REPLAYCOUNTER:
return KM_STRERROR_LARGER_REPLAYCOUNTER;
case ERROR_UNMATCHED_GROUPKEY_LEN:
return KM_STRERROR_UNMATCHED_GROUPKEY_LEN;
case ERROR_NONEQUAL_RSNIE:
return KM_STRERROR_NONEQUAL_RSNIE;
}
return "Uknown Failure";
}
int CheckMIC(OCTET_STRING EAPOLMsgRecvd, u_char *key, int keylen)
{
int retVal = 0;
OCTET_STRING EapolKeyMsgRecvd;
char ucAlgo;
OCTET_STRING tmp; //copy of overall 802.1x message
struct lib1x_eapol * tmpeapol;
lib1x_eapol_key * tmpeapolkey;
u_char sha1digest[20];
EapolKeyMsgRecvd.Octet = EAPOLMsgRecvd.Octet +\
ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN;
EapolKeyMsgRecvd.Length = EAPOLMsgRecvd.Length -\
(ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN);
ucAlgo = Message_KeyDescVer(EapolKeyMsgRecvd);
tmp.Length = EAPOLMsgRecvd.Length;
tmp.Octet = (u_char*)malloc(EAPOLMsgRecvd.Length);
memcpy(tmp.Octet, EAPOLMsgRecvd.Octet, EAPOLMsgRecvd.Length);
tmpeapol = (struct lib1x_eapol *)(tmp.Octet + ETHER_HDRLEN);
tmpeapolkey = (lib1x_eapol_key *)(tmp.Octet + ETHER_HDRLEN +
LIB1X_EAPOL_HDRLEN);
memset(tmpeapolkey->key_mic, 0, KEY_MIC_LEN);
if(ucAlgo == key_desc_ver1)
{
hmac_md5((u_char*)tmpeapol, EAPOLMsgRecvd.Length - ETHER_HDRLEN ,
key, keylen, tmpeapolkey->key_mic);
#ifdef DEBUG_MIC
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CheckMIC", EapolKeyMsgRecvd.Octet +
KeyMICPos, KEY_MIC_LEN, "Original");
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CheckMIC", tmpeapolkey->key_mic,
KEY_MIC_LEN, "Calculated");
#endif
if(!memcmp(tmpeapolkey->key_mic, EapolKeyMsgRecvd.Octet + KeyMICPos,
KEY_MIC_LEN))
retVal = 1;
}
else if(ucAlgo == key_desc_ver2)
{
hmac_sha1((u_char*)tmpeapol, EAPOLMsgRecvd.Length - ETHER_HDRLEN ,
key, keylen, sha1digest);
if(!memcmp(sha1digest, EapolKeyMsgRecvd.Octet + KeyMICPos, KEY_MIC_LEN))
retVal = 1;
}
#ifdef CONFIG_IEEE80211W
else if(ucAlgo == key_desc_ver3)
{
omac1_aes_128(key, (u_char*)tmpeapol, EAPOLMsgRecvd.Length - ETHER_HDRLEN, tmpeapolkey->key_mic);
if(!memcmp(tmpeapolkey->key_mic, EapolKeyMsgRecvd.Octet + KeyMICPos, KEY_MIC_LEN))
retVal = 1;
}
#endif /* CONFIG_IEEE80211W */
free(tmp.Octet); // david+2006-03-31, fix memory leak
return retVal;
}
#ifdef RTL_WPA2
void CalcPMKID(char* pmkid, char* pmk, char* aa, char* spa
#ifdef CONFIG_IEEE80211W
, int use_sha256
#endif /* CONFIG_IEEE80211W */
)
{
//u_char data[sizeof(PMKID_NAME_CONST) + 2*ETHER_ADDRLEN];
u_char data[PMKID_NAME_CONST_SIZE + 2*ETHER_ADDRLEN];
u_char sha1digest[32];
memcpy(data, PMKID_NAME_CONST, PMKID_NAME_CONST_SIZE);
memcpy(data+PMKID_NAME_CONST_SIZE, aa, ETHER_ADDRLEN);
memcpy(data+PMKID_NAME_CONST_SIZE+ETHER_ADDRLEN, spa, ETHER_ADDRLEN);
//printf("CalcPMKID\n");
//wpa2_hexdump("AA", aa, ETHER_ADDRLEN);
//wpa2_hexdump("SPA", spa, ETHER_ADDRLEN);
//wpa2_hexdump("PMK", pmk, PMK_LEN);
//wpa2_hexdump("DATA", data, sizeof(data));
#ifdef CONFIG_IEEE80211W
if(use_sha256)
hmac_sha256((u_char*)data, sizeof(data), (unsigned char *)pmk, PMK_LEN, sha1digest);
else
#endif /* CONFIG_IEEE80211W */
hmac_sha1(data, sizeof(data), (unsigned char *)pmk, PMK_LEN, sha1digest);
memcpy(pmkid, sha1digest, PMKID_LEN);
//wpa2_hexdump("PMKID", pmkid, PMKID_LEN);
}
#endif /* RTL_WPA2 */
void CalcMIC(OCTET_STRING EAPOLMsgSend, int algo, u_char *key, int keylen)
{
struct lib1x_eapol * eapol = (struct lib1x_eapol *)(EAPOLMsgSend.Octet +
ETHER_HDRLEN);
lib1x_eapol_key * eapolkey = (lib1x_eapol_key *)(EAPOLMsgSend.Octet +
ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN);
u_char sha1digest[20];
memset(eapolkey->key_mic, 0, KEY_MIC_LEN);
// kenny
// lib1x_message(MESS_DBG_KEY_MANAGE, "CaclMIC Algorithm = %d ", algo);
// lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcMIC(1)", key, keylen, "PTK");
// lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcMIC(2)", (u_char*)eapol, EAPOLMsgSend.Length - ETHER_HDRLEN , "Packet");
if(algo == key_desc_ver1)
{
hmac_md5((u_char*)eapol, EAPOLMsgSend.Length - ETHER_HDRLEN ,
key, keylen, eapolkey->key_mic);
}
else if(algo == key_desc_ver2)
{
hmac_sha1((u_char*)eapol, EAPOLMsgSend.Length - ETHER_HDRLEN ,
key, keylen, sha1digest);
memcpy(eapolkey->key_mic, sha1digest, KEY_MIC_LEN);
}
#ifdef CONFIG_IEEE80211W
else if (algo == key_desc_ver3) {
omac1_aes_128(key, (unsigned char*)eapol, EAPOLMsgSend.Length - ETHER_HDRLEN, eapolkey->key_mic);
}
#endif /* CONFIG_IEEE80211W */
// kenny
// lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcMIC(3)", eapolkey->key_mic, KEY_MIC_LEN, "MIC");
}
void CalcPTK(u_char *addr1, u_char *addr2, u_char *nonce1, u_char *nonce2,
u_char * keyin, int keyinlen,
u_char * keyout, int keyoutlen
#ifdef CONFIG_IEEE80211W
,int use_sha256
#endif /* CONFIG_IEEE80211W */
)
{
u_char data[2*ETHER_ADDRLEN + 2*KEY_NONCE_LEN], tmpPTK[128];
if(MIN(addr1, addr2, ETHER_ADDRLEN)<=0)
{
memcpy(data, addr1, ETHER_ADDRLEN);
memcpy(data + ETHER_ADDRLEN, addr2, ETHER_ADDRLEN);
}else
{
memcpy(data, addr2, ETHER_ADDRLEN);
memcpy(data + ETHER_ADDRLEN, addr1, ETHER_ADDRLEN);
}
if(MIN(nonce1, nonce2, KEY_NONCE_LEN)<=0)
{
memcpy(data + 2*ETHER_ADDRLEN, nonce1, KEY_NONCE_LEN);
memcpy(data + 2*ETHER_ADDRLEN + KEY_NONCE_LEN, nonce2, KEY_NONCE_LEN);
}else
{
memcpy(data + 2*ETHER_ADDRLEN, nonce2, KEY_NONCE_LEN);
memcpy(data + 2*ETHER_ADDRLEN + KEY_NONCE_LEN, nonce1, KEY_NONCE_LEN);
}
#ifdef CONFIG_IEEE80211W
if (use_sha256) {
sha256_prf(keyin, keyinlen, (unsigned char*)PMK_EXPANSION_CONST, data, sizeof(data),
tmpPTK, keyoutlen);
}
else
#endif /* CONFIG_IEEE80211W */
i_PRF(keyin, keyinlen, (u_char*)PMK_EXPANSION_CONST,
PMK_EXPANSION_CONST_SIZE, data,sizeof(data),
tmpPTK, PTK_LEN_TKIP);
memcpy(keyout, tmpPTK, keyoutlen);
#if 0 // for debug
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcPTK", nonce1, KEY_NONCE_LEN, "ANonce");
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcPTK", nonce2, KEY_NONCE_LEN, "SNonce");
//lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcPTK", data, sizeof(data), "data");
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcPTK", keyin, keyinlen, "PMK");
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "CalcPTK", keyout, keyoutlen, "PTK");
#endif
}
// //////////// Nonce generation function 802.11i/D3.0 p117, p.189/
void GenNonce(u_char * nonce, u_char * addr)
{
u_char secret[256], random[256], result[256];
time_t t;
time(&t);
memcpy(random, (u_char*)&t, sizeof(t));
memset(secret, 0, sizeof secret);
//memset(random, 0, sizeof random);
i_PRF(secret, sizeof(secret), (u_char*)RANDOM_EXPANSION_CONST, RANDOM_EXPANSION_CONST_SIZE,
random, sizeof(random), result, KEY_NONCE_LEN);
memcpy(nonce, result, KEY_NONCE_LEN);
}
/* GTK-PRF-X
X = 256 in TKIP
X = 128 in CCMP, WRAP, and WEP
*/
void CalcGTK(u_char *addr, u_char *nonce,
u_char * keyin, int keyinlen,
u_char * keyout, int keyoutlen
#ifdef CONFIG_IEEE80211W
, u_char * label
#endif /* CONFIG_IEEE80211W */
)
{
u_char data[ETHER_ADDRLEN + KEY_NONCE_LEN], tmp[64];
memcpy(data, addr, ETHER_ADDRLEN);
memcpy(data + ETHER_ADDRLEN, nonce, KEY_NONCE_LEN);
#ifdef CONFIG_IEEE80211W
sha256_prf(keyin, keyinlen, label, data, sizeof(data), tmp, keyoutlen);
#else
i_PRF(keyin, keyinlen, (u_char*)GMK_EXPANSION_CONST,
GMK_EXPANSION_CONST_SIZE, data, sizeof(data),
tmp, keyoutlen);
#endif /* CONFIG_IEEE80211W */
memcpy(keyout, tmp, keyoutlen);
}
void EncGTK(Global_Params * global, u_char *kek, int keklen, u_char *key,
int keylen, u_char *out, u_short *outlen)
{
u_char tmp1[257], tmp2[257];
RC4_KEY rc4key;
// kenny
u_char default_key_iv[] = { 0xA6,0xA6,0xA6,0xA6,0xA6,0xA6,0xA6,0xA6 };
//struct lib1x_eapol * eapol = (struct lib1x_eapol *)(global->EAPOLMsgSend.Octet + ETHER_HDRLEN);
lib1x_eapol_key * eapolkey = (lib1x_eapol_key *)(global->EAPOLMsgSend.Octet +
ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN);
// should refer tx packet, david+2006-04-06
// if(Message_KeyDescVer(global->EapolKeyMsgRecvd) == key_desc_ver1)
if(Message_KeyDescVer(global->EapolKeyMsgSend) == key_desc_ver1)
{
memcpy(tmp1, eapolkey->key_iv, KEY_IV_LEN);
memcpy(tmp1 + KEY_IV_LEN, kek, keklen);
RC4_set_key(&rc4key, KEY_IV_LEN + keklen, tmp1);
//first 256 bytes are discarded
RC4(&rc4key, 256, (u_char*)tmp1, (u_char*)tmp2);
RC4(&rc4key, keylen, (u_char*)key, out);
*outlen = keylen;
// should refer tx packet, david+2006-04-06
// }else if(Message_KeyDescVer(global->EapolKeyMsgRecvd) == key_desc_ver2)
}else if(Message_KeyDescVer(global->EapolKeyMsgSend) == key_desc_ver2)
#ifdef CONFIG_IEEE80211W
{
//according to p75 of 11i/D3.0, the IV should be put in the least significant octecs of
//KeyIV field which shall be padded with 0, so eapolkey->key_iv + 8
AES_WRAP(key, keylen, default_key_iv, 8, kek, keklen, out, outlen);
}else if(Message_KeyDescVer(global->EapolKeyMsgSend) == key_desc_ver3)
#endif /* CONFIG_IEEE80211W */
{
//according to p75 of 11i/D3.0, the IV should be put in the least significant octecs of
//KeyIV field which shall be padded with 0, so eapolkey->key_iv + 8
AES_WRAP(key, keylen, default_key_iv, 8, kek, keklen, out, outlen);
}
// Kenny
//lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "EncGTK", kek, keklen, "Group Key encryption key");
//lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "EncGTK", key, keylen, "Group Key");
//lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "EncGTK", default_key_iv, 8, "Group Key encryption IV");
//lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "EncGTK", out, *outlen, "Encryted Group Key");
}
#ifdef RTL_WPA2_CLIENT
/*
decrypt WPA2 Message 3's Key Data
*/
// Use RC4 or AES to decode the keydata by checking desc-ver, david-2006-01-06
//int DecWPA2KeyData(u_char *key, int keylen, u_char *kek, int keklen, u_char *kout)
int DecWPA2KeyData(Supp_Global* pGlobal, u_char *key, int keylen, u_char *kek, int keklen, u_char *kout, int kout_len)
{
int retVal = 0;
u_char default_key_iv[] = { 0xA6,0xA6,0xA6,0xA6,0xA6,0xA6,0xA6,0xA6 };
u_char tmp2[257];
// Use RC4 or AES to decode the keydata by checking desc-ver, david-2006-01-06
u_char tmp1[257];
RC4_KEY rc4key;
lib1x_eapol_key *eapolkey = (lib1x_eapol_key *)(pGlobal->EAPOLMsgRecvd.Octet +
ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN);
if (Message_KeyDescVer(pGlobal->EapolKeyMsgRecvd) == key_desc_ver1) {
memcpy(tmp1, eapolkey->key_iv, KEY_IV_LEN);
if (keklen > sizeof(tmp1) - KEY_IV_LEN) {
printf("DecWPA2KeyData Error: keklen exceeds!\n");
return 0;
}
memcpy(tmp1+KEY_IV_LEN, kek, keklen);
RC4_set_key(&rc4key, KEY_IV_LEN + keklen, tmp1);
//first 256 bits is discard
RC4(&rc4key, 256, (u_char*)tmp1, (u_char*)tmp2);
//RC4(&rc4key, keylen, eapol_key->key_data, global->skm_sm->GTK[Message_KeyIndex(global->EapolKeyMsgRecvd)]);
RC4(&rc4key, keylen, pGlobal->EapolKeyMsgRecvd.Octet + KeyDataPos, (u_char*)tmp2);
if (keylen > kout_len) {
printf("DecWPA2KeyData Error: keylen exceeds!\n");
return 0;
}
memcpy(kout, tmp2, keylen);
//memcpy(&global->supp_kmsm->GTK[Message_KeyIndex(global->EapolKeyMsgRecvd)], tmp2, keylen);
retVal = 1;
}
else
{
//--------------------------------------------------------
AES_UnWRAP(key, keylen, kek, keklen, tmp2, sizeof(tmp2));
#if 0
wpa2_hexdump("DecGTK: kek", kek, keklen);
wpa2_hexdump("DecGTK: key", key, keylen);
wpa2_hexdump("DecGTK: out", tmp2, 8+keylen);
#endif
if(memcmp(tmp2, default_key_iv, 8))
retVal = 0;
else {
if (keylen > kout_len) {
printf("DecWPA2KeyData Error: keylen exceeds!\n");
return 0;
}
memcpy(kout, tmp2+8, keylen);
retVal = 1;
}
}
return retVal;
}
#endif /* RTL_WPA2_CLIENT */
/*
The routine will set the key into state machine data structure for RC$
encryption and
for AES_WRAP when DecGTK success.
"DecGTK successful" means MIC of AES_WRAP algorithm has no data integrity
failure.
*/
int DecGTK(OCTET_STRING EAPOLMsgRecvd, u_char *kek, int keklen, int keylen,
u_char *kout, int kout_len)
{
int retVal = 0;
u_char tmp1[257], tmp2[257];
RC4_KEY rc4key;
lib1x_eapol_key * eapol_key = (lib1x_eapol_key *)(EAPOLMsgRecvd.Octet +
ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN);
OCTET_STRING EapolKeyMsgRecvd;
EapolKeyMsgRecvd.Octet = EAPOLMsgRecvd.Octet +
ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN;
EapolKeyMsgRecvd.Length = EAPOLMsgRecvd.Length -
(ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN);
if(Message_KeyDescVer(EapolKeyMsgRecvd) == key_desc_ver1)
{
memcpy(tmp1, eapol_key->key_iv, KEY_IV_LEN);
if (keklen > sizeof(tmp1) - KEY_IV_LEN) {
printf("DecGTK Error: keklen exceeds!\n");
return 0;
}
memcpy(tmp1 + KEY_IV_LEN, kek, keklen);
RC4_set_key(&rc4key, KEY_IV_LEN + keklen, tmp1);
//first 256 bits is discard
RC4(&rc4key, 256, (u_char*)tmp1, (u_char*)tmp2);
//RC4(&rc4key, keylen, eapol_key->key_data, global->skm_sm->GTK[Message_KeyIndex(global->EapolKeyMsgRecvd)]);
RC4(&rc4key, keylen, EapolKeyMsgRecvd.Octet + KeyDataPos, (u_char*)tmp2);
if (keylen > kout_len) {
printf("DecGTK Error: keylen exceeds!\n");
return 0;
}
memcpy(kout, tmp2, keylen);
//memcpy(&global->supp_kmsm->GTK[Message_KeyIndex(global->EapolKeyMsgRecvd)], tmp2, keylen);
retVal = 1;
}else if(Message_KeyDescVer(EapolKeyMsgRecvd) == key_desc_ver2)
{
// kenny: should use default IV 0xA6A6A6A6A6A6A6A6
u_char default_key_iv[] = { 0xA6,0xA6,0xA6,0xA6,0xA6,0xA6,0xA6,0xA6 };
// david, get key len from eapol packet
// AES_UnWRAP(EapolKeyMsgRecvd.Octet + KeyDataPos, keylen + 8, kek, keklen, tmp2);
keylen = Message_KeyDataLength(EapolKeyMsgRecvd);
AES_UnWRAP(EapolKeyMsgRecvd.Octet + KeyDataPos, keylen, kek, keklen, tmp2, sizeof(tmp2));
//------------------------- 2005-08-01
//if(memcmp(tmp2, eapol_key->key_iv + 8, 8))
if(memcmp(tmp2, default_key_iv, 8))
retVal = 0;
else
{
//memcpy(kout, tmp2, keylen);
//memcpy(global->supp_kmsm->GTK[Message_KeyIndex(global->EapolKeyMsgRecvd)], tmp2 + 8, keylen - 8);
if (keylen > kout_len) {
printf("DecGTK Error: keylen exceeds!\n");
return 0;
}
memcpy(kout, tmp2+8, keylen);
retVal = 1;
}
}
return retVal;
}
#ifndef COMPACK_SIZE
void PrintHex(u_char *str, u_char *buf, int size)
{
int i;
printf("\t%s:", str);
for(i=0 ; i<size ; i++){
if(i%16 == 0 ) printf("\n\t\t");
printf("%2x ", *(buf + i));
}
printf("\n");
}
#endif
//#define ENABLE_KEYDUMP
#ifdef ENABLE_KEYDUMP
void KeyDump(char *fun, u_char *buf, int size, char *comment)
{
u_char *ptr;
short len;
struct lib1x_ethernet * eth = (struct lib1x_ethernet *)buf;
lib1x_eapol_key * eapol_key = (lib1x_eapol_key *)(buf + ETHER_HDRLEN +
LIB1X_EAPOL_HDRLEN);
printf("$$ %s $$: %s, packet length=%d\n", fun, comment, size);
if (buf != NULL && EAPOLKEY_DEBUG >=2) {
PrintHex((u_char*)"DstAddr", eth->ether_dhost, sizeof(eth->ether_dhost));
PrintHex((u_char*)"SrcAddr", eth->ether_shost, sizeof(eth->ether_shost));
//PrintHex((u_char*)"EtherType", (u_char*)eth->ether_type, sizeof(eth->
ether_type));
//PrintHex((u_char*)"EAPOLHeader", (u_char*)(buf + ETHER_HDRLEN),
LIB1X_EAPOL_HDRLEN);
//printf("\tKeyDescVer:%x\n", eapol_key->key_desc_ver);
PrintHex((u_char *)"KeyInfo", eapol_key->key_info, sizeof(eapol_key->
key_info));
//PrintHex((u_char *)"KeyLength", eapol_key->key_len, sizeof(eapol_key->
key_len));
PrintHex((u_char *)"KeyReplayCounter", eapol_key->key_replay_counter,
sizeof(eapol_key->key_replay_counter));
//PrintHex((u_char *)"KeyNonce", eapol_key->key_nounce, sizeof(eapol_key->
key_nounce));
//PrintHex((u_char *)"KeyIV", eapol_key->key_iv, sizeof(eapol_key->
key_iv));
//PrintHex((u_char *)"KeyReplaySequenceCounter", eapol_key->key_rsc,
sizeof(eapol_key->key_rsc));
//PrintHex((u_char *)"KeyID", eapol_key->key_id, sizeof(eapol_key->
key_id));
//PrintHex((u_char *)"KeyMIC", eapol_key->key_mic, sizeof(eapol_key->
key_mic));
//PrintHex((u_char *)"KeyDataLength", eapol_key->key_data_len,
sizeof(eapol_key->key_data_len));
ptr = buf + KeyDataLenPos;
net2short(ptr, len);
if(!len)
PrintHex((u_char *)"KeyData", buf + KeyDataPos, len);
}
printf("\n");
}
#else
void KeyDump(char *fun, u_char *buf, int size, char *comment)
{}
#endif
/*-----------------------------------------------------------------------------
LargeInteger
Inline Function definition
-------------------------------------------------------------------------------*/
void INCLargeInteger(LARGE_INTEGER * x){
if( x->field.LowPart == 0xffffffff){
if( x->field.HighPart == 0xffffffff)
{
x->field.HighPart = 0;
x->field.LowPart = 0;
}else
{
x->field.HighPart++;
x->field.LowPart = 0;
}
}else
x->field.LowPart++;
}
/*-----------------------------------------------------------------------------
Octet16Integer
Inline Function definition
-------------------------------------------------------------------------------*/
void INCOctet16_INTEGER(OCTET16_INTEGER * x){
if( LargeIntegerOverflow(x->field.LowPart)){
if( LargeIntegerOverflow(x->field.HighPart))
{
LargeIntegerZero( x->field.HighPart);
LargeIntegerZero( x->field.LowPart);
}else
{
INCLargeInteger(&x->field.HighPart);
LargeIntegerZero( x->field.LowPart);
}
}else
INCLargeInteger(&x->field.LowPart);
}
/*-----------------------------------------------------------------------------
OCTET32_INTEGER
Inline Function definition
-------------------------------------------------------------------------------*/
OCTET32_INTEGER * INCOctet32_INTEGER(OCTET32_INTEGER * x)
{
if( Octet16IntegerOverflow(x->field.LowPart)){
if( Octet16IntegerOverflow(x->field.HighPart))
{
Octet16IntegerZero( x->field.HighPart);
Octet16IntegerZero( x->field.LowPart);
}else
{
INCOctet16_INTEGER(&x->field.HighPart);
Octet16IntegerZero( x->field.LowPart);
}
}else
INCOctet16_INTEGER(&x->field.LowPart);
return x;
}
/*-----------------------------------------------------------------------------
EAPOLKey field process
Inline Function definition
Macro definition
-------------------------------------------------------------------------------*/
OCTET_STRING SubStr(OCTET_STRING f, u_short s,u_short l) { \
OCTET_STRING res; \
res.Length = l; \
res.Octet = f.Octet+s; \
return res; \
}
void Message_ReplayCounter_OC2LI(OCTET_STRING f, LARGE_INTEGER * li){
li->field.HighPart = ((u_long)(*(f.Octet + ReplayCounterPos + 3)))
+ ((u_long)(*(f.Octet + ReplayCounterPos+ 2)) <<8 )
+ ((u_long)(*(f.Octet + ReplayCounterPos + 1)) << 16)
+ ((u_long)(*(f.Octet + ReplayCounterPos + 0)) <<24);
li->field.LowPart = ((u_long)(*(f.Octet + ReplayCounterPos + 7)))
+ ((u_long)(*(f.Octet + ReplayCounterPos + 6)) <<8 )
+ ((u_long)(*(f.Octet + ReplayCounterPos + 5)) << 16)
+ ((u_long)(*(f.Octet + ReplayCounterPos + 4)) <<24);
}
void ReplayCounter_OC2LI(OCTET_STRING f, LARGE_INTEGER * li){
li->field.HighPart = ((u_long)(*(f.Octet + 3)))
+ ((u_long)(*(f.Octet + 2)) <<8 )
+ ((u_long)(*(f.Octet + 1)) << 16)
+ ((u_long)(*(f.Octet + 0)) <<24);
li->field.LowPart = ((u_long)(*(f.Octet + 7)))
+ ((u_long)(*(f.Octet + 6)) <<8 )
+ ((u_long)(*(f.Octet + 5)) << 16)
+ ((u_long)(*(f.Octet + 4)) <<24);
}
void ReplayCounter_LI2OC(OCTET_STRING f, LARGE_INTEGER * li){
*(f.Octet + 0) = (li->field.HighPart >> 24) & 0xff;
*(f.Octet + 1) = (li->field.HighPart >> 16) & 0xff;
*(f.Octet + 2) = (li->field.HighPart >> 8) & 0xff;
*(f.Octet + 3) = (li->field.HighPart >> 0) & 0xff;
*(f.Octet + 4) = (li->field.LowPart >> 24) & 0xff;
*(f.Octet + 5) = (li->field.LowPart >> 16) & 0xff;
*(f.Octet + 6) = (li->field.LowPart >> 8) & 0xff;
*(f.Octet + 7) = (li->field.LowPart >> 0) & 0xff;
}
/*-----------------------------------------------------------------------------------------------
f is EAPOL-KEY message
------------------------------------------------------------------------------------------------*/
int Message_EqualReplayCounter(LARGE_INTEGER li1, OCTET_STRING f)
{
LARGE_INTEGER li2;
Message_ReplayCounter_OC2LI(f, &li2);
if(li1.field.HighPart == li2.field.HighPart && li1.field.LowPart ==
li2.field.LowPart)
return 1;
else
return 0;
}
/*-------------------------------------------------------------------------------------------
li1 is recorded replay counter on STA
f is the replay counter from EAPOL-KEY message
---------------------------------------------------------------------------------------------*/
int Message_SmallerEqualReplayCounter(LARGE_INTEGER li1, OCTET_STRING f)
//f<li1
{
LARGE_INTEGER li2;
Message_ReplayCounter_OC2LI(f, &li2);
if(li2.field.HighPart > li1.field.HighPart)
return 0;
else if(li2.field.HighPart < li1.field.HighPart)
return 1;
else if(li2.field.LowPart > li1.field.LowPart)
return 0;
else if(li2.field.LowPart <= li1.field.LowPart)
return 1;
else
return 0;
}
/*---------------------------------------------------------------------------------------------
li1 is recorded replay counter on STA
f is the replay counter from EAPOL-KEY message
-----------------------------------------------------------------------------------------------*/
int Message_LargerReplayCounter(LARGE_INTEGER li1, OCTET_STRING f)
{
LARGE_INTEGER li2;
Message_ReplayCounter_OC2LI(f, &li2);
//lib1x_message(MESS_DBG_KEY_MANAGE, "Authenticator : HighPart = %d, LowPart = %d\n", li1.field.HighPart, li1.field.LowPart);
//lib1x_message(MESS_DBG_KEY_MANAGE, "Supplicant : HighPart = %d, LowPart = %d\n", li2.field.HighPart, li2.field.LowPart);
if(li2.field.HighPart > li1.field.HighPart)
return 1;
else if(li2.field.LowPart > li1.field.LowPart)
return 1;
else
return 0;
}
void Message_setReplayCounter(OCTET_STRING f, u_long h, u_long l){
LARGE_INTEGER *li = (LARGE_INTEGER *)(f.Octet + ReplayCounterPos);
li->charData[0] = (u_char)(h >> 24) & 0xff;
li->charData[1] = (u_char)(h >> 16) & 0xff;
li->charData[2] = (u_char)(h >> 8) & 0xff;
li->charData[3] = (u_char)(h >> 0) & 0xff;
li->charData[4] = (u_char)(l >> 24) & 0xff;
li->charData[5] = (u_char)(l >> 16) & 0xff;
li->charData[6] = (u_char)(l >> 8) & 0xff;
li->charData[7] = (u_char)(l >> 0) & 0xff;
}
void SetNonce(OCTET_STRING ocDst, OCTET32_INTEGER oc32Counter)
{
u_char *ptr = ocDst.Octet;
long2net(oc32Counter.field.HighPart.field.HighPart.field.HighPart, ptr);
ptr+=4;
long2net(oc32Counter.field.HighPart.field.HighPart.field.LowPart, ptr);
ptr+=4;
long2net(oc32Counter.field.HighPart.field.LowPart.field.HighPart, ptr);
ptr+=4;
long2net(oc32Counter.field.HighPart.field.LowPart.field.LowPart, ptr);
ptr+=4;
long2net(oc32Counter.field.LowPart.field.HighPart.field.HighPart, ptr);
ptr+=4;
long2net(oc32Counter.field.LowPart.field.HighPart.field.LowPart, ptr);
ptr+=4;
long2net(oc32Counter.field.LowPart.field.LowPart.field.HighPart, ptr);
ptr+=4;
long2net(oc32Counter.field.LowPart.field.LowPart.field.LowPart, ptr);
}
#ifdef RTL_WPA2
void SetEAPOL_KEYIV(OCTET_STRING ocDst, OCTET32_INTEGER oc32Counter)
{
u_char *ptr = ocDst.Octet;
long2net(oc32Counter.field.LowPart.field.HighPart.field.HighPart, ptr);
ptr+=4;
long2net(oc32Counter.field.LowPart.field.HighPart.field.LowPart, ptr);
ptr+=4;
long2net(oc32Counter.field.LowPart.field.LowPart.field.HighPart, ptr);
ptr+=4;
long2net(oc32Counter.field.LowPart.field.LowPart.field.LowPart, ptr);
}
#endif /* RTL_WPA2 */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,256 @@
#include "stdafx.h"
#include "stdlib.h"
#include "string.h"
#include "1x_common.h"
#include "1x_kmsm_eapolkey.h"
void i_P_SHA1(
unsigned char* key, // pointer to authentication key
int key_len, // length of authentication key
unsigned char* text, // pointer to data stream
int text_len, // length of data stream
unsigned char* digest, // caller digest to be filled in
int digest_len // in byte
)
{
int i;
int offset=0;
int step=20;
int IterationNum=(digest_len+step-1)/step;
for(i=0;i<IterationNum;i++)
{
text[text_len]=(unsigned char)i;
hmac_sha(key,key_len,text,text_len+1,digest+offset,step);
offset+=step;
}
}
void i_PRF(
unsigned char* secret,
int secret_len,
unsigned char* prefix,
int prefix_len,
unsigned char* random,
int random_len,
unsigned char* digest, // caller digest to be filled in
int digest_len // in byte
)
{
unsigned char data[1000];
memcpy(data,prefix,prefix_len);
data[prefix_len++]=0;
memcpy(data+prefix_len,random,random_len);
i_P_SHA1(secret,secret_len,data,prefix_len+random_len,digest,digest_len);
}
#ifndef COMPACK_SIZE
// PRF : added by Emily
// Length of output is in octets rather than bits
// since length is always a multiple of 8
// output array is organized so first N octets starting from 0
// contains PRF output
//
// supported inputs are 16, 32, 48, 64
// output array must be 80 octets in size to allow for sha1 overflow
//
void PRF(unsigned char *key, int key_len, unsigned char *prefix,
int prefix_len, unsigned char *data, int data_len,
unsigned char *output, int len)
{
int i;
unsigned char input[1024]; // concatenated input
int currentindex = 0;
int total_len;
memcpy(input, prefix, prefix_len);
input[prefix_len] = 0; // single octet 0
memcpy(&input[prefix_len+1], data, data_len);
total_len = prefix_len + 1 + data_len;
input[total_len] = 0; // single octet count, starts at 0
total_len++;
for(i = 0; i < (len+19)/20; i++) {
hmac_sha1(input, total_len, key, key_len, &output[currentindex]);
currentindex += 20; // next concatenation location
input[total_len-1]++; // increment octet count
}
}
#endif
#define A_SHA_DIGEST_LEN 20
/*
* F(P, S, c, i) = U1 xor U2 xor ... Uc
* U1 = PRF(P, S || Int(i))
* U2 = PRF(P, U1)
* Uc = PRF(P, Uc-1)
*/
void F(
char *password,
int passwordlength,
unsigned char *ssid,
int ssidlength,
int iterations,
int count,
unsigned char *output)
{
unsigned char digest[36], digest1[A_SHA_DIGEST_LEN];
int i, j;
/* U1 = PRF(P, S || int(i)) */
memcpy(digest, ssid, ssidlength);
digest[ssidlength] = (unsigned char)((count>>24) & 0xff);
digest[ssidlength+1] = (unsigned char)((count>>16) & 0xff);
digest[ssidlength+2] = (unsigned char)((count>>8) & 0xff);
digest[ssidlength+3] = (unsigned char)(count & 0xff);
hmac_sha1(digest, ssidlength + 4,
(unsigned char*) password, (int)strlen(password),
digest1);
/*
hmac_sha1((unsigned char*) password, passwordlength,
digest, ssidlength+4, digest1);
*/
/* output = U1 */
memcpy(output, digest1, A_SHA_DIGEST_LEN);
for (i = 1; i < iterations; i++) {
/* Un = PRF(P, Un-1) */
hmac_sha1(digest1, A_SHA_DIGEST_LEN, (unsigned char*) password,
(int)strlen(password), digest);
//hmac_sha1((unsigned char*) password, passwordlength,digest1, A_SHA_DIGEST_LEN, digest);
memcpy(digest1, digest, A_SHA_DIGEST_LEN);
/* output = output xor Un */
for (j = 0; j < A_SHA_DIGEST_LEN; j++) {
output[j] ^= digest[j];
}
}
}
/*
* password - ascii string up to 63 characters in length
* ssid - octet string up to 32 octets
* ssidlength - length of ssid in octets
* output must be 40 octets in length and outputs 256 bits of key
*/
int PasswordHash (
char *password,
int passwordlength,
unsigned char *ssid,
int ssidlength,
unsigned char *output)
{
if ((strlen(password) > 63) || (ssidlength > 32))
return 0;
F(password, passwordlength, ssid, ssidlength, 4096, 1, output);
F(password, passwordlength, ssid, ssidlength, 4096, 2, &output[A_SHA_DIGEST_LEN]);
return 1;
}
#ifndef COMPACK_SIZE
void TestPassPhrases()
{
int i;
unsigned char output[3][32];
PasswordHash("password", 8, (unsigned char *)"IEEE", 4, output[0]);
PasswordHash("ThisIsAPassword", 15, (unsigned char *)"ThisIsASSID", 11, output[1]);
PasswordHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 32,
(unsigned char *)"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ", 32 , output[2]);
for(i=0 ; i<3 ; i++)
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "TestPassPhrases", output[i], sizeof(output[i]), "Result key");
}
#endif
#ifndef COMPACK_SIZE
#define PMK_EXPANSION_CONST "Pairwise key expansion"
#define PMK_EXPANSION_CONST_SIZE 22
void TestPRF()
{
u_char PMK[]= {0x0d, 0xc0, 0xd6, 0xeb, 0x90, 0x55, 0x5e, 0xd6,
0x41, 0x97, 0x56, 0xb9, 0xa1, 0x5e, 0xc3, 0xe3,
0x20, 0x9b, 0x63, 0xdf, 0x70, 0x7d, 0xd5, 0x08,
0xd1, 0x45, 0x81, 0xf8, 0x98, 0x27, 0x21, 0xaf};
u_char AA[]= {0xa0, 0xa1, 0xa1, 0xa3, 0xa4, 0xa5};
u_char SA[]= {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5};
u_char SNonce[]={0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9};
u_char ANonce[]={0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9};
u_char Data[256];
u_char tmpPTK[128];
memset(Data, 0, sizeof Data);
memcpy(Data, AA, sizeof AA);
memcpy(Data+6, SA, sizeof SA);
memcpy(Data+12,SNonce, sizeof SNonce);
memcpy(Data+32,ANonce, sizeof ANonce);
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "TestPRF", Data, 52, "Data");
i_PRF(PMK, sizeof PMK, (u_char*)PMK_EXPANSION_CONST,
PMK_EXPANSION_CONST_SIZE, Data,52,
tmpPTK, PTK_LEN_TKIP);
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "TestPRF", tmpPTK, 64, "KEY");
}
#endif
#ifndef COMPACK_SIZE
//#include <openssl/rc4.h>
#include "1x_rc4.h"
void TestRC4()
{
u_char Key[] ={0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
u_char Input[] ={0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
u_char Output[8]; //= {0x75, 0xb7, 0x87, 0x80, 0x99, 0xe0, 0xc5, 0x96 }
RC4_KEY rc4key;
RC4_set_key(&rc4key, sizeof Key, Key);
RC4(&rc4key, sizeof Input, (u_char*)Input, Output);
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "TestRC4", Output, sizeof Output, "CipherText");
}
#endif
#ifndef COMPACK_SIZE
void testMIC()
{
u_char data[] ={
0x1, 0x3, 0x0, 0x79, 0xfe, 0x1, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x9d, 0xb2, 0x5, 0xec, 0xf0, 0xfa, 0x79, 0x8b, 0x7f, 0x2c, 0x77, 0xc8, 0xd6, 0x79, 0xf0,
0xfb, 0xe, 0x8f, 0xa3, 0xe1, 0x2, 0x18, 0xce, 0xf3, 0xd7, 0x62, 0xe1, 0xb, 0x6c, 0x63, 0x33,
0x4f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,0x0,
0x0, 0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0, 0x0, 0x0, 0x0,
0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0,
0x0,0x0, 0x1a, 0xdd, 0x18, 0x0, 0x50, 0xf2, 0x1, 0x1, 0x0, 0x0, 0x50,0xf2, 0x2, 0x1,
0x0, 0x0, 0x50, 0xf2, 0x1, 0x1, 0x0, 0x0, 0x50, 0xf2, 0x2, 0xa , 0x0};
u_char key[] =
{0x92, 0x4e, 0xbc, 0xb0, 0x64, 0x70, 0xc7, 0x7e, 0x6d, 0xe1, 0x1, 0xc5, 0xe9, 0x27, 0x81, 0xc3};
u_char micout[16];
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "testMIC", data, sizeof data, "data");
hmac_md5((u_char*)data, sizeof(data)-12 , key, sizeof key, micout);
lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "testMIC", micout, sizeof micout, "micout");
//lib1x_hmac_md5((u_char*)data, sizeof(data)-12 , key, sizeof key, micout);
//lib1x_hexdump2(MESS_DBG_KEY_MANAGE, "testMIC", micout, sizeof micout, "micout");
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,73 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_krc_sm.c
// Programmer : Arunesh Mishra
// Key Receive State Machine Implementation
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
#include "1x_common.h"
#include "1x_krc_sm.h"
#include <stddef.h>
void lib1x_krcsm_init( Krc_SM * krc_sm )
{
assert( krc_sm != NULL );
krc_sm->state = krcsm_No_Key_Receive;
krc_sm->rxKey = FALSE;
}
//--------------------------------------------------
// lib1x_trans_krcsm:
// One transition of the Key Receive State Machine.
//--------------------------------------------------
void lib1x_trans_krcsm( Global_Params * global, Krc_SM * krc_sm )
{
if ( global->initialize || ! global->portEnabled )
{
krc_sm->state = krcsm_No_Key_Receive;
return;
}
if ( krc_sm->state == krcsm_No_Key_Receive )
{
if ( krc_sm->rxKey == TRUE )
{
krc_sm->state = krcsm_Key_Receive;
lib1x_krcsm_processKey(); // TODO
krc_sm->state = FALSE;
return;
}
return;
}
if ( krc_sm->state == krcsm_Key_Receive )
{
if ( krc_sm->rxKey == TRUE )
{
krc_sm->state = krcsm_Key_Receive;
lib1x_krcsm_processKey(); // TODO
krc_sm->state = FALSE;
return;
}
}
}
//--------------------------------------------------
// Key process. TODO
//--------------------------------------------------
void lib1x_krcsm_processKey()
{
lib1x_message( MESS_DBG_KRCSM," Key Receive State Machine: PROCESS KEY ?");
}

View File

@ -0,0 +1,293 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_kxsm.c
// Programmer : Arunesh Mishra
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
// Key Transmit State Machine
//--------------------------------------------------
#include "1x_kxsm.h"
#include "1x_common.h"
#include "1x_auth_pae.h"
#include "1x_ioctl.h"
#include "1x_eapol.h"
#include "1x_kmsm_eapolkey.h"
#include "1x_nal.h"
#include <stddef.h>
//#include <openssl/hmac.h>
//#include <openssl/evp.h>
#include "1x_rc4.h"
//--------------------------------------------------
// init function for the Authenticator Key Transmit State Machine.
//--------------------------------------------------
void lib1x_kxsm_init( Auth_KeyxmitSM * key_sm )
{
assert( key_sm != NULL );
key_sm->state = kxsm_No_Key_Transmit;
key_sm->keyAvailable = FALSE;
key_sm->keyTxEnabled = TRUE;
}
//--------------------------------------------------
// lib1x_trans_authxmitsm:
// This function implements one transition of the Authenticator Key Transmit State Machine.
//--------------------------------------------------
void lib1x_trans_kxsm( Auth_Pae * auth_pae, Global_Params * global, Auth_KeyxmitSM * key_sm )
{
if(global->AuthKeyMethod != DOT11_AuthKeyType_NonRSN802dot1x ||
(global->AuthKeyMethod == DOT11_AuthKeyType_NonRSN802dot1x && global->RSNVariable.UnicastCipher == DOT11_ENC_NONE && global->RSNVariable.MulticastCipher == DOT11_ENC_NONE) )
return;
if(key_sm->keyAvailable)
lib1x_message(MESS_DBG_KXSM, "key_sm->keyAvailable=%d\n", key_sm->keyAvailable);
// Global condition first :
if ( global->initialize || global->portControl != pmt_Auto )
{
key_sm->state = kxsm_No_Key_Transmit;
// Note: No initialization for this state.
return;
}
if ( key_sm->state == kxsm_No_Key_Transmit &&
( key_sm->keyTxEnabled && key_sm->keyAvailable &&
( global->portStatus == pst_Authorized ) )
)
{
key_sm->state = kxsm_Key_Transmit;
lib1x_kxsm_key_transmit( auth_pae, global, key_sm );
return;
}
if ( key_sm->state == kxsm_Key_Transmit &&
key_sm->keyAvailable )
{
// Next state is the same state : key_transmit
lib1x_kxsm_key_transmit( auth_pae, global, key_sm );
return;
}
if ( key_sm->state == kxsm_Key_Transmit &&
( ! key_sm->keyTxEnabled || global->portStatus == pst_Unauthorized ) )
{
key_sm->state = kxsm_No_Key_Transmit;
// Note : No initialization for entry to this state.
return;
}
}
//--------------------------------------------------
// lib1x_authxmitsm_key_transmit:
// This function has the initialization for entry to state Key_Transmit for the
// Authenticator Key Transmit State Machine.
//--------------------------------------------------
void lib1x_kxsm_key_transmit( Auth_Pae * auth_pae, Global_Params * global, Auth_KeyxmitSM * key_sm )
{
struct lib1x_ethernet * eth;
struct lib1x_eapol * eapol;
struct lib1x_eapolkey_dot1x *eapol_key;
OCTET_STRING ocCounter = {.Octet=NULL, .Length=0};
u_long ulKeyLen = 5;
RC4_KEY rc4key;
//TODO read default key with ioctl
/*
u_char szDefaultKey[16] = {0x11, 0x11,0x11, 0x11,0x11, 0x11,0x11, 0x11,
0x11, 0x11,0x11, 0x11,0x11, 0x11,0x11, 0x11};
*/
u_char szIV[16] = {0x22, 0x22,0x22, 0x22,0x22, 0x22,0x22, 0x22,
0x22, 0x22,0x22, 0x22,0x22, 0x22,0x22, 0x22};
u_char szKeyBuf[64];
// Set the from / to ethernet addresses.
memset(auth_pae->sendBuffer, 0, 100);
eth = ( struct lib1x_ethernet * ) auth_pae->sendBuffer;
memcpy ( eth->ether_dhost, auth_pae->supp_addr, ETHER_ADDRLEN);
memcpy ( eth->ether_shost, auth_pae->global->TxRx->oursupp_addr, ETHER_ADDRLEN);
eth->ether_type = htons( LIB1X_ETHER_EAPOL_TYPE );
eapol = ( struct lib1x_eapol * )( auth_pae->sendBuffer + ETHER_HDRLEN );
eapol->protocol_version = LIB1X_EAPOL_VER;
eapol->packet_type = LIB1X_EAPOL_KEY;
if(global->RSNVariable.UnicastCipher == DOT11_ENC_WEP40)
ulKeyLen = 5;
else if(global->RSNVariable.UnicastCipher == DOT11_ENC_WEP104)
ulKeyLen = 13;
//
else if(global->RSNVariable.UnicastCipher == DOT11_ENC_NONE)
ulKeyLen = 13;
//
if(auth_pae->sendreplyready == TRUE)
{
//----------------------------------------
//(1)Send Group Key using default key
//----------------------------------------
eapol_key = (struct lib1x_eapolkey_dot1x *) ( ( (u_char *) eapol) + LIB1X_EAPOL_HDRLEN );
eapol_key->type = LIB1X_KEY_TYPE_RC4;
lib1x_S2N(ulKeyLen, (u_char*)&eapol_key->length);
ocCounter.Octet = (u_char*)malloc(LIB1X_RC_LEN);
ocCounter.Length = LIB1X_RC_LEN;
ReplayCounter_LI2OC(ocCounter, &global->auth->Dot1xKeyReplayCounter);
memcpy(eapol_key->counter, ocCounter.Octet, LIB1X_RC_LEN);
INCLargeInteger(&global->auth->Dot1xKeyReplayCounter);
//printf("Higg = %d, Low = %d\n", global->auth->Dot1xKeyReplayCounter.field.HighPart,
//global->auth->Dot1xKeyReplayCounter.field.LowPart);
//TODO:Generate Random number as Key IV
memcpy(eapol_key->iv, szIV, LIB1X_IV_LEN);
eapol_key->index = 0;
eapol_key->index |= (EAPOL_GROUP_KEY|EAPOL_GROUP_INDEX);
memcpy(szKeyBuf, szIV, LIB1X_IV_LEN);
memcpy(&szKeyBuf[16], global->RadiusKey.RecvKey.Octet, global->RadiusKey.RecvKey.Length);
RC4_set_key(&rc4key, LIB1X_IV_LEN + global->RadiusKey.RecvKey.Length, szKeyBuf);
//lib1x_hexdump2(MESS_DBG_RAD, "TestFun", szKeyBuf, LIB1X_IV_LEN + global->RadiusKey.RecvKey.Length, "szKeyBuf");
//Need to be removed
/*
memcpy( global->auth->gk_sm->GTK[global->auth->gk_sm->GN] ,
szDefaultKey,
global->RSNVariable.MulticastCipher == DOT11_ENC_WEP40 ? 5:13);
*/
//RC4(&rc4key, ulKeyLen, (u_char*)szDefaultKey, (u_char*)(eapol_key->material));
RC4(&rc4key, ulKeyLen, (u_char*)global->auth->WepGroupKey, (u_char*)(eapol_key->material));
eapol->packet_body_length = htons(LIB1X_EAPOLKEY_HDRLEN + ulKeyLen);
//lib1x_hexdump2(MESS_DBG_KXSM, "lib1x_kxsm_key_transmit", auth_pae->sendBuffer, 100, "snedBuffer");
memset(eapol_key->mic, 0, sizeof(eapol_key->mic));
hmac_md5((u_char*)eapol,
LIB1X_EAPOL_HDRLEN + LIB1X_EAPOLKEY_HDRLEN + ulKeyLen,
global->RadiusKey.SendKey.Octet,
global->RadiusKey.SendKey.Length,
eapol_key->mic);
auth_pae->sendbuflen = ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN + LIB1X_EAPOLKEY_HDRLEN + ulKeyLen;
#ifdef ALLOW_DBG_KXSM
lib1x_hexdump2(MESS_DBG_KXSM, "lib1x_kxsm_key_transmit", auth_pae->sendBuffer, auth_pae->sendbuflen, "Send EAPOL-KEY of Group Key");
#endif
if(global->auth->RSNVariable.MulticastCipher == DOT11_ENC_WEP40 ||
global->auth->RSNVariable.MulticastCipher == DOT11_ENC_WEP104)
lib1x_nal_send( auth_pae->global->TxRx->network_supp, (char *)auth_pae->sendBuffer,
auth_pae->sendbuflen );
lib1x_control_SetGTK(global);
//----------------------------------------
//(2)Send Key-mapping-Key
//----------------------------------------
eapol_key = (struct lib1x_eapolkey_dot1x *) ( ( (u_char *) eapol) + LIB1X_EAPOL_HDRLEN );
eapol_key->type = LIB1X_KEY_TYPE_RC4;
lib1x_S2N(ulKeyLen, (u_char*)&eapol_key->length);
ocCounter.Length = LIB1X_RC_LEN;
ReplayCounter_LI2OC(ocCounter, &global->auth->Dot1xKeyReplayCounter);
memcpy(eapol_key->counter, ocCounter.Octet, LIB1X_RC_LEN);
INCLargeInteger(&global->auth->Dot1xKeyReplayCounter);
//printf("Higg = %d, Low = %d\n", global->auth->Dot1xKeyReplayCounter.field.HighPart,
//global->auth->Dot1xKeyReplayCounter.field.LowPart);
//TODO:Generate Random number as Key IV
memcpy(eapol_key->iv, szIV, LIB1X_IV_LEN);
eapol_key->index = 0;
eapol_key->index |= (EAPOL_PAIRWISE_KEY|EAPOL_PAIRWISE_INDEX);
eapol->packet_body_length = htons(LIB1X_EAPOLKEY_HDRLEN);
memset(eapol_key->mic, 0, sizeof(eapol_key->mic));
hmac_md5((u_char*)eapol,
LIB1X_EAPOL_HDRLEN + LIB1X_EAPOLKEY_HDRLEN,
global->RadiusKey.SendKey.Octet,
global->RadiusKey.SendKey.Length,
eapol_key->mic);
auth_pae->sendbuflen = ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN + LIB1X_EAPOLKEY_HDRLEN;
#ifdef ALLOW_DBG_KXSM
lib1x_hexdump2(MESS_DBG_KXSM, "lib1x_kxsm_key_transmit", auth_pae->sendBuffer, auth_pae->sendbuflen, "Send EAPOL-KEY of key-mapping-key");
#endif
if(global->RSNVariable.UnicastCipher == DOT11_ENC_WEP40 ||
global->RSNVariable.UnicastCipher == DOT11_ENC_WEP104)
lib1x_nal_send( auth_pae->global->TxRx->network_supp,
(char *)auth_pae->sendBuffer,auth_pae->sendbuflen );
//----Set key-mapping key to driver
//----Key Mapping is for 5280
//lib1x_control_KeyMapping(global, KEYMAP_OPERATION_SET, WEP_MODE_ON_40, KEYMAP_VALID_ON);
//----SetPTK is for software encryption
lib1x_control_SetPORT(global, DOT11_PortStatus_Authorized);
lib1x_control_SetPTK(global);
}
//lib1x_authxmitsm_txKey( auth_pae , global->currentId ); // TODO
auth_pae->sendreplyready = FALSE;
key_sm->keyAvailable = FALSE;
global->RadiusKey.Status = MPPE_SDRCKEY_NONAVALIABLE;
free(ocCounter.Octet);
}
#ifndef COMPACK_SIZE
//--------------------------------------------------
// Transmit key to authenticator. TODO
//--------------------------------------------------
void lib1x_authxmitsm_txKey( Auth_Pae * auth_pae, int currentId )
{
if ( auth_pae->sendreplyready ) /* if we prefabricated */
{
lib1x_nal_send( auth_pae->global->TxRx->network_supp, auth_pae->sendBuffer,
auth_pae->sendbuflen );
auth_pae->sendreplyready = FALSE;
}
lib1x_message(MESS_DBG_KXSM,"Key Transmit SM: Transmit Key to Authenticator");
}
#endif

View File

@ -0,0 +1,414 @@
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
//#include "8021x.h"
#include "1x_md5c.h"
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
static void MD5Transform(UINT4 [4], UINT8 [64]);
static void Encode(UINT8 *, UINT4 *, UINT32);
static void Decode(UINT4 *, UINT8 *, UINT32);
static void MD5_memcpy(POINTER, POINTER, UINT32);
static void MD5_memset(POINTER, int, UINT32);
static UINT8 PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
/* MD5 initialization. Begins an MD5 operation, writing a new context.
*/
void MD5_Init (context)
MD5_CTX *context; /* context */
{
context->count[0] = context->count[1] = 0;
/* Load magic initialization constants.
*/
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
/* MD5 block update operation. Continues an MD5 message-digest
operation, processing another message block, and updating the
context.
*/
void MD5_Update (context, input, inputLen)
MD5_CTX *context; /* context */
UINT8 *input; /* input block */
UINT32 inputLen; /* length of input block */
{
UINT32 i, index, partLen;
/* Compute number of bytes mod 64 */
index = (UINT32)((context->count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((context->count[0] += ((UINT4)inputLen << 3))
< ((UINT4)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT4)inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible.
*/
if (inputLen >= partLen) {
MD5_memcpy
((POINTER)&context->buffer[index], (POINTER)input, partLen);
MD5Transform (context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform (context->state, &input[i]);
index = 0;
}
else
i = 0;
/* Buffer remaining input */
MD5_memcpy
((POINTER)&context->buffer[index], (POINTER)&input[i],
inputLen-i);
}
/* MD5 finalization. Ends an MD5 message-digest operation, writing the
the message digest and zeroizing the context.
*/
void MD5_Final (digest, context)
UINT8 digest[16]; /* message digest */
MD5_CTX *context; /* context */
{
UINT8 bits[8];
UINT32 index, padLen;
/* Save number of bits */
Encode (bits, context->count, 8);
/* Pad out to 56 mod 64.
*/
index = (UINT32)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
MD5_Update (context, PADDING, padLen);
/* Append length (before padding) */
MD5_Update (context, bits, 8);
/* Store state in digest */
Encode (digest, context->state, 16);
/* Zeroize sensitive information.
*/
MD5_memset ((POINTER)context, 0, sizeof (*context));
}
/* MD5 basic transformation. Transforms state based on block.
*/
static void MD5Transform (state, block)
UINT4 state[4];
UINT8 block[64];
{
UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode (x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information.
*/
MD5_memset ((POINTER)x, 0, sizeof (x));
}
/* Encodes input (UINT4) into output (UINT8). Assumes len is
a multiple of 4.
*/
static void Encode (output, input, len)
UINT8 *output;
UINT4 *input;
UINT32 len;
{
UINT32 i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (UINT8)(input[i] & 0xff);
output[j+1] = (UINT8)((input[i] >> 8) & 0xff);
output[j+2] = (UINT8)((input[i] >> 16) & 0xff);
output[j+3] = (UINT8)((input[i] >> 24) & 0xff);
}
}
/* Decodes input (UINT8) into output (UINT4). Assumes len is
a multiple of 4.
*/
static void Decode (output, input, len)
UINT4 *output;
UINT8 *input;
UINT32 len;
{
UINT32 i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
(((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
}
/* Note: Replace "for loop" with standard memcpy if possible.
*/
static void MD5_memcpy (output, input, len)
POINTER output;
POINTER input;
UINT32 len;
{
UINT32 i;
for (i = 0; i < len; i++)
output[i] = input[i];
}
/* Note: Replace "for loop" with standard memset if possible.
*/
static void MD5_memset (output, value, len)
POINTER output;
int value;
UINT32 len;
{
UINT32 i;
for (i = 0; i < len; i++)
((char *)output)[i] = (char)value;
}
#if 0
/*
UINT8* text; pointer to data stream
int text_len; length of data stream
UINT8* key; pointer to authentication key
int key_len; length of authentication key
UINT8* digest; caller digest to be filled in
*/
void hmac_md5(UINT8 *text, INT32 text_len, UINT8 *key, INT32 key_len,UINT8 *digest)
{
MD5_CTX context;
UINT8 k_ipad[65]; /* inner padding -
* key XORd with ipad
*/
UINT8 k_opad[65]; /* outer padding -
* key XORd with opad
*/
UINT8 tk[16];
int i;
/* if key is longer than 64 bytes reset it to key=MD5(key) */
if (key_len > 64) {
MD5_CTX tctx;
MD5Init(&tctx);
MD5Update(&tctx, key, key_len);
MD5Final(tk, &tctx);
key = tk;
key_len = 16;
}
/*
* the HMAC_MD5 transform looks like:
*
* MD5(K XOR opad, MD5(K XOR ipad, text))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and text is the data being protected
*/
/* start out by storing key in pads */
memset(k_ipad, 0x0, sizeof(k_ipad));
memset(k_opad, 0x0, sizeof(k_opad));
memcpy(k_ipad, key, key_len);
memcpy(k_opad, key, key_len);
//bzero( k_ipad, sizeof k_ipad);
//bzero( k_opad, sizeof k_opad);
//bcopy( key, k_ipad, key_len);
//bcopy( key, k_opad, key_len);
/* XOR key with ipad and opad values */
for (i=0; i<64; i++) {
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
/*
* perform inner MD5
*/
MD5Init(&context); /* init context for 1st
* pass */
MD5Update(&context, k_ipad, 64); /* start with inner pad */
MD5Update(&context, text, text_len); /* then text of datagram */
MD5Final(digest, &context); /* finish up 1st pass */
/*
* perform outer MD5
*/
MD5Init(&context); /* init context for 2nd
* pass */
MD5Update(&context, k_opad, 64); /* start with outer pad */
MD5Update(&context, digest, 16); /* then results of 1st
* hash */
MD5Final(digest, &context); /* finish up 2nd pass */
}
#endif

View File

@ -0,0 +1,62 @@
/*
* 8021x_md5c.h - header file for MD5C.C
*/
#ifndef P8021X_MD5C_H
#define P8021X_MD5C_H
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
/* MD5_TYPE.H - RSAREF types and constants */
/* POINTER defines a generic pointer type */
typedef unsigned char *POINTER;
/* UINT2 defines a two byte word */
typedef unsigned short int UINT2;
/* UINT4 defines a four byte word */
typedef unsigned long int UINT4;
/* UINT4 defines a four byte word */
typedef unsigned char UINT8;
typedef unsigned long UINT32;
typedef int INT32;
/* MD5 context. */
typedef struct {
UINT4 state[4]; /* state (ABCD) */
UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} MD5_CTX;
void MD5_Init(MD5_CTX *);
void MD5_Update(MD5_CTX *, UINT8 *, UINT32);
void MD5_Final(unsigned char [16], MD5_CTX *);
//void hmac_md5(UINT8 *, INT32, UINT8 * , INT32, UINT8 * );
#endif

View File

@ -0,0 +1,931 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_nal
// Programmer : Arunesh Mishra
// This file implements the 1x-Network Abstraction
// Layer part.
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/poll.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#ifdef __ANDROID__
#include <err.h>
#else
#include <error.h>
#endif
#include <string.h>
#include "1x_nal.h"
#include "1x_ethernet.h"
#include "1x_eapol.h"
#include "1x_auth_pae.h"
#include "1x_fifo.h"
#include "1x_ioctl.h"
#ifdef RTL_WPA_CLIENT
#include "1x_supp_pae.h"
extern Dot1x_Client RTLClient;
#endif
#ifdef START_AUTH_IN_LIB
extern int read_wlan_evt( int skfd, char *ifname, char *out);
#endif
#define EAP_BY_QUEUE
//--------------------------------------------------
// initialize pkt sender and receiver
// TODO: currently cannot get our own ethernet
// addr .. needs to be fixed.
//--------------------------------------------------
struct lib1x_nal_intfdesc * lib1x_nal_initialize( u_char * intdev , u_char * ouraddr, u_char inttype)
{
struct lib1x_nal_intfdesc * desc;
#ifndef EAP_BY_QUEUE
struct ifreq ifr;
int flags;
int retval;
#endif
if ( intdev == NULL )
lib1x_message( MESS_ERROR_FATAL, "lib1x_nal_intfdesc: Received NULL interface to open.");
//1. General initializations
desc = ( struct lib1x_nal_intfdesc * ) malloc( sizeof ( struct lib1x_nal_intfdesc ) );
strncpy((char *)desc->device, (char *)intdev, LIB1X_MAXDEVLEN);
desc->device[LIB1X_MAXDEVLEN] = '\0';
desc->inttype = inttype;
memcpy( desc->ouraddr, ouraddr, ETHER_ADDRLEN);
//2. Specific to the listener
desc->promisc_mode = LIB1X_LSTNR_PROMISCMODE;
desc->snaplen = LIB1X_LSTNR_SNAPLEN;
desc->read_timeout = LIB1X_LSTNR_RDTIMEOUT;
//desc->packet_handler = NULL ;
//desc->global = global; // not sure if we need this sort of backlink
//sc_yang
#if 0
//desc->pcap_desc = lib1x_nal_setup_pcap( desc );
if ( desc->pcap_desc == NULL )
{
fprintf(stderr," Could not open device : %s", intdev );
exit(1);
}
#endif
/* 1. Create a socket */
#ifndef EAP_BY_QUEUE
desc->pf_sock = socket( PF_PACKET, SOCK_RAW, htons(ETH_P_ALL ) ); // P_ALL coz we dont have P_EAPOL yet in if_ether.h !
if ( desc->pf_sock > 0 ) lib1x_message( MESS_DBG_NAL,"PF_PACKET socket created ");
#endif
// kenny
// desc->pf_sock = pcap_fileno(desc->pcap_desc);
if ( inttype == LIB1X_IT_PKTSOCK )
{
#ifndef EAP_BY_QUEUE
/* 2. Bind to an eth interface */
/* to do the bind we need to get if_index i.e. the interface index */
strncpy( ifr.ifr_name, desc->device, IFNAMSIZ -1 );
if ( ( retval = ioctl( desc->pf_sock, SIOCGIFINDEX , & ifr )) < 0 ) /* SIOCGIFINDEX gets the if_index into the ifr struct */
lib1x_message( MESS_ERROR_FATAL, "nal: IOCTL failed on %s", desc->device );
// prepare for bind .. : man netdevice
desc->sock_device.sll_protocol = htons( ETH_P_ALL );
desc->sock_device.sll_family = AF_PACKET;
desc->sock_device.sll_ifindex = ifr.ifr_ifindex;
if ( ( retval = bind( desc->pf_sock, (struct sockaddr *)&desc->sock_device, sizeof(struct sockaddr_ll ))) != 0 )
lib1x_message( MESS_ERROR_FATAL, "nal: BIND failed on %s retval : %d errorstr : %s", desc->device , retval, strerror(errno));
flags = fcntl(desc->pf_sock, F_GETFL );
if ( fcntl( desc->pf_sock, F_SETFL, flags | O_NONBLOCK) != 0 )
lib1x_message( MESS_ERROR_FATAL, "nal: FCNTL failed on %s", desc->device );
#endif
//3. Specific to the transmitter
desc->libnet_desc = libnet_open_link_interface( (char *)intdev , (char *)desc->l_errbuf );
if ( desc->libnet_desc == NULL )
lib1x_message( MESS_ERROR_FATAL, "lib1x_nal_intfdesc: Could not open libnet interface ");
}
else
{
//---- Radius Authentication Server
desc->udpsock = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP);\
if ( desc->udpsock == -1 )
lib1x_message(MESS_ERROR_FATAL,"lib1x_nal_initialize: Could not open Radius Authentication UDP socket !");
desc->acctsock = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP);\
if ( desc->acctsock == -1 )
lib1x_message(MESS_ERROR_FATAL,"lib1x_nal_initialize: Could not open Radius Accounting UDP socket !");
// flags = fcntl(desc->udpsock, F_GETFL );
// if ( fcntl( desc->udpsock, F_SETFL, flags | O_NONBLOCK) != 0 )
// lib1x_message( MESS_ERROR_FATAL, "nal: FCNTL failed on UDP socket" );
}
desc->packet_buffer = ( u_char * ) malloc( LIB1X_MAXEAPLEN * sizeof(u_char));
return desc;
}
//--------------------------------------------------
// Bind to the RADIUS server, and connect: this function specifically
// for the wired interface.
// Return 0: Success, Return -1 Fail
//--------------------------------------------------
int lib1x_nal_connect( struct lib1x_nal_intfdesc * desc, /*u_short udp_ourport,*/ struct sockaddr_in *svraddr ,
int addrlen, int udpsock_type)
{
int flags;
struct sockaddr_in myaddr;
if ( desc->inttype != LIB1X_IT_UDPSOCK )
return -1;
// First bind to a local port
memset( &myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(0);
switch(udpsock_type)
{
case LIB1X_IT_UDPSOCK_AUTH:
if ( bind( desc->udpsock, (struct sockaddr *) & myaddr, sizeof( struct sockaddr_in)) != 0)
lib1x_message( MESS_ERROR_FATAL,"Could not BIND Authentication server UDP socket.");
desc->radsvraddr = svraddr;
if (svraddr == NULL )
{
lib1x_message(MESS_DBG_NAL,"lib1x_nal_connect: NULL argument svraddr ");
return -1;
}
// wait till succeed
while (1) {
if (connect( desc->udpsock, (struct sockaddr *)svraddr, addrlen ) != 0 )
{
lib1x_message(MESS_DBG_NAL,"lib1x_nal_connect: Could not connect to Authentication Server . ");
sleep(1);
}
else
break;
}
flags = fcntl(desc->udpsock, F_GETFL );
if ( fcntl( desc->udpsock, F_SETFL, flags | O_NONBLOCK) != 0 )
lib1x_message( MESS_ERROR_FATAL, "lib1x_nal_connect : FCNTL failed on UDP socket" );
break;
case LIB1X_IT_UDPSOCK_ACCT:
if ( bind( desc->acctsock, (struct sockaddr *) & myaddr, sizeof( struct sockaddr_in)) != 0)
lib1x_message( MESS_ERROR_FATAL,"Could not BIND Accounting server UDP socket.");
desc->acctsvraddr = svraddr;
if (svraddr == NULL )
{
lib1x_message(MESS_DBG_NAL,"lib1x_nal_connect: NULL argument svraddr ");
return -1;
}
if ( connect( desc->acctsock, (struct sockaddr *)svraddr, addrlen ) != 0 )
{
lib1x_message(MESS_DBG_NAL,"lib1x_nal_connect: Could not connect to Accounting Server. ");
return -1;
}
flags = fcntl(desc->acctsock, F_GETFL );
if ( fcntl( desc->acctsock, F_SETFL, flags | O_NONBLOCK) != 0 )
lib1x_message( MESS_ERROR_FATAL, "lib1x_nal_connect : FCNTL failed on UDP socket" );
break;
default:
break;
}
return 0;
//--- TESTING PART
/*
for ( i = 0; i < 100; i ++ )
pkt[i] = (u_char) i % 255;
//errcode = sendto( desc->udpsock, (u_char *) pkt, 99, 0, desc->radsvraddr, sizeof( struct sockaddr_in));
errcode = sendto( desc->acctsock, (u_char *) pkt, 99, 0, desc->acctsvraddr, sizeof( struct sockaddr_in));
if(errcode <= 0)
printf("\n\n HEY the error for lib1x_nal_connect is %s", strerror(errno) );
fflush(stdout);
*/
}
#if 0 //sc_yang
/* just print a count every time we have a packet... */
void my_callback(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char*
packet)
{
static int count = 1;
fprintf(stdout,"%d, ",count);
fflush(stdout);
count++;
}
//--------------------------------------------------
// initializes pcap
//--------------------------------------------------
pcap_t * lib1x_nal_setup_pcap( struct lib1x_nal_intfdesc * nd )
{
pcap_t* pcap_descr; /* pcap connection */
bpf_u_int32 pcap_maskp; /* subnet mask */
bpf_u_int32 pcap_netp; /* ip (not really sure) */
char pcap_filter[100]; /* filter for EAPOL pack */
struct bpf_program pcap_fp; /* To hold the compiled filter */
u_char * eapol_src;
pcap_lookupnet( nd->device , &pcap_netp, &pcap_maskp, nd->p_errbuf );
pcap_descr = pcap_open_live( nd->device, nd->snaplen, 0, -1, nd->p_errbuf);
/* Open Socket */
if(pcap_descr == NULL)
{
printf("pcap_open_live(): %s\n", nd->p_errbuf);
exit(1);
}
eapol_src = nd->ouraddr;
/* Setup filter */
sprintf(pcap_filter, "ether dst %x:%x:%x:%x:%x:%x and ether proto 0x%x",
eapol_src[0], eapol_src[1], eapol_src[2], eapol_src[3],
eapol_src[4], eapol_src[5], LIB1X_ETHER_EAPOL_TYPE );
//sprintf(pcap_filter, "ether proto 0x%x", LIB1X_ETHER_EAPOL_TYPE );
if(pcap_compile(pcap_descr,&pcap_fp,pcap_filter,0,pcap_netp) == -1)
{
fprintf(stderr,"Error calling pcap_compile\n");
exit(1);
}
//sprintf(pcap_filter, "src 172.20.13.220");
//printf("SET FILTER: %s\n", pcap_filter);
/*
if(pcap_compile(pcap_descr,&pcap_fp,pcap_filter,0,pcap_netp) == -1)
{
fprintf(stderr,"Error calling pcap_compile\n");
exit(1);
}
*/
if(pcap_setfilter(pcap_descr,&pcap_fp) == -1)
{
fprintf(stderr,"Error setting filter\n");
exit(1);
}
//pcap_loop(pcap_descr,-1,my_callback,NULL);
return pcap_descr;
}
#endif //sc_yang
//--------------------------------------------------
// lib1x_nal_receivepoll:
// This function polls the interface for any packets
// that might have come.
// TODO: Currently we expose the libpcap handler to
// the EAP layer. We need to put a level of abstraction here.
//--------------------------------------------------
int lib1x_nal_receive(Dot1x_Authenticator * auth)
{
struct lib1x_nal_intfdesc * descSupp = auth->GlobalTxRx->network_supp;
#ifdef RTL_RADIUS_2SET
struct lib1x_nal_intfdesc * descSvr2 = auth->GlobalTxRx->network_svr2;
#endif
int suppid;
#ifdef PSK_ONLY
int nRead=0;
#ifndef START_AUTH_IN_LIB
fd_set fsRead;
#endif
#else
struct lib1x_nal_intfdesc * descSvr = auth->GlobalTxRx->network_svr;
int numread;
int res;
fd_set fsRead;
struct timeval tvTimeOut;
int iFD_SETSIZE = 0;
tvTimeOut.tv_sec = 0;
tvTimeOut.tv_usec = 0;
FD_ZERO ( &fsRead);
#ifndef EAP_BY_QUEUE
FD_SET( descSupp->pf_sock, &fsRead);
iFD_SETSIZE = descSupp->pf_sock;
#endif
if(auth->RSNVariable.Dot1xEnabled || auth->RSNVariable.MacAuthEnabled)
{
FD_SET( descSvr->udpsock, &fsRead);
iFD_SETSIZE = (iFD_SETSIZE > descSvr->udpsock)?iFD_SETSIZE:descSvr->udpsock;
if(auth->AccountingEnabled)
{
FD_SET( descSvr->acctsock, &fsRead);
iFD_SETSIZE = (iFD_SETSIZE > descSvr->acctsock)?iFD_SETSIZE:descSvr->acctsock;
}
#ifdef RTL_RADIUS_2SET
if (auth->use_2nd_rad)
{
FD_SET( descSvr2->udpsock, &fsRead);
iFD_SETSIZE = (iFD_SETSIZE > descSvr2->udpsock)?iFD_SETSIZE:descSvr2->udpsock;
}
#endif
}
FD_SET( auth->GlobalTxRx->readfifo, &fsRead);
iFD_SETSIZE = (iFD_SETSIZE > auth->GlobalTxRx->readfifo)?iFD_SETSIZE:auth->GlobalTxRx->readfifo;
iFD_SETSIZE += 1;
// david
// res = select( iFD_SETSIZE, &fsRead, NULL, NULL, &tvTimeOut);
res = select( iFD_SETSIZE, &fsRead, NULL, NULL, NULL);
if ( res <= 0 )
{
return 0;
}
else
{
#ifndef EAP_BY_QUEUE
if(FD_ISSET(descSupp->pf_sock, &fsRead))
{
numread = recv( descSupp->pf_sock, descSupp->packet_buffer, LIB1X_MAXEAPLEN , 0);
if ( numread <= 0 )
{
lib1x_message(MESS_ERROR_FATAL," NUMREAD = 0 after recv !");
return 0;
}
descSupp->packet.caplen = numread;
descSupp->packet.data = descSupp->packet_buffer;
#ifdef RTL_WPA_CLIENT
// david ----------------
#if 0
if(auth->currentRole == role_Supplicant)
{
lib1x_suppsm_capture_auth( auth->client->global, descSupp, & descSupp->packet );
}else
#endif
if(auth->currentRole == role_Supplicant_infra)
{
lib1x_suppsm_capture_auth( auth->client->global, descSupp, & descSupp->packet );
}else if (auth->currentRole == role_Authenticator)
//------------------------
#endif
{
suppid = lib1x_search_supp(auth, & descSupp->packet, descSupp->inttype);
if(suppid != -1 && !memcmp(descSupp->packet.data, auth->GlobalTxRx->oursupp_addr, ETHER_ADDRLEN ))
{
lib1x_authsm_capture_supp(auth->Supp[suppid]->global, descSupp, & descSupp->packet);
lib1x_auth_process(auth);
}
}
}
#endif
if((auth->RSNVariable.Dot1xEnabled || auth->RSNVariable.MacAuthEnabled)
&& FD_ISSET(descSvr->udpsock, &fsRead))
{
numread = recv( descSvr->udpsock, descSvr->packet_buffer, LIB1X_MAXEAPLEN , 0);
if ( numread <= 0 )
{
lib1x_message(MESS_ERROR_FATAL," NUMREAD = 0 after recv !");
return 0;
}
descSvr->packet.caplen = numread;
descSvr->packet.data = descSvr->packet_buffer;
suppid = lib1x_search_supp(auth, & descSvr->packet, descSvr->inttype);
if(suppid != -1)
{
lib1x_authsm_capture_svr(auth->Supp[suppid]->global, descSvr, & descSvr->packet);
lib1x_auth_process(auth);
}
}
#ifdef RTL_RADIUS_2SET
if((auth->RSNVariable.Dot1xEnabled || auth->RSNVariable.MacAuthEnabled)
&& auth->use_2nd_rad && FD_ISSET(descSvr2->udpsock, &fsRead))
{
numread = recv( descSvr2->udpsock, descSvr2->packet_buffer, LIB1X_MAXEAPLEN , 0);
if ( numread <= 0 )
{
lib1x_message(MESS_ERROR_FATAL," NUMREAD = 0 after recv !");
return 0;
}
descSvr2->packet.caplen = numread;
descSvr2->packet.data = descSvr2->packet_buffer;
suppid = lib1x_search_supp(auth, & descSvr2->packet, descSvr2->inttype);
if(suppid != -1)
{
lib1x_authsm_capture_svr(auth->Supp[suppid]->global, descSvr2, & descSvr2->packet);
lib1x_auth_process(auth);
}
}
#endif
#endif // !PSK_ONLY
#ifndef START_AUTH_IN_LIB
if(FD_ISSET(auth->GlobalTxRx->readfifo, &fsRead))
#else
nRead = read_wlan_evt(auth->GlobalTxRx->fd_control, auth->GlobalTxRx->device_supp, auth->GlobalTxRx->RecvBuf);
if (nRead)
#endif
{
#ifndef START_AUTH_IN_LIB
int nRead;
nRead = read(auth->GlobalTxRx->readfifo, auth->GlobalTxRx->RecvBuf, RWFIFOSIZE);
if(nRead <= 0)
return 0;
#endif
auth->GlobalTxRx->network_supp->packet.data = auth->GlobalTxRx->RecvBuf + FIFO_HEADER_LEN;
auth->GlobalTxRx->network_supp->packet.caplen = nRead - FIFO_HEADER_LEN;
if(auth->GlobalTxRx->RecvBuf[FIFO_HEADER_LEN - 1] == FIFO_TYPE_DLISTEN)
{
#ifdef EAP_BY_QUEUE
#ifdef RTL_WPA2_PREAUTH
if(auth->GlobalTxRx->RecvBuf[FIFO_HEADER_LEN] == DOT11_EVENT_EAP_PACKET
|| auth->GlobalTxRx->RecvBuf[FIFO_HEADER_LEN] == DOT11_EVENT_EAP_PACKET_PREAUTH)
#else
if(auth->GlobalTxRx->RecvBuf[FIFO_HEADER_LEN] == DOT11_EVENT_EAP_PACKET)
#endif // RTL_WPA2
{
void *eap_packet = (void *)&(auth->GlobalTxRx->RecvBuf[FIFO_HEADER_LEN]);
unsigned short packet_len;
memcpy(&packet_len, (void *)((unsigned int)eap_packet + (int)(&((DOT11_EAP_PACKET *)0)->packet_len)), sizeof(unsigned short));
descSupp->packet.caplen = packet_len;
memcpy(descSupp->packet_buffer, (void *)((unsigned int)eap_packet + (int)(&((DOT11_EAP_PACKET *)0)->packet)), descSupp->packet.caplen);
descSupp->packet.data = descSupp->packet_buffer;
#ifdef RTL_WPA_CLIENT
if(auth->currentRole == role_Supplicant_infra)
{
lib1x_suppsm_capture_auth( auth->client->global, descSupp, & descSupp->packet );
}else if (auth->currentRole == role_Authenticator)
#endif
{
suppid = lib1x_search_supp(auth, & descSupp->packet, descSupp->inttype);
if(suppid != -1 && !memcmp(descSupp->packet.data, auth->GlobalTxRx->oursupp_addr, ETHER_ADDRLEN ))
{
lib1x_authsm_capture_supp(auth->Supp[suppid]->global, descSupp, & descSupp->packet);
lib1x_auth_process(auth);
}
}
}
else
{
#endif
#ifdef RTL_WPA_CLIENT
// david -----------------------------
#if 0
if(auth->currentRole == role_Supplicant)
{
lib1x_message(MESS_DBG_SUPP, "Receive driver indication\n");
lib1x_suppsm_capture_control( auth->client->global, descSupp, & descSupp->packet );
}else
#endif
if(auth->currentRole == role_Supplicant_infra)
{
lib1x_message(MESS_DBG_SUPP, "Receive driver indication\n");
lib1x_suppsm_capture_control( auth->client->global, descSupp, & descSupp->packet );
}else if(auth->currentRole == role_Authenticator)
//------------------------------------
#endif
{
suppid = lib1x_search_supp(auth, (struct lib1x_packet *)& auth->GlobalTxRx->network_supp->packet, LIB1X_IT_CTLSOCK);
if(suppid != -1)
{
lib1x_capture_control( auth->Supp[suppid]->global,auth->GlobalTxRx->network_supp ,& auth->GlobalTxRx->network_supp->packet);
lib1x_auth_process(auth);
}
}
#ifdef EAP_BY_QUEUE
}
#endif
}
}
#ifdef PSK_ONLY
if (nRead <= 0)
return 0;
#else
if(((auth->RSNVariable.Dot1xEnabled || auth->RSNVariable.MacAuthEnabled)&& (auth->AccountingEnabled))
&& FD_ISSET(descSvr->acctsock, &fsRead))
{
numread = recv( descSvr->acctsock, descSvr->packet_buffer, LIB1X_MAXEAPLEN , 0);
if ( numread <= 0 )
{
lib1x_message(MESS_ERROR_FATAL," NUMREAD = 0 after recv !");
return 0;
}
descSvr->packet.caplen = numread;
descSvr->packet.data = descSvr->packet_buffer;
suppid = lib1x_search_supp(auth, & descSvr->packet, descSvr->inttype);
if(suppid == LIB1X_AUTH_INDEX)
lib1x_authsm_capture_svr(auth->authGlobal->global, descSvr, & descSvr->packet);
else if(suppid != -1)
{
lib1x_authsm_capture_svr(auth->Supp[suppid]->global, descSvr, & descSvr->packet);
lib1x_auth_process(auth);
}
}
}
#endif // !PSK_ONLY
return 1; // david
}
#if 0 //sc_yang
//int lib1x_nal_receivepoll( Dot1x_Authenticator * auth, struct lib1x_nal_intfdesc * desc , lib1x_nal_genpkt_handler * pkt_handler, u_char * info)
int lib1x_nal_receivepoll( Dot1x_Authenticator * auth, struct lib1x_nal_intfdesc * desc , lib1x_nal_genpkt_handler * pkt_handler, u_char * info)
{
struct pollfd pfd;
int pret;
int numread;
int res;
int suppid;
struct timeval timeout;
fd_set readfs;
static int which = 1;
if ( pkt_handler == NULL )
lib1x_message( MESS_ERROR_FATAL," lib1x_nal_receivepoll called with NULL handler! ");
timeout.tv_sec = 0;
// timeout.tv_usec = 100;
timeout.tv_usec = 0;
if ( desc->inttype == LIB1X_IT_PKTSOCK )
{
pfd.fd = desc->pf_sock;
pfd.events = POLLIN;
pret = poll( &pfd, 1, 0 );
if ( pret < 0 )
{
//if(pret != EINTR)
// lib1x_message( MESS_DBG_NAL," errno = %d%s", errno, strerror(errno));
}
if ( pret == 0 )
{
return 0;
}
numread = recv( desc->pf_sock, desc->packet_buffer, LIB1X_MAXEAPLEN , 0);
if ( numread <= 0 )
{
return 0;
}
desc->packet.caplen = numread;
desc->packet.data = desc->packet_buffer;
suppid = lib1x_search_supp(auth, & desc->packet, desc->inttype);
if(suppid != -1 && !memcmp(desc->packet.data, auth->GlobalTxRx->oursupp_addr, ETHER_ADDRLEN ))
(*pkt_handler)(auth->Supp[suppid]->global, desc, & desc->packet);
}
else // udp socket
{
if(auth->AccountingEnabled)
which = !which;
//-------------------------------------------------------------------------
// For UDP socket from Authentication Server
//-------------------------------------------------------------------------
if(which)
{
FD_ZERO ( &readfs);
FD_SET( desc->udpsock, &readfs);
res = select( desc->udpsock +1, &readfs, NULL, NULL, &timeout);
if ( res == -1 )
{
return 0;
}
if ( res <= 0 ) return 0;
numread = recv( desc->udpsock, desc->packet_buffer, LIB1X_MAXEAPLEN , 0);
if ( numread <= 0 )
{
lib1x_message(MESS_ERROR_FATAL," NUMREAD = 0 after poll !");
return 0;
}
lib1x_message(MESS_DBG_SPECIAL, "Received message on UDP socket");
desc->packet.caplen = numread;
desc->packet.data = desc->packet_buffer;
suppid = lib1x_search_supp(auth, & desc->packet, desc->inttype);
//lib1x_hexdump2(MESS_DBG_NAL, "lib1x_nal_receive_poll", desc->packet.data, desc->packet.caplen, "receive UDP packet");
if(suppid != -1)
(*pkt_handler)(auth->Supp[suppid]->global, desc, & desc->packet);
lib1x_message( MESS_DBG_SPECIAL, "READ %d BYTES FROM AUTH UDP SOCKET", numread );
}else
//-------------------------------------------------------------------------
// For UDP socket from Accounting Server
//-------------------------------------------------------------------------
{
FD_ZERO ( &readfs);
FD_SET( desc->acctsock, &readfs);
res = select( desc->acctsock +1, &readfs, NULL, NULL, &timeout);
if ( res == -1 )
{
return 0;
}
if ( res <= 0 ) return 0;
numread = recv( desc->acctsock, desc->packet_buffer, LIB1X_MAXEAPLEN , 0);
if ( numread <= 0 )
{
lib1x_message(MESS_ERROR_FATAL," NUMREAD = 0 after poll !");
return 0;
}
desc->packet.caplen = numread;
desc->packet.data = desc->packet_buffer;
suppid = lib1x_search_supp(auth, & desc->packet, desc->inttype);
//lib1x_hexdump2(MESS_DBG_NAL, "lib1x_nal_receive_poll", desc->packet.data, desc->packet.caplen, "receive UDP packet");
if(suppid == LIB1X_AUTH_INDEX)
(*pkt_handler)(auth->authGlobal->global, desc, & desc->packet);
else if(suppid != -1)
(*pkt_handler)(auth->Supp[suppid]->global, desc, & desc->packet);
lib1x_message( MESS_DBG_SPECIAL, "READ %d BYTES FROM ACCT UDP SOCKET", numread );
}
}
return 1; // david
}
#endif
#ifndef COMPACK_SIZE
//----------------------------------------------------------------
// lib1x_nal_receivefifo:
// This function receive data from fifo.
// Three sources of data are ceceived from fifo including:
// (1) 8181 Wireless Interface
// (2) Ethernet interface
// (3) Ioctl return from 8181 driver
//
// Data received from fifo(1, 2) has the header
// _________________________________________________
// | pid (4 bytes) | fifo type (1 byte) | data (*) |
// -------------------------------------------------
//-----------------------------------------------------------------
int lib1x_nal_receivefifo(Dot1x_Authenticator * auth )
{
ssize_t nRead;
int suppid;
nRead = read(auth->GlobalTxRx->readfifo, auth->GlobalTxRx->RecvBuf, RWFIFOSIZE);
if(nRead <= 0)
return 0;
#ifdef ALLOW_DBG_NAL
lib1x_hexdump2(MESS_DBG_NAL, "1x_daemon", auth->GlobalTxRx->RecvBuf, nRead, "read from fifo");
lib1x_message(MESS_DBG_FIFO, "rx event id=%d\n", *((int *)auth->GlobalTxRx->RecvBuf));
#endif
auth->GlobalTxRx->network_supp->packet.data = auth->GlobalTxRx->RecvBuf + FIFO_HEADER_LEN;
auth->GlobalTxRx->network_supp->packet.caplen = nRead - FIFO_HEADER_LEN;
switch(auth->GlobalTxRx->RecvBuf[FIFO_HEADER_LEN - 1])
{
case FIFO_TYPE_DLISTEN:
suppid = lib1x_search_supp(auth, (struct lib1x_packet *)& auth->GlobalTxRx->network_supp->packet.data, LIB1X_IT_CTLSOCK);
//lib1x_hexdump2(MESS_DBG_NAL, "lib1x_nal_receivefifo", (u_char*)&auth->GlobalTxRx->network_supp->packet.data, auth->GlobalTxRx->network_supp->packet.caplen, "receive from driver");
if(suppid != -1)
{
lib1x_capture_control( auth->Supp[suppid]->global,auth->GlobalTxRx->network_supp ,& auth->GlobalTxRx->network_supp->packet);
}else
lib1x_message(MESS_DBG_NAL, "***********************NOT in TABLE");
break;
}
return 1; // david
}
#endif
#ifndef COMPACK_SIZE
void lib1x_nal_receiveioctl(Dot1x_Authenticator * auth)
{
int suppid = -1;
lib1x_control_Poll(auth);
if(auth->IoctlBufLen)
{
lib1x_hexdump2(MESS_DBG_NAL, "lib1x_nal_receiveioctl", auth->IoctlBuf, auth->IoctlBufLen, "receive from driver");
auth->GlobalTxRx->network_supp->packet.data = auth->IoctlBuf;
auth->GlobalTxRx->network_supp->packet.caplen = auth->IoctlBufLen;
suppid = lib1x_search_supp(auth, (struct lib1x_packet *)& auth->GlobalTxRx->network_supp->packet.data, LIB1X_IT_CTLSOCK);
if(suppid != -1)
{
lib1x_capture_control( auth->Supp[suppid]->global,auth->GlobalTxRx->network_supp ,& auth->GlobalTxRx->network_supp->packet);
}
auth->IoctlBufLen = 0;
}
}
#endif
//--------------------------------------------------
//--------------------------------------------------
#ifndef COMPACK_SIZE
void lib1x_nal_close( struct lib1x_nal_intfdesc * desc )
{
// Close the listener part.
//sc_yang
// pcap_close( desc->pcap_desc );
// Close the xmitter part.
if (libnet_close_link_interface( desc->libnet_desc) == -1 )
lib1x_message( MESS_ERROR_OK,"lib1x_nal_close: Error closing libnet channel.");
}
#endif
#if 0 //sc_yang
//--------------------------------------------------
// lib1x_nal_packet_handler:
// This function will be called by pcap for each packet.
//--------------------------------------------------
void lib1x_nal_pcappkt_handler( u_char * lib1x_data , const struct pcap_pkthdr * packet_header, const u_char * the_packet)
{
struct lib1x_nal_intfdesc * desc;
struct lib1x_ethernet * ehdr;
u_int caplen;
u_int length;
u_short ether_type;
desc = ( struct lib1x_nal_intfdesc * ) lib1x_data;
caplen = packet_header->caplen;
length = packet_header->len;
if ( caplen < ETHER_HDRLEN )
{
fprintf(stderr,"\n One packet missed .. captured length too small");
return ;
}
ehdr = (struct lib1x_ethernet * ) the_packet;
ether_type = ntohs( ehdr->ether_type );
printf("\n packet received.");
// We need to call the appropriate handler which is
// given by desc->packet_handler.
}
#endif
//--------------------------------------------------
// lib1x_nal_send:
// Make sure from and to addresses are proper
// in the ethernet header .. coz i dont check
// that here.
//--------------------------------------------------
BOOLEAN lib1x_nal_send( struct lib1x_nal_intfdesc * desc, char * packet , int size)
{
int num_sent = 0;
if ( desc->inttype == LIB1X_IT_PKTSOCK )
{
// if ( size > 1499 ) size = 1499; /* needed for ethernet only if you are not handling fragmentation */
if ( desc->libnet_desc == NULL )
lib1x_message( MESS_ERROR_FATAL, "lib1x_nal_send: Descriptor contains invalid network identifier.");
num_sent = libnet_write_link_layer( desc->libnet_desc, (char *)desc->device ,
(unsigned char *)packet, size );
lib1x_message(MESS_DBG_NAL, "libnet_write_link_layer send packets %d\n", num_sent);
#ifdef DBG_WPA_CLIENT
{
struct lib1x_packet spkt;
spkt.data = packet;
spkt.caplen = size;
lib1x_suppsm_capture_auth( RTLClient.global, desc, &spkt );
}
#endif
}
else
{
num_sent = send( desc->udpsock, (void*) packet, size, 0); /* flags = 0 */
lib1x_message( MESS_DBG_SPECIAL, "lib1x_nal_send: Sending UDP packet.");
}
if ( num_sent != size )
{
lib1x_message( MESS_ERROR_OK, "lib1x_nal_send: Mismatch in send size!");
lib1x_message( MESS_ERROR_FATAL," NUM_SENT : %d . actual %d", num_sent, size );
return FALSE;
}
return TRUE;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,215 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_parser.c
// Programmer : Arunesh Mishra
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
//
#include "1x_ethernet.h"
#include "1x_eapol.h"
#include "1x_nal.h"
#include "1x_common.h"
#include "1x_radius.h"
#include "1x_auth_pae.h"
#include <stdio.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/*
void lib1x_parsePrint( FILE * fdesc, Auth_Pae * auth_pae, struct lib1x_packet * spkt )
{
struct lib1x_ethernet * eth;
struct lib1x_eapol * eapol;
struct lib1x_eap * eap;
u_char etheraddr[40];
struct timeval tod;
struct lib1x_iphdr *ip;
struct lib1x_udphdr *udp;
struct lib1x_radiushdr *rhdr;
struct lib1x_radiusattr *rattr;
int unexplen;
if ( spkt == NULL )
{
lib1x_message( MESS_DBG_NAL, "parser: spkt null ");
return;
}
eth = ( struct lib1x_ethernet * ) spkt->data;
fprintf(fdesc, "\n--------------------------------------START PKT DUMP---------------------------------------------\n");
if ( gettimeofday( & tod ,NULL ) == 0 )
fprintf(fdesc, " TIMESTAMP : %ld seconds : %ld microseconds ", tod.tv_sec, tod.tv_usec );
fprintf(fdesc, " Packet Length: %d",spkt->caplen );
// 1. parse ethernet header
lib1x_print_etheraddr( etheraddr, eth->ether_dhost );
fprintf(fdesc, "\n DEST Ethernet Addr : %s", etheraddr );
lib1x_print_etheraddr( etheraddr, eth->ether_shost );
fprintf(fdesc, " SRC Ethernet Addr : %s", etheraddr );
fprintf(fdesc, "\n Ether Type : 0x%04X ", htons(eth->ether_type) );
if ( eth->ether_type == htons(LIB1X_ETHER_EAPOL_TYPE ))
{
fprintf(fdesc, " - EAPOL Packet. \n");
eapol = ( struct lib1x_eapol * ) ( spkt->data + ETHER_HDRLEN );
fprintf(fdesc, "\nEAPOL: Protocol Version: %d", eapol->protocol_version );
fprintf(fdesc, " Packet Type : %d", eapol->packet_type );
fprintf(fdesc, " Body Length: %d\n", htons(eapol->packet_body_length));
if ( eapol->packet_type == LIB1X_EAPOL_LOGOFF )
{
fprintf(fdesc, "EAPOL: LOGOFF message \n");
}
if ( eapol->packet_type == LIB1X_EAPOL_EAPPKT )
{
fprintf(fdesc, "EAPOL: EAP packet \n");
eap = ( struct lib1x_eap * ) ( spkt->data + ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN);
fprintf(fdesc, " EAP: Code : %u", eap->code );
fprintf(fdesc, " Identifier: %u", eap->identifier );
fprintf(fdesc, " Length : %u\n", htons(eap->length) );
if ( eap->code == LIB1X_EAP_REQUEST )
{
fprintf(fdesc, " EAP: REQuest Message\n");
lib1x_hexdump( fdesc, ( spkt->data + ETHER_HDRLEN + LIB1X_EAPOL_HDRLEN + LIB1X_EAP_HDRLEN ), htons(eap->length) - LIB1X_EAP_HDRLEN );
}
if ( eap->code == LIB1X_EAP_SUCCESS )
{
fprintf(fdesc, " EAP: SUCcess Message\n");
}
if ( eap->code == LIB1X_EAP_FAILURE )
{
fprintf(fdesc, " EAP: FAILure Message\n");
}
if ( eap->code == LIB1X_EAP_RESPONSE )
{
fprintf(fdesc, " EAP: RESPonse Message\n");
}
}
if ( eapol->packet_type == LIB1X_EAPOL_START )
{
fprintf(fdesc, "EAPOL: START Message ");
}
if ( eapol->packet_type == LIB1X_EAPOL_KEY )
{
fprintf(fdesc, "EAPOL: KEY Message ");
}
if ( eapol->packet_type == LIB1X_EAPOL_ENCASFALERT )
{
fprintf(fdesc, "EAPOL: Encasf alert Message -? ");
}
}
if ( eth->ether_type == htons(LIB1X_ETHER_IP ))
{
fprintf(fdesc," - IP packet.\n");
ip = ( struct lib1x_iphdr * ) ( spkt->data + ETHER_HDRLEN );
fprintf(fdesc," IP: Source: %s", inet_ntoa( ip->ip_src ));
fprintf(fdesc," Dest: %s \n", inet_ntoa( ip->ip_dst ));
fprintf(fdesc," IP: Length : %d", ntohs( ip->ip_len ));
fprintf(fdesc," IP: Checksum: %04d", ip->ip_sum );
fprintf(fdesc," IP: Protocol: %d", ip->ip_p );
if ( ip->ip_p == LIB1X_IPPROTO_UDP )
{
udp = ( struct lib1x_udphdr * ) ( spkt->data + ETHER_HDRLEN + LIB1X_IPHDRLEN );
fprintf(fdesc," - UDP Protocol.\n");
fprintf(fdesc," UDP: Source Port: %d Dest Port: %d", ntohs(udp->sport), ntohs(udp->dport));
fprintf(fdesc," AUTHPAE: Source Port: %ud Dest Port: %ud", auth_pae->global->TxRx->udp_ourport, auth_pae->global->TxRx->udp_svrport);
fprintf(fdesc," Length: %d - ", ntohs( udp->len ));
if ( ( udp->sport == htons(auth_pae->global->TxRx->udp_ourport ) ) || TRUE || // this IF Statement is JUST NOT WORKING .. auth_pae->udp_ourport gets some weird value
( udp->sport == htons(auth_pae->global->TxRx->udp_svrport ) ) ) // radius response
{
rhdr = ( struct lib1x_radiushdr * ) ( spkt->data + ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN );
fprintf(fdesc," RADIUS PACKET\n");
fprintf(fdesc," RAD: Code : %d Identifier: %d Length: %d \n", rhdr->code, rhdr->identifier, ntohs(rhdr->length ));
unexplen = ntohs(rhdr->length ) - LIB1X_RADHDRLEN;
rattr = ( struct lib1x_radiusattr * ) ( spkt->data + ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN + LIB1X_RADHDRLEN );
while ( ( unexplen > 0 ) && ( rattr->length > 0 ) )
{
fprintf(fdesc, " RAD-Attr: Type: %d Length: %d \n", rattr->type, rattr->length );
fprintf(fdesc," RAD-Attr:DATA >> \n");
lib1x_hexdump(fdesc, ( ( u_char * ) rattr ) + 2, rattr->length - 2 );
unexplen -= rattr->length;
rattr = ( struct lib1x_radiusattr * )( ( (u_char *) rattr ) + rattr->length );
}
} else fprintf(fdesc," - OTHER. \n ");
}
else fprintf(fdesc," - OTHER. \n ");
}
fprintf(fdesc, "\n--------------------------------------END DUMP---------------------------------------------\n");
lib1x_hexdump(fdesc, spkt->data, spkt->caplen );
fflush(fdesc );
}
*/
#ifndef COMPACK_SIZE
void lib1x_parsePrint( FILE * fdesc, Auth_Pae * auth_pae, struct lib1x_packet * spkt )
{
struct lib1x_ethernet * eth;
struct lib1x_iphdr *ip;
struct lib1x_udphdr *udp;
struct lib1x_radiushdr *rhdr;
struct lib1x_radiusattr *rattr;
int unexplen;
if ( spkt == NULL )
{
lib1x_message( MESS_DBG_NAL, "parser: spkt null ");
return;
}
eth = ( struct lib1x_ethernet * ) spkt->data;
printf("eth->ether_type = %x\n", eth->ether_type);
fprintf(fdesc, "\n--------------------------------------START PKT DUMP---------------------------------------------\n");
if ( eth->ether_type == htons(LIB1X_ETHER_EAPOL_TYPE ))
{
return;
}
if ( eth->ether_type == htons(LIB1X_ETHER_IP ))
{
fprintf(fdesc," - IP packet.\n");
ip = ( struct lib1x_iphdr * ) ( spkt->data + ETHER_HDRLEN );
fprintf(fdesc," IP: Source: %s", inet_ntoa( ip->ip_src ));
fprintf(fdesc," Dest: %s \n", inet_ntoa( ip->ip_dst ));
if ( ip->ip_p == LIB1X_IPPROTO_UDP )
{
udp = ( struct lib1x_udphdr * ) ( spkt->data + ETHER_HDRLEN + LIB1X_IPHDRLEN );
fprintf(fdesc," - UDP Protocol.\n");
fprintf(fdesc," UDP: Source Port: %d Dest Port: %d", ntohs(udp->sport), ntohs(udp->dport));
//fprintf(fdesc," AUTHPAE: Source Port: %ud Dest Port: %ud", auth_pae->global->TxRx->udp_ourport, auth_pae->global->TxRx->udp_svrport);
if (TRUE ) // radius response
{
rhdr = ( struct lib1x_radiushdr * ) ( spkt->data + ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN );
fprintf(fdesc," RADIUS PACKET\n");
fprintf(fdesc," RAD: Code : %d Identifier: %d Length: %d \n", rhdr->code, rhdr->identifier, ntohs(rhdr->length ));
unexplen = ntohs(rhdr->length ) - LIB1X_RADHDRLEN;
rattr = ( struct lib1x_radiusattr * ) ( spkt->data + ETHER_HDRLEN + LIB1X_IPHDRLEN + LIB1X_UDPHDRLEN + LIB1X_RADHDRLEN );
} else fprintf(fdesc," - OTHER. \n ");
}
else fprintf(fdesc," - OTHER. \n ");
}
fprintf(fdesc, "\n--------------------------------------END DUMP---------------------------------------------\n");
//lib1x_hexdump(fdesc, spkt->data, spkt->caplen );
fflush(fdesc );
}
#endif

View File

@ -0,0 +1,161 @@
# include <sys/types.h>
# include <netinet/in.h>
# include "1x_pkt_listener.h"
# include "1x_ethernet.h"
# include "1x_eapol.h"
# include "1x_common.h"
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_pkt_listener.c
// Programmer : Arunesh Mishra
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
// Implementation of the packet listening interface.
//--------------------------------------------------
//--------------------------------------------------
// lib1x_pktlst_init:
// Perform initialization of the pcap interface.
//--------------------------------------------------
void lib1x_pktlst_init( char * device , Global_Params * global )
{
PKT_LSTNR * listener;
listener = ( PKT_LSTNR * ) malloc( sizeof ( PKT_LSTNR) );
listener->promisc_mode = LIB1X_LSTNR_PROMISCMODE;
listener->snaplen = LIB1X_LSTNR_SNAPLEN;
listener->read_timeout = LIB1X_LSTNR_RDTIMEOUT;
listener->device = device;
listener->packet_handler = lib1x_pktlst_packet_handler;
listener->global = global;
listener->pkt_desc = pcap_open_live( device, listener->snaplen, listener->read_timeout,
listener->promisc_mode, listener->error_buf);
if ( listener->pkt_desc == NULL )
{
fprintf(stderr," Could not open device : %s", device );
exit(1);
}
}
void lib1x_pktlst_process( PKT_LSTNR * listener )
{
pcap_dispatch( listener->pkt_desc, -1, listener->packet_handler, (u_char *) listener );
}
//--------------------------------------------------
// lib1x_pktlst_packet_handler:
// This function will be called by pcap for each packet.
//--------------------------------------------------
void lib1x_pktlst_packet_handler( u_char * lib1x_data , const struct pcap_pkthdr * packet_header, const u_char * the_packet)
{
PKT_LSTNR * listener;
struct lib1x_ethernet_hdr * ehdr;
Lib1x_Eapol_Header * eapol_hdr;
u_int caplen;
u_int length;
u_short ether_type;
listener = (PKT_LSTNR * ) lib1x_data; // This is directly passed.
caplen = packet_header->caplen;
length = packet_header->length;
if ( caplen < ETHER_HDR_LEN )
{
printf(stderr,"\n One packet missed .. captured length too small");
return ;
}
ehdr = (struct lib1x_ethernet_hdr * ) the_packet;
ether_type = ntohs( ehdr->ether_type );
if ( ether_type == LIB1X_ETHER_EAPOL_TYPE ) // Now that it is an eapol packet
{
// Now we've got to parse the eapol header.
eapol_hdr = (Lib1x_Eapol_Header * )( the_packet + ETHER_HDR_LEN - 2) ; // -2 because the type field is common.
lib1x_pktlst_perform_action( eapol_hdr , listener );
}
printf("\n packet received.");
}
void lib1x_pktlst_close( PKT_LSTNR * listener )
{
pcap_close( listener->pd );
}
//--------------------------------------------------
// lib1x_pktlst_perform_action:
// This function parses the eapol packet and takes
// various actions.
//--------------------------------------------------
void lib1x_pktlst_perform_action( Lib1x_Eapol_Header * eapol_hdr , PKT_LSTNR * listener)
{
Global_Params * global = listener->global;
Auth_Pae * auth_pae = global->auth_pae;
Lib1x_EAP_PKTHDR * eap_hdr;
u_short * eap_rr_id; // The Request/Response type
// TODO: Need a generic technique for confirming the source address.
if ( global->currentRole == Authenticator )
{
switch( eapol_hdr->packet_type )
{
case LIB1X_EAPOL_LOGOFF :
// Page 53.
auth_pae->eapLogoff = TRUE;
break;
case LIB1X_EAPOL_START :
// Page 53.
auth_pae->eapStart = TRUE;
break;
case LIB1X_EAPOL_EAPPKT:
// Page 53.
// TODO: Parse EAP PACKET and if EAP Response/Identity Packet
// is received set rxRespId of authpae to TRUE;
eap_hdr = (Lib1x_EAP_PKTHDR * ) (eapol_hdr + LIB1X_EAPOL_HDR_LEN);
if ( eap_hdr->code == LIB1X_EAP_RESPONSE )
{
eap_rr_id = (u_short*) ( eap_hdr + LIB1X_EAP_HDRLEN ) ;
//Note :IMportant only if it is a response / request
// packet ..we are sure of existence of such a field.
if ( *eap_rr_id == LIB1X_EAP_RRIDENTITY )
{
auth_pae->rxRespId = TRUE;
}
}
break;
}
}
}

View File

@ -0,0 +1,28 @@
#include "1x_pkt_xmit.h"
#include "1x_common.h"
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_pkt_xmit.c
// Programmer : Arunesh Mishra
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
// Coding for calling libnet properly
//--------------------------------------------------
PKT_XMIT * lib1x_pktxmit_init( char *device, Global_Params * global )
{
PKT_XMIT * xmitter;
xmitter
}

View File

@ -0,0 +1,126 @@
//--------------------------------------------------
// IEEE 802.1x + 802.11i Implementation
//
// File : 1x_pmk_cache.c
// Programmer : Kenneth Lin
// PMK Cache routine
//
//
// Copyright (c) Kenneth Lin 2004
// All rights reserved.
// Realtek Semi.
//--------------------------------------------------
#include <string.h>
#include "1x_common.h"
#include "1x_list.h"
extern Dot1x_Authenticator RTLAuthenticator;
struct _WPA2_PMKSA_Node* get_pmksa_node()
{
struct _WPA2_PMKSA_Node* pmksa_node;
if ( (pmksa_node = (struct _WPA2_PMKSA_Node* )malloc(sizeof (struct _WPA2_PMKSA_Node))) == NULL)
printf("%s: malloc fails\n", __FUNCTION__);
return pmksa_node;
}
void free_pmksa_node(struct _WPA2_PMKSA_Node* pmksa_node)
{
free(pmksa_node);
}
void wpa2_hexdump(char* name, u_char * buf, int size )
{
#if 0
int i;
printf("%s:", name);
for (i = 0; i < size; i++) {
if (i % 16 == 0) {
printf("\n\t\t");
}
printf("%02X ", *(buf+i));
}
printf("\n");
#endif
}
void dump_pmk_cache()
{
Dot1x_Authenticator *auth = &RTLAuthenticator;
struct list_head* head = &auth->pmk_cache;
struct list_head *pos, *n;
struct _WPA2_PMKSA_Node* node;
printf("\nPMK Cache:\n");
list_for_each_safe(pos, n, head) {
node = list_entry(pos, struct _WPA2_PMKSA_Node, node);
wpa2_hexdump("PMKID", node->pmksa.pmkid, PMKID_LEN);
wpa2_hexdump("PMK", node->pmksa.pmk, PMK_LEN);
wpa2_hexdump("SPA", node->pmksa.spa, ETHER_ADDRLEN);
printf("\n");
}
printf("\n");
}
void del_pmksa_by_pmkid(u_char* pmkid)
{
Dot1x_Authenticator *auth = &RTLAuthenticator;
struct list_head* head = &auth->pmk_cache;
struct list_head *pos, *n;
struct _WPA2_PMKSA_Node* node;
list_for_each_safe(pos, n, head) {
node = list_entry(pos, struct _WPA2_PMKSA_Node, node);
if ( !memcmp(node->pmksa.pmkid, pmkid, PMKID_LEN ) ) {
list_del(pos);
free_pmksa_node(node);
}
}
}
void del_pmksa_by_spa(u_char* spa)
{
Dot1x_Authenticator *auth = &RTLAuthenticator;
struct list_head* head = &auth->pmk_cache;
struct list_head *pos, *n;
struct _WPA2_PMKSA_Node* node;
list_for_each_safe(pos, n, head) {
node = list_entry(pos, struct _WPA2_PMKSA_Node, node);
if ( !memcmp(node->pmksa.spa, spa, 6 ) ) {
list_del(pos);
free_pmksa_node(node);
}
}
}
struct _WPA2_PMKSA_Node* find_pmksa(u_char* pmkid)
{
Dot1x_Authenticator *auth = &RTLAuthenticator;
struct list_head* head = &auth->pmk_cache;
struct list_head *pos, *n;
struct _WPA2_PMKSA_Node* node;
list_for_each_safe(pos, n, head) {
node = list_entry(pos, struct _WPA2_PMKSA_Node, node);
//wpa2_hexdump("request pmkid", pmkid, PMKID_LEN);
//wpa2_hexdump("cached pmkid", node->pmksa.pmkid, PMKID_LEN);
if ( !memcmp(node->pmksa.pmkid, pmkid, PMKID_LEN ) ) {
return node;
}
}
return NULL;
}
void cache_pmksa(struct _WPA2_PMKSA_Node* pmksa_node)
{
Dot1x_Authenticator *auth = &RTLAuthenticator;
struct list_head* head = &auth->pmk_cache;
/* NOTE **************** */
del_pmksa_by_spa(pmksa_node->pmksa.spa);
//del_pmksa_by_pmkid(pmksa_node->pmksa.pmkid);
list_add_tail(&pmksa_node->node, head);
}

View File

@ -0,0 +1,133 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_ptsm.c
// Programmer : Arunesh Mishra
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
// Contains the port timers state machine.
//--------------------------------------------------
#include "1x_common.h"
#include "1x_ptsm.h"
#include "1x_auth_pae.h"
#include <signal.h>
#include <stddef.h>
#include <sys/time.h>
//-------------------------------------------------------------------------------
// Original implementation (Without WPA)
//-------------------------------------------------------------------------------
//sc_yang to move form 1x_common.h
void * lib1x_global_signal_info;
#ifndef _RTL_WPA_UNIX
// Set the 1 sec periodic timer.
// Use: Allocate memory and call this function, also take care of free()
void lib1x_ptsm_initialize( Global_Params * global, struct lib1x_ptsm * ptsm )
{
lib1x_global_signal_info = (void * ) ptsm;
signal( SIGALRM, lib1x_ptsm_alarm );
ptsm->authWhile = ptsm->aWhile = ptsm->heldWhile = 0;
ptsm->quietWhile = ptsm->reAuthWhen = ptsm->startWhen = ptsm->txWhen = 0;
//---- PTSM timer state machine is triggered per one seconds ----
ptsm->wakeupCounts = 1000000 / LIB1X_BASIC_TIMER_UNIT;
}
//---- the signal handler.. needs to be a quick piece of code ----
void lib1x_ptsm_alarm( int signum )
{
struct lib1x_ptsm * ptsm;
if (signum == SIGALRM)
{
if ( lib1x_global_signal_info != NULL )
{
ptsm = ( struct lib1x_ptsm * ) lib1x_global_signal_info;
if (ptsm->authWhile >= 0 ) ptsm->authWhile --;
if (ptsm->aWhile >= 0 ) ptsm->aWhile --;
if (ptsm->heldWhile >= 0 ) ptsm->heldWhile --;
if (ptsm->quietWhile >= 0 ) ptsm->quietWhile --;
if (ptsm->reAuthWhen >= 0 ) ptsm->reAuthWhen --;
if (ptsm->startWhen >= 0 ) ptsm->startWhen --;
if (ptsm->txWhen >= 0 ) ptsm->txWhen --;
}
alarm(1); // schedule next alarm
}
}
#else
//--------------------------------------------------------------------------
// Implementation with WPA Support
//--------------------------------------------------------------------------
void lib1x_ptsm_initialize( Global_Params * global, struct lib1x_ptsm * ptsm )
{
ptsm->authWhile = ptsm->aWhile = ptsm->heldWhile = 0;
ptsm->quietWhile = ptsm->reAuthWhen = ptsm->startWhen = ptsm->txWhen = 0;
}
void lib1x_ptsm_dump(Global_Params * global)
{
#ifndef DEBUG_DISABLE
struct lib1x_ptsm * ptsm = global->theAuthenticator->port_timers;
lib1x_message(MESS_DBG_PTSM, "----------- Dump PTSM Supplicant [%d]------------", global->index);
lib1x_message(MESS_DBG_PTSM, "ptsm->authWhile = %d", ptsm->authWhile);
lib1x_message(MESS_DBG_PTSM, "ptsm->aWhile= %d", ptsm->aWhile);
lib1x_message(MESS_DBG_PTSM, "ptsm->heldWhile = %d", ptsm->heldWhile);
lib1x_message(MESS_DBG_PTSM, "ptsm->quietWhile = %d", ptsm->quietWhile);
lib1x_message(MESS_DBG_PTSM, "ptsm->reAuthWhen = %d", ptsm->reAuthWhen);
lib1x_message(MESS_DBG_PTSM, "ptsm->startWhen = %d", ptsm->startWhen);
lib1x_message(MESS_DBG_PTSM, "ptsm->txWhen = %d", ptsm->txWhen);
lib1x_message(MESS_DBG_PTSM, "--------------------------------------------------");
#endif
}
void lib1x_ptsm_timer(Dot1x_Authenticator * auth)
{
int i;
struct lib1x_ptsm * ptsm;
Global_Params * global;
//sc_yang
for(i = 0 ; i < auth->MaxSupplicant ; i++)
{
// reduce pre-alloc memory size, david+2006-02-06
// if(!auth->Supp[i]->isEnable)
if(auth->Supp[i]==NULL || !auth->Supp[i]->isEnable)
continue;
global = auth->Supp[i]->global;
ptsm = global->theAuthenticator->port_timers;
lib1x_ptsm_dump(global);
//sc_yang >=0 to > 0
if (ptsm->authWhile > 0 ) ptsm->authWhile --;
if (ptsm->aWhile > 0 ) ptsm->aWhile --;
if (ptsm->heldWhile > 0 ) ptsm->heldWhile --;
if (ptsm->quietWhile > 0 ) ptsm->quietWhile --;
if (ptsm->reAuthWhen > 0 ) ptsm->reAuthWhen --;
if (ptsm->startWhen > 0 ) ptsm->startWhen --;
if (ptsm->txWhen > 0 ) ptsm->txWhen --;
}
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,367 @@
/* crypto/rc4/rc4_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include "1x_rc4.h"
/* RC4 as implemented from a posting from
* Newsgroups: sci.crypt
* From: sterndark@netcom.com (David Sterndark)
* Subject: RC4 Algorithm revealed.
* Message-ID: <sternCvKL4B.Hyy@netcom.com>
* Date: Wed, 14 Sep 1994 06:35:31 GMT
*/
void RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata,
unsigned char *outdata)
{
register RC4_INT *d;
register RC4_INT x,y,tx,ty;
int i;
x=key->x;
y=key->y;
d=key->data;
#if defined(RC4_CHUNK)
/*
* The original reason for implementing this(*) was the fact that
* pre-21164a Alpha CPUs don't have byte load/store instructions
* and e.g. a byte store has to be done with 64-bit load, shift,
* and, or and finally 64-bit store. Peaking data and operating
* at natural word size made it possible to reduce amount of
* instructions as well as to perform early read-ahead without
* suffering from RAW (read-after-write) hazard. This resulted
* in ~40%(**) performance improvement on 21064 box with gcc.
* But it's not only Alpha users who win here:-) Thanks to the
* early-n-wide read-ahead this implementation also exhibits
* >40% speed-up on SPARC and 20-30% on 64-bit MIPS (depending
* on sizeof(RC4_INT)).
*
* (*) "this" means code which recognizes the case when input
* and output pointers appear to be aligned at natural CPU
* word boundary
* (**) i.e. according to 'apps/openssl speed rc4' benchmark,
* crypto/rc4/rc4speed.c exhibits almost 70% speed-up...
*
* Cavets.
*
* - RC4_CHUNK="unsigned long long" should be a #1 choice for
* UltraSPARC. Unfortunately gcc generates very slow code
* (2.5-3 times slower than one generated by Sun's WorkShop
* C) and therefore gcc (at least 2.95 and earlier) should
* always be told that RC4_CHUNK="unsigned long".
*
* <appro@fy.chalmers.se>
*/
# define RC4_STEP ( \
x=(x+1) &0xff, \
tx=d[x], \
y=(tx+y)&0xff, \
ty=d[y], \
d[y]=tx, \
d[x]=ty, \
(RC4_CHUNK)d[(tx+ty)&0xff]\
)
if ( ( ((unsigned long)indata & (sizeof(RC4_CHUNK)-1)) |
((unsigned long)outdata & (sizeof(RC4_CHUNK)-1)) ) == 0 )
{
RC4_CHUNK ichunk,otp;
const union { long one; char little; } is_endian = {1};
/*
* I reckon we can afford to implement both endian
* cases and to decide which way to take at run-time
* because the machine code appears to be very compact
* and redundant 1-2KB is perfectly tolerable (i.e.
* in case the compiler fails to eliminate it:-). By
* suggestion from Terrel Larson <terr@terralogic.net>
* who also stands for the is_endian union:-)
*
* Special notes.
*
* - is_endian is declared automatic as doing otherwise
* (declaring static) prevents gcc from eliminating
* the redundant code;
* - compilers (those I've tried) don't seem to have
* problems eliminating either the operators guarded
* by "if (sizeof(RC4_CHUNK)==8)" or the condition
* expressions themselves so I've got 'em to replace
* corresponding #ifdefs from the previous version;
* - I chose to let the redundant switch cases when
* sizeof(RC4_CHUNK)!=8 be (were also #ifdefed
* before);
* - in case you wonder "&(sizeof(RC4_CHUNK)*8-1)" in
* [LB]ESHFT guards against "shift is out of range"
* warnings when sizeof(RC4_CHUNK)!=8
*
* <appro@fy.chalmers.se>
*/
if (!is_endian.little)
{ /* BIG-ENDIAN CASE */
# define BESHFT(c) (((sizeof(RC4_CHUNK)-(c)-1)*8)&(sizeof(RC4_CHUNK)*8-1))
for (;len&-sizeof(RC4_CHUNK);len-=sizeof(RC4_CHUNK))
{
ichunk = *(RC4_CHUNK *)indata;
otp = RC4_STEP<<BESHFT(0);
otp |= RC4_STEP<<BESHFT(1);
otp |= RC4_STEP<<BESHFT(2);
otp |= RC4_STEP<<BESHFT(3);
if (sizeof(RC4_CHUNK)==8)
{
otp |= RC4_STEP<<BESHFT(4);
otp |= RC4_STEP<<BESHFT(5);
otp |= RC4_STEP<<BESHFT(6);
otp |= RC4_STEP<<BESHFT(7);
}
*(RC4_CHUNK *)outdata = otp^ichunk;
indata += sizeof(RC4_CHUNK);
outdata += sizeof(RC4_CHUNK);
}
if (len)
{
RC4_CHUNK mask=(RC4_CHUNK)-1, ochunk;
ichunk = *(RC4_CHUNK *)indata;
ochunk = *(RC4_CHUNK *)outdata;
otp = 0;
i = BESHFT(0);
mask <<= (sizeof(RC4_CHUNK)-len)<<3;
switch (len&(sizeof(RC4_CHUNK)-1))
{
case 7: otp = RC4_STEP<<i, i-=8;
case 6: otp |= RC4_STEP<<i, i-=8;
case 5: otp |= RC4_STEP<<i, i-=8;
case 4: otp |= RC4_STEP<<i, i-=8;
case 3: otp |= RC4_STEP<<i, i-=8;
case 2: otp |= RC4_STEP<<i, i-=8;
case 1: otp |= RC4_STEP<<i, i-=8;
case 0: ; /*
* it's never the case,
* but it has to be here
* for ultrix?
*/
}
ochunk &= ~mask;
ochunk |= (otp^ichunk) & mask;
*(RC4_CHUNK *)outdata = ochunk;
}
key->x=x;
key->y=y;
return;
}
else
{ /* LITTLE-ENDIAN CASE */
# define LESHFT(c) (((c)*8)&(sizeof(RC4_CHUNK)*8-1))
for (;len&-sizeof(RC4_CHUNK);len-=sizeof(RC4_CHUNK))
{
ichunk = *(RC4_CHUNK *)indata;
otp = RC4_STEP;
otp |= RC4_STEP<<8;
otp |= RC4_STEP<<16;
otp |= RC4_STEP<<24;
if (sizeof(RC4_CHUNK)==8)
{
otp |= RC4_STEP<<LESHFT(4);
otp |= RC4_STEP<<LESHFT(5);
otp |= RC4_STEP<<LESHFT(6);
otp |= RC4_STEP<<LESHFT(7);
}
*(RC4_CHUNK *)outdata = otp^ichunk;
indata += sizeof(RC4_CHUNK);
outdata += sizeof(RC4_CHUNK);
}
if (len)
{
RC4_CHUNK mask=(RC4_CHUNK)-1, ochunk;
ichunk = *(RC4_CHUNK *)indata;
ochunk = *(RC4_CHUNK *)outdata;
otp = 0;
i = 0;
mask >>= (sizeof(RC4_CHUNK)-len)<<3;
switch (len&(sizeof(RC4_CHUNK)-1))
{
case 7: otp = RC4_STEP, i+=8;
case 6: otp |= RC4_STEP<<i, i+=8;
case 5: otp |= RC4_STEP<<i, i+=8;
case 4: otp |= RC4_STEP<<i, i+=8;
case 3: otp |= RC4_STEP<<i, i+=8;
case 2: otp |= RC4_STEP<<i, i+=8;
case 1: otp |= RC4_STEP<<i, i+=8;
case 0: ; /*
* it's never the case,
* but it has to be here
* for ultrix?
*/
}
ochunk &= ~mask;
ochunk |= (otp^ichunk) & mask;
*(RC4_CHUNK *)outdata = ochunk;
}
key->x=x;
key->y=y;
return;
}
}
#endif
#define LOOP(in,out) \
x=((x+1)&0xff); \
tx=d[x]; \
y=(tx+y)&0xff; \
d[x]=ty=d[y]; \
d[y]=tx; \
(out) = d[(tx+ty)&0xff]^ (in);
#ifndef RC4_INDEX
#define RC4_LOOP(a,b,i) LOOP(*((a)++),*((b)++))
#else
#define RC4_LOOP(a,b,i) LOOP(a[i],b[i])
#endif
i=(int)(len>>3L);
if (i)
{
for (;;)
{
RC4_LOOP(indata,outdata,0);
RC4_LOOP(indata,outdata,1);
RC4_LOOP(indata,outdata,2);
RC4_LOOP(indata,outdata,3);
RC4_LOOP(indata,outdata,4);
RC4_LOOP(indata,outdata,5);
RC4_LOOP(indata,outdata,6);
RC4_LOOP(indata,outdata,7);
#ifdef RC4_INDEX
indata+=8;
outdata+=8;
#endif
if (--i == 0) break;
}
}
i=(int)len&0x07;
if (i)
{
for (;;)
{
RC4_LOOP(indata,outdata,0); if (--i == 0) break;
RC4_LOOP(indata,outdata,1); if (--i == 0) break;
RC4_LOOP(indata,outdata,2); if (--i == 0) break;
RC4_LOOP(indata,outdata,3); if (--i == 0) break;
RC4_LOOP(indata,outdata,4); if (--i == 0) break;
RC4_LOOP(indata,outdata,5); if (--i == 0) break;
RC4_LOOP(indata,outdata,6); if (--i == 0) break;
}
}
key->x=x;
key->y=y;
}
#ifndef COMPACK_SIZE
const char *RC4_options(void)
{
#ifdef RC4_INDEX
if (sizeof(RC4_INT) == 1)
return("rc4(idx,char)");
else
return("rc4(idx,int)");
#else
if (sizeof(RC4_INT) == 1)
return("rc4(ptr,char)");
else
return("rc4(ptr,int)");
#endif
}
#endif
/* RC4 as implemented from a posting from
* Newsgroups: sci.crypt
* From: sterndark@netcom.com (David Sterndark)
* Subject: RC4 Algorithm revealed.
* Message-ID: <sternCvKL4B.Hyy@netcom.com>
* Date: Wed, 14 Sep 1994 06:35:31 GMT
*/
void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data)
{
register RC4_INT tmp;
register int id1,id2;
register RC4_INT *d;
unsigned int i;
d= &(key->data[0]);
for (i=0; i<256; i++)
d[i]=i;
key->x = 0;
key->y = 0;
id1=id2=0;
#define SK_LOOP(n) { \
tmp=d[(n)]; \
id2 = (data[id1] + tmp + id2) & 0xff; \
if (++id1 == len) id1=0; \
d[(n)]=d[id2]; \
d[id2]=tmp; }
for (i=0; i < 256; i+=4)
{
SK_LOOP(i+0);
SK_LOOP(i+1);
SK_LOOP(i+2);
SK_LOOP(i+3);
}
}

View File

@ -0,0 +1,89 @@
/* crypto/rc4/rc4.h */
/* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef HEADER_RC4_H
#define HEADER_RC4_H
#ifdef OPENSSL_NO_RC4
#error RC4 is disabled.
#endif
//#include <openssl/opensslconf.h> /* RC4_INT */
#define RC4_INT unsigned int
#ifdef __cplusplus
extern "C" {
#endif
typedef struct rc4_key_st
{
RC4_INT x,y;
RC4_INT data[256];
} RC4_KEY;
const char *RC4_options(void);
void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data);
void RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata,
unsigned char *outdata);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,83 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_reauth_sm.c
// Programmer : Arunesh Mishra
// Reauthentication State Machine.
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#include "1x_common.h"
#include "1x_auth_pae.h"
#include <stddef.h>
#include "1x_reauth_sm.h"
#include "assert.h"
//--------------------------------------------------
// init function.
//--------------------------------------------------
void lib1x_reauthsm_init( Reauth_SM * reauth_sm , int reAuthTO )
{
assert ( reauth_sm != NULL );
reauth_sm->state = resm_Initialize; // Not sure if I should start in the initialize state.
if ( reAuthTO == 0 )
{
reauth_sm->reAuthEnabled = FALSE;
reauth_sm->reAuthPeriod = LIB1X_RSM_REAUTHPERIOD;
}
else
{
reauth_sm->reAuthEnabled = TRUE;
reauth_sm->reAuthPeriod = reAuthTO;
}
}
//--------------------------------------------------
// One transition and state specific inits.
//--------------------------------------------------
void lib1x_trans_reauthsm( Global_Params * global , Reauth_SM * reauth_sm)
{
// Global Transitions first :
if ( ( global->portControl != pmt_Auto ) || global->initialize ||
( global->portStatus == pst_Unauthorized) || ! reauth_sm->reAuthEnabled )
{
reauth_sm->state = resm_Initialize;
global->timers->reAuthWhen = reauth_sm->reAuthPeriod;
// TODO: Any initialization of timers here.
return;
}
// Specific Transitions:
if ( reauth_sm->state == resm_Initialize )
{
if ( global->timers->reAuthWhen == 0 )
{
reauth_sm->state = resm_Reauthenticate;
global->reAuthenticate = TRUE;
return;
}
return;
}
if ( reauth_sm->state == resm_Reauthenticate )
{
reauth_sm->state = resm_Initialize;
global->timers->reAuthWhen = reauth_sm->reAuthPeriod;
return;
}
}

View File

@ -0,0 +1,262 @@
#include "1x_common.h"
#include "1x_supp_pae.h"
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : 1x_supp_pae.c
// Programmer : Arunesh Mishra
// Implements the Supplicant PAE
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//--------------------------------------------------
BOOLEAN lib1x_trans_suppsm( Supp_Pae_Params * supp_params, Global * global )
{
// Global conditions first
if ( ( supp_params->userLogoff && !supp_params->logoffSent ) &&
!( global->initialize || ! global->portEnabled ) )
{
supp_params->state = Logoff;
return TRUE;
}
if ( global->initialize || ! global->portEnabled )
{
supp_params->state = Disconnected ;
return TRUE;
}
if ( supp_params->eapFail &&
! ( global->initialize || ! global->portEnabled )
&& ! supp_params->userLogoff && ! supp_params->logoffSent )
{
supp_params->state = Held;
return TRUE;
}
if ( supp_params->eapSuccess &&
!( global->initialize || ! global->portEnabled )
&& ! supp_params->userLogoff || ! supp_params->logoffSent )
{
supp_parms->state = Authenticated;
return TRUE;
}
// Actual Transition function i.e. non -global transitions
switch ( supp_params->state )
{
case Logoff:
if ( ! supp_params->userLogoff )
{
supp_params->state = Disconnected;
return TRUE;
}
break;
case Disconnected:
supp_params->state = Connecting; // Unconditional Transfer !
return TRUE;
break;
case Connecting:
if ( ( global->timers->startWhen == 0 ) &&
( supp_params->startCount >= supp_params->maxStart ))
{
supp_params->state = Authenticated;
return TRUE;
}
if ( supp_params->reqId )
{
supp_params->state = Acquired;
return TRUE;
}
if ( ( global->timers->startWhen == 0 ) &&
( supp_params->startCount < supp_params->maxStart ) )
{
// Same state
return TRUE;
}
break;
case Held:
if ( global->timers->heldWhile == 0 )
{
supp_params->state = Connecting;
return TRUE;
}
if ( supp_params->reqId )
{
supp_params->state = Acquired;
return TRUE;
}
break;
case Authenticating:
if ( supp_params->reqAuth )
{
// same state
return TRUE;
}
if ( supp_params->reqId )
{
supp_params->state = Acquired;
return TRUE;
}
if ( global->timers->authWhile == 0 )
{
supp_params->state = Connecting;
return TRUE;
}
break;
case Acquired:
if ( supp_params->reqId )
{
// Same state
return TRUE;
}
if ( supp_params->reqAuth )
{
supp_params->state = Authenticating;
return TRUE;
}
if ( global->timers->authWhile == 0 )
{
supp_params->state = Authenticating;
return TRUE;
}
break;
case Authenticated:
if ( supp_params->reqId )
{
supp_params->state = Acquired;
return TRUE;
}
break;
}
}
void lib1x_exec_suppsm( Supp_Pae_Params * supp_params, Global * global )
{
switch ( supp_params->state )
{
case Logoff:
lib1x_suppsm_logoff( supp_params, global );
break;
case Disconnected:
lib1x_suppsm_disconnected( supp_params, global );
break;
case Connecting:
lib1x_suppsm_connecting( supp_params, global );
break;
case Held:
lib1x_suppsm_held( supp_params, global );
break;
case Authenticating:
lib1x_suppsm_authenticating( supp_params, global );
break;
case Acquired:
lib1x_suppsm_acquired( supp_params, global );
break;
case Authenticated:
lib1x_suppsm_authenticated( supp_params, global );
break;
}
}
void lib1x_suppsm_logoff( Supp_Pae_Params * supp_params, Global * global )
{
lib1x_suppsm_txLogoff();
supp_params->logoffSent = TRUE;
supp_params->suppStatus = Unauthorized;
}
void lib1x_suppsm_disconnected( Supp_Pae_Params * supp_params, Global * global )
{
supp_params->eapSuccess = FALSE;
supp_params->eapFail = FALSE;
supp_params->startCount = 0;
supp_params->logoffSent = FALSE;
supp_params->previousId = 256;
supp_params->suppStatus = Unauthorized;
}
void lib1x_suppsm_connecting( Supp_Pae_Params * supp_params, Global * global )
{
global->timers->startWhen = supp_params->startPeriod;
supp_params->startCount ++;
supp_params->reqId = FALSE;
lib1x_suppsm_txStart();
}
void lib1x_suppsm_acquired( Supp_Pae_Params * supp_params, Global * global )
{
global->timers->authWhile = supp_params->authPeriod;
supp_params->startCount = 0;
supp_params->reqId = FALSE;
supp_params->reqAuth = FALSE;
lib1x_suppsm_txRspId( global->receivedId, supp_params->previousId );
supp_params->previousId = global->receivedId;
}
void lib1x_suppsm_authenticating( Supp_Pae_Params * supp_params, Global * global )
{
global->timers->authWhile = supp_params->authPeriod;
supp_params->reqAuth = FALSE;
lib1x_suppsm_txRspAuth( global->receivedId, supp_params->previousId );
supp_params->previousId = global->receivedId;
}
void lib1x_suppsm_held( Supp_Pae_Params * supp_params, Global * global )
{
global->timers->heldWhile = supp_params->heldPeriod;
supp_params->eapFail = FALSE;
supp_params->eapSuccess = FALSE;
supp_params->suppStatus = Unauthorized;
}
void lib1x_suppsm_authenticated( Supp_Pae_Params * supp_params, Global * global )
{
supp_params->eapSuccess = FALSE;
supp_params->eapFail = FALSE;
supp_params->suppStatus = Authorized;
}

View File

@ -0,0 +1,152 @@
LOCAL_PATH := $(call my-dir)
#########################
ARCH := rWPA.a
NAME := rWPA
WPA_ROOT_DIR = ..
RTL_WPA_TARGET = auth
###### WPA2 #######
ENABLE_WPA2 = true
ENABLE_WPA2_PREAUTH = true
ENABLE_WPA2_CLIENT = true
ENABLE_CLIENT_TLS = false
###### 2 set of RADIUS #######
ENABLE_RADIUS_2SET = true
###### Endian ######
ifeq ($(BIG_ENDIAN), y)
ENABLE_BIG_ENDIAN = true
else
ENABLE_BIG_ENDIAN = false
endif
ifeq ($(RTL8186_TR), 1)
RTL_WPA_CFLAG += -DCONFIG_RTL8186_TR
ENABLE_WPA2_CLIENT = false
ENABLE_WPA2_PREAUTH = false
endif
ifeq ($(RTL865X_AC), 1)
RTL_WPA_CFLAG += -DCONFIG_RTL865X_AC
ENABLE_WPA2_CLIENT = false
ENABLE_WPA2_PREAUTH = false
endif
ifeq ($(RTL865X_KLD), 1)
RTL_WPA_CFLAG += -DCONFIG_RTL865X_KLD
#ENABLE_WPA2_CLIENT = false
ENABLE_WPA2_PREAUTH = false
endif
ifeq ($(CONFIG_RTL865X_SC), 1)
RTL_WPA_CFLAG += -DCONFIG_RTL865X_SC
ENABLE_WPA2_CLIENT = false
#ENABLE_WPA2_PREAUTH = false
endif
DBG_FLAG := -DDEBUG_DISABLE
DOWN_SIZE := -DCOMPACK_SIZE
#INCS := -I$(TOP_USERS_DIR)/include
RTL_WPA_CFLAG += -Wall -Os $(DOWN_SIZE) $(DBG_FLAG) #$(INCS)
ifeq ($(SLINK), 1)
RTL_WPA_CFLAG += -ffunction-sections -fdata-sections
RTL_WPA_LDFLAG += --static -Wl,--gc-sections
endif
#RTL_WPA_IFLAGS = -I${WPA_ROOT_DIR}/include
ifeq ($ENABLE_BIG_ENDIAN), true)
RTL_WPA_DEFFLAGS = -D_ON_RTL8181_TARGET -DLIBNET_BIG_ENDIAN -DLIB1X_BIG_ENDIAN -D_DAEMON_SIDE -D_RTL_WPA_UNIX
else
RTL_WPA_DEFFLAGS = -D_ON_RTL8181_TARGET -DLIBNET_LIL_ENDIAN -DLIB1X_LIL_ENDIAN -D_DAEMON_SIDE -D_RTL_WPA_UNIX
endif
ifeq ($(ASUS),1)
RTL_WPA_DEFFLAGS += -D__ASUS_DVD__ -DPSK_ONLY -DAUTH_LITTLE_ENDIAN -DSTART_AUTH_IN_LIB
else
ifeq ($(ENABLE_BIG_ENDIAN), true)
RTL_WPA_DEFFLAGS += -DAUTH_BIG_ENDIAN
else
RTL_WPA_DEFFLAGS += -DAUTH_LITTLE_ENDIAN
endif
endif
ifeq ($(strip $(ENABLE_WPA2)),true)
RTL_WPA_DEFFLAGS += -DRTL_WPA2
RTL_WPA_CFLAG += -g
endif
ifeq ($(strip $(ENABLE_WPA2_PREAUTH)),true)
RTL_WPA_DEFFLAGS += -DRTL_WPA2_PREAUTH
endif # ENABLE_WPA2_PREAUTH
ifeq ($(strip $(ENABLE_WPA2_CLIENT)),true)
RTL_WPA_DEFFLAGS += -DRTL_WPA2_CLIENT
endif # ENABLE_WPA2_CLIENT
ifeq ($(strip $(ENABLE_RADIUS_2SET)),true)
RTL_WPA_DEFFLAGS += -DRTL_RADIUS_2SET
endif #ENABLE_RADIUS_2SET
#------------------------------------------------------------------------
# source files
#------------------------------------------------------------------------
RTL_WPA_SRCS = auth.c \
1x_auth_pae.c 1x_bauth_sm.c 1x_common.c 1x_krc_sm.c \
1x_nal.c 1x_kxsm.c 1x_radius.c 1x_ptsm.c 1x_reauth_sm.c \
1x_cdsm.c 1x_config.c 1x_ioctl.c 1x_parser.c \
1x_kmsm_auth.c 1x_kmsm_supp.c 1x_kmsm_eapolkey.c \
1x_info_auth.c 1x_kmsm_hmac.c 1x_kmsm_prf.c 1x_kmsm_aes.c 1x_acct_sm.c 1x_md5c.c 1x_rc4.c libnet.c
ifeq ($(strip $(ENABLE_WPA2)),true)
RTL_WPA_SRCS += 1x_pmk_cache.c
endif # ENABLE_WPA2
#RTL_WPA_OBJS = ${RTL_WPA_SRCS:.c=.o}
ifeq ($(ASUS),1)
RTL_WPA_SRCS += iwcontrol.c
endif
INCLUDES += external/openssl/include
#########################
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := $(RTL_WPA_SRCS)
LOCAL_MODULE := auth
OCAL_SHARED_LIBRARIES := libc libssl
LOCAL_CFLAGS := -Os -Wall $(RTL_WPA_DEFFLAGS) -D__ANDROID__
LOCAL_C_INCLUDES:= $(KERNEL_HEADERS) $(INCLUDES) $(LOCAL_PATH)/../include $(LOCAL_PATH)/../../include
include $(BUILD_EXECUTABLE)
#########################
dlisten_SRCS = dlisten/iwcontrol.c dlisten/iwconfig.c dlisten/iwcommon.c dlisten/iwreq.c
DRL_WPA_DEFFLAGS += -DGLIBC22_HEADERS
DRTL_WPA_CFLAG = -Wall -Os
DRTL_WPA_CFLAG += -DFOR_DUAL_BAND
ifeq ($(SLINK),1)
DRTL_WPA_CFLAG += -ffunction-sections -fdata-sections
DRTL_WPA_LDFLAG += --static -Wl,--gc-sections
endif
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := $(dlisten_SRCS)
LOCAL_MODULE := iwcontrol
LOCAL_SHARED_LIBRARIES := libc libssl
LOCAL_CFLAGS := -Os -Wall $(DRTL_WPA_DEFFLAGS) $(DRTL_WPA_CFLAG) -D__ANDROID__
LOCAL_C_INCLUDES:= $(KERNEL_HEADERS) $(INCLUDES) $(LOCAL_PATH)/../include $(LOCAL_PATH)/../../include
include $(BUILD_EXECUTABLE)

View File

@ -0,0 +1,250 @@
#
# Makefile for WPA for the Linux OS
#
#
# $Id: Makefile,v 1.8 2008/10/13 01:10:14 davidhsu Exp $
#
ARCH = rWPA.a
NAME = rWPA
WPA_ROOT_DIR = ..
RTL_WPA_TARGET = auth
###### WPA2 #######
ENABLE_WPA2 = true
ENABLE_WPA2_PREAUTH = true
ENABLE_WPA2_CLIENT = true
ENABLE_CLIENT_TLS = false
ENABLE_PMF = true
###### 2 set of RADIUS #######
ENABLE_RADIUS_2SET = true
###### Endian ######
ifeq ($(BIG_ENDIAN),y)
ENABLE_BIG_ENDIAN = true
else
ENABLE_BIG_ENDIAN = false
endif
#CC = $(CROSS_COMPILE)gcc
#STRIP = $(CROSS_COMPILE)strip
#LD = $(CROSS_COMPILE)ld
#AR = $(CROSS_COMPILE)ar
ifeq ($(RTL8186_TR),1)
RTL_WPA_CFLAG += -DCONFIG_RTL8186_TR
ENABLE_WPA2_CLIENT = false
ENABLE_WPA2_PREAUTH = false
endif
ifeq ($(RTL865X_AC),1)
RTL_WPA_CFLAG += -DCONFIG_RTL865X_AC
ENABLE_WPA2_CLIENT = false
ENABLE_WPA2_PREAUTH = false
endif
ifeq ($(RTL865X_KLD),1)
RTL_WPA_CFLAG += -DCONFIG_RTL865X_KLD
#ENABLE_WPA2_CLIENT = false
ENABLE_WPA2_PREAUTH = false
endif
ifeq ($(CONFIG_RTL865X_SC),1)
RTL_WPA_CFLAG += -DCONFIG_RTL865X_SC
ENABLE_WPA2_CLIENT = false
#ENABLE_WPA2_PREAUTH = false
endif
#kenny
DBG_FLAG=-DDEBUG_DISABLE
DOWN_SIZE=-DCOMPACK_SIZE
INCS = -I$(TOP_USERS_DIR)/include
RTL_WPA_CFLAG += -Wall -Os $(DOWN_SIZE) $(DBG_FLAG) $(INCS)
ifeq ($(SLINK),1)
RTL_WPA_CFLAG += -ffunction-sections -fdata-sections
RTL_WPA_LDFLAG += --static -Wl,--gc-sections
endif
#RTL_WPA_CFLAG = -Wall -O2
#RTL_WPA_LDFLAG = #-r
RTL_WPA_IFLAGS = -I${WPA_ROOT_DIR}/include
#RTL_WPA_LIBS = ${WPA_ROOT_DIR}/Package/libnet.a \
${WPA_ROOT_DIR}/Package/libpcap.a \
${WPA_ROOT_DIR}/Package/libcrypto.a
ifeq ($(strip $(ENABLE_BIG_ENDIAN)),true)
RTL_WPA_DEFFLAGS = -D_ON_RTL8181_TARGET -DLIBNET_BIG_ENDIAN -DLIB1X_BIG_ENDIAN -D_DAEMON_SIDE -D_RTL_WPA_UNIX
else
RTL_WPA_DEFFLAGS = -D_ON_RTL8181_TARGET -DLIBNET_LIL_ENDIAN -DLIB1X_LIL_ENDIAN -D_DAEMON_SIDE -D_RTL_WPA_UNIX
endif
ifeq ($(ASUS),1)
RTL_WPA_DEFFLAGS += -D__ASUS_DVD__ -DPSK_ONLY -DAUTH_LITTLE_ENDIAN -DSTART_AUTH_IN_LIB
else
ifeq ($(strip $(ENABLE_BIG_ENDIAN)),true)
RTL_WPA_DEFFLAGS += -DAUTH_BIG_ENDIAN
else
RTL_WPA_DEFFLAGS += -DAUTH_LITTLE_ENDIAN
endif
endif
ifeq ($(strip $(ENABLE_CLIENT_TLS)),true)
XSUPP_LIBS = xsup_src/xsup.a -ldl
openssl_dir = ../../openssl-0.9.8b
ifeq ($(strip $(USE_OPENSSL_DLIB)),true)
XSUPP_LIBS += ${openssl_dir}/libssl.so ${openssl_dir}/libcrypto.so
else
XSUPP_LIBS += ${openssl_dir}/libssl.a ${openssl_dir}/libcrypto.a
endif
RTL_WPA_DEFFLAGS += -DCLIENT_TLS
endif
ifeq ($(strip $(ENABLE_WPA2)),true)
RTL_WPA_DEFFLAGS += -DRTL_WPA2
RTL_WPA_CFLAG += -g
endif # ENABLE_WPA2
ifeq ($(strip $(ENABLE_WPA2_PREAUTH)),true)
RTL_WPA_DEFFLAGS += -DRTL_WPA2_PREAUTH
endif # ENABLE_WPA2_PREAUTH
ifeq ($(strip $(ENABLE_WPA2_CLIENT)),true)
RTL_WPA_DEFFLAGS += -DRTL_WPA2_CLIENT
endif # ENABLE_WPA2_CLIENT
ifeq ($(strip $(ENABLE_PMF)),true)
RTL_WPA_DEFFLAGS += -DCONFIG_IEEE80211W
endif # ENABLE_PMF
ifeq ($(strip $(ENABLE_RADIUS_2SET)),true)
RTL_WPA_DEFFLAGS += -DRTL_RADIUS_2SET
endif #ENABLE_RADIUS_2SET
#------------------------------------------------------------------------
# source files
#------------------------------------------------------------------------
RTL_WPA_SRCS = auth.o \
1x_auth_pae.o 1x_bauth_sm.o 1x_common.o 1x_krc_sm.o \
1x_nal.o 1x_kxsm.o 1x_radius.o 1x_ptsm.o 1x_reauth_sm.o \
1x_cdsm.o 1x_config.o 1x_ioctl.o 1x_parser.o \
1x_kmsm_auth.o 1x_kmsm_supp.o 1x_kmsm_eapolkey.o \
1x_info_auth.o 1x_kmsm_hmac.o 1x_kmsm_prf.o 1x_kmsm_aes.o 1x_acct_sm.o 1x_md5c.o 1x_rc4.o libnet.o
ifeq ($(strip $(ENABLE_PMF)),true)
RTL_WPA_SRCS += sha256.o
endif # ENABLE_PMF
ifeq ($(strip $(ENABLE_WPA2)),true)
RTL_WPA_SRCS += 1x_pmk_cache.o
endif # ENABLE_WPA2
RTL_WPA_OBJS = ${RTL_WPA_SRCS:.c=.o}
ifeq ($(ASUS),1)
RTL_WPA_SRCS += iwcontrol.o
endif
#------------------------------------------------------------------------
# Transition rules (add -o to put object in right directory)
#------------------------------------------------------------------------
.c.o:
$(CC) $(CFLAGS) $(RTL_WPA_CFLAG) $(RTL_WPA_IFLAGS) $(RTL_WPA_DEFFLAGS) -c -o $*.o $<
#ifeq ($(ASUS),1)
#iwcontrol.o: dlisten/iwcontrol.c
# $(CC) $(RTL_WPA_CFLAG) $(RTL_WPA_IFLAGS) $(RTL_WPA_DEFFLAGS) -c -o $*.o $<
#endif
###################
#all: build_lib build_listen ${RTL_WPA_TARGET} wpa_bin pretest
#all: pretest build_listen ${RTL_WPA_TARGET} wpa_bin
ifeq ($(strip $(ENABLE_CLIENT_TLS)),true)
all: xsup rwCert ${RTL_WPA_TARGET}
else
### ASUS library ###
ifeq ($(ASUS),1)
ASUS_WPA_LIB = auth.a
${ASUS_WPA_LIB}: ${RTL_WPA_OBJS}
$(AR) r $@ $(RTL_WPA_OBJS)
$(STRIP) -S $@
all: ${ASUS_WPA_LIB}
iwcontrol.o: dlisten/iwcontrol.c
$(CC) $(RTL_WPA_CFLAG) $(RTL_WPA_IFLAGS) $(RTL_WPA_DEFFLAGS) -c -o $*.o $<
else
### 8186 daemon ###
all: ${RTL_WPA_TARGET}
endif
endif
build_lib:
cd ${WPA_ROOT_DIR}/Package/Libnet-1.0.2a; \
${MAKE} clean; \
${MAKE} -f Makefile-rtl8181 RTL_WPA_CFLAG='${RTL_WPA_CFLAG}' RTL_WPA_LDFLAG='${RTL_WPA_LDFLAG}' RTL_WPA_DEFFLAGS='${RTL_WPA_DEFFLAGS}';
cd ${WPA_ROOT_DIR}/Package/libpcap-0.7.2; \
${MAKE} clean; \
${MAKE} -f Makefile-rtl8181 RTL_WPA_CFLAG='${RTL_WPA_CFLAG}' RTL_WPA_LDFLAG='${RTL_WPA_LDFLAG}' RTL_WPA_DEFFLAGS='${RTL_WPA_DEFFLAGS}';
cd ${WPA_ROOT_DIR}/Package/openssl-0.9.7d; \
${MAKE} clean; \
${MAKE} -f Makefile-rtl8181 RTL_WPA_CFLAG='${RTL_WPA_CFLAG}' RTL_WPA_LDFLAG='${RTL_WPA_LDFLAG}' RTL_WPA_DEFFLAGS='${RTL_WPA_DEFFLAGS}';
build_listen:
cd dlisten; ${MAKE} clean; \
${MAKE} -f Makefile-rtl8181 RTL_WPA_CFLAG='${RTL_WPA_CFLAG}' RTL_WPA_LDFLAG='${RTL_WPA_LDFLAG}' ;
ifeq ($(strip $(ENABLE_CLIENT_TLS)),true)
${RTL_WPA_TARGET}: ${RTL_WPA_OBJS} ${RTL_WPA_LIBS} ${XSUPP_LIBS}
$(CC) $(RTL_WPA_LDFLAG) -o $@ $(RTL_WPA_OBJS) ${RTL_WPA_LIBS} ${XSUPP_LIBS}
$(STRIP) $@
else
${RTL_WPA_TARGET}: ${RTL_WPA_OBJS} ${RTL_WPA_LIBS}
$(CC) $(RTL_WPA_LDFLAG) -o $@ $(RTL_WPA_OBJS) ${RTL_WPA_LIBS}
$(STRIP) $@
cp ./auth ../../bin/auth
endif
pretest: pretest.o
$(CC) $(RTL_WPA_LDFLAG) -o $@ pretest.o
rm pretest.o -f
wpa_bin:
chmod 744 ${WPA_ROOT_DIR}/bin/; \
${STRIP} dlisten/iwcontrol; \
cp dlisten/iwcontrol ${WPA_ROOT_DIR}/bin/; \
# ${STRIP} ${RTL_WPA_TARGET}; \
cp ${RTL_WPA_TARGET} ${WPA_ROOT_DIR}/bin/; \
cp pretest ${WPA_ROOT_DIR}/bin/; \
chmod 777 ${WPA_ROOT_DIR}/bin/*;
SUBDIRS=dlisten
xsup:
@for d in $(SUBDIRS); do (cd $$d && $(MAKE) DESTDIR=${DESTDIR}); done
SUBDIRS2=rwCertSrc
rwCert:
@for d in $(SUBDIRS2); do (cd $$d && $(MAKE) DESTDIR=${DESTDIR}); done
##-------------------------------------------------
clean:
rm -f *.o; rm -f ${RTL_WPA_TARGET}; rm -f *.a
# @for d in $(SUBDIRS); do (cd $$d && $(MAKE) DESTDIR=${DESTDIR} clean); done

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,649 @@
//--------------------------------------------------
// IEEE 802.1x Implementation
//
// File : auth.c
// Programmer : Arunesh Mishra
//
//
// Copyright (c) Arunesh Mishra 2002
// All rights reserved.
// Maryland Information and Systems Security Lab
// University of Maryland, College Park.
//
//--------------------------------------------------
#include <stdio.h>
#include <getopt.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <signal.h>
#include "1x_common.h"
#include "1x_auth_pae.h"
#include "1x_nal.h"
#include "1x_radius.h"
#include "1x_fifo.h"
#include "1x_ioctl.h"
#define SVR_ETH_ADDR { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // we do not need this currently
#define UDP_OURPORT 1116
#define IP_ADDRSIZE 50
// mark following define by referring the definition in 1x_common.h, david+2006-02-06
//#define MAX_SUPPLICANT 32
//#define MAX_SUPPLICANT 1
int lib1x_load_config(Dot1x_Authenticator * auth, char *confFileName);
#ifdef START_AUTH_IN_LIB
int lib1x_load_config_param(Dot1x_Authenticator *auth, auth_param_t *pParam);
extern int sockets_open(void);
#endif
//2003-06-27
#define PID_NAME_FMT (TOP_CONFIG_DIR "/run/auth-%s.pid")
/*
Debugging message dump
*/
#ifdef DEBUG_DISABLE
#define _AUTH_DBGMSG(fmt, args...)
#else
#define _AUTH_DBGMSG(fmt, args...) \
do {printf("[%s-%d]-DEBUG-: " fmt "\n", __FUNCTION__, __LINE__, ## args);} while (0)
#endif
#define _AUTH_ERRMSG(fmt, args...) \
do {printf("[%s-%d]-ERROR-: " fmt "\n", __FUNCTION__, __LINE__, ## args);} while (0)
Dot1x_Authenticator RTLAuthenticator;
#ifdef RTL_WPA_CLIENT
#include "1x_supp_pae.h"
Dot1x_Client RTLClient;
#endif
#ifdef CLIENT_TLS
#include "xsup_src/profile.h"
#include "xsup_src/xsup_err.h"
#include "xsup_src/xsup_debug.h"
#include "xsup_src/statemachine.h"
#include "xsup_src/eapol.h"
extern struct interface_data *int_list;
#endif
/*
* The following four options are taken from the config file
*/
u_char svrip[IP_ADDRSIZE+1];
u_char dev_svr[LIB1X_MAXDEVLEN];
u_char dev_supp[LIB1X_MAXDEVLEN];
u_short udp_svrport;
#ifdef RTL_RADIUS_2SET
u_char svrip2[IP_ADDRSIZE+1];
u_short udp_svrport2;
#endif
u_char oursvr_addr[ ETHER_ADDRLEN];
u_char oursupp_addr[ ETHER_ADDRLEN];
u_char svraddr[ ETHER_ADDRLEN];
u_char ourip[IP_ADDRSIZE+1];
/*
* Determine IP and ETH addresses
* Currently we are using libnet for this.
*/
// david
//void lib1x_resolve()
int lib1x_resolve()
{
u_char errbuf[LIBNET_ERRBUF_SIZE];
struct ether_addr * eth;
struct libnet_link_int * l;
#if defined(CONFIG_RTL8196C_AP_HCM)
unsigned char host_mac[6] = {0x00,0x12,0x34,0x56,0x78,0x99};
#endif //defined(CONFIG_RTL8196C_AP_HCM)
#ifndef PSK_ONLY
struct in_addr tmpip;
l = libnet_open_link_interface( dev_svr, errbuf );
if ( l == NULL ) {
lib1x_message(MESS_ERROR_FATAL,"open1x: Could not open interface %s", dev_svr );
return -1; // david
}
tmpip.s_addr = ntohl(libnet_get_ipaddr(l, dev_svr, errbuf));
if ( tmpip.s_addr == -1 ) {
lib1x_message(MESS_ERROR_FATAL,"open1x: Could not obtain IP for interface %s", dev_svr );
return -1; // david
}
strcpy( ourip, inet_ntoa(tmpip));
eth = libnet_get_hwaddr( l, dev_svr, errbuf);
if (eth == NULL ) {
lib1x_message(MESS_ERROR_FATAL,"open1x: Could not obtain ethernet address for interface %s", dev_svr );
return -1; // david
}
memcpy( oursvr_addr, eth, ETHER_ADDRLEN);
#if defined(CONFIG_RTL8196C_AP_HCM)
memcpy(oursvr_addr, host_mac, 6);
#endif
libnet_close_link_interface(l); // david
#endif
l = libnet_open_link_interface( dev_supp, errbuf );
if ( l == NULL ) {
lib1x_message(MESS_ERROR_FATAL,"open1x: Could not open interface %s", dev_supp );
return -1; // david
}
eth = libnet_get_hwaddr( l, dev_supp, errbuf);
if (eth == NULL ) {
lib1x_message(MESS_ERROR_FATAL,"open1x: Could not obtain ethernet address for interface %s", dev_supp );
return -2; // david
}
memcpy( oursupp_addr, eth, ETHER_ADDRLEN);
libnet_close_link_interface(l); // david
return 0; // david
}
int lib1x_init_fifo(Dot1x_Authenticator *auth, char *wlan_name)
{
int flags, retVal = 0;
struct stat status;
char fifo_name[80];
/* create server's well-known FIFO; OK if already exists */
/*
if((mkfifo(DAEMON_FIFO, FILE_MODE) < 0) )
{
//lib1x_message(MESS_DBG_DAEMON, "can't create %s", DAEMON_FIFO);
}
*/
/* open server's well-known for reading and writing */
sprintf(fifo_name, DAEMON_FIFO, wlan_name);
if(stat(fifo_name, &status) == 0)
unlink(fifo_name);
if((mkfifo(fifo_name, FILE_MODE) < 0)){
printf("mkfifo %s fifo error: %s!\n", fifo_name, strerror(errno));
return -1;
}
auth->GlobalTxRx->readfifo = open(fifo_name, O_RDONLY, 0);
if( (flags = fcntl(auth->GlobalTxRx->readfifo, F_GETFL, 0)) < 0)
{
printf("F_GETF: error\n");
retVal = -1;
}else
{
flags |= O_NONBLOCK;
if( (flags = fcntl(auth->GlobalTxRx->readfifo, F_SETFL, flags)) < 0)
{
printf("F_GETF: error\n");
retVal = -1;
}
}
auth->GlobalTxRx->dummyfd = open(fifo_name, O_WRONLY, 0);
auth->GlobalTxRx->RListenFIFO.Octet = (u_char*)malloc(100);
return retVal;
}
#ifndef START_AUTH_IN_LIB
static int pidfile_acquire(char *pidfile)
{
int pid_fd;
if(pidfile == NULL)
return -1;
pid_fd = open(pidfile, O_CREAT | O_WRONLY, 0644);
if (pid_fd < 0)
printf("Unable to open pidfile %s\n", pidfile);
else
lockf(pid_fd, F_LOCK, 0);
return pid_fd;
}
static void pidfile_write_release(int pid_fd)
{
FILE *out;
if(pid_fd < 0)
return;
if((out = fdopen(pid_fd, "w")) != NULL) {
fprintf(out, "%d\n", getpid());
fclose(out);
}
lockf(pid_fd, F_UNLCK, 0);
close(pid_fd);
}
#endif // !START_AUTH_IN_LIB
void _tmain_hmac();
void TestPassPhrases();
void TestPRF();
void TestRC4();
#ifdef START_AUTH_IN_LIB
int auth_main(auth_param_t *pParam)
#else
int main( int numArgs, char ** theArgs )
#endif
{
u_char eth[50];
char pid_name[100];
int i;
Dot1x_Authenticator * auth = &RTLAuthenticator;
#ifndef START_AUTH_IN_LIB
if ( numArgs < 5 ) {
printf("Usage: auth wlan-interface eth-interface mode conf-file\n");
return -1;
}
#ifdef RTL_WPA_CLIENT
// david -------------------------------
// if (numArgs == 4) {
if(!strcmp(theArgs[3], "client-infra"))
RTLAuthenticator.currentRole = role_Supplicant_infra;
else if(!strcmp(theArgs[3], "client-adhoc"))
RTLAuthenticator.currentRole = role_Supplicant_adhoc;
else if(!strcmp(theArgs[3], "auth"))
RTLAuthenticator.currentRole = role_Authenticator;
else if(!strcmp(theArgs[3], "wds"))
RTLAuthenticator.currentRole = role_wds;
else {
printf("\nArgument 4 is invalid. Valid value are: auth, client-infra or client-adhoc\n");
exit(1);
}
// }
// else
#endif
// RTLAuthenticator.currentRole = role_Authenticator;
RTLAuthenticator.NumOfSupplicant = 0;
//-------------------------------------
#ifdef _ON_RTL8181_TARGET
// 2003-06-27, destroy old process and create a PID file -------
{ FILE *fp;
char line[40];
pid_t pid;
int pid_fd;
sprintf(pid_name, PID_NAME_FMT, theArgs[1]);
if ((fp = fopen(pid_name, "r")) != NULL) {
fgets(line, sizeof(line), fp);
if ( sscanf(line, "%d", &pid) ) {
if (pid > 1)
kill(pid, SIGTERM);
}
fclose(fp);
}
pid_fd = pidfile_acquire(pid_name);
if (pid_fd < 0)
return 0;
if (daemon(0,1) == -1) {
printf("fork auth error!\n");
exit(1);
}
pidfile_write_release(pid_fd);
}
setsid(); // david, requested from abocom
//-----------------------------------------------------------
#endif
#ifdef _ON_RTL8181_TARGET
/*
Application Note:
Usage of 802.1x AUTH daemon:
" auth wlan_interface lan_interface auth wpa_conf & "
- wlan_interface: WLAN interface, e.g. wlan0
- lan_interface : LAN interface which connects to Radius server, e.g. br0 or eth1
- "auth" : denote to act as authenticator
- wpa_conf : path of wpa config file, e.g., /var/wpa-wlan0.conf
*/
/* wlan_interface */
if (strlen(theArgs[1]) >= sizeof(dev_supp))
{
_AUTH_ERRMSG("String Length of parameter [wlan_interface] exceeds (MAX: %d)", sizeof(dev_supp));
return -1;
}
_AUTH_DBGMSG("WLAN interface : %s", theArgs[1]);
strcpy(dev_supp, theArgs[1]);
/* lan_interface */
if (strlen(theArgs[2]) >= sizeof(dev_svr))
{
_AUTH_ERRMSG("String Length of parameter [lan_interface] exceeds (MAX: %d)", sizeof(dev_svr));
return -1;
}
_AUTH_DBGMSG("Radius interface : %s", theArgs[2]);
strcpy(dev_svr, theArgs[2]);
/* wpa_conf */
if (lib1x_load_config(&RTLAuthenticator, theArgs[4]) != 0)
{
_AUTH_ERRMSG("Configuration file [%s] loading FAILED!", theArgs[4]);
return -1;
}
_AUTH_DBGMSG("Configuration file [%s] loading OK!", theArgs[4]);
#else
lib1x_load_config(&RTLAuthenticator, "/etc/wpa.conf");
memcpy(dev_svr, "eth0", sizeof("eth0"));
memcpy(dev_supp, "wlan0", sizeof("wlan0"));
#endif
#else
lib1x_load_config_param(&RTLAuthenticator, pParam);
strcpy(dev_supp, "wlan0");
RTLAuthenticator.currentRole = pParam->role;
#endif // START_AUTH_IN_LIB
memcpy(svrip, RTLAuthenticator.svrip, sizeof(svrip));
udp_svrport = auth->udp_svrport;
#ifdef RTL_RADIUS_2SET
memcpy(svrip2, RTLAuthenticator.svrip2, sizeof(svrip2));
udp_svrport2 = auth->udp_svrport2;
#endif
// david ------------------------
// lib1x_resolve();
#ifdef RTL_WPA_CLIENT
while ((RTLAuthenticator.currentRole != role_Supplicant_adhoc) &&
(RTLAuthenticator.currentRole != role_wds))
#else
while (1)
#endif
{
i = lib1x_resolve();
if ( i == 0 ) // success
break;
if ( i == -1 ) {
sleep(1);
continue;
}
printf("802.1x daemon: open interface failed!\n");
exit(1);
}
//-------------------------------
lib1x_print_etheraddr( eth, oursvr_addr );
lib1x_print_etheraddr( eth, oursupp_addr );
#ifdef CONFIG_RTL865X
printf("Initiate IEEE 802.1X (WPA) daemon, version %d.%d (%d-%d-%d)\n",
AUTH_865XPLATFORM_VERH,
AUTH_865XPLATFORM_VERL,
AUTH_865XPLATFORM_Y,
AUTH_865XPLATFORM_M,
AUTH_865XPLATFORM_D);
#else
printf("IEEE 802.1x (WPA) daemon, version 1.8e\n");
#endif /* CONFIG_RTL865X */
RTLAuthenticator.GlobalTxRx = (TxRx_Params *)lib1x_init_txrx(
&RTLAuthenticator, oursvr_addr, svraddr, oursupp_addr, ourip,
svrip, UDP_OURPORT, udp_svrport,
#ifdef RTL_RADIUS_2SET
svrip2, udp_svrport2,
#endif
auth->acctip, auth->udp_acctport,
dev_svr, dev_supp);
lib1x_init_auth(&RTLAuthenticator);
RTLAuthenticator.Dot1xKeyReplayCounter.field.HighPart = 0xfffffff0;
RTLAuthenticator.Dot1xKeyReplayCounter.field.LowPart = 0;
#ifdef _RTL_WPA_UNIX
lib1x_init_authRSNConfig(&RTLAuthenticator);
lib1x_init_authGlobal(&RTLAuthenticator);
#endif
RTLAuthenticator.MaxSupplicant = MAX_SUPPLICANT;
if ((RTLAuthenticator.currentRole != role_Supplicant_adhoc) &&
(RTLAuthenticator.currentRole != role_wds)) {
#ifndef START_AUTH_IN_LIB
if(lib1x_init_fifo(&RTLAuthenticator, dev_supp)) {
printf("auth-%s:create fifo error \n", dev_supp);
return -1;
}
#endif
for(i = 0; i < MAX_SUPPLICANT; i++) {
// Allocate strcuture when inserting a supplicant dynamically to reduce pre-alloc memory size
#if 0
RTLAuthenticator.Supp[i] = (Dot1x_Supplicant * ) malloc ( sizeof (Dot1x_Supplicant) );
RTLAuthenticator.Supp[i]->index = i;
RTLAuthenticator.Supp[i]->isEnable = FALSE;
RTLAuthenticator.Supp[i]->global = lib1x_init_authenticator( &RTLAuthenticator, RTLAuthenticator.GlobalTxRx );
RTLAuthenticator.Supp[i]->global->index = i;
RTLAuthenticator.Supp[i]->global->theAuthenticator->rinfo->global_identifier = &RTLAuthenticator.GlobalTxRx->GlobalRadId;
#endif
RTLAuthenticator.Supp[i] = NULL;
//---------------------------------------------- david+2006-02-06
}
}
#ifdef RTL_WPA_CLIENT
if ( auth->currentRole != role_Authenticator)
lib1x_init_supp(&RTLAuthenticator, &RTLClient);
// david ----------------------
if ( (auth->currentRole == role_Supplicant_adhoc) || (auth->currentRole == role_wds) ) {
lib1x_control_STA_SetGTK(auth->client->global, auth->RSNVariable.PassPhraseKey, 0);
if (auth->currentRole == role_Supplicant_adhoc) {
lib1x_control_RSNIE(auth, DOT11_Ioctl_Set);
lib1x_control_InitQueue(auth);
}
}
//----------------------------
#endif
// david
// kenny
lib1x_init_authTimer( &RTLAuthenticator);
while(1)
{
//----if 0802
if(auth->RSNVariable.Dot1xEnabled || auth->RSNVariable.RSNEnabled || auth->RSNVariable.MacAuthEnabled)
//----else
//if(auth->RSNVariable.Dot1xEnabled || auth->RSNVariable.RSNEnabled)
//----endif
{
// kenny
#ifdef START_AUTH_IN_LIB
usleep(10000);
if (pParam->terminate){
pParam->terminate = 0;
// free buffer
for(i = 0; i < MAX_SUPPLICANT; i++) {
free(RTLAuthenticator.Supp[i]);
free(RTLAuthenticator.Supp[i]->global);
}
free(RTLClient.auth);
free(RTLClient.global);
free(RTLClient.supp_pae);
return;
}
#endif
#ifdef RTL_WPA_CLIENT
#ifdef CLIENT_TLS
if(auth->currentRole == role_Supplicant_infra
&& RTLClient.global->AuthKeyMethod == DOT11_AuthKeyType_RSN)
{
static int xsup_inited = 0;
static int not_associated = 1;
static int reset_xsup = 0;
not_associated = lib1x_control_STA_QUERY_BSSID(RTLClient.global);
if ( not_associated != 0) {
//printf("%s role_Supplicant_infra not associated!\n", __FUNCTION__);
//printf(".");
if (xsup_inited == 1) {
//statemachine_reset(int_list);
eapol_cleanup(int_list);
reset_xsup = 1;
//printf("set xsup_inited = %d\n", xsup_inited);
}
continue;
}
if (xsup_inited == 1) {
if (reset_xsup == 1) {
eapol_init(int_list);
reset_xsup = 0;
lib1x_reset_supp(RTLClient.global);
}
}
else
{
void global_deinit(int);
static char *xsup_argv[]= { "xsuplicant", "-i", "wlan0", "-c", "/etc/1x/1x.conf", "-d", "4" };
static const int xsup_argc = 7;
struct sigaction action;
lib1x_reset_supp(RTLClient.global);
lib1x_message(MESS_DBG_SUPP, "Wait for packet Timeout, Resent");
lib1x_message(MESS_DBG_SUPP, "reset_xsup == %d, lib1x_control_STA_QUERY_BSSID(RTLClient.global) = %d\n", xsup_inited, not_associated);
xsup_main(xsup_argc, xsup_argv);
xsup_inited = 1;
// When we quit, cleanup.
action.sa_handler = (void (*)())global_deinit;
action.sa_flags = 0;
if (sigaction(SIGTERM,&action,0)==-1)
{
perror( "sigaction");
printf("sigaction %d\n", __LINE__);
return 1;
}
if (sigaction(SIGINT,&action,0)==-1)
{
perror( "sigaction");
printf("sigaction %d\n", __LINE__);
return 1;
}
if (sigaction(SIGQUIT,&action,0)==-1)
{
perror( "sigaction");
printf("sigaction %d\n", __LINE__);
return 1;
}
//signal(SIGTERM, global_deinit);
//signal(SIGINT, global_deinit);
//signal(SIGQUIT, global_deinit);
//signal(SIGKILL, global_deinit);
lib1x_message(MESS_DBG_SUPP, "xsup_inited == %d, lib1x_control_STA_QUERY_BSSID(RTLClient.global) = %d\n", xsup_inited, not_associated);
}
}
#endif /* CLIENT_TLS */
// david ---------------------------
#if 0
if(auth->currentRole == role_Supplicant)
lib1x_do_supplicant(&RTLAuthenticator, RTLClient.global);
else
#endif
if(auth->currentRole == role_Supplicant_infra)
lib1x_do_supplicant(&RTLAuthenticator, RTLClient.global);
else if ( (auth->currentRole == role_Supplicant_adhoc) ||
(auth->currentRole == role_wds) )
break;
else
//----------------------------------
#endif
lib1x_do_authenticator( &RTLAuthenticator );
// david ---------
// kenny
/*
if (!(cnt++%10))
lib1x_timer_authenticator(SIGALRM);
usleep(10000);
*/
//----------------
}
else
sleep(1000);
}
unlink(pid_name);
return 0;
}
#ifdef START_AUTH_IN_LIB
#if 0
int main()
{
auth_param_t param;
param.encryption = 2; // 2:WPA, 4:WPA2
strcpy(param.psk, "1234567890");
strcpy(param.ssid, "draytek-ap");
param.role = 1; // 0:AP, 1:infra-client, 2:ad-hoc
param.wpaCipher = 1; // 1:TKIP, 2:AES
param.wpa2Cipher = 0; // 1:TKIP, 2:AES
auth_main(&param);
}
#endif
#endif

View File

@ -0,0 +1,73 @@
#
# Makefile for WPA for the Linux OS
#
#
# $Id: Makefile,v 1.1.1.1 2007/08/06 10:04:42 root Exp $
#
WPA_ROOT_DIR = ../..
ARCH =
NAME = dlisten
###################
#CC = $(CROSS_COMPILE)gcc
#STRIP = $(CROSS_COMPILE)strip
#LD = $(CROSS_COMPILE)ld
#AR = $(CROSS_COMPILE)ar
###################
dlisten_SRCS = iwcontrol.c iwconfig.c iwcommon.c iwreq.c
dlisten_OBJS = ${dlisten_SRCS:.c=.o}
RTL_WPA_IFLAGS = -I${WPA_ROOT_DIR}/include \
-I${WPA_ROOT_DIR}/Package/Libnet-1.0.2a/include \
-I${WPA_ROOT_DIR}/Package/libpcap-0.7.2 \
-I${WPA_ROOT_DIR}/Package/openssl-0.9.7b/include \
-I$(TOP_USERS_DIR)/include
#RTL_WPA_LIBS = ${WPA_ROOT_DIR}/libnet.a \
# ${WPA_ROOT_DIR}/libpcap.a \
# ${WPA_ROOT_DIR}/libcrypto.a
RTL_WPA_DEFFLAGS += -DGLIBC22_HEADERS
RTL_WPA_CFLAG = -Wall -Os
#ifeq ($(CONFIG_RTL_92D_DMDP),y)
#RTL_WPA_CFLAG += -DFOR_DUAL_BAND
#endif
RTL_WPA_CFLAG += -DFOR_DUAL_BAND
ifeq ($(SLINK),1)
RTL_WPA_CFLAG += -ffunction-sections -fdata-sections
RTL_WPA_LDFLAG += --static -Wl,--gc-sections
endif
#
# Transition rules (add -o to put object in right directory)
#
.c.o:
$(CC) $(RTL_WPA_CFLAG) $(RTL_WPA_IFLAGS) $(RTL_WPA_DEFFLAGS) -c -o $*.o $<
###################
all: iwcontrol
iwcontrol: $(dlisten_OBJS)
$(CC) ${RTL_WPA_LDFLAG} -o iwcontrol $(dlisten_OBJS) $(RTL_WPA_LIBS)
$(STRIP) $(STRIPFLAGS) iwcontrol
cp -p ./iwcontrol ../../../bin/
##-------------------------------------------------
clean:
rm -f *.o; rm -f iwcontrol
romfs:
$(ROMFSINST) iwcontrol /bin/iwcontrol

View File

@ -0,0 +1,83 @@
#
# Basic and crude Makefile...
#
# Targets to build
#PROGS= iwcontrol # iwlist iwpriv iwspy iwgetid
# Installation directory. By default, go in local.
# Distributions should probably use /usr/sbin, but they probably know better...
INSTALL_DIR= /usr/local/sbin
# This is our header selection. Try to hide the mess and the misery :-(
# Please choose *only one* of the define...
# Kernel headers 2.4.X + Glibc 2.2 - Mandrake 8.0, Debian 2.3
HEADERS= -DGLIBC22_HEADERS
# Kernel headers 2.0.X + Glibc 2.0 - Debian 2.0, RH 5
# Kernel headers 2.2.X + Glibc 2.1 - Debian 2.2, RH 6.1
# Kernel headers 2.4.X + Glibc 2.1 - Debian 2.2 upgraded, RH 7.0
#HEADERS= -DGLIBC_HEADERS
# Kernel headers 2.2.X + Glibc 2.0 - Debian 2.1
#HEADERS= -DKLUDGE_HEADERS
# Kernel headers 2.0.X + libc5 - old systems
#HEADERS= -DLIBC5_HEADERS
# Use private copy of Wireless Extension definition instead of the
# system wide one in /usr/include/linux. Use with care.
# Can be used to create multiple versions of the tools on the same system
# for multiple kernels or get around broken distributions.
#WE_HEADER= -DPRIVATE_WE_HEADER
#WE_HEADER=
# ------------ End of config --------------
RM = rm -f
RM_CMD = $(RM) *.BAK *.bak *.o ,* *~ *.a iwcontrol
CFLAGS=-O2 -Wall $(HEADERS) $(WE_HEADER)
LIBS=-lm
DIR1X = ../..
INC = -I$(DIR1X)/include -I/usr/include/i386-glibc21-linux/
LIBM=/usr/lib/libm.a
#all:: $(PROGS)
target: iwcontrol.o iwconfig.o iwcommon.o iwreq.o
gcc $(CFLAGS) $(INC) $(LIBS) -o iwcontrol iwcontrol.o iwconfig.o iwcommon.o iwreq.o
iwconfig.o: iwcommon.h iwconfig.c
gcc -c iwconfig.c $(CFLAGS) $(INC) $(LIBS)
iwcommon.o: iwcommon.h wireless.h iwcommon.c
gcc -c iwcommon.c $(CFLAGS) $(INC) $(LIBS)
iwreq.o: iwcommon.h iwreq.c
gcc -c iwreq.c $(CFLAGS) $(INC) $(LIBS)
# So crude but so effective ;-)
install:
$(INSTALL) -d $(IMAGE_DIR)/sbin
$(INSTALL) iwcontrol $(IMAGE_DIR)/sbin
$(STRIP) $(STRIPFLAGS) $(IMAGE_DIR)/sbin/iwcontrol
clean::
$(RM_CMD)
realclean::
$(RM_CMD)
$(RM) $(PROGS)
depend::
makedepend -s "# DO NOT DELETE" -- $(INCLUDES) -- $(SRCS)
# DO NOT DELETE

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,957 @@
/*
* Wireless Tools
*
* Jean II - HPLB 97->99 - HPL 99->01
*
* Common header for the wireless tools...
*
* This file is released under the GPL license.
*/
#ifndef IWCOMMON_H
#define IWCOMMON_H
/************************** DOCUMENTATION **************************/
/*
* None ? Todo...
*/
/* --------------------------- HISTORY --------------------------- */
/*
* wireless 16 : (Jean Tourrilhes)
* -----------
* o iwconfig, iwpriv & iwspy
*
* wireless 17 : (Justin Seger)
* -----------
* o Compile under glibc fix
* o merge iwpriv in iwconfig
* o Add Wavelan roaming support
* o Update man page of iwconfig
*
* wireless 18 :
* -----------
* (From Andreas Neuhaus <andy@fasta.fh-dortmund.de>)
* o Many fix to remove "core dumps" in iwconfig
* o Remove useless headers in iwconfig
* o CHAR wide private ioctl
* (From Jean Tourrilhes)
* o Create iwcommon.h and iwcommon.c
* o Separate iwpriv again for user interface issues
* The folllowing didn't make sense and crashed :
* iwconfig eth0 priv sethisto 12 15 nwid 100
* o iwspy no longer depend on net-tools-1.2.0
* o Reorganisation of the code, cleanup
* o Add ESSID stuff in iwconfig
* o Add display of level & noise in dBm (stats in iwconfig)
* o Update man page of iwconfig and iwpriv
* o Add xwireless (didn't check if it compiles)
* (From Dean W. Gehnert <deang@tpi.com>)
* o Minor fixes
* (Jan Rafaj <rafaj@cedric.vabo.cz>)
* o Cosmetic changes (sensitivity relative, freq list)
* o Frequency computation on double
* o Compile clean on libc5
* (From Jean Tourrilhes)
* o Move listing of frequencies to iwspy
* o Add AP address stuff in iwconfig
* o Add AP list stuff in iwspy
*
* wireless 19 :
* -----------
* (From Jean Tourrilhes)
* o Allow for sensitivity in dBm (if < 0) [iwconfig]
* o Formatting changes in displaying ap address in [iwconfig]
* o Slightly improved man pages and usage display
* o Add channel number for each frequency in list [iwspy]
* o Add nickname... [iwconfig]
* o Add "port" private ioctl shortcut [iwpriv]
* o If signal level = 0, no range or dBms [iwconfig]
* o I think I now got set/get char strings right in [iwpriv]
* (From Thomas Ekstrom <tomeck@thelogic.com>)
* o Fix a very obscure bug in [iwspy]
*
* wireless 20 :
* -----------
* (From Jean Tourrilhes)
* o Remove all #ifdef WIRELESS ugliness, but add a #error :
* we require Wireless Extensions 9 or nothing ! [all]
* o Switch to new 'nwid' definition (specific -> iw_param) [iwconfig]
* o Rewriten totally the encryption support [iwconfig]
* - Multiple keys, through key index
* - Flexible/multiple key size, and remove 64bits upper limit
* - Open/Restricted modes
* - Enter keys as ASCII strings
* o List key sizes supported and all keys in [iwspy]
* o Mode of operation support (ad-hoc, managed...) [iwconfig]
* o Use '=' to indicate fixed instead of ugly '(f)' [iwconfig]
* o Ability to disable RTS & frag (off), now the right way [iwconfig]
* o Auto as an input modifier for bitrate [iwconfig]
* o Power Management support [iwconfig]
* - set timeout or period and its value
* - Reception mode (unicast/multicast/all)
* o Updated man pages with all that ;-)
*
* wireless 21 :
* -----------
* (from Alan McReynolds <alan_mcreynolds@hpl.hp.com>)
* o Use proper macros for compilation directives [Makefile]
* (From Jean Tourrilhes)
* o Put licensing info everywhere (almost). Yes, it's GPL !
* o Document the use of /etc/pcmcia/wireless.opts
* o Add min/max modifiers to power management parameters [iwconfig]
* -> requested by Lee Keyser-Allen for the Spectrum24 driver
* o Optionally output a second power management parameter [iwconfig]
* ---
* o Common subroutines to display stats & power saving info [iwcommon]
* o Display all power management info, capability and values [iwspy]
* ---
* o Optional index for ESSID (for Aironet driver) [iwcommon]
* o IW_ENCODE_NOKEY for write only keys [iwconfig/iwspy]
* o Common subrouting to print encoding keys [iwspy]
* ---
* o Transmit Power stuff (dBm + mW) [iwconfig/iwspy]
* o Cleaner formatting algorithm when displaying params [iwconfig]
* ---
* o Fix get_range_info() and use it everywhere - Should fix core dumps.
* o Catch WE version differences between tools and driver and
* warn user. Thanks to Tobias Ringstrom for the tip... [iwcommon]
* o Add Retry limit and lifetime support. [iwconfig/iwlist]
* o Display "Cell:" instead of "Access Point:" in ad-hoc mode [iwconfig]
* o Header fix for glibc2.2 by Ross G. Miller <Ross_Miller@baylor.edu>
* o Move header selection flags in Makefile [iwcommon/Makefile]
* o Spin-off iwlist.c from iwspy.c. iwspy is now much smaller
* After moving this bit of code all over the place, from iwpriv
* to iwconfig to iwspy, it now has a home of its own... [iwspy/iwlist]
* o Wrote quick'n'dirty iwgetid.
* o Remove output of second power management parameter [iwconfig]
* Please use iwlist, I don't want to bloat iwconfig
* ---
* o Fix bug in display ints - "Allen Miu" <aklmiu@mit.edu> [iwpriv]
*
* wireless 21 :
* -----------
* (From Jim Kaba <jkaba@sarnoff.com>)
* o Fix socket_open to not open all types of sockets [iwcommon]
* (From Michael Tokarev <mjt@tls.msk.ru>)
* o Rewrite main (top level) + command line parsing of [iwlist]
* (From Jean Tourrilhes)
* o Set commands should return proper success flag [iwspy/iwpriv]
* requested by Michael Tokarev
* ---
* (From Torgeir Hansen <torgeir@trenger.ro>)
* o Replace "strcpy(wrq.ifr_name," with strncpy to avoid buffer
* overflows. This is OK because the kernel use strncmp...
*
*/
/* ----------------------------- TODO ----------------------------- */
/*
* One day, maybe...
*
* iwconfig :
* --------
* Make disable a per encryption key modifier if some hardware
* requires it.
*
* iwpriv :
* ------
* Remove 'port' and 'roam' cruft now that we have mode in iwconfig
*
* iwspy :
* -----
* -
*
* Doc & man pages :
* ---------------
* Update main doc.
*
* Other :
* -----
* What about some graphical tools ?
*/
/***************************** INCLUDES *****************************/
/* Standard headers */
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h> /* gethostbyname, getnetbyname */
#include <stdarg.h>
/* This is our header selection. Try to hide the mess and the misery :-(
* The selection has been moved in the Makefile, here we have only
* the ugly part. Don't look, you would go blind ;-) */
#ifdef KLUDGE_HEADERS
#include <socketbits.h>
#endif /* KLUDGE_HEADERS */
#if defined(KLUDGE_HEADERS) || defined(GLIBC_HEADERS)
#include <linux/if_arp.h> /* For ARPHRD_ETHER */
#include <linux/socket.h> /* For AF_INET & struct sockaddr */
#include <linux/in.h> /* For struct sockaddr_in */
#endif /* KLUDGE_HEADERS || GLIBC_HEADERS */
#ifdef GLIBC22_HEADERS
/* Added by Ross G. Miller <Ross_Miller@baylor.edu>, 3/28/01 */
#include <linux/if_arp.h> /* For ARPHRD_ETHER */
#include <linux/socket.h> /* For AF_INET & struct sockaddr */
#include <sys/socket.h>
#endif /* GLIBC22_HEADERS */
#ifdef LIBC5_HEADERS
#include <sys/socket.h> /* For AF_INET & struct sockaddr & socket() */
#include <linux/if_arp.h> /* For ARPHRD_ETHER */
#include <linux/in.h> /* For struct sockaddr_in */
#endif /* LIBC5_HEADERS */
#ifdef PRIVATE_WE_HEADER
/* Private copy of Wireless extensions */
// marked by chilong
//#include "wireless.h"
// modified by chilong
#ifdef __ASUS_DVD__
#include "./wireless_asus_2421.h"
#else
#include <linux/wireless.h>
#endif
// modified by chilong
#else /* PRIVATE_WE_HEADER */
/* System wide Wireless extensions */
// marked by chilong
//#include <linux/wireless.h>
// modified by chilong
#ifdef __ASUS_DVD__
#include "./wireless_asus_2421.h"
#else
#include <linux/wireless.h>
#endif
// modified by chilong
#endif /* PRIVATE_WE_HEADER */
#if WIRELESS_EXT < 9
#error "Wireless Extension v9 or newer required :-( Use Wireless Tools v19 or update your kernel headers"
#endif
#if WIRELESS_EXT < 11
#warning "Wireless Extension v11 recommended... You may update your kernel and/or system headers to get the new features..."
#endif
/****************************** DEBUG ******************************/
/************************ CONSTANTS & MACROS ************************/
/* Some usefull constants */
#define KILO 1e3
#define MEGA 1e6
#define GIGA 1e9
/* Backward compatibility for Wireless Extension 9 */
#ifndef IW_POWER_MODIFIER
#define IW_POWER_MODIFIER 0x000F /* Modify a parameter */
#define IW_POWER_MIN 0x0001 /* Value is a minimum */
#define IW_POWER_MAX 0x0002 /* Value is a maximum */
#define IW_POWER_RELATIVE 0x0004 /* Value is not in seconds/ms/us */
#endif //IW_POWER_MODIFIER
#ifndef IW_ENCODE_NOKEY
#define IW_ENCODE_NOKEY 0x0800 /* Key is write only, so not here */
#define IW_ENCODE_MODE 0xF000 /* Modes defined below */
#endif //IW_ENCODE_NOKEY
/* Emily Added */
#define IW_CTLMSG_MAX_SIXE 1024 /* Data from driver, and will be passed to FIFO of 802.1x */
/****************************** TYPES ******************************/
/* Shortcuts */
typedef struct iw_statistics iwstats;
typedef struct iw_range iwrange;
typedef struct iw_param iwparam;
typedef struct iw_freq iwfreq;
typedef struct iw_quality iwqual;
typedef struct iw_priv_args iwprivargs;
typedef struct sockaddr sockaddr;
/* Structure for storing all wireless information for each device */
typedef struct wireless_info
{
char name[IFNAMSIZ]; /* Wireless/protocol name */
int has_nwid;
iwparam nwid; /* Network ID */
int has_freq;
float freq; /* Frequency/channel */
int has_sens;
iwparam sens; /* sensitivity */
int has_key;
unsigned char key[IW_ENCODING_TOKEN_MAX]; /* Encoding key used */
int key_size; /* Number of bytes */
int key_flags; /* Various flags */
int has_essid;
int essid_on;
char essid[IW_ESSID_MAX_SIZE + 1]; /* ESSID (extended network) */
int has_nickname;
char nickname[IW_ESSID_MAX_SIZE + 1]; /* NickName */
int has_ap_addr;
sockaddr ap_addr; /* Access point address */
int has_bitrate;
iwparam bitrate; /* Bit rate in bps */
int has_rts;
iwparam rts; /* RTS threshold in bytes */
int has_frag;
iwparam frag; /* Fragmentation threshold in bytes */
int has_mode;
int mode; /* Operation mode */
int has_power;
iwparam power; /* Power management parameters */
int has_txpower;
iwparam txpower; /* Transmit Power in dBm */
int has_retry;
iwparam retry; /* Retry limit or lifetime */
//Added by Emily
int has_mic_failure;
char ctl_msg[IW_CTLMSG_MAX_SIXE];
int ctl_msglen;
/* Stats */
iwstats stats;
int has_stats;
iwrange range;
int has_range;
} wireless_info;
typedef struct _Dot1x_RTLDListener
{
int WriteFIFO;
int Iffd;
char wlanName[16];
//char SendBuf[1600];
}Dot1x_RTLDListener;
/**************************** PROTOTYPES ****************************/
/*
* All the functions in iwcommon.c
*/
/* ---------------------- SOCKET SUBROUTINES -----------------------*/
int
sockets_open(void);
/* --------------------- WIRELESS SUBROUTINES ----------------------*/
int
get_range_info(int skfd,
char * ifname,
iwrange * range);
int
get_priv_info(int skfd,
char * ifname,
iwprivargs * priv);
/* -------------------- FREQUENCY SUBROUTINES --------------------- */
void
float2freq(double in,
iwfreq * out);
double
freq2float(iwfreq * in);
/* ---------------------- POWER SUBROUTINES ----------------------- */
int
dbm2mwatt(int in);
int
mwatt2dbm(int in);
/* -------------------- STATISTICS SUBROUTINES -------------------- */
void
print_stats(FILE * stream,
iwqual * qual,
iwrange * range,
int has_range);
/* --------------------- ENCODING SUBROUTINES --------------------- */
void
print_key(FILE * stream,
unsigned char * key,
int key_size,
int key_flags);
/* ----------------- POWER MANAGEMENT SUBROUTINES ----------------- */
void
print_pm_value(FILE * stream,
int value,
int flags);
void
print_pm_mode(FILE * stream,
int flags);
/* --------------- RETRY LIMIT/LIFETIME SUBROUTINES --------------- */
#if WIRELESS_EXT > 10
void
print_retry_value(FILE * stream,
int value,
int flags);
#endif
/* --------------------- ADDRESS SUBROUTINES ---------------------- */
int
check_addr_type(int skfd,
char * ifname);
char *
pr_ether(unsigned char *ptr);
int
in_ether(char *bufp, struct sockaddr *sap);
int
in_inet(char *bufp, struct sockaddr *sap);
int
in_addr(int skfd,
char * ifname,
char * bufp,
struct sockaddr *sap);
/* ----------------------- MISC SUBROUTINES ------------------------ */
int
byte_size(int args);
int
sockets_open(void);
void
print_info(int skfd,
char * ifname);
void
iw_message(int type,
char * msg, ... );
void
iw_ctldump(char *fun,
u_char *buf,
int size,
char *comment);
void
iw_hexdump(int type,
char *fun,
u_char *buf,
int size,
char *comment);
#define iw_L2N(l,c) (*((c) )=(unsigned char)(((l)>>24)&0xff),\
*((c)+1)=(unsigned char)(((l)>>16)&0xff),\
*((c)+2)=(unsigned char)(((l)>> 8)&0xff),\
*((c)+3)=(unsigned char)(((l) )&0xff))
#define iw_N2L(c,l) (l =((unsigned long)(*((c) )))<<24,\
l|=((unsigned long)(*((c)+1)))<<16, \
l|=((unsigned long)(*((c)+2)))<< 8, \
l|=((unsigned long)(*((c)+3))))
/********************** iwreq.c specific ***************************/
/* ------------- IOCTL STUFF FOR 802.1x DAEMON--------------------- */
#define SIOCGIWIND 0x89ff
#define SIOCSAPPPID 0x8b3e
int
RequestIndication(int skfd,
char * ifname,
char * out,
int * outlen);
int
InitialEventQueue(int skfd,
char * ifname,
struct wireless_info * info);
int
RegisterPID(int skfd,
char * ifname);
/********************** iwgetid.c specific *************************/
#define FORMAT_DEFAULT 0 /* Nice looking display for the user */
#define FORMAT_SCHEME 1 /* To be used as a Pcmcia Scheme */
int
print_nwid(int skfd,
char * ifname,
int format);
/********************** iwcommon.c specific *************************/
#define MESS_BUF_SIZE 512
//#define ALLOW_DBG_CONTROL 1
#define MESS_DBG_IWCONTROL 18 //2003-06-13
/**************************** VARIABLES ****************************/
#endif /* IWCOMMON_H */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,734 @@
#include <stdio.h>
#include <sys/time.h>
#include <signal.h>
#include <dirent.h>
#ifndef __ASUS_DVD__
#define RTL_WPA2_CLIENT
#define RTL_WPA2
#define AUTO_CONFIG
#define WIFI_SIMPLE_CONFIG
#endif
#include "iwcommon.h"
#include "../../include/1x_fifo.h"
#include "../../include/1x_ioctl.h"
#ifndef __ASUS_DVD__
#define INTERVAL 1
#define WLAN_CHR_MISC
//----------------------------------------------------------
// Local variables
//----------------------------------------------------------
static char *pidfile=(TOP_CONFIG_DIR "/run/iwcontrol.pid");
#define MAX_WLAN_INTF 10
#define READ_BUF_SIZE 50
static Dot1x_RTLDListener RTLDListenerAuth[MAX_WLAN_INTF];
static Dot1x_RTLDListener RTLDListenerIapp;
static char dlisten_SendBuf[RWFIFOSIZE];
static int link_auth = FALSE;
static int link_iapp = FALSE;
static int wlan_num = 0 ;
static char wlan_tbl[MAX_WLAN_INTF][20];
#ifdef AUTO_CONFIG
static int link_autoconf = FALSE;
static Dot1x_RTLDListener RTLDListenerAutoconf[MAX_WLAN_INTF];
#endif
#ifdef WIFI_SIMPLE_CONFIG
static int link_wscd = FALSE;
static Dot1x_RTLDListener RTLDListenerWscd[MAX_WLAN_INTF];
#endif
#ifdef WLAN_CHR_MISC
static int wl_chr_fd;
#endif
//----------------------------------------------------------
// Functions
//----------------------------------------------------------
int get_info()
{
int skfd = -1; /* generic raw socket desc */
/* Create a channel to the NET kernel */
if((skfd = sockets_open()) < 0)
{
perror("socket");
exit(-1);
}
return skfd;
}
/*
Initialize the SendBuf
_________________________________________________
| pid (4 bytes) | fifo type (1 byte) | data (*) |
-------------------------------------------------
*/
void iw_init_sendBuf(char *ptr)
{
pid_t pid;
pid = getpid();
iw_L2N((long)pid, ptr);
*(ptr + sizeof(long)) = FIFO_TYPE_DLISTEN;
}
void iw_init_fifo(Dot1x_RTLDListener *listen, char *fifo_name)
{
int init_retry = 0;
while(1){
if((listen->WriteFIFO = open(fifo_name, O_WRONLY, 0)) < 0)
{
if (init_retry > 6)
{
printf("iw_init_fifo: open fifo %s error\n", fifo_name);
break;
}
init_retry++;
//iw_message(MESS_DBG_CONTROL, "open fifo %s error: %s", fifo_name, strerror(errno));
iw_message(MESS_DBG_CONTROL, "wait %s to create", fifo_name);
sleep(1);
//exit(0);
}
else
break;
}
}
int ProcessRequestEvent(char *wlan_name)
{
int outlen = 0;
int retVal = 0;
char szEvent[64];
int iSend = FALSE; // iSend = 1 for test
int iRet = 0;
int i;
#ifdef AUTO_CONFIG
int isAutoconfEvt=0;
#endif
#ifdef WIFI_SIMPLE_CONFIG
int isWscdEvt = FALSE;
#endif
// Get message from wlan ioctl
if(RequestIndication(RTLDListenerAuth[0].Iffd, wlan_name, &dlisten_SendBuf[5], &outlen) < 0)
{
iw_message(MESS_DBG_CONTROL, "RequestIndication return Fail");
return 0;
}
// Process message
if(dlisten_SendBuf[5] != 0)
{
memset(szEvent, 0, sizeof szEvent);
switch(dlisten_SendBuf[5])
{
case DOT11_EVENT_ASSOCIATION_IND:
sprintf(szEvent, (char*)"Receive Event %s", "ASSOCIATION_IND");
iSend = TRUE;
break;
case DOT11_EVENT_REASSOCIATION_IND:
sprintf(szEvent, (char*)"Receive Event %s", "REASSOCIATION_IND");
iSend = TRUE;
break;
case DOT11_EVENT_AUTHENTICATION_IND:
sprintf(szEvent, (char*)"Receive Event %s", "AUTHENTICATION_IND");
iSend = TRUE;
break;
case DOT11_EVENT_REAUTHENTICATION_IND:
sprintf(szEvent, (char*)"Receive Event %s", "REAUTHENTICATION_IND");
iSend = TRUE;
break;
case DOT11_EVENT_DEAUTHENTICATION_IND:
sprintf(szEvent, (char*)"Receive Event %s", "DEAUTHENTICATION_IND");
iSend = TRUE;
break;
case DOT11_EVENT_DISASSOCIATION_IND:
sprintf(szEvent, (char*)"Receive Event %s", "DISASSOCIATION_IND");
iSend = TRUE;
break;
case DOT11_EVENT_MIC_FAILURE:
sprintf(szEvent, (char*)"Receive Event %s", "MIC_FAILURE");
iSend = TRUE;
break;
case DOT11_EVENT_EAPOLSTART:
sprintf(szEvent, (char*)"Receive Event %s", "EAPOL_START");
iSend = TRUE;
break;
case DOT11_EVENT_EAP_PACKET:
sprintf(szEvent, (char*)"Receive Event %s", "EAP_PACKET");
#ifdef WIFI_SIMPLE_CONFIG
isWscdEvt = TRUE;
#endif
iSend = TRUE;
break;
#ifdef RTL_WPA2
case DOT11_EVENT_EAPOLSTART_PREAUTH:
sprintf(szEvent, (char*)"Receive Event %s", "EAPOLSTART_PREAUTH");
iSend = TRUE;
break;
case DOT11_EVENT_EAP_PACKET_PREAUTH:
sprintf(szEvent, (char*)"Receive Event %s", "EAP_PACKET_PREAUTH");
iSend = TRUE;
break;
#endif
#ifdef RTL_WPA2_CLIENT
case DOT11_EVENT_WPA2_MULTICAST_CIPHER:
sprintf(szEvent, (char*)"Receive Event %s", "WPA2_MULTICAST_CIPHER");
iSend = TRUE;
break;
#endif
case DOT11_EVENT_WPA_MULTICAST_CIPHER:
sprintf(szEvent, (char*)"Receive Event %s", "WPA_MULTICAST_CIPHER");
iSend = TRUE;
break;
#ifdef AUTO_CONFIG
case DOT11_EVENT_AUTOCONF_ASSOCIATION_IND:
sprintf(szEvent, (char*)"Receive Event %s", "AUTOCONF_ASSOC_IND");
iSend = TRUE;
isAutoconfEvt = 1;
break;
case DOT11_EVENT_AUTOCONF_ASSOCIATION_CONFIRM:
sprintf(szEvent, (char*)"Receive Event %s", "AUTOCONF_ASSOC_CONFIRM");
iSend = TRUE;
isAutoconfEvt = 1;
break;
case DOT11_EVENT_AUTOCONF_PACKET:
sprintf(szEvent, (char*)"Receive Event %s", "AUTOCONF_PACKET");
iSend = TRUE;
isAutoconfEvt = 1;
break;
case DOT11_EVENT_AUTOCONF_LINK_IND:
sprintf(szEvent, (char*)"Receive Event %s", "AUTOCONF_LINK_IND");
iSend = TRUE;
isAutoconfEvt = 1;
break;
#endif
#ifdef WIFI_SIMPLE_CONFIG
case DOT11_EVENT_WSC_PIN_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_PIN_IND");
isWscdEvt = TRUE;
break;
/* WPS2DOTX ; support Assigned MAC Addr,Assigned SSID,dymanic change STA's PIN code, 2011-0505 */
case DOT11_EVENT_WSC_SET_MY_PIN:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_SET_MY_PIN");
isWscdEvt = TRUE;
break;
case DOT11_EVENT_WSC_SPEC_SSID:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_SPEC_SSID");
isWscdEvt = TRUE;
break;
case DOT11_EVENT_WSC_SPEC_MAC_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_SPEC_MAC");
isWscdEvt = TRUE;
break;
/* WPS2DOTX ; support Assigned MAC Addr,Assigned SSID,dymanic change STA's PIN code, 2011-0505 */
#ifdef CONFIG_IWPRIV_INTF
case DOT11_EVENT_WSC_START_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_START_IND");
isWscdEvt = TRUE;
break;
//EV_MODE, EV_STATUS, EV_MEHOD, EV_STEP, EV_OOB
case DOT11_EVENT_WSC_MODE_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_MODE_IND");
isWscdEvt = TRUE;
break;
case DOT11_EVENT_WSC_STATUS_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_STATUS_IND");
isWscdEvt = TRUE;
break;
case DOT11_EVENT_WSC_METHOD_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_METHOD_IND");
isWscdEvt = TRUE;
break;
case DOT11_EVENT_WSC_STEP_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_STEP_IND");
isWscdEvt = TRUE;
break;
case DOT11_EVENT_WSC_OOB_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_OOB_IND");
isWscdEvt = TRUE;
break;
#endif //ifdef CONFIG_IWPRIV_INTF
case DOT11_EVENT_WSC_PROBE_REQ_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_PROBE_REQ_IND");
isWscdEvt = TRUE;
break;
case DOT11_EVENT_WSC_ASSOC_REQ_IE_IND:
sprintf(szEvent, (char*)"Receive Event %s", "WSC_ASSOC_REQ_IE_IND");
isWscdEvt = TRUE;
break;
#endif
default:
sprintf(szEvent, (char*)"Receive Invalid or Unhandled Event %d",
dlisten_SendBuf[5]);
iSend = FALSE;
break;
}
iw_message(MESS_DBG_CONTROL, "[iwcontrol]: %s", szEvent);
if(iSend)
{
#ifdef AUTO_CONFIG
if (link_autoconf && isAutoconfEvt) {
for(i=0; i < link_autoconf; i++){
if(!strcmp(RTLDListenerAutoconf[i].wlanName,wlan_name)){
if((iRet = write(RTLDListenerAutoconf[i].WriteFIFO, dlisten_SendBuf, RWFIFOSIZE)) < 0)
iw_message(MESS_DBG_CONTROL, "Write FIFO: %s", strerror(errno));
else
iw_message(MESS_DBG_CONTROL, "Write %d bytes\n", iRet);
}
}
goto ret_process;
}
#endif
if(link_auth)
{
for(i=0; i < wlan_num; i++){
if(!strcmp(RTLDListenerAuth[i].wlanName,wlan_name)){
if((iRet = write(RTLDListenerAuth[i].WriteFIFO, dlisten_SendBuf, RWFIFOSIZE)) < 0)
iw_message(MESS_DBG_CONTROL, "Write FIFO: %s", strerror(errno));
else
iw_message(MESS_DBG_CONTROL, "Write %d bytes\n", iRet);
}
}
}
if(link_iapp)
{
if((iRet = write(RTLDListenerIapp.WriteFIFO, dlisten_SendBuf, RWFIFOSIZE)) < 0)
iw_message(MESS_DBG_CONTROL, "Write FIFO: %s", strerror(errno));
else
iw_message(MESS_DBG_CONTROL, "Write %d bytes\n", iRet);
}
#ifdef AUTO_CONFIG
ret_process:
#endif
retVal = (dlisten_SendBuf[6] == TRUE)? TRUE : FALSE; //If more event
}
#ifdef WIFI_SIMPLE_CONFIG
if (isWscdEvt)
{
if (link_wscd && isWscdEvt) {
for(i=0; i < link_wscd; i++){
if(!strcmp(RTLDListenerWscd[i].wlanName,wlan_name)){
if((iRet = write(RTLDListenerWscd[i].WriteFIFO, dlisten_SendBuf, RWFIFOSIZE)) < 0)
iw_message(MESS_DBG_CONTROL, "Write FIFO: %s", strerror(errno));
else
iw_message(MESS_DBG_CONTROL, "Write %d bytes\n", iRet);
}
}
}
retVal = (dlisten_SendBuf[6] == TRUE)? TRUE : FALSE; //If more event
}
#endif
}
return retVal;
}
void RequestEvent(int sig_no)
{
u_long ulMoreEvent;
int i ;
for(i=0 ;i < wlan_num; i ++){
do {
ulMoreEvent = ProcessRequestEvent(wlan_tbl[i]);
} while(ulMoreEvent);
}
}
// david ----------------------------------------
#ifdef __ANDROID__
#define F_LOCK LOCK_EX
#define F_ULOCK LOCK_UN
static int lockf(int fd, int cmd, off_t ignored_len) {
return flock(fd, cmd);
}
#endif
static int pidfile_acquire(char *pidfile)
{
int pid_fd;
if(pidfile == NULL)
return -1;
pid_fd = open(pidfile, O_CREAT | O_WRONLY, 0644);
if (pid_fd < 0)
{
printf("Unable to open pidfile %s\n", pidfile);
}
else
{
lockf(pid_fd, F_LOCK, 0);
}
return pid_fd;
}
static void pidfile_write_release(int pid_fd)
{
FILE *out;
if(pid_fd < 0)
return;
if((out = fdopen(pid_fd, "w")) != NULL)
{
fprintf(out, "%d\n", getpid());
fclose(out);
}
lockf(pid_fd, F_UNLCK, 0);
close(pid_fd);
}
//-----------------------------------------------
/* parsing var pid file for fifo create */
int parsing_var_pid(Dot1x_RTLDListener *auth, Dot1x_RTLDListener *autoconf, Dot1x_RTLDListener *wscd)
{
DIR *dir;
struct dirent *next;
int i;
char *ptr;
dir = opendir(TOP_CONFIG_DIR "/run");
if (!dir) {
printf("Cannot open %s", TOP_CONFIG_DIR "/run");
return 0;
}
while ((next = readdir(dir)) != NULL){
iw_message(MESS_DBG_CONTROL,"iwcontrol:" TOP_CONFIG_DIR "/run/%s\n", next->d_name);
if(!strncmp(next->d_name, "auth", strlen("auth"))){
if ((sscanf(next->d_name, "auth-%s.pid", auth[link_auth].wlanName) == 1)
&& (ptr = strstr(auth[link_auth].wlanName, ".pid"))) {
*ptr = 0;
link_auth++;
iw_message(MESS_DBG_CONTROL,"auth[%d].wlanName=%s\n", link_auth-1, auth[link_auth-1].wlanName);
}
}
if(!strncmp(next->d_name, "iapp", strlen("iapp"))){
link_iapp = TRUE;
iw_message(MESS_DBG_CONTROL,"link_iapp =true\n");
}
#ifdef AUTO_CONFIG
if(!strncmp(next->d_name, "autoconf", strlen("autoconf"))){
if ((sscanf(next->d_name, "autoconf-%s.pid", autoconf[link_autoconf].wlanName) == 1)
&& (ptr = strstr(autoconf[link_autoconf].wlanName, ".pid"))) {
*ptr = 0;
iw_message(MESS_DBG_CONTROL,"autoconf[%d].wlanName=%s\n", link_autoconf-1, autoconf[link_autoconf-1].wlanName);
}
}
#endif
#ifdef WIFI_SIMPLE_CONFIG
#if 1 //def FOR_DUAL_BAND
if(!strncmp(next->d_name, "wscd-", strlen("wscd-"))){
int idx;
if(!strncmp(next->d_name, "wscd-wlan0-wlan1.pid", strlen("wscd-wlan0-wlan1.pid")))
{
iw_message(MESS_DBG_CONTROL,"next->d_name=%s\n", next->d_name);
strcpy(wscd[0].wlanName,"wlan0");
strcpy(wscd[1].wlanName,"wlan1");
//printf("AP mode-->> \n\n");
link_wscd=2;
}
else
{
if ((sscanf(next->d_name, "wscd-%s.pid", wscd[link_wscd].wlanName) == 1)
&& (ptr = strstr(wscd[link_wscd].wlanName, ".pid"))) {
*ptr = 0;
link_wscd++;
iw_message(MESS_DBG_CONTROL,"wscd[%d].wlanName=%s\n", link_wscd-1, wscd[link_wscd-1].wlanName);
}
}
for(idx=0 ; idx<link_wscd ; idx++)
iw_message(MESS_DBG_CONTROL,"wscd[%d].wlanName=%s\n", idx, wscd[idx].wlanName);
}
#else
if(!strncmp(next->d_name, "wscd", strlen("wscd"))){
if ((sscanf(next->d_name, "wscd-%s.pid", wscd[link_wscd].wlanName) == 1)
&& (ptr = strstr(wscd[link_wscd].wlanName, ".pid"))) {
*ptr = 0;
link_wscd++;
iw_message(MESS_DBG_CONTROL,"wscd[%d].wlanName=%s\n", link_wscd-1, wscd[link_wscd-1].wlanName);
}
}
#endif
#endif
}
return 0;
}
#ifdef AUTO_CONFIG
#define AUTOCONFIG_FIFO (TOP_CONFIG_DIR "/autoconf-%s.fifo")
#endif
#ifdef WIFI_SIMPLE_CONFIG
#define WSCD_FIFO (TOP_CONFIG_DIR "/wscd-%s.fifo")
#endif
int main(int argc, char *argv[])
{
int i;
char *iapp_fifo = (TOP_CONFIG_DIR "/iapp.fifo");
char fifo_buf[30];
int poll = 0; //david
// destroy old process
{
FILE *fp;
char line[20];
pid_t pid;
if((fp = fopen(pidfile, "r")) != NULL)
{
fgets(line, sizeof(line), fp);
if(sscanf(line, "%d", &pid))
{
if(pid > 1)
kill(pid, SIGTERM);
}
fclose(fp);
}
}
setsid(); // david, requested from abocom
// depend on arguments to decide link fifo
//printf("argv=");
for(i=1; i<argc; i++)
{
//printf("%s",argv[i]);
if(!strncmp("wlan", argv[i], strlen("wlan"))){
if(wlan_num >= MAX_WLAN_INTF){
printf("Only %d Wlan interace is supported\n", MAX_WLAN_INTF);
return -1;
}
printf("Register to %s\n",argv[i]);
strcpy(wlan_tbl[wlan_num], argv[i]);
wlan_num++ ;
}
// david ------------------------------------------------------
else if(!strncmp("poll", argv[i], strlen("poll"))){
poll = 1;
}
//-------------------------------------------------------------
else
{
printf("Usage: %s [wlan0] [wlan1] ... \n", argv[0]);
return -1;
}
}
//printf("\n");
if(wlan_num == 0){
printf("At least one wlan interface should be binded\n");
return -1 ;
}
/* parsing /var/iapp.pid or /var/auth*.pid , /var/autoconf*.conf */
if(parsing_var_pid(RTLDListenerAuth, RTLDListenerAutoconf, RTLDListenerWscd) < 0){
printf("parsing pid failed\n");
return -1;
}
// david ------------------------------------------
// delete old fifo and create filo
{
int pid_fd;
pid_fd = pidfile_acquire(pidfile);
if(daemon(0,1) == -1)
{
printf("fork iwcontrol error!\n");
exit(1);
}
pidfile_write_release(pid_fd);
}
//---------------------------------------------------
// init send buffer pid header
iw_init_sendBuf(dlisten_SendBuf);
// init fifo and socket
if(link_auth){
for(i=0 ; i < link_auth; i++){
sprintf(fifo_buf, DAEMON_FIFO, RTLDListenerAuth[i].wlanName);
iw_message(MESS_DBG_CONTROL,"open auth fifo %s\n", fifo_buf);
iw_init_fifo(&RTLDListenerAuth[i], fifo_buf);
}
}
if(link_iapp){
iw_message(MESS_DBG_CONTROL,"open iapp fifo %s\n", iapp_fifo);
iw_init_fifo(&RTLDListenerIapp, iapp_fifo);
}
#ifdef AUTO_CONFIG
if(link_autoconf){
for(i=0 ; i < link_autoconf; i++){
sprintf(fifo_buf, AUTOCONFIG_FIFO, RTLDListenerAutoconf[i].wlanName);
iw_message(MESS_DBG_CONTROL,"open autoconfig fifo %s\n", fifo_buf);
iw_init_fifo(&RTLDListenerAutoconf[i], fifo_buf);
}
}
#endif
#ifdef WIFI_SIMPLE_CONFIG
if(link_wscd){
for(i=0 ; i < link_wscd; i++){
sprintf(fifo_buf, WSCD_FIFO, RTLDListenerWscd[i].wlanName);
iw_message(MESS_DBG_CONTROL,"open wscd fifo %s\n", fifo_buf);
iw_init_fifo(&RTLDListenerWscd[i], fifo_buf);
}
}
#endif
RTLDListenerAuth[0].Iffd = get_info();
if(RTLDListenerAuth[0].Iffd <= 0)
{
perror("Socket fd return 0");
exit(0);
}
// infinite loop
#ifdef WLAN_CHR_MISC
if (!poll) // david
{
int fdflags, idx=0, wlan0_up=0, wlan1_up=0;
char dev_name[20];
for(i=0; i<wlan_num; i++)
{
if (strncmp("wlan0", wlan_tbl[i], 5) == 0) {
if (wlan0_up)
continue;
else
wlan0_up = 1;
idx = 0;
}
if (strncmp("wlan1", wlan_tbl[i], 5) == 0) {
if (wlan1_up)
continue;
else
wlan1_up = 1;
idx = 1;
}
sprintf(dev_name, "/dev/wl_chr%d", idx);
if((wl_chr_fd = open(dev_name, O_RDWR, 0)) < 0)
{
int retval;
if (idx == 0){
retval = RegisterPID(RTLDListenerAuth[0].Iffd, "wlan0");
printf("iwcontrol RegisterPID to (wlan0)\n");
}else{
retval = RegisterPID(RTLDListenerAuth[0].Iffd, "wlan1");
printf("iwcontrol RegisterPID to (wlan1)\n");
}
if (retval > 0)
signal(SIGIO, RequestEvent);
else
{
printf("Warning: unable to open an wl_chr device and PID registration fail.(wlan%d)(%d %s)\n",idx,__LINE__ , __FUNCTION__);
//exit(1);
}
}
else
{
signal(SIGIO, RequestEvent);
fcntl(wl_chr_fd, F_SETOWN, getpid());
fdflags = fcntl(wl_chr_fd, F_GETFL);
fcntl(wl_chr_fd, F_SETFL, fdflags | FASYNC);
}
}
while(1)
pause();
}
#endif
while( 1 )
{
RequestEvent(SIGIO);
sleep(INTERVAL);
}
return 0;
}
#else
//#include "1x_common.h"
//#include "wireless.h"
#define MAXDATALEN 1560 // jimmylin: org:256, enlarge for pass EAP packet by event queue
int read_wlan_evt( int skfd, char *ifname, char *out)
{
struct iwreq wrq;
DOT11_REQUEST *req;
/* Get wireless name */
memset(wrq.ifr_name, 0, sizeof wrq.ifr_name);
strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
req = (DOT11_REQUEST *)malloc(MAXDATALEN);
wrq.u.data.pointer = (caddr_t)req;
req->EventId = DOT11_EVENT_REQUEST;
wrq.u.data.length = sizeof(DOT11_REQUEST);
if (ioctl(skfd, SIOCGIWIND, &wrq) < 0) {
// If no wireless name : no wireless extensions
free(req);
strerror(errno);
return(-1);
}
else
memcpy(&out[5], wrq.u.data.pointer, wrq.u.data.length);
free(req);
if (out[5] != 0) {
out[4] = FIFO_TYPE_DLISTEN;
return wrq.u.data.length+5;;
}
return 0;
}
#endif

View File

@ -0,0 +1,547 @@
/*
* Wireless Tools
*
* Jean II - HPLB 97->99 - HPL 99->00
*
* Main code for "iwconfig". This is the generic tool for most
* manipulations...
* You need to link this code against "iwcommon.c" and "-lm".
*
* This file is released under the GPL license.
*/
#include "iwcommon.h" /* Header */
/************************* MISC SUBROUTINES **************************/
/*------------------------------------------------------------------*/
/*
* Print usage string
*/
static void
iw_usage(void)
{
fprintf(stderr, "Usage: iwpriv interface [private-command [private-arguments]]\n");
fprintf(stderr, " interface [roam {on|off}]\n");
fprintf(stderr, " interface [port {ad-hoc|managed|N}]\n");
}
/************************ GENERIC FUNCTIONS *************************/
/*------------------------------------------------------------------*/
/*
* Print on the screen in a neat fashion all the info we have collected
* on a device.
*/
static void
print_priv_info(int skfd,
char * ifname)
{
int k;
iwprivargs priv[16];
int n;
char * argtype[] = { " ", "byte", "char", "", "int ", "float" };
/* Read the private ioctls */
n = get_priv_info(skfd, ifname, priv);
/* Is there any ? */
if(n <= 0)
{
/* Could skip this message ? */
fprintf(stderr, "%-8.8s no private ioctls.\n\n",
ifname);
}
else
{
printf("%-8.8s Available private ioctl :\n", ifname);
/* Print the all */
for(k = 0; k < n; k++)
printf(" %s (%X) : set %3d %s & get %3d %s\n",
priv[k].name, priv[k].cmd,
priv[k].set_args & IW_PRIV_SIZE_MASK,
argtype[(priv[k].set_args & IW_PRIV_TYPE_MASK) >> 12],
priv[k].get_args & IW_PRIV_SIZE_MASK,
argtype[(priv[k].get_args & IW_PRIV_TYPE_MASK) >> 12]);
printf("\n");
}
}
/*------------------------------------------------------------------*/
/*
* Get info on all devices and print it on the screen
*/
static void
print_priv_devices(int skfd)
{
char buff[1024];
struct ifconf ifc;
struct ifreq *ifr;
int i;
/* Get list of active devices */
ifc.ifc_len = sizeof(buff);
ifc.ifc_buf = buff;
if(ioctl(skfd, SIOCGIFCONF, &ifc) < 0)
{
fprintf(stderr, "SIOCGIFCONF: %s\n", strerror(errno));
return;
}
ifr = ifc.ifc_req;
/* Print them */
for(i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; ifr++)
print_priv_info(skfd, ifr->ifr_name);
}
/************************* SETTING ROUTINES **************************/
/*------------------------------------------------------------------*/
/*
* Execute a private command on the interface
*/
static int
set_private(int skfd, /* Socket */
char * args[], /* Command line args */
int count, /* Args count */
char * ifname) /* Dev name */
{
u_char buffer[1024];
struct iwreq wrq;
int i = 0; /* Start with first arg */
int k;
iwprivargs priv[16];
int number;
/* Read the private ioctls */
number = get_priv_info(skfd, ifname, priv);
/* Is there any ? */
if(number <= 0)
{
/* Could skip this message ? */
fprintf(stderr, "%-8.8s no private ioctls.\n\n",
ifname);
return(-1);
}
/* Search the correct ioctl */
k = -1;
while((++k < number) && strcmp(priv[k].name, args[i]));
/* If not found... */
if(k == number)
{
fprintf(stderr, "Invalid command : %s\n", args[i]);
return(-1);
}
/* Next arg */
i++;
/* If we have to set some data */
if((priv[k].set_args & IW_PRIV_TYPE_MASK) &&
(priv[k].set_args & IW_PRIV_SIZE_MASK))
{
switch(priv[k].set_args & IW_PRIV_TYPE_MASK)
{
case IW_PRIV_TYPE_BYTE:
/* Number of args to fetch */
wrq.u.data.length = count - 1;
if(wrq.u.data.length > (priv[k].set_args & IW_PRIV_SIZE_MASK))
wrq.u.data.length = priv[k].set_args & IW_PRIV_SIZE_MASK;
/* Fetch args */
for(; i < wrq.u.data.length + 1; i++)
sscanf(args[i], "%d", (int *)(buffer + i - 1));
break;
case IW_PRIV_TYPE_INT:
/* Number of args to fetch */
wrq.u.data.length = count - 1;
if(wrq.u.data.length > (priv[k].set_args & IW_PRIV_SIZE_MASK))
wrq.u.data.length = priv[k].set_args & IW_PRIV_SIZE_MASK;
/* Fetch args */
for(; i < wrq.u.data.length + 1; i++)
sscanf(args[i], "%d", ((u_int *) buffer) + i - 1);
break;
case IW_PRIV_TYPE_CHAR:
if(i < count)
{
/* Size of the string to fetch */
wrq.u.data.length = strlen(args[i]) + 1;
if(wrq.u.data.length > (priv[k].set_args & IW_PRIV_SIZE_MASK))
wrq.u.data.length = priv[k].set_args & IW_PRIV_SIZE_MASK;
/* Fetch string */
memcpy(buffer, args[i], wrq.u.data.length);
buffer[sizeof(buffer) - 1] = '\0';
i++;
}
else
{
wrq.u.data.length = 1;
buffer[0] = '\0';
}
break;
default:
fprintf(stderr, "Not yet implemented...\n");
return(-1);
}
if((priv[k].set_args & IW_PRIV_SIZE_FIXED) &&
(wrq.u.data.length != (priv[k].set_args & IW_PRIV_SIZE_MASK)))
{
printf("The command %s need exactly %d argument...\n",
priv[k].name, priv[k].set_args & IW_PRIV_SIZE_MASK);
return(-1);
}
} /* if args to set */
else
{
wrq.u.data.length = 0L;
}
strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
if((priv[k].set_args & IW_PRIV_SIZE_FIXED) &&
(byte_size(priv[k].set_args) < IFNAMSIZ))
memcpy(wrq.u.name, buffer, IFNAMSIZ);
else
{
wrq.u.data.pointer = (caddr_t) buffer;
wrq.u.data.flags = 0;
}
/* Perform the private ioctl */
if(ioctl(skfd, priv[k].cmd, &wrq) < 0)
{
fprintf(stderr, "Interface doesn't accept private ioctl...\n");
fprintf(stderr, "%X: %s\n", priv[k].cmd, strerror(errno));
return(-1);
}
/* If we have to get some data */
if((priv[k].get_args & IW_PRIV_TYPE_MASK) &&
(priv[k].get_args & IW_PRIV_SIZE_MASK))
{
int j;
int n = 0; /* number of args */
printf("%-8.8s %s:", ifname, priv[k].name);
if((priv[k].get_args & IW_PRIV_SIZE_FIXED) &&
(byte_size(priv[k].get_args) < IFNAMSIZ))
{
memcpy(buffer, wrq.u.name, IFNAMSIZ);
n = priv[k].get_args & IW_PRIV_SIZE_MASK;
}
else
n = wrq.u.data.length;
switch(priv[k].get_args & IW_PRIV_TYPE_MASK)
{
case IW_PRIV_TYPE_BYTE:
/* Display args */
for(j = 0; j < n; j++)
printf("%d ", buffer[j]);
printf("\n");
break;
case IW_PRIV_TYPE_INT:
/* Display args */
for(j = 0; j < n; j++)
printf("%d ", ((u_int *) buffer)[j]);
printf("\n");
break;
case IW_PRIV_TYPE_CHAR:
/* Display args */
buffer[wrq.u.data.length - 1] = '\0';
printf("%s\n", buffer);
break;
default:
fprintf(stderr, "Not yet implemented...\n");
return(-1);
}
} /* if args to set */
return(0);
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,125 @@
#include "iwcommon.h"
#include "1x_ioctl.h"
#include <string.h>
#ifdef __ANDROID__
#include <err.h>
#else
#include <error.h>
#endif
#define Dot1XDataLen(payloadlen) sizeof(DOT1X_EVENT) + sizeof (unsigned short) + payloadlen
#define MAXDATALEN 1560 // jimmylin: org:256, enlarge for pass EAP packet by event queue
/*------------------------------------------------------------------*/
/*
* Request indication from driver with ioctl. If there is no ,
* indication from driver, the function blocks.
*/
int RequestIndication(
int skfd,
char * ifname,
char * out,
int * outlen)
{
struct iwreq wrq;
DOT11_REQUEST * req;
/* Get wireless name */
memset(wrq.ifr_name, 0, sizeof wrq.ifr_name);
strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
req = (DOT11_REQUEST *)malloc(MAXDATALEN);
wrq.u.data.pointer = (caddr_t)req;
req->EventId = DOT11_EVENT_REQUEST;
wrq.u.data.length = sizeof(DOT11_REQUEST);
//iw_message(MESS_DBG_IWCONTROL, "[RequestIndication] : Start\n");
//printf("\n[RequestIndication] : Start\n");
if(ioctl(skfd, SIOCGIWIND, &wrq) < 0)
{
// If no wireless name : no wireless extensions
free(req);
strerror(errno);
return(-1);
}
else{
//iw_message(MESS_DBG_IWCONTROL, "[RequestIndication]"," : Return\n");
//iw_ctldump("RequestIndication", wrq.u.data.pointer, wrq.u.data.length, "receive message from driver");
memcpy(out, wrq.u.data.pointer, wrq.u.data.length);
*outlen = wrq.u.data.length;
//write(1, "RequestIndication<1>\n", sizeof("RequestIndication<1>\n"));
}
free(req);
return 1;
}
/*
int InitialEventQueue(
int skfd,
char * ifname,
struct wireless_info * info)
{
struct iwreq wrq;
DOT11_RESET_QUEUE * ResetQueue;
int i;
memset((char *) info, 0, sizeof(struct wireless_info));
//Get wireless name
strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
ResetQueue = (DOT11_RESET_QUEUE *)malloc(sizeof(DOT11_RESET_QUEUE));
wrq.u.data.pointer = (caddr_t)ResetQueue;
ResetQueue->EventId = DOT11_EVENT_RESET_QUEUE;
wrq.u.data.length = sizeof(DOT11_RESET_QUEUE);
iw_message(MESS_DBG_IWCONTROL, "[InitialEventQueue] : Start\n");
write(1, "[InitialEventQueue] : Start\n", sizoef("[InitialEventQueue] : Start\n"));
printf("\n[InitialEvenetQueue] : Start\n");
if(ioctl(skfd, SIOCGIWIND, &wrq) < 0)
// If no wireless name : no wireless extensions
return(-1);
else{
iw_message(MESS_DBG_IWCONTROL, "[InitialEventQueue] : Return\n");
for(i=0; i<wrq.u.data.length;i++)
printf("%x ", wrq.u.data.pointer[i]);
}
return 1;
}
*/
int RegisterPID(
int skfd,
char * ifname)
{
struct iwreq wrq;
pid_t pid;
/* Get wireless name */
memset(wrq.ifr_name, 0, sizeof wrq.ifr_name);
strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
pid = getpid();
wrq.u.data.pointer = (caddr_t)&pid;
wrq.u.data.length = sizeof(pid_t);
if(ioctl(skfd, SIOCSAPPPID, &wrq) < 0)
{
// If no wireless name : no wireless extensions
printf("<<<<<RegisterPID error>>>>\n");
perror("RegisterPID error");
strerror(errno);
return(-1);
}
return 1;
}

View File

@ -0,0 +1,521 @@
/*
* This file define a set of standard wireless extensions
*
* Version : 11 28.3.01
*
* Authors : Jean Tourrilhes - HPL - <jt@hpl.hp.com>
*/
#ifndef _LINUX_WIRELESS_H
#define _LINUX_WIRELESS_H
/************************** DOCUMENTATION **************************/
/*
* Basically, the wireless extensions are for now a set of standard ioctl
* call + /proc/net/wireless
*
* The entry /proc/net/wireless give statistics and information on the
* driver.
* This is better than having each driver having its entry because
* its centralised and we may remove the driver module safely.
*
* Ioctl are used to configure the driver and issue commands. This is
* better than command line options of insmod because we may want to
* change dynamically (while the driver is running) some parameters.
*
* The ioctl mechanimsm are copied from standard devices ioctl.
* We have the list of command plus a structure descibing the
* data exchanged...
* Note that to add these ioctl, I was obliged to modify :
* net/core/dev.c (two place + add include)
* net/ipv4/af_inet.c (one place + add include)
*
* /proc/net/wireless is a copy of /proc/net/dev.
* We have a structure for data passed from the driver to /proc/net/wireless
* Too add this, I've modified :
* net/core/dev.c (two other places)
* include/linux/netdevice.h (one place)
* include/linux/proc_fs.h (one place)
*
* Do not add here things that are redundant with other mechanisms
* (drivers init, ifconfig, /proc/net/dev, ...) and with are not
* wireless specific.
*
* These wireless extensions are not magic : each driver has to provide
* support for them...
*
* IMPORTANT NOTE : As everything in the kernel, this is very much a
* work in progress. Contact me if you have ideas of improvements...
*/
/***************************** INCLUDES *****************************/
#include <linux/types.h> /* for "caddr_t" et al */
#include <linux/socket.h> /* for "struct sockaddr" et al */
#include <linux/if.h> /* for IFNAMSIZ and co... */
/**************************** CONSTANTS ****************************/
/* --------------------------- VERSION --------------------------- */
/*
* This constant is used to know the availability of the wireless
* extensions and to know which version of wireless extensions it is
* (there is some stuff that will be added in the future...)
* I just plan to increment with each new version.
*/
#define WIRELESS_EXT 11
/*
* Changes :
*
* V2 to V3
* --------
* Alan Cox start some incompatibles changes. I've integrated a bit more.
* - Encryption renamed to Encode to avoid US regulation problems
* - Frequency changed from float to struct to avoid problems on old 386
*
* V3 to V4
* --------
* - Add sensitivity
*
* V4 to V5
* --------
* - Missing encoding definitions in range
* - Access points stuff
*
* V5 to V6
* --------
* - 802.11 support (ESSID ioctls)
*
* V6 to V7
* --------
* - define IW_ESSID_MAX_SIZE and IW_MAX_AP
*
* V7 to V8
* --------
* - Changed my e-mail address
* - More 802.11 support (nickname, rate, rts, frag)
* - List index in frequencies
*
* V8 to V9
* --------
* - Support for 'mode of operation' (ad-hoc, managed...)
* - Support for unicast and multicast power saving
* - Change encoding to support larger tokens (>64 bits)
* - Updated iw_params (disable, flags) and use it for NWID
* - Extracted iw_point from iwreq for clarity
*
* V9 to V10
* ---------
* - Add PM capability to range structure
* - Add PM modifier : MAX/MIN/RELATIVE
* - Add encoding option : IW_ENCODE_NOKEY
* - Add TxPower ioctls (work like TxRate)
*
* V10 to V11
* ----------
* - Add WE version in range (help backward/forward compatibility)
* - Add retry ioctls (work like PM)
*/
/* -------------------------- IOCTL LIST -------------------------- */
/* Basic operations */
#define SIOCSIWNAME 0x8B00 /* Unused */
#define SIOCGIWNAME 0x8B01 /* get name == wireless protocol */
#define SIOCSIWNWID 0x8B02 /* set network id (the cell) */
#define SIOCGIWNWID 0x8B03 /* get network id */
#define SIOCSIWFREQ 0x8B04 /* set channel/frequency (Hz) */
#define SIOCGIWFREQ 0x8B05 /* get channel/frequency (Hz) */
#define SIOCSIWMODE 0x8B06 /* set operation mode */
#define SIOCGIWMODE 0x8B07 /* get operation mode */
#define SIOCSIWSENS 0x8B08 /* set sensitivity (dBm) */
#define SIOCGIWSENS 0x8B09 /* get sensitivity (dBm) */
/* Informative stuff */
#define SIOCSIWRANGE 0x8B0A /* Unused */
#define SIOCGIWRANGE 0x8B0B /* Get range of parameters */
#define SIOCSIWPRIV 0x8B0C /* Unused */
#define SIOCGIWPRIV 0x8B0D /* get private ioctl interface info */
/* Mobile IP support */
#define SIOCSIWSPY 0x8B10 /* set spy addresses */
#define SIOCGIWSPY 0x8B11 /* get spy info (quality of link) */
/* Access Point manipulation */
#define SIOCSIWAP 0x8B14 /* set access point MAC addresses */
#define SIOCGIWAP 0x8B15 /* get access point MAC addresses */
#define SIOCGIWAPLIST 0x8B17 /* get list of access point in range */
/* 802.11 specific support */
#define SIOCSIWESSID 0x8B1A /* set ESSID (network name) */
#define SIOCGIWESSID 0x8B1B /* get ESSID */
#define SIOCSIWNICKN 0x8B1C /* set node name/nickname */
#define SIOCGIWNICKN 0x8B1D /* get node name/nickname */
/* As the ESSID and NICKN are strings up to 32 bytes long, it doesn't fit
* within the 'iwreq' structure, so we need to use the 'data' member to
* point to a string in user space, like it is done for RANGE...
* The "flags" member indicate if the ESSID is active or not (promiscuous).
*/
/* Other parameters usefull in 802.11 and some other devices */
#define SIOCSIWRATE 0x8B20 /* set default bit rate (bps) */
#define SIOCGIWRATE 0x8B21 /* get default bit rate (bps) */
#define SIOCSIWRTS 0x8B22 /* set RTS/CTS threshold (bytes) */
#define SIOCGIWRTS 0x8B23 /* get RTS/CTS threshold (bytes) */
#define SIOCSIWFRAG 0x8B24 /* set fragmentation thr (bytes) */
#define SIOCGIWFRAG 0x8B25 /* get fragmentation thr (bytes) */
#define SIOCSIWTXPOW 0x8B26 /* set transmit power (dBm) */
#define SIOCGIWTXPOW 0x8B27 /* get transmit power (dBm) */
#define SIOCSIWRETRY 0x8B28 /* set retry limits and lifetime */
#define SIOCGIWRETRY 0x8B29 /* get retry limits and lifetime */
/* Encoding stuff (scrambling, hardware security, WEP...) */
#define SIOCSIWENCODE 0x8B2A /* set encoding token & mode */
#define SIOCGIWENCODE 0x8B2B /* get encoding token & mode */
/* Power saving stuff (power management, unicast and multicast) */
#define SIOCSIWPOWER 0x8B2C /* set Power Management settings */
#define SIOCGIWPOWER 0x8B2D /* get Power Management settings */
/* ------------------------- IOCTL STUFF ------------------------- */
/* The first and the last (range) */
#define SIOCIWFIRST 0x8B00
#define SIOCIWLAST 0x8B30
/* ------------- IOCTL STUFF FOR 802.1x DAEMON--------------------- */
#define SIOCGIWIND 0x89fc
/* Even : get (world access), odd : set (root access) */
#define IW_IS_SET(cmd) (!((cmd) & 0x1))
#define IW_IS_GET(cmd) ((cmd) & 0x1)
/* ------------------------- PRIVATE INFO ------------------------- */
/*
* The following is used with SIOCGIWPRIV. It allow a driver to define
* the interface (name, type of data) for its private ioctl.
* Privates ioctl are SIOCDEVPRIVATE -> SIOCDEVPRIVATE + 0xF
*/
#define IW_PRIV_TYPE_MASK 0x7000 /* Type of arguments */
#define IW_PRIV_TYPE_NONE 0x0000
#define IW_PRIV_TYPE_BYTE 0x1000 /* Char as number */
#define IW_PRIV_TYPE_CHAR 0x2000 /* Char as character */
#define IW_PRIV_TYPE_INT 0x4000 /* 32 bits int */
#define IW_PRIV_TYPE_FLOAT 0x5000
#define IW_PRIV_SIZE_FIXED 0x0800 /* Variable or fixed nuber of args */
#define IW_PRIV_SIZE_MASK 0x07FF /* Max number of those args */
/*
* Note : if the number of args is fixed and the size < 16 octets,
* instead of passing a pointer we will put args in the iwreq struct...
*/
/* ----------------------- OTHER CONSTANTS ----------------------- */
/* Maximum frequencies in the range struct */
#define IW_MAX_FREQUENCIES 16
/* Note : if you have something like 80 frequencies,
* don't increase this constant and don't fill the frequency list.
* The user will be able to set by channel anyway... */
/* Maximum bit rates in the range struct */
#define IW_MAX_BITRATES 8
/* Maximum tx powers in the range struct */
#define IW_MAX_TXPOWER 8
/* Maximum of address that you may set with SPY */
#define IW_MAX_SPY 8
/* Maximum of address that you may get in the
list of access points in range */
#define IW_MAX_AP 8
/* Maximum size of the ESSID and NICKN strings */
#define IW_ESSID_MAX_SIZE 32
/* Modes of operation */
#define IW_MODE_AUTO 0 /* Let the driver decides */
#define IW_MODE_ADHOC 1 /* Single cell network */
#define IW_MODE_INFRA 2 /* Multi cell network, roaming, ... */
#define IW_MODE_MASTER 3 /* Synchronisation master or Access Point */
#define IW_MODE_REPEAT 4 /* Wireless Repeater (forwarder) */
#define IW_MODE_SECOND 5 /* Secondary master/repeater (backup) */
/* Maximum number of size of encoding token available
* they are listed in the range structure */
#define IW_MAX_ENCODING_SIZES 8
/* Maximum size of the encoding token in bytes */
#define IW_ENCODING_TOKEN_MAX 32 /* 256 bits (for now) */

View File

@ -0,0 +1,698 @@
/*
* This file define a set of standard wireless extensions
*
* Version : 15 12.7.02
*
* Authors : Jean Tourrilhes - HPL - <jt@hpl.hp.com>
* Copyright (c) 1997-2002 Jean Tourrilhes, All Rights Reserved.
*/
#ifndef _LINUX_WIRELESS_H
#define _LINUX_WIRELESS_H
/************************** DOCUMENTATION **************************/
/*
* Initial APIs (1996 -> onward) :
* -----------------------------
* Basically, the wireless extensions are for now a set of standard ioctl
* call + /proc/net/wireless
*
* The entry /proc/net/wireless give statistics and information on the
* driver.
* This is better than having each driver having its entry because
* its centralised and we may remove the driver module safely.
*
* Ioctl are used to configure the driver and issue commands. This is
* better than command line options of insmod because we may want to
* change dynamically (while the driver is running) some parameters.
*
* The ioctl mechanimsm are copied from standard devices ioctl.
* We have the list of command plus a structure descibing the
* data exchanged...
* Note that to add these ioctl, I was obliged to modify :
* # net/core/dev.c (two place + add include)
* # net/ipv4/af_inet.c (one place + add include)
*
* /proc/net/wireless is a copy of /proc/net/dev.
* We have a structure for data passed from the driver to /proc/net/wireless
* Too add this, I've modified :
* # net/core/dev.c (two other places)
* # include/linux/netdevice.h (one place)
* # include/linux/proc_fs.h (one place)
*
* New driver API (2002 -> onward) :
* -------------------------------
* This file is only concerned with the user space API and common definitions.
* The new driver API is defined and documented in :
* # include/net/iw_handler.h
*
* Note as well that /proc/net/wireless implementation has now moved in :
* # include/linux/wireless.c
*
* Wireless Events (2002 -> onward) :
* --------------------------------
* Events are defined at the end of this file, and implemented in :
* # include/linux/wireless.c
*
* Other comments :
* --------------
* Do not add here things that are redundant with other mechanisms
* (drivers init, ifconfig, /proc/net/dev, ...) and with are not
* wireless specific.
*
* These wireless extensions are not magic : each driver has to provide
* support for them...
*
* IMPORTANT NOTE : As everything in the kernel, this is very much a
* work in progress. Contact me if you have ideas of improvements...
*/
/***************************** INCLUDES *****************************/
#include <linux/types.h> /* for "caddr_t" et al */
#include <linux/socket.h> /* for "struct sockaddr" et al */
#include <linux/if.h> /* for IFNAMSIZ and co... */
/***************************** VERSION *****************************/
/*
* This constant is used to know the availability of the wireless
* extensions and to know which version of wireless extensions it is
* (there is some stuff that will be added in the future...)
* I just plan to increment with each new version.
*/
#define WIRELESS_EXT 15
/*
* Changes :
*
* V2 to V3
* --------
* Alan Cox start some incompatibles changes. I've integrated a bit more.
* - Encryption renamed to Encode to avoid US regulation problems
* - Frequency changed from float to struct to avoid problems on old 386
*
* V3 to V4
* --------
* - Add sensitivity
*
* V4 to V5
* --------
* - Missing encoding definitions in range
* - Access points stuff
*
* V5 to V6
* --------
* - 802.11 support (ESSID ioctls)
*
* V6 to V7
* --------
* - define IW_ESSID_MAX_SIZE and IW_MAX_AP
*
* V7 to V8
* --------
* - Changed my e-mail address
* - More 802.11 support (nickname, rate, rts, frag)
* - List index in frequencies
*
* V8 to V9
* --------
* - Support for 'mode of operation' (ad-hoc, managed...)
* - Support for unicast and multicast power saving
* - Change encoding to support larger tokens (>64 bits)
* - Updated iw_params (disable, flags) and use it for NWID
* - Extracted iw_point from iwreq for clarity
*
* V9 to V10
* ---------
* - Add PM capability to range structure
* - Add PM modifier : MAX/MIN/RELATIVE
* - Add encoding option : IW_ENCODE_NOKEY
* - Add TxPower ioctls (work like TxRate)
*
* V10 to V11
* ----------
* - Add WE version in range (help backward/forward compatibility)
* - Add retry ioctls (work like PM)
*
* V11 to V12
* ----------
* - Add SIOCSIWSTATS to get /proc/net/wireless programatically
* - Add DEV PRIVATE IOCTL to avoid collisions in SIOCDEVPRIVATE space
* - Add new statistics (frag, retry, beacon)
* - Add average quality (for user space calibration)
*
* V12 to V13
* ----------
* - Document creation of new driver API.
* - Extract union iwreq_data from struct iwreq (for new driver API).
* - Rename SIOCSIWNAME as SIOCSIWCOMMIT
*
* V13 to V14
* ----------
* - Wireless Events support : define struct iw_event
* - Define additional specific event numbers
* - Add "addr" and "param" fields in union iwreq_data
* - AP scanning stuff (SIOCSIWSCAN and friends)
*
* V14 to V15
* ----------
* - Add IW_PRIV_TYPE_ADDR for struct sockaddr private arg
* - Make struct iw_freq signed (both m & e), add explicit padding
* - Add IWEVCUSTOM for driver specific event/scanning token
* - Add IW_MAX_GET_SPY for driver returning a lot of addresses
* - Add IW_TXPOW_RANGE for range of Tx Powers
* - Add IWEVREGISTERED & IWEVEXPIRED events for Access Points
* - Add IW_MODE_MONITOR for passive monitor
*/
/**************************** CONSTANTS ****************************/
/* -------------------------- IOCTL LIST -------------------------- */
/* Wireless Identification */
#define SIOCSIWCOMMIT 0x8B00 /* Commit pending changes to driver */
#define SIOCGIWNAME 0x8B01 /* get name == wireless protocol */
/* SIOCGIWNAME is used to verify the presence of Wireless Extensions.
* Common values : "IEEE 802.11-DS", "IEEE 802.11-FH", "IEEE 802.11b"...
* Don't put the name of your driver there, it's useless. */
/* Basic operations */
#define SIOCSIWNWID 0x8B02 /* set network id (pre-802.11) */
#define SIOCGIWNWID 0x8B03 /* get network id (the cell) */
#define SIOCSIWFREQ 0x8B04 /* set channel/frequency (Hz) */
#define SIOCGIWFREQ 0x8B05 /* get channel/frequency (Hz) */
#define SIOCSIWMODE 0x8B06 /* set operation mode */
#define SIOCGIWMODE 0x8B07 /* get operation mode */
#define SIOCSIWSENS 0x8B08 /* set sensitivity (dBm) */
#define SIOCGIWSENS 0x8B09 /* get sensitivity (dBm) */
/* Informative stuff */
#define SIOCSIWRANGE 0x8B0A /* Unused */
#define SIOCGIWRANGE 0x8B0B /* Get range of parameters */
#define SIOCSIWPRIV 0x8B0C /* Unused */
#define SIOCGIWPRIV 0x8B0D /* get private ioctl interface info */
#define SIOCSIWSTATS 0x8B0E /* Unused */
#define SIOCGIWSTATS 0x8B0F /* Get /proc/net/wireless stats */
/* SIOCGIWSTATS is strictly used between user space and the kernel, and
* is never passed to the driver (i.e. the driver will never see it). */
/* Mobile IP support (statistics per MAC address) */
#define SIOCSIWSPY 0x8B10 /* set spy addresses */
#define SIOCGIWSPY 0x8B11 /* get spy info (quality of link) */
/* Access Point manipulation */
#define SIOCSIWAP 0x8B14 /* set access point MAC addresses */
#define SIOCGIWAP 0x8B15 /* get access point MAC addresses */
#define SIOCGIWAPLIST 0x8B17 /* Deprecated in favor of scanning */
#define SIOCSIWSCAN 0x8B18 /* trigger scanning (list cells) */
#define SIOCGIWSCAN 0x8B19 /* get scanning results */
/* 802.11 specific support */
#define SIOCSIWESSID 0x8B1A /* set ESSID (network name) */
#define SIOCGIWESSID 0x8B1B /* get ESSID */
#define SIOCSIWNICKN 0x8B1C /* set node name/nickname */
#define SIOCGIWNICKN 0x8B1D /* get node name/nickname */
/* As the ESSID and NICKN are strings up to 32 bytes long, it doesn't fit
* within the 'iwreq' structure, so we need to use the 'data' member to
* point to a string in user space, like it is done for RANGE... */
/* Other parameters useful in 802.11 and some other devices */
#define SIOCSIWRATE 0x8B20 /* set default bit rate (bps) */
#define SIOCGIWRATE 0x8B21 /* get default bit rate (bps) */
#define SIOCSIWRTS 0x8B22 /* set RTS/CTS threshold (bytes) */
#define SIOCGIWRTS 0x8B23 /* get RTS/CTS threshold (bytes) */
#define SIOCSIWFRAG 0x8B24 /* set fragmentation thr (bytes) */
#define SIOCGIWFRAG 0x8B25 /* get fragmentation thr (bytes) */
#define SIOCSIWTXPOW 0x8B26 /* set transmit power (dBm) */
#define SIOCGIWTXPOW 0x8B27 /* get transmit power (dBm) */
#define SIOCSIWRETRY 0x8B28 /* set retry limits and lifetime */
#define SIOCGIWRETRY 0x8B29 /* get retry limits and lifetime */
/* Encoding stuff (scrambling, hardware security, WEP...) */
#define SIOCSIWENCODE 0x8B2A /* set encoding token & mode */
#define SIOCGIWENCODE 0x8B2B /* get encoding token & mode */
/* Power saving stuff (power management, unicast and multicast) */
#define SIOCSIWPOWER 0x8B2C /* set Power Management settings */
#define SIOCGIWPOWER 0x8B2D /* get Power Management settings */
/* -------------------- DEV PRIVATE IOCTL LIST -------------------- */
/* These 16 ioctl are wireless device private.
* Each driver is free to use them for whatever purpose it chooses,
* however the driver *must* export the description of those ioctls
* with SIOCGIWPRIV and *must* use arguments as defined below.
* If you don't follow those rules, DaveM is going to hate you (reason :
* it make mixed 32/64bit operation impossible).
*/
#define SIOCIWFIRSTPRIV 0x8BE0
#define SIOCIWLASTPRIV 0x8BFF
/* Previously, we were using SIOCDEVPRIVATE, but we now have our
* separate range because of collisions with other tools such as
* 'mii-tool'.
* We now have 32 commands, so a bit more space ;-).
* Also, all 'odd' commands are only usable by root and don't return the
* content of ifr/iwr to user (but you are not obliged to use the set/get
* convention, just use every other two command).
* And I repeat : you are not obliged to use them with iwspy, but you
* must be compliant with it.
*/
/* ------------------------- IOCTL STUFF ------------------------- */
/* The first and the last (range) */
#define SIOCIWFIRST 0x8B00
#define SIOCIWLAST SIOCIWLASTPRIV /* 0x8BFF */
/* Even : get (world access), odd : set (root access) */
#define IW_IS_SET(cmd) (!((cmd) & 0x1))
#define IW_IS_GET(cmd) ((cmd) & 0x1)
/* ----------------------- WIRELESS EVENTS ----------------------- */
/* Those are *NOT* ioctls, do not issue request on them !!! */
/* Most events use the same identifier as ioctl requests */
#define IWEVTXDROP 0x8C00 /* Packet dropped to excessive retry */
#define IWEVQUAL 0x8C01 /* Quality part of statistics (scan) */
#define IWEVCUSTOM 0x8C02 /* Driver specific ascii string */
#define IWEVREGISTERED 0x8C03 /* Discovered a new node (AP mode) */
#define IWEVEXPIRED 0x8C04 /* Expired a node (AP mode) */
#define IWEVFIRST 0x8C00
/* ------------------------- PRIVATE INFO ------------------------- */
/*
* The following is used with SIOCGIWPRIV. It allow a driver to define
* the interface (name, type of data) for its private ioctl.
* Privates ioctl are SIOCIWFIRSTPRIV -> SIOCIWLASTPRIV
*/
#define IW_PRIV_TYPE_MASK 0x7000 /* Type of arguments */
#define IW_PRIV_TYPE_NONE 0x0000
#define IW_PRIV_TYPE_BYTE 0x1000 /* Char as number */
#define IW_PRIV_TYPE_CHAR 0x2000 /* Char as character */
#define IW_PRIV_TYPE_INT 0x4000 /* 32 bits int */
#define IW_PRIV_TYPE_FLOAT 0x5000 /* struct iw_freq */
#define IW_PRIV_TYPE_ADDR 0x6000 /* struct sockaddr */
#define IW_PRIV_SIZE_FIXED 0x0800 /* Variable or fixed nuber of args */
#define IW_PRIV_SIZE_MASK 0x07FF /* Max number of those args */
/*
* Note : if the number of args is fixed and the size < 16 octets,
* instead of passing a pointer we will put args in the iwreq struct...
*/
/* ----------------------- OTHER CONSTANTS ----------------------- */
/* Maximum frequencies in the range struct */
#define IW_MAX_FREQUENCIES 16
/* Note : if you have something like 80 frequencies,
* don't increase this constant and don't fill the frequency list.
* The user will be able to set by channel anyway... */
/* Maximum bit rates in the range struct */
#define IW_MAX_BITRATES 8
/* Maximum tx powers in the range struct */
#define IW_MAX_TXPOWER 8
/* Note : if you more than 8 TXPowers, just set the max and min or
* a few of them in the struct iw_range. */
/* Maximum of address that you may set with SPY */
#define IW_MAX_SPY 8 /* set */
#define IW_MAX_GET_SPY 64 /* get */
/* Maximum of address that you may get in the
list of access points in range */
#define IW_MAX_AP 64
/* Maximum size of the ESSID and NICKN strings */
#define IW_ESSID_MAX_SIZE 32
/* Modes of operation */
#define IW_MODE_AUTO 0 /* Let the driver decides */
#define IW_MODE_ADHOC 1 /* Single cell network */
#define IW_MODE_INFRA 2 /* Multi cell network, roaming, ... */
#define IW_MODE_MASTER 3 /* Synchronisation master or Access Point */
#define IW_MODE_REPEAT 4 /* Wireless Repeater (forwarder) */
#define IW_MODE_SECOND 5 /* Secondary master/repeater (backup) */
#define IW_MODE_MONITOR 6 /* Passive monitor (listen only) */
/* Maximum number of size of encoding token available
* they are listed in the range structure */
#define IW_MAX_ENCODING_SIZES 8
/* Maximum size of the encoding token in bytes */
#define IW_ENCODING_TOKEN_MAX 32 /* 256 bits (for now) */
/* Flags for encoding (along with the token) */
#define IW_ENCODE_INDEX 0x00FF /* Token index (if needed) */
#define IW_ENCODE_FLAGS 0xFF00 /* Flags defined below */
#define IW_ENCODE_MODE 0xF000 /* Modes defined below */
#define IW_ENCODE_DISABLED 0x8000 /* Encoding disabled */
#define IW_ENCODE_ENABLED 0x0000 /* Encoding enabled */
#define IW_ENCODE_RESTRICTED 0x4000 /* Refuse non-encoded packets */
#define IW_ENCODE_OPEN 0x2000 /* Accept non-encoded packets */
#define IW_ENCODE_NOKEY 0x0800 /* Key is write only, so not present */
/* Power management flags available (along with the value, if any) */
#define IW_POWER_ON 0x0000 /* No details... */
#define IW_POWER_TYPE 0xF000 /* Type of parameter */
#define IW_POWER_PERIOD 0x1000 /* Value is a period/duration of */
#define IW_POWER_TIMEOUT 0x2000 /* Value is a timeout (to go asleep) */
#define IW_POWER_MODE 0x0F00 /* Power Management mode */
#define IW_POWER_UNICAST_R 0x0100 /* Receive only unicast messages */
#define IW_POWER_MULTICAST_R 0x0200 /* Receive only multicast messages */
#define IW_POWER_ALL_R 0x0300 /* Receive all messages though PM */
#define IW_POWER_FORCE_S 0x0400 /* Force PM procedure for sending unicast */
#define IW_POWER_REPEATER 0x0800 /* Repeat broadcast messages in PM period */
#define IW_POWER_MODIFIER 0x000F /* Modify a parameter */
#define IW_POWER_MIN 0x0001 /* Value is a minimum */
#define IW_POWER_MAX 0x0002 /* Value is a maximum */
#define IW_POWER_RELATIVE 0x0004 /* Value is not in seconds/ms/us */
/* Transmit Power flags available */
#define IW_TXPOW_TYPE 0x00FF /* Type of value */
#define IW_TXPOW_DBM 0x0000 /* Value is in dBm */
#define IW_TXPOW_MWATT 0x0001 /* Value is in mW */
#define IW_TXPOW_RANGE 0x1000 /* Range of value between min/max */
/* Retry limits and lifetime flags available */
#define IW_RETRY_ON 0x0000 /* No details... */
#define IW_RETRY_TYPE 0xF000 /* Type of parameter */
#define IW_RETRY_LIMIT 0x1000 /* Maximum number of retries*/
#define IW_RETRY_LIFETIME 0x2000 /* Maximum duration of retries in us */
#define IW_RETRY_MODIFIER 0x000F /* Modify a parameter */
#define IW_RETRY_MIN 0x0001 /* Value is a minimum */
#define IW_RETRY_MAX 0x0002 /* Value is a maximum */
#define IW_RETRY_RELATIVE 0x0004 /* Value is not in seconds/ms/us */
/* Scanning request flags */
#define IW_SCAN_DEFAULT 0x0000 /* Default scan of the driver */
#define IW_SCAN_ALL_ESSID 0x0001 /* Scan all ESSIDs */
#define IW_SCAN_THIS_ESSID 0x0002 /* Scan only this ESSID */
#define IW_SCAN_ALL_FREQ 0x0004 /* Scan all Frequencies */
#define IW_SCAN_THIS_FREQ 0x0008 /* Scan only this Frequency */
#define IW_SCAN_ALL_MODE 0x0010 /* Scan all Modes */
#define IW_SCAN_THIS_MODE 0x0020 /* Scan only this Mode */
#define IW_SCAN_ALL_RATE 0x0040 /* Scan all Bit-Rates */
#define IW_SCAN_THIS_RATE 0x0080 /* Scan only this Bit-Rate */
/* Maximum size of returned data */
#define IW_SCAN_MAX_DATA 4096 /* In bytes */
/* Max number of char in custom event - use multiple of them if needed */
#define IW_CUSTOM_MAX 256 /* In bytes */
/****************************** TYPES ******************************/
/* --------------------------- SUBTYPES --------------------------- */
/*
* Generic format for most parameters that fit in an int
*/
struct iw_param
{
__s32 value; /* The value of the parameter itself */
__u8 fixed; /* Hardware should not use auto select */
__u8 disabled; /* Disable the feature */
__u16 flags; /* Various specifc flags (if any) */
};
/*
* For all data larger than 16 octets, we need to use a
* pointer to memory allocated in user space.
*/
struct iw_point
{
caddr_t pointer; /* Pointer to the data (in user space) */
__u16 length; /* number of fields or size in bytes */
__u16 flags; /* Optional params */
};
/*
* A frequency
* For numbers lower than 10^9, we encode the number in 'm' and
* set 'e' to 0
* For number greater than 10^9, we divide it by the lowest power
* of 10 to get 'm' lower than 10^9, with 'm'= f / (10^'e')...
* The power of 10 is in 'e', the result of the division is in 'm'.
*/
struct iw_freq
{
__s32 m; /* Mantissa */
__s16 e; /* Exponent */
__u8 i; /* List index (when in range struct) */
__u8 pad; /* Unused - just for alignement */
};
/*
* Quality of the link
*/
struct iw_quality
{
__u8 qual; /* link quality (%retries, SNR,
%missed beacons or better...) */
__u8 level; /* signal level (dBm) */
__u8 noise; /* noise level (dBm) */
__u8 updated; /* Flags to know if updated */
};
/*
* Packet discarded in the wireless adapter due to
* "wireless" specific problems...
* Note : the list of counter and statistics in net_device_stats
* is already pretty exhaustive, and you should use that first.
* This is only additional stats...
*/
struct iw_discarded
{
__u32 nwid; /* Rx : Wrong nwid/essid */
__u32 code; /* Rx : Unable to code/decode (WEP) */
__u32 fragment; /* Rx : Can't perform MAC reassembly */
__u32 retries; /* Tx : Max MAC retries num reached */
__u32 misc; /* Others cases */
};
/*
* Packet/Time period missed in the wireless adapter due to
* "wireless" specific problems...
*/
struct iw_missed
{
__u32 beacon; /* Missed beacons/superframe */
};
/* ------------------------ WIRELESS STATS ------------------------ */
/*
* Wireless statistics (used for /proc/net/wireless)
*/
struct iw_statistics
{
__u16 status; /* Status
* - device dependent for now */
struct iw_quality qual; /* Quality of the link
* (instant/mean/max) */
struct iw_discarded discard; /* Packet discarded counts */
struct iw_missed miss; /* Packet missed counts */
};
/* ------------------------ IOCTL REQUEST ------------------------ */
/*
* This structure defines the payload of an ioctl, and is used
* below.
*
* Note that this structure should fit on the memory footprint
* of iwreq (which is the same as ifreq), which mean a max size of
* 16 octets = 128 bits. Warning, pointers might be 64 bits wide...
* You should check this when increasing the structures defined
* above in this file...
*/
union iwreq_data
{
/* Config - generic */
char name[IFNAMSIZ];
/* Name : used to verify the presence of wireless extensions.
* Name of the protocol/provider... */
struct iw_point essid; /* Extended network name */
struct iw_param nwid; /* network id (or domain - the cell) */
struct iw_freq freq; /* frequency or channel :
* 0-1000 = channel
* > 1000 = frequency in Hz */
struct iw_param sens; /* signal level threshold */
struct iw_param bitrate; /* default bit rate */
struct iw_param txpower; /* default transmit power */
struct iw_param rts; /* RTS threshold threshold */
struct iw_param frag; /* Fragmentation threshold */
__u32 mode; /* Operation mode */
struct iw_param retry; /* Retry limits & lifetime */
struct iw_point encoding; /* Encoding stuff : tokens */
struct iw_param power; /* PM duration/timeout */
struct iw_quality qual; /* Quality part of statistics */
struct sockaddr ap_addr; /* Access point address */
struct sockaddr addr; /* Destination address (hw) */
struct iw_param param; /* Other small parameters */
struct iw_point data; /* Other large parameters */
};
/*
* The structure to exchange data for ioctl.
* This structure is the same as 'struct ifreq', but (re)defined for
* convenience...
* Do I need to remind you about structure size (32 octets) ?
*/
struct iwreq
{
union
{
char ifrn_name[IFNAMSIZ]; /* if name, e.g. "eth0" */
} ifr_ifrn;
/* Data part (defined just above) */
union iwreq_data u;
};
/* -------------------------- IOCTL DATA -------------------------- */
/*
* For those ioctl which want to exchange mode data that what could
* fit in the above structure...
*/
/*
* Range of parameters
*/
struct iw_range
{
/* Informative stuff (to choose between different interface) */
__u32 throughput; /* To give an idea... */
/* In theory this value should be the maximum benchmarked
* TCP/IP throughput, because with most of these devices the
* bit rate is meaningless (overhead an co) to estimate how
* fast the connection will go and pick the fastest one.
* I suggest people to play with Netperf or any benchmark...
*/
/* NWID (or domain id) */
__u32 min_nwid; /* Minimal NWID we are able to set */
__u32 max_nwid; /* Maximal NWID we are able to set */
/* Frequency */
__u16 num_channels; /* Number of channels [0; num - 1] */
__u8 num_frequency; /* Number of entry in the list */
struct iw_freq freq[IW_MAX_FREQUENCIES]; /* list */
/* Note : this frequency list doesn't need to fit channel numbers */
/* signal level threshold range */
__s32 sensitivity;
/* Quality of link & SNR stuff */
struct iw_quality max_qual; /* Quality of the link */
/* Rates */
__u8 num_bitrates; /* Number of entries in the list */
__s32 bitrate[IW_MAX_BITRATES]; /* list, in bps */
/* RTS threshold */
__s32 min_rts; /* Minimal RTS threshold */
__s32 max_rts; /* Maximal RTS threshold */
/* Frag threshold */
__s32 min_frag; /* Minimal frag threshold */
__s32 max_frag; /* Maximal frag threshold */
/* Power Management duration & timeout */
__s32 min_pmp; /* Minimal PM period */
__s32 max_pmp; /* Maximal PM period */
__s32 min_pmt; /* Minimal PM timeout */
__s32 max_pmt; /* Maximal PM timeout */
__u16 pmp_flags; /* How to decode max/min PM period */
__u16 pmt_flags; /* How to decode max/min PM timeout */
__u16 pm_capa; /* What PM options are supported */
/* Encoder stuff */
__u16 encoding_size[IW_MAX_ENCODING_SIZES]; /* Different token sizes */
__u8 num_encoding_sizes; /* Number of entry in the list */
__u8 max_encoding_tokens; /* Max number of tokens */
/* Transmit power */
__u16 txpower_capa; /* What options are supported */
__u8 num_txpower; /* Number of entries in the list */
__s32 txpower[IW_MAX_TXPOWER]; /* list, in bps */
/* Wireless Extension version info */
__u8 we_version_compiled; /* Must be WIRELESS_EXT */
__u8 we_version_source; /* Last update of source */
/* Retry limits and lifetime */
__u16 retry_capa; /* What retry options are supported */
__u16 retry_flags; /* How to decode max/min retry limit */
__u16 r_time_flags; /* How to decode max/min retry life */
__s32 min_retry; /* Minimal number of retries */
__s32 max_retry; /* Maximal number of retries */
__s32 min_r_time; /* Minimal retry lifetime */
__s32 max_r_time; /* Maximal retry lifetime */
/* Average quality of link & SNR */
struct iw_quality avg_qual; /* Quality of the link */
/* This should contain the average/typical values of the quality
* indicator. This should be the threshold between a "good" and
* a "bad" link (example : monitor going from green to orange).
* Currently, user space apps like quality monitors don't have any
* way to calibrate the measurement. With this, they can split
* the range between 0 and max_qual in different quality level
* (using a geometric subdivision centered on the average).
* I expect that people doing the user space apps will feedback
* us on which value we need to put in each driver...
*/
};
/*
* Private ioctl interface information
*/
struct iw_priv_args
{
__u32 cmd; /* Number of the ioctl to issue */
__u16 set_args; /* Type and number of args */
__u16 get_args; /* Type and number of args */
char name[IFNAMSIZ]; /* Name of the extension */
};
/* ----------------------- WIRELESS EVENTS ----------------------- */
/*
* Wireless events are carried through the rtnetlink socket to user
* space. They are encapsulated in the IFLA_WIRELESS field of
* a RTM_NEWLINK message.
*/
/*
* A Wireless Event. Contains basically the same data as the ioctl...
*/
struct iw_event
{
__u16 len; /* Real lenght of this stuff */
__u16 cmd; /* Wireless IOCTL */
union iwreq_data u; /* IOCTL fixed payload */
};
/* Size of the Event prefix (including padding and alignement junk) */
#define IW_EV_LCP_LEN (sizeof(struct iw_event) - sizeof(union iwreq_data))
/* Size of the various events */
#define IW_EV_CHAR_LEN (IW_EV_LCP_LEN + IFNAMSIZ)
#define IW_EV_UINT_LEN (IW_EV_LCP_LEN + sizeof(__u32))
#define IW_EV_FREQ_LEN (IW_EV_LCP_LEN + sizeof(struct iw_freq))
#define IW_EV_POINT_LEN (IW_EV_LCP_LEN + sizeof(struct iw_point))
#define IW_EV_PARAM_LEN (IW_EV_LCP_LEN + sizeof(struct iw_param))
#define IW_EV_ADDR_LEN (IW_EV_LCP_LEN + sizeof(struct sockaddr))
#define IW_EV_QUAL_LEN (IW_EV_LCP_LEN + sizeof(struct iw_quality))
/* Note : in the case of iw_point, the extra data will come at the
* end of the event */
#endif /* _LINUX_WIRELESS_H */

View File

@ -0,0 +1,404 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "config.h"
#include "libnet.h"
#include <net/if.h>
#if defined(__GLIBC__) && (__GLIBC__)
#include <netinet/if_ether.h>
#include <net/if_arp.h>
#else
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#ifdef __ANDROID__
#include <net/if_ether.h>
#endif
#endif
#include "bpf.h"
struct libnet_link_int *
libnet_open_link_interface(char *device, char *ebuf)
{
register struct libnet_link_int *l;
struct ifreq ifr;
l = (struct libnet_link_int *)malloc(sizeof (*l));
if (l == NULL)
{
sprintf(ebuf, "malloc: %s", strerror(errno));
return (NULL);
}
memset(l, 0, sizeof (*l));
//l->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
// sc_yang , modify to avoid every packet copy
l->fd = socket(PF_INET, SOCK_PACKET, 0);
if (l->fd == -1)
{
sprintf(ebuf, "socket: %s", strerror(errno));
goto bad;
}
memset(&ifr, 0, sizeof (ifr));
strncpy(ifr.ifr_name, device, sizeof (ifr.ifr_name));
if (ioctl(l->fd, SIOCGIFHWADDR, &ifr) < 0 )
{
sprintf(ebuf, "SIOCGIFHWADDR: %s", strerror(errno));
goto bad;
}
switch (ifr.ifr_hwaddr.sa_family)
{
case ARPHRD_ETHER:
case ARPHRD_METRICOM:
l->linktype = DLT_EN10MB;
l->linkoffset = 0xe;
break;
case ARPHRD_SLIP:
case ARPHRD_CSLIP:
case ARPHRD_SLIP6:
case ARPHRD_CSLIP6:
case ARPHRD_PPP:
l->linktype = DLT_RAW;
break;
default:
sprintf(ebuf, "unknown physical layer type 0x%x",
ifr.ifr_hwaddr.sa_family);
goto bad;
}
return (l);
bad:
if (l->fd >= 0)
{
close(l->fd);
}
free(l);
return (NULL);
}
int
libnet_write_link_layer(struct libnet_link_int *l, const char *device,
u_char *buf, int len)
{
int c;
struct sockaddr sa;
memset(&sa, 0, sizeof (sa));
strncpy(sa.sa_data, device, sizeof (sa.sa_data));
c = sendto(l->fd, buf, len, 0, (struct sockaddr *)&sa, sizeof (sa));
if (c != len)
{
#if (__DEBUG)
libnet_error(LIBNET_ERR_WARNING,
"write_link_layer: %d bytes written (%s)\n", c,
strerror(errno));
#endif
}
return (c);
}
int
libnet_close_link_interface(struct libnet_link_int *l)
{
if (close(l->fd) == 0)
{
return (1);
}
else
{
return (-1);
}
}
struct ether_addr *
libnet_get_hwaddr(struct libnet_link_int *l, const char *device, char *ebuf)
{
int fd;
struct ifreq ifr;
struct ether_addr *eap;
/*
* XXX - non-re-entrant!
*/
static struct ether_addr ea;
/*
* Create dummy socket to perform an ioctl upon.
*/
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
sprintf(ebuf, "get_hwaddr: %s", strerror(errno));
return (NULL);
}
memset(&ifr, 0, sizeof(ifr));
eap = &ea;
strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
if (ioctl(fd, SIOCGIFHWADDR, (char *)&ifr) < 0)
{
close(fd);
sprintf(ebuf, "get_hwaddr: %s", strerror(errno));
return (NULL);
}
memcpy(eap, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
close(fd);
return (eap);
}
#ifndef COMPACK_SIZE
int
libnet_in_cksum(u_short *addr, int len)
{
int sum;
int nleft;
u_short ans;
u_short *w;
sum = 0;
ans = 0;
nleft = len;
w = addr;
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
if (nleft == 1)
{
*(u_char *)(&ans) = *(u_char *)w;
sum += ans;
}
return (sum);
}
#endif
#ifndef COMPACK_SIZE
int
libnet_do_checksum(u_char *buf, int protocol, int len)
{
struct libnet_ip_hdr *iph_p;
int ip_hl;
int sum;
sum = 0;
iph_p = (struct libnet_ip_hdr *)buf;
ip_hl = iph_p->ip_hl << 2;
/*
* Dug Song came up with this very cool checksuming implementation
* eliminating the need for explicit psuedoheader use. Check it out.
*/
switch (protocol)
{
/*
* Style note: normally I don't advocate declaring variables inside
* blocks of control, but it makes good sense here. -- MDS
*/
case IPPROTO_TCP:
{
struct libnet_tcp_hdr *tcph_p =
(struct libnet_tcp_hdr *)(buf + ip_hl);
#if (STUPID_SOLARIS_CHECKSUM_BUG)
tcph_p->th_sum = tcph_p->th_off << 2;
return (1);
#endif /* STUPID_SOLARIS_CHECKSUM_BUG */
tcph_p->th_sum = 0;
sum = libnet_in_cksum((u_short *)&iph_p->ip_src, 8);
sum += ntohs(IPPROTO_TCP + len);
sum += libnet_in_cksum((u_short *)tcph_p, len);
tcph_p->th_sum = LIBNET_CKSUM_CARRY(sum);
break;
}
case IPPROTO_UDP:
{
struct libnet_udp_hdr *udph_p =
(struct libnet_udp_hdr *)(buf + ip_hl);
udph_p->uh_sum = 0;
sum = libnet_in_cksum((u_short *)&iph_p->ip_src, 8);
sum += ntohs(IPPROTO_UDP + len);
sum += libnet_in_cksum((u_short *)udph_p, len);
udph_p->uh_sum = LIBNET_CKSUM_CARRY(sum);
break;
}
case IPPROTO_ICMP:
{
struct libnet_icmp_hdr *icmph_p =
(struct libnet_icmp_hdr *)(buf + ip_hl);
icmph_p->icmp_sum = 0;
sum = libnet_in_cksum((u_short *)icmph_p, len);
icmph_p->icmp_sum = LIBNET_CKSUM_CARRY(sum);
break;
}
case IPPROTO_IGMP:
{
struct libnet_igmp_hdr *igmph_p =
(struct libnet_igmp_hdr *)(buf + ip_hl);
igmph_p->igmp_sum = 0;
sum = libnet_in_cksum((u_short *)igmph_p, len);
igmph_p->igmp_sum = LIBNET_CKSUM_CARRY(sum);
break;
}
case IPPROTO_OSPF:
{
struct libnet_ospf_hdr *oh_p =
(struct libnet_ospf_hdr *)(buf + ip_hl);
u_char *payload = (u_char *)(buf + ip_hl + LIBNET_AUTH_H +
sizeof(oh_p));
u_char *tbuf = (u_char *)malloc(sizeof(oh_p) + sizeof(payload));
if (tbuf == NULL)
{
return (-1);
}
oh_p->ospf_cksum = 0;
sum += libnet_in_cksum((u_short *)tbuf, sizeof(tbuf));
oh_p->ospf_cksum = LIBNET_CKSUM_CARRY(sum);
free(tbuf);
break;
}
case IPPROTO_OSPF_LSA:
{
/*
* Reworked fletcher checksum taken from RFC 1008.
*/
int c0, c1;
struct libnet_lsa_hdr *lsa_p = (struct libnet_lsa_hdr *)buf;
u_char *p, *p1, *p2, *p3;
c0 = 0;
c1 = 0;
lsa_p->lsa_cksum[0] = 0;
lsa_p->lsa_cksum[1] = 0; /* zero out checksum */
p = buf;
p1 = buf;
p3 = buf + len; /* beginning and end of buf */
while (p1 < p3)
{
p2 = p1 + LIBNET_MODX;
if (p2 > p3)
{
p2 = p3;
}
for (p = p1; p < p2; p++)
{
c0 += (*p);
c1 += c0;
}
c0 %= 255;
c1 %= 255; /* modular 255 */
p1 = p2;
}
lsa_p->lsa_cksum[0] = (((len - 17) * c0 - c1) % 255);
if (lsa_p->lsa_cksum[0] <= 0)
{
lsa_p->lsa_cksum[0] += 255;
}
lsa_p->lsa_cksum[1] = (510 - c0 - lsa_p->lsa_cksum[0]);
if (lsa_p->lsa_cksum[1] > 255)
{
lsa_p->lsa_cksum[1] -= 255;
}
break;
}
case IPPROTO_IP:
{
iph_p->ip_sum = 0;
sum = libnet_in_cksum((u_short *)iph_p, len);
iph_p->ip_sum = LIBNET_CKSUM_CARRY(sum);
break;
}
case IPPROTO_VRRP:
{
struct libnet_vrrp_hdr *vrrph_p =
(struct libnet_vrrp_hdr *)(buf + ip_hl);
vrrph_p->vrrp_sum = 0;
sum = libnet_in_cksum((u_short *)vrrph_p, len);
vrrph_p->vrrp_sum = LIBNET_CKSUM_CARRY(sum);
break;
}
default:
{
#if (__DEBUG)
libnet_error(LN_ERR_CRITICAL, "do_checksum: UNSUPP protocol %d\n",
protocol);
#endif
return (-1);
}
}
return (1);
}
u_short
libnet_ip_check(u_short *addr, int len)
{
int sum;
sum = libnet_in_cksum(addr, len);
return (LIBNET_CKSUM_CARRY(sum));
}
#endif
u_long
libnet_get_ipaddr(struct libnet_link_int *l, const char *device, char *ebuf)
{
struct ifreq ifr;
register struct sockaddr_in *sin;
int fd;
/*
* Create dummy socket to perform an ioctl upon.
*/
fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
sprintf(ebuf, "socket: %s", strerror(errno));
return (0);
}
memset(&ifr, 0, sizeof(ifr));
sin = (struct sockaddr_in *)&ifr.ifr_addr;
strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
ifr.ifr_addr.sa_family = AF_INET;
if (ioctl(fd, SIOCGIFADDR, (char*) &ifr) < 0)
{
close(fd);
return(0);
}
close(fd);
return (ntohl(sin->sin_addr.s_addr));
}

View File

@ -0,0 +1,388 @@
/*
* SHA-256 hash implementation and interface functions
* Copyright (c) 2003-2007, Jouni Malinen <j@w1.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.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#include <stdlib.h>
#include "sha256.h"
#define SHA256_BLOCK_SIZE 64
/**
* hmac_sha256_vector - HMAC-SHA256 over data vector (RFC 2104)
* @key: Key for HMAC operations
* @key_len: Length of the key in bytes
* @num_elem: Number of elements in the data vector
* @addr: Pointers to the data areas
* @len: Lengths of the data blocks
* @mac: Buffer for the hash (32 bytes)
* Returns: 0 on success, -1 on failure
*/
int hmac_sha256_vector(const u1Byte *key, size_t key_len, size_t num_elem,
const u1Byte *addr[], const size_t *len, u1Byte *mac)
{
unsigned char k_pad[64]; /* padding - key XORd with ipad/opad */
unsigned char tk[32];
const u1Byte *_addr[6];
size_t _len[6], i;
if (num_elem > 5) {
/*
* Fixed limit on the number of fragments to avoid having to
* allocate memory (which could fail).
*/
return -1;
}
/* if key is longer than 64 bytes reset it to key = SHA256(key) */
if (key_len > 64) {
if (sha256_vector(1, &key, &key_len, tk) < 0)
return -1;
key = tk;
key_len = 32;
}
/* the HMAC_SHA256 transform looks like:
*
* SHA256(K XOR opad, SHA256(K XOR ipad, text))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and text is the data being protected */
/* start out by storing key in ipad */
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with ipad values */
for (i = 0; i < 64; i++)
k_pad[i] ^= 0x36;
/* perform inner SHA256 */
_addr[0] = k_pad;
_len[0] = 64;
for (i = 0; i < num_elem; i++) {
_addr[i + 1] = addr[i];
_len[i + 1] = len[i];
}
if (sha256_vector(1 + num_elem, _addr, _len, mac) < 0)
return -1;
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with opad values */
for (i = 0; i < 64; i++)
k_pad[i] ^= 0x5c;
/* perform outer SHA256 */
_addr[0] = k_pad;
_len[0] = 64;
_addr[1] = mac;
_len[1] = SHA256_MAC_LEN;
return sha256_vector(2, _addr, _len, mac);
}
/**
* hmac_sha256 - HMAC-SHA256 over data buffer (RFC 2104)
* @key: Key for HMAC operations
* @key_len: Length of the key in bytes
* @data: Pointers to the data area
* @data_len: Length of the data area
* @mac: Buffer for the hash (20 bytes)
*/
int hmac_sha256(const u1Byte *key, size_t key_len, const u1Byte *data,
size_t data_len, u1Byte *mac)
{
return hmac_sha256_vector(key, key_len, 1, &data, &data_len, mac);
}
/**
* sha256_prf - SHA256-based Pseudo-Random Function (IEEE 802.11r, 8.5.1.5.2)
* @key: Key for PRF
* @key_len: Length of the key in bytes
* @label: A unique label for each purpose of the PRF
* @data: Extra data to bind into the key
* @data_len: Length of the data
* @buf: Buffer for the generated pseudo-random key
* @buf_len: Number of bytes of key to generate
*
* This function is used to derive new, cryptographically separate keys from a
* given key.
*/
void sha256_prf(const u1Byte *key, size_t key_len, const char *label,
const u1Byte *data, size_t data_len, u1Byte *buf, size_t buf_len)
{
u2Byte counter = 1;
size_t pos, plen;
u1Byte hash[SHA256_MAC_LEN];
const u1Byte *addr[4];
size_t len[4];
u1Byte counter_le[2], length_le[2];
addr[0] = counter_le;
len[0] = 2;
addr[1] = (u1Byte *) label;
len[1] = strlen(label);
addr[2] = data;
len[2] = data_len;
addr[3] = length_le;
len[3] = sizeof(length_le);
WPA_PUT_LE16(length_le, buf_len * 8);
pos = 0;
while (pos < buf_len) {
plen = buf_len - pos;
WPA_PUT_LE16(counter_le, counter);
if (plen >= SHA256_MAC_LEN) {
hmac_sha256_vector(key, key_len, 4, addr, len,
&buf[pos]);
pos += SHA256_MAC_LEN;
} else {
hmac_sha256_vector(key, key_len, 4, addr, len, hash);
memcpy(&buf[pos], hash, plen);
break;
}
counter++;
}
}
struct sha256_state {
u8Byte length;
u4Byte state[8], curlen;
u1Byte buf[SHA256_BLOCK_SIZE];
};
static void sha256_init(struct sha256_state *md);
static int sha256_process(struct sha256_state *md, const unsigned char *in,
unsigned long inlen);
static int sha256_done(struct sha256_state *md, unsigned char *out);
/**
* sha256_vector - SHA256 hash for data vector
* @num_elem: Number of elements in the data vector
* @addr: Pointers to the data areas
* @len: Lengths of the data blocks
* @mac: Buffer for the hash
* Returns: 0 on success, -1 of failure
*/
int sha256_vector(size_t num_elem, const u1Byte *addr[], const size_t *len,
u1Byte *mac)
{
struct sha256_state ctx;
size_t i;
sha256_init(&ctx);
for (i = 0; i < num_elem; i++)
if (sha256_process(&ctx, addr[i], len[i]))
return -1;
if (sha256_done(&ctx, mac))
return -1;
return 0;
}
/* ===== start - public domain SHA256 implementation ===== */
/* This is based on SHA256 implementation in LibTomCrypt that was released into
* public domain by Tom St Denis. */
/* the K array */
static const unsigned long K[64] = {
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
/* Various logical functions */
#define RORc(x, y) \
( ((((unsigned long) (x) & 0xFFFFFFFFUL) >> (unsigned long) ((y) & 31)) | \
((unsigned long) (x) << (unsigned long) (32 - ((y) & 31)))) & 0xFFFFFFFFUL)
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) RORc((x), (n))
#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))
#ifndef MIN
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#endif
/* compress 512-bits */
static int sha256_compress(struct sha256_state *md, unsigned char *buf)
{
u4Byte S[8], W[64], t0, t1;
u4Byte t;
int i;
/* copy state into S */
for (i = 0; i < 8; i++) {
S[i] = md->state[i];
}
/* copy the state into 512-bits into W[0..15] */
for (i = 0; i < 16; i++)
W[i] = WPA_GET_BE32(buf + (4 * i));
/* fill W[16..63] */
for (i = 16; i < 64; i++) {
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) +
W[i - 16];
}
/* Compress */
#define RND(a,b,c,d,e,f,g,h,i) \
t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1;
for (i = 0; i < 64; ++i) {
RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i);
t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];
S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
}
/* feedback */
for (i = 0; i < 8; i++) {
md->state[i] = md->state[i] + S[i];
}
return 0;
}
/* Initialize the hash state */
static void sha256_init(struct sha256_state *md)
{
md->curlen = 0;
md->length = 0;
md->state[0] = 0x6A09E667UL;
md->state[1] = 0xBB67AE85UL;
md->state[2] = 0x3C6EF372UL;
md->state[3] = 0xA54FF53AUL;
md->state[4] = 0x510E527FUL;
md->state[5] = 0x9B05688CUL;
md->state[6] = 0x1F83D9ABUL;
md->state[7] = 0x5BE0CD19UL;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
static int sha256_process(struct sha256_state *md, const unsigned char *in,
unsigned long inlen)
{
unsigned long n;
if (md->curlen >= sizeof(md->buf))
return -1;
while (inlen > 0) {
if (md->curlen == 0 && inlen >= SHA256_BLOCK_SIZE) {
if (sha256_compress(md, (unsigned char *) in) < 0)
return -1;
md->length += SHA256_BLOCK_SIZE * 8;
in += SHA256_BLOCK_SIZE;
inlen -= SHA256_BLOCK_SIZE;
} else {
n = MIN(inlen, (SHA256_BLOCK_SIZE - md->curlen));
memcpy(md->buf + md->curlen, in, n);
md->curlen += n;
in += n;
inlen -= n;
if (md->curlen == SHA256_BLOCK_SIZE) {
if (sha256_compress(md, md->buf) < 0)
return -1;
md->length += 8 * SHA256_BLOCK_SIZE;
md->curlen = 0;
}
}
}
return 0;
}
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (32 bytes)
@return CRYPT_OK if successful
*/
static int sha256_done(struct sha256_state *md, unsigned char *out)
{
int i;
if (md->curlen >= sizeof(md->buf))
return -1;
/* increase the length of the message */
md->length += md->curlen * 8;
/* append the '1' bit */
md->buf[md->curlen++] = (unsigned char) 0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->curlen > 56) {
while (md->curlen < SHA256_BLOCK_SIZE) {
md->buf[md->curlen++] = (unsigned char) 0;
}
sha256_compress(md, md->buf);
md->curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->curlen < 56) {
md->buf[md->curlen++] = (unsigned char) 0;
}
/* store length */
WPA_PUT_BE64(md->buf + 56, md->length);
sha256_compress(md, md->buf);
/* copy output */
for (i = 0; i < 8; i++)
WPA_PUT_BE32(out + (4 * i), md->state[i]);
return 0;
}
/* ===== end - public domain SHA256 implementation ===== */

View File

@ -0,0 +1,117 @@
/*
* SHA256 hash implementation and interface functions
* Copyright (c) 2003-2006, Jouni Malinen <j@w1.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.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#ifndef SHA256_H
#define SHA256_H
#define SHA256_MAC_LEN 32
//typedef unsigned long u64;
//typedef unsigned int u32;
//typedef unsigned short u16;
//typedef unsigned char u8;
/**
* sha256_vector - SHA256 hash for data vector
* @num_elem: Number of elements in the data vector
* @addr: Pointers to the data areas
* @len: Lengths of the data blocks
* @mac: Buffer for the hash
* Returns: 0 on success, -1 on failure
*/
typedef unsigned char u1Byte;
typedef unsigned short u2Byte;
typedef unsigned long u4Byte;
typedef unsigned long long u8Byte;
#define WPA_GET_BE16(a) ((u2Byte) (((a)[0] << 8) | (a)[1]))
#define WPA_PUT_BE16(a, val) \
do { \
(a)[0] = ((u2Byte) (val)) >> 8; \
(a)[1] = ((u2Byte) (val)) & 0xff; \
} while (0)
#define WPA_GET_LE16(a) ((u2Byte) (((a)[1] << 8) | (a)[0]))
#define WPA_PUT_LE16(a, val) \
do { \
(a)[1] = ((u2Byte) (val)) >> 8; \
(a)[0] = ((u2Byte) (val)) & 0xff; \
} while (0)
#define WPA_GET_BE24(a) ((((u32) (a)[0]) << 16) | (((u4Byte) (a)[1]) << 8) | \
((u4Byte) (a)[2]))
#define WPA_PUT_BE24(a, val) \
do { \
(a)[0] = (u1Byte) ((((u4Byte) (val)) >> 16) & 0xff); \
(a)[1] = (u1Byte) ((((u4Byte) (val)) >> 8) & 0xff); \
(a)[2] = (u1Byte) (((u4Byte) (val)) & 0xff); \
} while (0)
#define WPA_GET_BE32(a) ((((u4Byte) (a)[0]) << 24) | (((u4Byte) (a)[1]) << 16) | \
(((u4Byte) (a)[2]) << 8) | ((u4Byte) (a)[3]))
#define WPA_PUT_BE32(a, val) \
do { \
(a)[0] = (u1Byte) ((((u4Byte) (val)) >> 24) & 0xff); \
(a)[1] = (u1Byte) ((((u4Byte) (val)) >> 16) & 0xff); \
(a)[2] = (u1Byte) ((((u4Byte) (val)) >> 8) & 0xff); \
(a)[3] = (u1Byte) (((u4Byte) (val)) & 0xff); \
} while (0)
#define WPA_GET_LE32(a) ((((u4Byte) (a)[3]) << 24) | (((u4Byte) (a)[2]) << 16) | \
(((u4Byte) (a)[1]) << 8) | ((u4Byte) (a)[0]))
#define WPA_PUT_LE32(a, val) \
do { \
(a)[3] = (u1Byte) ((((u4Byte) (val)) >> 24) & 0xff); \
(a)[2] = (u1Byte) ((((u4Byte) (val)) >> 16) & 0xff); \
(a)[1] = (u1Byte) ((((u4Byte) (val)) >> 8) & 0xff); \
(a)[0] = (u1Byte) (((u4Byte) (val)) & 0xff); \
} while (0)
#define WPA_GET_BE64(a) ((((u8Byte) (a)[0]) << 56) | (((u8Byte) (a)[1]) << 48) | \
(((u8Byte) (a)[2]) << 40) | (((u8Byte) (a)[3]) << 32) | \
(((u8Byte) (a)[4]) << 24) | (((u8Byte) (a)[5]) << 16) | \
(((u8Byte) (a)[6]) << 8) | ((u8Byte) (a)[7]))
#define WPA_PUT_BE64(a, val) \
do { \
(a)[0] = (u1Byte) (((u8Byte) (val)) >> 56); \
(a)[1] = (u1Byte) (((u8Byte) (val)) >> 48); \
(a)[2] = (u1Byte) (((u8Byte) (val)) >> 40); \
(a)[3] = (u1Byte) (((u8Byte) (val)) >> 32); \
(a)[4] = (u1Byte) (((u8Byte) (val)) >> 24); \
(a)[5] = (u1Byte) (((u8Byte) (val)) >> 16); \
(a)[6] = (u1Byte) (((u8Byte) (val)) >> 8); \
(a)[7] = (u1Byte) (((u8Byte) (val)) & 0xff); \
} while (0)
#define WPA_GET_LE64(a) ((((u8Byte) (a)[7]) << 56) | (((u8Byte) (a)[6]) << 48) | \
(((u8Byte) (a)[5]) << 40) | (((u8Byte) (a)[4]) << 32) | \
(((u8Byte) (a)[3]) << 24) | (((u8Byte) (a)[2]) << 16) | \
(((u8Byte) (a)[1]) << 8) | ((u8Byte) (a)[0]))
int sha256_vector(size_t num_elem, const unsigned char *addr[], const size_t *len,
unsigned char *mac);
int hmac_sha256_vector(const unsigned char *key, size_t key_len, size_t num_elem,
const unsigned char *addr[], const size_t *len, unsigned char *mac);
int hmac_sha256(const unsigned char *key, size_t key_len, const unsigned char *data,
size_t data_len, unsigned char *mac);
void sha256_prf(const unsigned char *key, size_t key_len, const char *label,
const unsigned char *data, size_t data_len, unsigned char *buf, size_t buf_len);
#endif /* SHA256_H */