std::pair<bool, MACAddressType> GetPrimaryMacAddress() { kern_return_t kernResult = KERN_SUCCESS; // on PowerPC this is an int (4 bytes) /* * error number layout as follows (see mach/error.h and IOKit/IOReturn.h): * * hi lo * | system(6) | subsystem(12) | code(14) | */ io_iterator_t intfIterator; MACAddressType mac_address = {0}; kernResult = FindEthernetInterfaces(&intfIterator, "en0"); if (KERN_SUCCESS != kernResult) { //printf("FindEthernetInterfaces returned 0x%08x\n", kernResult); (void) IOObjectRelease(intfIterator); // Release the iterator. return std::pair<bool, MACAddressType>(false, mac_address); } else { kernResult = GetMACAddress(intfIterator, mac_address.array, sizeof(MACAddressType)); if (KERN_SUCCESS != kernResult) { kernResult = FindEthernetInterfaces(&intfIterator, "en1"); if (KERN_SUCCESS != kernResult) { //printf("FindEthernetInterfaces returned 0x%08x\n", kernResult); (void) IOObjectRelease(intfIterator); // Release the iterator. return std::pair<bool, MACAddressType>(false, mac_address); } else { kernResult = GetMACAddress(intfIterator, mac_address.array, sizeof(MACAddressType)); if (KERN_SUCCESS != kernResult) { //printf("GetMACAddress returned 0x%08x\n", kernResult); (void) IOObjectRelease(intfIterator); // Release the iterator. return std::pair<bool, MACAddressType>(false, mac_address); } else { (void) IOObjectRelease(intfIterator); // Release the iterator. return std::pair<bool, MACAddressType>(true, mac_address); } } } else { (void) IOObjectRelease(intfIterator); // Release the iterator. return std::pair<bool, MACAddressType>(true, mac_address); } } }
NSString *getMACAddressString() { static NSString *addressString = nil; if (!addressString) { kern_return_t kernResult = KERN_SUCCESS; // on PowerPC this is an int (4 bytes) /* * error number layout as follows (see mach/error.h and IOKit/IOReturn.h): * * hi lo * | system(6) | subsystem(12) | code(14) | */ io_iterator_t intfIterator; UInt8 MACAddress[kIOEthernetAddressSize]; kernResult = FindEthernetInterfaces(&intfIterator); if (KERN_SUCCESS != kernResult) { printf("FindEthernetInterfaces returned 0x%08x\n", kernResult); } else { kernResult = GetMACAddress(intfIterator, MACAddress, sizeof(MACAddress)); if (KERN_SUCCESS != kernResult) { printf("GetMACAddress returned 0x%08x\n", kernResult); } else { addressString = [[NSString alloc] initWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", MACAddress[0], MACAddress[1], MACAddress[2], MACAddress[3], MACAddress[4], MACAddress[5] ]; } } (void) IOObjectRelease(intfIterator); // Release the iterator. }
//取得已打开网卡的MAC地址 int NetworkInterface::SetLocalMAC() { if( !GetMACAddress(adapter.lpAdapter, srcMAC) ) { LastErrCode = 0x00; strcpy_s(LastErrStr, "Failed to Set the MAC Address!"); return -1; } return 0; }
bool CSysInfoJob::DoWork() { m_info.systemUptime = GetSystemUpTime(false); m_info.systemTotalUptime = GetSystemUpTime(true); m_info.internetState = GetInternetState(); m_info.videoEncoder = GetVideoEncoder(); m_info.cpuFrequency = GetCPUFreqInfo(); m_info.kernelVersion = CSysInfo::GetKernelVersion(); m_info.macAddress = GetMACAddress(); return true; }
bool CSysInfoJob::DoWork() { m_info.systemUptime = GetSystemUpTime(false); m_info.systemTotalUptime = GetSystemUpTime(true); m_info.internetState = GetInternetState(); m_info.videoEncoder = GetVideoEncoder(); m_info.cpuFrequency = GetCPUFreqInfo(); m_info.osVersionInfo = CSysInfo::GetOsPrettyNameWithVersion() + " (kernel: " + CSysInfo::GetKernelName() + " " + CSysInfo::GetKernelVersionFull() + ")"; m_info.macAddress = GetMACAddress(); m_info.batteryLevel = GetBatteryLevel(); return true; }
/********************************************************************* * Function: BOOL SetSecurityKey(INPUT BYTE index, INPUT NETWORK_KEY_INFO newSecurityKey) * * PreCondition: None * * Input: BYTE index: the index to the security key, usually either 0 or 1 * NETWORK_KEY_INFO: the network key information to be saved in external NVM * * Output: BOOL to indicate if operation is successful * * Side Effects: The security keys will be encrypted and stored in the external NVM * * Overview: This function is used to encrypt the security key and store it in the external * NVM. ********************************************************************/ BOOL SetSecurityKey(INPUT BYTE index, INPUT NETWORK_KEY_INFO newSecurityKey) { SECURITY_INPUT SecurityInput; BYTE Counter; BYTE i; BYTE EncryptedLen; BYTE tmpBuf[16]; LONG_ADDR myAddr; plainSecurityKey[index] = newSecurityKey; SecurityInput.cipherMode = 0x01; SecurityInput.FrameCounter.Val = 0; SecurityInput.SecurityControl.Val = nwkSecurityLevel; SecurityInput.SecurityKey = (BYTE *)defaultMasterKey; SecurityInput.KeySeq = 0; GetMACAddress(&myAddr); SecurityInput.SourceAddress = &myAddr; SecurityInput.Header = NULL; SecurityInput.HeaderLen = 0; Counter = CIPHER_RETRY; while(Counter) { SecurityInput.InputText = newSecurityKey.NetKey.v; SecurityInput.TextLen = 16; PHYCipher(MODE_ENCRYPTION, SecurityInput, tmpBuf, &EncryptedLen); SecurityInput.InputText = tmpBuf; SecurityInput.TextLen = EncryptedLen; if( PHYCipher(MODE_DECRYPTION, SecurityInput, newSecurityKey.NetKey.v, &i) == CIPHER_SUCCESS ) { break; } Counter--; } if( Counter ) { for(i = 0; i < 16; i++) currentNetworkKeyInfo.NetKey.v[i] = tmpBuf[i]; currentNetworkKeyInfo.SeqNumber.v[0] = newSecurityKey.SeqNumber.v[0]; currentNetworkKeyInfo.SeqNumber.v[1] = nwkMAGICResSeq; PutNwkKeyInfo((networkKeyInfo+index*sizeof(NETWORK_KEY_INFO)), ¤tNetworkKeyInfo); return TRUE; } return FALSE; }
//机器标识 bool CWHService::GetMachineID(TCHAR szMachineID[LEN_MACHINE_ID]) { //变量定义 TCHAR szMACAddress[LEN_NETWORK_ID]=TEXT(""); //网卡标识 GetMACAddress(szMACAddress); //转换信息 ASSERT(LEN_MACHINE_ID>=LEN_MD5); CWHEncrypt::MD5Encrypt(szMACAddress,szMachineID); return true; }
//通过适配器名字获取MAC地址 bool NetworkInterface::GetMACAddress(char *adapterName, u_char *localMAC) { LPADAPTER lpAdapter = PacketOpenAdapter(adapterName); if (!adapter.lpAdapter || (adapter.lpAdapter->hFile == INVALID_HANDLE_VALUE)) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Unable to open the adapter!"); return false; } GetMACAddress(lpAdapter, localMAC); PacketCloseAdapter(lpAdapter); return true; }
/********************************************************************* * Function: BOOL InitSecurityKey(void) * * PreCondition: None * * Input: None * * Output: BOOL to indicate if operation is successful * * Side Effects: The security keys stored in external NVM encrypted get decrypted and * stored in the RAM * * Overview: This function is used in the system start up to retrieve security key * stored in external NVM encrypted and decrypt them and store in the * RAM for future security operation use ********************************************************************/ BOOL InitSecurityKey(void) { SECURITY_INPUT SecurityInput; BYTE i,j; BYTE DataLen; LONG_ADDR myAddr; for(i = 0; i < 2; i++) { GetNwkKeyInfo(¤tNetworkKeyInfo, (networkKeyInfo+i*sizeof(NETWORK_KEY_INFO))); //ConsolePutROMString((ROM char *)"\r\nStored key:"); //for(j=0;j<16;j++) PrintChar(currentNetworkKeyInfo.NetKey.v[j]); plainSecurityKey[i].SeqNumber.Val = currentNetworkKeyInfo.SeqNumber.Val; if( currentNetworkKeyInfo.SeqNumber.v[1] != nwkMAGICResSeq ) { plainSecurityKey[i].SeqNumber = currentNetworkKeyInfo.SeqNumber; continue; } SecurityInput.cipherMode = 0x01; SecurityInput.FrameCounter.Val = 0; SecurityInput.SecurityControl.Val = nwkSecurityLevel; SecurityInput.SecurityKey = (BYTE *)defaultMasterKey; SecurityInput.KeySeq = 0; GetMACAddress(&myAddr); SecurityInput.SourceAddress = &myAddr; SecurityInput.Header = NULL; SecurityInput.HeaderLen = 0; SecurityInput.InputText = currentNetworkKeyInfo.NetKey.v; SecurityInput.TextLen = 16; if( PHYCipher(MODE_DECRYPTION, SecurityInput, plainSecurityKey[i].NetKey.v, &DataLen) != CIPHER_SUCCESS ) { return FALSE; } plainSecurityKey[i].SeqNumber = currentNetworkKeyInfo.SeqNumber; //{ // BYTE j; // ConsolePutROMString((ROM char *)"\r\nRecovered Key: "); // for(j = 0; j < DataLen; j++) // PrintChar(plainSecurityKey[i].NetKey.v[j]); //} } return TRUE; }
static psych_bool GetPrimaryEthernetAddress(UInt8 *MACAddress) { psych_bool errorReturn; kern_return_t kernResult; io_iterator_t intfIterator; errorReturn=FALSE; kernResult = FindEthernetInterfaces(&intfIterator); if(kernResult != KERN_SUCCESS) errorReturn=TRUE; else{ kernResult = GetMACAddress(intfIterator, MACAddress); if(kernResult != KERN_SUCCESS) errorReturn=TRUE; } (void) IOObjectRelease(intfIterator); // Release the iterator. return(errorReturn); }
void IAndroid::GetClientSerial(tagClientSerial & ClientSerial) { //获取版本 OSVERSIONINFO OSVerInfo; OSVerInfo.dwOSVersionInfoSize=sizeof(OSVerInfo); GetVersionEx(&OSVerInfo); ClientSerial.dwSystemVer=MAKELONG(OSVerInfo.dwMajorVersion,OSVerInfo.dwMinorVersion); //网卡标识 ZeroMemory(ClientSerial.dwComputerID,sizeof(ClientSerial.dwComputerID)); WORD wMacSize=GetMACAddress((BYTE *)ClientSerial.dwComputerID,sizeof(ClientSerial.dwComputerID)); //硬盘标识 WORD wIndex=(wMacSize+sizeof(DWORD)-1)/sizeof(DWORD); LPCTSTR pszHardDisk[]={TEXT("C:\\"),TEXT("D:\\"),TEXT("E:\\")}; for (WORD i=wIndex;i<CountArray(ClientSerial.dwComputerID);i++) { ASSERT(CountArray(pszHardDisk)>(i-wIndex)); GetVolumeInformation(pszHardDisk[i-wIndex],NULL,0,&ClientSerial.dwComputerID[i],NULL,NULL,0,NULL); } return; }
static CFStringRef CopyPrimaryMacAddress(void) { io_iterator_t intfIterator; UInt8 MAC[kIOEthernetAddressSize]; CFStringRef macAddress = NULL; kern_return_t kernResult = FindEthernetInterfaces(&intfIterator); if (KERN_SUCCESS != kernResult) { DbgLog( kLogError, "FindEthernetInterfaces returned 0x%08x", kernResult ); } else { kernResult = GetMACAddress(intfIterator, MAC, sizeof(MAC)); if (KERN_SUCCESS != kernResult) { DbgLog( kLogError, "GetMACAddress returned 0x%08x", kernResult ); } else { macAddress = CFStringCreateWithFormat(NULL, NULL, CFSTR("[%02x:%02x:%02x:%02x:%02x:%02x]"), MAC[0], MAC[1], MAC[2], MAC[3], MAC[4], MAC[5]); } } (void)IOObjectRelease(intfIterator); return macAddress; }
int get_macaddr(const char *ifname, U8 *addr) { #if defined(__NBR_OSX__) kern_return_t kernResult = KERN_SUCCESS; io_iterator_t intfIterator; UInt8 MACAddress[kIOEthernetAddressSize]; kernResult = FindEthernetInterfaces(&intfIterator); if (KERN_SUCCESS != kernResult) { //OSDEP_ERROUT(ERROR,SYSCALL,"FindEthernetInterfaces returned 0x%08x\n", kernResult); return NBR_ESYSCALL; } else { kernResult = GetMACAddress(intfIterator, addr, sizeof(MACAddress)); if (KERN_SUCCESS != kernResult) { //OSDEP_ERROUT(ERROR,SYSCALL,"GetMACAddress returned 0x%08x\n", kernResult); } else { TRACE("This system's built-in MAC address is %02x:%02x:%02x:%02x:%02x:%02x.\n", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); } } (void) IOObjectRelease(intfIterator); // Release the iterator. return kernResult == KERN_SUCCESS ? NBR_OK : NBR_ESYSCALL; #elif defined(__NBR_IOS__) int mib[6]; size_t len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex(ifname)) == 0) { TRACE("Error: if_nametoindex error\n"); return NBR_ESYSCALL; } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { TRACE("Error: sysctl, take 1\n"); return NBR_ESYSCALL; } if ((buf = (char *)util::mem::alloc(len)) == NULL) { TRACE("Could not allocate memory. error!\n"); return NBR_EMALLOC; } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { TRACE("Error: sysctl, take 2"); util::mem::free(buf); return NBR_ESYSCALL; } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); util::mem::copy(addr, ptr, 6); util::mem::free(buf); TRACE("MAC ADDRESS (%s): [%02X:%02X:%02X:%02X:%02X:%02X]\n", ifname, *addr, *(addr+1), *(addr+2), *(addr+3), *(addr+4), *(addr+5)); return NBR_OK; #else int soc, ret; struct ifreq req; if ((soc = socket(AF_INET, SOCK_STREAM, 0)) < 0) { TRACE("socket fail: ret=%d,errno=%d",soc,errno); ret = soc; goto error; } util::str::copy(req.ifr_name, ifname, sizeof(req.ifr_name)); req.ifr_addr.sa_family = AF_INET; if ((ret = ioctl(soc, SIOCGIFHWADDR, &req)) < 0) { TRACE("ioctl fail: soc=%d,ret=%d,errno=%d",soc,ret,errno); goto error; } util::mem::copy(addr, &(req.ifr_addr.sa_data), 6); ret = 0; TRACE("MAC ADDRESS (%s): [%02X:%02X:%02X:%02X:%02X:%02X]\n", ifname, *addr, *(addr+1), *(addr+2), *(addr+3), *(addr+4), *(addr+5)); error: if (soc >= 0) { close(soc); } return ret; #endif }
boolean SMSC951xDeviceConfigure (TUSBDevice *pUSBDevice) { TSMSC951xDevice *pThis = (TSMSC951xDevice *) pUSBDevice; assert (pThis != 0); u8 MACAddress[MAC_ADDRESS_SIZE]; if (GetMACAddress (MACAddress)) { MACAddressSet (&pThis->m_MACAddress, MACAddress); } else { LogWrite (FromSMSC951x, LOG_ERROR, "Cannot get MAC address"); return FALSE; } TString MACString; String (&MACString); MACAddressFormat (&pThis->m_MACAddress, &MACString); LogWrite (FromSMSC951x, LOG_DEBUG, "MAC address is %s", StringGet (&MACString)); const TUSBConfigurationDescriptor *pConfigDesc = (TUSBConfigurationDescriptor *) USBDeviceGetDescriptor (&pThis->m_USBDevice, DESCRIPTOR_CONFIGURATION); if ( pConfigDesc == 0 || pConfigDesc->bNumInterfaces != 1) { USBDeviceConfigurationError (&pThis->m_USBDevice, FromSMSC951x); _String (&MACString); return FALSE; } const TUSBInterfaceDescriptor *pInterfaceDesc = (TUSBInterfaceDescriptor *) USBDeviceGetDescriptor (&pThis->m_USBDevice, DESCRIPTOR_INTERFACE); if ( pInterfaceDesc == 0 || pInterfaceDesc->bInterfaceNumber != 0x00 || pInterfaceDesc->bAlternateSetting != 0x00 || pInterfaceDesc->bNumEndpoints != 3) { USBDeviceConfigurationError (&pThis->m_USBDevice, FromSMSC951x); _String (&MACString); return FALSE; } const TUSBEndpointDescriptor *pEndpointDesc; while ((pEndpointDesc = (TUSBEndpointDescriptor *) USBDeviceGetDescriptor (&pThis->m_USBDevice, DESCRIPTOR_ENDPOINT)) != 0) { if ((pEndpointDesc->bmAttributes & 0x3F) == 0x02) // Bulk { if ((pEndpointDesc->bEndpointAddress & 0x80) == 0x80) // Input { if (pThis->m_pEndpointBulkIn != 0) { USBDeviceConfigurationError (&pThis->m_USBDevice, FromSMSC951x); _String (&MACString); return FALSE; } pThis->m_pEndpointBulkIn = (TUSBEndpoint *) malloc (sizeof (TUSBEndpoint)); assert (pThis->m_pEndpointBulkIn); USBEndpoint2 (pThis->m_pEndpointBulkIn, &pThis->m_USBDevice, pEndpointDesc); } else // Output { if (pThis->m_pEndpointBulkOut != 0) { USBDeviceConfigurationError (&pThis->m_USBDevice, FromSMSC951x); _String (&MACString); return FALSE; } pThis->m_pEndpointBulkOut = (TUSBEndpoint *) malloc (sizeof (TUSBEndpoint)); assert (pThis->m_pEndpointBulkOut); USBEndpoint2 (pThis->m_pEndpointBulkOut, &pThis->m_USBDevice, pEndpointDesc); } } } if ( pThis->m_pEndpointBulkIn == 0 || pThis->m_pEndpointBulkOut == 0) { USBDeviceConfigurationError (&pThis->m_USBDevice, FromSMSC951x); _String (&MACString); return FALSE; } if (!USBDeviceConfigure (&pThis->m_USBDevice)) { LogWrite (FromSMSC951x, LOG_ERROR, "Cannot set configuration"); _String (&MACString); return FALSE; } u8 MACAddressBuffer[MAC_ADDRESS_SIZE]; MACAddressCopyTo (&pThis->m_MACAddress, MACAddressBuffer); u16 usMACAddressHigh = *(u16 *) &MACAddressBuffer[4]; u32 nMACAddressLow = *(u32 *) &MACAddressBuffer[0]; if ( !SMSC951xDeviceWriteReg (pThis, ADDRH, usMACAddressHigh) || !SMSC951xDeviceWriteReg (pThis, ADDRL, nMACAddressLow)) { LogWrite (FromSMSC951x, LOG_ERROR, "Cannot set MAC address"); _String (&MACString); return FALSE; } if ( !SMSC951xDeviceWriteReg (pThis, LED_GPIO_CFG, LED_GPIO_CFG_SPD_LED | LED_GPIO_CFG_LNK_LED | LED_GPIO_CFG_FDX_LED) || !SMSC951xDeviceWriteReg (pThis, MAC_CR, MAC_CR_RCVOWN //| MAC_CR_PRMS // promiscous mode | MAC_CR_TXEN | MAC_CR_RXEN) || !SMSC951xDeviceWriteReg (pThis, TX_CFG, TX_CFG_ON)) { LogWrite (FromSMSC951x, LOG_ERROR, "Cannot start device"); _String (&MACString); return FALSE; } // TODO: check if PHY is up (wait for it) TString DeviceName; String (&DeviceName); StringFormat (&DeviceName, "eth%u", s_nDeviceNumber++); DeviceNameServiceAddDevice (DeviceNameServiceGet (), StringGet (&DeviceName), pThis, FALSE); _String (&DeviceName); _String (&MACString); return TRUE; }
// Function which receives packets from the Radius server void *ListenToRadius(void *args) { int bytesReceived, position; BYTE packet[PACKET_LENGTH], *mac; struct sockaddr radiusAddr; socklen_t addrlen = sizeof(radiusAddr); SUBSCRIBER *sub; RADIUS_PACKET *radiusData = malloc(PACKET_LENGTH - RADIUS_HEADER_LENGTH); RESPONSE response; response.length = 0; response.packet = malloc(PACKET_LENGTH); bzero(response.packet, PACKET_LENGTH); // Get the MAC address of subscriber-facing interface if ((mac = GetMACAddress(subscriberInterface, rawSocket)) == NULL) { syslog(LOG_ERR, "Unable to get MAC address of Radius-facing interface"); return NULL; } // Log start of thread syslog(LOG_INFO, "Listening for incoming Radius packets on %s", radiusInterface); // Listen to incoming packets from Radius server while (1) { bzero(packet, PACKET_LENGTH); bytesReceived = recvfrom(radiusSocket, &packet, PACKET_LENGTH, 0, &radiusAddr, &addrlen); if (bytesReceived == -1) { syslog(LOG_NOTICE, "No packets received from the Internet"); continue; } memcpy(radiusData, packet, bytesReceived); // Discard packets that are not Access-Accept or Access-Reject if ( (radiusData->code != ACCESS_ACCEPT) && (radiusData->code != ACCESS_REJECT) ) continue; // Find subscriber for who the Radius response is received; if not found, continue sem_wait(&semaphoreTree); sub = GetSubscriberRadius(&subscriberList, radiusData); sem_post(&semaphoreTree); if (sub == NULL) continue; // Create reply packet for subscriber position = 0; // Add destination MAC memcpy(response.packet, sub->mac_array, MAC_ADDRESS_LENGTH); position += MAC_ADDRESS_LENGTH; // Add source MAC Append(response.packet, position, mac, MAC_ADDRESS_LENGTH); position += MAC_ADDRESS_LENGTH; // Add ethertype Append(response.packet, position, "\x88\x64", ETHERTYPE_LENGTH); position += ETHERTYPE_LENGTH; // Add PPPoE header Append(response.packet, position, "\x11", 1); position++; Append(response.packet, position, "\x00", 1); position++; // Add PPPoE SESSION_ID response.packet[position] = sub->session_id % 256; position++; response.packet[position] = sub->session_id / 256; position++; // Add payload length if (radiusData->code == ACCESS_ACCEPT) { Append(response.packet, position, "\x00\x07", 2); position += 2; } else { Append(response.packet, position, "\x00\x0a", 2); position += 2; } // Add PPP protocol Append(response.packet, position, "\xc0\x23", 2); position += 2; // Add code for Auth-Ack or Auth-Nak if (radiusData->code == ACCESS_ACCEPT) { response.packet[position] = 0x02; position++; } else { response.packet[position] = 0x03; position++; } // Add identifier response.packet[position] = sub->auth_ppp_identifier; position++; // Add length if (radiusData->code == ACCESS_ACCEPT) { response.packet[position] = 0x00; position++; response.packet[position] = 0x05; position++; } else { response.packet[position] = 0x00; position++; response.packet[position] = 0x08; position++; // Add Msg-Length response.packet[position] = 0x03; position++; } // Add data if (radiusData->code == ACCESS_ACCEPT) { response.packet[position] = 0x00; position++; } else { Append(response.packet, position, "\x4e\x4f\x4b", 3); position += 3; } // Send packet to subscriber response.length = position; if ((sendto(rawSocket, response.packet, response.length, 0, NULL, sizeof(struct sockaddr_ll))) == -1) { syslog(LOG_NOTICE, "Error sending response to PPPoE discover message"); } } }
/********************************************************************* * Function: BOOL DataEncrypt(IOPUT BYTE *Input, IOPUT BYTE *DataLen, INPUT BYTE *Header, INPUT BYTE HeaderLen, INPUT KEY_IDENTIFIER KeyIdentifier, BOOL bExtendedNonce) * * PreCondition: Input and Header has been filled * * Input: BYTE *Header - Point to MiWi header * BYTE HeaderLen - MiWi header length * KEY_IDENTIFIER KeyIdentifier - Identifier to specify key type. reserved for commercial mode * BOOL bExtendedNonce - if extended nonce being used. * * Output: BOOL - If data encryption successful * * Input/Output: BYTE *Input - Pointer to the data to be encrypted. The encrypted data will be write back to the pointer * BYTE *DataLen - Input as the length of the data to be encrypted. The encrypted data length (including MICs) will be written back * * Side Effects: Input data get encrypted and written back to the input pointer * * Overview: This is the function that call the hardware cipher to encrypt input data ********************************************************************/ BOOL DataEncrypt(IOPUT BYTE *Input, IOPUT BYTE *DataLen, INPUT BYTE *Header, INPUT BYTE HeaderLen, INPUT KEY_IDENTIFIER KeyIdentifier, BOOL bExtendedNonce) { SECURITY_INPUT SecurityInput; BYTE EncryptedLen; BYTE i; BYTE Counter; BYTE ActiveKeyIndex; LONG_ADDR myAddress; // reserve space for multiple try of encryption BYTE *tmpBuf = (BYTE *)SRAMalloc(*DataLen + 18); if( tmpBuf == NULL ) { return FALSE; } // get the IEEE 802.15.4 security mode SecurityInput.cipherMode = SecurityLevel_ZIGBEE_2_IEEE(nwkSecurityLevel); // get security key GetNwkActiveKeyNumber(&ActiveKeyIndex); if( ActiveKeyIndex != 0x01 && ActiveKeyIndex != 0x02 ) // no valid key { nfree(tmpBuf); return FALSE; } // handle the frame counter SecurityInput.FrameCounter = (OutgoingFrameCount[ActiveKeyIndex-1]); OutgoingFrameCount[ActiveKeyIndex-1].Val++; // fill the secuirty input SecurityInput.SecurityControl.Val = nwkSecurityLevel | (KeyIdentifier << 3); if( bExtendedNonce ) { SecurityInput.SecurityControl.Val |= 0x20; } #ifdef USE_EXTERNAL_NVM currentNetworkKeyInfo = plainSecurityKey[ActiveKeyIndex-1]; #else GetNwkKeyInfo( ¤tNetworkKeyInfo, &(networkKeyInfo[ActiveKeyIndex-1]) ); #endif SecurityInput.SecurityKey = currentNetworkKeyInfo.NetKey.v; SecurityInput.KeySeq = currentNetworkKeyInfo.SeqNumber.v[0]; GetMACAddress(&myAddress); SecurityInput.SourceAddress = &myAddress; SecurityInput.Header = Header; SecurityInput.HeaderLen = HeaderLen; // in rare cases, the hardware encryption engine may not suceed for the // first time. Retry a few times will solve the problem Counter = CIPHER_RETRY; while(Counter) { // fill the input data and data length SecurityInput.InputText = Input; SecurityInput.TextLen = *DataLen; // call hardware cipher and store the output to the temporary buffer PHYCipher(MODE_ENCRYPTION, SecurityInput, tmpBuf, &EncryptedLen); // try to decrypt the buffer to make sure that encryption is correct SecurityInput.InputText = tmpBuf; SecurityInput.TextLen = EncryptedLen; if( PHYCipher(MODE_DECRYPTION, SecurityInput, Input, &i) == CIPHER_SUCCESS ) { break; } Counter--; } // fill the auxilary header Input[0] = SecurityInput.SecurityControl.Val & 0xF8; // set security level for(i = 0; i < 4; i++) { Input[i+1] = SecurityInput.FrameCounter.v[i]; } Counter = i+1; if( bExtendedNonce ) { for(i = 0; i < 8; i++) { Input[Counter++] = SecurityInput.SourceAddress->v[i]; } } if( KeyIdentifier == ID_NetworkKey ) { Input[Counter++] = currentNetworkKeyInfo.SeqNumber.v[0]; } // fill the encrypted data for(i = 0; i < EncryptedLen; i++) { Input[Counter++] = tmpBuf[i]; } nfree(tmpBuf); *DataLen = Counter; return TRUE; }
int pcap_io_init(char *adapter) { int dlt; char *dlt_name; emu_printf("Opening adapter '%s'...",adapter); u16 checksum; GetMACAddress(adapter,&host_mac); //Near copy of the host mac, butchered slightly, should be pretty good! eeprom[0] = host_mac.bytes[0]; eeprom[1] = host_mac.bytes[1]; eeprom[2] = host_mac.bytes[2]; eeprom[3] = host_mac.bytes[2]; eeprom[4] = host_mac.bytes[5]; eeprom[5] = host_mac.bytes[4]; virtual_mac.bytes[0] = host_mac.bytes[0]; virtual_mac.bytes[1] = host_mac.bytes[1]; virtual_mac.bytes[2] = host_mac.bytes[2]; virtual_mac.bytes[3] = host_mac.bytes[3]; virtual_mac.bytes[4] = host_mac.bytes[4]; virtual_mac.bytes[5] = host_mac.bytes[5]; //The checksum seems to be all the values of the mac added up in 16bit chunks checksum = dev9.eeprom[0] + dev9.eeprom[1] + dev9.eeprom[2] & 0xffff; dev9.eeprom[3] = checksum; //emu_printf("eeprom Mac set to %x %x %x %x %x %x", eeprom[0], eeprom[1], eeprom[2], eeprom[3], eeprom[4], eeprom[5]); //emu_printf("Checksum %x %x", eeprom[6], eeprom[7]); /* Open the adapter */ if ((adhandle= pcap_open_live(adapter, // name of the device 65536, // portion of the packet to capture. // 65536 grants that the whole packet will be captured on all the MACs. pcap_mode==switched?1:0, // promiscuous mode (nonzero means promiscuous) 1, // read timeout errbuf // error buffer )) == NULL) { fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", adapter); return -1; } dlt = pcap_datalink(adhandle); dlt_name = (char*)pcap_datalink_val_to_name(dlt); fprintf(stderr,"Device uses DLT %d: %s\n",dlt,dlt_name); switch(dlt) { case DLT_EN10MB : //case DLT_IEEE802_11: break; default: SysMessage("ERROR: Unsupported DataLink Type (%d): %s",dlt,dlt_name); pcap_close(adhandle); return -1; } if(pcap_setnonblock(adhandle,1,errbuf)==-1) { fprintf(stderr,"WARNING: Error setting non-blocking mode. Default mode will be used.\n"); } //Changing the LogSetting might not affect logging //directory of winPcap logs if done after Open() const std::string pfile(s_strLogPath + "/packet.log"); packet_log = fopen(pfile.c_str(), "w"); const std::string plfile(s_strLogPath + "/pkt_log.pcap"); dump_pcap = pcap_dump_open(adhandle, plfile.c_str()); pcap_io_running=1; emu_printf("Ok.\n"); return 0; }