Skip to content

Instantly share code, notes, and snippets.

@zanderz
Created May 21, 2018 21:45
Show Gist options
  • Save zanderz/bab477991468584f615704b68971a097 to your computer and use it in GitHub Desktop.
Save zanderz/bab477991468584f615704b68971a097 to your computer and use it in GitHub Desktop.
test windows user account creation apis
// user_test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "userenv.h"
#include "lm.h"
#pragma comment(lib, "userenv.lib")
#pragma comment(lib, "Netapi32.lib")
int main()
{
USER_INFO_1 ui1;
DWORD dwError;
HANDLE hToken;
PROFILEINFO pi;
// Set up the USER_INFO_1 structure that will be used to create the
// new user account
ZeroMemory(&ui1, sizeof(ui1));
ui1.usri1_name = _T("testuser");
ui1.usri1_password = _T("123456789");
ui1.usri1_priv = USER_PRIV_USER;
ui1.usri1_flags = UF_SCRIPT;
// Create the new user account
dwError = NetUserAdd(
NULL, // target computer name
1, // info level
(LPBYTE)&ui1, // address of user info structure
NULL); // index to invalid parameter
if (dwError != NERR_Success) {
_tprintf(_T("NetUserAdd() failed. Error %d\n"), dwError);
dwError = ERROR_ACCESS_DENIED;
return -1;
}
// Do a network logon because most systems do not grant new users
// the right to logon interactively (SE_INTERACTIVE_LOGON_NAME)
// but they do grant the right to do a network logon
// (SE_NETWORK_LOGON_NAME). A network logon has the added advantage
// of being quicker.
// NOTE: To call LogonUser(), the current user must have the
// SE_TCB_NAME privilege
if (!LogonUser(
ui1.usri1_name, // user name
_T("."), // domain or server
ui1.usri1_password, // password
LOGON32_LOGON_NETWORK, // type of logon operation
LOGON32_PROVIDER_DEFAULT, // logon provider
&hToken)) { // pointer to token handle
_tprintf(_T("LogonUser() failed. Error %d\n"), GetLastError());
return -1;
}
// Set up the PROFILEINFO structure that will be used to load the
// new user's profile
ZeroMemory(&pi, sizeof(pi));
pi.dwSize = sizeof(pi);
pi.lpUserName = ui1.usri1_name;
pi.dwFlags = PI_NOUI;
// Load the profile. Since it doesn't exist, it will be created
if (!LoadUserProfile(
hToken, // token for the user
&pi)) { // pointer to PROFILEINFO structure
_tprintf(_T("LoadUserProfile() failed. Error %d\n"),
GetLastError());
return -1;
}
PROCESS_INFORMATION procInfo;
if (!CreateProcessAsUser(
hToken,
_T("git.exe"),
_T("-version"),
NULL,
NULL,
false,
0,
NULL,
NULL,
NULL,
&procInfo
)) {
_tprintf(_T("CreateProcessAsUser() failed. Error %d\n"),
GetLastError());
return -1;
}
// Unload the profile when it is no longer needed
if (!UnloadUserProfile(
hToken, // token for the user
pi.hProfile)) { // registry key handle
_tprintf(_T("UnloadUserProfile() failed. Error %d\n"),
GetLastError());
return -1;
}
_tprintf(_T("I guess it worked\n"));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment