0409200bd92a46aa1fa46c4ff68b1976b3e1d640
[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 if (Session->LogonState == STATE_LOGGED_OFF)
849 {
850 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
851 }
852 break;
853 case WLX_SAS_ACTION_LOCK_WKSTA: /* 0x03 */
854 if (Session->Gina.Functions.WlxIsLockOk(Session->Gina.Context))
855 {
856 SwitchDesktop(WLSession->WinlogonDesktop);
857 Session->LogonState = STATE_LOCKED;
858 Session->Gina.Functions.WlxDisplayLockedNotice(Session->Gina.Context);
859 }
860 break;
861 case WLX_SAS_ACTION_LOGOFF: /* 0x04 */
862 case WLX_SAS_ACTION_SHUTDOWN: /* 0x05 */
863 case WLX_SAS_ACTION_SHUTDOWN_POWER_OFF: /* 0x0a */
864 case WLX_SAS_ACTION_SHUTDOWN_REBOOT: /* 0x0b */
865 if (Session->LogonState != STATE_LOGGED_OFF)
866 {
867 if (!Session->Gina.Functions.WlxIsLogoffOk(Session->Gina.Context))
868 break;
869 SwitchDesktop(WLSession->WinlogonDesktop);
870 Session->Gina.Functions.WlxLogoff(Session->Gina.Context);
871 if (!NT_SUCCESS(HandleLogoff(Session, EWX_LOGOFF)))
872 {
873 RemoveStatusMessage(Session);
874 break;
875 }
876 }
877 if (WLX_SHUTTINGDOWN(wlxAction))
878 {
879 Session->Gina.Functions.WlxShutdown(Session->Gina.Context, wlxAction);
880 if (!NT_SUCCESS(HandleShutdown(Session, wlxAction)))
881 {
882 RemoveStatusMessage(Session);
883 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
884 }
885 }
886 else
887 {
888 RemoveStatusMessage(Session);
889 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
890 }
891 break;
892 case WLX_SAS_ACTION_TASKLIST: /* 0x07 */
893 SwitchDesktop(WLSession->ApplicationDesktop);
894 StartTaskManager(Session);
895 break;
896 case WLX_SAS_ACTION_UNLOCK_WKSTA: /* 0x08 */
897 SwitchDesktop(WLSession->ApplicationDesktop);
898 Session->LogonState = STATE_LOGGED_ON;
899 break;
900 default:
901 WARN("Unknown SAS action 0x%lx\n", wlxAction);
902 }
903 }
904
905 static
906 VOID
907 DispatchSAS(
908 IN OUT PWLSESSION Session,
909 IN DWORD dwSasType)
910 {
911 DWORD wlxAction = WLX_SAS_ACTION_NONE;
912
913 if (Session->LogonState == STATE_LOGGED_ON)
914 wlxAction = (DWORD)Session->Gina.Functions.WlxLoggedOnSAS(Session->Gina.Context, dwSasType, NULL);
915 else if (Session->LogonState == STATE_LOCKED)
916 wlxAction = (DWORD)Session->Gina.Functions.WlxWkstaLockedSAS(Session->Gina.Context, dwSasType);
917 else
918 {
919 /* Display a new dialog (if necessary) */
920 switch (dwSasType)
921 {
922 case WLX_SAS_TYPE_TIMEOUT: /* 0x00 */
923 {
924 Session->Gina.Functions.WlxDisplaySASNotice(Session->Gina.Context);
925 return;
926 }
927 default:
928 {
929 PSID LogonSid = NULL; /* FIXME */
930 HWND hwnd;
931
932 hwnd = GetTopDialogWindow();
933 if (hwnd != NULL)
934 {
935 SendMessage(hwnd, WM_USER, 0, 0);
936 }
937
938 Session->Options = 0;
939
940 wlxAction = (DWORD)Session->Gina.Functions.WlxLoggedOutSAS(
941 Session->Gina.Context,
942 Session->SASAction,
943 &Session->LogonId,
944 LogonSid,
945 &Session->Options,
946 &Session->UserToken,
947 &Session->MprNotifyInfo,
948 (PVOID*)&Session->Profile);
949 break;
950 }
951 }
952 }
953
954 if (dwSasType == WLX_SAS_TYPE_SCRNSVR_TIMEOUT)
955 {
956 BOOL bSecure = TRUE;
957 if (!Session->Gina.Functions.WlxScreenSaverNotify(Session->Gina.Context, &bSecure))
958 {
959 /* Skip start of screen saver */
960 SetEvent(Session->hEndOfScreenSaver);
961 }
962 else
963 {
964 StartScreenSaver(Session);
965 if (bSecure)
966 DoGenericAction(Session, WLX_SAS_ACTION_LOCK_WKSTA);
967 }
968 }
969 else if (dwSasType == WLX_SAS_TYPE_SCRNSVR_ACTIVITY)
970 SetEvent(Session->hUserActivity);
971
972 DoGenericAction(Session, wlxAction);
973 }
974
975 static
976 BOOL
977 RegisterHotKeys(
978 IN PWLSESSION Session,
979 IN HWND hwndSAS)
980 {
981 /* Register Ctrl+Alt+Del Hotkey */
982 if (!RegisterHotKey(hwndSAS, HK_CTRL_ALT_DEL, MOD_CONTROL | MOD_ALT, VK_DELETE))
983 {
984 ERR("WL: Unable to register Ctrl+Alt+Del hotkey!\n");
985 return FALSE;
986 }
987
988 /* Register Ctrl+Shift+Esc (optional) */
989 Session->TaskManHotkey = RegisterHotKey(hwndSAS, HK_CTRL_SHIFT_ESC, MOD_CONTROL | MOD_SHIFT, VK_ESCAPE);
990 if (!Session->TaskManHotkey)
991 WARN("WL: Warning: Unable to register Ctrl+Alt+Esc hotkey!\n");
992 return TRUE;
993 }
994
995 static
996 BOOL
997 UnregisterHotKeys(
998 IN PWLSESSION Session,
999 IN HWND hwndSAS)
1000 {
1001 /* Unregister hotkeys */
1002 UnregisterHotKey(hwndSAS, HK_CTRL_ALT_DEL);
1003
1004 if (Session->TaskManHotkey)
1005 UnregisterHotKey(hwndSAS, HK_CTRL_SHIFT_ESC);
1006
1007 return TRUE;
1008 }
1009
1010 static
1011 NTSTATUS
1012 CheckForShutdownPrivilege(
1013 IN DWORD RequestingProcessId)
1014 {
1015 HANDLE Process;
1016 HANDLE Token;
1017 BOOL CheckResult;
1018 PPRIVILEGE_SET PrivSet;
1019
1020 TRACE("CheckForShutdownPrivilege()\n");
1021
1022 Process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, RequestingProcessId);
1023 if (!Process)
1024 {
1025 WARN("OpenProcess() failed with error %lu\n", GetLastError());
1026 return STATUS_INVALID_HANDLE;
1027 }
1028 if (!OpenProcessToken(Process, TOKEN_QUERY, &Token))
1029 {
1030 WARN("OpenProcessToken() failed with error %lu\n", GetLastError());
1031 CloseHandle(Process);
1032 return STATUS_INVALID_HANDLE;
1033 }
1034 CloseHandle(Process);
1035 PrivSet = HeapAlloc(GetProcessHeap(), 0, sizeof(PRIVILEGE_SET) + sizeof(LUID_AND_ATTRIBUTES));
1036 if (!PrivSet)
1037 {
1038 ERR("Failed to allocate mem for privilege set\n");
1039 CloseHandle(Token);
1040 return STATUS_NO_MEMORY;
1041 }
1042 PrivSet->PrivilegeCount = 1;
1043 PrivSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
1044 if (!LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &PrivSet->Privilege[0].Luid))
1045 {
1046 WARN("LookupPrivilegeValue() failed with error %lu\n", GetLastError());
1047 HeapFree(GetProcessHeap(), 0, PrivSet);
1048 CloseHandle(Token);
1049 return STATUS_UNSUCCESSFUL;
1050 }
1051 if (!PrivilegeCheck(Token, PrivSet, &CheckResult))
1052 {
1053 WARN("PrivilegeCheck() failed with error %lu\n", GetLastError());
1054 HeapFree(GetProcessHeap(), 0, PrivSet);
1055 CloseHandle(Token);
1056 return STATUS_ACCESS_DENIED;
1057 }
1058 HeapFree(GetProcessHeap(), 0, PrivSet);
1059 CloseHandle(Token);
1060
1061 if (!CheckResult)
1062 {
1063 WARN("SE_SHUTDOWN privilege not enabled\n");
1064 return STATUS_ACCESS_DENIED;
1065 }
1066 return STATUS_SUCCESS;
1067 }
1068
1069 BOOL
1070 WINAPI
1071 HandleMessageBeep(UINT uType)
1072 {
1073 LPWSTR EventName;
1074
1075 switch(uType)
1076 {
1077 case 0xFFFFFFFF:
1078 EventName = NULL;
1079 break;
1080 case MB_OK:
1081 EventName = L"SystemDefault";
1082 break;
1083 case MB_ICONASTERISK:
1084 EventName = L"SystemAsterisk";
1085 break;
1086 case MB_ICONEXCLAMATION:
1087 EventName = L"SystemExclamation";
1088 break;
1089 case MB_ICONHAND:
1090 EventName = L"SystemHand";
1091 break;
1092 case MB_ICONQUESTION:
1093 EventName = L"SystemQuestion";
1094 break;
1095 default:
1096 WARN("Unhandled type %d\n", uType);
1097 EventName = L"SystemDefault";
1098 }
1099
1100 return PlaySoundRoutine(EventName, FALSE, SND_ALIAS | SND_NOWAIT | SND_NOSTOP | SND_ASYNC);
1101 }
1102
1103 static
1104 LRESULT
1105 CALLBACK
1106 SASWindowProc(
1107 IN HWND hwndDlg,
1108 IN UINT uMsg,
1109 IN WPARAM wParam,
1110 IN LPARAM lParam)
1111 {
1112 PWLSESSION Session = (PWLSESSION)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
1113
1114 switch (uMsg)
1115 {
1116 case WM_HOTKEY:
1117 {
1118 switch (lParam)
1119 {
1120 case MAKELONG(MOD_CONTROL | MOD_ALT, VK_DELETE):
1121 {
1122 TRACE("SAS: CONTROL+ALT+DELETE\n");
1123 if (!Session->Gina.UseCtrlAltDelete)
1124 break;
1125 PostMessageW(Session->SASWindow, WLX_WM_SAS, WLX_SAS_TYPE_CTRL_ALT_DEL, 0);
1126 return TRUE;
1127 }
1128 case MAKELONG(MOD_CONTROL | MOD_SHIFT, VK_ESCAPE):
1129 {
1130 TRACE("SAS: CONTROL+SHIFT+ESCAPE\n");
1131 DoGenericAction(Session, WLX_SAS_ACTION_TASKLIST);
1132 return TRUE;
1133 }
1134 }
1135 break;
1136 }
1137 case WM_CREATE:
1138 {
1139 /* Get the session pointer from the create data */
1140 Session = (PWLSESSION)((LPCREATESTRUCT)lParam)->lpCreateParams;
1141
1142 /* Save the Session pointer */
1143 SetWindowLongPtrW(hwndDlg, GWLP_USERDATA, (LONG_PTR)Session);
1144 if (GetSetupType())
1145 return TRUE;
1146 return RegisterHotKeys(Session, hwndDlg);
1147 }
1148 case WM_DESTROY:
1149 {
1150 if (!GetSetupType())
1151 UnregisterHotKeys(Session, hwndDlg);
1152 return TRUE;
1153 }
1154 case WM_SETTINGCHANGE:
1155 {
1156 UINT uiAction = (UINT)wParam;
1157 if (uiAction == SPI_SETSCREENSAVETIMEOUT
1158 || uiAction == SPI_SETSCREENSAVEACTIVE)
1159 {
1160 SetEvent(Session->hScreenSaverParametersChanged);
1161 }
1162 return TRUE;
1163 }
1164 case WM_LOGONNOTIFY:
1165 {
1166 switch(wParam)
1167 {
1168 case LN_MESSAGE_BEEP:
1169 {
1170 return HandleMessageBeep(lParam);
1171 }
1172 case LN_SHELL_EXITED:
1173 {
1174 /* lParam is the exit code */
1175 if(lParam != 1)
1176 {
1177 SetTimer(hwndDlg, 1, 1000, NULL);
1178 }
1179 break;
1180 }
1181 case LN_START_SCREENSAVE:
1182 {
1183 DispatchSAS(Session, WLX_SAS_TYPE_SCRNSVR_TIMEOUT);
1184 break;
1185 }
1186 case LN_LOCK_WORKSTATION:
1187 {
1188 DoGenericAction(Session, WLX_SAS_ACTION_LOCK_WKSTA);
1189 break;
1190 }
1191 default:
1192 {
1193 ERR("WM_LOGONNOTIFY case %d is unimplemented\n", wParam);
1194 }
1195 }
1196 return 0;
1197 }
1198 case WM_TIMER:
1199 {
1200 if (wParam == 1)
1201 {
1202 KillTimer(hwndDlg, 1);
1203 StartUserShell(Session);
1204 }
1205 break;
1206 }
1207 case WLX_WM_SAS:
1208 {
1209 DispatchSAS(Session, (DWORD)wParam);
1210 return TRUE;
1211 }
1212 case PM_WINLOGON_EXITWINDOWS:
1213 {
1214 UINT Flags = (UINT)lParam;
1215 UINT Action = Flags & EWX_ACTION_MASK;
1216 DWORD wlxAction;
1217
1218 /* Check parameters */
1219 switch (Action)
1220 {
1221 case EWX_LOGOFF: wlxAction = WLX_SAS_ACTION_LOGOFF; break;
1222 case EWX_SHUTDOWN: wlxAction = WLX_SAS_ACTION_SHUTDOWN; break;
1223 case EWX_REBOOT: wlxAction = WLX_SAS_ACTION_SHUTDOWN_REBOOT; break;
1224 case EWX_POWEROFF: wlxAction = WLX_SAS_ACTION_SHUTDOWN_POWER_OFF; break;
1225 default:
1226 {
1227 ERR("Invalid ExitWindows action 0x%x\n", Action);
1228 return STATUS_INVALID_PARAMETER;
1229 }
1230 }
1231
1232 if (WLX_SHUTTINGDOWN(wlxAction))
1233 {
1234 NTSTATUS Status = CheckForShutdownPrivilege((DWORD)wParam);
1235 if (!NT_SUCCESS(Status))
1236 return Status;
1237 }
1238 DoGenericAction(Session, wlxAction);
1239 return 1;
1240 }
1241 }
1242
1243 return DefWindowProc(hwndDlg, uMsg, wParam, lParam);
1244 }
1245
1246 BOOL
1247 InitializeSAS(
1248 IN OUT PWLSESSION Session)
1249 {
1250 WNDCLASSEXW swc;
1251 BOOL ret = FALSE;
1252
1253 if (!SwitchDesktop(Session->WinlogonDesktop))
1254 {
1255 ERR("WL: Failed to switch to winlogon desktop\n");
1256 goto cleanup;
1257 }
1258
1259 /* Register SAS window class */
1260 swc.cbSize = sizeof(WNDCLASSEXW);
1261 swc.style = CS_SAVEBITS;
1262 swc.lpfnWndProc = SASWindowProc;
1263 swc.cbClsExtra = 0;
1264 swc.cbWndExtra = 0;
1265 swc.hInstance = hAppInstance;
1266 swc.hIcon = NULL;
1267 swc.hCursor = NULL;
1268 swc.hbrBackground = NULL;
1269 swc.lpszMenuName = NULL;
1270 swc.lpszClassName = WINLOGON_SAS_CLASS;
1271 swc.hIconSm = NULL;
1272 if (RegisterClassExW(&swc) == 0)
1273 {
1274 ERR("WL: Failed to register SAS window class\n");
1275 goto cleanup;
1276 }
1277
1278 /* Create invisible SAS window */
1279 Session->SASWindow = CreateWindowExW(
1280 0,
1281 WINLOGON_SAS_CLASS,
1282 WINLOGON_SAS_TITLE,
1283 WS_POPUP,
1284 0, 0, 0, 0, 0, 0,
1285 hAppInstance, Session);
1286 if (!Session->SASWindow)
1287 {
1288 ERR("WL: Failed to create SAS window\n");
1289 goto cleanup;
1290 }
1291
1292 /* Register SAS window to receive SAS notifications */
1293 if (!SetLogonNotifyWindow(Session->SASWindow, Session->InteractiveWindowStation))
1294 {
1295 ERR("WL: Failed to register SAS window\n");
1296 goto cleanup;
1297 }
1298
1299 if (!SetDefaultLanguage(FALSE))
1300 return FALSE;
1301
1302 ret = TRUE;
1303
1304 cleanup:
1305 if (!ret)
1306 UninitializeSAS(Session);
1307 return ret;
1308 }