Exemplo n.º 1
0
int entropy_fun(unsigned char buf[], unsigned int len)
{
    HCRYPTPROV provider;
    unsigned __int64 pentium_tsc[1];
    unsigned int i;
    int result = 0;


    if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
    {
        result = CryptGenRandom(provider, len, buf);
        CryptReleaseContext(provider, 0);
        if (result)
            return len;
    }

    QueryPerformanceCounter((LARGE_INTEGER *)pentium_tsc);

    for(i = 0; i < 8 && i < len; ++i)
        buf[i] = ((unsigned char*)pentium_tsc)[i];

    return i;
}
static int
arc4_seed_win32(void)
{
	/* This is adapted from Tor's crypto_seed_rng() */
	static int provider_set = 0;
	static HCRYPTPROV provider;
	unsigned char buf[ADD_ENTROPY];

	if (!provider_set) {
		if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
		    CRYPT_VERIFYCONTEXT)) {
			if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
				return -1;
		}
		provider_set = 1;
	}
	if (!CryptGenRandom(provider, sizeof(buf), buf))
		return -1;
	arc4_addrandom(buf, sizeof(buf));
	memset(buf, 0, sizeof(buf));
	arc4_seeded_ok = 1;
	return 0;
}
Exemplo n.º 3
0
unsigned int
getrandom_chars(int desired, unsigned char *buf, int lenbuf) {
	HCRYPTPROV hcryptprov;
	BOOL err;

	if (buf == NULL || lenbuf <= 0 || desired > lenbuf)
		return (0);
	/*
	 * The first time we just try to acquire the context
	 */
	err = CryptAcquireContext(&hcryptprov, NULL, NULL, PROV_RSA_FULL,
				  CRYPT_VERIFYCONTEXT);
	if (!err){
		return (0);
	}
	if (!CryptGenRandom(hcryptprov, desired, buf)) {
		CryptReleaseContext(hcryptprov, 0);
		return (0);
	}

	CryptReleaseContext(hcryptprov, 0);
	return (desired);
}
Exemplo n.º 4
0
BOOL CreateKeyset(HCRYPTPROV *hProv) {
	HCRYPTKEY hXchgKey;
	LONG error;
	if(!CryptAcquireContext(hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
		return FALSE;

    if(!CryptGenKey(*hProv,AT_SIGNATURE,0,&hXchgKey))  {
		error=GetLastError();
		CryptReleaseContext(*hProv, 0);
		SetLastError(error);
		return FALSE;
	}
    CryptDestroyKey(hXchgKey);
    
	if(!CryptGenKey(*hProv,AT_KEYEXCHANGE,CRYPT_EXPORTABLE,&hXchgKey)) {
		error=GetLastError();
		CryptReleaseContext(*hProv, 0);
		SetLastError(error);
		return FALSE;
	}
	CryptDestroyKey(hXchgKey);
	return TRUE;
}
Exemplo n.º 5
0
/**
 * exsltCryptoCryptoApiHash:
 * @ctxt: an XPath parser context
 * @algorithm: hashing algorithm to use
 * @msg: text to be hashed
 * @msglen: length of text to be hashed
 * @dest: buffer to place hash result
 *
 * Helper function which hashes a message using MD4, MD5, or SHA1.
 * Uses Win32 CryptoAPI.
 */
static void
exsltCryptoCryptoApiHash (xmlXPathParserContextPtr ctxt,
			  ALG_ID algorithm, const char *msg,
			  unsigned long msglen,
			  char dest[HASH_DIGEST_LENGTH]) {
    HCRYPTPROV hCryptProv;
    HCRYPTHASH hHash;

    if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL,
			      CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
	exsltCryptoCryptoApiReportError (ctxt, __LINE__);
	return;
    }

    hHash = exsltCryptoCryptoApiCreateHash (ctxt, hCryptProv,
					    algorithm, msg, msglen,
					    dest, HASH_DIGEST_LENGTH);
    if (0 != hHash) {
	CryptDestroyHash (hHash);
    }

    CryptReleaseContext (hCryptProv, 0);
}
Exemplo n.º 6
0
/**
 * Loads an RSA private key from the specified key container
 */
RSA_key_t read_RSA_key(const char *container)
{
    int idx, found;
    const char *_container;

    // First find available private key slot
    for (idx = 0, found = 0; (idx < MAXLIST) && (!found); idx++) {
        if (private_key_list[idx].provider == 0) {
            found = 1;
        }
    }
    if (!found) {
        log(0, 0, "Couldn't find empty key slot for private key");
        return (RSA_key_t)NULL;
    }
    idx--;

    if (!strcmp(container, "")) {
        _container = DEF_KEY_CONTAINER;
    } else {
        _container = container;
    }

    if (!CryptAcquireContext(&private_key_list[idx].provider, _container,
                             NULL, prov_type, machine_keyset)) {
        mserror("CryptAcquireContext failed");
        return (RSA_key_t)NULL;
    }

    if (!CryptGetUserKey(private_key_list[idx].provider, AT_KEYEXCHANGE,
                         &private_key_list[idx].key)) {
        mserror("CryptGetUserKey failed");
        return (RSA_key_t)NULL;
    }

    return (RSA_key_t)private_key_list[idx].key;
}
Exemplo n.º 7
0
Arquivo: srp.c Projeto: cocagne/csrp
static void init_random()
{    
#ifdef WIN32
    HCRYPTPROV wctx;
#else
    FILE   *fp   = 0;
#endif
    
    unsigned char buff[64];

    if (g_initialized)
        return;
    
#ifdef WIN32

        CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
        
        CryptGenRandom(wctx, sizeof(buff), (BYTE*) buff);
        
        CryptReleaseContext(wctx, 0);

        g_initialized = 1;
        
#else
        fp = fopen("/dev/urandom", "r");
        
        if (fp)
        {
            size_t read = fread(buff, sizeof(buff), 1, fp);
            g_initialized = read == 1;
            fclose(fp);
        }
#endif

    if (g_initialized)
       RAND_seed( buff, sizeof(buff) );
}
Exemplo n.º 8
0
void randombytes(void *ptr, size_t length)
{

    char failed = 0;

    #ifdef WIN32

    static HCRYPTPROV prov = 0;
    if (prov == 0) {
        if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) {
            failed = 1;
        }
    }
    if (!failed && !CryptGenRandom(prov, length, ptr)) {
        failed = 1;
    }

    #else

    int fh;
    if ((fh = open("/dev/urandom", O_RDONLY)) >= 0 || (fh = open("/dev/random", O_RDONLY)) >= 0) {
        const ssize_t ret = read(fh, ptr, length);
        if (ret < 0 || (size_t) ret != length) {
            failed = 1;
        }
        close(fh);
    } else {
        failed = 1;
    }

    #endif

    if (failed) {
        ErrorExit("%s: ERROR: randombytes failed for all possible methods for accessing random data", __local_name);
    }
}
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;
}
Exemplo n.º 10
0
int mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len,
                           size_t *olen )
{
    HCRYPTPROV provider;
    ((void) data);
    *olen = 0;

    if( CryptAcquireContext( &provider, NULL, NULL,
                              PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) == FALSE )
    {
        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
    }

    if( CryptGenRandom( provider, (DWORD) len, output ) == FALSE )
    {
        CryptReleaseContext( provider, 0 );
        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
    }

    CryptReleaseContext( provider, 0 );
    *olen = len;

    return( 0 );
}
Exemplo n.º 11
0
void cryptographicallyRandomValuesFromOS(unsigned char* buffer, size_t length)
{
#if OS(UNIX)
    int fd = open("/dev/urandom", O_RDONLY, 0);
    if (fd < 0)
        CRASH(); // We need /dev/urandom for this API to work...

    if (read(fd, buffer, length) != static_cast<ssize_t>(length))
        CRASH();

    close(fd);
#elif OS(WINDOWS)
    HCRYPTPROV hCryptProv = 0;
    if (!CryptAcquireContext(&hCryptProv, 0, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
        CRASH();
    if (!CryptGenRandom(hCryptProv, length, buffer))
        CRASH();
    CryptReleaseContext(hCryptProv, 0);
#else
    #error "This configuration doesn't have a strong source of randomness."
    // WARNING: When adding new sources of OS randomness, the randomness must
    //          be of cryptographic quality!
#endif
}
Exemplo n.º 12
0
void GenRandomBytes(void* dest, size_t size)
{
#ifdef _WIN32
	HCRYPTPROV prov;
	if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
		Sys::Error("CryptAcquireContext failed: %s", Win32StrError(GetLastError()));

	if (!CryptGenRandom(prov, size, (BYTE*)dest))
		Sys::Error("CryptGenRandom failed: %s", Win32StrError(GetLastError()));

	CryptReleaseContext(prov, 0);
#elif defined(__native_client__)
	size_t bytes_written;
	if (nacl_secure_random(dest, size, &bytes_written) != 0 || bytes_written != size)
		Sys::Error("nacl_secure_random failed");
#else
	int fd = open("/dev/urandom", O_RDONLY);
	if (fd == -1)
		Sys::Error("Failed to open /dev/urandom: %s", strerror(errno));
	if (read(fd, dest, size) != (ssize_t) size)
		Sys::Error("Failed to read from /dev/urandom: %s", strerror(errno));
	close(fd);
#endif
}
Exemplo n.º 13
0
/**
 *
 *  Generate System key from pass phrase -> level 2
 *  Derives 128-bit value from MD5
 *
 */
BOOL SystemKey::SetFromPassword (std::wstring pwd) {
  HCRYPTPROV hProv;
  HCRYPTHASH hHash;

  if (CryptAcquireContext (&hProv, NULL, NULL, PROV_RSA_FULL,
      CRYPT_VERIFYCONTEXT)) {
    if (CryptCreateHash (hProv, CALG_MD5, 0, 0, &hHash)) {
      if (CryptHashData (hHash, (PBYTE)pwd.c_str(),
          pwd.length() * sizeof(wchar_t), 0)) {

        DWORD dwHashLen = SYSTEM_KEY_LEN;
        CryptGetHashParam (hHash, HP_HASHVAL, key, &dwHashLen, 0);
        dwError = GetLastError();
      }
      CryptDestroyHash (hHash);
    } else {
      dwError = GetLastError ();
    }
    CryptReleaseContext (hProv, 0);
  } else {
    dwError = GetLastError ();
  }
  return dwError == ERROR_SUCCESS;
}
Exemplo n.º 14
0
bool mod_hash::getHbootKeyFromBootKeyAndF(BYTE hBootKey[0x10], BYTE bootKey[0x10], BYTE * AccountsF)
{
	bool reussite = false;
	unsigned char qwe[] = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%";
	unsigned char num[] = "0123456789012345678901234567890123456789";

	HCRYPTPROV hCryptProv = NULL;
	HCRYPTHASH hHash = NULL;
	if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
	{
		BYTE md5hash[0x10] = {0};
		DWORD dwHashDataLen = sizeof(md5hash);
		CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash);
		CryptHashData(hHash, AccountsF + 0x70, 0x10, 0);
		CryptHashData(hHash, qwe, sizeof(qwe), 0);
		CryptHashData(hHash, bootKey, 0x10, 0);
		CryptHashData(hHash, num, sizeof(num), 0);
		CryptGetHashParam(hHash, HP_HASHVAL, md5hash, &dwHashDataLen, 0);
		CryptDestroyHash(hHash);
		CryptReleaseContext(hCryptProv, 0);
		reussite = mod_crypto::genericDecrypt(AccountsF + 0x80, 0x10, md5hash, 0x10, CALG_RC4, hBootKey, 0x10);
	}
	return reussite;
}
Exemplo n.º 15
0
/*
 * On Windows, CryptGenRandom is supposed to be a well-seeded
 * cryptographically strong random number generator.
 */
int
getentropy(void *buf, size_t len)
{
	HCRYPTPROV provider;

	if (len > 256) {
		errno = EIO;
		return -1;
	}

	if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
	    CRYPT_VERIFYCONTEXT) != 0)
		goto fail;
	if (CryptGenRandom(provider, len, buf) != 0) {
		CryptReleaseContext(provider, 0);
		goto fail;
	}
	CryptReleaseContext(provider, 0);
	return (0);

fail:
	errno = EIO;
	return (-1);
}
Exemplo n.º 16
0
void vlc_rand_bytes (void *buf, size_t len)
{
    HCRYPTPROV hProv;
    size_t count = len;
    uint8_t *p_buf = (uint8_t *)buf;

    /* fill buffer with pseudo-random data */
    while (count > 0)
    {
        unsigned int val;
        val = rand();
        if (count < sizeof (val))
        {
            memcpy (p_buf, &val, count);
            break;
        }
 
        memcpy (p_buf, &val, sizeof (val));
        count -= sizeof (val);
        p_buf += sizeof (val);
    }

    /* acquire default encryption context */
    if( CryptAcquireContext(
        &hProv,            // Variable to hold returned handle.
        NULL,              // Use default key container.
        MS_DEF_PROV,       // Use default CSP.
        PROV_RSA_FULL,     // Type of provider to acquire.
        0) )
    {
        /* fill buffer with pseudo-random data, intial buffer content
           is used as auxillary random seed */
        CryptGenRandom(hProv, len, buf);
        CryptReleaseContext(hProv, 0);
    }
}
Exemplo n.º 17
0
String WebCore::signedPublicKeyAndChallengeString(unsigned index, const String& challenge, const KURL& url)
{
    String keyString;

    HCRYPTPROV hContext = 0;
    HCRYPTKEY hKey = 0;
    PCERT_PUBLIC_KEY_INFO pPubInfo = 0;

    // Try to delete it if it exists already
    CryptAcquireContext(&hContext, _T("keygen_container"), MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_DELETEKEYSET);

    do {
        if (!CryptAcquireContext(&hContext, _T("keygen_container"), MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
            break;

        DWORD dwPubInfoLength = 0;
        if (!CryptGenKey(hContext, AT_KEYEXCHANGE, 0, &hKey) || !CryptExportPublicKeyInfo(hContext, AT_KEYEXCHANGE, X509_ASN_ENCODING, 0, &dwPubInfoLength))
            break;

        // Use malloc instead of new, because malloc guarantees to return a pointer aligned for all data types.
        pPubInfo = reinterpret_cast<PCERT_PUBLIC_KEY_INFO>(fastMalloc(dwPubInfoLength));

        if (!CryptExportPublicKeyInfo(hContext, AT_KEYEXCHANGE, X509_ASN_ENCODING, pPubInfo, &dwPubInfoLength))
            break;

        CERT_KEYGEN_REQUEST_INFO requestInfo = { 0 };
        requestInfo.dwVersion = CERT_KEYGEN_REQUEST_V1;
        requestInfo.pwszChallengeString = L"";
        requestInfo.SubjectPublicKeyInfo = *pPubInfo;

        String localChallenge = challenge;

        // Windows API won't write to our buffer, although it's not declared with const.
        requestInfo.pwszChallengeString = const_cast<wchar_t*>(localChallenge.charactersWithNullTermination());

        CRYPT_ALGORITHM_IDENTIFIER signAlgo = { 0 };
        signAlgo.pszObjId = szOID_RSA_SHA1RSA;

        DWORD dwEncodedLength;
        if (!CryptSignAndEncodeCertificate(hContext, AT_KEYEXCHANGE, X509_ASN_ENCODING, X509_KEYGEN_REQUEST_TO_BE_SIGNED, &requestInfo, &signAlgo, 0, 0, &dwEncodedLength))
            break;

        Vector<char> binary(dwEncodedLength);
        if (!CryptSignAndEncodeCertificate(hContext, AT_KEYEXCHANGE, X509_ASN_ENCODING, X509_KEYGEN_REQUEST_TO_BE_SIGNED, &requestInfo, &signAlgo, 0, reinterpret_cast<LPBYTE>(binary.data()), &dwEncodedLength))
            break;

        Vector<char> base64;
        base64Encode(binary, base64);
        keyString = String(base64.data(), base64.size());

    } while(0);

    if (pPubInfo)
        fastFree(pPubInfo);
       
    if (hKey)
        CryptDestroyKey(hKey);

    if (hContext)
        CryptReleaseContext(hContext, 0);

    return keyString;
}
/* 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.");
            }
        }
    }
}
Exemplo n.º 19
0
STATUS
GetSHA1Hash(
    IN CONST PBYTE Buffer,
    IN CONST DWORD BufferSize,
    OUT PBYTE HashValue,
    IN OUT PDWORD HashValueSize
)
{
    HCRYPTPROV hProv;
    HCRYPTHASH hHash;
    DWORD dwHashSize;
    DWORD dwCount;
    BOOL bCryptResult;
    ERRORINFO err;

    dwCount = sizeof(DWORD);

    bCryptResult = CryptAcquireContext( &hProv,
                                        NULL,
                                        NULL,
                                        PROV_RSA_FULL,
                                        CRYPT_VERIFYCONTEXT);
    if ( bCryptResult == FALSE )
    {
        REPORT_ERROR("CryptAcquireContext", &err);
        return MCEDP_STATUS_INTERNAL_ERROR;
    }

    bCryptResult = CryptCreateHash( hProv,
                                    CALG_SHA1,
                                    0,
                                    0,
                                    &hHash);
    if ( bCryptResult == FALSE)
    {
        REPORT_ERROR("CryptCreateHash", &err);
        CryptDestroyHash(hHash);
        return MCEDP_STATUS_INTERNAL_ERROR;
    }

    bCryptResult = CryptHashData(hHash, (CONST PBYTE) Buffer, BufferSize, 0);

    if ( bCryptResult == FALSE )
    {
        REPORT_ERROR("CryptHashData", &err);
        CryptReleaseContext(hProv, 0);
        CryptDestroyHash(hHash);
        return MCEDP_STATUS_INTERNAL_ERROR;
    }

    bCryptResult = CryptGetHashParam( hHash,
                                      HP_HASHSIZE,
                                      (PBYTE)&dwHashSize,
                                      &dwCount,
                                      0);

    if ( *HashValueSize < dwHashSize )
    {
        DEBUG_PRINTF( LDBG, NULL, "Hash Buffer too small\n");
        CryptReleaseContext(hProv, 0);
        CryptDestroyHash(hHash);
        return MCEDP_STATUS_INSUFFICIENT_BUFFER;
    }

    bCryptResult = CryptGetHashParam( hHash,
                                      HP_HASHVAL,
                                      HashValue,
                                      HashValueSize,
                                      0);

    if ( bCryptResult == FALSE )
    {
        REPORT_ERROR("CryptGetHashParam", &err);
        CryptReleaseContext(hProv, 0);
        CryptDestroyHash(hHash);
        return MCEDP_STATUS_INTERNAL_ERROR;
    }

    *HashValueSize = dwHashSize;
    CryptReleaseContext(hProv, 0);
    CryptDestroyHash(hHash);
    return MCEDP_STATUS_SUCCESS;
}
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 (&ltemp, 1, sizeof (unsigned long), hSource);
		fread (&ltemp, 1, sizeof (unsigned long), hSource);
		fread (&ltemp, 1, sizeof (unsigned long), hSource);
		fread (&ltemp, 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
Exemplo n.º 21
0
isc_result_t
isc_entropy_createfilesource(isc_entropy_t *ent, const char *fname) {
	isc_result_t ret;
	isc_entropysource_t *source;
	HCRYPTPROV hcryptprov;
	BOOL err;

	REQUIRE(VALID_ENTROPY(ent));
	REQUIRE(fname != NULL);

	LOCK(&ent->lock);

	source = NULL;

	/*
	 * The first time we just try to acquire the context
	 */
	err = CryptAcquireContext(&hcryptprov, NULL, NULL, PROV_RSA_FULL,
				  CRYPT_VERIFYCONTEXT);
	if (!err){
		(void)GetLastError();
		ret = ISC_R_IOERROR;
		goto errout;
	}

	source = isc_mem_get(ent->mctx, sizeof(isc_entropysource_t));
	if (source == NULL) {
		ret = ISC_R_NOMEMORY;
		goto closecontext;
	}

	/*
	 * From here down, no failures can occur.
	 */
	source->magic = SOURCE_MAGIC;
	source->type = ENTROPY_SOURCETYPE_FILE;
	source->ent = ent;
	source->total = 0;
	source->bad = ISC_FALSE;
	memset(source->name, 0, sizeof(source->name));
	ISC_LINK_INIT(source, link);
	source->sources.file.handle = hcryptprov;

	/*
	 * Hook it into the entropy system.
	 */
	ISC_LIST_APPEND(ent->sources, source, link);
	ent->nsources++;

	UNLOCK(&ent->lock);
	return (ISC_R_SUCCESS);

 closecontext:
	CryptReleaseContext(hcryptprov, 0);

 errout:
	if (source != NULL)
		isc_mem_put(ent->mctx, source, sizeof(isc_entropysource_t));

	UNLOCK(&ent->lock);

	return (ret);
}
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);
}
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);
            }
        }
    }
}
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;
}
Exemplo n.º 26
0
static char *DigiCrypt_GetDefaultKeyContainerName(char *psCSPName)
{
char *psRes = NULL;
HCRYPTPROV hProvider;
BOOL  fRes;
DWORD dwFlags = CRYPT_VERIFYCONTEXT;
BYTE pbData[dNAME_ITEM_LEN+1];
DWORD cbData = dNAME_ITEM_LEN;
DWORD dwError;
DWORD dwProvType;

ZeroMemory(pbData,cbData);
ZeroMemory(oG_sKeyContainerName,1000);

dwProvType = DigiCrypt_FindContext_GetCSPType(psCSPName);

//LOG("GetDefaultKeyContainerName CSP=%s",psCSPName);
if (lstrcmp(psCSPName,psData_Extra_CSP_Name) != 0)
  fRes = CryptAcquireContext(&hProvider,NULL,psCSPName,dwProvType, CRYPT_SILENT);
else
   fRes = CryptAcquireContext(&hProvider,NULL,psCSPName,dwProvType, CRYPT_VERIFYCONTEXT);

if (fRes == FALSE && dwFlags == CRYPT_SILENT)
  {
  //by description must be CRYPT_VERIFYCONTEXT
  fRes = CryptAcquireContext(&hProvider,NULL,psCSPName,dwProvType, CRYPT_VERIFYCONTEXT);
  }

if (fRes == TRUE)
  {
  cbData = dNAME_ITEM_LEN;
  fRes = CryptGetProvParam(hProvider, PP_CONTAINER, pbData, &cbData, 0);

  /*if (fRes == FALSE)
    dwError = GetLastError();*/
  }


  //Some cards should not have default key container
  //let try to find key containers on the card.
  if (fRes == FALSE)
  {
     fRes=CryptGetProvParam(hProvider, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);
	   if (fRes == FALSE)
           dwError = GetLastError();
  }

  
  if (fRes == TRUE)
  {

  //oG_hProvider = hProvider;
  lstrcpy(oG_sKeyContainerName,(char *) pbData);
  //psRes = oG_sKeyContainerName;
  DigiCrypt_ChangeContainerName(oG_sKeyContainerName);
  }
  else
  {
  
  }


if (psRes != NULL)
  LOG("GetDefaultKeyContainerName CSP=%s",psCSPName);
else
 LOG("GetDefaultKeyContainerName Not found");


  if (hProvider != 0)
    CryptReleaseContext(hProvider, 0);


return(oG_sKeyContainerName);
}
Exemplo n.º 27
0
static char *DigiCrypt_GetFirstAllowedCSPName(void)
{
char *psRes = NULL;
HKEY  hKey = NULL;
LONG  lRet=0;
DWORD dwIndex = 0;
BOOL  fRes;
char sProvName[dSTRING_ITEM_LEN+1];
char sKeyNameBuf[dSTRING_ITEM_LEN+1];
HCRYPTPROV hProvide = 0;
DWORD dwBufLen;
FILETIME oTime;
//char buff[200];
BYTE pbData[dNAME_ITEM_LEN+1];
DWORD cbData=dNAME_ITEM_LEN+1;


//
DWORD dwProvType;
lstrcpy(sKeyNameBuf,psData_CSP_Path);
lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,sKeyNameBuf,0, KEY_READ, &hKey);

while (lRet == ERROR_SUCCESS)
  {
  dwBufLen = dSTRING_ITEM_LEN;
  lRet = RegEnumKeyEx(hKey,dwIndex,sProvName,&dwBufLen,NULL,NULL,0,&oTime);
  if (lRet == ERROR_SUCCESS)
    {
    if (lstrcmp(sProvName,psData_Ignore_CSP_Name) != 0)
      {
	 cbData=dNAME_ITEM_LEN+1;  
      dwProvType = DigiCrypt_FindContext_GetCSPType(sProvName);
	  LOG("CSP %s",sProvName);
	  
	if (lstrcmp(sProvName,psData_Extra_CSP_Name) != 0)
          fRes = OpenProvider(&hProvide, sProvName, CRYPT_SILENT);
	  else
	  {
		  fRes = OpenProvider(&hProvide, sProvName, CRYPT_VERIFYCONTEXT);
		 //fRes = CryptAcquireContext(&hProvide,"SetCARDKeyContainer",sProvName,dwProvType, CRYPT_SILENT);
		 fRes = CryptAcquireContext(&hProvide,NULL,sProvName,dwProvType, CRYPT_VERIFYCONTEXT);
		 if(fRes)
		 {
			 //the extra csp might give wrong answer. We should ask from provider, why.
			 //The following is the work-around -- try to lookup key container from the card.
			 //if the result is negative this is a not the csp what is needed.
			      fRes=CryptGetProvParam(hProvide, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);	   
		 }
	  }

      if (fRes == TRUE)// && dwProvType == 2)
        {
        //set global values

        LOG("CSP %s accepted",sProvName);
        lstrcpy(oG_sCSPName,sProvName);
        CryptReleaseContext(hProvide, 0);
        psRes = oG_sCSPName;

        break;
        }
      }
    }
  //hProvide = 0;
  CryptReleaseContext(hProvide, 0);
  dwIndex++;
  }
if (hKey != NULL)
  RegCloseKey(hKey);



return(psRes);
}
Exemplo n.º 28
0
PCCERT_CONTEXT DigiCrypt_ReadCertFromCard(void)
{
HCRYPTPROV hCryptProv;
BYTE       *pbData = NULL;   
HCRYPTKEY  hKey;          
DWORD cbData = 0;
DWORD dwKeyType=0;
DWORD dwErrCode=0;
DWORD cspType=0;
DWORD cspFlag=CRYPT_SILENT;
char *psCspName = NULL;
char *psKeyContainer;
BOOL fRes = FALSE;
PCCERT_CONTEXT  pCertContext = NULL; 
CRYPT_KEY_PROV_INFO KeyProvInfo;
LPWSTR wszContainerName=NULL;
LPWSTR wszProvName=NULL;
DWORD cchContainerName;
DWORD cchCSPName;
HCRYPTPROV hProv;


DigiCrypt_ReleaseFirstAllowedCSP();

psCspName=DigiCrypt_GetFirstAllowedCSPNameNew();

//very dummy thing.. i check from csp creators why i should do so...
if(!lstrcmp(psCspName,"EstEID Card CSP"))
   fRes = CryptAcquireContext(&hProv,"XXX",psCspName,2, CRYPT_SILENT);
// end dummy//

if (psCspName == NULL || strstr(psCspName,psData_Est_CSP_Name) == NULL)
  return(pCertContext);

cspType=DigiCrypt_FindContext_GetCSPType(psCspName);

psKeyContainer=DigiCrypt_GetDefaultKeyContainerName(psCspName);

fRes = CryptAcquireContext(&hCryptProv,psKeyContainer,psCspName,cspType, CRYPT_SILENT);
if (fRes == FALSE)
  return(pCertContext);

fRes=CryptGetUserKey(hCryptProv, AT_SIGNATURE, &hKey);
if (fRes == TRUE)
  {
  fRes=CryptGetKeyParam(hKey, KP_CERTIFICATE, NULL, &cbData, 0);
  if (fRes == TRUE)
    {
    pbData = (unsigned char*)malloc(cbData);
    if (pbData == NULL)
      fRes = FALSE;
    }
  if (fRes == TRUE)
    fRes=CryptGetKeyParam(hKey, KP_CERTIFICATE, pbData, &cbData, 0);
  if (fRes == TRUE)
    {
    pCertContext = CertCreateCertificateContext(MY_ENCODING_TYPE,pbData,cbData);
    if (pCertContext != NULL)
      { 
	  wszContainerName=NULL;
	  wszProvName=NULL;
	  cchContainerName = (lstrlen(psKeyContainer) + 1)  * sizeof(WCHAR);
	  cchCSPName = (lstrlen(psCspName) + 1) * sizeof(WCHAR);
      wszContainerName = (LPWSTR) malloc(cchContainerName);
      wszProvName = (LPWSTR) malloc(cchCSPName);
      mbstowcs(wszContainerName, psKeyContainer,cchContainerName);
	  mbstowcs(wszProvName, psCspName, cchCSPName);
      ZeroMemory((PVOID)&KeyProvInfo, sizeof(CRYPT_KEY_PROV_INFO));
      KeyProvInfo.pwszContainerName = (LPWSTR) wszContainerName;
      KeyProvInfo.pwszProvName      = (LPWSTR) wszProvName;
      KeyProvInfo.dwProvType        = PROV_RSA_SIG;
      KeyProvInfo.dwFlags           = 0;
      KeyProvInfo.dwKeySpec         = dwKeyType;
      fRes = CertSetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID, 0, (const void *) &KeyProvInfo);
      if (wszContainerName != NULL)
        free(wszContainerName);
      if (wszProvName != NULL)
        free(wszProvName);

      }
    }
  }

//if (pCertContext != NULL)
//  DigiCrypt_AddCertToStore(pCertContext);
if (fRes == FALSE && pCertContext != NULL)
  {
  CertFreeCertificateContext(pCertContext);
  pCertContext = NULL;
  }
if (pbData != NULL)
  free(pbData);
if (hCryptProv != 0)
  CryptReleaseContext(hCryptProv, 0);
return(pCertContext);
}
/* 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.");
        }
    }
}
Exemplo n.º 30
0
int rand_bytes(uint8_t *output, int len)
{
#if defined(USE_CRYPTO_OPENSSL)
    return RAND_bytes(output, len);
#elif defined(USE_CRYPTO_POLARSSL)
    static entropy_context ec = {};
    static ctr_drbg_context cd_ctx = {};
    static unsigned char rand_initialised = 0;
    const size_t blen                     = min(len, CTR_DRBG_MAX_REQUEST);

    if (!rand_initialised) {
#ifdef _WIN32
        HCRYPTPROV hProvider;
        union {
            unsigned __int64 seed;
            BYTE buffer[8];
        } rand_buffer;

        hProvider = 0;
        if (CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, \
                                CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
            CryptGenRandom(hProvider, 8, rand_buffer.buffer);
            CryptReleaseContext(hProvider, 0);
        } else {
            rand_buffer.seed = (unsigned __int64)clock();
        }
#else
        FILE *urand;
        union {
            uint64_t seed;
            uint8_t buffer[8];
        } rand_buffer;

        urand = fopen("/dev/urandom", "r");
        if (urand) {
            int read = fread(&rand_buffer.seed, sizeof(rand_buffer.seed), 1,
                             urand);
            fclose(urand);
            if (read <= 0) {
                rand_buffer.seed = (uint64_t)clock();
            }
        } else {
            rand_buffer.seed = (uint64_t)clock();
        }
#endif
        entropy_init(&ec);
        if (ctr_drbg_init(&cd_ctx, entropy_func, &ec,
                          (const unsigned char *)rand_buffer.buffer, 8) != 0) {
#if POLARSSL_VERSION_NUMBER >= 0x01030000
            entropy_free(&ec);
#endif
            FATAL("Failed to initialize random generator");
        }
        rand_initialised = 1;
    }
    while (len > 0) {
        if (ctr_drbg_random(&cd_ctx, output, blen) != 0) {
            return 0;
        }
        output += blen;
        len    -= blen;
    }
    return 1;
#elif defined(USE_CRYPTO_MBEDTLS)
    static mbedtls_entropy_context ec = {};
    // XXX: ctr_drbg_context changed, [if defined(MBEDTLS_THREADING_C)    mbedtls_threading_mutex_t mutex;]
    static mbedtls_ctr_drbg_context cd_ctx = {};
    static unsigned char rand_initialised = 0;
    const size_t blen                     = min(len, MBEDTLS_CTR_DRBG_MAX_REQUEST);

    if (!rand_initialised) {
#ifdef _WIN32
        HCRYPTPROV hProvider;
        union {
            unsigned __int64 seed;
            BYTE buffer[8];
        } rand_buffer;

        hProvider = 0;
        if (CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, \
                                CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
            CryptGenRandom(hProvider, 8, rand_buffer.buffer);
            CryptReleaseContext(hProvider, 0);
        } else {
            rand_buffer.seed = (unsigned __int64)clock();
        }
#else
        FILE *urand;
        union {
            uint64_t seed;
            uint8_t buffer[8];
        } rand_buffer;

        urand = fopen("/dev/urandom", "r");
        if (urand) {
            int read = fread(&rand_buffer.seed, sizeof(rand_buffer.seed), 1,
                             urand);
            fclose(urand);
            if (read <= 0) {
                rand_buffer.seed = (uint64_t)clock();
            }
        } else {
            rand_buffer.seed = (uint64_t)clock();
        }
#endif
        mbedtls_entropy_init(&ec);
        // XXX: ctr_drbg_init changed, seems we should initialize it before calling mbedtls_ctr_drbg_seed()
        mbedtls_ctr_drbg_init(&cd_ctx);
        if (mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, &ec,
                                  (const unsigned char *)rand_buffer.buffer, 8) != 0) {
            mbedtls_entropy_free(&ec);
            FATAL("mbed TLS: Failed to initialize random generator");
        }
        rand_initialised = 1;
    }
    while (len > 0) {
        if (mbedtls_ctr_drbg_random(&cd_ctx, output, blen) != 0) {
            return 0;
        }
        output += blen;
        len    -= blen;
    }
    return 1;
#endif
}