-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockScreen.cs
More file actions
4216 lines (3822 loc) · 202 KB
/
Copy pathLockScreen.cs
File metadata and controls
4216 lines (3822 loc) · 202 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
// =============================================================================
// StillGuard(靜守)— 鍵鼠鎖定工具
// 依 DESIGN.md v1.0 實作。C# + WinForms,目標 .NET Framework 4.x。
// 以 Windows 內建 csc.exe 編譯為單一 exe(見 build.bat)。
//
// 安全邊界:本工具屬使用者層級,「防隨手亂動」而非「防內行破解」。
// Ctrl+Alt+Del 仍可進入安全桌面結束本程式——此為無核心驅動之先天限制。
// =============================================================================
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization; // System.Web.Extensions.dll
using System.Windows.Forms;
namespace StillGuard
{
// =========================================================================
// 密碼策略(第 7 節,公開友善版)
// - 原始碼「不含任何機密」:無預設主密碼、無寫死緊急碼。
// - 主密碼:必設。首次於設定介面建立,以 PBKDF2 雜湊存入各機自己的 config.json。
// - 救援碼:使用者自選是否設定,同樣以雜湊存入 config.json。
// - 主密碼或救援碼(若有設)皆可解鎖。機密只存在各機本地,雲端原始碼一概沒有。
// =========================================================================
// 設定檔中的密碼欄位(僅存雜湊與鹽,不存明碼)。
internal sealed class PasswordConfig
{
public string hash; // base64(PBKDF2)
public string salt; // base64
public int iterations = 100000;
}
// PBKDF2 密碼雜湊與驗證。
internal static class PasswordManager
{
// 是否已設定主密碼(未設定則不允許鎖定,避免把自己鎖死)。
public static bool HasMaster(AppConfig cfg)
{
return cfg != null && cfg.password != null
&& !string.IsNullOrEmpty(cfg.password.hash) && !string.IsNullOrEmpty(cfg.password.salt);
}
public static void SetPassword(AppConfig cfg, string newPassword)
{
cfg.password = Make(newPassword);
}
// 設定 / 清除救援碼(傳空字串視為清除)。
public static void SetRescue(AppConfig cfg, string rescuePassword)
{
cfg.rescue = string.IsNullOrEmpty(rescuePassword) ? null : Make(rescuePassword);
}
public static bool HasRescue(AppConfig cfg)
{
return cfg != null && cfg.rescue != null
&& !string.IsNullOrEmpty(cfg.rescue.hash) && !string.IsNullOrEmpty(cfg.rescue.salt);
}
// 主密碼或救援碼任一相符即通過。無內建後門。
public static bool Verify(AppConfig cfg, string input)
{
if (input == null || cfg == null) return false;
if (VerifyAgainst(cfg.password, input)) return true;
if (VerifyAgainst(cfg.rescue, input)) return true;
return false;
}
private static bool VerifyAgainst(PasswordConfig pc, string input)
{
if (pc == null || string.IsNullOrEmpty(pc.hash) || string.IsNullOrEmpty(pc.salt)) return false;
try
{
byte[] salt = Convert.FromBase64String(pc.salt);
byte[] expected = Convert.FromBase64String(pc.hash);
byte[] actual = Derive(input, salt, pc.iterations <= 0 ? 100000 : pc.iterations);
return FixedTimeEquals(expected, actual);
}
catch { return false; }
}
private static PasswordConfig Make(string password)
{
byte[] salt = new byte[16];
using (var rng = new RNGCryptoServiceProvider()) rng.GetBytes(salt);
int iter = 100000;
byte[] hash = Derive(password, salt, iter);
return new PasswordConfig
{
salt = Convert.ToBase64String(salt),
hash = Convert.ToBase64String(hash),
iterations = iter
};
}
private static byte[] Derive(string password, byte[] salt, int iterations)
{
using (var pbkdf2 = new Rfc2898DeriveBytes(password ?? "", salt, iterations))
return pbkdf2.GetBytes(32);
}
private static bool FixedTimeEquals(byte[] a, byte[] b)
{
if (a == null || b == null || a.Length != b.Length) return false;
int diff = 0;
for (int i = 0; i < a.Length; i++) diff |= a[i] ^ b[i];
return diff == 0;
}
}
// =========================================================================
// OTP 一次性救援碼設定(送至手機 / APP)
// =========================================================================
internal sealed class OtpConfig
{
public bool enabled = false;
public string channel = "telegram"; // telegram | discord | ntfy
public string telegramToken = ""; // 機密,DPAPI 加密存放
public string telegramChatId = "";
public string discordWebhook = ""; // 機密,DPAPI 加密存放
public string ntfyServer = "https://ntfy.sh";
public string ntfyTopic = "";
}
// 以 Windows DPAPI(當前使用者)加密 / 解密機密字串;存放格式加前綴 "enc:"。
internal static class DataProtector
{
public static string Protect(string plain)
{
if (string.IsNullOrEmpty(plain)) return "";
if (plain.StartsWith("enc:")) return plain; // 已是加密字串
try
{
byte[] enc = ProtectedData.Protect(Encoding.UTF8.GetBytes(plain), null, DataProtectionScope.CurrentUser);
return "enc:" + Convert.ToBase64String(enc);
}
catch { return plain; }
}
public static string Unprotect(string stored)
{
if (string.IsNullOrEmpty(stored)) return "";
if (!stored.StartsWith("enc:")) return stored; // 相容明碼
try
{
byte[] enc = Convert.FromBase64String(stored.Substring(4));
byte[] data = ProtectedData.Unprotect(enc, null, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(data);
}
catch { return ""; }
}
}
// =========================================================================
// 通知通道(策略 + 工廠)—— 新增通道 = 新增一個 INotifier + 於工廠註冊
// =========================================================================
internal interface INotifier
{
bool Send(string message, out string error);
}
internal sealed class TelegramNotifier : INotifier
{
private readonly string _token, _chatId;
public TelegramNotifier(string token, string chatId) { _token = token; _chatId = chatId; }
public bool Send(string message, out string error)
{
error = null;
if (string.IsNullOrEmpty(_token) || string.IsNullOrEmpty(_chatId)) { error = "Telegram token / chatId 未設定"; return false; }
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
using (var wc = new WebClient())
{
var data = new System.Collections.Specialized.NameValueCollection();
data["chat_id"] = _chatId;
data["text"] = message;
wc.UploadValues("https://api.telegram.org/bot" + _token + "/sendMessage", data);
}
return true;
}
catch (Exception ex) { error = ex.Message; return false; }
}
}
internal sealed class DiscordNotifier : INotifier
{
private readonly string _webhook;
public DiscordNotifier(string webhook) { _webhook = webhook; }
public bool Send(string message, out string error)
{
error = null;
if (string.IsNullOrEmpty(_webhook)) { error = "Discord webhook 未設定"; return false; }
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
string json = "{\"content\":\"" + JsonEscape(message) + "\"}";
wc.UploadString(_webhook, "POST", json);
}
return true;
}
catch (Exception ex) { error = ex.Message; return false; }
}
private static string JsonEscape(string s)
{
return (s ?? "").Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "");
}
}
internal sealed class NtfyNotifier : INotifier
{
private readonly string _server, _topic;
public NtfyNotifier(string server, string topic) { _server = server; _topic = topic; }
public bool Send(string message, out string error)
{
error = null;
if (string.IsNullOrEmpty(_topic)) { error = "ntfy 主題未設定"; return false; }
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string baseUrl = string.IsNullOrEmpty(_server) ? "https://ntfy.sh" : _server.TrimEnd('/');
using (var wc = new WebClient())
{
wc.Encoding = Encoding.UTF8;
wc.UploadString(baseUrl + "/" + _topic, "POST", message);
}
return true;
}
catch (Exception ex) { error = ex.Message; return false; }
}
}
internal static class NotifierFactory
{
// 依設定建立通道(機密欄位於此解密)
public static INotifier Create(OtpConfig cfg)
{
if (cfg == null) return null;
switch ((cfg.channel ?? "").ToLowerInvariant())
{
case "telegram": return new TelegramNotifier(DataProtector.Unprotect(cfg.telegramToken), cfg.telegramChatId);
case "discord": return new DiscordNotifier(DataProtector.Unprotect(cfg.discordWebhook));
case "ntfy": return new NtfyNotifier(cfg.ntfyServer, cfg.ntfyTopic);
default: return null;
}
}
public static bool IsConfigured(OtpConfig cfg)
{
if (cfg == null || !cfg.enabled) return false;
switch ((cfg.channel ?? "").ToLowerInvariant())
{
case "telegram": return !string.IsNullOrEmpty(cfg.telegramToken) && !string.IsNullOrEmpty(cfg.telegramChatId);
case "discord": return !string.IsNullOrEmpty(cfg.discordWebhook);
case "ntfy": return !string.IsNullOrEmpty(cfg.ntfyTopic);
default: return false;
}
}
}
// OTP 產生與驗證(一次性、限時)
internal sealed class OtpState
{
private readonly object _lock = new object(); // Generate(UI 緒)與 Verify(輪詢緒)可能並行
private string _code;
private DateTime _expiry = DateTime.MinValue;
private bool _used;
public int ValiditySeconds = 300; // 5 分鐘
public string Generate()
{
byte[] b = new byte[4];
using (var rng = new RNGCryptoServiceProvider()) rng.GetBytes(b);
uint v = (uint)(BitConverter.ToUInt32(b, 0) % 1000000);
lock (_lock)
{
_code = v.ToString("D6");
_expiry = DateTime.Now.AddSeconds(ValiditySeconds);
_used = false;
return _code;
}
}
public bool Verify(string input)
{
lock (_lock)
{
if (string.IsNullOrEmpty(_code) || _used) return false;
if (DateTime.Now > _expiry) return false;
if (input != _code) return false;
_used = true; // 一次性
return true;
}
}
}
// =========================================================================
// 設定模型(config.json)
// =========================================================================
internal sealed class BackgroundConfig
{
public string type = "blurDesktop"; // blurDesktop | image | solidDark
public int blur = 18; // 模糊強度
public double dim = 0.25; // 變暗程度 0~1
public string path = null; // type=image 時的圖片路徑
}
internal sealed class WidgetConfig
{
public string type; // clock | date | text | hint | weather
public string format;
public string content;
public string city;
public string y = "50%"; // 垂直位置(百分比或像素)
public int fontSize = 20;
public bool enabled = true;
}
internal sealed class AppConfig
{
public BackgroundConfig background = new BackgroundConfig();
public int idleTimeoutSec = 10;
public string hotkey = "Ctrl+Alt+L"; // 全域鎖定快捷鍵
public bool showClock = true; // 鎖屏是否顯示內建時鐘
public bool showTerminal = false; // 鎖屏是否顯示終端特效(純裝飾)
public string terminalStyle = "hacker"; // 終端風格:hacker(駭客)| guard(仿真守護)
public bool fakeUpdate = false; // 偽 Windows 更新畫面(障眼模式,蓋過其他顯示)
public string fakeUpdateLang = "zh"; // 偽更新畫面文字語言:zh(中文)| en(英文)
public bool showPasswordPanel = true; // 鎖屏是否顯示密碼輸入框(false=隱藏,仍可盲打密碼 / F2 解鎖)
public List<WidgetConfig> widgets = new List<WidgetConfig>();
public PasswordConfig password = null; // 主密碼雜湊(由 UI 設定)
public PasswordConfig rescue = null; // 救援碼雜湊(可選,由 UI 設定)
public OtpConfig otp = new OtpConfig(); // OTP 一次性救援碼通道
public static AppConfig LoadOrDefault(string path)
{
try
{
if (!File.Exists(path)) return Default();
string json = File.ReadAllText(path, Encoding.UTF8);
var ser = new JavaScriptSerializer();
var root = ser.Deserialize<Dictionary<string, object>>(json);
return FromDict(root);
}
catch
{
// 設定壞了不應使程式無法鎖定——退回安全預設。
return Default();
}
}
private static AppConfig FromDict(Dictionary<string, object> root)
{
var cfg = new AppConfig();
if (root.ContainsKey("background") && root["background"] is Dictionary<string, object>)
{
var b = (Dictionary<string, object>)root["background"];
cfg.background.type = GetStr(b, "type", cfg.background.type);
cfg.background.blur = GetInt(b, "blur", cfg.background.blur);
cfg.background.dim = GetDouble(b, "dim", cfg.background.dim);
cfg.background.path = GetStr(b, "path", null);
}
cfg.idleTimeoutSec = GetInt(root, "idleTimeoutSec", cfg.idleTimeoutSec);
cfg.hotkey = GetStr(root, "hotkey", cfg.hotkey);
cfg.showClock = GetBool(root, "showClock", cfg.showClock);
cfg.showTerminal = GetBool(root, "showTerminal", cfg.showTerminal);
cfg.terminalStyle = GetStr(root, "terminalStyle", cfg.terminalStyle);
cfg.fakeUpdate = GetBool(root, "fakeUpdate", cfg.fakeUpdate);
cfg.fakeUpdateLang = GetStr(root, "fakeUpdateLang", cfg.fakeUpdateLang);
cfg.showPasswordPanel = GetBool(root, "showPasswordPanel", cfg.showPasswordPanel);
cfg.password = ReadPwd(root, "password");
cfg.rescue = ReadPwd(root, "rescue");
if (root.ContainsKey("otp") && root["otp"] is Dictionary<string, object>)
{
var o = (Dictionary<string, object>)root["otp"];
cfg.otp = new OtpConfig
{
enabled = GetBool(o, "enabled", false),
channel = GetStr(o, "channel", "telegram"),
telegramToken = GetStr(o, "telegramToken", ""),
telegramChatId = GetStr(o, "telegramChatId", ""),
discordWebhook = GetStr(o, "discordWebhook", ""),
ntfyServer = GetStr(o, "ntfyServer", "https://ntfy.sh"),
ntfyTopic = GetStr(o, "ntfyTopic", "")
};
}
cfg.widgets.Clear();
if (root.ContainsKey("widgets") && root["widgets"] is System.Collections.IEnumerable)
{
foreach (var item in (System.Collections.IEnumerable)root["widgets"])
{
var w = item as Dictionary<string, object>;
if (w == null) continue;
var wc = new WidgetConfig();
wc.type = GetStr(w, "type", null);
wc.format = GetStr(w, "format", null);
wc.content = GetStr(w, "content", null);
wc.city = GetStr(w, "city", null);
wc.y = GetStr(w, "y", "50%");
wc.fontSize = GetInt(w, "fontSize", 20);
wc.enabled = GetBool(w, "enabled", true);
if (!string.IsNullOrEmpty(wc.type)) cfg.widgets.Add(wc);
}
}
return cfg;
}
public static AppConfig Default()
{
// 預設:顯示內建時鐘即可(不再使用自訂 widget 清單)。
return new AppConfig();
}
// 手寫輸出整齊 JSON,並保留密碼雜湊區塊。
public void Save(string path)
{
var sb = new StringBuilder();
sb.AppendLine("{");
sb.AppendLine(" \"background\": { \"type\": " + JStr(background.type) +
", \"blur\": " + background.blur +
", \"dim\": " + background.dim.ToString(CultureInfo.InvariantCulture) +
(string.IsNullOrEmpty(background.path) ? "" : ", \"path\": " + JStr(background.path)) +
" },");
sb.AppendLine(" \"idleTimeoutSec\": " + idleTimeoutSec + ",");
sb.AppendLine(" \"hotkey\": " + JStr(hotkey) + ",");
// showClock 之後的成員(password / rescue / otp),統一處理逗號
var members = new List<string>();
if (password != null && !string.IsNullOrEmpty(password.hash)) members.Add(PwdJson("password", password));
if (rescue != null && !string.IsNullOrEmpty(rescue.hash)) members.Add(PwdJson("rescue", rescue));
if (otp != null) members.Add(OtpJson(otp));
sb.AppendLine(" \"showClock\": " + (showClock ? "true" : "false") + ",");
sb.AppendLine(" \"showTerminal\": " + (showTerminal ? "true" : "false") + ",");
sb.AppendLine(" \"terminalStyle\": " + JStr(terminalStyle) + ",");
sb.AppendLine(" \"fakeUpdate\": " + (fakeUpdate ? "true" : "false") + ",");
sb.AppendLine(" \"fakeUpdateLang\": " + JStr(fakeUpdateLang) + ",");
sb.AppendLine(" \"showPasswordPanel\": " + (showPasswordPanel ? "true" : "false") + (members.Count > 0 ? "," : ""));
for (int i = 0; i < members.Count; i++)
sb.AppendLine(" " + members[i] + (i < members.Count - 1 ? "," : ""));
sb.AppendLine("}");
File.WriteAllText(path, sb.ToString(), new UTF8Encoding(false));
}
private static string PwdJson(string key, PasswordConfig pc)
{
return "\"" + key + "\": { \"hash\": " + JStr(pc.hash) +
", \"salt\": " + JStr(pc.salt) +
", \"iterations\": " + pc.iterations + " }";
}
private static string OtpJson(OtpConfig o)
{
return "\"otp\": { \"enabled\": " + (o.enabled ? "true" : "false") +
", \"channel\": " + JStr(o.channel) +
", \"telegramToken\": " + JStr(o.telegramToken) +
", \"telegramChatId\": " + JStr(o.telegramChatId) +
", \"discordWebhook\": " + JStr(o.discordWebhook) +
", \"ntfyServer\": " + JStr(o.ntfyServer) +
", \"ntfyTopic\": " + JStr(o.ntfyTopic) + " }";
}
private static string JStr(string s)
{
if (s == null) return "null";
var sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default: sb.Append(c); break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static PasswordConfig ReadPwd(Dictionary<string, object> root, string key)
{
if (!root.ContainsKey(key) || !(root[key] is Dictionary<string, object>)) return null;
var p = (Dictionary<string, object>)root[key];
return new PasswordConfig
{
hash = GetStr(p, "hash", null),
salt = GetStr(p, "salt", null),
iterations = GetInt(p, "iterations", 100000)
};
}
private static string GetStr(Dictionary<string, object> d, string k, string def)
{
object v; return d.TryGetValue(k, out v) && v != null ? v.ToString() : def;
}
private static int GetInt(Dictionary<string, object> d, string k, int def)
{
object v; if (!d.TryGetValue(k, out v) || v == null) return def;
int r; return int.TryParse(v.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out r) ? r : def;
}
private static double GetDouble(Dictionary<string, object> d, string k, double def)
{
object v; if (!d.TryGetValue(k, out v) || v == null) return def;
double r; return double.TryParse(v.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out r) ? r : def;
}
private static bool GetBool(Dictionary<string, object> d, string k, bool def)
{
object v; if (!d.TryGetValue(k, out v) || v == null) return def;
bool r; return bool.TryParse(v.ToString(), out r) ? r : def;
}
}
// =========================================================================
// Widget 架構(第 6 節)—— 工廠 / 策略模式,符合開放封閉原則。
// =========================================================================
internal interface IWidget
{
// screen:本元件可用的版面矩形(以表單座標表示,通常為主螢幕區域)。
void Render(Graphics g, Rectangle screen);
}
internal abstract class TextWidgetBase : IWidget
{
protected readonly WidgetConfig Cfg;
protected TextWidgetBase(WidgetConfig cfg) { Cfg = cfg; }
protected abstract string GetText();
protected virtual Color TextColor { get { return Color.White; } }
public void Render(Graphics g, Rectangle screen)
{
string text = GetText();
if (string.IsNullOrEmpty(text)) return;
int y = ResolveY(Cfg.y, screen);
using (var font = new Font("Segoe UI", Cfg.fontSize, FontStyle.Regular, GraphicsUnit.Pixel))
using (var brush = new SolidBrush(TextColor))
using (var shadow = new SolidBrush(Color.FromArgb(160, 0, 0, 0)))
using (var fmt = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
{
var rect = new RectangleF(screen.Left, y, screen.Width, Cfg.fontSize * 1.6f);
// 陰影提升於各種背景上的可讀性
g.DrawString(text, font, shadow, new RectangleF(rect.X + 2, rect.Y + 2, rect.Width, rect.Height), fmt);
g.DrawString(text, font, brush, rect, fmt);
}
}
// 支援 "30%"(佔螢幕高比例)或 "120"(像素)
protected static int ResolveY(string y, Rectangle screen)
{
if (string.IsNullOrEmpty(y)) return screen.Top + screen.Height / 2;
y = y.Trim();
if (y.EndsWith("%"))
{
double pct;
if (double.TryParse(y.Substring(0, y.Length - 1), NumberStyles.Any, CultureInfo.InvariantCulture, out pct))
return screen.Top + (int)(screen.Height * pct / 100.0);
}
int px;
if (int.TryParse(y, NumberStyles.Any, CultureInfo.InvariantCulture, out px))
return screen.Top + px;
return screen.Top + screen.Height / 2;
}
}
internal sealed class ClockWidget : TextWidgetBase
{
public ClockWidget(WidgetConfig c) : base(c) { }
protected override string GetText()
{
string f = string.IsNullOrEmpty(Cfg.format) ? "HH:mm" : Cfg.format;
return DateTime.Now.ToString(f, CultureInfo.CurrentCulture);
}
}
internal sealed class DateWidget : TextWidgetBase
{
public DateWidget(WidgetConfig c) : base(c) { }
protected override string GetText()
{
string f = string.IsNullOrEmpty(Cfg.format) ? "yyyy/MM/dd dddd" : Cfg.format;
return DateTime.Now.ToString(f, CultureInfo.CurrentCulture);
}
}
internal sealed class TextWidget : TextWidgetBase
{
public TextWidget(WidgetConfig c) : base(c) { }
protected override string GetText() { return Cfg.content; }
}
internal sealed class HintWidget : TextWidgetBase
{
public HintWidget(WidgetConfig c) : base(c) { }
protected override Color TextColor { get { return Color.FromArgb(200, 220, 220, 220); } }
protected override string GetText()
{
return string.IsNullOrEmpty(Cfg.content) ? "按任意鍵或點擊以解鎖" : Cfg.content;
}
}
// 天氣元件(第 6 節:預留,預設關閉)。會送出城市名至 wttr.in,故由老爺自行啟用。
internal sealed class WeatherWidget : TextWidgetBase
{
private string _cache = "…";
private bool _fetching;
public WeatherWidget(WidgetConfig c) : base(c) { BeginFetch(); }
protected override Color TextColor { get { return Color.FromArgb(230, 200, 230, 255); } }
private void BeginFetch()
{
if (_fetching || string.IsNullOrEmpty(Cfg.city)) return;
_fetching = true;
var t = new Thread(() =>
{
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // TLS1.2
using (var wc = new WebClient())
{
wc.Encoding = Encoding.UTF8;
// 格式:城市 +溫度,例:Taipei: 26°C
string url = "https://wttr.in/" + Uri.EscapeDataString(Cfg.city) + "?format=%l:+%t";
_cache = wc.DownloadString(url).Trim();
}
}
catch { _cache = Cfg.city + ": —"; }
});
t.IsBackground = true;
t.Start();
}
protected override string GetText() { return _cache; }
}
internal static class WidgetFactory
{
public static IWidget Create(WidgetConfig cfg)
{
if (cfg == null || !cfg.enabled) return null;
switch ((cfg.type ?? "").ToLowerInvariant())
{
case "clock": return new ClockWidget(cfg);
case "date": return new DateWidget(cfg);
case "text": return new TextWidget(cfg);
case "hint": return new HintWidget(cfg);
case "weather": return new WeatherWidget(cfg);
default: return null; // 未知類型直接忽略
}
}
}
// 內建時鐘繪製:字級依畫面高度自動縮放,置於畫面中央偏上。
internal static class ClockRenderer
{
public static void Draw(Graphics g, Rectangle screen)
{
int fontSize = Math.Max(28, (int)(screen.Height * 0.09));
var cfg = new WidgetConfig { type = "clock", format = "HH:mm", y = "38%", fontSize = fontSize, enabled = true };
new ClockWidget(cfg).Render(g, screen);
}
}
// 鎖屏真實事件(供 Guard 終端做因果反應;駭客終端忽略之)
internal enum TermSignal { KeySuppressed, MouseSuppressed, PanelOpen, VerifyAttempt }
// 終端特效的共同介面:每種「鎖屏顯示畫面」都實作此方法,
// LockForm / PreviewPanel 依設定的 terminalStyle 挑選對應實作。
internal interface ITerminalEffect
{
void SetCols(int cols); // 依終端區寬度設定每行字數
void Step(); // 推進一影格
void Render(Graphics g, Rectangle area, float scale);// 繪製到指定區域
void Signal(TermSignal sig, string detail); // 接收鎖屏真實事件
}
// 依設定的風格字串產生對應的終端特效實作。
internal static class TerminalFactory
{
public static ITerminalEffect Create(string style)
{
string s = (style ?? "").Trim().ToLowerInvariant();
if (s == "guard") return new GuardTerminal();
return new FakeTerminal();
}
}
// 駭客終端特效:程式即時生成的綠字假指令,不停滾動(純裝飾,不影響安全)。
internal sealed class FakeTerminal : ITerminalEffect
{
// kind: 0 一般(暗綠) 1 成功(亮綠) 2 資訊(青) 3 警告(黃) 4 錯誤(紅) 5 進度
private sealed class Line { public string Text; public int Kind; }
private sealed class Cmd { public bool Progress; public bool Instant; public bool Spin; public int Pause; public string Text; public int Kind; public string Label; }
private readonly List<Line> _lines = new List<Line>();
private readonly Queue<Cmd> _queue = new Queue<Cmd>();
private readonly Random _rng = new Random();
private int _frame;
private int _cols = 80; // 每行可容字元數(依螢幕寬度動態設定)
private int _pauseLeft; // 停頓剩餘 tick(製造讀取等待感)
private string _typing; // 正在打字的整行
private int _typed; // 已打出的字元數
private int _typingKind;
private bool _inProg; // 進度條進行中
private int _prog;
private string _progLabel = "";
private int _progStyle; // 進度條樣式(每次隨機切換,避免單調)
private bool _inSpin; // spinner 旋轉等待中
private int _spinLeft; // 旋轉剩餘 tick,歸零後定版為 [ OK ]
private string _spinText = "";
public FakeTerminal() { EnqueueBanner(); }
// 由外部依終端區寬度與字寬設定每行可容字元數
public void SetCols(int cols) { if (cols > 24) _cols = cols; }
// 駭客終端為純自走式,不對真實事件反應。
public void Signal(TermSignal sig, string detail) { }
public void Step()
{
_frame++;
if (_pauseLeft > 0) { _pauseLeft--; return; } // 讀取等待停頓(游標仍閃)
if (_typing != null) // 逐字打字(少用,營造「輸入指令」感)
{
_typed += _rng.Next(2, 6);
if (_typed >= _typing.Length) { Commit(_typing, _typingKind); _typing = null; }
return;
}
if (_inProg) // 進度條原地成長(唯一的「等待%」慢節奏)
{
_prog += _rng.Next(4, 16);
if (_prog >= 100) _prog = 100;
_lines[_lines.Count - 1].Text = ProgressText(_prog);
if (_prog >= 100) { _inProg = false; if (_rng.Next(2) == 0) _pauseLeft = _rng.Next(5, 14); }
else if (_rng.Next(7) == 0) _pauseLeft = _rng.Next(3, 10); // 偶爾卡在某 %,像在等回應
return;
}
if (_inSpin) // spinner 原地旋轉(取代生硬的死等)
{
_spinLeft--;
if (_spinLeft <= 0)
{
_inSpin = false;
_lines[_lines.Count - 1].Text = " [ OK ] " + _spinText;
_lines[_lines.Count - 1].Kind = 1;
if (_rng.Next(3) == 0) _pauseLeft = _rng.Next(4, 12);
}
else _lines[_lines.Count - 1].Text = SpinLine(SpinFrames[(_frame / 2) % SpinFrames.Length]);
return;
}
if (_queue.Count == 0) Enqueue(); // 取下一個劇情步驟
var s = _queue.Dequeue();
if (s.Spin) { _inSpin = true; _spinLeft = s.Pause; _spinText = s.Text; Commit(SpinLine(SpinFrames[0]), 2); return; }
if (s.Pause > 0) { _pauseLeft = s.Pause; return; }
if (s.Instant) { Commit(s.Text, s.Kind); return; } // 資料狂跑:直接刷出,不逐字
if (s.Progress) { _inProg = true; _prog = 0; _progLabel = s.Label; _progStyle = _rng.Next(3); Commit(ProgressText(0), 5); }
else { _typing = s.Text; _typed = 0; _typingKind = s.Kind; }
}
private void Commit(string t, int k)
{
_lines.Add(new Line { Text = t, Kind = k });
while (_lines.Count > 80) _lines.RemoveAt(0);
}
private string ProgressText(int p)
{
int n = 30, f = p * n / 100;
switch (_progStyle)
{
case 1: // 流動實心方塊
return " " + new string('▰', f) + new string('▱', n - f) + " " + p.ToString().PadLeft(3) + "% " + _progLabel;
case 2: // 軌道 + 旋轉箭頭,到 100% 收尾
{
bool done = p >= 100;
string head = done ? "" : SpinFrames[(_frame / 2) % SpinFrames.Length];
int tail = Math.Max(0, n - f - (done ? 0 : 1));
return " " + new string('━', f) + head + new string('·', tail) + " " + p.ToString().PadLeft(3) + "% " + _progLabel;
}
default: // 經典 [####----]
return " [" + new string('#', f) + new string('-', n - f) + "] " + p.ToString().PadLeft(3) + "% " + _progLabel;
}
}
// spinner 旋轉動畫的影格與單行組裝
private static readonly string[] SpinFrames = { "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" };
private string SpinLine(string frame) { return " " + frame + " " + _spinText; }
private void QS(string label) { _queue.Enqueue(new Cmd { Spin = true, Pause = _rng.Next(18, 40), Text = label }); }
private void Q(int kind, string text) { _queue.Enqueue(new Cmd { Instant = true, Text = text, Kind = kind }); }
private void QP(string label) { _queue.Enqueue(new Cmd { Progress = true, Label = label }); }
private void QI(int kind, string text) { _queue.Enqueue(new Cmd { Instant = true, Text = text, Kind = kind }); }
// 多組開場 ASCII LOGO(每次鎖屏隨機挑一組,像 Spring Boot / CLI 工具啟動)
private static readonly string[][] Logos =
{
new[]
{
@" ____ _ _ _ _ ____ _ ",
@"/ ___| |_(_) | |/ ___|_ _ __ _ _ __ __| |",
@"\___ \ __| | | | | _| | | |/ _` | '__/ _` |",
@" ___) | |_| | | | |_| | |_| | (_| | | | (_| |",
@"|____/ \__|_|_|_|\____|\__,_|\__,_|_| \__,_|",
},
new[]
{
@" ___ _____ ___ _ _ ___ _ _ _ ___ ___ ",
@"/ __|_ _|_ _| | | | / __| | | | /_\ | _ \ \ ",
@"\__ \ | | | || |__| |__| (_ | |_| |/ _ \| / |) |",
@"|___/ |_| |___|____|____|\___|\___/_/ \_\_|_\___/ ",
},
new[]
{
@"╔═══════════════════════════════════════╗",
@"║ ▓▓▓ S T I L L G U A R D ▓▓▓ ║",
@"║ :: secure desktop lock daemon :: ║",
@"╚═══════════════════════════════════════╝",
},
new[]
{
@" __ ___ _ _ _ ___ _ _ _ _ ___ ___ ",
@"(_ )|_ _| | | | / _) || | /_\ | _ | \",
@" _\ \| || | | |_| (_ | || |/ _ \| | |) )",
@"(___/|_||_|_|___|\___|\__/_/ \_\_|_|___/ ",
},
};
private void EnqueueBanner()
{
QI(0, "");
foreach (var l in Logos[_rng.Next(Logos.Length)]) QI(10, l); // 隨機一組 LOGO(品牌橙)
QI(0, "");
QI(8, " secure desktop lock daemon · v1.0");
QI(9, " " + new string('─', 40));
QI(0, "");
QS("booting StillGuard sentinel"); // spinner 旋轉等待
QI(1, "[ OK ] kernel guard module loaded");
QI(1, "[ OK ] WH_KEYBOARD_LL / WH_MOUSE_LL hooks engaged");
QI(1, "[ OK ] crypto core ready (AES-256-GCM)");
QS("arming sentinel");
QI(1, "[+] sentinel ONLINE — monitoring input devices");
QI(0, "");
}
private void QW(int ticks) { _queue.Enqueue(new Cmd { Pause = ticks }); }
// 把多行內容包進對齊的方框
private string[] BuildBox(string[] inner)
{
int w = 0;
foreach (var s in inner) if (s.Length > w) w = s.Length;
var outp = new List<string>();
outp.Add("╔═" + new string('═', w) + "═╗");
foreach (var s in inner) outp.Add("║ " + s.PadRight(w) + " ║");
outp.Add("╚═" + new string('═', w) + "═╝");
return outp.ToArray();
}
// 一行 hex dump(長行,填滿右側)
private string HexDump()
{
// 位元組數依行寬動態調整,讓 hex dump 鋪滿右側(每 byte 約 4 字元 + 位址 12 + 邊框)
int n = Math.Max(8, Math.Min(48, (_cols - 16) / 4));
var sb = new StringBuilder();
sb.Append("0x").Append(Hex(4)).Append(" ");
var ascii = new StringBuilder();
for (int i = 0; i < n; i++)
{
int b = _rng.Next(0, 256);
sb.Append(b.ToString("X2")).Append((i % 8 == 7) ? " " : " ");
ascii.Append((b >= 32 && b < 127) ? (char)b : '.');
}
sb.Append(" |").Append(ascii).Append('|');
return sb.ToString();
}
// 一個埠掃描表格(box-drawing 對齊)
private string[] BuildPortTable()
{
string[][] rows =
{
new[]{ "22", "open", "ssh OpenSSH_8.9" },
new[]{ "80", "open", "http nginx/1.25" },
new[]{ "443", "open", "https TLS1.3" },
new[]{ "3306", "filtered", "mysql" },
new[]{ "8080", "open", "http-proxy" },
};
int c0 = 5, c1 = 9, c2 = 22;
var L = new List<string>();
L.Add("┌" + new string('─', c0) + "┬" + new string('─', c1) + "┬" + new string('─', c2) + "┐");
L.Add("│" + " PORT".PadRight(c0) + "│" + " STATE".PadRight(c1) + "│" + " SERVICE".PadRight(c2) + "│");
L.Add("├" + new string('─', c0) + "┼" + new string('─', c1) + "┼" + new string('─', c2) + "┤");
foreach (var r in rows)
L.Add("│" + (" " + r[0]).PadRight(c0) + "│" + (" " + r[1]).PadRight(c1) + "│" + (" " + r[2]).PadRight(c2) + "│");
L.Add("└" + new string('─', c0) + "┴" + new string('─', c1) + "┴" + new string('─', c2) + "┘");
return L.ToArray();
}
private string B64(int len)
{
const string cs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var sb = new StringBuilder(len);
for (int i = 0; i < len; i++) sb.Append(cs[_rng.Next(cs.Length)]);
return sb.ToString();
}
// 加權抽取池:畫面豐富型(清單 / 儀表板 / 叢集 / build)與全新圖表型(24~27)
// 權重加倍,提高多樣圖表登場頻率,讓畫面更熱鬧、形態更分歧
private static readonly int[] BlockPool =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 12, 13, 13, 14, 15, 15, 16, 16,
17, 18, 19, 20, 21, 22, 23,
24, 24, 25, 25, 26, 26, 27, 27, 28, 29,
30, 30, 30,
};
// 把一段連貫的劇情排入佇列(看起來像在執行一件完整任務)
// 每次隨機組裝 2~4 個不同「積木段落」,順序 / 長度 / 樣式每次都不同
private void Enqueue()
{
int blocks = _rng.Next(2, 5);
int last = -1;
for (int b = 0; b < blocks; b++)
{
int which = BlockPool[_rng.Next(BlockPool.Length)];
if (which == last) which = BlockPool[_rng.Next(BlockPool.Length)]; // 避免連續重複,重抽一次
last = which;
AppendBlock(which);
}
// 偶爾插入大段資料狂跑或表格,製造節奏變化
if (_rng.Next(3) == 0) { foreach (var l in BuildPortTable()) QI(2, l); QI(0, ""); }
}
private void AppendBlock(int which)
{
string ip = Ip();
switch (which)
{
case 0:
Q(0, "$ nmap -sS -p- -T4 " + ip);
QW(_rng.Next(10, 24));
Q(2, "[*] dispatching SYN probes ...");
QP("scanning " + ip + "/24");
Q(1, "[+] " + _rng.Next(40, 220) + " hosts up " + _rng.Next(2, 18) + "." + _rng.Next(10, 99) + "s");
DumpBurst(_rng.Next(2, 6));
break;
case 1:
Q(0, "$ hydra -l root -P rockyou.txt ssh://" + ip);
Q(2, "[*] loading 14,344,392 entries");
QW(_rng.Next(12, 30));
QP("brute-forcing ssh");
Q(3, "[!] lockout — rotating proxy " + Ip() + " -> " + Ip());
Q(1, "[+] access granted root:" + Hex(_rng.Next(3, 7)));
break;
case 2:
Q(0, "$ ./tunnel --to " + ip + " --enc aes256-gcm");
QS("negotiating handshake");
Q(1, "[+] tunnel up rtt=" + _rng.Next(8, 90) + "ms");
QP("exfiltrating payload");
DumpBurst(_rng.Next(3, 8));
Q(1, "[+] " + _rng.Next(1, 9) + "." + _rng.Next(0, 9) + " GB out trace wiped");
break;
case 3:
Q(0, "$ cryptsetup luksFormat /dev/vault0");
Q(2, "[*] deriving master key (PBKDF2 · 600000 iters)");
QW(_rng.Next(10, 20));
QP("encrypting volume");
Q(1, "[+] sealed sha256:" + Hex(_rng.Next(8, 16)));