-
Notifications
You must be signed in to change notification settings - Fork 2
/
users.cc
452 lines (362 loc) · 12.2 KB
/
users.cc
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Code made with reference to https://github.com/mmraff/windows-users
#include <napi.h>
#include <Windows.h>
#include <lm.h> // USER_INFO_xx and various #defines
#include <Sddl.h> // ConvertSidToStringSid
#include <userenv.h> // CreateProfile
#include <codecvt>
#include <vector>
#pragma comment(lib, "netapi32.lib")
#pragma comment(lib, "userenv.lib")
using namespace Napi;
std::wstring to_wstring(Value value) {
size_t length;
napi_status status = napi_get_value_string_utf16(
value.Env(),
value,
nullptr,
0,
&length);
NAPI_THROW_IF_FAILED_VOID(value.Env(), status);
std::wstring result;
result.reserve(length + 1);
result.resize(length);
status = napi_get_value_string_utf16(
value.Env(),
value,
reinterpret_cast<char16_t*>(result.data()),
result.capacity(),
nullptr);
NAPI_THROW_IF_FAILED_VOID(value.Env(), status);
return result;
}
Value to_value(Env env, std::wstring_view str) {
return String::New(
env,
reinterpret_cast<const char16_t*>(str.data()),
str.size());
}
// like unique_ptr, but takes a deleter value, not type.
template <typename T, auto Deleter>
struct Ptr {
T* value = NULL;
Ptr() = default;
// No copies
Ptr(const Ptr&) = delete;
Ptr& operator=(const Ptr&) = delete;
// Moves
Ptr(Ptr&& other) : value{ other.release() } {}
Ptr& operator=(Ptr&& other) {
assign(other.release());
}
~Ptr() { clear(); }
operator T*() const { return value; }
T* operator ->() const { return value; }
T* assign(T* newValue) {
clear();
return value = newValue;
}
T* release() {
auto result = value;
value = nullptr;
return result;
}
void clear() {
if (value) {
Deleter(value);
value = nullptr;
}
}
};
template <typename T>
using Win32Local = Ptr<T, LocalFree>;
std::wstring formatSystemError(HRESULT hr) {
Win32Local<WCHAR> message_ptr;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
hr,
LANG_USER_DEFAULT,
(LPWSTR)&message_ptr,
0,
nullptr);
if (!message_ptr) {
return L"Unknown Error";
}
std::wstring message(message_ptr);
// Windows ends it's system messages with "\r\n", which is bad formatting for us.
if (auto last_not_newline = message.find_last_not_of(L"\r\n");
last_not_newline != std::wstring::npos) {
message.erase(last_not_newline + 1);
}
return message;
}
Error createWindowsError(napi_env env, HRESULT hr, const char* syscall) {
napi_value error_value = nullptr;
napi_status status = napi_create_error(
env,
nullptr,
to_value(env, formatSystemError(hr)),
&error_value);
if (status != napi_ok) {
throw Error::New(env);
}
auto error = Error(env, error_value);
error.Value().DefineProperties({
PropertyDescriptor::Value("errno", Number::New(env, hr)),
PropertyDescriptor::Value("name", String::New(env, "WindowsError")),
PropertyDescriptor::Value("syscall", String::New(env, syscall)),
});
return error;
}
template <typename USER_INFO_level, int level>
struct NetUserInfo : Ptr<USER_INFO_level, NetApiBufferFree> {
bool get(Env env, LPCWSTR username) {
return get(env, nullptr, username);
}
bool get(Env env, LPCWSTR servername, LPCWSTR username) {
clear();
auto nerr = NetUserGetInfo(servername, username, level, reinterpret_cast<LPBYTE*>(&value));
if (nerr == NERR_UserNotFound) {
return false;
}
if (nerr != NERR_Success) {
throw createWindowsError(env, GetLastError(), "NetUserGetInfo");
}
return true;
}
};
#define NET_USER_INFO(level) NetUserInfo<USER_INFO_ ## level, level>
Win32Local<WCHAR> sid_to_local_string(Env env, PSID sid) {
Ptr<WCHAR, LocalFree> local;
if (!ConvertSidToStringSidW(sid, &local.value)) {
throw createWindowsError(env, GetLastError(), "ConvertSidToStringSidW");
}
return local;
}
Value sid_to_value(Env env, PSID sid) {
auto local = sid_to_local_string(env, sid);
return to_value(env, local.value);
}
Value get(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
NET_USER_INFO(23) user_info;
if (!user_info.get(env, name.c_str())) {
return env.Null();
}
auto res = Object::New(env);
res.DefineProperties({
PropertyDescriptor::Value("name", to_value(env, user_info->usri23_name), napi_enumerable),
PropertyDescriptor::Value("full_name", to_value(env, user_info->usri23_full_name), napi_enumerable),
PropertyDescriptor::Value("comment", to_value(env, user_info->usri23_comment), napi_enumerable),
PropertyDescriptor::Value("flags", Number::New(env, user_info->usri23_flags), napi_enumerable),
PropertyDescriptor::Value("sid", sid_to_value(env, user_info->usri23_user_sid), napi_enumerable),
});
return res;
}
Value add(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
auto password = to_wstring(info[1]);
auto flags = info[2].As<Number>().Uint32Value();
USER_INFO_1 user = {};
// The strings are not const, so using .data() instead of .c_str().
// If this surprises you, basic_string::data() was made non-const in C++17.
user.usri1_name = name.data();
user.usri1_password = password.data();
user.usri1_priv = USER_PRIV_USER;
user.usri1_flags = flags;
auto nerr = NetUserAdd(
NULL, // servername
1, // level (X in USER_INFO_X)
(LPBYTE) &user,
NULL); // parm_err
if (nerr == NERR_Success) {
return Boolean::New(env, true);
} else if (nerr == NERR_UserExists) {
return Boolean::New(env, false);
} else {
throw createWindowsError(env, nerr, "NetUserAdd");
}
}
Value del(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
auto nerr = NetUserDel(
NULL, // servername
name.c_str());
if (nerr == NERR_Success) {
return Boolean::New(env, true);
} else if (nerr == NERR_UserNotFound) {
return Boolean::New(env, false);
} else {
throw createWindowsError(env, nerr, "NetUserAdd");
}
}
Value createProfile(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
NET_USER_INFO(23) user_info;
if (!user_info.get(env, name.c_str())) {
// User does not exist
return Boolean::New(env, false);
}
auto sid_local = sid_to_local_string(env, user_info->usri23_user_sid);
WCHAR profile_path[MAX_PATH];
auto hr = CreateProfile(sid_local, name.c_str(), profile_path, MAX_PATH);
if (SUCCEEDED(hr)) {
return to_value(env, profile_path);
} else if (hr == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS)) {
return env.Null();
} else {
throw createWindowsError(env, hr, "CreateProfile");
}
}
Value deleteProfile(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
NET_USER_INFO(23) user_info;
if (!user_info.get(env, name.c_str())) {
// User does not exist
return Boolean::New(env, false);
}
auto sid_local = sid_to_local_string(env, user_info->usri23_user_sid);
if (!DeleteProfileW(sid_local.value, NULL, NULL)) {
auto error = GetLastError();
if (error == ERROR_FILE_NOT_FOUND) {
return Boolean::New(env, false);
} else {
throw createWindowsError(env, error, "DeleteProfileW");
}
} else {
return Boolean::New(env, true);
}
}
void changePassword(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
auto oldPassword = to_wstring(info[1]);
auto newPassword = to_wstring(info[2]);
auto nerr = NetUserChangePassword(
NULL, // servername,
name.c_str(),
oldPassword.c_str(),
newPassword.c_str());
if (nerr != NERR_Success) {
throw createWindowsError(env, nerr, "NetUserChangePassword");
}
}
#define NET_USER_SET_INFO(level, name, ...) { \
USER_INFO_##level user_info { __VA_ARGS__ }; \
auto nerr = NetUserSetInfo( \
nullptr, \
name, \
level, \
(LPBYTE) &info, \
nullptr); \
if (nerr != NERR_Success) { \
throw createWindowsError(env, nerr, "NetUserSetInfo"); \
} \
}
void set(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
auto options = info[1].As<Object>();
if (auto value = options.Get("full_name");
!value.IsEmpty() && !value.IsUndefined()) {
auto full_name = to_wstring(value);
NET_USER_SET_INFO(1011, name.c_str(), full_name.data());
}
if (auto value = options.Get("flags");
!value.IsEmpty() && !value.IsUndefined()) {
auto flags = value.As<Number>().Uint32Value();
NET_USER_SET_INFO(1008, name.c_str(), flags);
}
}
Value logonUser(CallbackInfo const& info) {
auto env = info.Env();
auto name = to_wstring(info[0]);
auto domain = to_wstring(info[1]);
auto password = to_wstring(info[2]);
auto type = info[3].As<Number>().Uint32Value();
auto provider = info[4].As<Number>().Uint32Value();
HANDLE token;
auto ok = LogonUserW(
name.c_str(),
domain.c_str(),
password.c_str(),
type,
provider,
&token);
if (!ok) {
throw createWindowsError(env, GetLastError(), "LogonUserW");
}
return External<void>::New(env, token, [](Env env, HANDLE handle) {
CloseHandle(handle);
});
}
HANDLE get_handle(Env env, Value value) {
if (!value.IsExternal()) {
throw TypeError::New(env, "'handle' should be an External returned from logonUser()");
}
return value.As<External<void>>().Data();
}
void closeHandle(CallbackInfo const& info) {
auto env = info.Env();
auto handle = get_handle(env, info[0]);
if (!CloseHandle(handle)) {
throw createWindowsError(env, GetLastError(), "CloseHandle");
}
}
void impersonateLoggedOnUser(CallbackInfo const& info) {
auto env = info.Env();
auto handle = get_handle(env, info[0]);
if (!ImpersonateLoggedOnUser(handle)) {
throw createWindowsError(env, GetLastError(), "ImpersonateLoggedOnUser");
}
}
void revertToSelf(CallbackInfo const& info) {
auto env = info.Env();
if (!RevertToSelf()) {
throw createWindowsError(env, GetLastError(), "RevertToSelf");
}
}
Value getUserProfileDirectory(CallbackInfo const& info) {
auto env = info.Env();
auto handle = get_handle(env, info[0]);
DWORD size = 0;
GetUserProfileDirectoryW(handle, NULL, &size);
if (!size) {
throw createWindowsError(env, GetLastError(), "GetUserProfileDirectoryW");
}
std::wstring data;
data.reserve(size + 1);
data.resize(size);
if (!GetUserProfileDirectoryW(handle, data.data(), &size)) {
throw createWindowsError(env, GetLastError(), "GetUserProfileDirectoryW");
}
return to_value(env, data);
}
#define EXPORT_FUNCTION(name) \
PropertyDescriptor::Function(env, exports, #name, name, napi_enumerable)
Object module_init(Env env, Object exports) {
exports.DefineProperties({
EXPORT_FUNCTION(get),
EXPORT_FUNCTION(add),
EXPORT_FUNCTION(del),
EXPORT_FUNCTION(createProfile),
EXPORT_FUNCTION(deleteProfile),
EXPORT_FUNCTION(changePassword),
EXPORT_FUNCTION(set),
EXPORT_FUNCTION(logonUser),
EXPORT_FUNCTION(closeHandle),
EXPORT_FUNCTION(impersonateLoggedOnUser),
EXPORT_FUNCTION(revertToSelf),
EXPORT_FUNCTION(getUserProfileDirectory),
});
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, module_init);