Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[CPP]View PlainCopy
- BOOL Executeasuser (lpcwstr lpszUserName, lpcwstr Lpszpassword, lpcwstr lpszapplication, LPCWSTR lpszCmdLine)
- {
- if (NULL = = lpszUserName)
- {
- return FALSE;
- }
- if (NULL = = lpszapplication)
- {
- return FALSE;
- }
- BOOL bRet = FALSE;
- wchar* pusername = NULL;
- wchar* ppassword = NULL;
- Startupinfo si = {sizeof (SI)};
- process_information pi = {0};
- WCHAR Szapp[max_path * 2] = {0};
- //Check User Name
- size_t Nlen = wcslen (lpszusername) + 1;
- Pusername = new Wchar[nlen];
- STRINGCCHPRINTFW (Pusername, Nlen, L"%s", lpszUserName);
- //Check Password
- Nlen = (NULL! = Lpszpassword)? (Wcslen (Lpszpassword) + 1): 2;
- Ppassword = new Wchar[nlen];
- STRINGCCHPRINTFW (Ppassword, Nlen, L"%s", (NULL! = Lpszpassword)? lpszpassword:l"");
- User_info_1 UI;
- DWORD dwerror = 0;
- DWORD dwlevel = 1;
- Ui.usri1_name = Pusername;
- Ui.usri1_password = Ppassword;
- Ui.usri1_priv = User_priv_user;
- Ui.usri1_home_dir = NULL;
- Ui.usri1_comment = NULL;
- Ui.usri1_flags = Uf_script;
- Ui.usri1_script_path = NULL;
- //ADD User
- if (nerr_success! = NetUserAdd (NULL, Dwlevel, (lpbyte) &ui, &dwerror))
- {
- Goto _end_;
- }
- if ((NULL! = lpszcmdline) && wcslen (lpszcmdline))
- STRINGCCHPRINTFW (Szapp, _countof (Szapp), L"%s%s", lpszapplication, lpszCmdLine);
- Else
- STRINGCCHPRINTFW (Szapp, _countof (Szapp), L"%s", lpszapplication);
- if (createprocesswithlogonw (lpszUserName, NULL, Lpszpassword, logon_with_profile, NULL, Szapp, 0, NULL, NULL, & Si, &pi))
- {
- BRet = TRUE;
- CloseHandle (Pi.hthread);
- CloseHandle (pi.hprocess);
- }
- Else
- {
- dwerror = GetLastError ();
- Goto _cleanup_;
- }
- BRet = TRUE;
- _cleanup_:
- //Delete User
- Netuserdel (NULL, lpszUserName);
- _end_:
- if (NULL! = Ppassword)
- {
- delete[] Ppassword;
- Ppassword = NULL;
- }
- if (NULL! = pusername)
- {
- delete[] Pusername;
- Pusername = NULL;
- }
- return bRet;
- }
- Test code
- #include "stdafx.h"
- #include <Windows.h>
- #include <lm.h>
- #include <strsafe.h>
- #pragma comment (lib, "Netapi32.lib")
- int _tmain (int argc, _tchar* argv[])
- {
- Executeasuser (l "ABC", l "Hello", l"F:\\11.exe", NULL);
- return 0;
- }
http://blog.csdn.net/visualeleven/article/details/7640475
This creates a new account that can be used to openprocesstoken+createrestrictedtoken the privileges of the current process's token for CreateProcessAsUser
A simple launch of an external application with user privileges (dynamically adding users using the NetUserAdd function and the user_info_1 struct, and then starting the program with CREATEPROCESSWITHLOGONW)