-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockService.c
More file actions
executable file
·2021 lines (1734 loc) · 77.8 KB
/
LockService.c
File metadata and controls
executable file
·2021 lines (1734 loc) · 77.8 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// lockservice_nowindow.c
// Compile with: x86_64-w64-mingw32-gcc -O2 -Wall -o LockService.exe lockservice_nowindow.c -lws2_32 -ladvapi32 -lwtsapi32 -luserenv -s
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <wtsapi32.h>
#include <userenv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <shlobj.h>
#include <tlhelp32.h>
#include <initguid.h>
#include <objbase.h>
#define SERVICE_NAME "LockService"
#define SERVICE_DISPLAY_NAME_W L"Lock Screen Service"
#define HTTP_PORT 8888
#define HELP_FLAG "--helper"
#define KEYBOARD_HOOK_FLAG "--keyboard-hook"
// Timeout constants (in milliseconds)
#define SESSION_POLL_INTERVAL_MS 10000
#define THREAD_SHUTDOWN_TIMEOUT_MS 5000
#define HTTP_SELECT_TIMEOUT_MS 100
// Virtual key code for 'L' key
#define VK_KEY_L 0x4C
// Resource IDs
#define IDI_APP_ICON 100
#define IDR_HTML_UI 200
#define IDR_WEBVIEW2_DLL 201
#define ID_TIMER_WEBVIEW_SHOW_FALLBACK 202
#define WEBVIEW_SHOW_FALLBACK_DELAY_MS 350
// Registry settings
#define REG_KEY_PATH "SOFTWARE\\JPIT\\LockService"
#define REG_VALUE_BIND_IP "BindIP"
#define REG_VALUE_BIND_PORT "BindPort"
#define REG_VALUE_ENABLE_HTTP "EnableHTTP"
#define REG_VALUE_ENABLE_MONOFF "EnableMonitorOff"
// Settings globals
static char g_bindIP[64] = "0.0.0.0";
static DWORD g_bindPort = 8888;
static DWORD g_enableHTTP = 1;
static DWORD g_enableMonitorOff = 1;
// Forward declaration
static void load_settings(void);
// Global service status handle
static SERVICE_STATUS g_ServiceStatus;
static SERVICE_STATUS_HANDLE g_StatusHandle;
static HANDLE g_ServiceStopEvent = NULL;
// Keyboard hook globals
static HHOOK g_hKeyboardHook = NULL;
static BOOL g_bWinKeyPressed = FALSE;
// Session monitoring globals
#define MAX_TRACKED_SESSIONS 32
typedef struct {
DWORD sessionId;
HANDLE hProcess;
} HELPER_PROC;
#define HELPER_HANDLE_LAUNCHING ((HANDLE)(LONG_PTR)-1)
static HELPER_PROC g_HelperProcs[MAX_TRACKED_SESSIONS];
static DWORD g_HelperProcCount = 0;
static CRITICAL_SECTION g_SessionLock;
// Single-instance mutex for keyboard hook helper
static HANDLE g_hSingleInstanceMutex = NULL;
static BOOL ensure_single_keyboard_helper_instance(void) {
DWORD sid = 0;
char name[128];
if (!ProcessIdToSessionId(GetCurrentProcessId(), &sid))
sid = 0;
snprintf(name, sizeof(name), "Local\\LockServiceKbHelper-%lu", sid);
g_hSingleInstanceMutex = CreateMutexA(NULL, TRUE, name);
if (!g_hSingleInstanceMutex)
return TRUE;
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(g_hSingleInstanceMutex);
g_hSingleInstanceMutex = NULL;
return FALSE;
}
return TRUE;
}
// Event logging
static HANDLE g_hEventLog = NULL;
// Log to Windows Event Viewer
static void log_event(WORD type, const char* message) {
if (!g_hEventLog) return;
const char* strings[1] = { message };
ReportEventA(g_hEventLog, type, 0, 0, NULL, 1, 0, strings, NULL);
}
// Log error with formatted message
static void log_error(const char* format, ...) {
char buffer[512];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
log_event(EVENTLOG_ERROR_TYPE, buffer);
fprintf(stderr, "ERROR: %s\n", buffer);
}
// Log info message
static void log_info(const char* format, ...) {
char buffer[512];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
log_event(EVENTLOG_INFORMATION_TYPE, buffer);
printf("INFO: %s\n", buffer);
}
// Window procedure for RawInput processing
static LRESULT CALLBACK raw_input_wnd_proc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
if (msg == WM_INPUT) {
RAWINPUT raw;
UINT size = sizeof(raw);
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, &raw, &size, sizeof(RAWINPUTHEADER)) != (UINT)-1) {
if (raw.header.dwType == RIM_TYPEKEYBOARD) {
USHORT vkey = raw.data.keyboard.VKey;
USHORT flags = raw.data.keyboard.Flags;
BOOL isKeyDown = !(flags & RI_KEY_BREAK);
// Track Win key state
if (vkey == VK_LWIN || vkey == VK_RWIN) {
g_bWinKeyPressed = isKeyDown;
}
// Detect L key press
if (vkey == VK_KEY_L && isKeyDown && g_bWinKeyPressed) {
// Double-check Win key is pressed
SHORT winLeftState = GetAsyncKeyState(VK_LWIN);
SHORT winRightState = GetAsyncKeyState(VK_RWIN);
BOOL winCurrentlyPressed = (winLeftState & 0x8000) || (winRightState & 0x8000);
if (winCurrentlyPressed) {
// Check no other modifiers
SHORT ctrlState = GetAsyncKeyState(VK_CONTROL);
SHORT altState = GetAsyncKeyState(VK_MENU);
SHORT shiftState = GetAsyncKeyState(VK_SHIFT);
if (!(ctrlState & 0x8000) && !(altState & 0x8000) && !(shiftState & 0x8000)) {
char username[256] = {0};
DWORD usernameLen = sizeof(username);
if (GetUserNameA(username, &usernameLen)) {
log_info("Detected WIN+L press from %s", username);
} else {
log_info("Detected WIN+L press");
}
if (g_enableMonitorOff) {
Sleep(500);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
}
}
}
}
}
}
} else if (msg == WM_HOTKEY && wParam == 1) {
// Hotkey backup
char username[256] = {0};
DWORD usernameLen = sizeof(username);
if (GetUserNameA(username, &usernameLen)) {
log_info("Detected WIN+L press from %s", username);
} else {
log_info("Detected WIN+L press");
}
if (g_enableMonitorOff) {
Sleep(500);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
}
}
return DefWindowProcA(hwnd, msg, wParam, lParam);
}
// Keyboard hook callback (kept as secondary backup)
static LRESULT CALLBACK keyboard_hook_proc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
KBDLLHOOKSTRUCT* pKbd = (KBDLLHOOKSTRUCT*)lParam;
BOOL isKeyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);
BOOL isKeyUp = (wParam == WM_KEYUP || wParam == WM_SYSKEYUP);
// Track Win key state
if (pKbd->vkCode == VK_LWIN || pKbd->vkCode == VK_RWIN) {
if (isKeyDown) {
g_bWinKeyPressed = TRUE;
} else if (isKeyUp) {
g_bWinKeyPressed = FALSE;
}
}
// Detect L key press (VK_KEY_L)
if (pKbd->vkCode == VK_KEY_L && isKeyDown) {
// First verify Win key is CURRENTLY pressed using GetAsyncKeyState
SHORT winLeftState = GetAsyncKeyState(VK_LWIN);
SHORT winRightState = GetAsyncKeyState(VK_RWIN);
BOOL winCurrentlyPressed = (winLeftState & 0x8000) || (winRightState & 0x8000);
// Only proceed if Win key is actually pressed right now AND our flag agrees
if (g_bWinKeyPressed && winCurrentlyPressed) {
// Check that ONLY Win key is pressed (no other modifiers)
SHORT ctrlState = GetAsyncKeyState(VK_CONTROL);
SHORT altState = GetAsyncKeyState(VK_MENU);
SHORT shiftState = GetAsyncKeyState(VK_SHIFT);
// Only trigger if no other modifiers are pressed
if (!(ctrlState & 0x8000) && !(altState & 0x8000) && !(shiftState & 0x8000)) {
// Win+L detected! Get username and log it
char username[256] = {0};
DWORD usernameLen = sizeof(username);
if (GetUserNameA(username, &usernameLen)) {
log_info("Detected WIN+L press from %s", username);
} else {
log_info("Detected WIN+L press");
}
// Turn off monitors using SendMessage for reliability
if (g_enableMonitorOff) {
Sleep(500);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
}
}
}
}
}
return CallNextHookEx(g_hKeyboardHook, nCode, wParam, lParam);
}
// Keyboard hook helper process entry point
static void run_keyboard_hook_helper(void) {
if (!ensure_single_keyboard_helper_instance())
exit(0);
load_settings();
MSG msg;
HWND hwnd = NULL;
// Open event log for this helper process
g_hEventLog = RegisterEventSourceA(NULL, SERVICE_NAME);
// Create a hidden window with custom window procedure for RawInput
WNDCLASSA wc = {0};
wc.lpfnWndProc = raw_input_wnd_proc;
wc.lpszClassName = "LockServiceHotkeyWindow";
wc.hInstance = GetModuleHandle(NULL);
if (!RegisterClassA(&wc)) {
DWORD dwError = GetLastError();
// If class already exists (from crashed helper), that's okay - reuse it
if (dwError != ERROR_CLASS_ALREADY_EXISTS) {
if (g_hEventLog) {
log_error("RegisterClass failed: %lu", dwError);
DeregisterEventSource(g_hEventLog);
}
exit(1);
}
}
hwnd = CreateWindowA(wc.lpszClassName, "", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, wc.hInstance, NULL);
if (!hwnd) {
if (g_hEventLog) {
log_error("CreateWindow failed: %lu", GetLastError());
DeregisterEventSource(g_hEventLog);
}
exit(1);
}
// Register for raw keyboard input (works with elevated apps)
RAWINPUTDEVICE rid = {0};
rid.usUsagePage = 0x01; // HID_USAGE_PAGE_GENERIC
rid.usUsage = 0x06; // HID_USAGE_GENERIC_KEYBOARD
rid.dwFlags = RIDEV_INPUTSINK; // Receive input even when not in foreground
rid.hwndTarget = hwnd;
if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
if (g_hEventLog) {
log_error("RegisterRawInputDevices failed: %lu", GetLastError());
DeregisterEventSource(g_hEventLog);
}
DestroyWindow(hwnd);
exit(1);
}
// Register Win+L as a hotkey (backup mechanism)
RegisterHotKey(hwnd, 1, MOD_WIN, VK_KEY_L);
// Install low-level keyboard hook (tertiary backup for non-elevated contexts)
g_hKeyboardHook = SetWindowsHookExA(WH_KEYBOARD_LL, keyboard_hook_proc, GetModuleHandle(NULL), 0);
// Message loop to handle RawInput, hotkeys, and hooks
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Cleanup
if (g_hKeyboardHook) UnhookWindowsHookEx(g_hKeyboardHook);
UnregisterHotKey(hwnd, 1);
// Unregister RawInput
rid.dwFlags = RIDEV_REMOVE;
rid.hwndTarget = NULL;
RegisterRawInputDevices(&rid, 1, sizeof(rid));
DestroyWindow(hwnd);
UnregisterClassA(wc.lpszClassName, wc.hInstance);
if (g_hSingleInstanceMutex) {
ReleaseMutex(g_hSingleInstanceMutex);
CloseHandle(g_hSingleInstanceMutex);
g_hSingleInstanceMutex = NULL;
}
if (g_hEventLog) {
DeregisterEventSource(g_hEventLog);
}
exit(0);
}
// Helper process entry point
static void run_helper(void) {
g_hEventLog = RegisterEventSourceA(NULL, SERVICE_NAME);
load_settings();
if (!LockWorkStation()) {
if (g_hEventLog) {
log_error("LockWorkStation failed: %lu", GetLastError());
DeregisterEventSource(g_hEventLog);
}
exit(1);
}
if (g_enableMonitorOff) {
Sleep(500);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
}
if (g_hEventLog) {
DeregisterEventSource(g_hEventLog);
}
exit(0);
}
// Launch helper process in specified session
static BOOL launch_helper_in_session(DWORD sessionId) {
HANDLE hToken = NULL, hDupToken = NULL;
STARTUPINFOW si = {0};
PROCESS_INFORMATION pi = {0};
LPVOID pEnvironment = NULL;
WCHAR szExePath[MAX_PATH];
WCHAR szCmdLine[MAX_PATH + 64]; // Increased buffer size
BOOL bResult = FALSE;
DWORD dwError;
if (!GetModuleFileNameW(NULL, szExePath, MAX_PATH)) {
dwError = GetLastError();
log_error("GetModuleFileName failed: %lu", dwError);
return FALSE;
}
swprintf(szCmdLine, sizeof(szCmdLine)/sizeof(WCHAR), L"\"%s\" %S", szExePath, HELP_FLAG);
// FIX: Hide the window completely
si.cb = sizeof(si);
si.lpDesktop = L"winsta0\\default";
si.dwFlags = STARTF_USESHOWWINDOW; // Use wShowWindow field
si.wShowWindow = SW_HIDE; // Hide the window
if (!WTSQueryUserToken(sessionId, &hToken)) {
dwError = GetLastError();
log_error("WTSQueryUserToken failed for session %lu: %lu", sessionId, dwError);
return FALSE;
}
if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, SecurityIdentification, TokenPrimary, &hDupToken)) {
dwError = GetLastError();
log_error("DuplicateTokenEx failed: %lu", dwError);
goto cleanup;
}
if (!CreateEnvironmentBlock(&pEnvironment, hDupToken, FALSE)) {
dwError = GetLastError();
log_error("CreateEnvironmentBlock failed: %lu", dwError);
goto cleanup;
}
// FIX: Use CREATE_NO_WINDOW instead of CREATE_NEW_CONSOLE
bResult = CreateProcessAsUserW(
hDupToken, NULL, szCmdLine, NULL, NULL, FALSE,
CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW, // No console window
pEnvironment, NULL, &si, &pi
);
if (bResult) {
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
} else {
dwError = GetLastError();
log_error("CreateProcessAsUserW failed: %lu", dwError);
}
cleanup:
if (pEnvironment) DestroyEnvironmentBlock(pEnvironment);
if (hDupToken) CloseHandle(hDupToken);
if (hToken) CloseHandle(hToken);
return bResult;
}
// Enumerate active sessions and lock them all
static void lock_all_sessions(void) {
PWTS_SESSION_INFOW pSessions = NULL;
DWORD sessionCount = 0;
DWORD dwError;
if (!WTSEnumerateSessionsW(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessions, &sessionCount)) {
dwError = GetLastError();
log_error("WTSEnumerateSessions failed: %lu", dwError);
return;
}
for (DWORD i = 0; i < sessionCount; i++) {
if (pSessions[i].State == WTSActive) {
launch_helper_in_session(pSessions[i].SessionId);
}
}
WTSFreeMemory(pSessions);
}
// Launch keyboard hook helper in specified session
static BOOL launch_keyboard_hook_in_session(DWORD sessionId, HANDLE *outProcess) {
HANDLE hToken = NULL, hDupToken = NULL;
STARTUPINFOW si = {0};
PROCESS_INFORMATION pi = {0};
LPVOID pEnvironment = NULL;
WCHAR szExePath[MAX_PATH];
WCHAR szCmdLine[MAX_PATH + 64]; // Increased buffer size
BOOL bResult = FALSE;
DWORD dwError;
if (outProcess)
*outProcess = NULL;
if (!GetModuleFileNameW(NULL, szExePath, MAX_PATH)) {
dwError = GetLastError();
log_error("GetModuleFileName failed: %lu", dwError);
return FALSE;
}
swprintf(szCmdLine, sizeof(szCmdLine)/sizeof(WCHAR), L"\"%s\" %S", szExePath, KEYBOARD_HOOK_FLAG);
si.cb = sizeof(si);
si.lpDesktop = L"winsta0\\default";
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
if (!WTSQueryUserToken(sessionId, &hToken)) {
dwError = GetLastError();
log_error("WTSQueryUserToken failed for session %lu: %lu", sessionId, dwError);
return FALSE;
}
// Duplicate token with elevated privileges
if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &hDupToken)) {
dwError = GetLastError();
log_error("DuplicateTokenEx failed: %lu", dwError);
goto cleanup;
}
// Try to get the linked token (elevated version) if available
TOKEN_LINKED_TOKEN linkedToken = {0};
DWORD dwSize = 0;
if (GetTokenInformation(hDupToken, TokenLinkedToken, &linkedToken, sizeof(linkedToken), &dwSize)) {
if (linkedToken.LinkedToken) {
// Use the linked (elevated) token instead
CloseHandle(hDupToken);
hDupToken = linkedToken.LinkedToken;
}
}
if (!CreateEnvironmentBlock(&pEnvironment, hDupToken, FALSE)) {
dwError = GetLastError();
log_error("CreateEnvironmentBlock failed: %lu", dwError);
goto cleanup;
}
bResult = CreateProcessAsUserW(
hDupToken, NULL, szCmdLine, NULL, NULL, FALSE,
CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW,
pEnvironment, NULL, &si, &pi
);
if (bResult) {
// Get username for this session
char username[256] = {0};
DWORD usernameLen = 0;
LPWSTR pUsername = NULL;
if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSUserName, &pUsername, &usernameLen)) {
int result = WideCharToMultiByte(CP_UTF8, 0, pUsername, -1, username, sizeof(username), NULL, NULL);
WTSFreeMemory(pUsername);
if (result > 0) {
log_info("Attaching keyboard helper to logged in user %s", username);
} else {
log_info("Attaching keyboard helper to session %lu", sessionId);
}
} else {
log_info("Attaching keyboard helper to session %lu", sessionId);
}
if (outProcess)
*outProcess = pi.hProcess;
else
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
} else {
dwError = GetLastError();
log_error("CreateProcessAsUserW failed: %lu", dwError);
}
cleanup:
if (pEnvironment) DestroyEnvironmentBlock(pEnvironment);
if (hDupToken) CloseHandle(hDupToken);
if (hToken) CloseHandle(hToken);
return bResult;
}
static int find_helper_index_nolock(DWORD sessionId) {
for (DWORD i = 0; i < g_HelperProcCount; i++) {
if (g_HelperProcs[i].sessionId == sessionId)
return (int)i;
}
return -1;
}
static BOOL is_helper_process_alive(HANDLE hProcess) {
if (!hProcess || hProcess == HELPER_HANDLE_LAUNCHING)
return FALSE;
DWORD rc = WaitForSingleObject(hProcess, 0);
return (rc == WAIT_TIMEOUT);
}
static void remove_helper_nolock(DWORD index, BOOL terminate) {
HANDLE h = g_HelperProcs[index].hProcess;
if (terminate && h && h != HELPER_HANDLE_LAUNCHING) {
TerminateProcess(h, 0);
WaitForSingleObject(h, 2000);
}
if (h && h != HELPER_HANDLE_LAUNCHING)
CloseHandle(h);
for (DWORD k = index; k < g_HelperProcCount - 1; k++)
g_HelperProcs[k] = g_HelperProcs[k + 1];
g_HelperProcCount--;
}
static void cleanup_helpers(void) {
PWTS_SESSION_INFOW pSessions = NULL;
DWORD sessionCount = 0;
if (!WTSEnumerateSessionsW(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessions, &sessionCount))
return;
EnterCriticalSection(&g_SessionLock);
for (DWORD i = 0; i < g_HelperProcCount; ) {
DWORD sid = g_HelperProcs[i].sessionId;
BOOL sessionActive = FALSE;
for (DWORD j = 0; j < sessionCount; j++) {
if (pSessions[j].SessionId == sid && pSessions[j].State == WTSActive) {
sessionActive = TRUE;
break;
}
}
if (!sessionActive) {
remove_helper_nolock(i, TRUE);
continue;
}
if (g_HelperProcs[i].hProcess != HELPER_HANDLE_LAUNCHING &&
!is_helper_process_alive(g_HelperProcs[i].hProcess)) {
remove_helper_nolock(i, FALSE);
continue;
}
i++;
}
LeaveCriticalSection(&g_SessionLock);
WTSFreeMemory(pSessions);
}
// Monitor for new sessions and attach keyboard hooks
static DWORD WINAPI session_monitor_thread(LPVOID param) {
DWORD iterationCount = 0;
do {
PWTS_SESSION_INFOW pSessions = NULL;
DWORD sessionCount = 0;
if (!WTSEnumerateSessionsW(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessions, &sessionCount))
continue;
for (DWORD i = 0; i < sessionCount; i++) {
DWORD sid = pSessions[i].SessionId;
if (pSessions[i].State != WTSActive)
continue;
BOOL reserved = FALSE;
EnterCriticalSection(&g_SessionLock);
int idx = find_helper_index_nolock(sid);
if (idx >= 0) {
HANDLE h = g_HelperProcs[idx].hProcess;
if (h == HELPER_HANDLE_LAUNCHING) {
LeaveCriticalSection(&g_SessionLock);
continue;
}
if (is_helper_process_alive(h)) {
LeaveCriticalSection(&g_SessionLock);
continue;
}
remove_helper_nolock((DWORD)idx, FALSE);
idx = -1;
}
if (idx < 0) {
if (g_HelperProcCount < MAX_TRACKED_SESSIONS) {
g_HelperProcs[g_HelperProcCount].sessionId = sid;
g_HelperProcs[g_HelperProcCount].hProcess = HELPER_HANDLE_LAUNCHING;
g_HelperProcCount++;
reserved = TRUE;
} else {
log_error("Maximum tracked sessions (%d) exceeded. Cannot track session %lu", MAX_TRACKED_SESSIONS, sid);
}
}
LeaveCriticalSection(&g_SessionLock);
if (reserved) {
HANDLE hProc = NULL;
if (launch_keyboard_hook_in_session(sid, &hProc) && hProc) {
EnterCriticalSection(&g_SessionLock);
int j = find_helper_index_nolock(sid);
if (j >= 0) {
g_HelperProcs[j].hProcess = hProc;
} else if (g_HelperProcCount < MAX_TRACKED_SESSIONS) {
g_HelperProcs[g_HelperProcCount].sessionId = sid;
g_HelperProcs[g_HelperProcCount].hProcess = hProc;
g_HelperProcCount++;
} else {
CloseHandle(hProc);
}
LeaveCriticalSection(&g_SessionLock);
} else {
EnterCriticalSection(&g_SessionLock);
int j = find_helper_index_nolock(sid);
if (j >= 0 && g_HelperProcs[j].hProcess == HELPER_HANDLE_LAUNCHING)
remove_helper_nolock((DWORD)j, FALSE);
LeaveCriticalSection(&g_SessionLock);
}
}
}
WTSFreeMemory(pSessions);
iterationCount++;
if (iterationCount >= 6) {
cleanup_helpers();
iterationCount = 0;
}
} while (WaitForSingleObject(g_ServiceStopEvent, SESSION_POLL_INTERVAL_MS) == WAIT_TIMEOUT);
return 0;
}
// Minimal HTTP server thread
static DWORD WINAPI http_server_thread(LPVOID param) {
WSADATA wsa;
SOCKET listenSocket = INVALID_SOCKET, clientSocket;
struct sockaddr_in addr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buffer[1024];
DWORD dwError;
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
log_error("WSAStartup failed");
return 1;
}
if ((listenSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
log_error("Socket creation failed");
goto cleanup;
}
int opt = 1;
setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
addr.sin_family = AF_INET;
if (inet_pton(AF_INET, g_bindIP, &addr.sin_addr) != 1)
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons((u_short)g_bindPort);
if (bind(listenSocket, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
dwError = WSAGetLastError();
log_error("Bind failed on port %lu: %d", g_bindPort, dwError);
goto cleanup;
}
if (listen(listenSocket, 3) == SOCKET_ERROR) {
dwError = WSAGetLastError();
log_error("Listen failed: %d", dwError);
goto cleanup;
}
while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0) {
fd_set readfds;
struct timeval tv = {0, HTTP_SELECT_TIMEOUT_MS * 1000};
FD_ZERO(&readfds);
FD_SET(listenSocket, &readfds);
if (select(listenSocket + 1, &readfds, NULL, NULL, &tv) > 0) {
if ((clientSocket = accept(listenSocket, (struct sockaddr*)&clientAddr, &clientAddrLen)) != INVALID_SOCKET) {
int recvSize = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
if (recvSize > 0) {
buffer[recvSize] = '\0';
// Check if request starts with "GET /lock"
if (recvSize >= 9 && strncmp(buffer, "GET /lock", 9) == 0) {
log_info("Received API request /lock");
lock_all_sessions();
const char* response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n"
"\r\n"
"{\"status\":\"ok\",\"message\":\"Sessions locked\"}\r\n";
send(clientSocket, response, strlen(response), 0);
} else {
const char* response =
"HTTP/1.1 404 Not Found\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n"
"\r\n"
"{\"status\":\"error\",\"message\":\"Endpoint not found\"}\r\n";
send(clientSocket, response, strlen(response), 0);
}
}
closesocket(clientSocket);
}
}
}
cleanup:
if (listenSocket != INVALID_SOCKET) closesocket(listenSocket);
WSACleanup();
return 0;
}
// Service control handler
static void WINAPI service_ctrl_handler(DWORD ctrl) {
switch (ctrl) {
case SERVICE_CONTROL_STOP:
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
SetEvent(g_ServiceStopEvent);
break;
case SERVICE_CONTROL_INTERROGATE:
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
break;
}
}
// Load bind settings from registry
static void load_settings(void) {
HKEY hKey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, REG_KEY_PATH, 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
DWORD type, size;
size = sizeof(g_bindIP);
if (RegQueryValueExA(hKey, REG_VALUE_BIND_IP, NULL, &type, (BYTE*)g_bindIP, &size) != ERROR_SUCCESS
|| type != REG_SZ || size == 0) {
strcpy(g_bindIP, "0.0.0.0");
}
g_bindIP[sizeof(g_bindIP) - 1] = '\0';
DWORD port = 0;
size = sizeof(port);
if (RegQueryValueExA(hKey, REG_VALUE_BIND_PORT, NULL, &type, (BYTE*)&port, &size) == ERROR_SUCCESS
&& type == REG_DWORD && port >= 1 && port <= 65535) {
g_bindPort = port;
}
DWORD val = 0;
size = sizeof(val);
if (RegQueryValueExA(hKey, REG_VALUE_ENABLE_HTTP, NULL, &type, (BYTE*)&val, &size) == ERROR_SUCCESS
&& type == REG_DWORD) {
g_enableHTTP = val ? 1 : 0;
} else {
g_enableHTTP = 1;
}
val = 0;
size = sizeof(val);
if (RegQueryValueExA(hKey, REG_VALUE_ENABLE_MONOFF, NULL, &type, (BYTE*)&val, &size) == ERROR_SUCCESS
&& type == REG_DWORD) {
g_enableMonitorOff = val ? 1 : 0;
} else {
g_enableMonitorOff = 1;
}
RegCloseKey(hKey);
}
}
// Save bind settings to registry
static BOOL save_settings(const char* ip, DWORD port, DWORD enableHTTP, DWORD enableMonOff) {
HKEY hKey;
DWORD disp;
if (RegCreateKeyExA(HKEY_LOCAL_MACHINE, REG_KEY_PATH, 0, NULL, 0, KEY_WRITE, NULL, &hKey, &disp) != ERROR_SUCCESS)
return FALSE;
BOOL ok = TRUE;
if (RegSetValueExA(hKey, REG_VALUE_BIND_IP, 0, REG_SZ, (const BYTE*)ip, (DWORD)strlen(ip) + 1) != ERROR_SUCCESS)
ok = FALSE;
if (RegSetValueExA(hKey, REG_VALUE_BIND_PORT, 0, REG_DWORD, (const BYTE*)&port, sizeof(port)) != ERROR_SUCCESS)
ok = FALSE;
if (RegSetValueExA(hKey, REG_VALUE_ENABLE_HTTP, 0, REG_DWORD, (const BYTE*)&enableHTTP, sizeof(enableHTTP)) != ERROR_SUCCESS)
ok = FALSE;
if (RegSetValueExA(hKey, REG_VALUE_ENABLE_MONOFF, 0, REG_DWORD, (const BYTE*)&enableMonOff, sizeof(enableMonOff)) != ERROR_SUCCESS)
ok = FALSE;
if (ok) {
g_enableHTTP = enableHTTP;
g_enableMonitorOff = enableMonOff;
}
RegCloseKey(hKey);
return ok;
}
// Service main function
static void WINAPI service_main(DWORD argc, LPWSTR* argv) {
g_StatusHandle = RegisterServiceCtrlHandlerW(L"LockService", service_ctrl_handler);
if (!g_StatusHandle) return;
memset(&g_ServiceStatus, 0, sizeof(g_ServiceStatus));
g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
// Initialize event logging
g_hEventLog = RegisterEventSourceA(NULL, SERVICE_NAME);
g_ServiceStopEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
if (!g_ServiceStopEvent) {
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = GetLastError();
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
if (g_hEventLog) DeregisterEventSource(g_hEventLog);
return;
}
g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
// Initialize session tracking
InitializeCriticalSection(&g_SessionLock);
g_HelperProcCount = 0;
// Load bind settings from registry
load_settings();
// Start HTTP server thread (if enabled)
HANDLE hHttpThread = NULL;
if (g_enableHTTP) {
hHttpThread = CreateThread(NULL, 0, http_server_thread, NULL, 0, NULL);
if (!hHttpThread) {
DWORD dwError = GetLastError();
log_error("Failed to create HTTP server thread: %lu", dwError);
DeleteCriticalSection(&g_SessionLock);
CloseHandle(g_ServiceStopEvent);
if (g_hEventLog) DeregisterEventSource(g_hEventLog);
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = dwError;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
return;
}
}
// Start session monitoring thread (does immediate check, then every 10 seconds)
HANDLE hMonitorThread = CreateThread(NULL, 0, session_monitor_thread, NULL, 0, NULL);
if (!hMonitorThread) {
DWORD dwError = GetLastError();
log_error("Failed to create session monitor thread: %lu", dwError);
SetEvent(g_ServiceStopEvent);
if (hHttpThread) {
WaitForSingleObject(hHttpThread, THREAD_SHUTDOWN_TIMEOUT_MS);
CloseHandle(hHttpThread);
}
DeleteCriticalSection(&g_SessionLock);
CloseHandle(g_ServiceStopEvent);
if (g_hEventLog) DeregisterEventSource(g_hEventLog);
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = dwError;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
return;
}
WaitForSingleObject(g_ServiceStopEvent, INFINITE);
// Terminate all helper processes before shutting down threads
EnterCriticalSection(&g_SessionLock);
for (DWORD i = 0; i < g_HelperProcCount; i++) {
HANDLE h = g_HelperProcs[i].hProcess;
if (h && h != HELPER_HANDLE_LAUNCHING) {
if (TerminateProcess(h, 0)) {
WaitForSingleObject(h, 2000);
}
CloseHandle(h);
}
}
g_HelperProcCount = 0;
LeaveCriticalSection(&g_SessionLock);
if (hHttpThread) {
WaitForSingleObject(hHttpThread, THREAD_SHUTDOWN_TIMEOUT_MS);
CloseHandle(hHttpThread);
}
if (hMonitorThread) {
WaitForSingleObject(hMonitorThread, THREAD_SHUTDOWN_TIMEOUT_MS);
CloseHandle(hMonitorThread);
}
DeleteCriticalSection(&g_SessionLock);
CloseHandle(g_ServiceStopEvent);
if (g_hEventLog) {
DeregisterEventSource(g_hEventLog);
}
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
}
// Kill all other LockService.exe instances (helpers, hooks, service) except ourselves
static void kill_other_instances(void) {
DWORD myPid = GetCurrentProcessId();
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE) return;
WCHAR myExe[MAX_PATH];
GetModuleFileNameW(NULL, myExe, MAX_PATH);
WCHAR *myName = wcsrchr(myExe, L'\\');
myName = myName ? myName + 1 : myExe;
PROCESSENTRY32W pe = {0};
pe.dwSize = sizeof(pe);