-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkAdminUser.ps1
347 lines (298 loc) · 11.9 KB
/
checkAdminUser.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# Author(s) : Paul Mizel
# Company : BROCKHAUS AG
# Year : 2017
# Source : https://github.com/BROCKHAUS-AG/SystemCheck
function BagCheckAdminUser{
param($username=$env:username,
[string]$Text="",
[bool]$Debug=$false,
[bool]$Fix=$false)
if(-NOT $Debug) { $ErrorActionPreference = "Stop" }
Try{
#([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
$_currentUser=([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent())
If (-NOT $_currentUser.IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator"))
{
write-host "ERROR: (" $_currentUser.Identity.Name ") You do not have Administrator rights. " $Text -ForegroundColor Red
If($Fix)
{
Add-LocalUserToGroup
Add-LocalUserToGroup -group RemoteDesktopBenutzer
}
}
Else
{
write-host "OK (" $_currentUser ")" -ForegroundColor Green
}
}
Catch
{
if(-NOT $Debug)
{
write-host "Ex:F:AdminUser, M:" $_.Exception.Message ")" -ForegroundColor Red
}
}
}
function Add-LocalUserToGroup {
Param(
[bool]$Debug=$false,
$computer=$env:computername,
$group='Administratoren',
$userdomain=$env:userdomain,
$username=$env:username
)
if(-NOT $Debug) { $ErrorActionPreference = "Stop" }
Try
{
([ADSI]"WinNT://$computer/$group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
write-host "FIX: (" $_currentUser.Identity.Name ") Add to " $group " Group" -ForegroundColor Yellow
}
Catch
{
if(-NOT $Debug)
{
write-host "Ex:F:AdminUser, M:" $_.Exception.Message ")" -ForegroundColor Red
}
}
}
function Add-DomainUserToGroup
{
[cmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$computer,
[Parameter(Mandatory=$False)]
[string]$domain,
[Parameter(Mandatory=$True)]
[string]$group,
[Parameter(Mandatory=$True)]
[string]$user
)
if([string]::IsNullOrEmpty($computer))
{
$computer = [System.Net.Dns]::GetHostByName(($env:computerName)).HostName;
}
if([string]::IsNullOrEmpty($domain))
{
$domain = (Get-WmiObject win32_computersystem).Domain;
}
$de = [ADSI]"WinNT://$computer/$group,group"
$adUser = [ADSI]"WinNT://$domain/$user"
$path = ([ADSI]"WinNT://$domain/$user").path
$de.psbase.Invoke("Add", $path)
write-host "FIX: (" $adUser.Name " added to group " $de.Name ")" -ForegroundColor Yellow
}
function Add-UserToLoginAsBatch ($user) {
<#
.SYNOPSIS
When run administratively this will add a user to the local system's login as batch job rights security policy.
.DESCRIPTION
When run administratively this will add a user to the local system's login as batch job rights security policy.
.PARAMETER User
User to add to the local system's login as batch job rights security policy.
.EXAMPLE
Add-UserToLoginAsBatch 'user'
Description
-----------
Adds the local user test.user to the login as batch job rights on the local machine.
#>
$CSharpCode = @'
using System;
// using System.Globalization;
using System.Text;
using System.Runtime.InteropServices;
public class LsaWrapper
{
// Import the LSA functions
[DllImport("advapi32.dll", PreserveSig = true)]
private static extern UInt32 LsaOpenPolicy(
ref LSA_UNICODE_STRING SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
Int32 DesiredAccess,
out IntPtr PolicyHandle
);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern long LsaAddAccountRights(
IntPtr PolicyHandle,
IntPtr AccountSid,
LSA_UNICODE_STRING[] UserRights,
long CountOfRights);
[DllImport("advapi32")]
public static extern void FreeSid(IntPtr pSid);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, PreserveSig = true)]
private static extern bool LookupAccountName(
string lpSystemName, string lpAccountName,
IntPtr psid,
ref int cbsid,
StringBuilder domainName, ref int cbdomainLength, ref int use);
[DllImport("advapi32.dll")]
private static extern bool IsValidSid(IntPtr pSid);
[DllImport("advapi32.dll")]
private static extern long LsaClose(IntPtr ObjectHandle);
[DllImport("kernel32.dll")]
private static extern int GetLastError();
[DllImport("advapi32.dll")]
private static extern long LsaNtStatusToWinError(long status);
// define the structures
private enum LSA_AccessPolicy : long
{
POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
POLICY_TRUST_ADMIN = 0x00000008L,
POLICY_CREATE_ACCOUNT = 0x00000010L,
POLICY_CREATE_SECRET = 0x00000020L,
POLICY_CREATE_PRIVILEGE = 0x00000040L,
POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
POLICY_SERVER_ADMIN = 0x00000400L,
POLICY_LOOKUP_NAMES = 0x00000800L,
POLICY_NOTIFICATION = 0x00001000L
}
[StructLayout(LayoutKind.Sequential)]
private struct LSA_OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public readonly LSA_UNICODE_STRING ObjectName;
public UInt32 Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr Buffer;
}
///
//Adds a privilege to an account
/// Name of an account - "domain\account" or only "account"
/// Name ofthe privilege
/// The windows error code returned by LsaAddAccountRights
public long SetRight(String accountName, String privilegeName)
{
long winErrorCode = 0; //contains the last error
//pointer an size for the SID
IntPtr sid = IntPtr.Zero;
int sidSize = 0;
//StringBuilder and size for the domain name
var domainName = new StringBuilder();
int nameSize = 0;
//account-type variable for lookup
int accountType = 0;
//get required buffer size
LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);
//allocate buffers
domainName = new StringBuilder(nameSize);
sid = Marshal.AllocHGlobal(sidSize);
//lookup the SID for the account
bool result = LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize,
ref accountType);
//say what you're doing
//Console.WriteLine("LookupAccountName result = " + result);
//Console.WriteLine("IsValidSid: " + IsValidSid(sid));
//Console.WriteLine("LookupAccountName domainName: " + domainName);
if (!result)
{
winErrorCode = GetLastError();
Console.WriteLine("LookupAccountName failed: " + winErrorCode);
}
else
{
//initialize an empty unicode-string
var systemName = new LSA_UNICODE_STRING();
//combine all policies
var access = (int) (
LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
LSA_AccessPolicy.POLICY_CREATE_SECRET |
LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
LSA_AccessPolicy.POLICY_NOTIFICATION |
LSA_AccessPolicy.POLICY_SERVER_ADMIN |
LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
LSA_AccessPolicy.POLICY_TRUST_ADMIN |
LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
);
//initialize a pointer for the policy handle
IntPtr policyHandle = IntPtr.Zero;
//these attributes are not used, but LsaOpenPolicy wants them to exists
var ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
ObjectAttributes.Length = 0;
ObjectAttributes.RootDirectory = IntPtr.Zero;
ObjectAttributes.Attributes = 0;
ObjectAttributes.SecurityDescriptor = IntPtr.Zero;
ObjectAttributes.SecurityQualityOfService = IntPtr.Zero;
//get a policy handle
uint resultPolicy = LsaOpenPolicy(ref systemName, ref ObjectAttributes, access, out policyHandle);
winErrorCode = LsaNtStatusToWinError(resultPolicy);
if (winErrorCode != 0)
{
Console.WriteLine("OpenPolicy failed: " + winErrorCode);
}
else
{
//Now that we have the SID an the policy,
//we can add rights to the account.
//initialize an unicode-string for the privilege name
var userRights = new LSA_UNICODE_STRING[1];
userRights[0] = new LSA_UNICODE_STRING();
userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName);
userRights[0].Length = (UInt16) (privilegeName.Length*UnicodeEncoding.CharSize);
userRights[0].MaximumLength = (UInt16) ((privilegeName.Length + 1)*UnicodeEncoding.CharSize);
//add the right to the account
long res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
winErrorCode = LsaNtStatusToWinError(res);
if (winErrorCode != 0)
{
Console.WriteLine("LsaAddAccountRights failed: " + winErrorCode);
}
LsaClose(policyHandle);
}
FreeSid(sid);
}
return winErrorCode;
}
}
public class AddUserToLoginAsBatch
{
public static bool GrantUserLogonAsBatchJob(string userName)
{
var result=false;
try
{
LsaWrapper lsaUtility = new LsaWrapper();
lsaUtility.SetRight(userName, "SeBatchLogonRight");
//Console.WriteLine("Logon as batch job right is granted successfully to " + userName);
result = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
}
'@
try {
Add-Type -ErrorAction Stop -Language:CSharpVersion3 -TypeDefinition $CSharpCode
}
catch {
Write-Error $_.Exception.Message
break
}
If([AddUserToLoginAsBatch]::GrantUserLogonAsBatchJob($user))
{
write-host "OK Logon as batch job right (" $user ")" -ForegroundColor Green
}
Else
{
write-host "NOK Logon as batch job right (" $user ")" -ForegroundColor Red
}
}