I am trying to set an executable to run as a local low-privileged user (different from the current logged-on user) by default. The Windows command "runas /savecred /user:username appname.exe" can do it, but it requires the current logged-on user to manually type in password of the different user at the first time. Ideally, I want the installer of the program set the credential, so no interaction would be needed for the current logged-on user. (I don't want to make the program as a Windows Service for other good reasons.)
When I ran the "runas" command, I observed that a new "interactive logon" Windows Credential got created in the Credential Manager, where "Internet or network address" was set as "$computer_name\$username (Interactive Logon)", "User name" was set as "$computer_name\$username", "password" was displayed as "********", and "Persistence" was set as "Enterprise".
Based on that observation, I found a Win32 API, CredWrite, and but I'm having trouble to make it work. I got error code 87 (ERROR_INVALID_PARAMETER - The parameter is incorrect.) when CredWrite was called.
#include <windows.h>
#include <wincred.h>
#include <tchar.h>
void main ()
{
char* password = "randompassword";
DWORD blobsize= 1 + strlen(password);
CREDENTIAL cred = {0};
cred.Flags = CRED_FLAGS_USERNAME_TARGET;
cred.Type = CRED_TYPE_DOMAIN_PASSWORD;
cred.TargetName = L"computername\\username";
cred.CredentialBlobSize = blobsize;
cred.CredentialBlob = (LPBYTE) password;
cred.Persist = CRED_PERSIST_LOCAL_MACHINE;
cred.UserName = L"computername\\username";
if (!CredWrite(&cred, 0))
{
std::cerr << GetLastError() << std::endl;
}
}
The references that I have been looking at are listed at the bottom. I was able to create a CRED_TYPE_GENERIC type credential but it was not recognized by RUNAS. I'm really puzzled on how to set fields like TargetName and Type in order to programmatically create an interactive logon credential as RUNAS does. The official MSDN documentation isn't clear and there is no example.
CredWrite : https://msdn.microsoft.com/en-us/library/windows/desktop/aa375187(v=vs.85).aspx CREDENTIAL: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374788(v=vs.85).aspx The sample code for creating a CRED_TYPE_GENERIC type credential: How do I store and retrieve credentials from the Windows Vault credential manager?