How to Sign an EXE with Additional Certificates using CryptoAPI and SignerSign - c++

I'm trying to build a tool that will mass sign a bunch of files based on Kernel-Mode Code Signing requirements. I know that signtool can take an additional certificate for cross-signatures trust via the /ac argument, but have not been able to figure out how to do the same using SignerSign or SignerSignEx. I've even spied on signtool's API calls, and mirroring them does not seems to produce the same affect.
Be aware, signtool or other command-line utilities cannot be used for this purpose due to project constraints.
Is there any documentation or examples on how to accomplish this?

Okay, after working on this for awhile, I've finally figured our how to do signing with a cross certificate. First, you will need four, or five depending on your version of signtool, certificates that are embedded in the signtool EXE's resources under the CERTIFICATE resource type, they all start with MS. Now I made my version pull all certificates from files so the following example pseudo code will explain how to do this. It's not purely the CryptoAPI calls, but does explain the basic process used by signtool. All certificate usage validation has also been left out for simplicity.
// inputs: string pfx_file_path, string cross_cert_file_path, string password, string file_to_sign
Certificate_Store signer_collection = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, NULL, CERT_STORE_CREATE_NEW_FLAG, NULL);
Certificate_Store signer_store = CertOpenStore(CERT_STORE_PROV_MEMORY, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL,
CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | CERT_STORE_READONLY_FLAG, NULL);
File pfx_file = File::open(pifx_file_path, GENERIC_READ, OPEN_EXISTING);
File_Mapping<BYTE> pfx_mapping = File_Mapping<BYTE>::map(pfx_file);
CRYPT_DATA_BLOB pfx_blob = { pfx_mapping.size(), pfx_mapping.data() };
Certificate_Store signer_pfx = PFXImportCertStore(&pfx_blob, password, CRYPT_USER_KEYSET);
// CertEnumCertificatesInStore
for (Certificate certificate: signer_pfx) {
signer_store.add(certificate); // CertAddCertificateContextToStore
}
signer_collection.add(signer_store); // CertAddStoreToCollection
Certificate signer;
for (Certificate certificate: signer_collection) {
// Assumes first certificate is the signer, need better validation.
signer = CertDuplicateCertificateContext(certificate);
break;
}
if (signer != NULL) {
throw NoSginerException();
}
Certificate_Store additional_collection;
if (cross_cert_file_path != NULL) {
Certificate_Store cross_collection;
Certificate_Store cross_store;
Certificate cross_certificate = Certificate::load(cross_cert_file_path);
// CryptQueryObject(CERT_QUERY_OBJECT_FILE, cross_cert_file_path,
// CERT_QUERY_CONTENT_FLAG_CERT, CERT_QUERY_FORMAT_FLAG_ALL,
// 0, NULL, NULL, NULL, NULL, NULL, &cross_certificate);
cross_collection = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, NULL, CERT_STORE_CREATE_NEW_FLAG, NULL);
cross_collection.add(signer_collection);
cross_store = CertOpenStore(CERT_STORE_PROV_MEMORY, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL,
CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | CERT_STORE_READONLY_FLAG, NULL);
cross_store.add(cross_certificate);
cross_collection.add(cross_store);
Certificate_Store ms_root_store = CertOpenStore(sz_CERT_STORE_PROV_MEMORY, 0, NULL,
CERT_STORE_CREATE_NEW_FLAG | CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL);
// This is where the embedded certificates from the MS Code Validation roots are collectioned.
for (Resource resource: Program_Resources::resources_under("CERTIFICATE")) { // EnumResourceNames, Find/Load/Lock|Resource
Certificate certificate = Certificate::from_blob(resource.size(), resource.data());
// CERT_BLOB blob = { resource.size(), resources.data() };
// CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &blob,
// CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT,
// CERT_QUERY_FORMAT_FLAG_ALL, 0, NULL, NULL, NULL, NULL, NULL,
// &certificate);
ms_root_store.add(certificate);
}
cross_collection.add(certificate);
static const DWORD CHAIN_FLAGS = CERT_CHAIN_DISABLE_PASS1_QUALITY_FILTERING |
CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS |
CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
static const CERT_CHAIN_PARA CHAIN_PARAMS = { sizeof(CERT_CHAIN_PARA) };
Certificate_Chain chain = Certificate_Chain::get(HCCE_LOCAL_MACHINE, signer, NULL,
cross_collection, &CHAIN_PARAMS, CHAIN_FLAGS, NULL);
// CertGetCertificateChain(HCCE_LOCAL_MACHINE, signer, NULL,
// cross_collection, &CHAIN_PARAMS, CHAIN_FLAGS, NULL, &chain);
Certificate_Store additional_store = CertOpenStore(CERT_STORE_PROV_MEMORY,
PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG |
CERT_STORE_READONLY_FLAG, NULL);
for (DWORD l = 0; l != chain->cLowerQualityChainContext; ++l) {
PCCERT_CHAIN_CONTEXT low_chain = pChain->rgpLowerQualityChainContext[l];
for (DWORD c = 0; c != low_chain->cChain; ++c) {
PCERT_SIMPLE_CHAIN simple_chain = low_chain->rgpChain[c];
for (DWORD e = 0; e != simple_chain->cElement; ++e) {
PCERT_CHAIN_ELEMENT element = simple_chain->rgpElement[e];
additional_store.add(element->pCertContext);
}
}
}
additional_collection = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, NULL, CERT_STORE_CREATE_NEW_FLAG, NULL);
additional_collection.add(additional_store);
}
SIGNER_FILE_INFO file_info = { sizeof(SIGNER_FILE_INFO) };
file_info.pwszFileName = file_to_sign;
DWORD index = 0;
SIGNER_SUBJECT_INFO subject_info = { sizeof(SIGNER_SUBJECT_INFO) };
subject_info.pdwIndex = &index;
subject_info.dwSubjectChoice = SIGNER_SUBJECT_FILE;
subject_info.pSignerFileInfo = &file_info;
SIGNER_CERT_STORE_INFO store_info = { sizeof(SIGNER_CERT_STORE_INFO) };
store_info.dwCertPolicy = SIGNER_CERT_POLICY_STORE;
store_info.pSigningCert = signer;
store_info.hCertStore = additional_collection;
SIGNER_CERT cert_info = { sizeof(SIGNER_CERT) };
cert_info.dwCertChoice = SIGNER_CERT_STORE;
cert_info.pCertStoreInfo = &store_info;
SIGNER_ATTR_AUTHCODE authcode_attr = { sizeof(SIGNER_ATTR_AUTHCODE) };
SIGNER_SIGNATURE_INFO signature_info = { sizeof(SIGNER_SIGNATURE_INFO) };
signature_info.algidHash = CALG_SHA;
signature_info.dwAttrChoice = SIGNER_AUTHCODE_ATTR;
signature_info.pAttrAuthcode = &authcode_attr;
SIGNER_PROVIDER_INFO provider_info = { sizeof(SIGNER_PROVIDER_INFO) };
provider_info.pwszProviderName = L"";
provider_info.dwPvkChoice = PVK_TYPE_KEYCONTAINER;
provider_info.pwszKeyContainer = L"";
HRESULT hr = SignerSign(&subject_info, &cert_info, &signature_info, &provider_info, NULL, NULL, NULL);

Related

Reading DSA private key protected with 3DES

Here is how I manage to create the key pair and store in files successfully. The problem comes when reading the private key protected with password where I always get NULL. Any tip to solve this issue? Thanks.
FILE *dsa_privatekey_file;
FILE *dsa_publickey_file;
const char *pkeykey = "password";
int result = 0;
DeleteFile("dsapub.pem");
DeleteFile("dsapriv.pem");
dsa_publickey_file = fopen("dsapub.pem", "r");
dsa_privatekey_file = fopen("dsapriv.pem", "r");
if (dsa_privatekey_file == NULL || dsa_publickey_file == NULL)
{
if (dsa_privatekey_file != NULL)
{
fclose(dsa_privatekey_file);
}
if (dsa_publickey_file != NULL)
{
fclose(dsa_publickey_file);
}
dsa_publickey_file = fopen("dsapub.pem", "w");
dsa_privatekey_file = fopen("dsapriv.pem", "w");
DSA* dsa = DSA_new();
result = DSA_generate_parameters_ex(dsa, 2048, NULL, 0, NULL, NULL, NULL);
result = DSA_generate_key(dsa);
result = PEM_write_DSAPrivateKey(dsa_privatekey_file, dsa, EVP_des_ede3_cbc(), NULL, 0, NULL, (void *)pkeykey);
//result = PEM_write_DSAPrivateKey(dsa_privatekey_file, dsa, EVP_des_ede3_cbc(), (unsigned char *) pkeykey, strlen(pkeykey), NULL, NULL);
//result = PEM_write_DSAPrivateKey(dsa_privatekey_file, dsa, NULL, NULL, 0, NULL, NULL);
result = PEM_write_DSA_PUBKEY(dsa_publickey_file, dsa);
fclose(dsa_privatekey_file);
fclose(dsa_publickey_file);
DSA_free(dsa);
dsa_publickey_file = fopen("dsapub.pem", "r");
dsa_privatekey_file = fopen("dsapriv.pem", "r");
}
DSA *dsa_sign = PEM_read_DSAPrivateKey(dsa_privatekey_file, NULL, default_set_password, (void *)pkeykey);
DSA *dsa_verify = PEM_read_DSA_PUBKEY(dsa_publickey_file, NULL, NULL, NULL);
Here's the simple function I use to hard insert the password, but anyway it seems not to be called.
static int default_set_password(char *buf, int size, int rwflag, void *descr){ memcpy(buf, descr, size); return size; }
A call to
OpenSSL_add_all_algorithms();
was needed to work as expected.

SCHANNEL TLS Server side cannot CertFindCertificateInStore

I am adding TLS encryption to a server side application. I am using the Schannel API to add the TLS. I am having a problem with CertFindCertificateInStore. It does not ever find the certificate that I am searching for. As criteria for the search I am using the name of the certificate. I have spent many hours on this now and do not understand why it is not working. Any help would be immensely appreciated. The function I am using this in is found below. Thanks,
int ServerCreateCredentials() {
//- get the certificate store
HCERTSTORE myCertStore = NULL;
myCertStore = CertOpenStore(
CERT_STORE_PROV_SYSTEM,
X509_ASN_ENCODING,
NULL,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
L"My");
// check for the failure to find the appropriate store
if (myCertStore == NULL) {
return 1;
}
// find the certificate in the store
m_CertificateContext = CertFindCertificateInStore(
myCertStore,
X509_ASN_ENCODING,
0,
CERT_FIND_SUBJECT_STR_A,
(LPVOID) CertificateName,
NULL);
if (m_CertificateContext == NULL) {
// try unicode
m_CertificateContext = CertFindCertificateInStore(
myCertStore,
X509_ASN_ENCODING,
0,
CERT_FIND_SUBJECT_STR_W,
CertificateName,
NULL);
if (m_CertificateContext == NULL ) {
// free the store
CertCloseStore(myCertStore, CERT_CLOSE_STORE_CHECK_FLAG);
return 2;
}
}
TimeStamp life;
// get the credentials
SCHANNEL_CRED SchannelCredentials;
ZeroMemory(&SchannelCredentials, sizeof(SchannelCredentials));
SchannelCredentials.dwVersion = SCHANNEL_CRED_VERSION;
SchannelCredentials.cCreds = 1; // number of credentials
SchannelCredentials.paCred = &m_CertificateContext; // credentials
SchannelCredentials.hRootStore = myCertStore; // certificate store location
SchannelCredentials.dwMinimumCipherStrength = 80; // minimum encryption allowed
SchannelCredentials.grbitEnabledProtocols = 0; // let the dll decide
SchannelCredentials.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION
| SCH_CRED_NO_SERVERNAME_CHECK
| SCH_CRED_REVOCATION_CHECK_CHAIN;
DWORD Status = SEC_E_OK;
Status = m_securityFunctionTable.AcquireCredentialsHandle(
NULL,
UNISP_NAME,
SECPKG_CRED_INBOUND,
NULL,
&SchannelCredentials,
NULL,
NULL,
&m_credentials,
&life);
// at this point we should be good
// free the store
CertCloseStore(myCertStore, CERT_CLOSE_STORE_CHECK_FLAG);
if (Status != SEC_E_OK) {
return 3;
}
return 0;
I have figured out that I was not searching on the correct parameters. You need to search based on the subject name and then it will work.

Adding Response from TSA to CRYPT_SIGN_MESSAGE_PARA for CryptSignMessage (c++, Crypto Api)

I'm struggling how must I add the response from a TSA server to my CryptSignMessage?
Using PKCS#7. I currently have my message digest and I successfully sign it with CryptSignMessage from crypto api. Like so:
// Initialize the signature structure.
CRYPT_SIGN_MESSAGE_PARA SigParams;
SigParams.cbSize = sizeof(CRYPT_SIGN_MESSAGE_PARA);
SigParams.dwMsgEncodingType = MY_ENCODING_TYPE;
SigParams.pSigningCert = hContext;
SigParams.HashAlgorithm.pszObjId = szOID_RSA_SHA1RSA;
SigParams.HashAlgorithm.Parameters.cbData = NULL;
SigParams.cMsgCert = 1;
SigParams.rgpMsgCert = &hContext;
SigParams.dwInnerContentType = 0;
SigParams.cMsgCrl = 0;
SigParams.cUnauthAttr = 0;
SigParams.dwFlags = 0;
SigParams.pvHashAuxInfo = NULL;
SigParams.cAuthAttr = 0;
SigParams.rgAuthAttr = NULL;
// First, get the size of the signed BLOB.
if(CryptSignMessage(
&SigParams,
FALSE,
1,
MessageArray,
MessageSizeArray,
NULL,
&cbSignedMessageBlob))
{
printf("%d bytes needed for the encoded BLOB.", cbSignedMessageBlob);
}
else
{
MyHandleError();
fReturn = false;
exit_SignMessage();
}
// Allocate memory for the signed BLOB.
if(!(pbSignedMessageBlob =
(BYTE*)malloc(cbSignedMessageBlob)))
{
MyHandleError();
exit_SignMessage();
}
// Get the signed message BLOB.
if(CryptSignMessage(
&SigParams,
TRUE,
1,
MessageArray,
MessageSizeArray,
pbSignedMessageBlob,
&cbSignedMessageBlob))
{
printf("The message was signed successfully. \n");
// pbSignedMessageBlob now contains the signed BLOB.
fReturn = true;
}
else
{
MyHandleError();
fReturn = false;
exit_SignMessage();
}
Now I want to use a TSA server to timestamp my digest, but I'm not really sure how to include this. Say I have a rfc3161 TimeStamp request; I send this to my TSA and I receive a rfc3161 TimeStamp response (probably using libcurl). How should incorporate the response into my SigParams? Must I extract the TimeStampToken and then store that as an unauthenticated counter signature? Something like:
CRYPT_ATTR_BLOB cablob[1];
CRYPT_ATTRIBUTE ca[1];
cablob[0].cbData = tstResponseSize;
cablob[0].pbData = tstResponse; // the response from TSA
ca[0].pszObjId = "1.2.840.113549.9.6"; // object identifier for counter signature
ca[0].cValue = 1;
ca[0].rgValue = cablob;
And then set the SigParams:
SigParams.cUnauthAtt = 1;
SigParams.rgUnauthAttr = ca;
Any advice would be greatly appreciated.
Thanks,
Magda
I struggled with this for a couple of days. There are not that many examples out there, so here is my solution. Hope it helps :)
HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, CMSG_DETACHED_FLAG, 0, NULL, NULL, NULL);
if (NULL == hMsg)
{
throw std::exception("Failed to open messsage to decode");
}
if (!::CryptMsgUpdate(hMsg, signedData.pbData, signedData.cbData, TRUE))
{
throw std::exception("Failed to add signature block to message");
}
//get the digest from the signature
PCRYPT_TIMESTAMP_CONTEXT pTsContext = NULL;
DWORD encDigestSize = 0;
if (::CryptMsgGetParam(hMsg, CMSG_ENCRYPTED_DIGEST, 0, NULL, &encDigestSize))
{
std::unique_ptr<BYTE> pEncDigest(new BYTE[encDigestSize]);
if (::CryptMsgGetParam(hMsg, CMSG_ENCRYPTED_DIGEST, 0, pEncDigest.get(), &encDigestSize))
{
//get timestamp
if (::CryptRetrieveTimeStamp(L"http://sha256timestamp.ws.symantec.com/sha256/timestamp",
TIMESTAMP_NO_AUTH_RETRIEVAL,
0, //timeout?????
szOID_NIST_sha256,
NULL,
pEncDigest.get(),
encDigestSize,
&pTsContext,
NULL,
NULL))
{
CRYPT_ATTR_BLOB cryptBlob = {};
cryptBlob.cbData = pTsContext->cbEncoded;
cryptBlob.pbData = pTsContext->pbEncoded;
CRYPT_ATTRIBUTE cryptAttribute = {};
cryptAttribute.pszObjId = "1.2.840.113549.1.9.16.2.14"; //id-smime-aa-timeStampToken
cryptAttribute.cValue = 1;
cryptAttribute.rgValue = &cryptBlob;
DWORD encodedAttributeSize = 0;
std::unique_ptr<BYTE> encodedAttribute;
if (::CryptEncodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_ATTRIBUTE, &cryptAttribute, NULL, &encodedAttributeSize))
{
encodedAttribute.reset(new BYTE[encodedAttributeSize]);
if (::CryptEncodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_ATTRIBUTE, &cryptAttribute, encodedAttribute.get(), &encodedAttributeSize))
{
CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR_PARA unauthenticatedParam = { 0 };
unauthenticatedParam.cbSize = sizeof(unauthenticatedParam);
unauthenticatedParam.dwSignerIndex = 0; //only have 1 cert
unauthenticatedParam.blob.cbData = encodedAttributeSize;
unauthenticatedParam.blob.pbData = encodedAttribute.get();
if (::CryptMsgControl(hMsg, 0, CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR, &unauthenticatedParam))
{
DWORD encodedMessageLength = 0;
if (::CryptMsgGetParam(hMsg, CMSG_ENCODED_MESSAGE, 0, NULL, &encodedMessageLength))
{
std::unique_ptr<BYTE> pData(new BYTE[encodedMessageLength]);
if (::CryptMsgGetParam(hMsg, CMSG_ENCODED_MESSAGE, 0, pData.get(), &encodedMessageLength))
{
//save pData/encodedMessageLength here to file
}
}
}
}
}
}
}
}
if (NULL != pTsContext)
{
::CryptMemFree(pTsContext);
}
if (NULL != hMsg)
{
::CryptMsgClose(hMsg);
}

ACE ordering within a DACL using AddAccessAllowedAceEx

I needed to grant access to a file on Windows in a c++ program. I browsed around and copy/pasted code from MSDN and came up with the following. It has been working as far as I can tell.
But then today I stumbled across a warning in MSDN for the use of AddAccessAllowedAceEx, which says: "The caller must ensure that ACEs are added to the DACL in the correct order.". It then refers the reader to this: http://msdn.microsoft.com/en-us/library/windows/desktop/aa379298(v=vs.85).aspx
So, my request is for any seasoned Windows programmer to review my code below and tell me if I am going to have problems vis-a-vis ACE ordering within the DACL of the file I am modifying (which is passed in via szPath in my function). I will say that I simply added my new ACE to the end of the DACL. If this will be a problem, must I really read out all the ACE's from the DACL, inspect them and then add them back one at a time being sure to insert my new ACE in the correct position to respect the correct ordering?
char* whoOps::ACLAmigo::AddACEToDACL(char* szPath, char* szSecurityPrincipal, DWORD dwPermission)
{
ACL_SIZE_INFORMATION ACLInfo;
memset(&ACLInfo, 0, sizeof(ACL_SIZE_INFORMATION));
UCHAR BuffSid[256];
PSID pSID = (PSID)BuffSid;
int returnCode = ResolveSID(szSecurityPrincipal, pSID);
SE_OBJECT_TYPE SEObjType = SE_FILE_OBJECT;
PACL pOldDACL = NULL;
PSECURITY_DESCRIPTOR pSD = NULL;
SECURITY_INFORMATION ACLSecInfo = DACL_SECURITY_INFORMATION;
returnCode = GetNamedSecurityInfoA(szPath, SEObjType, ACLSecInfo, NULL, NULL, &pOldDACL, NULL, &pSD);
char* szReturn = NULL;
if (returnCode != ERROR_SUCCESS) {
szReturn = "GetNamedSecurityInfoA() failed.";
} else {
BOOL getACLResult = GetAclInformation(pOldDACL, &ACLInfo, sizeof(ACLInfo), AclSizeInformation);
if (!getACLResult) {
szReturn = "GetAclInformation() failed.";
} else {
DWORD cb = 0;
DWORD cbExtra = sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) + GetLengthSid(pSID);
cb = ACLInfo.AclBytesInUse + cbExtra;
PACL pNewDACL = static_cast<PACL>(HeapAlloc(GetProcessHeap(),0,cb));
BOOL initACLResult = InitializeAcl(pNewDACL, cb, ACL_REVISION);
if (!initACLResult) {
szReturn = "InitializeAcl() failed.";
} else {
for (DWORD i = 0; i < ACLInfo.AceCount; ++i) {
ACE_HEADER * pACE = 0;
GetAce(pOldDACL, i, reinterpret_cast<void**>(&pACE));
pACE->AceFlags = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
pACE->AceType = ACCESS_ALLOWED_ACE_TYPE;
AddAce(pNewDACL, ACL_REVISION, MAXDWORD, pACE, pACE->AceSize);
}
BOOL addACEResult = AddAccessAllowedAceEx(pNewDACL, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, dwPermission, pSID);
if (!addACEResult) {
szReturn = "AddAccessAllowedAceEx() failed.";
} else {
DWORD setSIResult = SetNamedSecurityInfoA(szPath, SEObjType, ACLSecInfo, NULL, NULL, pNewDACL, NULL);
if (!setSIResult) {
szReturn = "SetNamedSecurityInfoA() failed.";
} else {
szReturn = "AddACEToDACL() succesful.";
}
}
}
if (pNewDACL) HeapFree(GetProcessHeap(),0, pNewDACL);
}
if (pSD) LocalFree(pSD);
}
return szReturn;
}
ACE ordering is really important! Yes, best solution would be
read the content of the ACL before modifying
programmatically inspect each element (ACE) in the Security Descriptor
place your entry appropriatelly (denied before allow)
This serie has a good amount of samples.

Creating VHD files with the VirtualDisk API

I'm trying to use a VSS snapshot as the source for CreateVirtualDisk(). Environment/tools are C++ VS2008SP1 and 7.1 SDK on W7x64Ultimate
[Edited]
This works on Windows 7 x64
BOOL CreateVHD_Fixed(PCWSTR pszVhdPath, ULONG sizeInMB)
{
BOOL bRet = FALSE;
HANDLE hvhd;
CREATE_VIRTUAL_DISK_PARAMETERS params;
VIRTUAL_DISK_ACCESS_MASK mask;
VIRTUAL_STORAGE_TYPE vst =
{
VIRTUAL_STORAGE_TYPE_DEVICE_VHD,
VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT
};
wprintf(L"CreateVHD_Fixed %s, size (MB) %d\n", pszVhdPath, sizeInMB);
params.Version1.UniqueId = GUID_NULL;
params.Version1.BlockSizeInBytes = 0;
params.Version1.MaximumSize = sizeInMB * 1024 * 1024;
params.Version1.ParentPath = NULL;
params.Version1.SourcePath = NULL;
params.Version1.SectorSizeInBytes = 512;
params.Version = CREATE_VIRTUAL_DISK_VERSION_1;
mask = VIRTUAL_DISK_ACCESS_CREATE;
DWORD ret = CreateVirtualDisk(&vst,
pszVhdPath,
mask,
NULL,
// To create a dynamic disk, use CREATE_VIRTUAL_DISK_FLAG_NONE instead.
CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION,
0,
&params,
NULL,
&hvhd);
if (ret == ERROR_SUCCESS)
{
bRet = TRUE;
}
else
{
bRet = FALSE;
printf("failed to create vdisk...err 0x%x\n", ret);
PrintErrorMessage(GetLastError());
}
if (INVALID_HANDLE_VALUE != hvhd)
{
CloseHandle(hvhd);
}
return bRet;
}
[Edited] - now failing in a different way with ERROR_INVALID_PARAMETER. Parameters are below with a root path of "\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy64"
VIRTUAL_STORAGE_TYPE storageType =
{
VIRTUAL_STORAGE_TYPE_DEVICE_VHD,
// do not use any other GUID else you get an unknown provider error
VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT // **critical!**
};
VIRTUAL_DISK_ACCESS_MASK vdam = (VIRTUAL_DISK_ACCESS_MASK)(VIRTUAL_DISK_ACCESS_CREATE); // |VIRTUAL_DISK_ACCESS_WRITABLE|VIRTUAL_DISK_ACCESS_READ|VIRTUAL_DISK_ACCESS_GET_INFO);
CREATE_VIRTUAL_DISK_FLAG flags = CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION; // CREATE_VIRTUAL_DISK_FLAG_NONE;
CREATE_VIRTUAL_DISK_PARAMETERS parameters;
//
parameters.Version = CREATE_VIRTUAL_DISK_VERSION_1;
parameters.Version1.UniqueId = GUID_NULL;
parameters.Version1.MaximumSize = 0;
parameters.Version1.BlockSizeInBytes = CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_BLOCK_SIZE;
parameters.Version1.ParentPath = 0;
parameters.Version1.SourcePath = root.c_str();
parameters.Version1.SectorSizeInBytes = CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_SECTOR_SIZE;
ULONG ProviderSpecificFlags = 0;
HANDLE handle = 0;
dwRet = CreateVirtualDisk(&storageType,
_T("t:\\test.vhd"),
vdam,
NULL,
flags,
ProviderSpecificFlags,
&parameters,0,&handle);
Any ideas? The virtual disk API does not seem to have much example code.
Thx++
Jerry.
Jerry,
Use CreateVirtualDisk API to create a VHD or a differential VHD, make sure u send the right parameters. You have to specify the parent hard disk but not the source hard disk. Care must also be taken while using the flags.
Refer the links below:
"http://code.msdn.microsoft.com/windowshardware/CppVhdAPI-4412d182"
and
"http://code.msdn.microsoft.com/windowsdesktop/Virtual-hard-disk-03108ed3"