CryptUIWizImport and protection password - winapi

I need to programmatically import certificate into Windows store.
The CryptUIWizImport function works well but Windows asks user create additional password to protect the certificate.
But user can choose to not set this password.
Is it possible to avoid Windows UI and set this additional password programmatically?

As the following code you should empty the password field:
#include "stdafx.h"
#include "windows.h"
#include "Cryptuiapi.h"
#pragma comment(lib, "Cryptui.lib")
int _tmain(int argc, _TCHAR* argv[]){
CRYPTUI_WIZ_IMPORT_SRC_INFO importSrc;
memset(&importSrc, 0, sizeof(CRYPTUI_WIZ_IMPORT_SRC_INFO));
importSrc.dwSize = sizeof(CRYPTUI_WIZ_IMPORT_SRC_INFO);
importSrc.dwSubjectChoice = CRYPTUI_WIZ_IMPORT_SUBJECT_FILE;
importSrc.pwszFileName = L"C:\\PathToPFX\\cert.pfx";
importSrc.pwszPassword = L"";
importSrc.dwFlags = CRYPT_EXPORTABLE | CRYPT_USER_PROTECTED;
if (CryptUIWizImport(
CRYPTUI_WIZ_NO_UI,
NULL,
NULL,
&importSrc,
NULL
) == 0)
{
printf(“CryptUIWizImport error 0x%x\n”, GetLastError());
}
return 0;
}

Related

How can I decrypt a string using CryptUnprotectData

I have been trying to decrypt some encrypted data (AES key encrypting chrome cookies) via the c++ CryptUnprotectData function for a short while now, but I cant seem to get it working. Currently the function will fail and return an error code of 13 (meaning "The parameter is incorrect."). Here is my code so far:
#include <iostream>
#include <Windows.h>
#include <wincrypt.h>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
std::string GetLastErrorAsString()
{
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
return std::string();
}
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
LocalFree(messageBuffer);
return message;
}
int main()
{
string data = "(data I want to decode)";
cout << data;
DATA_BLOB DataBytes;
DataBytes.pbData = (BYTE*)data.data();
DataBytes.cbData = (DWORD)data.size()+1;
DATA_BLOB output;
output.pbData = NULL;
output.cbData = (DWORD)data.size();
CryptUnprotectData(&DataBytes, NULL, NULL, NULL, NULL, 0, &output);
cout << GetLastErrorAsString() << endl;
cout << output.pbData;
LocalFree(output.pbData);
return 0;
}
If anyone can provide any help, that would be greatly appreciated.
I have tried different variations of the data types the parameters are stored in, although it still returns this error.
I modified your code, which is as follows. It only implements simple decryption.
And the data is not encrypted, so CryptUnprotectData() does not return the correct value.
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#pragma comment (lib, "Crypt32.lib")
int main()
{
// Decrypt data from DATA_BLOB DataOut to DATA_BLOB DataVerify.
//--------------------------------------------------------------------
// Declare and initialize variables.
string data = ("data I want to decode \n");
cout << data;
LPWSTR pDescrOut = NULL;
DATA_BLOB DataBytes;
BYTE* pbDataOutput = (BYTE*)data.data();
DWORD cbDataOutput = strlen((char*)pbDataOutput) + 1;
DataBytes.pbData = pbDataOutput;
DataBytes.cbData = cbDataOutput;
//DATA_BLOB DataVerify;
//--------------------------------------------------------------------
// The buffer DataOut would be created using the CryptProtectData
// function. If may have been read in from a file.
//--------------------------------------------------------------------
// Begin unprotect phase.
BOOL res = CryptUnprotectData(
&DataBytes,
&pDescrOut,
NULL, // Optional entropy
NULL, // Reserved
NULL, // Here, the optional
// prompt structure is not
// used.
0,
&DataBytes);
if (res==1)
{
printf("The decrypted data is: %s\n", DataBytes.pbData);
printf("The description of the data was: %s\n", pDescrOut);
}
else
{
printf("Decryption error!");
}
// LocalFree(DataVerify.pbData);
LocalFree(pDescrOut);
//LocalFree(DataBytes.pbData);
}
It is recommended to refer to Microsoft's official documentation when you add additional code.

NT Security API: SECURITY_DESCRIPTOR.Control, when can I see SE_OWNER_DEFAULTED?

From Windows NT security API, SE_OWNER_DEFAULTED is a flag bit from SECURITY_DESCRIPTOR_CONTROL.
MSDN states it quite briefly:
(SE_OWNER_DEFAULTED) Indicates that the SID of the owner of the security descriptor was provided by a default mechanism. This flag can be used by a resource manager to identify objects whose owner was set by a default mechanism.
I'm curious that when I can see this flag set.
I write NtfsOwner.cpp to display owner SID of an NTFS file/directory's security descriptor, and use GetSecurityDescriptorOwner to query that SE_OWNER_DEFAULTED flag, but have no chance seeing it even once.
Could somebody give me some clue. Could it be possible that SE_OWNER_DEFAULTED exhibits on other type of NT objects(not on a file/directory)?
#include <Windows.h>
#include <AclAPI.h>
#include <sddl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <locale.h>
template<typename T1, typename T2>
bool IsSameBool(T1 a, T2 b)
{
if(a && b)
return true;
else if(!a && !b)
return true;
else
return false;
}
void myDisplayNtfsOwner(const TCHAR *szfn)
{
DWORD succ = 0;
HANDLE hFile = CreateFile(szfn,
READ_CONTROL, // dwDesiredAccess=GENERIC_READ etc
FILE_SHARE_READ|FILE_SHARE_WRITE, // shareMode
NULL, // SecuAttr, no need bcz we are opening existing file
OPEN_EXISTING, // dwCreationDisposition
FILE_FLAG_BACKUP_SEMANTICS, // this is required for open a directory
NULL);
if(hFile==INVALID_HANDLE_VALUE)
{
_tprintf(_T("Warning: CreateFile() failed!(WinErr=%d) But I will go on calling GetSecurityInfo(0xFFFFffff, ...)\n"),
GetLastError());
}
SECURITY_DESCRIPTOR *pSD = nullptr;
DWORD winerr = GetSecurityInfo(hFile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL,
(PSECURITY_DESCRIPTOR*)&pSD);
assert(winerr==0);
SID* psidOwner = nullptr;
BOOL isOwnerDefaulted = 0;
succ = GetSecurityDescriptorOwner(pSD, (PSID*)&psidOwner, &isOwnerDefaulted);
assert(succ);
PTSTR strOwner = nullptr;
succ = ConvertSidToStringSid(psidOwner, &strOwner);
assert(succ);
_tprintf(_T("Owner SID is: %s\n"), strOwner);
_tprintf(_T("Is owner SID defaulted? %s\n"), isOwnerDefaulted?_T("yes"):_T("no"));
assert(IsSameBool(pSD->Control & SE_OWNER_DEFAULTED, isOwnerDefaulted));
LocalFree(strOwner);
LocalFree(pSD);
CloseHandle(hFile);
}
int _tmain(int argc, TCHAR* argv[])
{
setlocale(LC_ALL, "");
if(argc==1)
{
const TCHAR *s = _T("D:\\test\\foo.txt");
_tprintf(_T("Missing parameters.\n"));
_tprintf(_T("Example:\n"));
_tprintf(_T(" NtfsOwner1 %s\n"), s);
exit(1);
}
const TCHAR *szfn = argv[1];
myDisplayNtfsOwner(szfn);
return 0;
}

Windows - Unable to find WMI WiFi_AdapterAssociationInfo class

I am trying to execute the example at https://theroadtodelphi.wordpress.com/2011/10/15/all-about-wifi-networks-and-wifi-adapters-using-the-wmi-and-delphi/ in visual C++, wherein:
the WMI class WiFi_AdapterAssociationInfo is queried
retrieve WiFi asset information
On windows 2012 and Windows 8.1 am getting the error that unable to locate the WMI class, the code I am executing is placed below, I am getting erro code 0x80041010, please help here:
// wmiQuery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <atlbase.h> // For ATL autorelease classes (CComBSTR, CComPtr)
#include <wbemidl.h> // For WMI
#pragma comment(lib, "wbemuuid.lib") // Link to WMI library. (Can do in library includes instead)
std::string GetOsVersionString()
{
HRESULT hr = ::CoInitializeSecurity(NULL, -1, NULL, NULL,
RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE,
NULL, EOAC_NONE, NULL);
CComPtr<IWbemLocator> pWbemLocator;
hr = pWbemLocator.CoCreateInstance(CLSID_WbemLocator);
CComPtr<IWbemServices> pWbemServices;
hr = pWbemLocator->ConnectServer(CComBSTR(L"root\\cimv2"), NULL, NULL, 0, NULL, 0, NULL, &pWbemServices);
CComPtr<IEnumWbemClassObject> pEnum;
CComBSTR cbsQuery = L"Select Version from WiFi_AdapterAssociationInfo";
hr = pWbemServices->ExecQuery(CComBSTR("WQL"), cbsQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);
ULONG uObjectCount = 0;
CComPtr<IWbemClassObject> pWmiObject;
hr = pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount);
CComVariant cvtVersion;
hr = pWmiObject->Get(L"SSID", 0, &cvtVersion, 0, 0);
std::string sOsVersion = CW2A(cvtVersion.bstrVal);
return sOsVersion;
}
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
std::string sOsVersion = GetOsVersionString();
::CoUninitialize();
return 0;
}

How to get the name of a console in Windows?

Is possible to get the name of a console in Windows? Just like is done by the C function ttyname in Unix systems
You can use the WinAPI GetConsoleTitle function to retrieve it.
You might find links to all of the console functions useful.
You didn't specify a language, so here's the one in C++ from MSDN
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <strsafe.h>
int main( void )
{
TCHAR szOldTitle[MAX_PATH];
TCHAR szNewTitle[MAX_PATH];
// Save current console title.
if( GetConsoleTitle(szOldTitle, MAX_PATH) )
{
// Build new console title string.
StringCchPrintf(szNewTitle, MAX_PATH, TEXT("TEST: %s"), szOldTitle);
// Set console title to new title
if( !SetConsoleTitle(szNewTitle) )
{
_tprintf(TEXT("SetConsoleTitle failed (%d)\n"), GetLastError());
return 1;
}
else
{
_tprintf(TEXT("SetConsoleTitle succeeded.\n"));
}
}
return 0;
}

vc++ ipconfig cmd equivalent on Windows

How can I achieve the functionality given in ipconfig on Windows in VC++? I need to get local ip info of the machine, primary ip vs.
Well people, formerly I could not find something useful but I found the solution on this link.
// GetLocalIP.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
int _tmain(int argc, _TCHAR* argv[])
{
// Add 'ws2_32.lib' to your linker options
WSADATA WSAData;
// Initialize winsock dll
if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
{
// Error handling
}
// Get local host name
char szHostName[128] = "";
if(::gethostname(szHostName, sizeof(szHostName)))
{
// Error handling -> call 'WSAGetLastError()'
}
// Get local IP addresses
struct sockaddr_in SocketAddress;
struct hostent *pHost = 0;
pHost = ::gethostbyname(szHostName);
if(!pHost)
{
// Error handling -> call 'WSAGetLastError()'
}
char aszIPAddresses[10][16]; // maximum of ten IP addresses
for(int iCnt = 0; ((pHost->h_addr_list[iCnt]) && (iCnt < 10)); ++iCnt)
{
memcpy(&SocketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length);
strcpy(aszIPAddresses[iCnt], inet_ntoa(SocketAddress.sin_addr));
//std::cout << aszIPAddresses[iCnt] << endln;
}
// Cleanup
WSACleanup();
return 0;
}

Resources