1/* su切换用户
2* 2004/12/28 1.0,发现Bingle的wsu是假冒令牌,权限并没有真正设置.
3* 2004/12/29 2.0,真正实现模拟用户令牌的动作.
4* 2004/12/29 3.0,即使帐号禁止也可以模拟用户
5* 2004/12/30 4.0, 可以模拟SYSTEM用户,权限24个,全部默认开放
6* 2004/12/30 4.1 终端登陆用户可以获取管理员组/SYSTEM权限.普通用户失败.
7*/
8#include <stdio.h>
9#include <stdlib.h>
10#include <winsock2.h>
11#include <lm.h>
12#include <Ntsecapi.h>
13#include <Accctrl.h>
14#include <Aclapi.h>
15#include <Tlhelp32.h>
16#include <windows.h>
17
18
19#pragma comment(lib,"ws2_32")
20#pragma comment(lib,"Advapi32")
21#pragma comment(lib,"User32")
22#pragma comment(lib,"Netapi32")
23
24#define SIZE 1024
25#define VERSION "4.1"
26
27#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
28#define WINSTA_ALL (WINSTA_ACCESSCLIPBOARD|WINSTA_ACCESSGLOBALATOMS|WINSTA_CREATEDESKTOP| WINSTA_ENUMDESKTOPS|WINSTA_ENUMERATE|WINSTA_EXITWINDOWS|WINSTA_READATTRIBUTES | WINSTA_READSCREEN|WINSTA_WRITEATTRIBUTES|DELETE|READ_CONTROL| WRITE_DAC|WRITE_OWNER)
29#define DESKTOP_ALL (DESKTOP_CREATEMENU|DESKTOP_CREATEWINDOW|DESKTOP_ENUMERATE|DESKTOP_HOOKCONTROL|DESKTOP_JOURNALPLAYBACK|DESKTOP_JOURNALRECORD|DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP|DESKTOP_WRITEOBJECTS|DELETE|READ_CONTROL| WRITE_DAC|WRITE_OWNER)
30#define GENERIC_ACCESS (GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE|GENERIC_ALL)
31#define SE_GROUP_RESOURCE (0x20000000L)
32
33typedef struct _OBJECT_ATTRIBUTES
34{
35 ULONG Length;
36 HANDLE RootDirectory;
37 PUNICODE_STRING ObjectName;
38 ULONG Attributes;
39 PVOID SecurityDescriptor;
40 PVOID SecurityQualityOfService;
41} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;
42
43typedef enum _LSA_TOKEN_INFORMATION_TYPE {
44 LsaTokenInformationNull, // Implies LSA_TOKEN_INFORMATION_NULL data type
45 LsaTokenInformationV1, // Implies LSA_TOKEN_INFORMATION_V1 data type
46 LsaTokenInformationV2 // Implies LSA_TOKEN_INFORMATION_V2 data type
47} LSA_TOKEN_INFORMATION_TYPE, *PLSA_TOKEN_INFORMATION_TYPE;
48
49typedef struct _LSA_TOKEN_INFORMATION_NULL
50{
51 LARGE_INTEGER ExpirationTime;
52 PTOKEN_GROUPS Groups;
53} LSA_TOKEN_INFORMATION_NULL, *PLSA_TOKEN_INFORMATION_NULL;
54
55typedef NTSTATUS (*PNtCreateToken)(
56PHANDLE TokenHandle,
57ACCESS_MASK DesiredAccess,
58POBJECT_ATTRIBUTES ObjectAttributes,
59TOKEN_TYPE TokenType,
60PLUID AuthenticationId,
61PLARGE_INTEGER ExpirationTime,
62PTOKEN_USER TokenUser,
63PTOKEN_GROUPS TokenGroups,
64PTOKEN_PRIVILEGES TokenPrivileges,
65PTOKEN_OWNER TokenOwner,
66PTOKEN_PRIMARY_GROUP TokenPrimaryGroup,
67PTOKEN_DEFAULT_DACL TokenDefaultDacl,
68PTOKEN_SOURCE TokenSource
69);
70
71
72typedef struct _PROFILEINFO {
73 DWORD dwSize;
74 DWORD dwFlags;
75 LPTSTR lpUserName;
76 LPTSTR lpProfilePath;
77 LPTSTR lpDefaultPath;
78 LPTSTR lpServerName;
79 LPTSTR lpPolicyPath;
80 HANDLE hProfile;
81} PROFILEINFO, *LPPROFILEINFO;
82
83typedef BOOL (*PLoadUserProfile)(
84 HANDLE hToken, // user token
85 LPPROFILEINFO lpProfileInfo // profile
86);
87
88
89typedef BOOL (*PUnloadUserProfile)(
90 HANDLE hToken, // user token
91 HANDLE hProfile // handle to registry key
92);
93BOOL cback = 0;
94char *system_user = NULL;
95int lsasspid = 0;
96unsigned int DebugLevel = 7;
97
98/* 函数定义开始 */
99void usage(char *s);
100int GrantPriv();
101HANDLE CreateTokenAsUser(char *user);
102BOOL ConvertSidToStringSid(PSID pSid,LPTSTR TextualSid, LPDWORD lpdwBufferLen);
103BOOL GetUserGroup(char *username,char ***name,int *groupcount);
104PSID GetUserSid(char *LookupUser);
105HANDLE NtCreateTokenAsuser(char *user);
106int GrantPrivFromLsass(int pid);
107void *GetFromToken(HANDLE hToken, TOKEN_INFORMATION_CLASS tic);
108void pfree(void *p);
109LUID GetLuidFromText(char *s);
110TOKEN_PRIVILEGES *MakeAdminPriv();
111BOOL AddUserPrivToHandle(HANDLE Hhandle,char *s,ACCESS_MODE mode);
112
113/* 函数定义结束 */
114int main(int argc,char **argv)
115{
116int i;
117WSADATA wsd;
118HANDLE NewToken;
119PLoadUserProfile LoadUserProfile;
120PUnloadUserProfile UnloadUserProfile;
121HMODULE UserenvModule;
122
123printf( "su.exe like unix su tool,version %s \n"
124"by bkbll (bkbll#cnhonker.net) http://www.cnhonker.com\n\n",VERSION);
125
126if((argc>1) && (strnicmp(argv[1],"-h",2) == 0))
127{
128usage(argv[0]);
129return -1;
130}
131for(i=1;i<argc;i+=2)
132{
133if(strlen(argv[i]) != 2)
134{
135usage(argv[0]);
136return -1;
137}
138switch(argv[i][1])
139{
140case 'u':
141system_user = argv[i+1];
142break;
143case 'D':
144DebugLevel = atoi(argv[i+1]);
145break;
146
147}
148}
149if(system_user == NULL)
150{
151usage(argv[0]);
152return -1;
153}
154UserenvModule = LoadLibrary("Userenv.dll");
155if(UserenvModule == NULL )
156{
157printf("[-] GetModuleHandle Userenv error:%d\n",GetLastError());
158return -1;
159}
160LoadUserProfile = (PLoadUserProfile) GetProcAddress(UserenvModule,"LoadUserProfileA");
161if(LoadUserProfile == NULL)
162{
163printf("[-] GetProcAddress LoadUserProfile error:%d\n",GetLastError());
164return -1;
165}
166
167UnloadUserProfile = (PUnloadUserProfile) GetProcAddress(UserenvModule,"UnloadUserProfile");
168if(UnloadUserProfile == NULL)
169{
170printf("[-] GetProcAddress UnloadUserProfile error:%d\n",GetLastError());
171return -1;
172}
173
174if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
175{
176printf("[-] WSAStartup error:%d\n", WSAGetLastError());
177return -1;
178}
179//首先建立一个TOKEN,这里假设是ADMIN用户
180//提升自己权限,先.
181printf("[+] Enable SeDebugPrivilege..\n");
182if(GrantPriv("SeDebugPrivilege") < 0)
183return -1;
184printf("[+] Get Lsass.exe Pid.");
185fflush(NULL);
186lsasspid = GetPidOfProcess("lsass.exe");
187if(lsasspid == -1)
188{
189printf("Get Pid of services failed\n");
190return -1;
191}
192printf("%d\n",lsasspid);
193//从Lsass继承权限.
194printf("[+] GrantPrivilege From Lsass .\n");
195if(GrantPrivFromLsass(lsasspid) == 0)
196{
197//建立一个TOKEN
198//NewToken = CreateTokenAsUser(system_user);
199printf("[+] Calling NtCreateTokenAsuser \n");
200NewToken = NtCreateTokenAsuser(system_user);
201if(NewToken != INVALID_HANDLE_VALUE)
202{
203STARTUPINFO si;
204PROCESS_INFORMATION pi;
205PROFILEINFO ProfileInfo;
206
207
208printf("[+] CreateProcess By that Token\n");
209fflush(stdout);
210Sleep(1000);
211LoadUserProfile(NewToken,&ProfileInfo);
212
213ZeroMemory( &si, sizeof(si) );
214si.cb = sizeof(si);
215//si.lpDesktop = TEXT("winstaABC\\testdesktop");
216ZeroMemory( &pi, sizeof(pi) );
217if( !CreateProcessAsUser( NewToken,
218NULL, // No module name (use command line).
219 "cmd", // Command line.
220 NULL, // Process handle not inheritable.
221 NULL, // Thread handle not inheritable.
222 TRUE, // Set handle inheritance to FALSE.
223 0, // No creation flags.
224 NULL, // Use parent's environment block.
225 NULL, // Use parent's starting directory.
226 &si, // Pointer to STARTUPINFO structure.
227 &pi ) // Pointer to PROCESS_INFORMATION structure.
228)
229{
230printf( "CreateProcessAsuser failed:%d.",GetLastError());
231exit(0);
232}
233
234// Wait until child process exits.
235WaitForSingleObject( pi.hProcess, INFINITE );
236// Close process and thread handles.
237CloseHandle( pi.hProcess );
238CloseHandle( pi.hThread );
239printf("[-] Process exited.\n");
240UnloadUserProfile(NewToken,ProfileInfo.hProfile);
241CloseHandle(NewToken);
242//用这个Token建立进程
243}
244}
245WSACleanup();
246exit(0);
247}
248//获得指定exe的PID
249int GetPidOfProcess(char *exe)
250{
251HANDLE hProcessSnap = NULL;
252BOOL bRet = FALSE;
253PROCESSENTRY32 pe32;
254int pid;
255
256memset(&pe32,0,sizeof(PROCESSENTRY32));
257pid = -1;
258hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
259if (hProcessSnap == INVALID_HANDLE_VALUE)
260{
261printf("CreateToolhelp32Snapshot Failed:%d\n",GetLastError());
262return pid;
263}
264//copy from MSDN
265pe32.dwSize = sizeof(PROCESSENTRY32);
266if (Process32First(hProcessSnap, &pe32))
267{
268do
269{
270if(stricmp(pe32.szExeFile,exe) == 0)
271{
272pid = pe32.th32ProcessID;
273break;
274}
275//printf( "PID:%d\n", pe32.th32ProcessID);
276//printf( "exepath:%s\n", pe32.szExeFile);
277} while(Process32Next(hProcessSnap, &pe32));
278}
279else
280return pid;
281// Do not forget to clean up the snapshot object.
282CloseHandle(hProcessSnap);
283return pid;
284}
285//返回指定用户/组的SID
286PSID GetUserSid(char *LookupUser)
287{
288SID *GroupSid;
289//char StringSid[SIZE];
290//DWORD SidSize,GroupCount;
291char *DomainName;
292//**UserGroup,*CurrentUser;
293DWORD cbSid,cbDomainName;
294SID_NAME_USE peUse;
295int ErrorCode,i;
296
297cbDomainName = 0;
298cbSid = 0;
299LookupAccountName(NULL,LookupUser,NULL,&cbSid,NULL,&cbDomainName,&peUse);
300ErrorCode = GetLastError();
301if(ErrorCode == ERROR_INSUFFICIENT_BUFFER) //122
302{
303//printf("Buffer is small. require cbSid %d bytes,cbDomainName %d bytes\n",cbSid,cbDomainName);
304GroupSid = (SID *) malloc(cbSid + 1);
305DomainName = (char*) malloc(cbDomainName + 1);
306if((GroupSid == NULL) || (DomainName == NULL))
307{
308printf("Malloc failed:%d\n",GetLastError());
309return NULL;
310}
311memset(GroupSid,0,cbSid + 1);
312memset(DomainName,0,cbDomainName + 1);
313}
314else
315{
316printf("LookupAccountName in GetUserSid(\"%s\") Failed:%d\n",LookupUser,ErrorCode);
317return NULL;
318}
319if(!LookupAccountName(NULL,LookupUser,GroupSid,&cbSid,DomainName,&cbDomainName,&peUse))
320{
321printf("LookupAccountName GetUserSid(\"%s\") After Malloc Failed:%d\n",LookupUser,GetLastError());
322return NULL;
323}
324pfree(DomainName);
325return GroupSid;
326}
327
328//建立Administrators和SYSTEM 共用的privilege
329TOKEN_PRIVILEGES *MakeAdminPriv()
330{
331TOKEN_PRIVILEGES *token_privileges;
332DWORD i,PrivilegeCount;
333
334i = 0;
335PrivilegeCount = 24;
336token_privileges = (PTOKEN_PRIVILEGES) malloc(4 + (3*4)*PrivilegeCount + 4);
337if(token_privileges == NULL)
338{
339printf("malloc failed for PTOKEN_PRIVILEGES in NtCreateTokenAsuser\n");
340return NULL;
341}
342token_privileges->PrivilegeCount = PrivilegeCount;
343//0
344token_privileges->Privileges[i].Attributes = 3;
345token_privileges->Privileges[i++].Luid = GetLuidFromText("SeTcbPrivilege");
346//1
347token_privileges->Privileges[i].Attributes = 3;
348token_privileges->Privileges[i++].Luid = GetLuidFromText("SeCreateTokenPrivilege");
349//2
350token_privileges->Privileges[i].Attributes = 3;
351token_privileges->Privileges[i++].Luid = GetLuidFromText("SeTakeOwnershipPrivilege");
352//3
353token_privileges->Privileges[i].Attributes = 3;
354token_privileges->Privileges[i++].Luid = GetLuidFromText("SeCreatePagefilePrivilege");
355//4
356token_privileges->Privileges[i].Attributes = 3;
357token_privileges->Privileges[i++].Luid = GetLuidFromText("SeLockMemoryPrivilege");
358//5
359token_privileges->Privileges[i].Attributes = 3;
360token_privileges->Privileges[i++].Luid = GetLuidFromText("SeAssignPrimaryTokenPrivilege");
361//6
362token_privileges->Privileges[i].Attributes = 3;
363token_privileges->Privileges[i++].Luid = GetLuidFromText("SeIncreaseQuotaPrivilege");
364//7
365token_privileges->Privileges[i].Attributes = 3;
366token_privileges->Privileges[i++].Luid = GetLuidFromText("SeIncreaseBasePriorityPrivilege");
367//8
368token_privileges->Privileges[i].Attributes = 3;
369token_privileges->Privileges[i++].Luid = GetLuidFromText("SeCreatePermanentPrivilege");
370//9
371token_privileges->Privileges[i].Attributes = 3;
372token_privileges->Privileges[i++].Luid = GetLuidFromText("SeDebugPrivilege");
373//10
374token_privileges->Privileges[i].Attributes = 3;
375token_privileges->Privileges[i++].Luid = GetLuidFromText("SeAuditPrivilege");
376//11
377token_privileges->Privileges[i].Attributes = 3;
378token_privileges->Privileges[i++].Luid = GetLuidFromText("SeSecurityPrivilege");
379//12
380token_privileges->Privileges[i].Attributes = 3;
381token_privileges->Privileges[i++].Luid = GetLuidFromText("SeSystemEnvironmentPrivilege");
382//13
383token_privileges->Privileges[i].Attributes = 3;
384token_privileges->Privileges[i++].Luid = GetLuidFromText("SeChangeNotifyPrivilege");
385//14
386token_privileges->Privileges[i].Attributes = 3;
387token_privileges->Privileges[i++].Luid = GetLuidFromText("SeBackupPrivilege");
388//15
389token_privileges->Privileges[i].Attributes = 3;
390token_privileges->Privileges[i++].Luid = GetLuidFromText("SeRestorePrivilege");
391//16
392token_privileges->Privileges[i].Attributes = 3;
393token_privileges->Privileges[i++].Luid = GetLuidFromText("SeShutdownPrivilege");
394//17
395token_privileges->Privileges[i].Attributes = 3;
396token_privileges->Privileges[i++].Luid = GetLuidFromText("SeLoadDriverPrivilege");
397//18
398token_privileges->Privileges[i].Attributes = 3;
399token_privileges->Privileges[i++].Luid = GetLuidFromText("SeProfileSingleProcessPrivilege");
400//19
401token_privileges->Privileges[i].Attributes = 3;
402token_privileges->Privileges[i++].Luid = GetLuidFromText("SeSystemtimePrivilege");
403//20
404token_privileges->Privileges[i].Attributes = 3;
405token_privileges->Privileges[i++].Luid = GetLuidFromText("SeUndockPrivilege");
406//21
407token_privileges->Privileges[i].Attributes = 3;
408token_privileges->Privileges[i++].Luid = GetLuidFromText("SeManageVolumePrivilege");
409//22
410token_privileges->Privileges[i].Attributes = 3;
411token_privileges->Privileges[i++].Luid = GetLuidFromText("SeImpersonatePrivilege");
412//23
413token_privileges->Privileges[i].Attributes = 3;
414token_privileges->Privileges[i++].Luid = GetLuidFromText("SeCreateGlobalPrivilege");
415
416return token_privileges;
417
418}
419//加用户到HANDLE
420BOOL AddUserPrivToHandle(HANDLE Hhandle,char *s,ACCESS_MODE mode)
421{
422PSECURITY_DESCRIPTOR pSecurityDescriptor1,pSD = NULL;
423DWORD size,size1,len,ErrorCode,DaclPresent,DaclDefaulted,dwAbsoluteSDSize,dwDaclSize,dwSaclSize,dwOwnerSize,dwPrimaryGroupSize;
424ACL OldAcl;
425PACL POldAcl,PNewAcl,pDacl,pSacl;
426PSID pOwner,pPrimaryGroup;
427EXPLICIT_ACCESS ExplicitAccess1;
428SECURITY_INFORMATION sinfo;
429
430dwAbsoluteSDSize = dwDaclSize = dwSaclSize = dwOwnerSize = dwPrimaryGroupSize = 0;
431
432size = 0;
433sinfo = DACL_SECURITY_INFORMATION;
434//获得SECURITY_DESCRIPTOR
435GetUserObjectSecurity(Hhandle,&sinfo,pSD,size,&len);
436ErrorCode = GetLastError();
437if(ErrorCode == ERROR_INSUFFICIENT_BUFFER) //122
438{
439pSD = (PSECURITY_DESCRIPTOR) malloc(len + 1);
440if(pSD == NULL)
441{
442printf("Malloc failed:%d\n",GetLastError());
443return FALSE;
444}
445memset(pSD,0,len + 1);
446size = len;
447}
448else
449{
450printf("GetUserObjectSecurity in AddUserPrivToHandle(\"%s\") Failed:%d\n",s,ErrorCode);
451return FALSE;
452}
453if(!GetUserObjectSecurity(Hhandle,&sinfo,pSD,size,&len))
454{
455printf("GetUserObjectSecurity in AddUserPrivToHandle(\"%s\") Failed:%d\n",s,ErrorCode);
456return FALSE;
457}
458//获得DACL
459POldAcl = NULL;
460if(!GetSecurityDescriptorDacl(pSD,&DaclPresent,&POldAcl,&DaclDefaulted))
461{
462printf("GetSecurityDescriptorDacl Error:%d\n",GetLastError());
463return FALSE;
464}
465//重新生成一个ACL,然后在后面合并进去,给administrators组全部的权限.
466memset(&ExplicitAccess1,0,sizeof(ExplicitAccess1));
467BuildExplicitAccessWithName(&ExplicitAccess1,s,mode,GRANT_ACCESS,NO_INHERITANCE);
468//合并权限
469ErrorCode = SetEntriesInAcl(1,&ExplicitAccess1,POldAcl,&PNewAcl);
470if(ErrorCode != ERROR_SUCCESS)
471{
472printf("SetEntriesInAcl Error:%d\n",ErrorCode);
473return FALSE;
474}
475
476dwAbsoluteSDSize = 0x400;
477pSecurityDescriptor1 = (PSECURITY_DESCRIPTOR) malloc(dwAbsoluteSDSize+1);
478if(pSecurityDescriptor1 == NULL)
479{
480printf("Malloc for MakeAbsoluteSD failed:%d\n",GetLastError());
481return FALSE;
482}
483memset(pSecurityDescriptor1,0,dwAbsoluteSDSize+1);
484
485MakeAbsoluteSD( pSD,
486pSecurityDescriptor1,
487&dwAbsoluteSDSize,
488NULL,
489&dwDaclSize,
490NULL,
491&dwSaclSize,
492NULL,
493&dwOwnerSize,
494NULL,
495&dwPrimaryGroupSize);
496//申请内存先.
497ErrorCode = GetLastError();
498
499if(ErrorCode == ERROR_INSUFFICIENT_BUFFER)
500{
501//申请内存
502//printf("申请内存大小:\ndwDaclSize=%d\ndwSaclSize=%d\ndwOwnerSize=%d\ndwPrimaryGroupSize=%d\ndwAbsoluteSDSize=%d\n",
503// dwDaclSize,dwSaclSize,dwOwnerSize,dwPrimaryGroupSize,dwAbsoluteSDSize);
504//
505//pSecurityDescriptor1 = (PSECURITY_DESCRIPTOR) malloc(dwAbsoluteSDSize+1);
506pDacl = (PACL) malloc(dwDaclSize+1);
507pSacl = (PACL) malloc(dwSaclSize+1);
508pOwner = (PSID) malloc(dwOwnerSize+1);
509pPrimaryGroup = (PSID) malloc(dwPrimaryGroupSize+1);
510
511if( //(pSecurityDescriptor1 == NULL) ||
512 (pDacl == NULL) ||
513 (pSacl == NULL) ||
514 (pOwner == NULL) ||
515 (pPrimaryGroup == NULL))
516{
517printf("Malloc for MakeAbsoluteSD failed:%d\n",GetLastError());
518return FALSE;
519}
520//memset(pSecurityDescriptor1,0,dwAbsoluteSDSize+1);
521}
522else
523{
524printf("MakeAbsoluteSD Error:%d\n",GetLastError());
525return FALSE;
526}
527//申请后就可以接受了
528if(!MakeAbsoluteSD(pSD,
529pSecurityDescriptor1,
530&dwAbsoluteSDSize,
531pDacl,
532&dwDaclSize,
533pSacl,
534&dwSaclSize,
535pOwner,
536&dwOwnerSize,
537pPrimaryGroup,
538&dwPrimaryGroupSize))
539{
540printf("MakeAbsoluteSD After Malloc Error:%d\n",GetLastError());
541return FALSE;
542}
543//printf("实际接受大小:\ndwDaclSize=%d\ndwSaclSize=%d\ndwOwnerSize=%d\ndwPrimaryGroupSize=%d\ndwAbsoluteSDSize=%d\n",
544// dwDaclSize,dwSaclSize,dwOwnerSize,dwPrimaryGroupSize,size1);
545//设置新的DACL
546if(!SetSecurityDescriptorDacl(pSecurityDescriptor1,DaclPresent,PNewAcl,DaclDefaulted))
547{
548printf("SetSecurityDescriptorDacl Error:%d\n",GetLastError());
549return FALSE;
550}
551//检查新的SecurityDescriptor是否合法
552if(!IsValidSecurityDescriptor(pSecurityDescriptor1))
553{
554printf("pSecurityDescriptor1 is not a valid SD:%d\n",GetLastError());
555return FALSE;
556}
557
558//给句柄设置新的ACL
559if(!SetUserObjectSecurity(Hhandle,&sinfo,pSecurityDescriptor1))
560{
561printf("SetKernelObjectSecurity Error:%d\n",GetLastError());
562return FALSE;
563}
564if(POldAcl)
565LocalFree(POldAcl);
566if(PNewAcl)
567LocalFree(PNewAcl);
568pfree(pSD);
569pfree(pSecurityDescriptor1);
570pfree(pDacl);
571pfree(pSacl);
572pfree(pOwner);
573pfree(pPrimaryGroup);
574return TRUE;
575}
576
577//根据指定用户名来建立Token
578HANDLE NtCreateTokenAsuser(char *user)
579{
580SID *GroupSid,*UserSid;
581char StringSid[SIZE],UserDefaultGroup[SIZE];
582DWORD SidSize,GroupCount,GroupCount2,IsNotUsersGroup = 1;
583char *DomainName,**UserGroup,*CurrentUser;
584DWORD cbSid,cbDomainName,SessionId,sessionlen;
585SID_NAME_USE peUse;
586int ErrorCode,i;
587LUID Luid = ANONYMOUS_LOGON_LUID;
588//LUID Luid = SYSTEM_LUID;
589SECURITY_QUALITY_OF_SERVICE security_quality_of_service =
590 {
591 sizeof( security_quality_of_service ),
592 SecurityAnonymous,
593 SECURITY_STATIC_TRACKING,
594 FALSE
595 };
596OBJECT_ATTRIBUTES object_attributes =
597{
598 sizeof( object_attributes ),
599 NULL,
600 NULL,
601 0,
602 NULL,
603 &security_quality_of_service
604};
605
606TOKEN_SOURCE token_source;
607TOKEN_PRIVILEGES *token_privileges;
608TOKEN_GROUPS *token_groups;
609TOKEN_USER token_user;
610TOKEN_OWNER token_owner;
611TOKEN_PRIMARY_GROUP token_primary_group;
612TOKEN_DEFAULT_DACL token_default_dacl,*SelfDacl;
613ACL NewAcl2,*NewAcl;
614TOKEN_TYPE tokentype;
615HANDLE token,SelfToken;
616NTSTATUS ntstatus,ntstatus2;
617PNtCreateToken NtCreateToken;
618HMODULE ntdllmodule;
619ACCESS_MASK DesiredAccess;
620LARGE_INTEGER ExpireTime;
621EXPLICIT_ACCESS ExplicitAccess;
622//给winstation用的
623HDESK hdesk;
624HWINSTA hwinsta;
625DWORD PrivilegeCount;
626//是否是SYSTEM用户
627DWORD IfIsSystemUser = 0,IfIsAdmin = 0;
628//定义结束
629
630//获取CreateToken地址
631ntdllmodule = GetModuleHandle("ntdll");
632if(ntdllmodule == NULL )
633{
634printf("[-] GetModuleHandle ntdll error:%d\n",GetLastError());
635return INVALID_HANDLE_VALUE;
636}
637NtCreateToken = (PNtCreateToken) GetProcAddress(ntdllmodule,"ZwCreateToken");
638if(NtCreateToken == NULL)
639{
640printf("[-] GetProcAddress NtCreateToken error:%d\n",GetLastError());
641return INVALID_HANDLE_VALUE;
642}
643
644if(stricmp(user,"system") == 0)
645{
646IfIsSystemUser = 1;
647//Luid.LowPart = 0x3e7;
648//Luid.HighPart = 0x0;
649}
650//arg 2 for NtCreateToken();
651DesiredAccess = TOKEN_ALL_ACCESS;
652//arg 3 for NtCreateToken();
653//arg 4 for NtCreateToken();
654//IN TOKEN_TYPE TokenType,
655tokentype = TokenPrimary;
656//arg 5 for NtCreateToken();
657//memcpy(&Luid,&SYSTEM_LUID,sizeof(Luid));
658/*
659if(!AllocateLocallyUniqueId(&Luid))
660{
661printf("AllocateLocallyUniqueId Failed:%d\n",GetLastError());
662return INVALID_HANDLE_VALUE;
663}
664*/
665//arg 6 for NtCreateToken();
666ExpireTime.LowPart = 0xffffffff;
667ExpireTime.HighPart = 0x7fffffff;
668//printf("sizeof(ExpireTime) = %d\n",sizeof(ExpireTime));
669//QueryPerformanceFrequency(&ExpireTime);
670//arg 7 for NtCreateToken();
671//token_user正确
672token_user.User.Sid = GetUserSid(user);
673if(token_user.User.Sid == NULL)
674return INVALID_HANDLE_VALUE;
675token_user.User.Attributes = 0; //must be 0
676if(IfIsSystemUser == 0) //一般用户
677{
678//arg 8 for NtCreateToken();
679if(!GetUserGroup(user,&UserGroup,&GroupCount))
680return INVALID_HANDLE_VALUE;
681//printf("=====================\nGet %d groups\n",GroupCount);
682//给token_groups申请内存
683//看用户组里面有没有"Users"
684IsNotUsersGroup = 1;
685for(i=0;i<GroupCount;i++)
686{
687CurrentUser = UserGroup[i];
688if(stricmp(CurrentUser,"Users") == 0)
689{
690IsNotUsersGroup = 0;
691continue;
692}
693if(stricmp(CurrentUser,"Administrators") == 0)
694{
695IfIsAdmin = 1;
696continue;
697}
698}
699//保存一下,后面要用
700GroupCount2 = GroupCount;
701//没有就+1,有就+0
702GroupCount += IsNotUsersGroup + 2;
703token_groups = (PTOKEN_GROUPS) malloc(4+(4+4)*GroupCount+1);
704if(token_groups == NULL)
705{
706printf("Malloc for token_groups failed:%d\n",GetLastError());
707return INVALID_HANDLE_VALUE;
708}
709//加"None","Everyone","INTERACTIVE" 组
710//printf("GroupCount:%d\n",GroupCount);
711token_groups->GroupCount = GroupCount;
712//给第11个参数用
713//memset(UserDefaultGroup,0,SIZE);
714//strncpy(UserDefaultGroup,UserGroup[0],SIZE -1 );
715//printf("GroupCount:%d\n",GroupCount);
716//token_group需要最少加以下四个组:
717//只有Users可能有用户或者帐号存在
718//"None","Everyone","Users","INTERACTIVE"他们的ATTribute都是7
719if(DebugLevel != 7)
720{
721printf("Using DebugLevel 0x%x \n",DebugLevel);
722}
723for(i=0;i<GroupCount2;i++)
724{
725//printf("%d:%s\n",i,UserGroup[i]);
726
727CurrentUser = UserGroup[i];
728GroupSid = GetUserSid(CurrentUser);
729if(GroupSid == NULL)
730return INVALID_HANDLE_VALUE;
731token_groups->Groups[i].Sid = GroupSid;
732token_groups->Groups[i].Attributes = DebugLevel;
733free(CurrentUser);
734}
735free(UserGroup);
736/*
737GroupSid = GetUserSid("None");
738if(GroupSid == NULL)
739return INVALID_HANDLE_VALUE;
740token_groups->Groups[i].Sid = GroupSid;
741token_groups->Groups[i++].Attributes = DebugLevel;
742*/
743GroupSid = GetUserSid("Everyone");
744if(GroupSid == NULL)
745return INVALID_HANDLE_VALUE;
746token_groups->Groups[i].Sid = GroupSid;
747token_groups->Groups[i++].Attributes = DebugLevel;
748
749GroupSid = GetUserSid("INTERACTIVE");
750if(GroupSid == NULL)
751return INVALID_HANDLE_VALUE;
752token_groups->Groups[i].Sid = GroupSid;
753token_groups->Groups[i++].Attributes = DebugLevel;
754
755if(IsNotUsersGroup)
756{
757GroupSid = GetUserSid("Users");
758if(GroupSid == NULL)
759return INVALID_HANDLE_VALUE;
760token_groups->Groups[i].Sid = GroupSid;
761token_groups->Groups[i++].Attributes = DebugLevel;
762}
763//arg 9 for NtCreateToken();
764//这个倒没错
765//先申请内存
766if(IfIsAdmin == 0) //如果不是管理员组
767{
768PrivilegeCount = 2;
769token_privileges = (PTOKEN_PRIVILEGES) malloc(4 + (3*4)*PrivilegeCount + 4);
770if(token_privileges == NULL)
771{
772printf("malloc failed for PTOKEN_PRIVILEGES in NtCreateTokenAsuser\n");
773return INVALID_HANDLE_VALUE;
774}
775token_privileges->PrivilegeCount = PrivilegeCount;
776(token_privileges->Privileges)[0].Attributes = SE_PRIVILEGE_ENABLED_BY_DEFAULT;
777(token_privileges->Privileges)[0].Luid = GetLuidFromText("SeChangeNotifyPrivilege");
778
779(token_privileges->Privileges)[1].Attributes = SE_PRIVILEGE_ENABLED_BY_DEFAULT;
780(token_privileges->Privileges)[1].Luid = GetLuidFromText("SeUndockPrivilege");
781}
782else
783{
784token_privileges = MakeAdminPriv();
785if(token_privileges == NULL)
786return INVALID_HANDLE_VALUE;
787}
788/*
789if(!AllocateLocallyUniqueId(&(token_privileges.Privileges[0].Luid)))
790{
791printf("AllocateLocallyUniqueId for token_privileges Failed:%d\n",GetLastError());
792return INVALID_HANDLE_VALUE;
793}
794*/
795//arg 10 for NtCreateToken();
796//正确的方法
797token_owner.Owner = GetUserSid(user);
798if(token_owner.Owner == NULL)
799return INVALID_HANDLE_VALUE;
800//arg 11 for NtCreateToken();
801//PrimaryGroup统一都是None
802token_primary_group.PrimaryGroup = GetUserSid(user);
803if(token_primary_group.PrimaryGroup == NULL)
804return INVALID_HANDLE_VALUE;
805}
806else
807{
808//设置usergroup
809//三个组:administrators(0xe),everyone(0x7),Authenticated Users(0x7)
810GroupCount = 2;
811token_groups = (PTOKEN_GROUPS) malloc(4+(4+4)*GroupCount+1);
812if(token_groups == NULL)
813{
814printf("Malloc for token_groups failed:%d\n",GetLastError());
815return INVALID_HANDLE_VALUE;
816}
817token_groups->GroupCount = GroupCount;
818//自定义的debuglevel
819if(DebugLevel != 7)
820{
821printf("Using DebugLevel 0x%x \n",DebugLevel);
822}
823i = 0;
824GroupSid = GetUserSid("administrators");
825if(GroupSid == NULL)
826return INVALID_HANDLE_VALUE;
827token_groups->Groups[i].Sid = GroupSid;
828token_groups->Groups[i++].Attributes = 0xe;
829
830GroupSid = GetUserSid("Everyone");
831if(GroupSid == NULL)
832return INVALID_HANDLE_VALUE;
833token_groups->Groups[i].Sid = GroupSid;
834token_groups->Groups[i++].Attributes = DebugLevel;
835/*
836GroupSid = GetUserSid("Authenticated Users");
837if(GroupSid == NULL)
838return INVALID_HANDLE_VALUE;
839token_groups->Groups[i].Sid = GroupSid;
840token_groups->Groups[i++].Attributes = DebugLevel;
841*/
842//设置 token_privileges
843token_privileges = MakeAdminPriv();
844if(token_privileges == NULL)
845return INVALID_HANDLE_VALUE;
846//token_owner
847token_owner.Owner = GetUserSid("administrators");
848if(token_owner.Owner == NULL)
849return INVALID_HANDLE_VALUE;
850//arg 11 for NtCreateToken();
851//PrimaryGroup统一都是None
852token_primary_group.PrimaryGroup = GetUserSid("SYSTEM");
853if(token_primary_group.PrimaryGroup == NULL)
854return INVALID_HANDLE_VALUE;
855}
856//arg 12 for NtCreateToken();
857//NULL?
858//token_default_dacl
859/*
860token_default_dacl->DefaultDacl->AclRevision:2
861token_default_dacl->DefaultDacl->Sbz1:0
862token_default_dacl->DefaultDacl->AclSize:64
863token_default_dacl->DefaultDacl->AceCount:2
864token_default_dacl->DefaultDacl->Sbz2:0
865*/
866if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &SelfToken))
867{
868printf("OpenProcessToken self Error:%d\n",GetLastError());
869return INVALID_HANDLE_VALUE;
870}
871BuildExplicitAccessWithName(&ExplicitAccess,user,GENERIC_ALL,GRANT_ACCESS,NO_INHERITANCE);
872SelfDacl = (PTOKEN_DEFAULT_DACL) GetFromToken(SelfToken,TokenDefaultDacl);
873if(SelfDacl == NULL)
874{
875CloseHandle(SelfToken);
876return INVALID_HANDLE_VALUE;
877}
878ErrorCode = SetEntriesInAcl(1,&ExplicitAccess,SelfDacl->DefaultDacl,&NewAcl);
879if(ErrorCode != ERROR_SUCCESS)
880{
881printf("SetEntriesInAcl Under NtCreateTokenAsuser Failed:%d\n",ErrorCode);
882CloseHandle(SelfToken);
883return INVALID_HANDLE_VALUE;
884}
885//获得当前进程的SessionID,然后再同样set到新的token里面
886//printf("SelfProcess:\n");
887//DisplayTokenSessionId(SelfToken);
888//SessionId,sessionlen;
889sessionlen = sizeof(DWORD);
890if(!GetTokenInformation(SelfToken,TokenSessionId,&SessionId,sessionlen,&sessionlen))
891{
892printf("GetTokenInformation TokenSessionId Failed:%d\n",GetLastError());
893CloseHandle(SelfToken);
894return INVALID_HANDLE_VALUE;
895}
896CloseHandle(SelfToken);
897token_default_dacl.DefaultDacl = NewAcl;
898/*
899NewAcl2.AclRevision = 2;
900NewAcl2.Sbz1 = 0;
901NewAcl2.AclSize = 64;
902NewAcl2.AceCount = 2;
903NewAcl2.Sbz2 = 0;
904ErrorCode = SetEntriesInAcl(0,NULL,NULL,&NewAcl);
905if(ErrorCode != ERROR_SUCCESS)
906{
907printf("SetEntriesInAcl As new one failed:%d\n",ErrorCode);
908return INVALID_HANDLE_VALUE;
909}
910token_default_dacl.DefaultDacl = NewAcl;
911*/
912//arg 13 for NtCreateToken();
913//token_source
914if(IfIsSystemUser == 0) //一般用户
915memcpy(token_source.SourceName,"seclogon",8);
916else
917memcpy(token_source.SourceName,"*SYSTEM*",8);
918//生成LUID
919//token_source.SourceIdentifier = Luid;
920if(!AllocateLocallyUniqueId(&(token_source.SourceIdentifier)))
921{
922printf("AllocateLocallyUniqueId for token_source Failed:%d\n",GetLastError());
923return INVALID_HANDLE_VALUE;
924}
925if(IfIsSystemUser == 0)
926{
927//将该用户权限加入到当前用户所使用的 桌面 和 winstation
928//hwinsta = OpenWindowStation("WinSta0",TRUE,WINSTA_ALL);
929hwinsta = GetProcessWindowStation();
930if (hwinsta == NULL)
931{
932printf("OpenWindowStation Error:%d\n",GetLastError());
933return INVALID_HANDLE_VALUE;
934}
935//hwinstaold = GetProcessWindowStation();
936
937//
938// set the windowstation to winsta0 so that you obtain the
939// correct default desktop
940//
941/*
942if (!SetProcessWindowStation(hwinsta))
943{
944printf("SetProcessWindowStation Error:%d\n",GetLastError());
945CloseWindowStation(hwinsta);
946return INVALID_HANDLE_VALUE;
947}
948*/
949//
950// obtain a handle to the "default" desktop
951//
952//hdesk = OpenDesktop("Default",DF_ALLOWOTHERACCOUNTHOOK,FALSE,DESKTOP_ALL);
953hdesk = GetThreadDesktop(GetCurrentThreadId());
954if (hdesk == NULL)
955{
956printf("OpenDesktop Error:%d\n",GetLastError());
957CloseWindowStation(hwinsta);
958return INVALID_HANDLE_VALUE;
959}
960// add the user to interactive windowstation
961//
962AddUserPrivToHandle(hwinsta,user,WINSTA_ALL);
963AddUserPrivToHandle(hdesk,user,DESKTOP_ALL);
964/*
965if (!AddTheAceWindowStation(hwinsta, token_user.User.Sid))
966{
967printf("AddTheAceWindowStation Error:%d\n",GetLastError());
968CloseWindowStation(hwinsta);
969CloseDesktop(hdesk);
970return INVALID_HANDLE_VALUE;
971}
972//
973// add user to "default" desktop
974//
975if (!AddTheAceDesktop(hdesk, token_user.User.Sid))
976{
977printf("AddTheAceDesktop Error:%d\n",GetLastError());
978CloseWindowStation(hwinsta);
979CloseDesktop(hdesk);
980return INVALID_HANDLE_VALUE;
981}
982*/
983if (!SetProcessWindowStation(hwinsta))
984{
985printf("SetProcessWindowStation Error:%d\n",GetLastError());
986CloseWindowStation(hwinsta);
987return INVALID_HANDLE_VALUE;
988}
989if(!SetThreadDesktop(hdesk))
990{
991printf("SetThreadDesktop Error:%d\n",GetLastError());
992CloseDesktop(hdesk);
993return INVALID_HANDLE_VALUE;
994}
995//
996// close the handles to the interactive windowstation and desktop
997//
998CloseWindowStation(hwinsta);
999CloseDesktop(hdesk);
1000}
1001//开始create
1002ntstatus = NtCreateToken( &token,
1003DesiredAccess,
1004&object_attributes,
1005tokentype,
1006&Luid,
1007&ExpireTime,
1008&token_user,
1009token_groups,
1010token_privileges,
1011&token_owner,
1012&token_primary_group,
1013&token_default_dacl,
1014&token_source
1015);
1016if(ntstatus != STATUS_SUCCESS)
1017{
1018printf("CreateToken Failed:%d\n",LsaNtStatusToWinError(ntstatus));
1019return INVALID_HANDLE_VALUE;
1020}
1021//开始释放内存
1022/*
1023pfree(token_user.User.Sid);
1024pfree(token_groups);
1025pfree(token_privileges);
1026pfree(token_owner.Owner);
1027pfree(token_primary_group.PrimaryGroup);
1028if(NewAcl != NULL)
1029LocalFree(NewAcl);
1030*/
1031/*
1032printf("NewToken:\n");
1033DisplayTokenSessionId(token);
1034*/
1035if(TokenSessionId > 0)
1036{
1037sessionlen = sizeof(DWORD);
1038if(!SetTokenInformation(token,TokenSessionId,&SessionId,sessionlen))
1039{
1040printf("SetTokenInformation TokenSessionId Failed:%d\n",GetLastError());
1041}
1042}
1043return token;
1044}
1045
1046
1047//输出:指针指向一系列的group,groupcount为group数目.
1048BOOL GetUserGroup(char *username,char ***groupname,int *groupcount)
1049{
1050LPLOCALGROUP_USERS_INFO_0 pBuf = NULL;
1051DWORD dwLevel = 0;
1052DWORD dwFlags = LG_INCLUDE_INDIRECT ;
1053DWORD dwPrefMaxLen = -1;
1054DWORD dwEntriesRead = 0;
1055DWORD dwTotalEntries = 0;
1056NET_API_STATUS nStatus;
1057DWORD i;
1058 DWORD dwTotalCount = 0;
1059WCHAR wUserName[100];//,wAdminGroup[50];
1060BOOL returnvalue=FALSE;
1061char *p;
1062DWORD len;
1063char **name;
1064
1065MultiByteToWideChar( CP_ACP, 0, username,-1, wUserName,sizeof(wUserName)/sizeof(wUserName[0]));
1066//MultiByteToWideChar( CP_ACP, 0, admingroup,-1, wAdminGroup,sizeof(wAdminGroup)/sizeof(wAdminGroup[0]));
1067
1068nStatus = NetUserGetLocalGroups(NULL,wUserName,dwLevel,dwFlags,(LPBYTE *) &pBuf,dwPrefMaxLen,&dwEntriesRead,&dwTotalEntries);
1069
1070 if (nStatus != NERR_Success)
1071 {
1072 return returnvalue;
1073 }
1074
1075 if(pBuf == NULL)
1076 return returnvalue;
1077
1078
1079name = (char **) malloc(dwEntriesRead * sizeof(char *));
1080if(name == NULL)
1081{
1082printf("malloc failed in GetUserGroup for name:%d\n",GetLastError());
1083return returnvalue;
1084}
1085returnvalue = TRUE;
1086 for (i = 0; i < dwEntriesRead; i++)
1087{
1088if (pBuf == NULL)
1089return returnvalue;
1090len = wcslen(pBuf->lgrui0_name);
1091p = (char *) malloc(len+1);
1092if(p == NULL)
1093{
1094printf("malloc failed in GetUserGroup:%d\n",GetLastError());
1095break;
1096}
1097wsprintf(p,"%S",pBuf->lgrui0_name);
1098name[dwTotalCount] = p;
1099//printf("%d:%s\n",dwTotalCount,p);
1100pBuf++;
1101dwTotalCount++;
1102 }
1103 if(pBuf != NULL)
1104 NetApiBufferFree(pBuf);
1105 *groupname = name;
1106 *groupcount = dwTotalCount;
1107 return returnvalue;
1108}
1109//加权限
1110int GrantPriv(char *priv)
1111{
1112HANDLE token;
1113TOKEN_PRIVILEGES tkp;
1114HANDLE hProc;
1115
1116//SeCreateTokenPrivilege
1117if(LookupPrivilegeValue(NULL,priv,&tkp.Privileges[0].Luid) == FALSE)
1118{
1119fprintf(stderr, "LookupPrivilegeValue failed: 0x%X\n", GetLastError());
1120return(-1);
1121}
1122if(OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token) == FALSE)
1123{
1124fprintf(stderr, "OpenProcessToken SELF Failed: 0x%X\n", GetLastError());
1125return(-1);
1126}
1127tkp.PrivilegeCount = 1;
1128tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1129if(!AdjustTokenPrivileges(token,FALSE,&tkp,0,NULL, NULL))
1130{
1131fprintf(stderr,"AdjustTokenPrivileges Failed: 0x%X\n", GetLastError());
1132return(-1);
1133}
1134/*
1135else
1136{
1137switch(GetLastError())
1138{
1139case ERROR_SUCCESS:
1140printf("The function adjusted all specified privileges.\n");
1141break;
1142case ERROR_NOT_ALL_ASSIGNED: //0x514
1143printf("Adjust privileges not assigned\n");
1144break;
1145}
1146}
1147*/
1148CloseHandle(token);
1149return 0;
1150}
1151
1152//从 lsass.exe 继承权限
1153int GrantPrivFromLsass(int pid)
1154{
1155HANDLE LsassHandle,LsassToken,NewToken;
1156
1157//首先打开进程,获得HANDLE
1158//PROCESS_QUERY_INFORMATION ,FALSE
1159//LsassHandle = OpenProcess(PROCESS_ALL_ACCESS,TRUE,pid);
1160LsassHandle = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,pid);
1161//在OpenProcessToken(READ|WRITE
1162if(LsassHandle == NULL)
1163{
1164printf("OpenProcess %d Error:%d\n",pid,GetLastError());
1165return -1;
1166}
1167//再opentoken
1168if(!OpenProcessToken(LsassHandle,STANDARD_RIGHTS_READ|WRITE_DAC,&LsassToken))
1169{
1170printf("OpenProcessToken First Error:%d\n",GetLastError());
1171CloseHandle(LsassHandle);
1172return -1;
1173}
1174//得到Token的ACL信息
1175//pSecurityDescriptor = NULL;
1176//size = 0;
1177//len = 0;
1178//先申请内存
1179if(!AddUserPrivToHandle(LsassToken,"administrators",TOKEN_ALL_ACCESS))
1180{
1181CloseHandle(LsassToken);
1182CloseHandle(LsassHandle);
1183return -1;
1184}
1185//关闭句柄
1186CloseHandle(LsassToken);
1187
1188//打开Token
1189if(!OpenProcessToken(LsassHandle,TOKEN_ALL_ACCESS,&LsassToken))
1190{
1191printf("OpenProcessToken LsassHandle Error:%d\n",GetLastError());
1192CloseHandle(LsassHandle);
1193return -1;
1194}
1195//关闭句柄
1196CloseHandle(LsassHandle);
1197//复制Token
1198if(!DuplicateTokenEx(LsassToken,TOKEN_ALL_ACCESS,NULL,SecurityImpersonation,TokenPrimary,&NewToken))
1199{
1200printf("DuplicateTokenEx Error:%d\n",GetLastError());
1201return -1;
1202}
1203//CloseHandle(LsassToken);
1204if(!ImpersonateLoggedOnUser(NewToken))
1205{
1206printf("ImpersonateLoggedOnUser Error:%d\n",GetLastError());
1207CloseHandle(NewToken);
1208return -1;
1209}
1210GrantPriv("SeCreateTokenPrivilege");
1211GrantPriv("SeTcbPrivilege");
1212GrantPriv("SeIncreaseQuotaPrivilege");
1213GrantPriv("SeAssignPrimaryTokenPrivilege");
1214//CloseHandle(NewToken);
1215return 0;
1216// GetKernelObjectSecurity(Handle,DACL_SECURITY_INFORMATION,buf,size,&len)
1217// GetSecurityDescriptorDacl(buf,&lpbDaclPresent,PoldACL,&lpbDaclDefaulted);
1218// BuildExplicitAccessWithName(pstruct,"administrators",TOKEN_ALL_ACCESS,GRANT_ACCESS,NO_INHERITANCE)
1219// SetEntriesInAcl(1,pstruct,PoldACL,PnewACL); //合并权限
1220// MakeAbsoluteSD(buf,buf2,
1221// SetSecurityDescriptorDacl(buf2,lpbDaclPresent,PnewACL,lpbDaclDefaulted);
1222// SetKernelObjectSecurity(HANDLE,DACL_SECURITY_INFORMATION,buf2,);
1223// CloseHandle(HANDLE);
1224// DuplicateTokenEx(LsassToken,TOKEN_ALL_ACCESS,NULL,SecurityImpersonation,TokenPrimary,&NewToken);
1225// CloseHandle(LsassToken);
1226// ImpersonateLoggedOnUser
1227}
1228//帮助信息
1229void usage(char *s)
1230{
1231printf("Usage:%s <-u user>\n",s);
1232return;
1233}
1234
1235BOOL ConvertSidToStringSid(PSID pSid,LPTSTR TextualSid, LPDWORD lpdwBufferLen)
1236{
1237PSID_IDENTIFIER_AUTHORITY psia;
1238DWORD dwSubAuthorities;
1239DWORD dwSidRev=SID_REVISION;
1240DWORD dwCounter;
1241DWORD dwSidSize;
1242
1243// Validate the binary SID.
1244if(!IsValidSid(pSid)) return FALSE;
1245// Get the identifier authority value from the SID.
1246psia = GetSidIdentifierAuthority(pSid);
1247// Get the number of subauthorities in the SID.
1248dwSubAuthorities = *GetSidSubAuthorityCount(pSid);
1249// Compute the buffer length.
1250// S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL
1251dwSidSize=(15 + 12 + (12 * dwSubAuthorities) + 1) * sizeof(TCHAR);
1252// Check input buffer length.
1253// If too small, indicate the proper size and set last error.
1254if (*lpdwBufferLen < dwSidSize)
1255{
1256*lpdwBufferLen = dwSidSize;
1257SetLastError(ERROR_INSUFFICIENT_BUFFER);
1258return FALSE;
1259}
1260
1261// Add 'S' prefix and revision number to the string.
1262dwSidSize=wsprintf(TextualSid, TEXT("S-%lu-"), dwSidRev );
1263// Add SID identifier authority to the string.
1264if ( (psia->Value[0] != 0) || (psia->Value[1] != 0) )
1265{
1266dwSidSize+=wsprintf(TextualSid + lstrlen(TextualSid),TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"),
1267(USHORT)psia->Value[0],
1268(USHORT)psia->Value[1],
1269(USHORT)psia->Value[2],
1270(USHORT)psia->Value[3],
1271(USHORT)psia->Value[4],
1272(USHORT)psia->Value[5]);
1273}
1274else
1275{
1276dwSidSize+=wsprintf(TextualSid + lstrlen(TextualSid),TEXT("%lu"),
1277(ULONG)(psia->Value[5] ) +
1278(ULONG)(psia->Value[4] << 8) +
1279(ULONG)(psia->Value[3] << 16) +
1280(ULONG)(psia->Value[2] << 24) );
1281}
1282
1283// Add SID subauthorities to the string.
1284for (dwCounter=0 ; dwCounter < dwSubAuthorities ; dwCounter++)
1285{
1286dwSidSize+=wsprintf(TextualSid + dwSidSize, TEXT("-%lu"),
1287*GetSidSubAuthority(pSid, dwCounter) );
1288}
1289return TRUE;
1290}
1291
1292void *GetFromToken(HANDLE hToken, TOKEN_INFORMATION_CLASS tic)
1293{
1294DWORD n,n2,rv;
1295void *p;
1296
1297n2 = 0;
1298rv = GetTokenInformation(hToken,tic,NULL,n2, &n);
1299if (rv == FALSE && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1300{
1301printf("GetTokenInformation Failed:%d\n",GetLastError());
1302return NULL;
1303}
1304
1305p = malloc(n+1);
1306if(p == NULL)
1307{
1308printf("Malloc in GetFromToken Failed\n");
1309return NULL;
1310}
1311n2 = n;
1312if(!GetTokenInformation(hToken, tic, p, n2, &n) )
1313{
1314printf("GetTokenInformation After Malloc Failed:%d\n",GetLastError());
1315return NULL;
1316}
1317return p;
1318}
1319
1320void pfree(void *p)
1321{
1322if(p)
1323free(p);
1324}
1325
1326LUID GetLuidFromText(char *s)
1327{
1328LUID Luid;
1329
1330Luid.LowPart = 0;
1331Luid.HighPart = 0;
1332if(!LookupPrivilegeValue(NULL,s,&Luid))
1333{
1334printf("LookupPrivilegeValue under GetLuidFromText(\"%s\") Failed:%d\n",s,GetLastError());
1335return Luid;
1336}
1337return Luid;
1338}
1339