long int dtls_ccm_decrypt_message(rijndael_ctx *ctx, size_t M, size_t L, unsigned char nonce[DTLS_CCM_BLOCKSIZE], unsigned char *msg, size_t lm, const unsigned char *aad, size_t la) { size_t len; unsigned long counter_tmp; unsigned long counter = 1; /* \bug does not work correctly on ia32 when lm >= 2^16 */ unsigned char A[DTLS_CCM_BLOCKSIZE]; /* A_i blocks for encryption input */ unsigned char B[DTLS_CCM_BLOCKSIZE]; /* B_i blocks for CBC-MAC input */ unsigned char S[DTLS_CCM_BLOCKSIZE]; /* S_i = encrypted A_i blocks */ unsigned char X[DTLS_CCM_BLOCKSIZE]; /* X_i = encrypted B_i blocks */ if (lm < M) goto error; len = lm; /* save original length */ lm -= M; /* detract MAC size*/ /* create the initial authentication block B0 */ block0(M, L, la, lm, nonce, B); add_auth_data(ctx, aad, la, B, X); /* initialize block template */ A[0] = L-1; /* copy the nonce */ memcpy(A + 1, nonce, DTLS_CCM_BLOCKSIZE - L); while (lm >= DTLS_CCM_BLOCKSIZE) { /* decrypt */ encrypt(ctx, L, counter, msg, DTLS_CCM_BLOCKSIZE, A, S); /* calculate MAC */ mac(ctx, msg, DTLS_CCM_BLOCKSIZE, B, X); /* update local pointers */ lm -= DTLS_CCM_BLOCKSIZE; msg += DTLS_CCM_BLOCKSIZE; counter++; } if (lm) { /* decrypt */ encrypt(ctx, L, counter, msg, lm, A, S); /* Calculate MAC. Note that msg ends in the MAC so we must * construct B to contain X ^ msg for the first lm bytes (done in * mac() and X ^ 0 for the remaining DTLS_CCM_BLOCKSIZE - lm bytes * (i.e., we can use memcpy() here). */ memcpy(B + lm, X + lm, DTLS_CCM_BLOCKSIZE - lm); mac(ctx, msg, lm, B, X); /* update local pointers */ msg += lm; } /* calculate S_0 */ SET_COUNTER(A, L, 0, counter_tmp); #ifdef NOUVELLE_IMPLE_AES memcpy(S, A, DTLS_CCM_BLOCKSIZE); aes128_enc(S, ctx); #endif #ifdef ANCIENNE_IMPLE_AES rijndael_encrypt(ctx, A, S); #endif memxor(msg, S, M); /* return length if MAC is valid, otherwise continue with error handling */ if (equals(X, msg, M)) return len - M; error: return -1; }
void CSCanAPThread::DaemonDeviceScan() { //每隔一定时间,扫描指定的设备,获取ip std::string str_stalist = m_ssh.GetDeviceMAC(); if(str_stalist.c_str() == std::string("Error")) { m_bIsConnect = false; m_ssh.ConnectAP(); return; } else { m_bIsConnect = true; } //先分割获取MAC std::vector<std::string> vec_list; CUtil::split(str_stalist, vec_list, "\n"); if (vec_list.size() < 2) { return; } //去掉无用信息 vec_list.erase(vec_list.begin()); vec_list.erase(vec_list.end() - 1); int i = 0; for (std::vector<std::string>::iterator iter = vec_list.begin(); iter != vec_list.end(); iter++) { if (i % 4 == 0) { //写入数据库 CModel *pmodel = CSingleton<CModel>::instance(); std::string mac((*iter), 0, 17); //获取deviceID int deviceID = pmodel->GetDeviceIDbyMAC(mac); if (deviceID > 0) { //获取APID int APID = pmodel->GetAPIDbyIP(m_strIP); Field definition_tbMonitor[] = { Field(FIELD_KEY), Field("DeviceID", type_int), Field("APID", type_int), Field(DEFINITION_END), }; Table tbMonitor(pmodel->MGetDatabase(), std::string("DirectionMonitor"), definition_tbMonitor); tbMonitor.open(); Record record(tbMonitor.fields()); record.setInteger("DeviceID", deviceID); record.setInteger("APID", APID); tbMonitor.addRecord(&record); } } i++; } }
// get network interface info from file (should include all available interfaces) std::vector<std::map<std::string,std::string> > Responder::read_eth_info() { const std::string eth_file(_eth_file); std::vector<std::map<std::string,std::string> > eths; try { ifstream eth_info(eth_file.c_str()); if(!eth_info.is_open()){ return eths; } const int len = 256; char cline[len]; for(; !eth_info.eof() ;) { eth_info.getline(cline, len); std::string line(cline); if(line.find("## ETH Interface") != std::string::npos) { eth_info.getline(cline, len); std::string eth(cline); // cout << "interface=" << eth << endl; std::map<std::string,std::string> iface; iface["interface"] = eth; eths.push_back(iface); } const std::string ipstr("\tip "); if(line.find(ipstr) != std::string::npos) { std::string ip( line.replace(line.begin(), line.begin()+ipstr.length(), "") ); // cout << "ip=" << ip << endl; eths.back()["addr"] = ip; } const std::string macstr("\tmac "); if(line.find(macstr) != std::string::npos) { std::string mac( line.replace(line.begin(), line.begin()+macstr.length(), "") ); // cout << "mac=" << mac << endl; eths.back()["mac"] = mac; } const std::string vstr("\t\tvendor "); if(line.find(vstr) != std::string::npos) { std::string vendor( line.replace(line.begin(), line.begin()+vstr.length(), "") ); std::string vid( vendor.substr(0,6) ); vendor.replace(0, 7, ""); // cout << "id=" << vid << endl; // cout << "vendor=" << vendor << endl; eths.back()["vendor"] = vendor; eths.back()["vendor_id"] = vid; } const std::string dstr("\t\tdevice "); if(line.find(dstr) != std::string::npos) { std::string device( line.replace(line.begin(), line.begin()+dstr.length(), "") ); std::string did( device.substr(0,6) ); device.replace(0, 7, ""); // cout << "id=" << did << endl; // cout << "device=" << device << endl; eths.back()["device"] = device; eths.back()["device_id"] = did; } } } catch(...) { // nothing in yet } return eths; }
long int dtls_ccm_encrypt_message(rijndael_ctx *ctx, size_t M, size_t L, unsigned char nonce[DTLS_CCM_BLOCKSIZE], unsigned char *msg, size_t lm, const unsigned char *aad, size_t la) { size_t i, len; unsigned long counter_tmp; unsigned long counter = 1; /* \bug does not work correctly on ia32 when lm >= 2^16 */ unsigned char A[DTLS_CCM_BLOCKSIZE]; /* A_i blocks for encryption input */ unsigned char B[DTLS_CCM_BLOCKSIZE]; /* B_i blocks for CBC-MAC input */ unsigned char S[DTLS_CCM_BLOCKSIZE]; /* S_i = encrypted A_i blocks */ unsigned char X[DTLS_CCM_BLOCKSIZE]; /* X_i = encrypted B_i blocks */ len = lm; /* save original length */ /* create the initial authentication block B0 */ block0(M, L, la, lm, nonce, B); add_auth_data(ctx, aad, la, B, X); /* initialize block template */ A[0] = L-1; /* copy the nonce */ memcpy(A + 1, nonce, DTLS_CCM_BLOCKSIZE - L); while (lm >= DTLS_CCM_BLOCKSIZE) { /* calculate MAC */ mac(ctx, msg, DTLS_CCM_BLOCKSIZE, B, X); /* encrypt */ encrypt(ctx, L, counter, msg, DTLS_CCM_BLOCKSIZE, A, S); /* update local pointers */ lm -= DTLS_CCM_BLOCKSIZE; msg += DTLS_CCM_BLOCKSIZE; counter++; } if (lm) { /* Calculate MAC. The remainder of B must be padded with zeroes, so * B is constructed to contain X ^ msg for the first lm bytes (done in * mac() and X ^ 0 for the remaining DTLS_CCM_BLOCKSIZE - lm bytes * (i.e., we can use memcpy() here). */ memcpy(B + lm, X + lm, DTLS_CCM_BLOCKSIZE - lm); mac(ctx, msg, lm, B, X); /* encrypt */ encrypt(ctx, L, counter, msg, lm, A, S); /* update local pointers */ msg += lm; } /* calculate S_0 */ SET_COUNTER(A, L, 0, counter_tmp); #ifdef NOUVELLE_IMPLE_AES memcpy(S, A, DTLS_CCM_BLOCKSIZE); aes128_enc(S, ctx); #endif #ifdef ANCIENNE_IMPLE_AES rijndael_encrypt(ctx, A, S); #endif for (i = 0; i < M; ++i) *msg++ = X[i] ^ S[i]; return len + M; }
int AtiendeCliente(int socket, struct sockaddr_in addr) { char buffer[BUFFERSIZE]; char aux[BUFFERSIZE]; int bytecount; int fin=0; int code=0; /* Código de salida por defecto */ time_t t; struct tm *tmp; while (!fin) { memset(buffer, 0, BUFFERSIZE); if((bytecount = recv(socket, buffer, BUFFERSIZE, 0))== -1) error(5, "No puedo recibir información"); //verificamos si lo que mandan es una ip y entonces la cambiamos por MAC if (strncmp(buffer, "IP", 2)==0) { printf("Se trata de in IPHONE\n"); std::string comando(buffer); comando=comando.substr(3); comando="weon:"+GetMac(comando); printf("El comando dice:"); printf(comando.c_str()); comando.copy(buffer,comando.length(),0); } /////////////////////////////////////// /* Evaluamos los comandos */ /* El sistema de gestión de comandos es muy rudimentario, pero nos vale */ /* Comando TIME - Da la hora */ //weon:mac if (strncmp(buffer, "weon", 4)==0) { t = time(NULL); tmp = localtime(&t); //separo la mac address std::string mac(buffer); mac=mac.substr(5,17); //registro el inicio de sesion, talvez solo registro todos memset(buffer, 0, 7); strftime(buffer, BUFFERSIZE, "echo '%H|", tmp); std::string txt(buffer); txt.append(mac); txt.append("' >> /etc/weon/InciosSesion.txt"); memset(buffer, 0, txt.length()); txt.copy(buffer,txt.length(),0); system(buffer); printf(buffer); //coloco la regla que logea //se registrara todo, esta linea no es necesaria txt="iptables -A FORWARD -p tcp --dport 443 -m mac --mac-source "; txt.append(mac); txt.append(" -m state --state NEW -j LOG --log-prefix 'weon:"); txt.append(mac); txt.append("' --log-level 4 "); memset(buffer, 0, BUFFERSIZE); txt.copy(buffer,txt.length(),0); system(buffer); printf(buffer); //coloco la regla que concede permisos //std::string txt; txt="/sbin/iptables -A FORWARD -m mac --mac-source "; txt.append(mac); txt.append(" -j ACCEPT"); memset(buffer, 0,BUFFERSIZE); txt.copy(buffer,txt.length(),0); system(buffer); printf(buffer); //regla que manda todo a squid txt="/sbin/iptables -t nat -I PREROUTING 2 -m mac --mac-source "; txt.append(mac); txt.append(" -p tcp --dport 80 -j DNAT --to-destination 192.168.1.250:3128"); memset(buffer, 0,BUFFERSIZE); txt.copy(buffer,txt.length(),0); system(buffer); printf(buffer); //esta regla deja saliro todo el trafico que no va al 80 txt="/sbin/iptables -t nat -I PREROUTING 3 -m mac --mac-source "; txt.append(mac); txt.append(" -j ACCEPT"); memset(buffer, 0,BUFFERSIZE); txt.copy(buffer,txt.length(),0); system(buffer); printf(buffer); //regreso mesage de concedido txt="OK:"+mac; memset(buffer, 0, BUFFERSIZE); txt.copy(buffer,txt.length(),0); fin=1; } else if (strncmp(buffer, "check", 5)==0) { std::string cmd(buffer); cmd=cmd.substr(6); memset(buffer,0,BUFFERSIZE); cmd.copy(buffer,cmd.length(),0); system(buffer); fin=1; } /* Comando DATE - Da la fecha */ else if (strncmp(buffer, "DATE", 4)==0) { memset(buffer, 0, BUFFERSIZE); t = time(NULL); tmp = localtime(&t); strftime(buffer, BUFFERSIZE, "Hoy es %d/%m/%Y\n", tmp); } /* Comando HOLA - Saluda y dice la IP */ else if (strncmp(buffer, "HOLA", 4)==0) { memset(buffer, 0, BUFFERSIZE); sprintf(buffer, "Hola %s, ¿cómo estás?\n", inet_ntoa(addr.sin_addr)); } /* Comando EXIT - Cierra la conexión actual */ else if (strncmp(buffer, "E", 1)==0) { memset(buffer, 0, BUFFERSIZE); sprintf(buffer, "Hasta luego. Vuelve pronto %s\n", inet_ntoa(addr.sin_addr)); fin=1; } /* Comando CERRAR - Cierra el servidor */ else if (strncmp(buffer, "Q",1)==0) { memset(buffer, 0, BUFFERSIZE); sprintf(buffer, "Adiós. Cierro el servidor\n"); fin=1; code=99; /* Salir del programa */ } else { sprintf(aux, "ECHO: %s\n", buffer); strcpy(buffer, aux); } if((bytecount = send(socket, buffer, strlen(buffer), 0))== -1) error(6, "No puedo enviar información"); } close(socket); return code; }
/* * check: read logfile and check it */ void check(void) { FILE *finput; int i; int input; int mfd; unsigned char key[41]; int keylen; unsigned char lastkey[21]; int lastkeylen; int line; unsigned char mkey1[21]; int mkey1len; unsigned char mkey2[21]; int mkey2len; char msg[MAXLINE]; int msglen; /* open logfile */ if (actionf & ST_IN) input = STDIN_FILENO; else if ( (input = open(logfile, O_RDONLY, 0)) == -1) { perror(logfile); exit(-1); } mfd = 0; /* shutup gcc */ /* open macfile */ if (macfile) if ( (mfd = open(macfile, O_RDONLY, 0)) == -1) { perror(macfile); exit(-1); } /* read initial key (as ascii string) and tranlate it to binary */ if ( (i = open(key0file, O_RDONLY, 0)) == -1) { perror(key0file); exit(-1); } if ( (keylen = read(i, key, 40)) == -1) { perror(key0file); exit(-1); } if (!keylen) { if (actionf & QUIET) eexit(1, "1\n"); else eexit(1, "(1) %s: %s\n", key0file, corrupted); } key[keylen] = 0; asc2bin(key, key); keylen >>= 1; close(i); /* read last key */ if ( (i = open(keyfile, O_RDONLY, 0)) == -1) { perror(keyfile); exit(-1); } if ( (lastkeylen = read(i, lastkey, 20)) == -1) { perror(keyfile); exit(-1); } if (!lastkeylen) { if (actionf & QUIET) eexit(1, "1\n"); else eexit(1, "(1) %s: %s\n", keyfile, corrupted); } close(i); /* test both key lenghts */ if (lastkeylen != keylen) { if (actionf & QUIET) eexit(1, "1\n"); else eexit(1, "(1) %s and/or %s %s\n", key0file, keyfile, corrupted); } /* check it */ line = 1; finput = NULL; while ( (msglen = readline(input, msg, MAXLINE, &finput)) > 0) { if (macfile) { if ( ((mkey1len = mac2(key, keylen, (unsigned char *) msg, msglen, mkey1)) < 0) || ((mkey2len = read(mfd, mkey2, mkey1len)) < 0) ) { perror(macfile); exit(-1); } if ((mkey2len != mkey1len) || memcmp(mkey2, mkey1, mkey1len)) { if (actionf & QUIET) eexit(1, "%i\n", line); else eexit(1, "(%i) %s %s on line %i\n", line, logfile, corrupted, line); } line++; } if ( (keylen = mac(method, key, keylen, (unsigned char *) msg, msglen, key)) == -1) { perror("fatal"); exit(-1); } } if (finput != NULL) fclose(finput); if (macfile != NULL) close(mfd); if (i < 0) { fprintf(stderr, "error reading logs form %s : %s\n", (actionf & ST_IN) ? "standard input" : logfile, strerror(errno)); exit(-1); } if (memcmp(lastkey, key, keylen)) { if (actionf & QUIET) eexit(1, "1\n"); else eexit(1, "(1) %s %s\n", logfile, corrupted); } if (actionf & QUIET) eexit(0, "0\n"); else eexit(0, "(0) %s file is ok\n", logfile); }
/*---------------------------------------------------------------------- | NPT_NetworkInterface::GetNetworkInterfaces +---------------------------------------------------------------------*/ NPT_Result NPT_NetworkInterface::GetNetworkInterfaces(NPT_List<NPT_NetworkInterface*>& interfaces) { IP_ADAPTER_ADDRESSES* iface_list = NULL; ULONG size = sizeof(IP_ADAPTER_INFO); // get the interface table for(;;) { iface_list = (IP_ADAPTER_ADDRESSES*)malloc(size); DWORD result = GetAdaptersAddresses(AF_INET, 0, NULL, iface_list, &size); if (result == NO_ERROR) { break; } else { // free and try again free(iface_list); if (result != ERROR_BUFFER_OVERFLOW) { return NPT_FAILURE; } } } // iterate over the interfaces for (IP_ADAPTER_ADDRESSES* iface = iface_list; iface; iface = iface->Next) { // skip this interface if it is not up if (iface->OperStatus != IfOperStatusUp) continue; // get the interface type and mac address NPT_MacAddress::Type mac_type; switch (iface->IfType) { case IF_TYPE_ETHERNET_CSMACD: mac_type = NPT_MacAddress::TYPE_ETHERNET; break; case IF_TYPE_SOFTWARE_LOOPBACK: mac_type = NPT_MacAddress::TYPE_LOOPBACK; break; case IF_TYPE_PPP: mac_type = NPT_MacAddress::TYPE_PPP; break; default: mac_type = NPT_MacAddress::TYPE_UNKNOWN; break; } NPT_MacAddress mac(mac_type, iface->PhysicalAddress, iface->PhysicalAddressLength); // compute interface flags NPT_Flags flags = 0; if (!(iface->Flags & IP_ADAPTER_NO_MULTICAST)) flags |= NPT_NETWORK_INTERFACE_FLAG_MULTICAST; if (iface->IfType == IF_TYPE_SOFTWARE_LOOPBACK) flags |= NPT_NETWORK_INTERFACE_FLAG_LOOPBACK; if (iface->IfType == IF_TYPE_PPP) flags |= NPT_NETWORK_INTERFACE_FLAG_POINT_TO_POINT; // compute the unicast address (only the first one is supported for now) NPT_IpAddress primary_address; if (iface->FirstUnicastAddress) { if (iface->FirstUnicastAddress->Address.lpSockaddr == NULL) continue; if (iface->FirstUnicastAddress->Address.iSockaddrLength != sizeof(SOCKADDR_IN)) continue; SOCKADDR_IN* address = (SOCKADDR_IN*)iface->FirstUnicastAddress->Address.lpSockaddr; if (address->sin_family != AF_INET) continue; primary_address.Set(ntohl(address->sin_addr.s_addr)); } NPT_IpAddress broadcast_address; // not supported yet NPT_IpAddress netmask; // not supported yet // convert the interface name to UTF-8 // BUG in Wine: FriendlyName is NULL unsigned int iface_name_length = (unsigned int)iface->FriendlyName?wcslen(iface->FriendlyName):0; char* iface_name = new char[4*iface_name_length+1]; int result = WideCharToMultiByte( CP_UTF8, 0, iface->FriendlyName, iface_name_length, iface_name, 4*iface_name_length+1, NULL, NULL); if (result > 0) { iface_name[result] = '\0'; } else { iface_name[0] = '\0'; } // create an interface descriptor NPT_NetworkInterface* iface_object = new NPT_NetworkInterface(iface_name, mac, flags); NPT_NetworkInterfaceAddress iface_address( primary_address, broadcast_address, NPT_IpAddress::Any, netmask); iface_object->AddAddress(iface_address); // cleanup delete[] iface_name; // add the interface to the list interfaces.Add(iface_object); } free(iface_list); return NPT_SUCCESS; }
int main(){ int i; for(i=0;i<TIME;i++)mac(N); printf("%f\n",mac(N)); return 0; }
int crypto_aead_decrypt( unsigned char *m,unsigned long long *mlen, unsigned char *nsec, const unsigned char *c,unsigned long long clen, const unsigned char *ad,unsigned long long adlen, const unsigned char *npub, const unsigned char *k ) { const unsigned char* in = c; unsigned char* out = m; unsigned long long remaining; unsigned int i; uint8_t buf[16] = { 0 }; __m128i W, Wtmp; __m128i block, Lup, Ldown; __m128i Lup1, Lup2, Lup3, Lup4, Lup5, Lup6, Lup7, Lup8; __m128i Ldown1, Ldown2, Ldown3, Ldown4, Ldown5, Ldown6, Ldown7, Ldown8; __m128i block1, block2, block3, block4; __m128i block5, block6, block7, block8; __m128i checksum = { 0 }; __m128i LL = { 0 }; __m128i expkey[11]; __m128i decexpkey[11]; /* key schedule */ AES_set_encrypt_key(k, expkey); AES_set_decrypt_key(expkey, decexpkey); if (clen < 16) { return -1; } /* Set output length */ *mlen = remaining = clen - 16; LL = AES_encrypt(LL, expkey); /* LL = AES(0) */ Lup = LL; Ldown = gf128_mul3(gf128_mul3(LL)); /* Ldown = 3^2*LL */ /* mac AD + nonce */ W = mac(ad, adlen, npub, LL, expkey); /* Decrypt 8 blocks parallel */ Lup8 = Lup; Ldown8 = Ldown; while (remaining > 8*16) { Ldown1 = gf128_mul2(Ldown8); Ldown2 = gf128_mul2(Ldown1); Ldown3 = gf128_mul2(Ldown2); Ldown4 = gf128_mul2(Ldown3); Ldown5 = gf128_mul2(Ldown4); Ldown6 = gf128_mul2(Ldown5); Ldown7 = gf128_mul2(Ldown6); Ldown8 = gf128_mul2(Ldown7); block1 = byte_swap(_mm_loadu_si128((__m128i*)in)); block2 = byte_swap(_mm_loadu_si128((__m128i*)in+1)); block3 = byte_swap(_mm_loadu_si128((__m128i*)in+2)); block4 = byte_swap(_mm_loadu_si128((__m128i*)in+3)); block5 = byte_swap(_mm_loadu_si128((__m128i*)in+4)); block6 = byte_swap(_mm_loadu_si128((__m128i*)in+5)); block7 = byte_swap(_mm_loadu_si128((__m128i*)in+6)); block8 = byte_swap(_mm_loadu_si128((__m128i*)in+7)); block1 ^= Ldown1; block2 ^= Ldown2; block3 ^= Ldown3; block4 ^= Ldown4; block5 ^= Ldown5; block6 ^= Ldown6; block7 ^= Ldown7; block8 ^= Ldown8; AES_DECRYPT8(block1,block2,block3,block4,block5,block6,block7,block8, decexpkey); Lup1 = gf128_mul2(Lup8); Lup2 = gf128_mul2(Lup1); Lup3 = gf128_mul2(Lup2); Lup4 = gf128_mul2(Lup3); Lup5 = gf128_mul2(Lup4); Lup6 = gf128_mul2(Lup5); Lup7 = gf128_mul2(Lup6); Lup8 = gf128_mul2(Lup7); rho_inv(block1, W, Wtmp); rho_inv(block2, W, Wtmp); rho_inv(block3, W, Wtmp); rho_inv(block4, W, Wtmp); rho_inv(block5, W, Wtmp); rho_inv(block6, W, Wtmp); rho_inv(block7, W, Wtmp); rho_inv(block8, W, Wtmp); AES_DECRYPT8(block1,block2,block3,block4,block5,block6,block7,block8, decexpkey); block1 ^= Lup1; block2 ^= Lup2; block3 ^= Lup3; block4 ^= Lup4; block5 ^= Lup5; block6 ^= Lup6; block7 ^= Lup7; block8 ^= Lup8; checksum ^= block1 ^ block2 ^ block3 ^ block4; checksum ^= block5 ^ block6 ^ block7 ^ block8; _mm_storeu_si128((__m128i*)out, byte_swap(block1)); _mm_storeu_si128((__m128i*)out+1, byte_swap(block2)); _mm_storeu_si128((__m128i*)out+2, byte_swap(block3)); _mm_storeu_si128((__m128i*)out+3, byte_swap(block4)); _mm_storeu_si128((__m128i*)out+4, byte_swap(block5)); _mm_storeu_si128((__m128i*)out+5, byte_swap(block6)); _mm_storeu_si128((__m128i*)out+6, byte_swap(block7)); _mm_storeu_si128((__m128i*)out+7, byte_swap(block8)); in += 8*16; out += 8*16; remaining -= 8*16; } Lup = Lup8; Ldown = Ldown8; /* Decrypt */ while (remaining > 16) { Lup = gf128_mul2(Lup); Ldown = gf128_mul2(Ldown); block = byte_swap(_mm_loadu_si128((__m128i*)in)); block ^= Ldown; block = AES_decrypt(block, decexpkey); /* (X,W') = rho^-1(block, W) */ rho_inv(block, W, Wtmp); block = AES_decrypt(block, decexpkey); block ^= Lup; checksum ^= block; _mm_storeu_si128((__m128i*)out, byte_swap(block)); in += 16; out += 16; remaining -= 16; } Lup = gf128_mul7(Lup); Ldown = gf128_mul7(Ldown); if (remaining < 16) { Lup = gf128_mul7(Lup); Ldown = gf128_mul7(Ldown); } block = _mm_loadu_si128((__m128i*)in); block = byte_swap(block); block ^= Ldown; block = AES_decrypt(block, decexpkey); /* (X,W') = rho^-1(block, W) */ rho_inv(block, W, Wtmp); block = AES_decrypt(block, decexpkey); block ^= Lup; /* block now contains M[l] = M[l+1] */ checksum ^= block; /* checksum now contains M*[l] */ in += 16; /* output last (maybe partial) plaintext block */ _mm_storeu_si128((__m128i*)buf, byte_swap(checksum)); memcpy(out, buf, remaining); /* work on M[l+1] */ Lup = gf128_mul2(Lup); Ldown = gf128_mul2(Ldown); block ^= Lup; block = AES_encrypt(block, expkey); /* (Y,W') = rho(block, W) */ rho(block, W, Wtmp); block = AES_encrypt(block, expkey); block ^= Ldown; /* block now contains C'[l+1] */ _mm_storeu_si128((__m128i*)buf, byte_swap(block)); if (memcmp(in, buf, remaining) != 0) { return -1; } if (remaining < 16) { _mm_storeu_si128((__m128i*)buf, byte_swap(checksum)); if (buf[remaining] != 0x80) { return -1; } for (i = remaining+1; i < 16; i++) { if (buf[i] != 0) { return -1; } } } return 0; }
bool MessageAuthenticationCode::Verify(const byte *macIn) { SecByteBlock mac(DigestSize()); Final(mac); return memcmp(mac, macIn, DigestSize()) == 0; }
int crypto_aead_encrypt( unsigned char *c,unsigned long long *clen, const unsigned char *m,unsigned long long mlen, const unsigned char *ad,unsigned long long adlen, const unsigned char *nsec, const unsigned char *npub, const unsigned char *k ) { const unsigned char* in = m; unsigned char* out = c; unsigned long long remaining = mlen; uint8_t buf[16] = { 0 }; __m128i W, Wtmp; __m128i block, Lup, Ldown; __m128i Lup1, Lup2, Lup3, Lup4, Lup5, Lup6, Lup7, Lup8; __m128i Ldown1, Ldown2, Ldown3, Ldown4, Ldown5, Ldown6, Ldown7, Ldown8; __m128i block1, block2, block3, block4; __m128i block5, block6, block7, block8; __m128i checksum = { 0 }; __m128i LL = { 0 }; __m128i expkey[11]; /* key schedule */ AES_set_encrypt_key(k, expkey); /* set ouput length */ *clen = mlen + 16; LL = AES_encrypt(LL, expkey); /* LL = AES(0) */ Lup = LL; Ldown = gf128_mul3(gf128_mul3(LL)); /* Ldown = 3^2*LL */ /* mac AD + nonce */ W = mac(ad, adlen, npub, LL, expkey); Lup8 = Lup; Ldown8 = Ldown; while (remaining > 8*16) { Lup1 = gf128_mul2(Lup8); Lup2 = gf128_mul2(Lup1); Lup3 = gf128_mul2(Lup2); Lup4 = gf128_mul2(Lup3); Lup5 = gf128_mul2(Lup4); Lup6 = gf128_mul2(Lup5); Lup7 = gf128_mul2(Lup6); Lup8 = gf128_mul2(Lup7); block1 = byte_swap(_mm_loadu_si128((__m128i*)in)); block2 = byte_swap(_mm_loadu_si128((__m128i*)in+1)); block3 = byte_swap(_mm_loadu_si128((__m128i*)in+2)); block4 = byte_swap(_mm_loadu_si128((__m128i*)in+3)); block5 = byte_swap(_mm_loadu_si128((__m128i*)in+4)); block6 = byte_swap(_mm_loadu_si128((__m128i*)in+5)); block7 = byte_swap(_mm_loadu_si128((__m128i*)in+6)); block8 = byte_swap(_mm_loadu_si128((__m128i*)in+7)); checksum ^= block1 ^ block2 ^ block3 ^ block4; checksum ^= block5 ^ block6 ^ block7 ^ block8; block1 ^= Lup1; block2 ^= Lup2; block3 ^= Lup3; block4 ^= Lup4; block5 ^= Lup5; block6 ^= Lup6; block7 ^= Lup7; block8 ^= Lup8; AES_ENCRYPT8(block1,block2,block3,block4,block5,block6,block7,block8, expkey); Ldown1 = gf128_mul2(Ldown8); Ldown2 = gf128_mul2(Ldown1); Ldown3 = gf128_mul2(Ldown2); Ldown4 = gf128_mul2(Ldown3); Ldown5 = gf128_mul2(Ldown4); Ldown6 = gf128_mul2(Ldown5); Ldown7 = gf128_mul2(Ldown6); Ldown8 = gf128_mul2(Ldown7); rho(block1, W, Wtmp); rho(block2, W, Wtmp); rho(block3, W, Wtmp); rho(block4, W, Wtmp); rho(block5, W, Wtmp); rho(block6, W, Wtmp); rho(block7, W, Wtmp); rho(block8, W, Wtmp); AES_ENCRYPT8(block1,block2,block3,block4,block5,block6,block7,block8, expkey); block1 ^= Ldown1; block2 ^= Ldown2; block3 ^= Ldown3; block4 ^= Ldown4; block5 ^= Ldown5; block6 ^= Ldown6; block7 ^= Ldown7; block8 ^= Ldown8; _mm_storeu_si128((__m128i*)out, byte_swap(block1)); _mm_storeu_si128((__m128i*)out+1, byte_swap(block2)); _mm_storeu_si128((__m128i*)out+2, byte_swap(block3)); _mm_storeu_si128((__m128i*)out+3, byte_swap(block4)); _mm_storeu_si128((__m128i*)out+4, byte_swap(block5)); _mm_storeu_si128((__m128i*)out+5, byte_swap(block6)); _mm_storeu_si128((__m128i*)out+6, byte_swap(block7)); _mm_storeu_si128((__m128i*)out+7, byte_swap(block8)); in += 8*16; out += 8*16; remaining -= 8*16; } Lup = Lup8; Ldown = Ldown8; while (remaining > 16) { Lup = gf128_mul2(Lup); Ldown = gf128_mul2(Ldown); block = _mm_loadu_si128((__m128i*)in); block = byte_swap(block); checksum ^= block; block ^= Lup; block = AES_encrypt(block, expkey); /* (Y,W') = rho(block, W) */ rho(block, W, Wtmp); block = AES_encrypt(block, expkey); block ^= Ldown; _mm_storeu_si128((__m128i*)out, byte_swap(block)); in += 16; out += 16; remaining -= 16; } /* XOR checksum into last block (padded if necessary) */ memcpy(buf, in, remaining); Lup = gf128_mul7(Lup); Ldown = gf128_mul7(Ldown); if (remaining < 16) { buf[remaining] = 0x80; Lup = gf128_mul7(Lup); Ldown = gf128_mul7(Ldown); } block = _mm_loadu_si128((__m128i*)buf); block = byte_swap(block); checksum ^= block; block = checksum ^ Lup; block = AES_encrypt(block, expkey); /* (Y,W') = rho(block, W) */ rho(block, W, Wtmp); block = AES_encrypt(block, expkey); block ^= Ldown; _mm_storeu_si128((__m128i*)out, byte_swap(block)); out += 16; /* could stop here if remaining == 0 */ if (remaining == 0) return 0; /* Duplicate last block */ Lup = gf128_mul2(Lup); Ldown = gf128_mul2(Ldown); block = checksum ^ Lup; block = AES_encrypt(block, expkey); /* (Y,W') = rho(block, W) */ rho(block, W, Wtmp); block = AES_encrypt(block, expkey); block ^= Ldown; _mm_storeu_si128((__m128i*)buf, byte_swap(block)); memcpy(out, buf, remaining); return 0; }
static MAStreamConn& getStreamConn(MAHandle conn) { MAConn& mac(getConn(conn)); MYASSERT(mac.type == eStreamConn, ERR_CONN_NOT_STREAM); return (MAStreamConn&)mac; }
net_interface_imp::net_interface_imp() { total_devs = 0; if (pcap_findalldevs(&all_devs, err_buf) == -1) // Retrieve the device list on the local machine. { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_findalldevs error %s", err_buf); } else { for (dev = all_devs; dev; dev = dev->next) { // store the valid IPv4 addresses associated with the device std::vector<std::string> device_ip_addresses; pcap_addr_t * dev_addr; for (dev_addr = dev->addresses; dev_addr != NULL; dev_addr = dev_addr->next) { if (dev_addr->addr->sa_family == AF_INET && dev_addr->addr) { char ip_str[INET_ADDRSTRLEN] = { 0 }; inet_ntop(AF_INET, &((struct sockaddr_in *)dev_addr->addr)->sin_addr, ip_str, INET_ADDRSTRLEN); device_ip_addresses.push_back(std::string(ip_str)); } } all_ip_addresses.push_back(device_ip_addresses); total_devs++; } /****************************** Find Adapter Info ***************************/ IP_ADAPTER_INFO * AdapterInfo; ULONG AIS; DWORD status; AdapterInfo = (IP_ADAPTER_INFO *)calloc(total_devs, sizeof(IP_ADAPTER_INFO)); AIS = sizeof(IP_ADAPTER_INFO) * total_devs; if (GetAdaptersInfo(AdapterInfo, &AIS) == ERROR_BUFFER_OVERFLOW) { free(AdapterInfo); AdapterInfo = (IP_ADAPTER_INFO *)calloc(1, AIS); if (AdapterInfo == NULL) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Allocating memory needed to call GetAdaptersinfo.", dev->name); return; } status = GetAdaptersInfo(AdapterInfo, &AIS); if (status != ERROR_SUCCESS) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "GetAdaptersInfo call in net_interface_imp.cpp failed.", dev->name); free(AdapterInfo); return; } } PIP_ADAPTER_INFO pAdapterInfo = NULL; for (dev = all_devs; dev; dev = dev->next) { uint64_t dev_mac_addr = 0; for (pAdapterInfo = AdapterInfo; pAdapterInfo != NULL; pAdapterInfo = pAdapterInfo->Next) { if (strstr(dev->name, pAdapterInfo->AdapterName) != 0) { utility::MacAddr mac( pAdapterInfo->Address[0], pAdapterInfo->Address[1], pAdapterInfo->Address[2], pAdapterInfo->Address[3], pAdapterInfo->Address[4], pAdapterInfo->Address[5]); dev_mac_addr = mac.tovalue(); break; } } all_mac_addresses.push_back(dev_mac_addr); } free(AdapterInfo); } if (total_devs == 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "No interfaces found! Make sure WinPcap is installed."); } pcap_interface = nullptr; }
void options::parse(int argc, char* argv[]) { addp::options::parse(argc, argv); if(_vm.count("action") == 0) { std::cerr << "No action given" << std::endl << std::endl; usage(); std::exit(1); } /* * discover [device] * reboot <device> [passwd] * config <device> <ip> <netmask> <gateway> [passwd] * dhcp <device> <on|off> [passwd] */ size_t min = 0; size_t max = 0; const std::string& action = this->action(); if(action == "discover") { min = 0; max = 0; } else { // must have a specific device address for further actions if(boost::lexical_cast<addp::mac_address>(mac()) == addp::MAC_ADDR_BROADCAST) { std::cerr << "Please select a device's mac address" << std::endl << std::endl; usage(); std::exit(1); } if(action == "reboot") { min = 0; max = 1; } else if(action == "config") { min = 3; max = 4; } else if(action == "dhcp") { min = 1; max = 2; } else { std::cerr << "Unknown action \"" << action << "\"" << std::endl << std::endl; usage(); std::exit(1); } } size_t count = args().size(); if(count < min || count > max) { usage(); std::exit(1); } // optional password is always the last argument _password_index = max - 1; }
vmxnet3::vmxnet3(hw::PCI_Device& d, const uint16_t mtu) : Link(Link_protocol{{this, &vmxnet3::transmit}, mac()}, bufstore_), m_pcidev(d), m_mtu(mtu), bufstore_{1024, buffer_size_for_mtu(mtu)} { INFO("vmxnet3", "Driver initializing (rev=%#x)", d.rev_id()); assert(d.rev_id() == REVISION_ID); // find and store capabilities d.parse_capabilities(); // find BARs etc. d.probe_resources(); if (d.msix_cap()) { d.init_msix(); uint8_t msix_vectors = d.get_msix_vectors(); INFO2("[x] Device has %u MSI-X vectors", msix_vectors); assert(msix_vectors >= 3); if (msix_vectors > 2 + NUM_RX_QUEUES) msix_vectors = 2 + NUM_RX_QUEUES; for (int i = 0; i < msix_vectors; i++) { auto irq = Events::get().subscribe(nullptr); this->irqs.push_back(irq); d.setup_msix_vector(SMP::cpu_id(), IRQ_BASE + irq); } Events::get().subscribe(irqs[0], {this, &vmxnet3::msix_evt_handler}); Events::get().subscribe(irqs[1], {this, &vmxnet3::msix_xmit_handler}); for (int q = 0; q < NUM_RX_QUEUES; q++) Events::get().subscribe(irqs[2 + q], {this, &vmxnet3::msix_recv_handler}); } else { assert(0 && "This driver does not support legacy IRQs"); } // dma areas this->iobase = d.get_bar(PCI_BAR_VD); assert(this->iobase); this->ptbase = d.get_bar(PCI_BAR_PT); assert(this->ptbase); // verify and select version bool ok = check_version(); assert(ok); // reset device ok = reset(); assert(ok); // get mac address retrieve_hwaddr(); // check link status auto link_spd = check_link(); if (link_spd) { INFO2("Link up at %u Mbps", link_spd); } else { INFO2("LINK DOWN! :("); return; } // set MAC set_hwaddr(this->hw_addr); // initialize DMA areas this->dma = (vmxnet3_dma*) memalign(VMXNET3_DMA_ALIGN, sizeof(vmxnet3_dma)); memset(this->dma, 0, sizeof(vmxnet3_dma)); auto& queues = dma->queues; // setup tx queues queues.tx.cfg.desc_address = (uintptr_t) &dma->tx_desc; queues.tx.cfg.comp_address = (uintptr_t) &dma->tx_comp; queues.tx.cfg.num_desc = vmxnet3::NUM_TX_DESC; queues.tx.cfg.num_comp = VMXNET3_NUM_TX_COMP; queues.tx.cfg.intr_index = 1; // temp rxq buffer storage memset(tx.buffers, 0, sizeof(tx.buffers)); // setup rx queues for (int q = 0; q < NUM_RX_QUEUES; q++) { memset(rx[q].buffers, 0, sizeof(rx[q].buffers)); rx[q].desc0 = &dma->rx0_desc[0]; rx[q].desc1 = &dma->rx1_desc[0]; rx[q].comp = &dma->rx_comp[0]; rx[q].index = q; auto& queue = queues.rx[q]; queue.cfg.desc_address[0] = (uintptr_t) rx[q].desc0; queue.cfg.desc_address[1] = (uintptr_t) rx[q].desc1; queue.cfg.comp_address = (uintptr_t) rx[q].comp; queue.cfg.num_desc[0] = vmxnet3::NUM_RX_DESC; queue.cfg.num_desc[1] = vmxnet3::NUM_RX_DESC; queue.cfg.num_comp = VMXNET3_NUM_RX_COMP; queue.cfg.driver_data_len = sizeof(vmxnet3_rx_desc) + 2 * sizeof(vmxnet3_rx_desc); queue.cfg.intr_index = 2 + q; } auto& shared = dma->shared; // setup shared physical area shared.magic = VMXNET3_REV1_MAGIC; shared.misc.guest_info.arch = (sizeof(void*) == 4) ? GOS_BITS_32_BITS : GOS_BITS_64_BITS; shared.misc.guest_info.type = GOS_TYPE_LINUX; shared.misc.version = VMXNET3_VERSION_MAGIC; shared.misc.version_support = 1; shared.misc.upt_version_support = 1; shared.misc.upt_features = UPT1_F_RXVLAN; shared.misc.driver_data_address = (uintptr_t) &dma; shared.misc.queue_desc_address = (uintptr_t) &dma->queues; shared.misc.driver_data_len = sizeof(vmxnet3_dma); shared.misc.queue_desc_len = sizeof(vmxnet3_queues); shared.misc.mtu = packet_len(); // 60-9000 shared.misc.num_tx_queues = 1; shared.misc.num_rx_queues = NUM_RX_QUEUES; shared.interrupt.mask_mode = VMXNET3_IT_AUTO | (VMXNET3_IMM_AUTO << 2); shared.interrupt.num_intrs = 2 + NUM_RX_QUEUES; shared.interrupt.event_intr_index = 0; memset(shared.interrupt.moderation_level, UPT1_IML_ADAPTIVE, VMXNET3_MAX_INTRS); shared.interrupt.control = 0x1; // disable all shared.rx_filter.mode = VMXNET3_RXM_UCAST | VMXNET3_RXM_BCAST | VMXNET3_RXM_ALL_MULTI; // location of shared area to device uintptr_t shabus = (uintptr_t) &shared; mmio_write32(this->iobase + 0x10, shabus); // shared low mmio_write32(this->iobase + 0x18, 0x0); // shared high // activate device int status = command(VMXNET3_CMD_ACTIVATE_DEV); if (status) { assert(0 && "Failed to activate device"); } // initialize and fill RX queue... for (int q = 0; q < NUM_RX_QUEUES; q++) { refill(rx[q]); } // deferred transmit this->deferred_irq = Events::get().subscribe(handle_deferred); // enable interrupts enable_intr(0); enable_intr(1); for (int q = 0; q < NUM_RX_QUEUES; q++) enable_intr(2 + q); }
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) { std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC()); unsigned int macSize = mac->DigestSize(); SecByteBlock tempMac; SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; actualMac.resize(macSize); unsigned long tempLocation; unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; macFileLocation = 0; HashFilter verifier(*mac, new ArraySink(actualMac, actualMac.size())); // FileSink verifier("c:\\dt.tmp"); FileStore file(moduleFilename); #ifdef CRYPTOPP_WIN32_AVAILABLE // try to hash from memory first HMODULE h = GetModuleHandle(moduleFilename); const byte *memBase = (const byte *)h; IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)h; IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)((byte *)h + ph->e_lfanew); IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); DWORD nSections = phnt->FileHeader.NumberOfSections; DWORD currentFilePos = 0; while (nSections--) { switch (phs->Characteristics) { default: break; case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); const byte *sectionMemStart = memBase + phs->VirtualAddress; unsigned int sectionFileStart = phs->PointerToRawData; unsigned int subSectionStart = 0, nextSubSectionStart; do { const byte *subSectionMemStart = sectionMemStart + subSectionStart; unsigned int subSectionFileStart = sectionFileStart + subSectionStart; unsigned int subSectionSize = sectionSize - subSectionStart; nextSubSectionStart = 0; unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT}; for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++) { const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]]; const byte *entryMemStart = memBase + entry.VirtualAddress; if (subSectionMemStart <= entryMemStart && entryMemStart < subSectionMemStart + subSectionSize) { subSectionSize = entryMemStart - subSectionMemStart; nextSubSectionStart = entryMemStart - sectionMemStart + entry.Size; } } file.TransferTo(verifier, subSectionFileStart - currentFilePos); if (subSectionMemStart <= expectedModuleMac && expectedModuleMac < subSectionMemStart + subSectionSize) { // skip over the MAC verifier.Put(subSectionMemStart, expectedModuleMac - subSectionMemStart); verifier.Put(expectedModuleMac + macSize, subSectionSize - macSize - (expectedModuleMac - subSectionMemStart)); macFileLocation = subSectionFileStart + (expectedModuleMac - subSectionMemStart); } else verifier.Put(subSectionMemStart, subSectionSize); file.Skip(subSectionSize); currentFilePos = subSectionFileStart + subSectionSize; subSectionStart = nextSubSectionStart; } while (nextSubSectionStart != 0); } phs++; } #endif file.TransferAllTo(verifier); #ifdef CRYPTOPP_WIN32_AVAILABLE // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // hash from disk instead if (memcmp(expectedModuleMac, actualMac, macSize) != 0) { OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); file.Initialize(MakeParameters("InputFileName", moduleFilename)); verifier.Detach(new ArraySink(actualMac, actualMac.size())); if (macFileLocation) { file.TransferTo(verifier, macFileLocation); file.Skip(macSize); } file.TransferAllTo(verifier); } #endif if (memcmp(expectedModuleMac, actualMac, macSize) == 0) return true; #ifdef CRYPTOPP_WIN32_AVAILABLE std::string hexMac; HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); OutputDebugString((moduleFilename + (" integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); #endif return false; }
//////////////////////////////////////////////////////////////////////////////// // Simulation::init_terminals // // // // initializes terminals for a new iteration // //////////////////////////////////////////////////////////////////////////////// void Simulation::init_terminals(){ adapt_struct adapt (sim_par.get_TxMode(), sim_par.get_AdaptMode(), sim_par.get_TxPowerMax(), sim_par.get_TxPowerMin(), sim_par.get_TxPowerStepUp(),sim_par.get_TxPowerStepDown(), sim_par.get_TargetPER(),sim_par.get_LAMaxSucceedCounter(), sim_par.get_LAFailLimit(), sim_par.get_UseRxMode()); mac_struct mac(sim_par.get_RetryLimit(), sim_par.get_RTSThreshold(), sim_par.get_FragmentationThresh(), sim_par.get_QueueSize(), sim_par.get_set_BA_agg()); PHY_struct phy(sim_par.get_NoiseVariance(), sim_par.get_CCASensitivity()); traffic_struct tr_dl(sim_par.get_DataRateDL(), sim_par.get_PacketLength(), sim_par.get_ArrivalTime()); traffic_struct tr_ul(sim_par.get_DataRateUL(), sim_par.get_PacketLength(), sim_par.get_ArrivalTime()); timestamp tr_time = sim_par.get_TransientTime(); for (unsigned i = 0; i < sim_par.get_NumberAPs(); i++) { AccessPoint* ap = new AccessPoint(sim_par.get_APPosition(i), &main_sch, ch, &randgent, &log, mac, phy, tr_time); term_vector.push_back(ap); if (log(log_type::setup)) log << *ap << " created at position " << sim_par.get_APPosition(i) << '\n' << endl; } double cell_radius = sim_par.get_Radius(); // Array containing the amount of connections belonging to each AC unsigned ppArray[5] = {round(2*sim_par.get_ppAC_BK()*sim_par.get_NumberStas()), round(2*sim_par.get_ppAC_BE()*sim_par.get_NumberStas()), round(2*sim_par.get_ppAC_VI()*sim_par.get_NumberStas()), round(2*sim_par.get_ppAC_VO()*sim_par.get_NumberStas()), round(2*sim_par.get_ppLegacy()*sim_par.get_NumberStas())}; unsigned sum = 0; for(int k = 0; k < 5; k++) { sum = sum + ppArray[k]; } int diff = sum - 2*sim_par.get_NumberStas(); if(diff > 0) { for(int k = 0; k < 5; k++) { while(ppArray[k] > 0 && diff > 0){ ppArray[k]--; diff--; } } } if(diff < 0) { ppArray[0] = (-1)*diff; } vector<int> noZe_ppArray; accCat MS_AC = AC_BK; accCat AP_AC = AC_BK; int idx = 0; for (unsigned i = 0; i < sim_par.get_NumberStas(); i++) { // Vector containing elements of ppArray that are non-zero noZe_ppArray.clear(); for(int k = 0; k < 5; k++) { if(ppArray[k] != 0) noZe_ppArray.push_back(k); } // Choose one access category randomly if(noZe_ppArray.size() != 0) { idx = randgent.from_vec(noZe_ppArray); MS_AC = allACs[idx]; ppArray[idx]--; } // if just one mobile station, then distance = cell radius Position pos(cell_radius,0); // else Stas are uniformly distributed if (sim_par.get_NumberStas() > 1) { do { pos = Position (randgent.uniform(-cell_radius,cell_radius), randgent.uniform(-cell_radius,cell_radius)); } while(pos.distance() > cell_radius); } MobileStation* ms = new MobileStation(pos, &main_sch, ch, &randgent, &log, mac, phy, tr_time); term_vector.push_back(ms); double min_dist = HUGE_VAL; int min_index = -1; for (unsigned count = 0; count < sim_par.get_NumberAPs(); count++) { double dist = pos.distance(sim_par.get_APPosition(count)); if (dist < min_dist) { min_dist = dist; min_index = count; } } // Vector containing elements of ppArray that are non-zero noZe_ppArray.clear(); for(int k = 0; k < 5; k++) { if(ppArray[k] != 0) noZe_ppArray.push_back(k); } // Choose one access category randomly if(noZe_ppArray.size() != 0) { idx = randgent.from_vec(noZe_ppArray); AP_AC = allACs[idx]; ppArray[idx]--; } // Connect mobile terminal to closest AP connect_two(term_vector[min_index], AP_AC, ms, MS_AC, ch, adapt, tr_dl, tr_ul); if (log(log_type::setup)) log << *ms << " created at position " << pos << " with distance " << min_dist << " m to " << *term_vector[min_index] << "\nMobile station AC: "<< MS_AC << ". Access Point AC: " << AP_AC << "." <<endl; } if (log(log_type::setup)) log_connections(); }
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) { std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC()); unsigned int macSize = mac->DigestSize(); SecByteBlock tempMac; SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; actualMac.resize(macSize); unsigned long tempLocation; unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; macFileLocation = 0; MeterFilter verifier(new HashFilter(*mac, new ArraySink(actualMac, actualMac.size()))); // MeterFilter verifier(new FileSink("c:\\dt.tmp")); std::ifstream moduleStream; #ifdef CRYPTOPP_WIN32_AVAILABLE HMODULE h; { char moduleFilenameBuf[MAX_PATH] = ""; if (moduleFilename == NULL) { #if (_MSC_VER >= 1400 && !defined(_STLPORT_VERSION)) // ifstream doesn't support wide filename on other compilers wchar_t wideModuleFilename[MAX_PATH]; if (GetModuleFileNameW(s_hModule, wideModuleFilename, MAX_PATH) > 0) { moduleStream.open(wideModuleFilename, std::ios::in | std::ios::binary); h = GetModuleHandleW(wideModuleFilename); } else #endif { GetModuleFileNameA(s_hModule, moduleFilenameBuf, MAX_PATH); moduleFilename = moduleFilenameBuf; } } #endif if (moduleFilename != NULL) { moduleStream.open(moduleFilename, std::ios::in | std::ios::binary); #ifdef CRYPTOPP_WIN32_AVAILABLE h = GetModuleHandleA(moduleFilename); moduleFilename = NULL; } #endif } if (!moduleStream) { #ifdef CRYPTOPP_WIN32_AVAILABLE OutputDebugString("Crypto++ DLL integrity check failed. Cannot open file for reading."); #endif return false; } FileStore file(moduleStream); #ifdef CRYPTOPP_WIN32_AVAILABLE // try to hash from memory first const byte *memBase = (const byte *)h; const IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)memBase; const IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)(memBase + ph->e_lfanew); const IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); DWORD nSections = phnt->FileHeader.NumberOfSections; size_t currentFilePos = 0; size_t checksumPos = (byte *)&phnt->OptionalHeader.CheckSum - memBase; size_t checksumSize = sizeof(phnt->OptionalHeader.CheckSum); size_t certificateTableDirectoryPos = (byte *)&phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] - memBase; size_t certificateTableDirectorySize = sizeof(phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]); size_t certificateTablePos = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; size_t certificateTableSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); while (nSections--) { switch (phs->Characteristics) { default: break; case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); const byte *sectionMemStart = memBase + phs->VirtualAddress; unsigned int sectionFileStart = phs->PointerToRawData; size_t subSectionStart = 0, nextSubSectionStart; do { const byte *subSectionMemStart = sectionMemStart + subSectionStart; size_t subSectionFileStart = sectionFileStart + subSectionStart; size_t subSectionSize = sectionSize - subSectionStart; nextSubSectionStart = 0; unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT}; for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++) { const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]]; const byte *entryMemStart = memBase + entry.VirtualAddress; if (subSectionMemStart <= entryMemStart && entryMemStart < subSectionMemStart + subSectionSize) { subSectionSize = entryMemStart - subSectionMemStart; nextSubSectionStart = entryMemStart - sectionMemStart + entry.Size; } } #if defined(_MSC_VER) && _MSC_VER >= 1400 // first byte of _CRT_DEBUGGER_HOOK gets modified in memory by the debugger invisibly, so read it from file if (IsDebuggerPresent()) { if (subSectionMemStart <= (byte *)&_CRT_DEBUGGER_HOOK && (byte *)&_CRT_DEBUGGER_HOOK < subSectionMemStart + subSectionSize) { subSectionSize = (byte *)&_CRT_DEBUGGER_HOOK - subSectionMemStart; nextSubSectionStart = (byte *)&_CRT_DEBUGGER_HOOK - sectionMemStart + 1; } } #endif if (subSectionMemStart <= expectedModuleMac && expectedModuleMac < subSectionMemStart + subSectionSize) { // found stored MAC macFileLocation = (unsigned long)(subSectionFileStart + (expectedModuleMac - subSectionMemStart)); verifier.AddRangeToSkip(0, macFileLocation, macSize); } file.TransferTo(verifier, subSectionFileStart - currentFilePos); verifier.Put(subSectionMemStart, subSectionSize); file.Skip(subSectionSize); currentFilePos = subSectionFileStart + subSectionSize; subSectionStart = nextSubSectionStart; } while (nextSubSectionStart != 0); } phs++; } #endif file.TransferAllTo(verifier); #ifdef CRYPTOPP_WIN32_AVAILABLE // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // hash from disk instead if (!VerifyBufsEqual(expectedModuleMac, actualMac, macSize)) { OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); moduleStream.clear(); moduleStream.seekg(0); verifier.Initialize(MakeParameters(Name::OutputBuffer(), ByteArrayParameter(actualMac, (unsigned int)actualMac.size()))); // verifier.Initialize(MakeParameters(Name::OutputFileName(), (const char *)"c:\\dt2.tmp")); verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); verifier.AddRangeToSkip(0, macFileLocation, macSize); FileStore(moduleStream).TransferAllTo(verifier); } #endif if (VerifyBufsEqual(expectedModuleMac, actualMac, macSize)) return true; #ifdef CRYPTOPP_WIN32_AVAILABLE std::string hexMac; HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); OutputDebugString((("Crypto++ DLL integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); #endif return false; }
void SmartMote::work(){ while(1){ /* se l'ora corrente è di scansione */ if(!(RTCC.hours() % 6) && (RTCC.minutes() >= 0x00 && RTCC.minutes() <= 0x05)){ AString data; AString message; AString answer; /* abilito il core timer (la prima volta è già abilitato) */ System::wakeCoreTimer(); /* accendo il led verde */ turnOnGreen(); /* accendo la seriale */ openUART(); /* accendo l'i2c */ openI2C(); /* prendo le misure */ data += mac(); data += luminosity(); data += ambientTempAndHum(); data += groundTemp(); data += groundHum(); data += battey(); /* compongo la stringa */ message += _PHP_CHUNK1; /* inserisco l'hostname */ message += getHost(); /* inserisco la seconda parte di richiesta http */ message += _PHP_CHUNK2; /* inserisco la lunghezza dei dati */ message += AString(static_cast<sint32>(data.size())); /* inserisco la terza parte di richiesta http */ message += _PHP_CHUNK3; /* inserisco i dati */ message += data; /* se fallisce l'inizializzazione dell'esp */ if(!m_net.initialize()){ /* notifico l'errore */ error(); } /* se fallisce l'avvio del dhcp */ if(!m_net.setDhcp(true)){ /* notifico l'errore */ error(); } /* se fallisce la connessione alla rete */ if(!m_net.joinAP(getSSID(), getKey())){ /* notifico l'errore */ error(); } /* se fallisce la connessione al server */ if(!m_net.connectToHost(getHost(), 80)){ /* notifico l'errore */ error(); } /* invio i dati */ m_net.send(message); /* aspetto l'ok */ m_net.waitForData(answer); /* notifico l'ok o lerrore dell'invio */ wasSuccess(answer); /* lascio l'ap */ m_net.leaveAP(); /* libero la memoria occupata dalle stringhe */ message.clear(); data.clear(); answer.clear(); } /* calcolo del tempo di sleep per il wifi */ m_net.sleep(getSleepTime()); /* punto la prossima sveglia */ setNextAlarm(); /* spengo il led verde */ turnOffGreen(); /* spengo l'uart */ closeUART(); /* chiudo l'i2c */ closeI2C(); /* spengo il core timer */ System::stopCoreTimer(); /* vado a dormire */ System::sleep(); } }
bool ValidateXMACC() { typedef XMACC<MD5> XMACC_MD5; const byte keys[2][XMACC_MD5::KEYLENGTH]={ {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb}, {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98}}; const word32 counters[2]={0xccddeeff, 0x76543210}; const char *TestVals[7]={ "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890"}; const byte output[2][7][XMACC_MD5::DIGESTSIZE]={ {{0xcc,0xdd,0xef,0x00,0xfa,0x89,0x54,0x92,0x86,0x32,0xda,0x2a,0x3f,0x29,0xc5,0x52,0xa0,0x0d,0x05,0x13}, {0xcc,0xdd,0xef,0x01,0xae,0xdb,0x8b,0x7b,0x69,0x71,0xc7,0x91,0x71,0x48,0x9d,0x18,0xe7,0xdf,0x9d,0x5a}, {0xcc,0xdd,0xef,0x02,0x5e,0x01,0x2e,0x2e,0x4b,0xc3,0x83,0x62,0xc2,0xf4,0xe6,0x18,0x1c,0x44,0xaf,0xca}, {0xcc,0xdd,0xef,0x03,0x3e,0xa9,0xf1,0xe0,0x97,0x91,0xf8,0xe2,0xbe,0xe0,0xdf,0xf3,0x41,0x03,0xb3,0x5a}, {0xcc,0xdd,0xef,0x04,0x2e,0x6a,0x8d,0xb9,0x72,0xe3,0xce,0x9f,0xf4,0x28,0x45,0xe7,0xbc,0x80,0xa9,0xc7}, {0xcc,0xdd,0xef,0x05,0x1a,0xd5,0x40,0x78,0xfb,0x16,0x37,0xfc,0x7a,0x1d,0xce,0xb4,0x77,0x10,0xb2,0xa0}, {0xcc,0xdd,0xef,0x06,0x13,0x2f,0x11,0x47,0xd7,0x1b,0xb5,0x52,0x36,0x51,0x26,0xb0,0x96,0xd7,0x60,0x81}}, {{0x76,0x54,0x32,0x11,0xe9,0xcb,0x74,0x32,0x07,0x93,0xfe,0x01,0xdd,0x27,0xdb,0xde,0x6b,0x77,0xa4,0x56}, {0x76,0x54,0x32,0x12,0xcd,0x55,0x87,0x5c,0xc0,0x35,0x85,0x99,0x44,0x02,0xa5,0x0b,0x8c,0xe7,0x2c,0x68}, {0x76,0x54,0x32,0x13,0xac,0xfd,0x87,0x50,0xc3,0x8f,0xcd,0x58,0xaa,0xa5,0x7e,0x7a,0x25,0x63,0x26,0xd1}, {0x76,0x54,0x32,0x14,0xe3,0x30,0xf5,0xdd,0x27,0x2b,0x76,0x22,0x7f,0xaa,0x90,0x73,0x6a,0x48,0xdb,0x00}, {0x76,0x54,0x32,0x15,0xfc,0x57,0x00,0x20,0x7c,0x9d,0xf6,0x30,0x6f,0xbd,0x46,0x3e,0xfb,0x8a,0x2c,0x60}, {0x76,0x54,0x32,0x16,0xfb,0x0f,0xd3,0xdf,0x4c,0x4b,0xc3,0x05,0x9d,0x63,0x1e,0xba,0x25,0x2b,0xbe,0x35}, {0x76,0x54,0x32,0x17,0xc6,0xfe,0xe6,0x5f,0xb1,0x35,0x8a,0xf5,0x32,0x7a,0x80,0xbd,0xb8,0x72,0xee,0xae}}}; byte digest[XMACC_MD5::DIGESTSIZE]; bool pass=true, fail; cout << "\nXMACC/MD5 validation suite running...\n"; for (int k=0; k<2; k++) { XMACC_MD5 mac(keys[k], counters[k]); cout << "\nKEY: "; for (int j=0;j<XMACC_MD5::KEYLENGTH;j++) cout << setw(2) << setfill('0') << hex << (int)keys[k][j]; cout << " COUNTER: 0x" << hex << counters[k] << endl << endl; for (int i=0;i<7;i++) { mac.Update((byte *)TestVals[i], strlen(TestVals[i])); mac.Final(digest); fail = memcmp(digest, output[k][i], XMACC_MD5::DIGESTSIZE) || !mac.VerifyDigest(output[k][i], (byte *)TestVals[i], strlen(TestVals[i])); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); for (int j=0;j<XMACC_MD5::DIGESTSIZE;j++) cout << setw(2) << setfill('0') << hex << (int)digest[j]; cout << " \"" << TestVals[i] << '\"' << endl; } } return pass; }
int main( int argc, char *argv[] ) { printf("%s\n",mac("192.168.48.2")); }