I need to set up an active directory authentication system using Kerberos. My AcquireCredentialsHandleA class looks as follows. https://learn.microsoft.com/en-us/windows/win32/secauthn/acquirecredentialshandle--kerberos
SEC_WINNT_AUTH_IDENTITY AuthData, *pAuthData = NULL;
#ifdef UNICODE
AuthData.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
#else
AuthData.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
#endif
unsigned char username[200] = "user";
unsigned char domain[200] = "domain.com";
unsigned char password[100] = "secret";
AuthData.User = &username[0]; //username
AuthData.Domain = &domain[0]; //domain
AuthData.Password = &password[0]; //password
AuthData.UserLength = AuthData.User ? sizeof(AuthData.User) : 0;
AuthData.DomainLength = AuthData.Domain ? sizeof(AuthData.Domain) : 0;
AuthData.PasswordLength = AuthData.Password ? sizeof(AuthData.Password) : 0;
Status = g_pSSPI->AcquireCredentialsHandleA(
NULL, // Name of principal //pN
ppPackageInfo[2].Name,//"kerberos" Name of package
SECPKG_CRED_OUTBOUND, // Flags indicating use
NULL, // Pointer to logon ID
pAuthData, //NULL, // Package specific data
NULL, // Pointer to GetKey() func
NULL, // Value to pass to GetKey()
phCreds, // (out) Cred Handle
&tsExpiry
);
This returns Success. However, when I call my InitializeSecurityContextAfunction it gives me 0x80090311 error which means SEC_E_NO_AUTHENTICATING_AUTHORITY. I have tried all sorts of possible domain name etc. When I do ksetup in the powershell it can generate ticket with same credentials. But the code always fails. Can anyone spot any problem here?
dwSSPIFlags = ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_USE_SESSION_KEY | ISC_REQ_CONNECTION; // Not sure at all about them flags
OutBuffers[0].pvBuffer = NULL;
OutBuffers[0].BufferType = SECBUFFER_TOKEN; //2
//OutBuffers[0].cbBuffer = 0;
OutBuffers[0].cbBuffer = 7084;
OutBuffer.cBuffers = 1;
OutBuffer.pBuffers = OutBuffers;
OutBuffer.ulVersion = SECBUFFER_VERSION; //0
Status = g_pSSPI->InitializeSecurityContextA
(
phCreds,
fHaveCtxtHandle ? phContext : NULL,//phContext, can be NULL for the first call
server,
dwSSPIFlags,
0,
SECURITY_NETWORK_DREP,//SECURITY_NATIVE_DREP,
fHaveCtxtHandle ? &InBuffer : NULL,
0,
fHaveCtxtHandle ? NULL : phContext ,
&OutBuffer,
&dwSSPIOutFlags,
&tsExpiry
);
Can anyone help me with this? Thanks a lot. :)
--------------------------------------------------------------- edit ---------------------------------------------------------------
std::string fqdn = "HTTP/staging.company.com";
char * server = new char[fqdn.size() + 1];
std::copy(fqdn.begin(), fqdn.end(), server);
server[fqdn.size()] = '\0';
So this is how I set up the Service name. I have this service name registered in my active directory as well. Though the address does not offer any particular service yet. Do you think that could be the problem?
Another details: The Active directory is not in the same office, we tunnel to it via router.
Related
I am trying to the WinVerifyTrust function to verify the signature of a msi.
And while this works for files on the file system I cannot get it to work with a memory blob.
This basis of my example to show the problem is the example program from microsoft
BOOL VerifyEmbeddedSignature(LPCWSTR pwszSourceFile)
{
std::basic_ifstream<BYTE> file(pwszSourceFile, std::ios::binary);
std::vector<BYTE> data((std::istreambuf_iterator<BYTE>(file)),std::istreambuf_iterator<BYTE>());
LONG lStatus;
/*
// this works
WINTRUST_FILE_INFO FileData;
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
FileData.pcwszFilePath = pwszSourceFile;
FileData.hFile = NULL;
FileData.pgKnownSubject = NULL;
*/
WINTRUST_BLOB_INFO FileData{};
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_BLOB_INFO);
FileData.gSubject = WIN_TRUST_SUBJTYPE_RAW_FILE;
FileData.cbMemObject = static_cast<DWORD>(data.size());
FileData.pbMemObject = data.data();
GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
WINTRUST_DATA WinTrustData;
memset(&WinTrustData, 0, sizeof(WinTrustData));
WinTrustData.cbStruct = sizeof(WinTrustData);
WinTrustData.pPolicyCallbackData = NULL;
WinTrustData.pSIPClientData = NULL;
WinTrustData.dwUIChoice = WTD_UI_NONE;
WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
//WinTrustData.dwUnionChoice = WTD_CHOICE_FILE; -- works
WinTrustData.dwUnionChoice = WTD_CHOICE_BLOB;
WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
WinTrustData.hWVTStateData = NULL;
WinTrustData.pwszURLReference = NULL;
WinTrustData.dwUIContext = 0;
WinTrustData.pBlob = &FileData;
//WinTrustData.pFile = &FileData; -- works
lStatus = WinVerifyTrust(
NULL,
&WVTPolicyGUID,
&WinTrustData);
WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(
NULL,
&WVTPolicyGUID,
&WinTrustData);
return lStatus == ERROR_SUCCESS;
}
In the above example using the WINTRUST_FILE_INFO works but the WINTRUST_BLOB_INFO does not.
The error that I get with a memory blob is always TRUST_E_PROVIDER_UNKNOWN.
I assume that the problem might be the WIN_TRUST_SUBJTYPE_RAW_FILE subject type but I don't know which one I should use for a msi file.
I am wondering if the sign check is possible at all with memory blobs of msi files.
The WIN_TRUST_SUBJTYPE_RAW_FILE is not the suitable subject GUID. You could The function CryptSIPRetrieveSubjectGuid retrieves a GUID based on the header information in a specified file.
I need to mark a custom self-signed root certificate as trusted during certificate chain validation and, overall, I want to rely on the system API as much as possible.
I create a temporary memory store.
HCERTSTORE certStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, 0);
Then I place the custom root certificate into the store.
CertAddCertificateContextToStore(certStore, rootCertContext, CERT_STORE_ADD_REPLACE_EXISTING, 0);
The CertGetCertificateChain MSDN documentation says
hAdditionalStore A handle to any additional store to search for supporting certificates and certificate trust lists (CTLs).
As far as I understand if I create a CTL with the root certificate and place it to the store, CertGetCertificateChain will trust it. So, I create the root certificate CTL entry in an allocated buffer and then copy it to std::vector ctlEntries
CertCreateCTLEntryFromCertificateContextProperties(rootCertContext, 0, nullptr, CTL_ENTRY_FROM_PROP_CHAIN_FLAG, nullptr, ctlEntry, &size);
Then I create the CTL itself.
const std::wstring ctlID(L"TrustedRoots");
// I do not know what OIDs to use here. I tried different options.
std::vector<LPSTR> usageList;
usageList.push_back(szOID_SORTED_CTL);
usageList.push_back(szOID_PKIX_KP_CLIENT_AUTH);
usageList.push_back(szOID_PKIX_KP_SERVER_AUTH);
CTL_INFO ctlInfo;
ZeroMemory(&ctlInfo, sizeof(ctlInfo));
ctlInfo.dwVersion = CTL_V1;
ctlInfo.SubjectUsage.cUsageIdentifier = static_cast<DWORD>(usageList.size());
ctlInfo.SubjectUsage.rgpszUsageIdentifier = usageList.data();
ctlInfo.ListIdentifier.cbData = static_cast<DWORD>((ctlID.size() + 1) * sizeof(wchar_t));
ctlInfo.ListIdentifier.pbData = static_cast<BYTE*>(static_cast<void*>(const_cast<wchar_t*>(ctlID.data())));
ctlInfo.SubjectAlgorithm.pszObjId = szOID_OIWSEC_sha1;
ctlInfo.cCTLEntry = static_cast<DWORD>(ctlEntries.size());
ctlInfo.rgCTLEntry = const_cast<PCTL_ENTRY>(ctlEntries.data());
// From MSDN:
// The message can be encoded without signers if the cbSize member of the structure is set to the
// size of the structure and all of the other members are set to zero.
CMSG_SIGNED_ENCODE_INFO encode;
ZeroMemory(&encode, sizeof(encode));
encode.cbSize = sizeof(encode);
DWORD size = 0, flags = CMSG_ENCODE_SORTED_CTL_FLAG | CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG;
if (CryptMsgEncodeAndSignCTL(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, &ctlInfo, &encode, flags, nullptr, &size) == TRUE)
{
std::string data;
data.resize(size);
BYTE* p = static_cast<BYTE*>(static_cast<void*>(&data.front()));
if (CryptMsgEncodeAndSignCTL(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, &ctlInfo, &encode, flags, p, &size) == TRUE)
{
PCCTL_CONTEXT ctlContext = CertCreateCTLContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, p, size);
if (ctlContext)
{
if (CertAddCTLContextToStore(certStore, ctlContext, CERT_STORE_ADD_REPLACE_EXISTING, nullptr) == TRUE)
{
// success
}
}
}
}
All API calls above finish successfully but when I call CertGetCertificateChain, it still returns CERT_TRUST_IS_UNTRUSTED_ROOT in TrustStatus.dwErrorStatus.
Potential Workaround
If I get the CERT_TRUST_IS_UNTRUSTED_ROOT error, I just extract the CTL from the certificate store and check if the root from the result chain (returned by CertGetCertificateChain) is in the CTL. It works but is still not fully acceptable for me. I would like to rely on CertGetCertificateChain.
What is wrong with the solution?
What specific Certificate Trust List OIDs must I use?
Is any requirement (like specific extensions) for the root certificate to be trusted in this case?
p.s. The test certificates are created using this instruction https://gist.github.com/fntlnz/cf14feb5a46b2eda428e000157447309
UPD: 2020-01-31
CertModifyCertificatesToTrust did not help. It finishes successfully but the chain is still reported as having an untrusted root. Probably, the issue is in different area.
PCCERT_CONTEXT copiedCert = nullptr;
BOOL result = CertAddCertificateContextToStore(certStore,
cert, CERT_STORE_ADD_REPLACE_EXISTING, &copiedCert);
CertFreeCertificateContext(cert);
if (result)
{
// Save the certificate to create a CTL entry later
trustedRoots.push_back(copiedCert);
}
...
// Creating the CTL entries
...
std::vector<LPSTR> usageList;
usageList.push_back(szOID_CTL); // I really do not know what IDs I must use here
...
CTL_INFO ctlInfo;
ZeroMemory(&ctlInfo, sizeof(ctlInfo));
ctlInfo.dwVersion = CTL_V1;
ctlInfo.SubjectUsage.cUsageIdentifier = static_cast<DWORD>(usageList.size());
ctlInfo.SubjectUsage.rgpszUsageIdentifier = usageList.data();
...
// Should I use any of the flags?
DWORD size = 0, flags = 0; /*CMSG_ENCODE_SORTED_CTL_FLAG | CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG;*/
if (CryptMsgEncodeAndSignCTL(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, &ctlInfo, &encode, flags, nullptr, &size) == TRUE)
...
if (CertAddCTLContextToStore(certStore, ctlContext, CERT_STORE_ADD_REPLACE_EXISTING, nullptr) == TRUE)
{
// Check that the CTL is in the store and the root certificate is in the CTL
CTL_FIND_USAGE_PARA usagePara;
ZeroMemory(&usagePara, sizeof(usagePara));
usagePara.cbSize = sizeof(usagePara);
usagePara.SubjectUsage.cUsageIdentifier = 0;
usagePara.ListIdentifier.cbData = static_cast<DWORD>((ctlID.size() + 1) * sizeof(wchar_t));
usagePara.ListIdentifier.pbData = static_cast<BYTE*>(static_cast<void*>(const_cast<wchar_t*>(ctlID.data())));
PCCTL_CONTEXT foundCTLContext = CertFindCTLInStore(certStore,
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CTL_FIND_USAGE,
static_cast<void*>(&usagePara), nullptr);
if (foundCTLContext != nullptr)
{
PCTL_ENTRY ctlEntry = CertFindSubjectInCTL(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
CTL_CERT_SUBJECT_TYPE, const_cast<void*>(*trustedRoots.begin()), foundCTLContext, 0);
if (ctlEntry != nullptr)
{
// It means the root certificate has been correctly added to the CTL and the CTL is in the store.
std::cout << "Found the certificate in the CTL" << std::endl;
}
}
// Make the certificate trusted via CertModifyCertificatesToTrust
HMODULE module = LoadLibrary(L"CryptDlg.dll");
if (module)
{
CertModifyCertificatesToTrustPfn pfn =
(CertModifyCertificatesToTrustPfn)GetProcAddress(hModule, "CertModifyCertificatesToTrust");
if (pfn != nullptr)
{
CTL_MODIFY_REQUEST req;
// Only one certificate is in the trustedRoots store curretly
req.pccert = static_cast<PCCERT_CONTEXT>(*trustedRoots.begin());
req.dwOperation = CTL_MODIFY_REQUEST_ADD_TRUSTED;
req.dwError = 0;
HRESULT hr = pfn(1, &req, szOID_CTL, NULL, certStore, nullptr);
if (hr == S_OK)
{
// Success
std::cout << "Modified" << std::endl;
}
}
}
}
You can try to use the following api: CertModifyCertificatesToTrust
And note that
This function has no associated import library. You must use the
LoadLibrary and GetProcAddress functions to dynamically link to
CryptDlg.dll.
Set the CTL_MODIFY_REQUEST.dwOperation to the flagCTL_MODIFY_REQUEST_ADD_TRUSTED to add the certificate to the CTL. The certificate is explicitly trusted.
How to add Subject Alternative Name in the certificate. Using wincrypt I have created and added the certificate to "MY" and "root" path where CN can be machine fully qualified domain name or hostname or IP. As Subject alternate name I want to add the following:DNS name=fully qualified domain name, DNS name=hostname and
DNS name=IP
How to do this?
I do not want to use openssl.
LPCTSTR cnName= fqdn;
DWORD cbEncoded = 0;
if (!CertStrToName(X509_ASN_ENCODING, cnName, CERT_X500_NAME_STR, NULL,
pbdata, &cbData, NULL))
{
_tprintf(_T("CertStrToName failed 0x%x\n"), GetLastError());
return 0;
}
if (!(pbdata = (BYTE *)malloc(cbData)))
{
_tprintf(_T("malloc Error 0x%x\n"), GetLastError());
return 0;
}
if (!CertStrToName(X509_ASN_ENCODING, cnName, CERT_X500_NAME_STR, NULL, pbdata, &cbData, NULL))
{
_tprintf(_T("CertStrToName failed 0x%x\n"), GetLastError());
return 0;
}
CERT_NAME_BLOB IssuerBlob;
IssuerBlob.cbData = cbEncoded;
IssuerBlob.pbData = pbEncoded;
CertCreateSelfSignCertificate(NULL, &IssuerBlob, 0, &KeyProvInfo, &Alg, 0, &EndTime, 0);
OpenandAddCertificateToStore(pCertContext, L"MY");
OpenandAddCertificateToStore(pCertContext, L"Root");
This creates and adds certificate to the store without SAN in the certificate
I tried passing extension list like below:
CertCreateSelfSignCertificate(NULL, &IssuerBlob, 0, &KeyProvInfo, &Alg, 0, &EndTime, &myExtns_list);
CERT_EXTENSION myExtn;
myExtn.fCritical = TRUE;
myExtn.pszObjId = szOID_SUBJECT_ALT_NAME;
myExtn.Value = myBlobdata;
CERT_EXTENSIONS myExtns_list;
myExtns_list.cExtension = 1;
myExtns_list.rgExtension = &myExtn;
char cb[20] = { "DNS Names=abc.com" };
BYTE *pbData = (BYTE*)cb;
CERT_NAME_BLOB myBlobdata;
myBlobdata.cbData = 20;
myBlobdata.pbData = pbData;
with this I could get the SAN as byte format in the left pane and the right pane shows my string "DNS Names=abc.com".
But my requirement is to show only the DNS Names in the SAN.
I'm assuming that your building of the extension data actually happened prior to your call to CertCreateSelfSignedCertificate (and, likewise, that your building of myBlobdata happened before using it).
The main problem is that you used one SAN entry (sort of) as the entirety of the SAN extension; which meant you lost some encoding wrappers. A secondary problem is that you used szOID_SUBJECT_ALT_NAME, which is the incorrect OID for Subject Alternative Name... you actually want szOID_SUBJECT_ALT_NAME2.
I want to add the following:DNS name=fully qualified domain name, DNS name=hostname and DNS name=IP
Adding an IP address as a DNS name is non-standard and is supposed to result in a match failure. You'd actually want to add the IP address as an IP Address SAN entry.
CERT_ALT_NAME_ENTRY entries[3];
entries[0] = { CERT_ALT_NAME_DNS_NAME };
entries[0].pwszDNSName = L"example.org";
// IPv4 Address 10.12.1.130
BYTE ip4Bytes[] = { 10, 12, 1, 130 };
entries[1] = { CERT_ALT_NAME_IP_ADDRESS };
entries[1].IPAddress = { sizeof(ip4Bytes), ip4Bytes };
// ::1, big-endian
BYTE ip6Bytes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
entries[2] = { CERT_ALT_NAME_IP_ADDRESS };
entries[2].IPAddress = { sizeof(ip6Bytes), ip6Bytes };
CERT_NAME_BLOB name = { cbEncoded, buf };
BYTE extBuf[1024] = { 0 };
cbEncoded = sizeof(extBuf);
CERT_ALT_NAME_INFO info = { sizeof(entries) / sizeof(CERT_ALT_NAME_ENTRY), entries };
if (!CryptEncodeObjectEx(
X509_ASN_ENCODING,
X509_ALTERNATE_NAME,
&info,
0,
nullptr,
extBuf,
&cbEncoded))
{
// Whatever your error handling story is.
//
// Note I didn't do a 0 buffer or CRYPT_ENCODE_ALLOC; I just knew
// that my buffer would be big enough.
}
CERT_EXTENSION extension = { 0 };
extension.fCritical = 0;
extension.pszObjId = szOID_SUBJECT_ALT_NAME2;
extension.Value = { cbEncoded, extBuf };
CERT_EXTENSIONS extensions = { 1, &extension };
...
PCCERT_CONTEXT cert = CertCreateSelfSignCertificate(
0,
&name,
0,
&keyProvInfo,
&sigAlg,
0,
&certExpirationDate,
&extensions);
In CertUI that gives me the Subject Alternative Name value I expect:
DNS Name=example.org
IP Address=10.12.1.130
IP Address=0000:0000:0000:0000:0000:0000:0000:0001
I am using the following function and query to retrieve the network adapter's MAC address :
QueryValue( pService, L"SELECT MACAddress FROM Win32_NetworkAdapter", L"MACAddress", NetMacAddress, bufferLength );
But i don't know how to specify which card i want to get the address of. Is there a way to get the MAC address of every card on the computer (assuming they are activated and all that) using WMI ? Or using something else ?
Thank you :)
Without WMI you can simply use something like this...
unsigned long ulLen = 0;
IP_ADAPTER_ADDRESSES* p_adapAddress = NULL;
DWORD dwRetValue = GetAdaptersAddresses(AF_INET, 0, NULL, p_adapAddress,&ulLen);
if(dwRetValue == ERROR_BUFFER_OVERFLOW)
{
p_adapAddress = (PIP_ADAPTER_ADDRESSES)malloc(ulLen);
if(p_adapAddress)
{
dwRetValue = GetAdaptersAddresses(AF_INET, 0, NULL, p_adapAddress,&ulLen);
if(dwRetValue == NO_ERROR)
{
IP_ADAPTER_ADDRESSES* p_adapAddressAux = p_adapAddress;
do
{
// Get the value of the p_adapAddressAux.PhysicalAddress
}
while(p_adapAddressAux != NULL);
}
free(p_adapAddress);
}
}
URL_COMPONENTS urlComp;
LPCWSTR pwszUrl1 =
L"http://search.msn.com/results.asp?RS=CHECKED&FORM=MSNH&v=1&q=wininet";
DWORD dwUrlLen = 0;
// Initialize the URL_COMPONENTS structure.
ZeroMemory(&urlComp, sizeof(urlComp));
urlComp.dwStructSize = sizeof(urlComp);
// Set required component lengths to non-zero
// so that they are cracked.
urlComp.dwSchemeLength = (DWORD)-1;
urlComp.dwHostNameLength = (DWORD)-1;
urlComp.dwUrlPathLength = (DWORD)-1;
urlComp.dwExtraInfoLength = (DWORD)-1;
// Crack the URL.
if (!WinHttpCrackUrl( pwszUrl1, (DWORD)wcslen(pwszUrl1), 0, &urlComp))
{
printf("Error %u in WinHttpCrackUrl.\n", GetLastError());
}
This WinHttpCrackUrl api failed with 87(invalid param) on Win7( OS ) please any one suggest a solution or how can i decode my URL in an Easy way in server side ?.Also i want to know how can i distinguish %20 from encoded URL and actual data present in the URL. Example: localhost:8080\Server\search?value="value%20"
Sets required component lengths to expected value.
All to zero if doesn't need to crack.
urlComp.dwSchemeLength = (DWORD)0;
urlComp.dwHostNameLength = (DWORD)0;
urlComp.dwUrlPathLength = (DWORD)0;
urlComp.dwExtraInfoLength = (DWORD)0;
Or
std::wstring urlHost;
urlHost.resize(url.size());
urlComp.dwHostNameLength = (DWORD)urlHost.size();
urlComp.lpszHostName = &urlHost[0];