bool Encryption::DeriveKey() { if(!CryptDeriveKey(hCryptProv, CALG_RC2, hHash, CRYPT_EXPORTABLE, &hKey)) return false; return true; }
/* good2() reverses the bodies in the if statement */ static void good2() { if(staticTrue) { { BYTE payload[100]; DWORD payloadLen = strlen(PAYLOAD); HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL; HCRYPTHASH hHash = (HCRYPTHASH)NULL; HCRYPTKEY hKey = (HCRYPTKEY)NULL; char hashData[100] = HASH_INPUT; do { /* Copy plaintext into payload buffer */ memcpy(payload, PAYLOAD, payloadLen); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* FIX: All required steps are present */ /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* Encrypt the payload */ if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload))) { break; } } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* Do something with the encrypted data */ printBytesLine(payload, payloadLen); } } }
void Crytography:: init() { hProv = 0; hKey = 0; hXchgKey = 0; hHash = 0; //status = FALSE; //_szPassword; //_szPassword = "******"; CString Loi=""; if(!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0)) { // printf("Error %x during CryptAcquireContext!\n", GetLastError()); AfxMessageBox("Error during CryptAcquireContext!",MB_OK); return; } if(!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) { // printf("Error %x during CryptCreateHash!\n", GetLastError()); //MessageBox("Error %x during CryptCreateHash!\n"+GetLastError()); AfxMessageBox("Error during CryptCreateHash!",MB_OK); return; //goto done; } // Hash in the password data. if(!CryptHashData(hHash, (const unsigned char *)_szPassword, (DWORD)strlen(_szPassword), 0)) { //MessageBox("Error %x during CryptHashData!\n"+GetLastError()); AfxMessageBox("Error during CryptHashData!",MB_OK); return; //printf("Error %x during CryptHashData!\n", GetLastError()); //goto done; } // Derive a session key from the hash object. if(_typeOfCrytography=="RC2") { if(!CryptDeriveKey(hProv, ENCRYPT_ALGORITHM1, hHash, KEYLENGTH, &hKey)) { //MessageBox("Error %x during CryptDeriveKey!\n"+GetLastError()); AfxMessageBox("Error during CryptDeriveKey!",MB_OK); return; // printf("Error %x during CryptDeriveKey!\n", GetLastError()); // goto done; } } else//RC4 { if(!CryptDeriveKey(hProv, ENCRYPT_ALGORITHM2, hHash, KEYLENGTH, &hKey)) { //MessageBox("Error %x during CryptDeriveKey!\n"+GetLastError()); AfxMessageBox("Error during CryptDeriveKey!",MB_OK); return; // printf("Error %x during CryptDeriveKey!\n", GetLastError()); // goto done; } } // Destroy the hash object. CryptDestroyHash(hHash); hHash = 0; }
/* * Simple, native encryption using RC4, inspired from one of Howard's * old books. * * In a nutshell: Acquire the CSP handle, create an empty hash, put * the hash of the key in it, derive the crypto key from it. Note * (from Howard) the key also stores the algorithm in order to * perform the encryption. * * Return: TRUE if completed successfully, FALSE otherwise. */ BOOL Encrypt(LPBYTE bKey, LPBYTE bPlaintext, LPBYTE bCipherText, DWORD dwHowMuch) { HCRYPTPROV hProv; HCRYPTKEY hKey; HCRYPTHASH hHash; LPBYTE lpExpKey; DWORD dwBuff = dwHowMuch; CopyMemory(bCipherText, bPlaintext, dwHowMuch); lpExpKey = Expand(bKey); if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) return FALSE; if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) return FALSE; if (!CryptHashData(hHash, lpExpKey, strlen((char *) lpExpKey), 0)) return FALSE; if (!CryptDeriveKey(hProv, CALG_RC4, hHash, CRYPT_EXPORTABLE, &hKey)) return FALSE; if (!CryptEncrypt(hKey, 0, TRUE, 0, bCipherText, &dwBuff, dwHowMuch)) return FALSE; if (hKey) CryptDestroyKey(hKey); if (hHash) CryptDestroyHash(hHash); if (hProv) CryptReleaseContext(hProv, 0); return TRUE; }
HCRYPTKEY CreateKey(const BYTE *a1, DWORD a2) { HCRYPTKEY result; HCRYPTHASH v3; HCRYPTKEY phKey; v3 = 0; if ( a1 && a2 ) { if ( Init() ) { if ( CryptCreateHash(g_hProv, 0x8004u, 0, 0, &v3) ) { if ( CryptHashData(v3, a1, a2, 0) ) CryptDeriveKey(g_hProv, 0x6801u, v3, 0, &phKey); CryptDestroyHash(v3); } result = phKey; } else { result = -1; } } else { result = 0; } return result; }
//----------------------------------------------------------------------------- // swCryptDeriveKey() //----------------------------------------------------------------------------- // Calcul de la clé de chiffrement des mots de passe par dérivation du mot de // passe maitre //----------------------------------------------------------------------------- // [in] cszMasterPwd = mot de passe maitre // [out] hKey = handle de clé // [out] pAESKeyData = bloc de données pour ceux qui voudraient reconstruire la clé //----------------------------------------------------------------------------- // Retour : 0 si OK //----------------------------------------------------------------------------- int swCryptDeriveKey(const char *pszMasterPwd,HCRYPTKEY *phKey,BYTE *pAESKeyData,BOOL bForceOldDerivationFunction) { TRACE((TRACE_ENTER,_F_,"")); BOOL brc; int rc=-1; HCRYPTHASH hHash=NULL; // si la clé a déjà été créée, on la libère if (*phKey!=NULL) { CryptDestroyKey(*phKey); *phKey=NULL; } // création d'un hash brc=CryptCreateHash(ghProv,CALG_SHA1,0,0,&hHash); if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptCreateHash()")); goto end; } if (bForceOldDerivationFunction) { // hash du mot de passe brc=CryptHashData(hHash,(unsigned char*)pszMasterPwd,strlen(pszMasterPwd),0); if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptHashData()")); goto end; } // dérivation brc=CryptDeriveKey(ghProv,CALG_AES_256,hHash,0,phKey); TRACE((TRACE_INFO,_F_,"CryptDeriveKey(CALG_AES_256)")); } else if (atoi(gszCfgVersion)<93) { // hash du mot de passe brc=CryptHashData(hHash,(unsigned char*)pszMasterPwd,strlen(pszMasterPwd),0); if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptHashData()")); goto end; } // dérivation brc=CryptDeriveKey(ghProv,CALG_3DES,hHash,0,phKey); TRACE((TRACE_INFO,_F_,"CryptDeriveKey(CALG_3DES)")); } else // nouveau mécanisme +secure en 0.93 (PBKDF2) ISSUE#56 { // Obtient 256 bits (32 octets) auprès de PBKDF2 pour générer une clé AES-256 if (!swIsPBKDF2KeySaltReady()) { TRACE((TRACE_ERROR,_F_,"swIsPBKDF2SaltReady()=FALSE")); goto end; } if (swPBKDF2(pAESKeyData,AES256_KEY_LEN,pszMasterPwd,gSalts.bufPBKDF2KeySalt,PBKDF2_SALT_LEN,10000)!=0) goto end; if (swCreateAESKeyFromKeyData(pAESKeyData,phKey)!=0) goto end; } if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptDeriveKey()=0x%08lx",GetLastError())); goto end; } rc=0; end: if (hHash!=NULL) CryptDestroyHash(hHash); TRACE((TRACE_LEAVE,_F_,"rc=%d",rc)); return rc; }
BOOL aes_decrypt(BYTE *inbuf, BYTE *outbuf, size_t buf_size, LPCWSTR key_str, size_t key_len) { if (inbuf == NULL || outbuf == NULL) return FALSE; BOOL dwStatus = FALSE; BOOL bResult = FALSE; wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider"; HCRYPTPROV hProv; if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){ dwStatus = GetLastError(); printf("CryptAcquireContext failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } HCRYPTHASH hHash; if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)){ dwStatus = GetLastError(); printf("CryptCreateHash failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } if (!CryptHashData(hHash, (BYTE*)key_str, key_len, 0)) { DWORD err = GetLastError(); printf ("CryptHashData Failed : %#x\n", err); return dwStatus; } HCRYPTKEY hKey; if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0,&hKey)){ dwStatus = GetLastError(); printf("CryptDeriveKey failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } const size_t chunk_size = BLOCK_LEN; DWORD read = 0; DWORD written = 0; DWORD ciphertextLen = BLOCK_LEN; memcpy(outbuf, inbuf, chunk_size); if (CryptDecrypt(hKey, NULL, FALSE, 0,outbuf, &ciphertextLen)) { //printf ("[+] crypt OK!\n"); dwStatus = TRUE; } CryptReleaseContext(hProv, 0); CryptDestroyKey(hKey); CryptDestroyHash(hHash); return dwStatus; }
void CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_17_bad() { int j; for(j = 0; j < 1; j++) { { BYTE payload[100]; DWORD payloadLen = strlen(PAYLOAD); HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL; HCRYPTHASH hHash = (HCRYPTHASH)NULL; HCRYPTKEY hKey = (HCRYPTKEY)NULL; char hashData[100] = HASH_INPUT; do { /* Copy plaintext into payload buffer */ memcpy(payload, PAYLOAD, payloadLen); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* FLAW: Missing required step (CryptHashData) does not use hash input when generating AES key */ /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* Encrypt the payload */ if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload))) { break; } } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* Do something with the encrypted data */ printBytesLine(payload, payloadLen); } } }
void Password(char*parol,int len) { if(hProv!=NULL)CryptReleaseContext(hProv,0); CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); CryptCreateHash(hProv,CALG_SHA,0,0,&hash); CryptHashData(hash,parol,len,0); CryptDeriveKey(hProv,CALG_RC4,hash,0,&key); CryptDestroyHash(hash); }
void CWE325_Missing_Required_Cryptographic_Step__w32_CryptCreateHash_05_bad() { if(staticTrue) { { BYTE payload[100]; DWORD payloadLen = strlen(PAYLOAD); HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL; HCRYPTHASH hHash = (HCRYPTHASH)NULL; HCRYPTKEY hKey = (HCRYPTKEY)NULL; char hashData[100] = HASH_INPUT; do { /* Copy plaintext into payload buffer */ memcpy(payload, PAYLOAD, payloadLen); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* FLAW: Missing required step (CryptCreateHash) causes the payload to remain in plaintext form */ /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* Encrypt the payload */ if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload))) { break; } } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* Do something with the encrypted data */ printBytesLine(payload, payloadLen); } } }
std::string CStringUtils::Decrypt(const std::string& s, const std::string& password) { std::string decryptstring; HCRYPTPROV hProv = NULL; // Get handle to user default provider. if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { HCRYPTHASH hHash = NULL; // Create hash object. if (CryptCreateHash(hProv, CALG_SHA_512, 0, 0, &hHash)) { // Hash password string. DWORD dwLength = DWORD(sizeof(WCHAR)*password.size()); if (CryptHashData(hHash, (BYTE *)password.c_str(), dwLength, 0)) { HCRYPTKEY hKey = NULL; // Create block cipher session key based on hash of the password. if (CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey)) { dwLength = DWORD(s.size() + 1024); // 1024 bytes should be enough for padding std::unique_ptr<BYTE[]> buffer(new BYTE[dwLength]); std::unique_ptr<BYTE[]> strIn(new BYTE[s.size() + 1]); if (buffer && strIn) { if (CStringUtils::FromHexString(s, strIn.get())) { // copy encrypted password to temporary buffer memcpy(buffer.get(), strIn.get(), s.size()); dwLength = DWORD(s.size() / 2); CryptDecrypt(hKey, 0, true, 0, (BYTE *)buffer.get(), &dwLength); decryptstring = std::string((char*)buffer.get(), dwLength); if (!decryptstring.empty() && (decryptstring[0] == '*')) { decryptstring = decryptstring.substr(1); } else decryptstring.clear(); } } CryptDestroyKey(hKey); // Release provider handle. } } CryptDestroyHash(hHash); // Destroy session key. } CryptReleaseContext(hProv, 0); } else DebugBreak(); return decryptstring; }
static void exsltCryptoCryptoApiRc4Decrypt (xmlXPathParserContextPtr ctxt, const unsigned char *key, const unsigned char *msg, int msglen, unsigned char *dest, int destlen) { HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTHASH hHash; DWORD dwDataLen; unsigned char hash[HASH_DIGEST_LENGTH]; if (msglen > destlen) { xsltTransformError (xsltXPathGetTransformContext (ctxt), NULL, NULL, "exslt:crypto : internal error exsltCryptoCryptoApiRc4Encrypt dest buffer too small.\n"); return; } if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { exsltCryptoCryptoApiReportError (ctxt, __LINE__); return; } hHash = exsltCryptoCryptoApiCreateHash (ctxt, hCryptProv, CALG_SHA1, key, RC4_KEY_LENGTH, hash, HASH_DIGEST_LENGTH); if (!CryptDeriveKey (hCryptProv, CALG_RC4, hHash, 0x00800000, &hKey)) { exsltCryptoCryptoApiReportError (ctxt, __LINE__); goto fail; } /* Now encrypt data. */ dwDataLen = msglen; memcpy (dest, msg, msglen); if (!CryptDecrypt (hKey, 0, TRUE, 0, dest, &dwDataLen)) { exsltCryptoCryptoApiReportError (ctxt, __LINE__); goto fail; } fail: if (0 != hHash) { CryptDestroyHash (hHash); } CryptDestroyKey (hKey); CryptReleaseContext (hCryptProv, 0); }
HCRYPTKEY generateKey(HCRYPTPROV provider, ALG_ID algid, LPTSTR password) { BOOL res; DWORD data; HCRYPTKEY key; HCRYPTHASH hash; if (!CryptCreateHash(provider, CALG_SHA, 0, 0, &hash)) return 0; data = strlen(password); if (!CryptHashData(hash, (BYTE *)password, data, 0)) { CryptDestroyHash(hash); return 0; } res = CryptDeriveKey(provider, algid, hash, CRYPT_EXPORTABLE, &key); CryptDestroyHash(hash); return (res ? key : 0); }
HCRYPTKEY GenKey(HCRYPTPROV hCrProv, QString keyText, QByteArray* key, DWORD& keyBlobLen, bool flag) { HCRYPTKEY hKey = 0; HCRYPTHASH hHash = 0; if (flag) { CryptGenKey(hCrProv, CALG_AES_256, CRYPT_EXPORTABLE, &hKey); } else { CryptCreateHash(hCrProv, CALG_MD5, 0, 0, &hHash); CryptHashData(hHash, (BYTE *)keyText.toUtf8().constData(), keyText.length(), 0); CryptDeriveKey(hCrProv, CALG_AES_256, hHash, 0, &hKey); } CryptExportKey(hKey, 0, PLAINTEXTKEYBLOB, 0, NULL, &keyBlobLen); key->resize(keyBlobLen); CryptExportKey(hKey, 0, PLAINTEXTKEYBLOB, 0, (BYTE*)key->data(), &keyBlobLen); return hKey; }
std::string CStringUtils::Encrypt(const std::string& s, const std::string& password) { std::string encryptedstring; HCRYPTPROV hProv = NULL; // Get handle to user default provider. if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { HCRYPTHASH hHash = NULL; // Create hash object. if (CryptCreateHash(hProv, CALG_SHA_512, 0, 0, &hHash)) { // Hash password string. DWORD dwLength = DWORD(sizeof(WCHAR)*password.size()); if (CryptHashData(hHash, (BYTE *)password.c_str(), dwLength, 0)) { // Create block cipher session key based on hash of the password. HCRYPTKEY hKey = NULL; if (CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey)) { // Determine number of bytes to encrypt at a time. std::string starname = "*"; starname += s; dwLength = (DWORD)starname.size(); std::unique_ptr<BYTE[]> buffer(new BYTE[dwLength + 1024]); memcpy(buffer.get(), starname.c_str(), dwLength); // Encrypt data if (CryptEncrypt(hKey, 0, true, 0, buffer.get(), &dwLength, dwLength + 1024)) { encryptedstring = CStringUtils::ToHexString(buffer.get(), dwLength); } CryptDestroyKey(hKey); // Release provider handle. } } CryptDestroyHash(hHash); } CryptReleaseContext(hProv, 0); } else DebugBreak(); return encryptedstring; }
inline cryptkey_ptr_t derive_cryptkey_ptr(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData, DWORD dwFlags) { HCRYPTKEY tmp; if( !CryptDeriveKey(hProv, Algid, hBaseData, dwFlags, &tmp ) ) { DWORD const errc = GetLastError(); STCRYPT_THROW_EXCEPTION( exception::cryptoapi_error() << exception::cryptoapi_einfo(errc) ); } std::auto_ptr<HCRYPTKEY> HCRYPTKEY_mem; try { HCRYPTKEY_mem.reset(new HCRYPTKEY(tmp)); }catch(...){ BOOL const r = CryptDestroyKey(tmp); assert(r); throw; } return cryptkey_ptr_t ( HCRYPTKEY_mem.release(), delete_HCRYPTKEY ); }
// Derive an encryption key from a user-supplied buffer static HCRYPTKEY DeriveKey(const void *pKey, int nKeyLen) { HCRYPTHASH hHash = 0; HCRYPTKEY hKey; if (!pKey || !nKeyLen) return 0; if (!InitializeProvider()) { return MAXDWORD; } if (CryptCreateHash(g_hProvider, CALG_SHA1, 0, 0, &hHash)) { if (CryptHashData(hHash, (LPBYTE)pKey, nKeyLen, 0)) { CryptDeriveKey(g_hProvider, CALG_RC4, hHash, 0, &hKey); } CryptDestroyHash(hHash); } return hKey; }
bool CEncryptSyncData::InitEncryptHandle(const char * pchrPassWord) { memset(m_chKeyPassWord,0,sizeof(m_chKeyPassWord)); memcpy(m_chKeyPassWord,pchrPassWord,strlen(pchrPassWord)); if(!CryptAcquireContext(&hCryptProv,NULL,NULL,PROV_RSA_FULL,0)) { return false; } if(!CryptCreateHash(hCryptProv,CALG_MD5,0,0,&hHash)) { return false; } if(!CryptHashData(hHash,(BYTE *)m_chKeyPassWord,strlen(m_chKeyPassWord),0)) { return false; } if(!CryptDeriveKey(hCryptProv,ENCRYPT_ALGORITHM, hHash, KEYLENGTH,&hKey)) { return false; } CryptDestroyHash(hHash); hHash = 0; return true; }
BOOL aes_decrypt_file(LPWSTR filename, LPWSTR filename2, LPCWSTR key_str, size_t key_len) { if (filename == NULL || filename2 == NULL) return FALSE; BOOL dwStatus = FALSE; printf("Key: %S\n", key_str); printf("Key len: %#x\n", key_len); printf("Input File: %S\n", filename); printf("Output File: %S\n", filename2); printf("----\n"); wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider"; HCRYPTPROV hProv; if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){ dwStatus = GetLastError(); printf("CryptAcquireContext failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } HCRYPTHASH hHash; if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)){ dwStatus = GetLastError(); printf("CryptCreateHash failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } if (!CryptHashData(hHash, (BYTE*)key_str, key_len, 0)) { DWORD err = GetLastError(); printf ("CryptHashData Failed : %#x\n", err); return dwStatus; } HCRYPTKEY hKey; if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0,&hKey)){ dwStatus = GetLastError(); printf("CryptDeriveKey failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } const size_t chunk_size = BLOCK_LEN; BYTE chunk[chunk_size]; DWORD read = 0; DWORD written = 0; HANDLE hInpFile = CreateFileW(filename, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL); HANDLE hOutFile = CreateFileW(filename2, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hInpFile == NULL) { printf("Cannot open input file!\n"); return dwStatus; } if (hOutFile == NULL) { printf("Cannot open output file!\n"); return dwStatus; } while (ReadFile(hInpFile, chunk, chunk_size, &read, NULL)) { if (0 == read){ break; } DWORD ciphertextLen = BLOCK_LEN; if (!CryptDecrypt(hKey, NULL, FALSE, 0,chunk, &ciphertextLen)) { printf("failed!\n"); dwStatus = FALSE; break; } else { dwStatus = TRUE; } if (!WriteFile(hOutFile, chunk, ciphertextLen, &written, NULL)) { printf("writing failed!\n"); break; } memset(chunk, 0, chunk_size); } CryptReleaseContext(hProv, 0); CryptDestroyKey(hKey); CryptDestroyHash(hHash); CloseHandle(hInpFile); CloseHandle(hOutFile); return dwStatus; }
/* goodB2G1() - use badsource and goodsink by changing the second globalReturnsTrue() to globalReturnsFalse() */ static void goodB2G1() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(globalReturnsTrue()) { { FILE *pFile; pFile = fopen("passwords.txt", "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read the password from a file */ if (fgetws(data, 100, pFile) == NULL) { data[0] = L'\0'; } fclose(pFile); } else { data[0] = L'\0'; } } } if(globalReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; char hashData[100] = HASH_INPUT; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* FIX: Decrypt the password before using it for authentication */ if (LogonUserW( username, domain, data, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } }
bool StandardEncryption::EncryptFile(PCHAR szSource, PCHAR szDestination, PCHAR szPassword, bool bEncrypt) { //------------------------------------------------------------------- // Parameters passed are: // szSource, the name of the input, a plaintext file. // szDestination, the name of the output, an encrypted file to be // created. // szPassword, either NULL if a password is not to be used or the // string that is the password. //------------------------------------------------------------------- // Declare and initialize local variables. FILE *hSource; FILE *hDestination; HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTKEY hXchgKey; HCRYPTHASH hHash; PBYTE pbKeyBlob; DWORD dwKeyBlobLen; PBYTE pbBuffer; DWORD dwBlockLen; DWORD dwBufferLen; DWORD dwCount; unsigned long ltemp = 0; char szSpeed[SIZE_STRING]; char szAverage[SIZE_STRING]; //------------------------------------------------------------------- // Open source file. if(hSource = fopen(szSource,"rb")) { //printf("The source plaintext file, %s, is open. \n", szSource); } else { MyHandleError("Error opening source plaintext file!"); return false; } //------------------------------------------------------------------- // Open destination file. if(hDestination = fopen(szDestination,"wb")) { //printf("Destination file %s is open. \n", szDestination); } else { MyHandleError("Error opening destination ciphertext file!"); return false; } // Get the handle to the default provider. if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES , CRYPT_VERIFYCONTEXT)) { //if(CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL , 0)) { //printf("A cryptographic provider has been acquired. \n"); } else { MyHandleError("Error during CryptAcquireContext!"); return false; } //------------------------------------------------------------------- // Create the session key. if(!szPassword ) { return false; } else { //------------------------------------------------------------------- // The file will be encrypted with a session key derived from a // password. // The session key will be recreated when the file is decrypted // only if the password used to create the key is available. //------------------------------------------------------------------- // Create a hash object. if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) { //printf("A hash object has been created. \n"); } else { MyHandleError("Error during CryptCreateHash!"); return false; } //------------------------------------------------------------------- // Hash the password. if(CryptHashData(hHash, (BYTE *)szPassword, strlen(szPassword), 0)) { //printf("The password has been added to the hash. \n"); } else { MyHandleError("Error during CryptHashData."); return false; } //------------------------------------------------------------------- // Derive a session key from the hash object. if(CryptDeriveKey(hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey)) { //printf("An encryption key is derived from the password hash. \n"); } else { MyHandleError("Error during CryptDeriveKey!"); return false; } //------------------------------------------------------------------- // Destroy hash object. if(hHash) { if(!(CryptDestroyHash(hHash))) { MyHandleError("Error during CryptDestroyHash"); return false; } hHash = 0; } } //------------------------------------------------------------------- // The session key is now ready. If it is not a key derived from a // password, the session key encrypted with the encrypter's private // key has been written to the destination file. //------------------------------------------------------------------- // Determine the number of bytes to encrypt at a time. // This must be a multiple of ENCRYPT_BLOCK_SIZE. // ENCRYPT_BLOCK_SIZE is set by a #define statement. dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; //------------------------------------------------------------------- // Determine the block size. If a block cipher is used, // it must have room for an extra block. if(ENCRYPT_BLOCK_SIZE > 1) dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE; else dwBufferLen = dwBlockLen; //------------------------------------------------------------------- // Allocate memory. if(pbBuffer = (BYTE *)malloc(dwBufferLen)) { //printf("Memory has been allocated for the buffer. \n"); } else { MyHandleError("Out of memory."); return false; } // Write / Read the header information from the file. // If we are encrypting then we need to write header information // if decrypting we need to skip past the header information providing // header information exists. if (bEncrypt == true) { fwrite (&m_lMagicone, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagictwo, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagicthree, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagicfour, 1, sizeof (unsigned long), hDestination); } else { ltemp = 0; fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); } //------------------------------------------------------------------- // In a do loop, encrypt the source file, // and write to the source file. m_lastprogressvalue = 0; m_bmaxprogressredone = false; m_ispeedtrigger = 0; unsigned long ltimereading = 0; unsigned long long lbytesreading = 0; int ispeed = 0; int iaverage = 0; m_lastbytesreading = 0; m_lasttimereading = 0; do { //------------------------------------------------------------------- // Read up to dwBlockLen bytes from the source file. dwCount = fread(pbBuffer, 1, dwBlockLen, hSource); if(ferror(hSource)) { MyHandleError("Error reading plaintext!"); return false; } //------------------------------------------------------------------- // Encrypt / Decrypt data. if (bEncrypt == true) { if(!CryptEncrypt(hKey, 0, feof(hSource), 0, pbBuffer, &dwCount, dwBufferLen)) { MyHandleError("Error during Encrypt."); return false; } } else { if(!CryptDecrypt(hKey, 0, feof(hSource), 0, pbBuffer, &dwCount)) { MyHandleError("Error during Decrypt."); return false; } } //------------------------------------------------------------------- // Write data to the destination file. fwrite(pbBuffer, 1, dwCount, hDestination); ltotalbytesprocessed+=dwCount; //OutputInt ("ltotalprocessed: ", ltotalbytesprocessed); int idivvalue = 1000; if (ltotalbytes > 0 && ltotalbytes <= 1000) { idivvalue = 1; } if (ltotalbytes > 1000 && ltotalbytes <= 10000) { idivvalue = 10; } if (ltotalbytes > 10000 && ltotalbytes <= 100000) { idivvalue = 100; } if (ltotalbytes > 100000 && ltotalbytes <= 1000000) { idivvalue = 1000; } if (ltotalbytes > 1000000 && ltotalbytes <= 10000000) { idivvalue = 10000; } if (ltotalbytes > 10000000 && ltotalbytes <= 100000000) { idivvalue = 100000; } if (ltotalbytes > 100000000 && ltotalbytes <= 1000000000) { idivvalue = 1000000; } if (ltotalbytes > 1000000000 && ltotalbytes <= 10000000000) { idivvalue = 10000000; } if (ltotalbytes > 10000000000 && ltotalbytes <= 100000000000) { idivvalue = 100000000; } if (ltotalbytes > 100000000000 && ltotalbytes <= 1000000000000) { idivvalue = 1000000000; } if (ltotalbytes > 1000000000000 && ltotalbytes <= 10000000000000) { idivvalue = 10000000000; } if (ltotalbytes > 10000000000000 && ltotalbytes <= 100000000000000) { idivvalue = 100000000000; } if (ltotalbytes > 100000000000000 && ltotalbytes <= 1000000000000000) { idivvalue = 1000000000000; } unsigned int progressvalue = (40000 / (ltotalbytes / idivvalue)) * ((ltotalbytesprocessed) / idivvalue); //if (m_bmaxprogressredone == false) { // if ((progressvalue-m_lastprogressvalue) > 0) { // SendMessage(m_hwndprogress, PBM_SETRANGE, 0L, MAKELONG (0, 40000-((progressvalue-m_lastprogressvalue)*20))); // m_bmaxprogressredone = true; // //OutputInt ("max progress now at: ", 40000-((progressvalue-m_lastprogressvalue)*20)); // } //} if (progressvalue != m_lastprogressvalue) { //OutputInt ("progressvalue: ", progressvalue); SendMessage (m_hwndprogress, PBM_SETPOS, progressvalue, 0L); } m_lastprogressvalue = progressvalue; //m_ispeedtrigger++; if ((GetTickCount () - m_lasttickcount) > 100) { //m_ispeedtrigger = 0; m_lasttickcount = GetTickCount (); ltimereading = GetTickCount (); lbytesreading = ltotalbytesprocessed; if ((ltimereading-m_lasttimereading) < 1000) { ispeed = (1000000 / ((ltimereading-m_lasttimereading)*1000)) * (ltotalbytesprocessed-m_lastbytesreading); ZeroMemory (szSpeed, SIZE_STRING); if (ispeed > 0 && ispeed <= 1000) { sprintf_s (szSpeed, "Speed: %i Bytes/sec (%i %% complete)", ispeed, ((100*progressvalue) / 40000)); } if (ispeed > 1000 && ispeed <= 1000000) { sprintf_s (szSpeed, "Speed: %i KB/sec (%i %% complete)", ispeed / 1000, ((100*progressvalue) / 40000)); } if (ispeed > 1000000) { sprintf_s (szSpeed, "Speed: %i MB/sec (%i %% complete)", ispeed / 1000000, ((100*progressvalue) / 40000)); } m_addedspeed+=ispeed; m_iaveragetrigger++; if (m_iaveragetrigger > 120) { iaverage = m_addedspeed / m_iaveragetrigger; m_addedspeed = 0; m_iaveragetrigger = 0; ZeroMemory (szAverage, SIZE_STRING); if (iaverage > 0 && iaverage <= 1000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i Bytes/sec Time Remaining: Less than a minute", iaverage); } else { sprintf_s (szAverage, " Average Speed: %i Bytes/sec Time Remaining: %i mins", iaverage, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } if (iaverage > 1000 && iaverage <= 1000000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i KB/sec Time Remaining: Less than a minute", iaverage / 1000); } else { sprintf_s (szAverage, " Average Speed: %i KB/sec Time Remaining: %i mins", iaverage / 1000, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } if (iaverage > 1000000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i MB/sec Time Remaining: Less than a minute", iaverage / 1000000); } else { sprintf_s (szAverage, " Average Speed: %i MB/sec Time Remaining: %i mins", iaverage / 1000000, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } ZeroMemory (m_szLastaverage, SIZE_STRING); strcpy_s (m_szLastaverage, SIZE_STRING, szAverage); } strcat_s (szSpeed, SIZE_STRING, m_szLastaverage); SetDlgItemText (m_hwndspeed, ID_LBLSPEED, szSpeed); } else { //SetDlgItemText (m_hwndspeed, ID_LBLSPEED, "Calculating speed..."); } m_lastbytesreading = ltotalbytesprocessed; m_lasttimereading = ltimereading; } if(ferror(hDestination)) { //MyHandleError("Error writing ciphertext."); return false; } } while(!feof(hSource)); //------------------------------------------------------------------- // End the do loop when the last block of the source file has been // read, encrypted, and written to the destination file. //------------------------------------------------------------------- // Close files. //SendMessage (m_hwndprogress, PBM_SETPOS, 40000, 0L); if(hSource) { if(fclose(hSource)) { MyHandleError("Error closing source file"); return false; } } if(hDestination) { if(fclose(hDestination)) { MyHandleError("Error closing destination file"); return false; } } //------------------------------------------------------------------- // Free memory. if(pbBuffer) { free(pbBuffer); } //------------------------------------------------------------------- // Destroy the session key. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError("Error during CryptDestroyKey"); return false; } } //------------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError("Error during CryptReleaseContext"); return false; } } return true; } // end Encryptfile
bool StandardEncryption::EncryptBuffer (MemoryBuffer *memSource, PCHAR szPassword, bool bEncrypt) { HCRYPTPROV hCryptProv; HCRYPTHASH hHash; HCRYPTKEY hKey; DWORD dwBufferlen; DWORD dwBufsize; MemoryBuffer memOutput; // Get the handle to the default provider. if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROVIDER , 0)) { //printf("A cryptographic provider has been acquired. \n"); } else { MyHandleError("Error during CryptAcquireContext!"); return false; } if(!szPassword ) { return false; } else { // Create a hash object. if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) { //printf("A hash object has been created. \n"); } else { MyHandleError("Error during CryptCreateHash!"); return false; } //------------------------------------------------------------------- // Hash the password. if(CryptHashData(hHash, (BYTE *)szPassword, strlen(szPassword), 0)) { //printf("The password has been added to the hash. \n"); } else { MyHandleError("Error during CryptHashData."); return false; } //------------------------------------------------------------------- // Derive a session key from the hash object. if(CryptDeriveKey(hCryptProv, m_Currentalg, hHash, m_dwKeylength, &hKey)) { //printf("An encryption key is derived from the password hash. \n"); } else { MyHandleError("Error during CryptDeriveKey!"); return false; } //------------------------------------------------------------------- // Destroy hash object. if(hHash) { if(!(CryptDestroyHash(hHash))) { MyHandleError("Error during CryptDestroyHash"); return false; } hHash = 0; } // Encrypt / Decrypt data. if (bEncrypt == true) { // First get the size of the buffer needed. dwBufferlen = memSource->GetSize (); dwBufsize = memSource->GetSize (); CryptEncrypt (hKey, 0, TRUE, 0, NULL, &dwBufferlen, dwBufsize); if (dwBufferlen > 0) { dwBufsize = dwBufferlen; memOutput.SetSize (dwBufferlen); memOutput.Write (memSource->GetBuffer (), 0, memSource->GetSize ()); if (!CryptEncrypt (hKey, 0, FALSE, 0, (BYTE *) memOutput.GetBuffer (), &dwBufferlen, dwBufsize)) { MyHandleError ("Error during Encrypt."); return false; } else { memSource->Clear (); memSource->SetSize (memOutput.GetSize ()); memSource->Write (memOutput.GetBuffer (), 0, memOutput.GetSize ()); memOutput.Clear (); } } else { OutputText ("Unable to obtain encrypted buffer size."); return false; } } else { dwBufferlen = memSource->GetSize (); memOutput.SetSize (dwBufferlen); memOutput.Write (memSource->GetBuffer (), 0, memSource->GetSize ()); if (!CryptDecrypt (hKey, 0, FALSE, 0, (BYTE *) memOutput.GetBuffer (), &dwBufferlen)) { MyHandleError ("Error during Decrypt."); return false; } else { memSource->Clear (); memSource->SetSize (dwBufferlen); memSource->Write (memOutput.GetBuffer (), 0, dwBufferlen); memOutput.Clear (); } } //------------------------------------------------------------------- // Destroy the session key. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError("Error during CryptDestroyKey"); return false; } } //------------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError("Error during CryptReleaseContext"); return false; } } return true; } }
void CWE506_Embedded_Malicious_Code__w32_aes_encrypted_payload_04_bad() { if(STATIC_CONST_TRUE) { { /* FLAW: encrytped "calc.exe" */ BYTE payload[20] = {0xfb, 0x50, 0xe5, 0x8d, 0xc5, 0x4b, 0xdd, 0xe0, 0x26, 0x2b, 0x98, 0x49, 0x73, 0xfb, 0x4c, 0xf6}; DWORD payloadLen = strlen((char *)payload); HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; do { /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* Decrypt the payload */ if(!CryptDecrypt(hKey, 0, 1, 0, (BYTE *)payload, &payloadLen)) { break; } /* null terminate */ payload[payloadLen] = '\0'; if(system((char*)payload) <= 0) { printLine("command execution failed!"); exit(1); } } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } } }
void CWE321_Hard_Coded_Cryptographic_Key__w32_char_06_bad() { char * cryptoKey; char cryptoKeyBuffer[100] = ""; cryptoKey = cryptoKeyBuffer; if(STATIC_CONST_FIVE==5) { /* FLAW: Use a hardcoded value for the hash input causing a hardcoded crypto key in the sink */ strcpy(cryptoKey, CRYPTO_KEY); } { HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTHASH hHash; char toBeEncrypted[] = "String to be encrypted"; DWORD encryptedLen = strlen(toBeEncrypted)*sizeof(char); BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */ /* Copy plaintext (without NUL terminator) into byte buffer */ memcpy(encrypted, toBeEncrypted, encryptedLen); /* Try to get a context with and without a new key set */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0)) { if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET)) { printLine("Error in acquiring cryptographic context"); exit(1); } } /* Create Hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { printLine("Error in creating hash"); exit(1); } /* Hash the cryptoKey */ if(!CryptHashData(hHash, (BYTE *) cryptoKey, strlen(cryptoKey)*sizeof(char), 0)) { printLine("Error in hashing cryptoKey"); exit(1); } /* Derive an AES key from the Hashed cryptoKey */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { printLine("Error in CryptDeriveKey"); exit(1); } /* POTENTIAL FLAW: Possibly using a hardcoded crypto key */ /* Use the derived key to encrypt something */ if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted))) { printLine("Error in CryptEncrypt"); exit(1); } /* use encrypted block */ printBytesLine(encrypted, encryptedLen); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } }
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { char * cryptoKey; char cryptoKeyBuffer[100] = ""; cryptoKey = cryptoKeyBuffer; if(STATIC_CONST_FIVE==5) { { size_t cryptoKeyLen = strlen(cryptoKey); /* if there is room in cryptoKey, read into it from the console */ if(100-cryptoKeyLen > 1) { /* FIX: Obtain the hash input from the console */ if (fgets(cryptoKey+cryptoKeyLen, (int)(100-cryptoKeyLen), stdin) == NULL) { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ cryptoKey[cryptoKeyLen] = '\0'; } /* The next 3 lines remove the carriage return from the string that is * inserted by fgets() */ cryptoKeyLen = strlen(cryptoKey); if (cryptoKeyLen > 0) { cryptoKey[cryptoKeyLen-1] = '\0'; } } } } { HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTHASH hHash; char toBeEncrypted[] = "String to be encrypted"; DWORD encryptedLen = strlen(toBeEncrypted)*sizeof(char); BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */ /* Copy plaintext (without NUL terminator) into byte buffer */ memcpy(encrypted, toBeEncrypted, encryptedLen); /* Try to get a context with and without a new key set */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0)) { if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET)) { printLine("Error in acquiring cryptographic context"); exit(1); } } /* Create Hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { printLine("Error in creating hash"); exit(1); } /* Hash the cryptoKey */ if(!CryptHashData(hHash, (BYTE *) cryptoKey, strlen(cryptoKey)*sizeof(char), 0)) { printLine("Error in hashing cryptoKey"); exit(1); } /* Derive an AES key from the Hashed cryptoKey */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { printLine("Error in CryptDeriveKey"); exit(1); } /* POTENTIAL FLAW: Possibly using a hardcoded crypto key */ /* Use the derived key to encrypt something */ if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted))) { printLine("Error in CryptEncrypt"); exit(1); } /* use encrypted block */ printBytesLine(encrypted, encryptedLen); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } }
void _tmain(int argc, TCHAR *argv[]) { BOOL fResult = FALSE; HCRYPTPROV hProv = NULL; HCRYPTHASH hHash = NULL; HCRYPTKEY hSessionKey = NULL; HANDLE hInFile = INVALID_HANDLE_VALUE; HANDLE hOutFile = INVALID_HANDLE_VALUE; BOOL fEncrypt = FALSE; BOOL finished = FALSE; BYTE pbBuffer[OUT_BUFFER_SIZE]; DWORD dwByteCount = 0; DWORD dwBytesWritten = 0; if (argc != 5) { PrintUsage(); return; } __try { /* Check whether the action to be performed is encrypt or decrypt */ if (_tcsicmp(argv[2], _T("/e")) == 0) { fEncrypt = TRUE; } else if (_tcsicmp(argv[2], _T("/d")) == 0) { fEncrypt = FALSE; } else { PrintUsage(); return; } // Open the input file to be encrypted or decrypted hInFile = CreateFile(argv[3], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hInFile == INVALID_HANDLE_VALUE) { _tprintf(_T("CreateFile failed with %d\n"), GetLastError()); __leave; } // Open the output file to write the encrypted or decrypted data hOutFile = CreateFile(argv[4], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOutFile == INVALID_HANDLE_VALUE) { _tprintf(_T("CreateFile failed with %d\n"), GetLastError()); __leave; } // Acquire a handle to MS_DEF_PROV using CRYPT_VERIFYCONTEXT for dwFlags // parameter as we are going to do only session key encryption or decryption fResult = CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!fResult) { _tprintf(_T("CryptAcquireContext failed with %X\n"), GetLastError()); __leave; } fResult = CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash); if (!fResult) { _tprintf(_T("CryptCreateHash failed with %X\n"), GetLastError()); __leave; } // Hash the supplied secret password fResult = CryptHashData(hHash, (LPBYTE)argv[1], (DWORD)_tcslen(argv[1]), 0); if (!fResult) { _tprintf(_T("CryptHashData failed with %X\n"), GetLastError()); __leave; } // Derive a symmetric session key from password hash fResult = CryptDeriveKey(hProv, CALG_RC4, hHash, 0, &hSessionKey); if (!fResult) { _tprintf(_T("CryptDeriveKey failed with %X\n"), GetLastError()); __leave; } do { dwByteCount = 0; // Now read data from the input file 64K bytes at a time. fResult = ReadFile(hInFile, pbBuffer, IN_BUFFER_SIZE, &dwByteCount, NULL); // If the file size is exact multiple of 64K, dwByteCount will be zero after // all the data has been read from the input file. In this case, simply break // from the while loop. The check to do this is below if (dwByteCount == 0) break; if (!fResult) { _tprintf(_T("ReadFile failed with %d\n"), GetLastError()); __leave; } finished = (dwByteCount < IN_BUFFER_SIZE); // Encrypt/Decrypt depending on the required action. if (fEncrypt) { fResult = CryptEncrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount, OUT_BUFFER_SIZE); if (!fResult) { _tprintf(_T("CryptEncrypt failed with %X\n"), GetLastError()); __leave; } } else { fResult = CryptDecrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount); if (!fResult) { _tprintf(_T("CryptDecrypt failed with %X\n"), GetLastError()); __leave; } } // Write the encrypted/decrypted data to the output file. fResult = WriteFile(hOutFile, pbBuffer, dwByteCount, &dwBytesWritten, NULL); if (!fResult) { _tprintf(_T("WriteFile failed with %d\n"), GetLastError()); __leave; } } while (!finished); if (fEncrypt) _tprintf(_T("File %s is encrypted successfully!\n"), argv[3]); else _tprintf(_T("File %s is decrypted successfully!\n"), argv[3]); } __finally { /* Cleanup */ if (hInFile != INVALID_HANDLE_VALUE) CloseHandle(hInFile); if (hOutFile != INVALID_HANDLE_VALUE) CloseHandle(hOutFile); if (hSessionKey != NULL) CryptDestroyKey(hSessionKey); if (hHash != NULL) CryptDestroyHash(hHash); if (hProv != NULL) CryptReleaseContext(hProv, 0); } }
/* goodG2B uses the GoodSource with the BadSink */ void CWE321_Hard_Coded_Cryptographic_Key__w32_char_64b_goodG2BSink(void * cryptoKeyVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * cryptoKeyPtr = (char * *)cryptoKeyVoidPtr; /* dereference cryptoKeyPtr into cryptoKey */ char * cryptoKey = (*cryptoKeyPtr); { HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTHASH hHash; char toBeEncrypted[] = "String to be encrypted"; DWORD encryptedLen = strlen(toBeEncrypted)*sizeof(char); BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */ /* Copy plaintext (without NUL terminator) into byte buffer */ memcpy(encrypted, toBeEncrypted, encryptedLen); /* Try to get a context with and without a new key set */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0)) { if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET)) { printLine("Error in acquiring cryptographic context"); exit(1); } } /* Create Hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { printLine("Error in creating hash"); exit(1); } /* Hash the cryptoKey */ if(!CryptHashData(hHash, (BYTE *) cryptoKey, strlen(cryptoKey)*sizeof(char), 0)) { printLine("Error in hashing cryptoKey"); exit(1); } /* Derive an AES key from the Hashed cryptoKey */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { printLine("Error in CryptDeriveKey"); exit(1); } /* POTENTIAL FLAW: Possibly using a hardcoded crypto key */ /* Use the derived key to encrypt something */ if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted))) { printLine("Error in CryptEncrypt"); exit(1); } /* use encrypted block */ printBytesLine(encrypted, encryptedLen); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } }
static void goodG2B() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; { FILE *pFile; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; pFile = fopen("passwords.txt", "r"); if (pFile != NULL) { if (fgetws(data, 100, pFile) == NULL) { data[0] = L'\0'; } fclose(pFile); } else { data[0] = L'\0'; } do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* FIX: Decrypt the password before passing it to the sink */ if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } CWE256_Plaintext_Storage_of_Password__w32_wchar_t_64b_goodG2BSink(&data); }
/* goodB2G uses the BadSource with the GoodSink */ void CWE256_Plaintext_Storage_of_Password__w32_char_53d_goodB2GSink(char * data) { { HANDLE pHandle; char * username = "******"; char * domain = "Domain"; char hashData[100] = HASH_INPUT; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; do { BYTE payload[(100 - 1) * sizeof(char)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserA if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(char)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(char)] = '\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* FIX: Decrypt the password before using it for authentication */ if (LogonUserA( username, domain, data, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } }
void bad() { wchar_t * cryptoKey; wchar_t cryptoKeyBuffer[100] = L""; cryptoKey = cryptoKeyBuffer; badSource(cryptoKey); { HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTHASH hHash; wchar_t toBeEncrypted[] = L"String to be encrypted"; DWORD encryptedLen = wcslen(toBeEncrypted)*sizeof(wchar_t); BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */ /* Copy plaintext (without NUL terminator) into byte buffer */ memcpy(encrypted, toBeEncrypted, encryptedLen); /* Try to get a context with and without a new key set */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0)) { if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET)) { printLine("Error in acquiring cryptographic context"); exit(1); } } /* Create Hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { printLine("Error in creating hash"); exit(1); } /* Hash the cryptoKey */ if(!CryptHashData(hHash, (BYTE *) cryptoKey, wcslen(cryptoKey)*sizeof(wchar_t), 0)) { printLine("Error in hashing cryptoKey"); exit(1); } /* Derive an AES key from the Hashed cryptoKey */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { printLine("Error in CryptDeriveKey"); exit(1); } /* POTENTIAL FLAW: Possibly using a hardcoded crypto key */ /* Use the derived key to encrypt something */ if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted))) { printLine("Error in CryptEncrypt"); exit(1); } /* use encrypted block */ printBytesLine(encrypted, encryptedLen); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } }