[WINLOGON]
[reactos.git] / reactos / base / system / winlogon / sas.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS Winlogon
4 * FILE: base/system/winlogon/sas.c
5 * PURPOSE: Secure Attention Sequence
6 * PROGRAMMERS: Thomas Weidenmueller (w3seek@users.sourceforge.net)
7 * Hervé Poussineau (hpoussin@reactos.org)
8 * UPDATE HISTORY:
9 * Created 28/03/2004
10 */
11
12 /* INCLUDES *****************************************************************/
13
14 #include "winlogon.h"
15
16 /* GLOBALS ******************************************************************/
17
18 #define WINLOGON_SAS_CLASS L"SAS Window class"
19 #define WINLOGON_SAS_TITLE L"SAS window"
20
21 #define HK_CTRL_ALT_DEL 0
22 #define HK_CTRL_SHIFT_ESC 1
23
24 #define EWX_ACTION_MASK 0xffffffeb
25 #define EWX_FLAGS_MASK 0x00000014
26
27 typedef struct tagLOGOFF_SHUTDOWN_DATA
28 {
29 UINT Flags;
30 PWLSESSION Session;
31 } LOGOFF_SHUTDOWN_DATA, *PLOGOFF_SHUTDOWN_DATA;
32
33 /* FUNCTIONS ****************************************************************/
34
35 static BOOL
36 StartTaskManager(
37 IN OUT PWLSESSION Session)
38 {
39 LPVOID lpEnvironment;
40 BOOL ret;
41
42 if (!Session->Gina.Functions.WlxStartApplication)
43 return FALSE;
44
45 if (!CreateEnvironmentBlock(
46 &lpEnvironment,
47 Session->UserToken,
48 TRUE))
49 {
50 return FALSE;
51 }
52
53 ret = Session->Gina.Functions.WlxStartApplication(
54 Session->Gina.Context,
55 L"Default",
56 lpEnvironment,
57 L"taskmgr.exe");
58
59 DestroyEnvironmentBlock(lpEnvironment);
60 return ret;
61 }
62
63 static BOOL
64 StartUserShell(
65 IN OUT PWLSESSION Session)
66 {
67 LPVOID lpEnvironment = NULL;
68 BOOLEAN Old;
69 BOOL ret;
70
71 /* Create environment block for the user */
72 if (!CreateEnvironmentBlock(&lpEnvironment, Session->UserToken, TRUE))
73 {
74 WARN("WL: CreateEnvironmentBlock() failed\n");
75 return FALSE;
76 }
77
78 /* Get privilege */
79 /* FIXME: who should do it? winlogon or gina? */
80 /* FIXME: reverting to lower privileges after creating user shell? */
81 RtlAdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_PRIVILEGE, TRUE, FALSE, &Old);
82
83 ret = Session->Gina.Functions.WlxActivateUserShell(
84 Session->Gina.Context,
85 L"Default",
86 NULL, /* FIXME */
87 lpEnvironment);
88
89 DestroyEnvironmentBlock(lpEnvironment);
90 return ret;
91 }
92
93
94 BOOL
95 SetDefaultLanguage(
96 IN BOOL UserProfile)
97 {
98 HKEY BaseKey;
99 LPCWSTR SubKey;
100 LPCWSTR ValueName;
101 LONG rc;
102 HKEY hKey = NULL;
103 DWORD dwType, dwSize;
104 LPWSTR Value = NULL;
105 UNICODE_STRING ValueString;
106 NTSTATUS Status;
107 LCID Lcid;
108 BOOL ret = FALSE;
109
110 if (UserProfile)
111 {
112 BaseKey = HKEY_CURRENT_USER;
113 SubKey = L"Control Panel\\International";
114 ValueName = L"Locale";
115 }
116 else
117 {
118 BaseKey = HKEY_LOCAL_MACHINE;
119 SubKey = L"System\\CurrentControlSet\\Control\\Nls\\Language";
120 ValueName = L"Default";
121 }
122
123 rc = RegOpenKeyExW(
124 BaseKey,
125 SubKey,
126 0,
127 KEY_READ,
128 &hKey);
129 if (rc != ERROR_SUCCESS)
130 {
131 TRACE("RegOpenKeyEx() failed with error %lu\n", rc);
132 goto cleanup;
133 }
134 rc = RegQueryValueExW(
135 hKey,
136 ValueName,
137 NULL,
138 &dwType,
139 NULL,
140 &dwSize);
141 if (rc != ERROR_SUCCESS)
142 {
143 TRACE("RegQueryValueEx() failed with error %lu\n", rc);
144 goto cleanup;
145 }
146 else if (dwType != REG_SZ)
147 {
148 TRACE("Wrong type for %S\\%S registry entry (got 0x%lx, expected 0x%x)\n",
149 SubKey, ValueName, dwType, REG_SZ);
150 goto cleanup;
151 }
152
153 Value = HeapAlloc(GetProcessHeap(), 0, dwSize);
154 if (!Value)
155 {
156 TRACE("HeapAlloc() failed\n");
157 goto cleanup;
158 }
159 rc = RegQueryValueExW(
160 hKey,
161 ValueName,
162 NULL,
163 NULL,
164 (LPBYTE)Value,
165 &dwSize);
166 if (rc != ERROR_SUCCESS)
167 {
168 TRACE("RegQueryValueEx() failed with error %lu\n", rc);
169 goto cleanup;
170 }
171
172 /* Convert Value to a Lcid */
173 ValueString.Length = ValueString.MaximumLength = (USHORT)dwSize;
174 ValueString.Buffer = Value;
175 Status = RtlUnicodeStringToInteger(&ValueString, 16, (PULONG)&Lcid);
176 if (!NT_SUCCESS(Status))
177 {
178 TRACE("RtlUnicodeStringToInteger() failed with status 0x%08lx\n", Status);
179 goto cleanup;
180 }
181
182 TRACE("%s language is 0x%08lx\n",
183 UserProfile ? "User" : "System", Lcid);
184 Status = NtSetDefaultLocale(UserProfile, Lcid);
185 if (!NT_SUCCESS(Status))
186 {
187 TRACE("NtSetDefaultLocale() failed with status 0x%08lx\n", Status);
188 goto cleanup;
189 }
190
191 ret = TRUE;
192
193 cleanup:
194 if (hKey)
195 RegCloseKey(hKey);
196 if (Value)
197 HeapFree(GetProcessHeap(), 0, Value);
198 return ret;
199 }
200
201 BOOL
202 PlaySoundRoutine(
203 IN LPCWSTR FileName,
204 IN UINT bLogon,
205 IN UINT Flags)
206 {
207 typedef BOOL (WINAPI *PLAYSOUNDW)(LPCWSTR,HMODULE,DWORD);
208 typedef UINT (WINAPI *WAVEOUTGETNUMDEVS)(VOID);
209 PLAYSOUNDW Play;
210 WAVEOUTGETNUMDEVS waveOutGetNumDevs;
211 UINT NumDevs;
212 HMODULE hLibrary;
213 BOOL Ret = FALSE;
214
215 hLibrary = LoadLibraryW(L"winmm.dll");
216 if (hLibrary)
217 {
218 waveOutGetNumDevs = (WAVEOUTGETNUMDEVS)GetProcAddress(hLibrary, "waveOutGetNumDevs");
219 if (waveOutGetNumDevs)
220 {
221 NumDevs = waveOutGetNumDevs();
222 if (!NumDevs)
223 {
224 if (!bLogon)
225 {
226 Beep(500, 500);
227 }
228 FreeLibrary(hLibrary);
229 return FALSE;
230 }
231 }
232
233 Play = (PLAYSOUNDW)GetProcAddress(hLibrary, "PlaySoundW");
234 if (Play)
235 {
236 Ret = Play(FileName, NULL, Flags);
237 }
238 FreeLibrary(hLibrary);
239 }
240
241 return Ret;
242 }
243
244 DWORD
245 WINAPI
246 PlayLogonSoundThread(
247 IN LPVOID lpParameter)
248 {
249 BYTE TokenUserBuffer[256];
250 PTOKEN_USER pTokenUser = (TOKEN_USER*)TokenUserBuffer;
251 ULONG Length;
252 HKEY hKey;
253 WCHAR wszBuffer[MAX_PATH] = {0};
254 WCHAR wszDest[MAX_PATH];
255 DWORD dwSize = sizeof(wszBuffer), dwType;
256 SERVICE_STATUS_PROCESS Info;
257 UNICODE_STRING SidString;
258 NTSTATUS Status;
259 ULONG Index = 0;
260 SC_HANDLE hSCManager, hService;
261
262 /* Get SID of current user */
263 Status = NtQueryInformationToken((HANDLE)lpParameter,
264 TokenUser,
265 TokenUserBuffer,
266 sizeof(TokenUserBuffer),
267 &Length);
268 if (!NT_SUCCESS(Status))
269 {
270 ERR("NtQueryInformationToken failed: %x!\n", Status);
271 return 0;
272 }
273
274 /* Convert SID to string */
275 RtlInitEmptyUnicodeString(&SidString, wszBuffer, sizeof(wszBuffer));
276 Status = RtlConvertSidToUnicodeString(&SidString, pTokenUser->User.Sid, FALSE);
277 if (!NT_SUCCESS(Status))
278 {
279 ERR("RtlConvertSidToUnicodeString failed: %x!\n", Status);
280 return 0;
281 }
282
283 /* Build path to logon sound registry key.
284 Note: We can't use HKCU here, because Winlogon is owned by SYSTEM user */
285 if (FAILED(StringCbCopyW(wszBuffer + SidString.Length/sizeof(WCHAR),
286 sizeof(wszBuffer) - SidString.Length,
287 L"\\AppEvents\\Schemes\\Apps\\.Default\\WindowsLogon\\.Current")))
288 {
289 /* SID is too long. Should not happen. */
290 ERR("StringCbCopyW failed!\n");
291 return 0;
292 }
293
294 /* Open registry key and query sound path */
295 if (RegOpenKeyExW(HKEY_USERS, wszBuffer, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
296 {
297 ERR("RegOpenKeyExW(%ls) failed!\n", wszBuffer);
298 return 0;
299 }
300
301 if (RegQueryValueExW(hKey, NULL, NULL, &dwType,
302 (LPBYTE)wszBuffer, &dwSize) != ERROR_SUCCESS ||
303 (dwType != REG_SZ && dwType != REG_EXPAND_SZ))
304 {
305 ERR("RegQueryValueExW failed!\n");
306 RegCloseKey(hKey);
307 return 0;
308 }
309
310 RegCloseKey(hKey);
311
312 if (!wszBuffer[0])
313 {
314 /* No sound has been set */
315 ERR("No sound has been set\n");
316 return 0;
317 }
318
319 /* Expand environment variables */
320 if (!ExpandEnvironmentStringsW(wszBuffer, wszDest, MAX_PATH))
321 {
322 ERR("ExpandEnvironmentStringsW failed!\n");
323 return 0;
324 }
325
326 /* Open service manager */
327 hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
328 if (!hSCManager)
329 {
330 ERR("OpenSCManager failed (%x)\n", GetLastError());
331 return 0;
332 }
333
334 /* Open wdmaud service */
335 hService = OpenServiceW(hSCManager, L"wdmaud", GENERIC_READ);
336 if (!hService)
337 {
338 /* Sound is not installed */
339 TRACE("Failed to open wdmaud service (%x)\n", GetLastError());
340 CloseServiceHandle(hSCManager);
341 return 0;
342 }
343
344 /* Wait for wdmaud start */
345 do
346 {
347 if (!QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&Info, sizeof(SERVICE_STATUS_PROCESS), &dwSize))
348 {
349 TRACE("QueryServiceStatusEx failed (%x)\n", GetLastError());
350 break;
351 }
352
353 if (Info.dwCurrentState == SERVICE_RUNNING)
354 break;
355
356 Sleep(1000);
357
358 } while (Index++ < 20);
359
360 CloseServiceHandle(hService);
361 CloseServiceHandle(hSCManager);
362
363 /* If wdmaud is not running exit */
364 if (Info.dwCurrentState != SERVICE_RUNNING)
365 {
366 WARN("wdmaud has not started!\n");
367 return 0;
368 }
369
370 /* Sound subsystem is running. Play logon sound. */
371 TRACE("Playing logon sound: %ls\n", wszDest);
372 PlaySoundRoutine(wszDest, TRUE, SND_FILENAME);
373 return 0;
374 }
375
376 static
377 VOID
378 PlayLogonSound(
379 IN OUT PWLSESSION Session)
380 {
381 HANDLE hThread;
382
383 hThread = CreateThread(NULL, 0, PlayLogonSoundThread, (PVOID)Session->UserToken, 0, NULL);
384 if (hThread)
385 CloseHandle(hThread);
386 }
387
388 static
389 BOOL
390 HandleLogon(
391 IN OUT PWLSESSION Session)
392 {
393 PROFILEINFOW ProfileInfo;
394 BOOL ret = FALSE;
395
396 /* Loading personal settings */
397 DisplayStatusMessage(Session, Session->WinlogonDesktop, IDS_LOADINGYOURPERSONALSETTINGS);
398 ProfileInfo.hProfile = INVALID_HANDLE_VALUE;
399 if (0 == (Session->Options & WLX_LOGON_OPT_NO_PROFILE))
400 {
401 if (Session->Profile == NULL
402 || (Session->Profile->dwType != WLX_PROFILE_TYPE_V1_0
403 && Session->Profile->dwType != WLX_PROFILE_TYPE_V2_0))
404 {
405 ERR("WL: Wrong profile\n");
406 goto cleanup;
407 }
408
409 /* Load the user profile */
410 ZeroMemory(&ProfileInfo, sizeof(PROFILEINFOW));
411 ProfileInfo.dwSize = sizeof(PROFILEINFOW);
412 ProfileInfo.dwFlags = 0;
413 ProfileInfo.lpUserName = Session->MprNotifyInfo.pszUserName;
414 ProfileInfo.lpProfilePath = Session->Profile->pszProfile;
415 if (Session->Profile->dwType >= WLX_PROFILE_TYPE_V2_0)
416 {
417 ProfileInfo.lpDefaultPath = Session->Profile->pszNetworkDefaultUserProfile;
418 ProfileInfo.lpServerName = Session->Profile->pszServerName;
419 ProfileInfo.lpPolicyPath = Session->Profile->pszPolicy;
420 }
421
422 if (!LoadUserProfileW(Session->UserToken, &ProfileInfo))
423 {
424 ERR("WL: LoadUserProfileW() failed\n");
425 goto cleanup;
426 }
427 }
428
429 /* Create environment block for the user */
430 if (!CreateUserEnvironment(Session))
431 {
432 WARN("WL: SetUserEnvironment() failed\n");
433 goto cleanup;
434 }
435
436 DisplayStatusMessage(Session, Session->WinlogonDesktop, IDS_APPLYINGYOURPERSONALSETTINGS);
437 UpdatePerUserSystemParameters(0, TRUE);
438
439 /* Set default language */
440 if (!SetDefaultLanguage(TRUE))
441 {
442 WARN("WL: SetDefaultLanguage() failed\n");
443 goto cleanup;
444 }
445
446 if (!StartUserShell(Session))
447 {
448 //WCHAR StatusMsg[256];
449 WARN("WL: WlxActivateUserShell() failed\n");
450 //LoadStringW(hAppInstance, IDS_FAILEDACTIVATEUSERSHELL, StatusMsg, sizeof(StatusMsg) / sizeof(StatusMsg[0]));
451 //MessageBoxW(0, StatusMsg, NULL, MB_ICONERROR);
452 goto cleanup;
453 }
454
455 if (!InitializeScreenSaver(Session))
456 WARN("WL: Failed to initialize screen saver\n");
457
458 Session->hProfileInfo = ProfileInfo.hProfile;
459
460 /* Logon has successed. Play sound. */
461 PlayLogonSound(Session);
462
463 ret = TRUE;
464
465 cleanup:
466 if (Session->Profile)
467 {
468 HeapFree(GetProcessHeap(), 0, Session->Profile->pszProfile);
469 HeapFree(GetProcessHeap(), 0, Session->Profile);
470 }
471 Session->Profile = NULL;
472 if (!ret
473 && ProfileInfo.hProfile != INVALID_HANDLE_VALUE)
474 {
475 UnloadUserProfile(WLSession->UserToken, ProfileInfo.hProfile);
476 }
477 RemoveStatusMessage(Session);
478 if (!ret)
479 {
480 CloseHandle(Session->UserToken);
481 Session->UserToken = NULL;
482 }
483 return ret;
484 }
485
486
487 static
488 DWORD
489 WINAPI
490 LogoffShutdownThread(
491 LPVOID Parameter)
492 {
493 PLOGOFF_SHUTDOWN_DATA LSData = (PLOGOFF_SHUTDOWN_DATA)Parameter;
494
495 if (LSData->Session->UserToken != NULL && !ImpersonateLoggedOnUser(LSData->Session->UserToken))
496 {
497 ERR("ImpersonateLoggedOnUser() failed with error %lu\n", GetLastError());
498 return 0;
499 }
500
501 /* Close processes of the interactive user */
502 if (!ExitWindowsEx(
503 EWX_INTERNAL_KILL_USER_APPS | (LSData->Flags & EWX_FLAGS_MASK) |
504 (EWX_LOGOFF == (LSData->Flags & EWX_ACTION_MASK) ? EWX_INTERNAL_FLAG_LOGOFF : 0),
505 0))
506 {
507 ERR("Unable to kill user apps, error %lu\n", GetLastError());
508 RevertToSelf();
509 return 0;
510 }
511
512 /* FIXME: Call ExitWindowsEx() to terminate COM processes */
513
514 if (LSData->Session->UserToken)
515 RevertToSelf();
516
517 return 1;
518 }
519
520
521 static
522 NTSTATUS
523 CreateLogoffSecurityAttributes(
524 OUT PSECURITY_ATTRIBUTES* ppsa)
525 {
526 /* The following code is not working yet and messy */
527 /* Still, it gives some ideas about data types and functions involved and */
528 /* required to set up a SECURITY_DESCRIPTOR for a SECURITY_ATTRIBUTES */
529 /* instance for a thread, to allow that thread to ImpersonateLoggedOnUser(). */
530 /* Specifically THREAD_SET_THREAD_TOKEN is required. */
531 PSECURITY_DESCRIPTOR SecurityDescriptor = NULL;
532 PSECURITY_ATTRIBUTES psa = 0;
533 BYTE* pMem;
534 PACL pACL;
535 EXPLICIT_ACCESS Access;
536 PSID pEveryoneSID = NULL;
537 static SID_IDENTIFIER_AUTHORITY WorldAuthority = { SECURITY_WORLD_SID_AUTHORITY };
538
539 *ppsa = NULL;
540
541 // Let's first try to enumerate what kind of data we need for this to ever work:
542 // 1. The Winlogon SID, to be able to give it THREAD_SET_THREAD_TOKEN.
543 // 2. The users SID (the user trying to logoff, or rather shut down the system).
544 // 3. At least two EXPLICIT_ACCESS instances:
545 // 3.1 One for Winlogon itself, giving it the rights
546 // required to THREAD_SET_THREAD_TOKEN (as it's needed to successfully call
547 // ImpersonateLoggedOnUser).
548 // 3.2 One for the user, to allow *that* thread to perform its work.
549 // 4. An ACL to hold the these EXPLICIT_ACCESS ACE's.
550 // 5. A SECURITY_DESCRIPTOR to hold the ACL, and finally.
551 // 6. A SECURITY_ATTRIBUTES instance to pull all of this required stuff
552 // together, to hand it to CreateThread.
553 //
554 // However, it seems struct LOGOFF_SHUTDOWN_DATA doesn't contain
555 // these required SID's, why they'd have to be added.
556 // The Winlogon's own SID should probably only be created once,
557 // while the user's SID obviously must be created for each new user.
558 // Might as well store it when the user logs on?
559
560 if(!AllocateAndInitializeSid(&WorldAuthority,
561 1,
562 SECURITY_WORLD_RID,
563 0, 0, 0, 0, 0, 0, 0,
564 &pEveryoneSID))
565 {
566 ERR("Failed to initialize security descriptor for logoff thread!\n");
567 return STATUS_UNSUCCESSFUL;
568 }
569
570 /* set up the required security attributes to be able to shut down */
571 /* To save space and time, allocate a single block of memory holding */
572 /* both SECURITY_ATTRIBUTES and SECURITY_DESCRIPTOR */
573 pMem = HeapAlloc(GetProcessHeap(),
574 0,
575 sizeof(SECURITY_ATTRIBUTES) +
576 SECURITY_DESCRIPTOR_MIN_LENGTH +
577 sizeof(ACL));
578 if (!pMem)
579 {
580 ERR("Failed to allocate memory for logoff security descriptor!\n");
581 return STATUS_NO_MEMORY;
582 }
583
584 /* Note that the security descriptor needs to be in _absolute_ format, */
585 /* meaning its members must be pointers to other structures, rather */
586 /* than the relative format using offsets */
587 psa = (PSECURITY_ATTRIBUTES)pMem;
588 SecurityDescriptor = (PSECURITY_DESCRIPTOR)(pMem + sizeof(SECURITY_ATTRIBUTES));
589 pACL = (PACL)(((PBYTE)SecurityDescriptor) + SECURITY_DESCRIPTOR_MIN_LENGTH);
590
591 // Initialize an EXPLICIT_ACCESS structure for an ACE.
592 // The ACE will allow this thread to log off (and shut down the system, currently).
593 ZeroMemory(&Access, sizeof(Access));
594 Access.grfAccessPermissions = THREAD_SET_THREAD_TOKEN;
595 Access.grfAccessMode = SET_ACCESS; // GRANT_ACCESS?
596 Access.grfInheritance = NO_INHERITANCE;
597 Access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
598 Access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
599 Access.Trustee.ptstrName = pEveryoneSID;
600
601 if (SetEntriesInAcl(1, &Access, NULL, &pACL) != ERROR_SUCCESS)
602 {
603 ERR("Failed to set Access Rights for logoff thread. Logging out will most likely fail.\n");
604
605 HeapFree(GetProcessHeap(), 0, pMem);
606 return STATUS_UNSUCCESSFUL;
607 }
608
609 if (!InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION))
610 {
611 ERR("Failed to initialize security descriptor for logoff thread!\n");
612 HeapFree(GetProcessHeap(), 0, pMem);
613 return STATUS_UNSUCCESSFUL;
614 }
615
616 if (!SetSecurityDescriptorDacl(SecurityDescriptor,
617 TRUE, // bDaclPresent flag
618 pACL,
619 FALSE)) // not a default DACL
620 {
621 ERR("SetSecurityDescriptorDacl Error %lu\n", GetLastError());
622 HeapFree(GetProcessHeap(), 0, pMem);
623 return STATUS_UNSUCCESSFUL;
624 }
625
626 psa->nLength = sizeof(SECURITY_ATTRIBUTES);
627 psa->lpSecurityDescriptor = SecurityDescriptor;
628 psa->bInheritHandle = FALSE;
629
630 *ppsa = psa;
631
632 return STATUS_SUCCESS;
633 }
634
635 static
636 VOID
637 DestroyLogoffSecurityAttributes(
638 IN PSECURITY_ATTRIBUTES psa)
639 {
640 if (psa)
641 {
642 HeapFree(GetProcessHeap(), 0, psa);
643 }
644 }
645
646
647 static
648 NTSTATUS
649 HandleLogoff(
650 IN OUT PWLSESSION Session,
651 IN UINT Flags)
652 {
653 PLOGOFF_SHUTDOWN_DATA LSData;
654 PSECURITY_ATTRIBUTES psa;
655 HANDLE hThread;
656 DWORD exitCode;
657 NTSTATUS Status;
658
659 DisplayStatusMessage(Session, Session->WinlogonDesktop, IDS_SAVEYOURSETTINGS);
660
661 /* Prepare data for logoff thread */
662 LSData = HeapAlloc(GetProcessHeap(), 0, sizeof(LOGOFF_SHUTDOWN_DATA));
663 if (!LSData)
664 {
665 ERR("Failed to allocate mem for thread data\n");
666 return STATUS_NO_MEMORY;
667 }
668 LSData->Flags = Flags;
669 LSData->Session = Session;
670
671 Status = CreateLogoffSecurityAttributes(&psa);
672 if (!NT_SUCCESS(Status))
673 {
674 ERR("Failed to create a required security descriptor. Status 0x%08lx\n", Status);
675 HeapFree(GetProcessHeap(), 0, LSData);
676 return Status;
677 }
678
679 /* Run logoff thread */
680 hThread = CreateThread(psa, 0, LogoffShutdownThread, (LPVOID)LSData, 0, NULL);
681
682 /* we're done with the SECURITY_DESCRIPTOR */
683 DestroyLogoffSecurityAttributes(psa);
684 psa = NULL;
685
686 if (!hThread)
687 {
688 ERR("Unable to create logoff thread, error %lu\n", GetLastError());
689 HeapFree(GetProcessHeap(), 0, LSData);
690 return STATUS_UNSUCCESSFUL;
691 }
692 WaitForSingleObject(hThread, INFINITE);
693 HeapFree(GetProcessHeap(), 0, LSData);
694 if (!GetExitCodeThread(hThread, &exitCode))
695 {
696 ERR("Unable to get exit code of logoff thread (error %lu)\n", GetLastError());
697 CloseHandle(hThread);
698 return STATUS_UNSUCCESSFUL;
699 }
700 CloseHandle(hThread);
701 if (exitCode == 0)
702 {
703 ERR("Logoff thread returned failure\n");
704 return STATUS_UNSUCCESSFUL;
705 }
706
707 UnloadUserProfile(Session->UserToken, Session->hProfileInfo);
708 CloseHandle(Session->UserToken);
709 UpdatePerUserSystemParameters(0, FALSE);
710 Session->LogonState = STATE_LOGGED_OFF;
711 Session->UserToken = NULL;
712 return STATUS_SUCCESS;
713 }
714
715 static
716 INT_PTR
717 CALLBACK
718 ShutdownComputerWindowProc(
719 IN HWND hwndDlg,
720 IN UINT uMsg,
721 IN WPARAM wParam,
722 IN LPARAM lParam)
723 {
724 UNREFERENCED_PARAMETER(lParam);
725
726 switch (uMsg)
727 {
728 case WM_COMMAND:
729 {
730 switch (LOWORD(wParam))
731 {
732 case IDC_BTNSHTDOWNCOMPUTER:
733 EndDialog(hwndDlg, IDC_BTNSHTDOWNCOMPUTER);
734 return TRUE;
735 }
736 break;
737 }
738 case WM_INITDIALOG:
739 {
740 RemoveMenu(GetSystemMenu(hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND);
741 SetFocus(GetDlgItem(hwndDlg, IDC_BTNSHTDOWNCOMPUTER));
742 return TRUE;
743 }
744 }
745 return FALSE;
746 }
747
748 static
749 VOID
750 UninitializeSAS(
751 IN OUT PWLSESSION Session)
752 {
753 if (Session->SASWindow)
754 {
755 DestroyWindow(Session->SASWindow);
756 Session->SASWindow = NULL;
757 }
758 if (Session->hEndOfScreenSaverThread)
759 SetEvent(Session->hEndOfScreenSaverThread);
760 UnregisterClassW(WINLOGON_SAS_CLASS, hAppInstance);
761 }
762
763 NTSTATUS
764 HandleShutdown(
765 IN OUT PWLSESSION Session,
766 IN DWORD wlxAction)
767 {
768 PLOGOFF_SHUTDOWN_DATA LSData;
769 HANDLE hThread;
770 DWORD exitCode;
771
772 DisplayStatusMessage(Session, Session->WinlogonDesktop, IDS_REACTOSISSHUTTINGDOWN);
773
774 /* Prepare data for shutdown thread */
775 LSData = HeapAlloc(GetProcessHeap(), 0, sizeof(LOGOFF_SHUTDOWN_DATA));
776 if (!LSData)
777 {
778 ERR("Failed to allocate mem for thread data\n");
779 return STATUS_NO_MEMORY;
780 }
781 if (wlxAction == WLX_SAS_ACTION_SHUTDOWN_POWER_OFF)
782 LSData->Flags = EWX_POWEROFF;
783 else if (wlxAction == WLX_SAS_ACTION_SHUTDOWN_REBOOT)
784 LSData->Flags = EWX_REBOOT;
785 else
786 LSData->Flags = EWX_SHUTDOWN;
787 LSData->Session = Session;
788
789 /* Run shutdown thread */
790 hThread = CreateThread(NULL, 0, LogoffShutdownThread, (LPVOID)LSData, 0, NULL);
791 if (!hThread)
792 {
793 ERR("Unable to create shutdown thread, error %lu\n", GetLastError());
794 HeapFree(GetProcessHeap(), 0, LSData);
795 return STATUS_UNSUCCESSFUL;
796 }
797 WaitForSingleObject(hThread, INFINITE);
798 HeapFree(GetProcessHeap(), 0, LSData);
799 if (!GetExitCodeThread(hThread, &exitCode))
800 {
801 ERR("Unable to get exit code of shutdown thread (error %lu)\n", GetLastError());
802 CloseHandle(hThread);
803 return STATUS_UNSUCCESSFUL;
804 }
805 CloseHandle(hThread);
806 if (exitCode == 0)
807 {
808 ERR("Shutdown thread returned failure\n");
809 return STATUS_UNSUCCESSFUL;
810 }
811
812 /* Destroy SAS window */
813 UninitializeSAS(Session);
814
815 FIXME("FIXME: Call SMSS API #1\n");
816 if (wlxAction == WLX_SAS_ACTION_SHUTDOWN_REBOOT)
817 NtShutdownSystem(ShutdownReboot);
818 else
819 {
820 if (FALSE)
821 {
822 /* FIXME - only show this dialog if it's a shutdown and the computer doesn't support APM */
823 DialogBox(hAppInstance, MAKEINTRESOURCE(IDD_SHUTDOWNCOMPUTER), GetDesktopWindow(), ShutdownComputerWindowProc);
824 }
825 NtShutdownSystem(ShutdownNoReboot);
826 }
827 return STATUS_SUCCESS;
828 }
829
830 static
831 VOID
832 DoGenericAction(
833 IN OUT PWLSESSION Session,
834 IN DWORD wlxAction)
835 {
836 switch (wlxAction)
837 {
838 case WLX_SAS_ACTION_LOGON: /* 0x01 */
839 if (HandleLogon(Session))
840 {
841 SwitchDesktop(Session->ApplicationDesktop);
842 Session->LogonState = STATE_LOGGED_ON;
843 }
844 else
845 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
846 break;
847 case WLX_SAS_ACTION_NONE: /* 0x02 */
848 break;
849 case WLX_SAS_ACTION_LOCK_WKSTA: /* 0x03 */
850 if (Session->Gina.Functions.WlxIsLockOk(Session->Gina.Context))
851 {
852 SwitchDesktop(WLSession->WinlogonDesktop);
853 Session->LogonState = STATE_LOCKED;
854 Session->Gina.Functions.WlxDisplayLockedNotice(Session->Gina.Context);
855 }
856 break;
857 case WLX_SAS_ACTION_LOGOFF: /* 0x04 */
858 case WLX_SAS_ACTION_SHUTDOWN: /* 0x05 */
859 case WLX_SAS_ACTION_SHUTDOWN_POWER_OFF: /* 0x0a */
860 case WLX_SAS_ACTION_SHUTDOWN_REBOOT: /* 0x0b */
861 if (Session->LogonState != STATE_LOGGED_OFF)
862 {
863 if (!Session->Gina.Functions.WlxIsLogoffOk(Session->Gina.Context))
864 break;
865 SwitchDesktop(WLSession->WinlogonDesktop);
866 Session->Gina.Functions.WlxLogoff(Session->Gina.Context);
867 if (!NT_SUCCESS(HandleLogoff(Session, EWX_LOGOFF)))
868 {
869 RemoveStatusMessage(Session);
870 break;
871 }
872 }
873 if (WLX_SHUTTINGDOWN(wlxAction))
874 {
875 Session->Gina.Functions.WlxShutdown(Session->Gina.Context, wlxAction);
876 if (!NT_SUCCESS(HandleShutdown(Session, wlxAction)))
877 {
878 RemoveStatusMessage(Session);
879 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
880 }
881 }
882 else
883 {
884 RemoveStatusMessage(Session);
885 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
886 }
887 break;
888 case WLX_SAS_ACTION_TASKLIST: /* 0x07 */
889 SwitchDesktop(WLSession->ApplicationDesktop);
890 StartTaskManager(Session);
891 break;
892 case WLX_SAS_ACTION_UNLOCK_WKSTA: /* 0x08 */
893 SwitchDesktop(WLSession->ApplicationDesktop);
894 Session->LogonState = STATE_LOGGED_ON;
895 break;
896 default:
897 WARN("Unknown SAS action 0x%lx\n", wlxAction);
898 }
899 }
900
901 static
902 VOID
903 DispatchSAS(
904 IN OUT PWLSESSION Session,
905 IN DWORD dwSasType)
906 {
907 DWORD wlxAction = WLX_SAS_ACTION_NONE;
908
909 if (Session->LogonState == STATE_LOGGED_ON)
910 wlxAction = (DWORD)Session->Gina.Functions.WlxLoggedOnSAS(Session->Gina.Context, dwSasType, NULL);
911 else if (Session->LogonState == STATE_LOCKED)
912 wlxAction = (DWORD)Session->Gina.Functions.WlxWkstaLockedSAS(Session->Gina.Context, dwSasType);
913 else
914 {
915 /* Display a new dialog (if necessary) */
916 switch (dwSasType)
917 {
918 case WLX_SAS_TYPE_TIMEOUT: /* 0x00 */
919 {
920 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
921 break;
922 }
923 default:
924 {
925 PSID LogonSid = NULL; /* FIXME */
926
927 Session->Options = 0;
928
929 wlxAction = (DWORD)Session->Gina.Functions.WlxLoggedOutSAS(
930 Session->Gina.Context,
931 Session->SASAction,
932 &Session->LogonId,
933 LogonSid,
934 &Session->Options,
935 &Session->UserToken,
936 &Session->MprNotifyInfo,
937 (PVOID*)&Session->Profile);
938 break;
939 }
940 }
941 }
942
943 if (dwSasType == WLX_SAS_TYPE_SCRNSVR_TIMEOUT)
944 {
945 BOOL bSecure = TRUE;
946 if (!Session->Gina.Functions.WlxScreenSaverNotify(Session->Gina.Context, &bSecure))
947 {
948 /* Skip start of screen saver */
949 SetEvent(Session->hEndOfScreenSaver);
950 }
951 else
952 {
953 StartScreenSaver(Session);
954 if (bSecure)
955 DoGenericAction(Session, WLX_SAS_ACTION_LOCK_WKSTA);
956 }
957 }
958 else if (dwSasType == WLX_SAS_TYPE_SCRNSVR_ACTIVITY)
959 SetEvent(Session->hUserActivity);
960
961 DoGenericAction(Session, wlxAction);
962 }
963
964 static
965 BOOL
966 RegisterHotKeys(
967 IN PWLSESSION Session,
968 IN HWND hwndSAS)
969 {
970 /* Register Ctrl+Alt+Del Hotkey */
971 if (!RegisterHotKey(hwndSAS, HK_CTRL_ALT_DEL, MOD_CONTROL | MOD_ALT, VK_DELETE))
972 {
973 ERR("WL: Unable to register Ctrl+Alt+Del hotkey!\n");
974 return FALSE;
975 }
976
977 /* Register Ctrl+Shift+Esc (optional) */
978 Session->TaskManHotkey = RegisterHotKey(hwndSAS, HK_CTRL_SHIFT_ESC, MOD_CONTROL | MOD_SHIFT, VK_ESCAPE);
979 if (!Session->TaskManHotkey)
980 WARN("WL: Warning: Unable to register Ctrl+Alt+Esc hotkey!\n");
981 return TRUE;
982 }
983
984 static
985 BOOL
986 UnregisterHotKeys(
987 IN PWLSESSION Session,
988 IN HWND hwndSAS)
989 {
990 /* Unregister hotkeys */
991 UnregisterHotKey(hwndSAS, HK_CTRL_ALT_DEL);
992
993 if (Session->TaskManHotkey)
994 UnregisterHotKey(hwndSAS, HK_CTRL_SHIFT_ESC);
995
996 return TRUE;
997 }
998
999 static
1000 NTSTATUS
1001 CheckForShutdownPrivilege(
1002 IN DWORD RequestingProcessId)
1003 {
1004 HANDLE Process;
1005 HANDLE Token;
1006 BOOL CheckResult;
1007 PPRIVILEGE_SET PrivSet;
1008
1009 TRACE("CheckForShutdownPrivilege()\n");
1010
1011 Process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, RequestingProcessId);
1012 if (!Process)
1013 {
1014 WARN("OpenProcess() failed with error %lu\n", GetLastError());
1015 return STATUS_INVALID_HANDLE;
1016 }
1017 if (!OpenProcessToken(Process, TOKEN_QUERY, &Token))
1018 {
1019 WARN("OpenProcessToken() failed with error %lu\n", GetLastError());
1020 CloseHandle(Process);
1021 return STATUS_INVALID_HANDLE;
1022 }
1023 CloseHandle(Process);
1024 PrivSet = HeapAlloc(GetProcessHeap(), 0, sizeof(PRIVILEGE_SET) + sizeof(LUID_AND_ATTRIBUTES));
1025 if (!PrivSet)
1026 {
1027 ERR("Failed to allocate mem for privilege set\n");
1028 CloseHandle(Token);
1029 return STATUS_NO_MEMORY;
1030 }
1031 PrivSet->PrivilegeCount = 1;
1032 PrivSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
1033 if (!LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &PrivSet->Privilege[0].Luid))
1034 {
1035 WARN("LookupPrivilegeValue() failed with error %lu\n", GetLastError());
1036 HeapFree(GetProcessHeap(), 0, PrivSet);
1037 CloseHandle(Token);
1038 return STATUS_UNSUCCESSFUL;
1039 }
1040 if (!PrivilegeCheck(Token, PrivSet, &CheckResult))
1041 {
1042 WARN("PrivilegeCheck() failed with error %lu\n", GetLastError());
1043 HeapFree(GetProcessHeap(), 0, PrivSet);
1044 CloseHandle(Token);
1045 return STATUS_ACCESS_DENIED;
1046 }
1047 HeapFree(GetProcessHeap(), 0, PrivSet);
1048 CloseHandle(Token);
1049
1050 if (!CheckResult)
1051 {
1052 WARN("SE_SHUTDOWN privilege not enabled\n");
1053 return STATUS_ACCESS_DENIED;
1054 }
1055 return STATUS_SUCCESS;
1056 }
1057
1058 BOOL
1059 WINAPI
1060 HandleMessageBeep(UINT uType)
1061 {
1062 LPWSTR EventName;
1063
1064 switch(uType)
1065 {
1066 case 0xFFFFFFFF:
1067 EventName = NULL;
1068 break;
1069 case MB_OK:
1070 EventName = L"SystemDefault";
1071 break;
1072 case MB_ICONASTERISK:
1073 EventName = L"SystemAsterisk";
1074 break;
1075 case MB_ICONEXCLAMATION:
1076 EventName = L"SystemExclamation";
1077 break;
1078 case MB_ICONHAND:
1079 EventName = L"SystemHand";
1080 break;
1081 case MB_ICONQUESTION:
1082 EventName = L"SystemQuestion";
1083 break;
1084 default:
1085 WARN("Unhandled type %d\n", uType);
1086 EventName = L"SystemDefault";
1087 }
1088
1089 return PlaySoundRoutine(EventName, FALSE, SND_ALIAS | SND_NOWAIT | SND_NOSTOP | SND_ASYNC);
1090 }
1091
1092 static
1093 LRESULT
1094 CALLBACK
1095 SASWindowProc(
1096 IN HWND hwndDlg,
1097 IN UINT uMsg,
1098 IN WPARAM wParam,
1099 IN LPARAM lParam)
1100 {
1101 PWLSESSION Session = (PWLSESSION)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
1102
1103 switch (uMsg)
1104 {
1105 case WM_HOTKEY:
1106 {
1107 switch (lParam)
1108 {
1109 case MAKELONG(MOD_CONTROL | MOD_ALT, VK_DELETE):
1110 {
1111 TRACE("SAS: CONTROL+ALT+DELETE\n");
1112 if (!Session->Gina.UseCtrlAltDelete)
1113 break;
1114 PostMessageW(Session->SASWindow, WLX_WM_SAS, WLX_SAS_TYPE_CTRL_ALT_DEL, 0);
1115 return TRUE;
1116 }
1117 case MAKELONG(MOD_CONTROL | MOD_SHIFT, VK_ESCAPE):
1118 {
1119 TRACE("SAS: CONTROL+SHIFT+ESCAPE\n");
1120 DoGenericAction(Session, WLX_SAS_ACTION_TASKLIST);
1121 return TRUE;
1122 }
1123 }
1124 break;
1125 }
1126 case WM_CREATE:
1127 {
1128 /* Get the session pointer from the create data */
1129 Session = (PWLSESSION)((LPCREATESTRUCT)lParam)->lpCreateParams;
1130
1131 /* Save the Session pointer */
1132 SetWindowLongPtrW(hwndDlg, GWLP_USERDATA, (LONG_PTR)Session);
1133 if (GetSetupType())
1134 return TRUE;
1135 return RegisterHotKeys(Session, hwndDlg);
1136 }
1137 case WM_DESTROY:
1138 {
1139 if (!GetSetupType())
1140 UnregisterHotKeys(Session, hwndDlg);
1141 return TRUE;
1142 }
1143 case WM_SETTINGCHANGE:
1144 {
1145 UINT uiAction = (UINT)wParam;
1146 if (uiAction == SPI_SETSCREENSAVETIMEOUT
1147 || uiAction == SPI_SETSCREENSAVEACTIVE)
1148 {
1149 SetEvent(Session->hScreenSaverParametersChanged);
1150 }
1151 return TRUE;
1152 }
1153 case WM_LOGONNOTIFY:
1154 {
1155 switch(wParam)
1156 {
1157 case LN_MESSAGE_BEEP:
1158 {
1159 return HandleMessageBeep(lParam);
1160 }
1161 case LN_SHELL_EXITED:
1162 {
1163 /* lParam is the exit code */
1164 if(lParam != 1)
1165 {
1166 SetTimer(hwndDlg, 1, 1000, NULL);
1167 }
1168 break;
1169 }
1170 case LN_START_SCREENSAVE:
1171 {
1172 DispatchSAS(Session, WLX_SAS_TYPE_SCRNSVR_TIMEOUT);
1173 break;
1174 }
1175 case LN_LOCK_WORKSTATION:
1176 {
1177 DoGenericAction(Session, WLX_SAS_ACTION_LOCK_WKSTA);
1178 break;
1179 }
1180 default:
1181 {
1182 ERR("WM_LOGONNOTIFY case %d is unimplemented\n", wParam);
1183 }
1184 }
1185 return 0;
1186 }
1187 case WM_TIMER:
1188 {
1189 if (wParam == 1)
1190 {
1191 KillTimer(hwndDlg, 1);
1192 StartUserShell(Session);
1193 }
1194 break;
1195 }
1196 case WLX_WM_SAS:
1197 {
1198 DispatchSAS(Session, (DWORD)wParam);
1199 return TRUE;
1200 }
1201 case PM_WINLOGON_EXITWINDOWS:
1202 {
1203 UINT Flags = (UINT)lParam;
1204 UINT Action = Flags & EWX_ACTION_MASK;
1205 DWORD wlxAction;
1206
1207 /* Check parameters */
1208 switch (Action)
1209 {
1210 case EWX_LOGOFF: wlxAction = WLX_SAS_ACTION_LOGOFF; break;
1211 case EWX_SHUTDOWN: wlxAction = WLX_SAS_ACTION_SHUTDOWN; break;
1212 case EWX_REBOOT: wlxAction = WLX_SAS_ACTION_SHUTDOWN_REBOOT; break;
1213 case EWX_POWEROFF: wlxAction = WLX_SAS_ACTION_SHUTDOWN_POWER_OFF; break;
1214 default:
1215 {
1216 ERR("Invalid ExitWindows action 0x%x\n", Action);
1217 return STATUS_INVALID_PARAMETER;
1218 }
1219 }
1220
1221 if (WLX_SHUTTINGDOWN(wlxAction))
1222 {
1223 NTSTATUS Status = CheckForShutdownPrivilege((DWORD)wParam);
1224 if (!NT_SUCCESS(Status))
1225 return Status;
1226 }
1227 DoGenericAction(Session, wlxAction);
1228 return 1;
1229 }
1230 }
1231
1232 return DefWindowProc(hwndDlg, uMsg, wParam, lParam);
1233 }
1234
1235 BOOL
1236 InitializeSAS(
1237 IN OUT PWLSESSION Session)
1238 {
1239 WNDCLASSEXW swc;
1240 BOOL ret = FALSE;
1241
1242 if (!SwitchDesktop(Session->WinlogonDesktop))
1243 {
1244 ERR("WL: Failed to switch to winlogon desktop\n");
1245 goto cleanup;
1246 }
1247
1248 /* Register SAS window class */
1249 swc.cbSize = sizeof(WNDCLASSEXW);
1250 swc.style = CS_SAVEBITS;
1251 swc.lpfnWndProc = SASWindowProc;
1252 swc.cbClsExtra = 0;
1253 swc.cbWndExtra = 0;
1254 swc.hInstance = hAppInstance;
1255 swc.hIcon = NULL;
1256 swc.hCursor = NULL;
1257 swc.hbrBackground = NULL;
1258 swc.lpszMenuName = NULL;
1259 swc.lpszClassName = WINLOGON_SAS_CLASS;
1260 swc.hIconSm = NULL;
1261 if (RegisterClassExW(&swc) == 0)
1262 {
1263 ERR("WL: Failed to register SAS window class\n");
1264 goto cleanup;
1265 }
1266
1267 /* Create invisible SAS window */
1268 Session->SASWindow = CreateWindowExW(
1269 0,
1270 WINLOGON_SAS_CLASS,
1271 WINLOGON_SAS_TITLE,
1272 WS_POPUP,
1273 0, 0, 0, 0, 0, 0,
1274 hAppInstance, Session);
1275 if (!Session->SASWindow)
1276 {
1277 ERR("WL: Failed to create SAS window\n");
1278 goto cleanup;
1279 }
1280
1281 /* Register SAS window to receive SAS notifications */
1282 if (!SetLogonNotifyWindow(Session->SASWindow, Session->InteractiveWindowStation))
1283 {
1284 ERR("WL: Failed to register SAS window\n");
1285 goto cleanup;
1286 }
1287
1288 if (!SetDefaultLanguage(FALSE))
1289 return FALSE;
1290
1291 ret = TRUE;
1292
1293 cleanup:
1294 if (!ret)
1295 UninitializeSAS(Session);
1296 return ret;
1297 }