-
Notifications
You must be signed in to change notification settings - Fork 1
/
userapi.cs
90 lines (79 loc) · 3.16 KB
/
userapi.cs
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
using System;
using System.DirectoryServices.AccountManagement;
namespace SharpRIDHijack
{
public class userapi
{
public static void Enable(string username, bool setpassword=false, string password=null)
{
try
{
using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
{
// Find the user by username
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
if (user != null)
{
// Check if the user account is disabled
if (user.Enabled == false)
{
// Enable the user account
user.Enabled = true;
if (setpassword == true) { user.SetPassword(password); }
user.Save();
Console.WriteLine("[+] Enabled user account : '{0}' !", username);
if (setpassword == true) { Console.WriteLine("[+] Changed the user password"); }
}
else
{
Console.WriteLine("[i] User account '{0}' is already enabled.", username);
}
}
else
{
Console.WriteLine("User account '{0}' not found.", username);
}
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
return;
}
}
public static bool UserExists(PrincipalContext context, string username)
{
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
return (user != null);
}
public static void Create(string username, string password)
{
try
{
using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
{
// Check if the user already exists
if (!UserExists(context, username))
{
// Create the new user
UserPrincipal newUser = new UserPrincipal(context);
newUser.SamAccountName = username;
newUser.SetPassword(password);
newUser.Enabled = true;
newUser.Save();
Console.WriteLine($"[+] Created User {username}.");
}
else
{
Console.WriteLine("User already exists.");
return;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error creating user: " + ex.Message);
}
}
}
}