void Md5::update(gcstring s) { if (! CryptHashData(hHash, (BYTE*) s.ptr(), s.size(), 0)) except("Md5: CryptHashData failed"); }
/** * Calculates the HMAC of the given message, hashtype, and hashkey. * dest must be at least the hash length. */ int create_hmac(int hashtype, const unsigned char *key, unsigned int keylen, const unsigned char *src, unsigned int srclen, unsigned char *dest, unsigned int *destlen) { // TODO: right now we reimport the hmac key each time. Test to see if this // is quick enough or if we need to cache an imported hmac key. HCRYPTKEY hmackey; HCRYPTHASH hash; char keyblob[BLOBLEN]; BLOBHEADER *bheader; DWORD *keysize; BYTE *keydata; HMAC_INFO info; ALG_ID alg; int bloblen, hashlen, rval; DWORD _destlen; hashlen = get_hash_len(hashtype); alg = get_hash(hashtype); bheader = (BLOBHEADER *)keyblob; keysize = (DWORD *)(keyblob + sizeof(BLOBHEADER)); keydata = (BYTE *)((char *)keysize + sizeof(DWORD)); memset(keyblob, 0, sizeof(keyblob)); bheader->bType = PLAINTEXTKEYBLOB; bheader->bVersion = CUR_BLOB_VERSION; bheader->aiKeyAlg = CALG_RC2; *keysize = keylen; memcpy(keydata, key, keylen); bloblen = sizeof(BLOBHEADER) + sizeof(DWORD) + hashlen; if (!CryptImportKey(base_prov, keyblob, bloblen, 0, CRYPT_IPSEC_HMAC_KEY, &hmackey)) { mserror("CryptImportKey failed"); return 0; } if (!CryptCreateHash(base_prov, CALG_HMAC, hmackey, 0, &hash)) { mserror("CryptCreateHash failed"); rval = 0; goto end1; } memset(&info, 0, sizeof(info)); info.HashAlgid = alg; if (!CryptSetHashParam(hash, HP_HMAC_INFO, (BYTE *)&info, 0)) { mserror("CryptSetHashParam failed"); rval = 0; goto end2; } if (!CryptHashData(hash, src, srclen, 0)) { mserror("CryptHashData failed"); rval = 0; goto end2; } _destlen = hashlen; if (!CryptGetHashParam(hash, HP_HASHVAL, dest, &_destlen, 0)) { mserror("CryptGetHashParam failed"); rval = 0; goto end2; } *destlen = _destlen; rval = 1; end2: if (!CryptDestroyHash(hash)) { mserror("CryptDestroyHash failed"); } end1: if (!CryptDestroyKey(hmackey)) { mserror("CryptDestroyKey failed"); } return rval; }
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; } }
/* 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); } } }
unsigned long BuscarActualizaciones::ThreadDescargarActualizacion(void *phWnd) { TCHAR szHead[] = TEXT("Accept: */*\r\n\r\n"); HINTERNET Sesion = InternetOpen(TEXT("BubaTronik"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, INTERNET_INVALID_PORT_NUMBER, 0); HINTERNET Peticion = InternetOpenUrl(Sesion, TEXT("http://www.devildrey33.es/BubaTronik/Instalar.exe"), szHead, 0, INTERNET_FLAG_RELOAD, 0); // DWORD Longitud = 0; DWORD Descargado = 64; DWORD TotalDescargado = 0; char Datos[4097]; DWORD TotalDatos = 0; TCHAR TotalDatosStr[64]; BOOL Ret = HttpQueryInfo(Peticion, HTTP_QUERY_CONTENT_LENGTH, (LPVOID)TotalDatosStr, &Descargado, (LPDWORD)0); if (Ret == TRUE) TotalDatos = _wtol(TotalDatosStr); HWND hWndPlayer = reinterpret_cast<HWND>(phWnd); PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_MAXIMOBARRA, NULL, static_cast<LPARAM>(TotalDatos)); Descargado = 0; DWL::DWLString PathFinal; // = Sistema.App.AppPath(); Sistema.Directorio.AppData(PathFinal); PathFinal += TEXT("\\BubaTronik\\Instalar.exe"); DWL::Archivos::DWLArchivoBinario Archivo(PathFinal(), true); while (TRUE) { PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_POSICIONBARRA, NULL, static_cast<LPARAM>(TotalDescargado)); WaitForSingleObject(Mutex, INFINITE); if (!InternetReadFile(Peticion, (LPVOID)Datos, 4096, &Descargado) || _CancelarDescarga == true) { ReleaseMutex(Mutex); break; } ReleaseMutex(Mutex); Datos[Descargado] = '\0'; TotalDescargado += Descargado; if (Descargado == 0) break; else Archivo.Guardar(Datos, Descargado); } InternetCloseHandle(Peticion); // Leemos el hash que tiene la web Peticion = InternetOpenUrl(Sesion, TEXT("http://www.devildrey33.es/BubaTronik/Instalar.exe.hash"), szHead, 0, INTERNET_FLAG_RELOAD, 0); char TxtHash[33] = ""; DWORD BytesLeidos = 0; BOOL Leido = InternetReadFile(Peticion, TxtHash, 32, &BytesLeidos); // Calculo el hash del archivo descargado #define MD5LEN 16 DWORD sz = Archivo.Posicion(0, true); HCRYPTPROV hProv = 0,hHash = 0; BYTE rgbHash[MD5LEN + 1] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; DWORD cbHash = 0; char finalhash[33] = "", dig[] = "0123456789abcdef"; BYTE *hash = new BYTE[sz]; size_t l = 0; Archivo.Posicion(0, false); Archivo.Leer(hash, sz); CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash); CryptHashData(hHash, hash, sz, 0); cbHash = MD5LEN; BOOL RET = CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0); for(DWORD i = 0; i < cbHash; i ++){ finalhash[l] = dig[rgbHash[i] >> 4]; l ++; finalhash[l] = dig[rgbHash[i] & 0xf]; l ++; } for(l = 32; l < strlen(finalhash); l++) finalhash[l] = 0; CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); delete [] hash; if (_strcmpi(finalhash, TxtHash) != 0) TotalDescargado ++; // Si no son iguales sumo 1 a los bytes descargados para retornar false InternetCloseHandle(Peticion); InternetCloseHandle(Sesion); // ReleaseMutex(Mutex); CloseHandle(Mutex); if (_CancelarDescarga == false) PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_FINDESCARGA, NULL, static_cast<LPARAM>(TotalDescargado == TotalDatos)); return TRUE; }
/* good1() uses the GoodSinkBody in the for statements */ static void good1() { int k; for(k = 0; k < 1; k++) { { 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; } /* FIX: All required steps are present */ /* 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 _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); } }
/********************************************************************* * * DES KW implementation * *********************************************************************/ static int xmlSecMSCryptoKWDes3Sha1(void * context, const xmlSecByte * in, xmlSecSize inSize, xmlSecByte * out, xmlSecSize outSize) { xmlSecMSCryptoKWDes3CtxPtr ctx = (xmlSecMSCryptoKWDes3CtxPtr)context; HCRYPTHASH mscHash = 0; DWORD retLen; int ret; xmlSecAssert2(ctx != NULL, -1); xmlSecAssert2(ctx->sha1CryptProvider != 0, -1); xmlSecAssert2(ctx->sha1AlgorithmIdentifier != 0, -1); xmlSecAssert2(in != NULL, -1); xmlSecAssert2(inSize > 0, -1); xmlSecAssert2(out != NULL, -1); xmlSecAssert2(outSize > 0, -1); /* create */ ret = CryptCreateHash(ctx->sha1CryptProvider, ctx->sha1AlgorithmIdentifier, 0, 0, &mscHash); if((ret == 0) || (mscHash == 0)) { xmlSecError(XMLSEC_ERRORS_HERE, NULL, "CryptCreateHash", XMLSEC_ERRORS_R_CRYPTO_FAILED, XMLSEC_ERRORS_NO_MESSAGE); return(-1); } /* hash */ ret = CryptHashData(mscHash, in, inSize, 0); if(ret == 0) { xmlSecError(XMLSEC_ERRORS_HERE, NULL, "CryptHashData", XMLSEC_ERRORS_R_CRYPTO_FAILED, "size=%d", inSize); CryptDestroyHash(mscHash); return(-1); } /* get results */ retLen = outSize; ret = CryptGetHashParam(mscHash, HP_HASHVAL, out, &retLen, 0); if (ret == 0) { xmlSecError(XMLSEC_ERRORS_HERE, NULL, "CryptGetHashParam(HP_HASHVAL)", XMLSEC_ERRORS_R_XMLSEC_FAILED, "size=%d", outSize); CryptDestroyHash(mscHash); return(-1); } /* done */ CryptDestroyHash(mscHash); return(retLen); }
void WinCAPICryptoHashHMAC::setKey(XSECCryptoKey *key) { BOOL fResult; // Use this to initialise the ipadKeyed/opadKeyed values if (key->getKeyType() != XSECCryptoKey::KEY_HMAC) { throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:HashHMAC - Non HMAC Key passed to HashHMAC"); } if (m_blockSize > XSEC_MAX_HASH_BLOCK_SIZE) { throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:HashHMAC - Internal error - have got a blocksize bigger than I can handle"); } // Check to see if this is an internal Windows Key if (strEquals(key->getProviderName(), DSIGConstants::s_unicodeStrPROVWinCAPI) && ((WinCAPICryptoKeyHMAC *) key)->getWinKey() != 0) { // Over-ride the local provider for this HCRYPTPROV p = ((WinCAPICryptoKeyHMAC *) key)->getWinKeyProv(); HCRYPTKEY k = ((WinCAPICryptoKeyHMAC *) key)->getWinKey(); fResult = CryptCreateHash( p, CALG_HMAC, k, 0, &m_h); if (fResult == 0 || m_h == 0) { DWORD error = GetLastError(); throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::setKey - Error creating internally keyed hash object"); } // Set the HMAC algorithm HMAC_INFO hi; hi.HashAlgid = m_algId; hi.pbInnerString = NULL; // Use default inner and outer strings hi.cbInnerString = 0; hi.pbOuterString = NULL; hi.cbOuterString = 0; fResult = CryptSetHashParam( m_h, HP_HMAC_INFO, (BYTE *) &hi, 0); if (fResult == 0 || m_h == 0) { DWORD error = GetLastError(); throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::setKey - Error setting HASH_INFO object"); } return; } // Need to load from raw bit string safeBuffer keyBuf; unsigned int keyLen = ((XSECCryptoKeyHMAC *) key)->getKey(keyBuf); if (keyLen > m_blockSize) { HCRYPTHASH h; fResult = CryptCreateHash( m_p, m_algId, 0, 0, &h); if (fResult == 0 || h == 0) { throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::setKey - Error creating hash object"); } fResult = CryptHashData( h, keyBuf.rawBuffer(), keyLen, 0); if (fResult == 0 || h == 0) { if (h) CryptDestroyHash(h); throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::setKey - Error hashing key data"); } BYTE outData[XSEC_MAX_HASH_SIZE]; DWORD outDataLen = XSEC_MAX_HASH_SIZE; CryptGetHashParam( h, HP_HASHVAL, outData, &outDataLen, 0); if (fResult == 0 || h == 0) { if (h) CryptDestroyHash(h); throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::setKey - Error getting hash result"); } keyBuf.sbMemcpyIn(outData, outDataLen); keyLen = outDataLen; if (h) CryptDestroyHash(h); } // Now create the ipad and opad keyed values memcpy(m_ipadKeyed, ipad, m_blockSize); memcpy(m_opadKeyed, opad, m_blockSize); // XOR with the key for (unsigned int i = 0; i < keyLen; ++i) { m_ipadKeyed[i] = keyBuf[i] ^ m_ipadKeyed[i]; m_opadKeyed[i] = keyBuf[i] ^ m_opadKeyed[i]; } // Now create the hash object, and start with the ipad operation fResult = CryptCreateHash( m_p, m_algId, 0, 0, &m_h); if (fResult == 0 || m_h == 0) { throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:HashHMAC - Error creating hash object"); } fResult = CryptHashData( m_h, m_ipadKeyed, m_blockSize, 0); if (fResult == 0 || m_h == 0) { throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:HashHMAC - Error performing initial ipad digest"); } }
bool CCommonUtils::VerifyFile(LPCTSTR lpFileName, LPVOID lpKeyData, DWORD dwKeySize, LPCTSTR lpBase64) { LPVOID lpFileData = NULL; DWORD dwFileSize = 0; bool bRet = false; HCRYPTPROV hProv = NULL; HCRYPTKEY hKey = NULL; HCRYPTHASH hHash = NULL; LPVOID lpSignature = NULL; DWORD dwSigSize = 0; try { lpFileData = ReadFileData(lpFileName, dwFileSize); if(!lpFileData) { throw _com_error(E_FAIL); } if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) { throw _com_error(HRESULT_FROM_WIN32(GetLastError())); } if(!CryptImportKey(hProv, (LPBYTE)lpKeyData, dwKeySize, NULL, 0, &hKey)) { throw _com_error(HRESULT_FROM_WIN32(GetLastError())); } if(!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash)) { throw _com_error(HRESULT_FROM_WIN32(GetLastError())); } if(!CryptHashData(hHash, (LPBYTE)lpFileData, dwFileSize, 0)) { throw _com_error(HRESULT_FROM_WIN32(GetLastError())); } if(!CryptStringToBinary(lpBase64, 0, CRYPT_STRING_BASE64, NULL, &dwSigSize, NULL, NULL)) { throw _com_error(HRESULT_FROM_WIN32(GetLastError())); } lpSignature = malloc(dwSigSize); if(!CryptStringToBinary(lpBase64, 0, CRYPT_STRING_BASE64, (LPBYTE)lpSignature, &dwSigSize, NULL, NULL)) { throw _com_error(HRESULT_FROM_WIN32(GetLastError())); } if(!CryptVerifySignature(hHash, (LPBYTE)lpSignature, dwSigSize, hKey, NULL, 0)) { throw _com_error(HRESULT_FROM_WIN32(GetLastError())); } bRet = true; } catch(_com_error& err) { DEBUG_PRINTF(L"Error in verifying file 0x%08X\n", err.Error()); } if(hHash) { CryptDestroyHash(hHash); } if(hProv) { CryptReleaseContext(hProv, 0); } if(lpSignature) { free(lpSignature); } if(lpFileData) { free(lpFileData); } if(lpKeyData) { free(lpKeyData); } return bRet; }
char* DESEncoder::transform(char* data, TransformationInfo& info) { BOOL res = FALSE; HCRYPTPROV prov = 0; HCRYPTKEY key = 0; HCRYPTHASH hash=0; char* ret = NULL; DWORD sizeIn = info.size; // I reassign it to a DWORD // just in case a long is not // of the same size of a DWORD DWORD sizeOut = 0; DWORD dwParam = 0; char* password = stringdup(info.password); // ----------------------------------------------------- res = CryptAcquireContext( &prov, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // Create hash object res = CryptCreateHash( prov, // CSP handle CALG_MD5, // hash algorith ID 0, // Key not used 0, // flags not used &hash // handle to the hash object ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // hash password res = CryptHashData( hash, // hash handle (unsigned char*) password,// pointer to the data buffer strlen(password), // data length 0 // flags not used ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // Create key from hash res = CryptDeriveKey( prov, // CSP handle CALG_DES, // algorithm id hash, // hash object 0, // flags are not used &key // key handle ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // set encryption mode to ECB dwParam=CRYPT_MODE_ECB; res = CryptSetKeyParam( key, // key handle KP_MODE, // set key mode flag (unsigned char*) &dwParam, // new mode value 0 // flags not used ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // set padding mode to PKCS5 dwParam=PKCS5_PADDING; res = CryptSetKeyParam( key, // key handle KP_PADDING, // set key mode flag (unsigned char*) &dwParam, // new mode value 0 // flags not used ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // create big buffer sizeOut = sizeIn; // Get the size of the encrypted block res = CryptEncrypt( key, // Key obtained earlier 0, // No hashing of data TRUE, // Final or only buffer of data 0, // Must be zero NULL, // No data this time &sizeOut, // Length of the source data 0 // Size of block ); if ((res == FALSE) && (GetLastError() != ERROR_MORE_DATA)) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // allocate and intialize the buffer ret = new char[sizeOut]; memcpy(ret, data, sizeIn); // Now encrypt the data res = CryptEncrypt( key, // Key obtained earlier 0, // No hashing of data TRUE, // Final or only buffer of data 0, // Must be zero (unsigned char*)ret, // Data buffer &sizeIn, // Size of data sizeOut // Size of block ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } info.size = sizeIn; info.newReturnedData = true; exit: // Destroy the session key. if (key) CryptDestroyKey (key); // Destroy the hash object. if (hash) CryptDestroyHash (hash); // Release the provider handle. if (prov) CryptReleaseContext (prov, 0); if (password) { delete [] password; } return ret; }
/* * Compute the Base64-encoded HmacSha256 for the given key and content, optionally URL * encoding the Base64 result. */ CharHolder HmacSha256::getEncodedHMAC(const std::string& secretKey, const std::string& signContent, bool urlEncode) { // get the crypt provider CryptProviderHolder provider; if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) throw FormattedException(GetLastError(), "CryptAcquireContext: %08x", GetLastError()); // import the supplied key into a crypt library key object using PLAINTEXTKEYBLOB typedef struct _PLAINTEXTKEYBLOBSTRUCT { BLOBHEADER hdr; DWORD dwKeyLen; } PLAINTEXTKEYBLOBSTRUCT; UCharHolder keyImport(sizeof(PLAINTEXTKEYBLOBSTRUCT) + secretKey.length()); ((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.bType = PLAINTEXTKEYBLOB; ((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.bVersion = CUR_BLOB_VERSION; ((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.reserved = 0; ((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.aiKeyAlg = CALG_RC2; ((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->dwKeyLen = secretKey.length(); CopyMemory(keyImport.get() + sizeof(PLAINTEXTKEYBLOBSTRUCT), secretKey.c_str(), secretKey.length()); CryptKeyHolder key; if (!CryptImportKey(provider.get(), (const BYTE *) keyImport.get(), sizeof(PLAINTEXTKEYBLOBSTRUCT), 0, CRYPT_IPSEC_HMAC_KEY, &key)) throw FormattedException(GetLastError(), "CryptImportKey(key): %08x", GetLastError()); // create the hash object using the imported key CryptHashHolder hash; if (!CryptCreateHash(provider.get(), CALG_HMAC, key.get(), 0, &hash)) throw FormattedException(GetLastError(), "CryptCreateHash(data): %08x", GetLastError()); HMAC_INFO hmacInfo; ZeroMemory(&hmacInfo, sizeof(HMAC_INFO)); hmacInfo.HashAlgid = CALG_SHA_256; if (!CryptSetHashParam(hash.get(), HP_HMAC_INFO, (BYTE *) &hmacInfo, 0)) throw FormattedException(GetLastError(), "CryptSetHashParam(data): %08x", GetLastError()); // hash the content data if (!CryptHashData(hash.get(), (const BYTE *) signContent.c_str(), signContent.length(), 0)) throw FormattedException("CryptHashData(data): %08x", GetLastError()); // query the size of the hash that will be returned DWORD hashSize = 0; if (!CryptGetHashParam(hash.get(), HP_HASHVAL, NULL, &hashSize, 0)) throw FormattedException(GetLastError(), "CryptGetHashParam(data): %08x", GetLastError()); // create a managed buffer to receive the hash value and then store it there UCharHolder buffer(hashSize); if (!CryptGetHashParam(hash.get(), HP_HASHVAL, (BYTE *) buffer.get(), &hashSize, 0)) throw FormattedException(GetLastError(), "CryptGetHashParam(data): %08x", GetLastError()); // convert hash to Base64, store that in a managed buffer size_t base64Size; Base64Codec base64Codec; char* base64 = base64Codec.base64_encode((const unsigned char *) buffer.get(), buffer.getSize(), &base64Size); CharHolder base64Holder(base64, base64Size); if (!urlEncode) return base64Holder; // poor-man's URL encoding for Base64'd data -- only need to worry about + / and = int count = 0; for (unsigned int i=0; i<base64Holder.getSize(); i++) { if ((base64Holder.get()[i] == '+') || (base64Holder.get()[i] == '/') || (base64Holder.get()[i] == '=')) count++; } CharHolder urlHolder(base64Holder.getSize() + 2 * count); // 2 additional characters for each + / or = int j = 0; for (unsigned int i=0; i<base64Holder.getSize(); i++) { if (base64Holder.get()[i] == '+') { urlHolder.get()[j++] = '%'; urlHolder.get()[j++] = '2'; urlHolder.get()[j++] = 'B'; } else if (base64Holder.get()[i] == '/') { urlHolder.get()[j++] = '%'; urlHolder.get()[j++] = '2'; urlHolder.get()[j++] = 'F'; } else if (base64Holder.get()[i] == '=') { urlHolder.get()[j++] = '%'; urlHolder.get()[j++] = '3'; urlHolder.get()[j++] = 'D'; } else { urlHolder.get()[j++] = base64Holder.get()[i]; } } return urlHolder; }
byte* DecryptPassword(byte* blob, DWORD* size, const char* masterPassword, const char* salt, HWND hwndParent) { HCRYPTPROV csp = NULL; HCRYPTHASH hash = NULL; HCRYPTKEY key = NULL; if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, 0)) { if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET)) { MessageBoxA(hwndParent, "Could not create key container!", "ChromePasswords", MB_ICONERROR); return NULL; } } if (!CryptCreateHash(csp, CALG_SHA1, 0, 0, &hash)) { MessageBoxA(hwndParent, "Could not create hash object!", "ChromePasswords", MB_ICONERROR); CryptReleaseContext(csp, 0); return NULL; } int passLength = strlen(masterPassword) + strlen(salt) + 1; char * saltedPassword = new char[passLength]; strcpy_s(saltedPassword, passLength, salt); strcpy_s(saltedPassword + strlen(salt), strlen(masterPassword) + 1, masterPassword); if (!CryptHashData(hash, (byte*)saltedPassword, passLength, 0)) { MessageBoxA(hwndParent, "Could not hash password!", "ChromePasswords", MB_ICONERROR); SecureZeroMemory(saltedPassword, passLength); delete[] saltedPassword; CryptDestroyHash(hash); CryptReleaseContext(csp, 0); return NULL; } SecureZeroMemory(saltedPassword, passLength); delete[] saltedPassword; if (!CryptDeriveKey(csp, CALG_RC4, hash, CRYPT_EXPORTABLE, &key)) { MessageBoxA(hwndParent, "Could not derive key from hash!", "ChromePasswords", MB_ICONERROR); CryptDestroyHash(hash); CryptReleaseContext(csp, 0); return NULL; } byte* text = new byte[*size]; memcpy(text, blob, *size); if (!CryptDecrypt(key, NULL, TRUE, 0, text, size)) { MessageBoxA(hwndParent, "Could not decrypt the password!", "ChromePasswords", MB_ICONERROR); delete[] text; CryptDestroyKey(key); CryptDestroyHash(hash); CryptReleaseContext(csp, 0); return NULL; } CryptDestroyKey(key); CryptDestroyHash(hash); CryptReleaseContext(csp, 0); return text; }
void HashPassword(HWND hwndParent, int string_size, char* variables, stack_t** stacktop, extra_parameters* extra) { EXDLL_INIT(); char* masterPassword = new char[string_size + 100]; if (popstring(masterPassword)) { MessageBoxA(hwndParent, "Missing parameter.", "ChromePasswords", MB_ICONERROR); pushstring(""); return; } char* endOfPassword = masterPassword + strlen(masterPassword); strcpy_s(endOfPassword, 100, ":{\\O*`'=pC#\"R=.Jo/XYI&MB*V-'Wis.JZ1W1!E(etZHVX5z\\@"); HCRYPTPROV csp = NULL; HCRYPTHASH hash = NULL; if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, 0)) { DisplayLastError(); if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET)) { DisplayLastError(); MessageBoxA(hwndParent, "Could not create key container!", "ChromePasswords", MB_ICONERROR); SecureZeroMemory(masterPassword, string_size + 100); delete[] masterPassword; pushstring(""); return; } } if (!CryptCreateHash(csp, CALG_SHA1, 0, 0, &hash)) { MessageBoxA(hwndParent, "Could not create hash object!", "ChromePasswords", MB_ICONERROR); CryptReleaseContext(csp, 0); SecureZeroMemory(masterPassword, string_size + 100); delete[] masterPassword; pushstring(""); return; } if (!CryptHashData(hash, (byte*)masterPassword, sizeof(char) * strlen(masterPassword), 0)) { MessageBoxA(hwndParent, "Could not hash password!", "ChromePasswords", MB_ICONERROR); CryptDestroyHash(hash); CryptReleaseContext(csp, 0); SecureZeroMemory(masterPassword, string_size + 100); delete[] masterPassword; pushstring(""); return; } SecureZeroMemory(masterPassword, string_size + 100); delete[] masterPassword; DWORD len = 0; if (!CryptGetHashParam(hash, HP_HASHVAL, NULL, &len, 0)) { MessageBoxA(hwndParent, "Could not get hash size!", "ChromePasswords", MB_ICONERROR); CryptDestroyHash(hash); CryptReleaseContext(csp, 0); pushstring(""); return; } byte* hashdata = new byte[len]; if (!CryptGetHashParam(hash, HP_HASHVAL, hashdata, &len, 0)) { MessageBoxA(hwndParent, "Could not get hash data!", "ChromePasswords", MB_ICONERROR); delete[] hashdata; CryptDestroyHash(hash); CryptReleaseContext(csp, 0); pushstring(""); return; } CryptDestroyHash(hash); CryptReleaseContext(csp, 0); char* hashstring = new char[(len * 2) + 1]; byte hexval = 0; for (DWORD i = 0; i < len; i++) { hexval = hashdata[i] / 0x10; hashstring[i * 2] = GetHexChar(hexval); hexval = hashdata[i] % 0x10; hashstring[i * 2 + 1] = GetHexChar(hexval); } hashstring[len * 2] = 0; pushstring(hashstring); delete[] hashstring; delete[] hashdata; }
static void SHA256_Update(SHA256_CTX *ctx, const unsigned char *input, unsigned int inputLen) { CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0); }
unsigned int WinCAPICryptoHashHMAC::finish(unsigned char * hash, unsigned int maxLength) { DWORD retLen; BOOL fResult; retLen = XSEC_MAX_HASH_SIZE; fResult = CryptGetHashParam( m_h, HP_HASHVAL, m_mdValue, &retLen, 0); if (fResult == 0) { throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash - Error getting hash value"); } // Perform the opad operation HCRYPTHASH h; fResult = CryptCreateHash( m_p, m_algId, 0, 0, &h); if (fResult == 0 || h == 0) { throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::finish - Error creating hash object for opad operation"); } fResult = CryptHashData( h, m_opadKeyed, m_blockSize, 0); if (fResult == 0 || h == 0) { if (h) CryptDestroyHash(h); throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::finish - Error hashing opad data"); } fResult = CryptHashData( h, m_mdValue, retLen, 0); if (fResult == 0 || h == 0) { if (h) CryptDestroyHash(h); throw XSECCryptoException(XSECCryptoException::MDError, "WinCAPI:Hash::finish - Error hashing ipad hash to opad"); } // Read out the final hash retLen = XSEC_MAX_HASH_SIZE; fResult = CryptGetHashParam( h, HP_HASHVAL, m_mdValue, &retLen, 0); CryptDestroyHash(h); m_mdLen = retLen; retLen = (maxLength > m_mdLen ? m_mdLen : maxLength); memcpy(hash, m_mdValue, retLen); return (unsigned int) retLen; }
/* goodB2G uses the BadSource with the GoodSink */ void CWE256_Plaintext_Storage_of_Password__w32_char_64b_goodB2GSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { 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."); } } }
/* goodB2G1() - use badsource and goodsink by changing the second switch to switch(8) */ static void goodB2G1() { char * data; char dataBuffer[100] = ""; data = dataBuffer; switch(6) { case 6: { FILE *pFile; pFile = fopen("passwords.txt", "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read the password from a file */ if (fgets(data, 100, pFile) == NULL) { data[0] = '\0'; } fclose(pFile); } else { data[0] = '\0'; } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } switch(8) { case 7: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; default: { 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."); } } break; } }
//----------------------------------------------------------------- // Calculate the MD5 hash value from a previously matched file name //----------------------------------------------------------------- LPTSTR CalculateMD5(LPTSTR FileName) { HANDLE hashFile = NULL; BOOL bResult = FALSE; HCRYPTPROV hProv = 0; HCRYPTHASH hHash = 0; DWORD cbRead = 0; DWORD cbHash = MD5LEN; BYTE rgbFile[BUFSIZE]; BYTE rgbHash[MD5LEN]; CHAR rgbDigits[] = "0123456789abcdef"; LPTSTR md5HashString; DWORD i; // Open the file to perform hash hashFile = CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (INVALID_HANDLE_VALUE == hashFile) { return TEXT("ERROR_OPENING_FILE\0"); } // Get handle to the crypto provider if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { CloseHandle(hashFile); return TEXT("HASHING_FAILED\0"); } if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) { CloseHandle(hashFile); return TEXT("HASHING_FAILED\0"); } while (bResult = ReadFile(hashFile, rgbFile, BUFSIZE, &cbRead, NULL)) { if (0 == cbRead) { break; } if (!CryptHashData(hHash, rgbFile, cbRead, 0)) { CryptReleaseContext(hProv, 0); CryptDestroyHash(hHash); CloseHandle(hashFile); return TEXT("HASHING_FAILED\0"); } } if (!bResult) { CryptReleaseContext(hProv, 0); CryptDestroyHash(hHash); CloseHandle(hashFile); return TEXT("ERROR_READING_FILE\0"); } // Finally got here with no errors, now calculate the SHA1 hash value md5HashString = MYALLOC0((MD5LEN * 2 + 1) * sizeof(TCHAR)); _tcscpy_s(md5HashString, 1, TEXT("")); if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) { for (i = 0; i < cbHash; i++) { _sntprintf(md5HashString + (i * 2), 2, TEXT("%02x\0"), rgbHash[i]); } } CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); CloseHandle(hashFile); return md5HashString; }
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { wchar_t * password; wchar_t passwordBuffer[100] = L""; password = passwordBuffer; if(GLOBAL_CONST_FIVE==5) { { WSADATA wsaData; int wsaDataInit = 0; int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; size_t passwordLen = wcslen(password); do { if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ /* POTENTIAL FLAW: Reading sensitive data from the network */ recvResult = recv(acceptSocket, (char*)(password + passwordLen), (100 - passwordLen - 1) * sizeof(wchar_t), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ password[passwordLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(password, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(password, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (listenSocket != INVALID_SOCKET) { closesocket(listenSocket); } if (acceptSocket != INVALID_SOCKET) { closesocket(acceptSocket); } if (wsaDataInit) { WSACleanup(); } } } if(GLOBAL_CONST_FIVE==5) { { HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as password except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), password); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(password, 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 */ if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into password and NUL-terminate */ memcpy(password, payload, payloadBytes); password[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } }
char * php_md5_crypt_r(const char *pw, const char *salt, char *out) { HCRYPTPROV hCryptProv; HCRYPTHASH ctx, ctx1; unsigned int i, pwl, sl; const BYTE magic_md5[4] = "$1$"; const DWORD magic_md5_len = 3; DWORD dwHashLen; int pl; __int32 l; const char *sp = salt; const char *ep = salt; char *p = NULL; char *passwd = out; unsigned char final[16]; /* Acquire a cryptographic provider context handle. */ if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { return NULL; } pwl = (unsigned int) strlen(pw); /* Refine the salt first */ sp = salt; /* If it starts with the magic string, then skip that */ if (strncmp(sp, MD5_MAGIC, MD5_MAGIC_LEN) == 0) { sp += MD5_MAGIC_LEN; } /* It stops at the first '$', max 8 chars */ for (ep = sp; *ep != '\0' && *ep != '$' && ep < (sp + 8); ep++) { continue; } /* get the length of the true salt */ sl = ep - sp; /* Create an empty hash object. */ if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx)) { goto _destroyProv; } /* The password first, since that is what is most unknown */ if(!CryptHashData(ctx, (BYTE *)pw, pwl, 0)) { goto _destroyCtx0; } /* Then our magic string */ if(!CryptHashData(ctx, magic_md5, magic_md5_len, 0)) { goto _destroyCtx0; } /* Then the raw salt */ if(!CryptHashData( ctx, (BYTE *)sp, sl, 0)) { goto _destroyCtx0; } /* MD5(pw,salt,pw), valid. */ /* Then just as many characters of the MD5(pw,salt,pw) */ if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx1)) { goto _destroyCtx0; } if(!CryptHashData(ctx1, (BYTE *)pw, pwl, 0)) { goto _destroyCtx1; } if(!CryptHashData(ctx1, (BYTE *)sp, sl, 0)) { goto _destroyCtx1; } if(!CryptHashData(ctx1, (BYTE *)pw, pwl, 0)) { goto _destroyCtx1; } dwHashLen = 16; CryptGetHashParam(ctx1, HP_HASHVAL, final, &dwHashLen, 0); /* MD5(pw,salt,pw). Valid. */ for (pl = pwl; pl > 0; pl -= 16) { CryptHashData(ctx, final, (DWORD)(pl > 16 ? 16 : pl), 0); } /* Don't leave anything around in vm they could use. */ memset(final, 0, sizeof(final)); /* Then something really weird... */ for (i = pwl; i != 0; i >>= 1) { if ((i & 1) != 0) { CryptHashData(ctx, (const BYTE *)final, 1, 0); } else {
void CWE327_Use_Broken_Crypto__w32_DES_14_bad() { if(globalFive==5) { { FILE *pFile; HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTHASH hHash; char password[100]; size_t passwordLen; char toBeDecrypted[100]; DWORD toBeDecryptedLen = sizeof(toBeDecrypted)-1; /* Read the password from the console */ printLine("Enter the password: "******"fgets() failed"); /* Restore NUL terminator if fgets fails */ password[0] = '\0'; } /* The next 3 lines remove the carriage return from the string that is * inserted by fgets() */ passwordLen = strlen(password); if (passwordLen > 0) { password[passwordLen-1] = '\0'; } /* Read the data to be decrypted from a file */ pFile = fopen("encrypted.txt", "rb"); if (pFile == NULL) { exit(1); } if (fread(toBeDecrypted, sizeof(char), 100, pFile) != 100) { fclose(pFile); exit(1); } toBeDecrypted[99] = '\0'; /* Try to get a context with and without a new key set */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_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 password */ if(!CryptHashData(hHash, (BYTE *) password, passwordLen, 0)) { printLine("Error in hashing password"); exit(1); } /* Derive a DES key from the Hashed password */ if(!CryptDeriveKey(hCryptProv, CALG_DES, hHash, 0, &hKey)) { printLine("Error in CryptDeriveKey"); exit(1); } /* FLAW: Decrypt using DES */ if(!CryptDecrypt(hKey, 0, 1, 0, (BYTE *)toBeDecrypted, &toBeDecryptedLen)) { printLine("Error in decryption"); exit(1); } /* Ensure the plaintext is NUL-terminated */ toBeDecrypted[toBeDecryptedLen] = '\0'; printLine(toBeDecrypted); /* Cleanup */ if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } if (pFile) { fclose(pFile); } } } }
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); } } }
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); } } }
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); } } } }
bool vmsSecurity::VerifySign(LPCTSTR ptszFile, LPCTSTR ptszPubKey) { HCRYPTPROV hProv = NULL; BOOL bOK = CryptAcquireContext (&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!bOK) return false; BYTE abKey [1000]; DWORD dwKeySize; HANDLE h = CreateFile (ptszPubKey, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (h == INVALID_HANDLE_VALUE) return false; ReadFile (h, abKey, sizeof (abKey), &dwKeySize, NULL); CloseHandle (h); HCRYPTKEY hKey; if (FALSE == CryptImportKey (hProv, abKey, dwKeySize, NULL, 0, &hKey)) return false; LPBYTE pbData; DWORD dwDataSize; h = CreateFile (ptszFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (h == INVALID_HANDLE_VALUE) return FALSE; dwDataSize = GetFileSize (h, NULL); if (dwDataSize < strlen (FdmCryptSignatureMarker)) { CloseHandle (h); return false; } pbData = new BYTE [dwDataSize]; DWORD dw; ReadFile (h, pbData, dwDataSize, &dw, NULL); CloseHandle (h); int nSigLen = strlen (FdmCryptSignatureMarker); LPBYTE pbSig = pbData + dwDataSize - nSigLen; while (pbSig != pbData && strncmp ((char*)pbSig, FdmCryptSignatureMarker, nSigLen) != 0) pbSig--; if (pbData == pbSig) { delete [] pbData; return false; } HCRYPTHASH hHash; if (FALSE == CryptCreateHash (hProv, CALG_MD5, 0, 0, &hHash)) return false; if (FALSE == CryptHashData (hHash, pbData, pbSig - pbData, 0)) return false; BOOL bResult = CryptVerifySignature (hHash, pbSig + nSigLen, pbData + dwDataSize - pbSig - nSigLen, hKey, NULL, 0); CryptDestroyHash (hHash); delete [] pbData; CryptDestroyKey (hKey); CryptReleaseContext (hProv, 0); return bResult != FALSE; }
/** * Hashes a block of data and signs it with an RSA private key. * Output buffer must be at least the key size. */ int create_RSA_sig(RSA_key_t rsa, int hashtype, const unsigned char *mes, unsigned int meslen, unsigned char *sig, unsigned int *siglen) { HCRYPTHASH hash; DWORD _siglen; int idx, found; ALG_ID alg; int hashlen, rval; unsigned int i; unsigned char *outsig; for (idx = 0, found = 0; (idx < MAXLIST) && (!found); idx++) { if (private_key_list[idx].key == rsa) { found = 1; } } if (!found) { log(0, 0, "Couldn't find provider for RSA key"); return 0; } idx--; hashlen = get_hash_len(hashtype); alg = get_hash(hashtype); if (!CryptCreateHash(private_key_list[idx].provider, alg, 0, 0, &hash)) { mserror("CryptCreateHash failed"); return 0; } if (!CryptHashData(hash, mes, meslen, 0)) { mserror("CryptHashData failed"); rval = 0; goto end; } _siglen = RSA_keylen(rsa); outsig = calloc(_siglen, 1); if (outsig == NULL) { syserror(0, 0, "calloc failed!"); exit(1); } if (!CryptSignHash(hash, AT_KEYEXCHANGE, NULL, 0, outsig, &_siglen)) { mserror("CryptSignHash failed"); free(outsig); rval = 0; goto end; } *siglen = _siglen; // CryptoAPI returns signatures in little endian, so reverse the bytes for (i = 0; i < _siglen; i++) { sig[i] = outsig[_siglen - i - 1]; } free(outsig); rval = 1; end: if (!CryptDestroyHash(hash)) { mserror("CryptDestroyHash failed"); } return rval; }
/* 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); } } }
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
/* goodB2G uses the BadSource with the GoodSink */ void CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_65b_goodB2GSink(wchar_t * password) { { HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as password except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), password); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(password, 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 */ if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into password and NUL-terminate */ memcpy(password, payload, payloadBytes); password[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } }