-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRDPWrapKit.iss
More file actions
8359 lines (7639 loc) · 324 KB
/
Copy pathRDPWrapKit.iss
File metadata and controls
8359 lines (7639 loc) · 324 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
; =========================================================================
; RDPWrapKit - Local RDP Management Suite
; =========================================================================
;
; PURPOSE:
; This Inno Setup installer provides a comprehensive solution for setting
; up TermWrap on Windows systems, enabling multiple concurrent
; Remote Desktop sessions on non-Server editions of Windows.
;
; KEY FEATURES:
; - Automatic installation of TermWrap (llccd)
; - VC++ Redistributable dependency management
; - User account creation with automatic RDP shortcuts
; - Security hardening (Windows Defender exclusions, secure credential handling)
; - Create Shortcuts flow for existing users and shortcuts
; - Complete uninstallation support with registry cleanup
;
; SECURITY CONSIDERATIONS:
; - All PowerShell commands run with ExecutionPolicy Bypass for reliability
; - Passwords are encrypted using SecureString before writing to temp files
; - Temporary files containing sensitive data are deleted after use
; - Admin privileges required for system modifications
;
; ARCHITECTURE:
; - Uses centralized constants for executables, paths, and URLs
; - Helper functions for PowerShell/CMD execution reduce code duplication
; - Progressive UI with step-by-step feedback during installation
; - Lazy loading of user lists to avoid blocking wizard initialization
; =========================================================================
#define APP_VERSION_STRING "0.5.8"
#define APP_VERSION_FILEINFO "0.5.8.0"
; Preprocessor captures source TermWrap.dll metadata at compile time for runtime comparison.
#define SourceTermWrapVersion GetVersionNumbersString("third_party\termwrap_release\TermWrap.dll")
#define SourceTermWrapSize FileSize("third_party\termwrap_release\TermWrap.dll")
; RdpSignTool.exe is compiled ahead-of-time from scripts\RdpSignTool.cs.
; Run scripts\build_rdpcrypt.ps1 before compiling this installer.
; This keeps the 19KB binary out of git while enabling a clean build.
[Setup]
AppName=RDPWrapKit
AppVersion={#APP_VERSION_STRING}
VersionInfoVersion={#APP_VERSION_FILEINFO}
AppPublisher=cpdx4
AppPublisherURL=https://cpdx4.github.io/RDPWrapKit/
AppSupportURL=https://github.com/cpdx4/RDPWrapKit/issues
AppUpdatesURL=https://github.com/cpdx4/RDPWrapKit/releases
AppCopyright=Copyright (C) 2024-2026 RDPWrapKit Project
DefaultDirName={commonpf64}\RDPWrapKit
OutputBaseFilename=RDPWrapKit-Setup
Compression=lzma
SolidCompression=yes
PrivilegesRequired=admin
ArchitecturesInstallIn64BitMode=x64compatible
CloseApplications=yes
RestartApplications=yes
CloseApplicationsFilter=*.exe,*.chm
WizardStyle=modern dark
SetupIconFile="assets\RDPWrapKitIcon.ico"
WizardBackImageFile="assets\RDPWrapInstallerBG.bmp"
WizardBackColor=#0b1018
[Files]
; Icon file always extracted to temp for welcome page display.
; TermWrap files only copied when DoInstallTermWrap = True (checked via ShouldInstallFiles).
Source: "third_party\termwrap_release\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Check: ShouldInstallFiles
Source: "output\RdpSignTool.exe"; DestDir: "{tmp}"; Flags: ignoreversion dontcopy
Source: "assets\RDPWrapKitIcon.bmp"; DestDir: "{tmp}"; Flags: ignoreversion dontcopy
Source: "assets\rdp_edit_save.bmp"; DestDir: "{tmp}"; Flags: ignoreversion skipifsourcedoesntexist dontcopy
Source: "assets\RDPWrapInstallerBG.bmp"; DestDir: "{tmp}"; Flags: ignoreversion dontcopy
[Registry]
; Enable RDP (fDenyTSConnections=0). Removed on uninstall via uninsdeletevalue.
Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Terminal Server"; ValueType: dword; ValueName: "fDenyTSConnections"; ValueData: 0; Flags: uninsdeletevalue; Check: ShouldApplyRegistryEntries
[Run]
; Run section is now handled in Code section for proper sequencing
[UninstallRun]
; Registry cleanup handled via uninsdeletevalue flags and Code section.
[Code]
{ Pascal Script: installer UI, validation, and install flow. }
// Forward declarations
procedure CheckAndInstallMSTSC; forward;
procedure OnCreateRdpShortcutsClick(Sender: TObject); forward;
procedure OnPrevUsersPageClick(Sender: TObject); forward;
procedure OnNextUsersPageClick(Sender: TObject); forward;
procedure UpdateUsersPageDisplay; forward;
procedure OnPrevShortcutPageClick(Sender: TObject); forward;
procedure OnNextShortcutPageClick(Sender: TObject); forward;
procedure OnShortcutCheckBoxClick(Sender: TObject); forward;
procedure BuildEditShortcutAdvancedControls; forward;
procedure UnSignRdpFile(const RdpPath: string); forward;
procedure UpdateShortcutPageDisplay; forward;
function IsValidPassword(const Password: string): String; forward;
procedure OpenTermWrap(Sender: TObject); forward;
function ValidateLocalCredential(const UserName, Password: string): Boolean; forward;
procedure OpenBSGH(Sender: TObject); forward;
procedure OpenBSSGrinders(Sender: TObject); forward;
procedure OnInstallModeChange(Sender: TObject); forward;
procedure OnFullScreenClick(Sender: TObject); forward;
procedure OnUseAllMonitorsClick(Sender: TObject); forward;
procedure OnResolutionChange(Sender: TObject); forward;
function IsTermWrapInstalled(): Boolean; forward;
function GetInstalledTermWrapVersion(): string; forward;
function GetInstalledTermWrapSize(): string; forward;
function BoolToStr(Value: Boolean): string; forward;
procedure EnsureTermServiceRunsAsNetworkService; forward;
procedure EnsureUmRdpServiceAutomatic; forward;
procedure InitInstallerLog; forward;
procedure WriteInstallerLog(const Msg: string); forward;
procedure LogSectionHeader(const Title: string); forward;
procedure LogKeyValue(const KeyName, KeyValue: string); forward;
// Logger architecture forward declarations
function GetThreadIdHex: string; forward;
function GetProcessIdHex: string; forward;
function LoggerRedact(const S: string): string; forward;
procedure LoggerWrite(const Level, Msg: string); forward;
procedure LogInfo(const Msg: string); forward;
procedure LogDebug(const Msg: string); forward;
procedure LogWarn(const Msg: string); forward;
procedure LogError(const Msg: string); forward;
procedure LogEntry(const FuncName: string); forward;
procedure LogExit(const FuncName: string); forward;
procedure LoggerStartOp; forward;
function LoggerEndOp: Cardinal; forward;
procedure LogFileOp(const Operation, FilePath: string; const Success: Boolean; const Extra: string); forward;
procedure LogRegOp(const Operation, RegKey, RegValue: string; const Success: Boolean); forward;
procedure LogServiceOp(const Operation, ServiceName: string; const ResultCode: Integer); forward;
procedure LogSim(const ScenarioText: string); forward;
// Debug-enriched command execution forward declarations
function RunCmdCapture(const CmdLine, OutTag: string): Integer; forward;
function RunNetHiddenCapture(const Params, OutTag: string): Integer; forward;
var
Page_InstallOptions: TWizardPage;
WelcomePage: TWizardPage;
UserPage: TInputQueryWizardPage;
// AdvancedPage removed - single create-shortcuts page retained
EditSystemwideSettingsPage: TWizardPage; // Main Edit System-wide settings page
Page_CreateShortcutsForExistingUsers: TWizardPage; // Create RDP desktop shortcuts
LocalUsersList: TStringList; // login usernames
LocalUserDisplayList: TStringList; // display labels (email if online account, else same as username)
CreateShortcutsControlsBuilt: Boolean;
UserCheckBoxes: array of TCheckBox;
UserPasswordEdits: array of TEdit;
UserPasswordStatus: array of TLabel;
// Pagination for existing user list display
CurrentUserPage: Integer;
Tool1PrevButton: TButton;
Tool1NextButton: TButton;
Tool1PageLabel: TLabel;
UsersPerPage: Integer;
ShortcutsList: TStringList;
InstallLogPath: string;
AddMoreRadio: TRadioButton;
DoneRadio: TRadioButton;
// New welcome/options controls
rbInstall: TRadioButton;
rbEditSystemwideSettings: TRadioButton;
rbShowRDPInfo: TRadioButton;
rbUninstall: TRadioButton;
Page_ShowRDPInfo: TWizardPage;
// Show RDP Info page controls
cmbGPCompression: TComboBox;
cmbGPImageQuality: TComboBox;
StepShowRDPInfo: TLabel;
chkInstallTermWrap: TCheckBox;
chkCreateRdpShortcuts: TCheckBox;
rbCreateUsers: TRadioButton;
rbUseExistingUsers: TRadioButton;
chkInstallTermWrapHint: TLabel;
rbUseExistingUsersHint: TLabel;
InstallOptionsAutoUserSourceApplied: Boolean;
rbEditShortcutSettings: TRadioButton;
CreateRdpShortcutsGroup: TPanel;
EditShortcutPage: TWizardPage;
Page_ShortcutSettings: TWizardPage;
Page_EditShortcutAdvanced: TWizardPage;
DesktopRdpFiles: TStringList;
ShortcutCheckBoxes: array of TCheckBox;
CurrentShortcutPage: Integer;
ShortcutsPerPage: Integer;
ShortcutPrevButton: TButton;
ShortcutNextButton: TButton;
ShortcutPageLabel: TLabel;
ShortcutHeaderLabel: TLabel;
ShortcutEmptyLabel: TLabel;
EditShortcutControlsBuilt: Boolean;
EditShortcutAdvancedControlsBuilt: Boolean;
SelectedShortcutIndex: Integer;
SelectedShortcutPath: string;
SelectedShortcutPaths: TStringList;
FinishedExampleImage: TBitmapImage;
EditShortcutAdvancedImage: TBitmapImage;
EditShortcutAdvancedLabel: TLabel;
// Flags derived from welcome/options controls
DoInstallTermWrap: Boolean;
DoCreateRdpShortcuts: Boolean;
CreateUserMode: Integer; // createUserModeNew or createUserModeExisting (only used when DoCreateRdpShortcuts = True)
DoEditSystemWideSettings: Boolean;
OrigEnableRDP: Boolean;
OrigShowUsers: Boolean;
OrigPreventDuplicate: Boolean;
OrigHideSecurityWarnings: Boolean;
OrigRdpPort: Cardinal;
OptionsLabel: TLabel;
Tool1UsersHeaderLabel: TLabel; // "Users found" header
Tool1PasswordHeaderLabel: TLabel; // "Password" header
Tool1PasswordResetLink: TLabel; // Password reset link at bottom
// Controls for Edit System-wide Settings page
lblSysHeader: TLabel;
lblWinVer: TLabel;
lblWinVerName: TLabel;
lblRDPService: TLabel;
lblRDPServiceName: TLabel;
lblWinRDPVer: TLabel;
lblWinRDPVerName: TLabel;
lblWrapperVer: TLabel;
lblWrapperVerName: TLabel;
lblListenerName: TLabel;
lblListener: TLabel;
lblGenHeader: TLabel;
chkEnableRDP: TCheckBox;
chkShowUsers: TCheckBox;
chkPreventDuplicate: TCheckBox;
chkHideSecurityWarnings: TCheckBox;
lblRdpPort: TLabel;
edtRdpPort: TEdit;
lblPortDefault: TLabel;
lblActionsHeader: TLabel;
chkRestartRDP: TCheckBox;
// Progress UI on Installing page
StepsHeaderLabel: TLabel;
StepAddExcl: TLabel;
StepRemoveExcl: TLabel;
StepStopSvc: TLabel;
StepEnsureVC: TLabel;
StepInstallTermWrap: TLabel;
StepConfigureService: TLabel;
StepCreateUsers: TLabel;
StepCreateShortcuts: TLabel;
StepPreTrust: TLabel;
StepStartSvc: TLabel;
StepCheckRDP: TLabel;
StepCheckMSTSC: TLabel;
StepInstallMSTSC: TLabel;
StepRemoveFolder: TLabel;
StepUninstallTermWrap: TLabel;
StepEnableRDP: TLabel;
StepShowUsers: TLabel;
StepPreventDuplicate: TLabel;
StepSetRdpPort: TLabel;
StepRestartRDP: TLabel;
SelectedInstallMode: Integer; // installModeInstall, installModeEditShortcuts, installModeEditSystemwideSettings, installModeUninstall
DebugMode: Boolean; // Set to True to force VC++ download even if installed
DoShowMstscEdit: Boolean; // True = open mstsc /edit after writing settings (EditShortcuts path)
// Simulation marker flags (log once per run)
SimLogNoMstscShown: Boolean;
SimLogNoVCRedistShown: Boolean;
SimLogNetPsShown: Boolean;
LastLoggedPageId: Integer;
LastLoggedPageTick: Cardinal;
LastSuppressedPageLogs: Integer;
PendingDebugCleanupFiles: TStringList;
UsersList: TStringList;
CreatedUsersList: TStringList; // Store usernames to display on finish page
CurrentUserIndex: Integer;
// Layout helpers for step labels
StepLeftPos: Integer;
StepTopBase: Integer;
StepWidthVal: Integer;
StepNextTop: Integer;
// Localized group names (resolved at runtime)
GroupAdministratorsName: string;
GroupRDPUsersName: string;
// Credits / license blurb on welcome page
CreditsText: TRichEditViewer;
// Rich text control on finished page to show long completion messages
FinishedText: TLabel;
// Button to open install log on finish page
ViewLogButton: TButton;
// Flag set when Smart App Control (VerifiedAndReputablePolicyState) is detected as On
SmartAppControlIsOn: Boolean;
// Shortcut settings controls on Create RDP User Account page
lblShortcutSection: TLabel;
lblScreenSize: TLabel;
cboResolution: TComboBox;
chkFullScreen: TCheckBox;
chkUseAllMonitors: TCheckBox;
chkCopyPaste: TCheckBox;
chkSound: TCheckBox;
lblMultiShortcutEditingNote: TLabel;
chkShowMoreShortcutOptions: TCheckBox;
lblCustomWidth: TLabel;
edtCustomWidth: TEdit;
lblCustomHeight: TLabel;
edtCustomHeight: TEdit;
// Experience / performance checkboxes on Shortcut Settings page
chkExpWallpaper: TCheckBox;
chkExpFontSmooth: TCheckBox;
chkExpComposition: TCheckBox;
chkExpDragContents: TCheckBox;
chkExpMenuAnim: TCheckBox;
chkExpVisualStyles: TCheckBox;
// New shortcut name customization
lblShortcutName: TLabel;
edtShortcutName: TEdit;
lblShortcutExtension: TLabel;
// Keyboard hook settings
lblKeyboardHook: TLabel;
cboKeyboardHook: TComboBox;
// Transparent overlay for status text (replaces WizardForm.StatusLabel which can't be made transparent)
StatusOverlay: TLabel;
// Determinate progress bar tracking
StepsTotal: Integer;
StepsDone: Integer;
// Logger state globals for performance profiling and metadata
LoggerProcId: DWORD;
LoggerThreadId: DWORD;
LoggerOpStartTick: Cardinal;
LoggerOpActive: Boolean;
const
// -------------------------------------------------------------------------
// SYSTEM CONSTANTS
// -------------------------------------------------------------------------
// Windows API return codes and limits
NERR_Success = 0; // Windows NetAPI success code
MAX_SHORTCUTS = 10; // Safety limit for RDP shortcut creation
// -------------------------------------------------------------------------
// USER INTERFACE TEXT
// -------------------------------------------------------------------------
// Step text constants for progress checklist - displayed during installation
TXT_AddExcl = 'Add Windows Defender exclusion';
TXT_RemoveExcl = 'Remove Windows Defender exclusion';
TXT_StopSvc = 'Stop Remote Desktop Services';
TXT_StartSvc = 'Start Remote Desktop Services';
TXT_RestartSvc = 'Restart Remote Desktop Services';
TXT_EnsureVC = 'Install VC++ Redistributable (2015-2022)';
TXT_InstallTermWrap = 'Install TermWrap';
TXT_ConfigureService = 'Install and configure TermWrap';
TXT_CreateUsers = 'Create user accounts';
TXT_CreateShortcuts = 'Create RDP shortcuts for selected users';
TXT_PreTrust = 'Pre-trust RDP certificate for current user';
TXT_CheckRDP = 'Verify RDP service is listening';
TXT_CheckMSTSC = 'Check for Remote Desktop Connection';
TXT_InstallMSTSC = 'Install Remote Desktop Connection (if missing)';
TXT_RemoveFolder = 'Remove TermWrap folder';
TXT_UninstallTermWrap = 'Uninstall TermWrap';
TXT_ShowRDPInfo = 'Apply RDP settings';
// -------------------------------------------------------------------------
// REGISTRY PATHS
// -------------------------------------------------------------------------
// Windows Registry keys for Terminal Services and RDP configuration
// IMPORTANT: These paths are system-critical and must remain accurate
REG_TERMSERVICE_PARAMS = 'SYSTEM\CurrentControlSet\Services\TermService\Parameters';
REG_TERMSERVICE = 'SYSTEM\CurrentControlSet\Services\TermService';
REG_TERMINAL_SERVER = 'SYSTEM\CurrentControlSet\Control\Terminal Server';
REG_UMRDPSERVICE = 'SYSTEM\CurrentControlSet\Services\UmRdpService';
REG_UMRDPSERVICE_PARAMS = 'SYSTEM\CurrentControlSet\Services\UmRdpService\Parameters';
REG_VCREDIST = 'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64';
REG_SHOW_USERS = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System';
REG_RDP_TCP = 'SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp';
REG_TS_POLICIES = 'SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services';
// Loopback alias used by TermWrap for local RDP sessions
RDP_LOOPBACK_IP = '127.0.0.2';
// Default RDP window resolution written into generated .rdp shortcut files
DEFAULT_RDP_WIDTH = 1366;
DEFAULT_RDP_HEIGHT = 768;
// User groups
GROUP_ADMINISTRATORS = 'Administrators';
GROUP_RDP_USERS = 'Remote Desktop Users';
NET_USER_TEMP_PASSWORD = 'Tmp1!'; // Short throwaway password for two-step net user /add (avoids 14-char LM prompt)
// -------------------------------------------------------------------------
// TIMING CONSTANTS
// -------------------------------------------------------------------------
// Sleep durations in milliseconds - optimized for fastest reliable installation
// These values balance responsiveness with system stabilization needs
SLEEP_SHORT = 100;
SLEEP_MEDIUM = 250;
SLEEP_LONG = 500;
SLEEP_EXTRALONG = 2000;
// -------------------------------------------------------------------------
// TIMEOUTS
// -------------------------------------------------------------------------
// Best-effort timeouts used to avoid extremely long hangs during user
// creation/shortcut generation. Note: Exec() calls block the script, so
// timeouts are best-effort overall watchers rather than hard per-process
// kill timers.
PER_USER_TIMEOUT = 120000; // 2 minutes per user (best-effort)
USERS_OVERALL_TIMEOUT = 600000; // 10 minutes overall for user operations
// -------------------------------------------------------------------------
// FILES, URLS, AND NETWORK PORTS
// -------------------------------------------------------------------------
// Application components and external resources
FILE_TERMWRAP = 'TermWrap.dll';
FILE_ZYDIS = 'Zydis.dll';
URL_VCREDIST_X64 = 'https://aka.ms/vs/17/release/vc_redist.x64.exe';
RDP_LISTEN_PORT = 3389;
URL_RDP_INSTALLER = 'https://go.microsoft.com/fwlink/?linkid=2247659';
// -------------------------------------------------------------------------
// REUSABLE EXECUTABLES AND COMMAND PATTERNS
// -------------------------------------------------------------------------
// Centralized constants for system executables to ensure consistency
// and enable easy updates if paths change
EXE_CMD = 'cmd.exe';
EXE_POWERSHELL = 'powershell.exe';
PS_ARGS_BASE = '-NoProfile -ExecutionPolicy Bypass';
PS_ARGS_HIDDEN = PS_ARGS_BASE + ' -NonInteractive -WindowStyle Hidden';
// -------------------------------------------------------------------------
// TEMPORARY FILE PATHS
// -------------------------------------------------------------------------
// Pre-expanded temp paths for frequently-used temporary files
// Using constants avoids repeated ExpandConstant() calls
FILE_ICON_BMP = 'RDPWrapKitIcon.bmp';
FILE_RDPEDITSAVE_BMP = 'rdp_edit_save.bmp';
TEMP_LOCAL_USERS = '{tmp}\\local_users.txt';
TEMP_ICON_BMP = '{tmp}\\' + FILE_ICON_BMP;
TEMP_RDPEDITSAVE_BMP = '{tmp}\\' + FILE_RDPEDITSAVE_BMP;
// Path to installer log file (auto-created in %TEMP%)
INSTALL_LOG_PATH = '{tmp}\\RDPWrapKit_install.log';
// -------------------------------------------------------------------------
// EXTERNAL PROJECT URLS
// -------------------------------------------------------------------------
// Centralized URLs for attribution and user navigation
// Update these if upstream projects change their repository locations
URL_TERMWRAP = 'https://github.com/llccd/TermWrap';
URL_BSGH_COMMUNITY = 'https://discord.gg/bsgh';
URL_BSS_GRINDERS = 'https://discord.gg/K5U3RdGXh6';
URL_PROJECT_HOME = 'https://cpdx4.github.io/RDPWrapKit/';
// -------------------------------------------------------------------------
// INSTALL MODE CONSTANTS
// -------------------------------------------------------------------------
// Four top-level modes. The Install mode uses boolean flags (DoInstallTermWrap,
// DoCreateRdpShortcuts) and CreateUserMode to describe what happens within it.
installModeInstall = 0; // Install: TermWrap + optional shortcuts
installModeEditShortcuts = 1; // Edit existing shortcut settings
installModeEditSystemwideSettings = 2; // Edit system-wide RDP settings
installModeUninstall = 3; // Uninstall everything
installModeShowRDPInfo = 4; // Show RDP Info + configure RemoteFX/startup settings
// CREATE USER MODE CONSTANTS (only relevant when DoCreateRdpShortcuts = True)
createUserModeNew = 0; // Create new local user accounts
createUserModeExisting = 1; // Use existing local user accounts
// -------------------------------------------------------------------------
// TEST SCENARIO TOGGLES (set 1 to enable, 0 to disable)
// -------------------------------------------------------------------------
// Use only one scenario at a time for predictable behavior.
SIM_SCENARIO_NO_MSTSC =0;
SIM_SCENARIO_NO_VCREDIST = 0;
SIM_SCENARIO_NET_FAIL_POWERSHELL = 0;
// Suppress duplicate CurPageChanged log blocks if the same page is raised
// again within this short interval (UI refresh/re-entry noise).
PAGE_LOG_DEDUPE_MS = 600;
// Debug controls
PRESERVE_USER_CREATE_DEBUG_LOGS = 0;
CLEANUP_DEBUG_FILES_ON_FINISH = 0;
// Password pipeline diagnostics (temporary deep debugging)
PASSWORD_PIPELINE_DIAG = 0;
BUILD_FINGERPRINT = '2026-06-12-2-34-27';
// External Windows API declarations
function NetUserGetInfo(ServerName: String; UserName: String; Level: Cardinal; var BufPtr: Cardinal): Cardinal;
external 'NetUserGetInfo@netapi32.dll stdcall';
function NetApiBufferFree(Buf: Cardinal): Cardinal;
external 'NetApiBufferFree@netapi32.dll stdcall';
function NetUserEnum(ServerName: String; Level: Cardinal; Filter: Cardinal; var BufPtr: Cardinal; PrefMaxLen: Cardinal; var EntriesRead: Cardinal; var TotalEntries: Cardinal; var ResumeHandle: Cardinal): Cardinal;
external 'NetUserEnum@netapi32.dll stdcall';
function LogonUser(lpUsername: string; lpDomain: string; lpPassword: string; dwLogonType, dwLogonProvider: Cardinal; var phToken: Cardinal): Boolean;
external 'LogonUserW@advapi32.dll stdcall';
function CloseHandle(hObject: Cardinal): Boolean;
external 'CloseHandle@kernel32.dll stdcall';
function GetTickCount: Cardinal;
external 'GetTickCount@kernel32.dll stdcall';
function GetCurrentProcessId: DWORD;
external 'GetCurrentProcessId@kernel32.dll stdcall';
function GetCurrentThreadId: DWORD;
external 'GetCurrentThreadId@kernel32.dll stdcall';
// Windows SYSTEMTIME structure and GetSystemTime API for timestamps
type
SYSTEMTIME = record
wYear: Word;
wMonth: Word;
wDayOfWeek: Word;
wDay: Word;
wHour: Word;
wMinute: Word;
wSecond: Word;
wMilliseconds: Word;
end;
function GetSystemTime(var lpSystemTime: SYSTEMTIME): Boolean;
external 'GetSystemTime@kernel32.dll stdcall';
function GetSysColor(nIndex: DWORD): DWORD;
external 'GetSysColor@user32.dll stdcall';
function MessageBox(hWnd: Integer; lpText, lpCaption: String; uType: Cardinal): Integer;
external 'MessageBoxW@user32.dll stdcall';
// Compares two dotted version strings (e.g. "0.4.9" vs "0.4.10").
// Returns 1 if A > B, -1 if A < B, 0 if equal.
function CompareVersions(A, B: String): Integer;
var
AParts, BParts: TStringList;
i, AVal, BVal, MaxLen: Integer;
begin
Result := 0;
AParts := TStringList.Create;
BParts := TStringList.Create;
try
AParts.Delimiter := '.';
AParts.StrictDelimiter := True;
AParts.DelimitedText := A;
BParts.Delimiter := '.';
BParts.StrictDelimiter := True;
BParts.DelimitedText := B;
if AParts.Count > BParts.Count then MaxLen := AParts.Count
else MaxLen := BParts.Count;
for i := 0 to MaxLen - 1 do
begin
if i < AParts.Count then AVal := StrToIntDef(AParts[i], 0) else AVal := 0;
if i < BParts.Count then BVal := StrToIntDef(BParts[i], 0) else BVal := 0;
if AVal > BVal then begin Result := 1; Break; end;
if AVal < BVal then begin Result := -1; Break; end;
end;
finally
AParts.Free;
BParts.Free;
end;
end;
// Fetches the latest release tag from GitHub Releases API.
// Returns tag_name (e.g. "0.4.9") with leading "v" stripped, or "" on failure.
function GetLatestGitHubVersion(): String;
var
Http: Variant;
Response: String;
TagStart, TagEnd: Integer;
Tag: String;
Remainder: String;
begin
Result := '';
try
Http := CreateOleObject('WinHttp.WinHttpRequest.5.1');
Http.Open('GET', 'https://api.github.com/repos/cpdx4/RDPWrapKit/releases/latest', False);
Http.SetRequestHeader('User-Agent', 'RDPWrapKit-Installer');
Http.Send('');
if Http.Status <> 200 then
Exit;
Response := Http.ResponseText;
// Extract the value of "tag_name":"..."
TagStart := Pos('"tag_name"', Response);
if TagStart = 0 then
Exit;
// Move past "tag_name" to get the substring starting from there
Remainder := Copy(Response, TagStart + Length('"tag_name"'), Length(Response));
// Find the opening quote in the remainder
TagStart := Pos('"', Remainder);
if TagStart = 0 then
Exit;
// Extract from after the opening quote
Remainder := Copy(Remainder, TagStart + 1, Length(Remainder));
// Find the closing quote
TagEnd := Pos('"', Remainder);
if TagEnd = 0 then
Exit;
Tag := Copy(Remainder, 1, TagEnd - 1);
// Strip optional leading "v"
if (Length(Tag) > 0) and (Tag[1] = 'v') then
Tag := Copy(Tag, 2, Length(Tag) - 1);
Result := Tag;
except
Result := '';
end;
end;
// Runs at installer startup before the wizard opens.
// Shows an update prompt when a newer version is available on GitHub.
// Returns False to abort the installer, True to continue.
function InitializeSetup(): Boolean;
var
LatestVersion: String;
CurrentVersion: String;
Msg: String;
Answer: Integer;
begin
Result := True;
CurrentVersion := '{#APP_VERSION_STRING}';
LatestVersion := GetLatestGitHubVersion();
// Only prompt when a version string was returned and it is strictly newer
if (LatestVersion <> '') and (CompareVersions(LatestVersion, CurrentVersion) > 0) then
begin
Msg := 'A newer version (v' + LatestVersion + ') is available.' + #13#10#13#10
+ 'Open the latest release page instead?';
Answer := MsgBox(Msg, mbConfirmation, MB_YESNOCANCEL);
if Answer = IDYES then
begin
ShellExec('open', 'https://github.com/cpdx4/RDPWrapKit/releases/latest', '', '', SW_SHOWNORMAL, ewNoWait, Answer);
Result := False;
end else if Answer = IDCANCEL then
Result := False;
// IDNO falls through with Result = True (install anyway)
end;
end;
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
// -----------------------------------------------------------------------------
// USER ACCOUNT VALIDATION
// -----------------------------------------------------------------------------
// Check if a local user account exists
function UserExists(const UserName: string): Boolean;
var
BufPtr: Cardinal;
begin
BufPtr := 0;
Result := NetUserGetInfo('', UserName, 0, BufPtr) = NERR_Success;
if BufPtr <> 0 then
NetApiBufferFree(BufPtr);
end;
// Parse a "username|password" string into its components
procedure ParseUserEntry(const Entry: string; var UserName, Password: string);
var
PipePos: Integer;
begin
LogEntry('ParseUserEntry');
PipePos := Pos('|', Entry);
UserName := Copy(Entry, 1, PipePos - 1);
Password := Copy(Entry, PipePos + 1, Length(Entry));
LogDebug('ParseUserEntry: user=' + UserName + ' hasPassword=' + BoolToStr(Password <> ''));
LogExit('ParseUserEntry');
end;
// Return a version of a pipe-delimited user entry with the password obscured
function MaskPasswordInEntry(const Entry: string): string;
var
PipePos: Integer;
begin
LogEntry('MaskPasswordInEntry');
PipePos := Pos('|', Entry);
if PipePos > 0 then
Result := Copy(Entry, 1, PipePos) + '*****'
else
Result := Entry;
LogExit('MaskPasswordInEntry');
end;
function PosFrom(const Needle, Haystack: string; const FromPos: Integer): Integer;
var
i: Integer;
begin
Result := 0;
if (Needle = '') or (Haystack = '') or (FromPos < 1) or (FromPos > Length(Haystack)) then
exit;
for i := FromPos to Length(Haystack) - Length(Needle) + 1 do
begin
if Copy(Haystack, i, Length(Needle)) = Needle then
begin
Result := i;
exit;
end;
end;
end;
// Mask common password flags in arbitrary command strings (e.g. -Password "..." or -Password ...)
function MaskPasswordsInString(const S: string): string;
var
U: string;
idx, p, startPos, endPos, SearchPos: Integer;
begin
Result := S;
U := UpperCase(Result);
SearchPos := 1;
idx := PosFrom('-PASSWORD', U, SearchPos);
while idx > 0 do
begin
p := idx + Length('-PASSWORD');
while (p <= Length(Result)) and ((Result[p] = ' ') or (Result[p] = '=') ) do
Inc(p);
if p > Length(Result) then
Break;
if Result[p] = '"' then
begin
startPos := p;
endPos := startPos + 1;
while (endPos <= Length(Result)) and (Result[endPos] <> '"') do
Inc(endPos);
if endPos > Length(Result) then
endPos := Length(Result);
Delete(Result, startPos, endPos - startPos + 1);
Insert('"*****"', Result, startPos);
end
else
begin
endPos := p;
while (endPos <= Length(Result)) and (Result[endPos] <> ' ') do
Inc(endPos);
Delete(Result, p, endPos - p);
Insert('*****', Result, p);
end;
U := UpperCase(Result);
SearchPos := idx + Length('-PASSWORD') + 1;
idx := PosFrom('-PASSWORD', U, SearchPos);
end;
end;
procedure NextArgRange(const S: string; var Cursor, StartPos, EndPos: Integer);
begin
while (Cursor <= Length(S)) and (S[Cursor] = ' ') do
Inc(Cursor);
StartPos := Cursor;
EndPos := 0;
if Cursor > Length(S) then
exit;
if S[Cursor] = '"' then
begin
Inc(Cursor);
while (Cursor <= Length(S)) and (S[Cursor] <> '"') do
Inc(Cursor);
if Cursor <= Length(S) then
EndPos := Cursor
else
EndPos := Length(S);
Inc(Cursor);
end
else
begin
while (Cursor <= Length(S)) and (S[Cursor] <> ' ') do
Inc(Cursor);
EndPos := Cursor - 1;
end;
end;
function StripWrappingQuotes(const S: string): string;
begin
Result := S;
if (Length(Result) >= 2) and (Result[1] = '"') and (Result[Length(Result)] = '"') then
Result := Copy(Result, 2, Length(Result) - 2);
end;
function MaskCommandForLog(const FileName, Params: string): string;
var
Cur: Integer;
A1Start, A1End, A2Start, A2End, A3Start, A3End: Integer;
Arg1: string;
begin
Result := MaskPasswordsInString(Params);
if CompareText(FileName, 'net.exe') <> 0 then
exit;
Cur := 1;
A1Start := 0; A1End := 0;
A2Start := 0; A2End := 0;
A3Start := 0; A3End := 0;
NextArgRange(Result, Cur, A1Start, A1End);
if (A1Start <= 0) or (A1End < A1Start) then
exit;
Arg1 := UpperCase(StripWrappingQuotes(Copy(Result, A1Start, A1End - A1Start + 1)));
if Arg1 <> 'USER' then
exit;
NextArgRange(Result, Cur, A2Start, A2End); // username
NextArgRange(Result, Cur, A3Start, A3End); // password
if (A3Start > 0) and (A3End >= A3Start) then
begin
Delete(Result, A3Start, A3End - A3Start + 1);
Insert('"*****"', Result, A3Start);
end;
end;
// -----------------------------------------------------------------------------
// PATH CONSTRUCTION HELPERS
// -----------------------------------------------------------------------------
// Expand a filename under {tmp}
function TempFile(const FileName: string): string;
begin
Result := ExpandConstant('{tmp}\' + FileName);
end;
function EnsureDebugWorkDir: string;
var
BaseDir: string;
begin
LogEntry('EnsureDebugWorkDir');
BaseDir := ExpandConstant('{localappdata}\RDPWrapKit');
if (not DirExists(BaseDir)) and (not CreateDir(BaseDir)) then
begin
LogWarn('Could not create debug work base directory: ' + BaseDir);
Result := ExpandConstant('{tmp}');
LogExit('EnsureDebugWorkDir');
exit;
end;
Result := BaseDir + '\DebugLogs';
if (not DirExists(Result)) and (not CreateDir(Result)) then
begin
LogWarn('Could not create debug work directory: ' + Result);
Result := ExpandConstant('{tmp}');
LogExit('EnsureDebugWorkDir');
exit;
end;
LogDebug('Debug work directory ready: ' + Result);
LogExit('EnsureDebugWorkDir');
end;
function DebugLogFile(const FileName: string): string;
begin
LogEntry('DebugLogFile');
Result := EnsureDebugWorkDir + '\' + FileName;
LogExit('DebugLogFile');
end;
function BuildPowerShellFileArgs(const ScriptPath, ExtraParams: string; Hidden: Boolean): string; forward;
function GetPSOutput(const Command: string): string; forward;
// Create a filesystem-safe filename from an arbitrary string by replacing
// non-alphanumeric characters with underscores.
function SanitizeFileName(const S: string): string;
var
i: Integer;
c: Char;
begin
Result := '';
for i := 1 to Length(S) do
begin
c := S[i];
if ((c >= 'a') and (c <= 'z')) or ((c >= 'A') and (c <= 'Z')) or ((c >= '0') and (c <= '9')) then
Result := Result + c
else
Result := Result + '_';
end;
end;
// Returns True if the given string is safe to use as a Windows filename (no invalid chars).
// Invalid Windows filename characters: < > : " / \ | ? *
function IsValidShortcutName(const Name: string): Boolean;
var
i: Integer;
c: Char;
begin
Result := False;
if Trim(Name) = '' then
exit;
for i := 1 to Length(Name) do
begin
c := Name[i];
if (c = '<') or (c = '>') or (c = ':') or (c = '"') or
(c = '/') or (c = '\') or (c = '|') or (c = '?') or (c = '*') then
exit;
end;
Result := True;
end;
// Escape single quotes for use in PowerShell single-quoted literals
function PSSingleQuote(const S: string): string;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(S) do
begin
if S[i] = '''' then
Result := Result + ''''''
else
Result := Result + S[i];
end;
end;
// Build a safe named PowerShell argument using single-quoted values
function BuildPSNamedParam(const Name, Value: string): string;
var
i: Integer;
SafeName: string;
Escaped: string;
c: Char;
begin
SafeName := '';
for i := 1 to Length(Name) do
begin
c := Name[i];
if ((c >= 'A') and (c <= 'Z')) or ((c >= 'a') and (c <= 'z')) or ((c >= '0') and (c <= '9')) then
SafeName := SafeName + c;
end;
if SafeName = '' then
SafeName := 'Param';
Escaped := '';
for i := 1 to Length(Value) do
begin
if Value[i] = '"' then
Escaped := Escaped + '\"'
else
Escaped := Escaped + Value[i];
end;
Result := '-' + SafeName + ' "' + Escaped + '"';
end;
// Quote an argument for direct executable invocation (CreateProcess semantics)
function QuoteExeArg(const S: string): string;
var
i: Integer;
Escaped: string;
begin
Escaped := '';
for i := 1 to Length(S) do
begin
if S[i] = '"' then
Escaped := Escaped + '\"'
else
Escaped := Escaped + S[i];
end;
Result := '"' + Escaped + '"';
end;
// Execute PowerShell script content through a temporary script file
function ExecPowerShellScriptContent(const ScriptBaseName, ScriptContent, ExtraParams: string; Hidden: Boolean; var ResultCode: Integer): Boolean;
var
ScriptPath: string;
OpTick: Cardinal;
begin
LogEntry('ExecPowerShellScriptContent');
OpTick := GetTickCount;
ScriptPath := TempFile(ScriptBaseName);
SaveStringToFile(ScriptPath, ScriptContent, False);
LogDebug('PowerShell File: ' + ScriptPath + ' ' + MaskPasswordsInString(ExtraParams));
Result := Exec(EXE_POWERSHELL, BuildPowerShellFileArgs(ScriptPath, ExtraParams, Hidden), '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
LogDebug('PowerShell exit=' + IntToStr(ResultCode) + ' [DURATION:' + IntToStr(GetTickCount - OpTick) + 'ms]');
DeleteFile(ScriptPath);
LogExit('ExecPowerShellScriptContent');
end;
function ExecSavedPowerShellDebugScriptParams(const ScriptTag, UserName, ScriptContent, ExtraParams: string; Hidden: Boolean; var ResultCode: Integer): Boolean;
var
ScriptPath: string;
OpTick: Cardinal;
begin
LogEntry('ExecSavedPowerShellDebugScriptParams');
OpTick := GetTickCount;
ScriptPath := TempFile(ScriptTag + '_' + SanitizeFileName(UserName) + '.ps1');
SaveStringToFile(ScriptPath, ScriptContent, False);
LogDebug('PowerShell File: ' + ScriptPath + ' ' + MaskPasswordsInString(ExtraParams));
Result := Exec(EXE_POWERSHELL, BuildPowerShellFileArgs(ScriptPath, ExtraParams, Hidden), '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
if not Result then
LogError('Failed to launch PowerShell script: code=' + IntToStr(ResultCode) + ' message=' + SysErrorMessage(ResultCode));
LogDebug('PowerShell exit=' + IntToStr(ResultCode) + ' [DURATION:' + IntToStr(GetTickCount - OpTick) + 'ms]');
DeleteFile(ScriptPath);
LogExit('ExecSavedPowerShellDebugScriptParams');
end;
function BuildAddGroupMemberPowerShellScript(const GroupName, UserName, OutPath, SuccessTag: string): string;
begin
Result :=