Forward credentials from app to credential provider - c++

I've started to investigate how credential providers work, but due to poor documentation I got stuck in couple of places.
I have console application(sort of like ssh server) when I connect remotly to this application and authenticate(none is logged on), I want it to be able to forward those credentials to credential provider and I want CP to login user(create session).
I've also noticed that In documentation it says that SetSerialization method always gets called after SetusageScenario. But I've added logs and SetSerialization never gets called after SetusageScenario.
As I know SetSerialization is called when credential is provided by application. I can't understand what does it mean to provide credential through application? It seems like this is what I need, to forward credentials from application to credential provider, but How can I do that? Are there some functions that I could call from credential provider dll to provoke login?
Is there any way I can achieve this? I've read that when remote login is done, UpdateRemoteCredential is called, But As I understand(correct me if I'm wrong) in remote login it means RDP but my application is simple, it just listens to some port and gets username and password and then uses Logonuser function.
A program named MxLogon2 implements this scheme. A remote server with MxLogon2 installed can authenticate a USB key(But I want username/password) connected to the client side in a remote desktop session.
Any suggestion that would direct me to right way would be greatly appriciated.
P.S
I'm using pGina as my credential provider.

I wouldn't mind too much of SetSerialization in your case. This is used for pre-initializing tile.
One example would be, with RDP connection, you can store certificates of credentials on your system. This function is used to pre-inquire tiles with those credentials (not the only solution though).
Make it return E_NOTIMPL in your case.
The main purpose of the provider is to initialize Credentials and tiles :
Credentials initialization
is done through SetUsageScenario function (automatically called after Provider construction).
In there, you can customize the behavior depending on scenario you are in. Most basic one being CPUS_LOGON.
It shall look like this (this is only a preview)
HRESULT Provider::SetUsageScenario(
__in CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus,
__in DWORD dwFlags
)
{
HRESULT hr;
switch(cpus)
{
case CPUS_UNLOCK_WORKSTATION:
case CPUS_LOGON:
hr = this->_InitCredential();
break;
default:
hr = E_INVALIDARG;
break;
}
return hr;
}
Tiles initialization
begins in GetCredentialCount function. It allows you to define how many tiles you gonna show (pdwCount out parameter), as well as the one to be used as the default tile (pdwDefault).
Auto-Logon is also handle in here (through pbAutoLogonWithDefault).
Tiles Enumeration is then beginning in GetCredentialAt function.
Passing credentials for authentication is done in the credential you're using through the GetSerialization function.
Examples of implementation can be found here.
I hardly insist on example as it easily divert depending on what you are trying to achieve. This is very flexible and you'd better understand the purpose of any function / parameter to fit your goals.
EDIT - cf comments :
#define IDCredential 0x1
Credential::Credential(Provider* parent)
{
//Do ssh connection or whatever
if(success)
{
parent->login = retrievedLogin;
parent->pwd = retrievedPwd;
parent->CredentialUsed = IDCredential;
parent->autoLogin = true;
parent->ProviderEvents->CredentialsChanged(AdviseContext);
}
}
HRESULT Provider::GetCredentialCount(
__out DWORD* pdwCount,
__out_range(<,*pdwCount) DWORD* pdwDefault,
__out BOOL* pbAutoLogonWithDefault
)
{
if(this->autoLogin && this->CredentialUsed)
{
*pbAutoLogonWithDefault = true; // --> Instant call to GetSerialization
*pdwDefault = this->CredentialUsed; //index of the tile
}
else
{
*pbAutoLogonWithDefault = false;
*pdwDefault = IDCredential;
}
return S_OK;
}

Related

Remote Desktop Connection with Custom Credential Provider

I have developed a custom credential provider using the SampleWrapExistingCredentialProvider from VistaCredentialProviderSamples. The credential provider has a filter implemented that filters all other credential providers and I see just my credential provider at the time of logon. The issue is that if we connect to it using remote desktop connection, the username/password are not passed from windows RDP client to the Credential provider and I have to enter it again when RDP session opens (unlike the behavior with default provider)
I am trying to explore which part of the code handles this scenario that the credential provider accepts the username/password from remote desktop client and does not ask again. Attached is the screenshot of my credential provider after providing successful credentials on the RDP client. After I click this icon of my credential provider, I am shown the credential provider tile that asking again for the username and password. Any help would be highly appreciated on how to receive credentials from RDP client.
I have returned S_OK for CREDUI. My SetUsageScenario is as follows:
HRESULT CSampleProvider::SetUsageScenario(
CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus,
DWORD dwFlags
)
{
HRESULT hr;
// Create the password credential provider and query its interface for an
// ICredentialProvider we can use. Once it's up and running, ask it about the
// usage scenario being provided.
IUnknown *pUnknown = NULL;
hr = ::CoCreateInstance(CLSID_PasswordCredentialProvider, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pUnknown));
if (SUCCEEDED(hr))
{
hr = pUnknown->QueryInterface(IID_PPV_ARGS(&(_pWrappedProvider)));
if (SUCCEEDED(hr))
{
hr = _pWrappedProvider->SetUsageScenario(cpus, dwFlags);
switch (cpus)
{
case CPUS_LOGON:
case CPUS_UNLOCK_WORKSTATION:
case CPUS_CREDUI:
{
hr = S_OK;
break;
}
case CPUS_CHANGE_PASSWORD:
default:
hr = E_INVALIDARG;
break;
}
}
}
if (FAILED(hr))
{
if (_pWrappedProvider != NULL)
{
_pWrappedProvider->Release();
_pWrappedProvider = NULL;
}
}
return hr;
}
the username/password are not passed from windows RDP client to the
Credential provider and I have to enter it again when RDP session
opens (unlike the behavior with default provider)
windows can not by some magic know client username/password, which connecting by rdp.
at begin on client side some credential provider must create CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION and pass it to server. inside it clsidCredentialProvider say which concrete provider collect this serialization.
what server must do with this CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION ? obvious pass it to some credential provider SetSerialization method. but for which ? for all ? no. again obvivous only for provider which clsid exactly matches clsidCredentialProvider from CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION. this provider (if exist and not filtered) must remember this credentional and then when called GetCredentialCount - say that it have dafault credentional (not CREDENTIAL_PROVIDER_NO_DEFAULT) and it usually ready for auto logon attempt with this.
from client side (mstsc) the password provider create serialization. so will be __uuidof(PasswordCredentialProvider) or __uuidof(V1PasswordCredentialProvider) (if client run on win7) in clsidCredentialProvider.
but you disable this providers in self filter. as result you yourself break process.
filter must implement UpdateRemoteCredential method. and here copy and update passed pcpcsIn. most importand part of this - we must replace clsidCredentialProvider to self CLSID. as result our SetSerialization method will be called. here we need restore original CLSID before pass it to wrapped credentional.
also important place - inside GetCredentialCount - first pass it to wrapped credentional and then do *pbAutoLogonWithDefault = FALSE; - disable autologon - you can not do this (autologon) if you require additional (OTP ?) information from client.
inside UpdateRemoteCredential method we can not modify pcpcsIn - if declared as const. so we need write our update credentional to pcpcsOut. because system can not know which size is required for rgbSerialization - we need allocate it yourself. and system then free it. obvivous need use CoTaskMemAlloc for allocate rgbSerialization.
so - all this can be understanded and without any documentation. however if all this was documented - will be not bad too.
so code for UpdateRemoteCredential :
HRESULT STDMETHODCALLTYPE CSampleProvider::UpdateRemoteCredential(
/* [annotation][in] */
_In_ const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *pcpcsIn,
/* [annotation][out] */
_Out_ CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *pcpcsOut)
{
if (pcpcsIn->clsidCredentialProvider != __uuidof(PasswordCredentialProvider) &&
pcpcsIn->clsidCredentialProvider != __uuidof(V1PasswordCredentialProvider))
{
// we dont know format of serialization
return E_UNEXPECTED;
}
ULONG cbSerialization = pcpcsIn->cbSerialization;
if (pcpcsOut->rgbSerialization = (PBYTE)CoTaskMemAlloc(cbSerialization + sizeof(GUID)))
{
memcpy(pcpcsOut->rgbSerialization, pcpcsIn->rgbSerialization, cbSerialization);
memcpy(pcpcsOut->rgbSerialization + cbSerialization, &pcpcsIn->clsidCredentialProvider, sizeof(GUID));
pcpcsOut->cbSerialization = cbSerialization + sizeof(GUID);
pcpcsOut->ulAuthenticationPackage = pcpcsIn->ulAuthenticationPackage;
pcpcsOut->clsidCredentialProvider = __uuidof(CSampleProvider);
return S_OK;
}
return E_OUTOFMEMORY;
}
if we dont know the clsidCredentialProvider - simply return E_UNEXPECTED
oterwise allocate more (on sizeof(CLSID)) memory and save original clsidCredentialProvider in the end
now SetSerialization:
HRESULT STDMETHODCALLTYPE CSampleProvider::SetSerialization(
__in const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs
)
{
if (pcpcs->clsidCredentialProvider == __uuidof(CSampleProvider))
{
// can not query WTSIsRemoteSession, small optimization
_IsRemoteSession = true;
// we got this via ICredentialProviderFilter::UpdateRemoteCredential
ULONG cbSerialization = pcpcs->cbSerialization;
if (cbSerialization >= sizeof(GUID))
{
// restore original clsidCredentialProvider
cbSerialization -= sizeof(GUID);
memcpy(const_cast<GUID*>(&pcpcs->clsidCredentialProvider), pcpcs->rgbSerialization + cbSerialization, sizeof(GUID));
const_cast<CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION*>(pcpcs)->cbSerialization = cbSerialization;
}
}
return _pWrappedProvider->SetSerialization(pcpcs);
}
restore original clsidCredentialProvider and fix cbSerialization. also because pcpcs->clsidCredentialProvider == __uuidof(CSampleProvider) can be set only inside UpdateRemoteCredential in my case (i not do CPUS_CREDUI on client side for RDP, only for "run as admin") - i just know that this is remote connection and save this information (_IsRemoteSession = true;) for not call WTSIsRemoteSession
finally GetCredentialCount:
HRESULT STDMETHODCALLTYPE CSampleProvider::GetCredentialCount(
__out DWORD* pdwCount,
__out_range(<,*pdwCount) DWORD* pdwDefault,
__out BOOL* pbAutoLogonWithDefault
)
{
HRESULT hr = _pWrappedProvider->GetCredentialCount(pdwCount, pdwDefault, pbAutoLogonWithDefault);
*pbAutoLogonWithDefault = FALSE;//!!!
return hr;
}
note very important *pbAutoLogonWithDefault = FALSE;//!!! line
According to official documentationhttps: RDC and Custom Credential Providers
If the user connected with a non-Microsoft credential provider, then
you will be prompted on the terminal server to enter credentials again
(twice). If NLA is not enabled, then despite entering using an
unsupported credential provider on the client prior to the connection,
the user will still be connected. You will be left at the logon
screen, where you can use any credential provider that is supported
for local authentication. There’s no way to avoid the two
authentications when using unsupported credential providers.
Having said that, if you have your own credential providers and you
try to do a remote desktop connection to a Vista box (having this
Credential provider) then you would need to log-in twice. This is an
expected behavior and it is by design and there is no legitimate way
to avoid it.

windows credential provider remote logon

I am trying to read a credential from a smart card on one workstation (local), then send it to a different workstation(remote) and use it to logon to that workstation from within a credential provider.
I've been searching and, and researching for weeks now but have not found anyone showing or telling how to do this.
I have found several references to an excellent work at https://www.idrix.fr/Root/Samples/LsaSmartCardLogon2.cpp, which is working code for a smart card credential provider, but unfortunately requires that the credential provider have direct access to the smart card with the credential on it.
The actual code I am working with seems a little to long to include in the post so I thought I try asking the question using sudo code.
On the local workstation:
MySendCredentialsFromSmartCard(){
CryptAcquireContext(hProv, containerName, cardName, PROV_RSA_FULL, CRYPT_SILENT)
CryptGetUserKey(*hProv, AT_KEYEXCHANGE, &hCryptKey);
CryptGetKeyParam(hCryptKey, KP_CERTIFICATE, encodedCert, &size, 0);
MySendCertToRemote(encodedCert,size);
}
On Remote workstation running in custom credential provider:
HRESULT CSampleCredential::GetSerialization(
_Out_ CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE *pcpgsr,
_Out_ CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *pcpcs,
_Outptr_result_maybenull_ PWSTR *ppwszOptionalStatusText,
_Out_ CREDENTIAL_PROVIDER_STATUS_ICON *pcpsiOptionalStatusIcon){
MyReadCertFromRemote(&cert,&size);
CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0);
CryptCreateHash(hCryptProv, CALG_SHA1, NULL, 0, &hHash);
CryptHashData(hHash, (BYTE *)cert, (DWORD)size, 0);
CERT_CREDENTIAL_INFO certInfo;
CryptGetHashParam(hHash, HP_HASHVAL, certInfo.rgbHashOfCert, &dwHashLen, 0);
CredMarshalCredential(CertCredential, &certInfo, marshalledCred);
/****************************for debug only*****************************/
LogonUser((*marshalledCred, NULL, NULL, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, &userHandle);
//this reuturns 1 (success)
/**************************************************************************/
KERB_INTERACTIVE_UNLOCK_LOGON kiul;
CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus
KerbInteractiveUnlockLogonInit(L"", (PWSTR)marshaledCred, L"", cpus, &kiul);//(note:I've tried this with the third param set to the card's pin)
KerbInteractiveUnlockLogonPack(kiul, &pcpcs->rgbSerialization, &pcpcs->cbSerialization);
RetrieveNegotiateAuthPackage(&ulAuthPackage);
pcpcs->ulAuthenticationPackage = ulAuthPackage;
pcpcs->clsidCredentialProvider = CLSID_OfProvider;
*pcpgsr = CPGSR_RETURN_CREDENTIAL_FINISHED;
}
LogonUI.exe displays "A specified logon session does not exist. It may already have been terminated." This seams to correspond to Windows error code 1312. It seems that most developers struggling with this error code are having trouble configuring IIS with an SSL cert. I have found no reference to this error in relation to a credential provider.
Various threads seem to indicate that LogonUser is mearly a wrapper around LSALogonUser and the returned values from ICredentialProviderCredential::GetSerialization will be passed to LSALogonUser. The fact that my call to LogonUser with the marshalled credential succeeds would seem to suggest that on I'm on the right track, but I haven't been able to verify that nor figure out what I'm missing.
I would like to try to avoid solutions that require storing the credential on the remote workstation as it is typically a domain admin credential.
Any ideas anybody? Any advise on how to proceed?
Thanks
I guess you can do it using a communication mechanism where you send your data from one workstation to another one and in the remote one you serialize your data in SetSerialization() instead of GetSerialization(), preparing all the fields and processing the logon.
From my understanding point of you, the Provider class (the one inherited by ICredentialProvider) has to wait for those credentials somehow and pass them to SetSerialization

Custom Windows Authentication Package Logon Failed

I have developed custom authentication package that I would like to use for interactive logon. It creates the access token in the LsaApUserLogon function.
When I call LsaUserLogon from an application I can enumerate new user sessions, but when I used it for logon (also I have created a custom credential provider) I can see in Windows Event log that I was successfully logged in and then logged out.
When I select my specific Credential and try to logon, it enters into LsaApLogonUser API of my Authentication Package. If I check log file, LsaApLogonUser return STATUS_SUCCESS. But Windows is not logged on. After leaving LsaAPLogonUser, LSA calls LsaApLogonTerminated API and back LogonUI.
When I prepared the TokenInformation I got LookupPrivilegeValueW failed for the SeInteractiveLogonRight. I don't know if this is important for logon.
LsaApLogonUser(...){
......
// NetUserGetInfo
// AllocateLocallyUniqueId (LogonId)
err = GetTokenInformationv2(pdi?pdi->DomainControllerName:NULL,wszDomain,wszUser,&LocalTokenInformation,LogonId);
err = g_pSec->CreateLogonSession(LogonId);
if(ProfileBuffer)
{
*ProfileBuffer=NULL;
*ProfileBufferLength=0;
}
(*TokenInformationType)=LsaTokenInformationV2;
(*TokenInformation)=LocalTokenInformation;
return STATUS_SUCCESS;
}
GetTokenInformationv2(...){
....
....
// Call LsaEnumerateAccountRights
// check LookupPrivilegeValueW // It failed for "SeInteractiveLogonRight"
//
return STATUS_SUCCESS;
}
Is ProfileBuffer important for logon? I don't know why LSA cannot logon.
The documentation does not say that the profile buffer can be set to NULL and it seems that it is indeed mandatory. The OP reports that allocating and returning a profile buffer (just a single byte was enough) resolved the problem.
The error when attempting to retrieve a LUID for SeInteractiveLogonRight was not relevant; the user's logon rights do not need to be included in the TOKEN_PRIVILEGES structure, so no LUID is needed, and as documented, the LookupPrivilegeValue function only accepts privileges:
The LookupPrivilegeValue function supports only the privileges specified in the Defined Privileges section of Winnt.h.
(Note that the relevant section of winnt.h only contains definitions for SeXxxPrivilege; the definitions for SeXxxLogonRight are in ntsecapi.h.)

Trying to understand SECURITY_LOGON_TYPE enumeration

I'm struggling to understand all of the SECURITY_LOGON_TYPE values:
typedef enum _SECURITY_LOGON_TYPE {
Interactive = 2,
Network,
Batch,
Service,
Proxy,
Unlock,
NetworkCleartext,
NewCredentials,
RemoteInteractive,
CachedInteractive,
CachedRemoteInteractive,
CachedUnlock
} SECURITY_LOGON_TYPE, *PSECURITY_LOGON_TYPE;
I'm trying to understand them in the context of a C++ code like this, that lists all logon sessions:
//Error handling is skipped!
ULONG n = 0;
LUID* pluid;
LsaEnumerateLogonSessions(&n, &pluid);
for(ULONG s = 0; s < n; s++)
{
PSECURITY_LOGON_SESSION_DATA* ps;
LsaGetLogonSessionData(&pluid[s], &ps);
//Analyze logon type
ps->LogonType;
LsaFreeReturnBuffer(ps);
}
LsaFreeReturnBuffer(pluid);
So far I can understand these:
Interactive if the actual (human) user logged in to the workstation. (As we are now while viewing this page.)
RemoteInteractive if a Remote Desktop Connection has been established with this workstation.
Can someone add more description to other values?
The MSDN explanations are all pretty self-explanatory, with the following clarifications:
CachedXXXX - Don't ask the domain controller to validate; instead, check against the local cached copy of the credentials.
Batch - Scheduled Tasks run using the Batch logon type. You can deny the Batch Logon right, which would prevent a user from running scheduled tasks.

WinAPI NetUserGetInfo() fails with NERR_UserNotFound error code on Active Directory domain

I'm running the following piece of code from a local service application. The purpose is to obtain the path to a user's profile before calling LoadUserProfile() to load that user's profile before calling CreateProcessAsUser() to run a user-mode process on behalf of that user.
Note that this question is not about LoadUserProfile(), or CreateProcessAsUser().
What happens is this. When the code below is run on Windows XP w/SP3 that is a part of the Active Directory domain, with a single user logged in via a local console (that user's session ID is used below) the NetUserGetInfo() API fails. Also note that it works fine in any other circumstance:
//'dwSessID' = session ID of the user to retrieve a user profile path for
LPTSTR pUserName = NULL;
DWORD dwcbSzUserName = 0;
if(!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSessID, WTSUserName, &pUserName, &dwcbSzUserName))
{
//Error
return false;
}
USER_INFO_4* pUI4 = NULL;
DWORD dwNetStatus;
if((dwNetStatus = NetUserGetInfo(NULL, pUserName, 4, (BYTE**)&pUI4)) == NERR_Success)
{
PROFILEINFO pfi = {0};
pfi.dwSize = sizeof(pfi);
pfi.lpUserName = pUserName;
pfi.dwFlags = PI_NOUI;
pfi.lpProfilePath = pUI4->usri4_profile;
LoadUserProfile(hToken, &pfi);
//And so on
}
else
{
//On that specific machine I get here with 'dwNetStatus' = 2221,
//or NERR_UserNotFound, that according to MSDN is
//"The user name could not be found."
//Also note that GetLastError is not used for this API.
}
Can some suggest why can NetUserGetInfo() fail on that particular machine, and how to fix this code?
PS. I know that MSDN for NetUserGetInfo states that there might be issues with a ACL on Active Directory domain, but it doesn't specify how to set one...
If I read the documentation for NetUserGetInfo, for the information level of the data you code 4 . It's written Level 4 Return detailed information and additional attributes about the user account. This level is valid only on servers. As far as I understand it's not your case. Do you verify the value of pUserName returned by WTSQuerySessionInformation.
As JPBlanc stated NetUserGetInfo with level 4 is valid only on servers.
Another problem is that you retrieve the name of the logged on user, but not the domain the user belongs to.
Noticed you are calling NetUserGetInfo with pUserName the type of LPTSTR.
Sometimes it won't work (if you will compile your project to use ANSII strings by default).
Consider changing you string types to LPWSTR.