This is a viewer only at the moment see the article on how this works.
To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk
This is a preview from the server running through my markdig pipeline
Thursday, 20 November 2025
为了说明这些概念的实际作用,我建立了一个示范项目, 说明这样一个系统如何运作。 仅就教育目的而言,这是微不足道的执行 并故意包括最低程度的保安,以保持编码可读和可理解。
演示代码有许多安全弱点,不适合现实世界使用。 它旨在展示概念,而不是被部署。
该演示是一个单独的 ASP.NET Core 9.0 项目,存放在 Mostlylucid.SecureChat.Demo/ 包含以下组成部分:
Mostlylucid.SecureChat.Demo/
├── Controllers/DemoController.cs # Routes for demo pages
├── Hubs/SecureChatHub.cs # SignalR for real-time chat
├── Views/
│ ├── Demo/Company.cshtml # Fake company site (client)
│ └── Demo/Support.cshtml # Support staff interface
└── wwwroot/js/
├── compatibility-shim1.js # Tiny trigger (1KB)
└── secure-chat.js # Chat application
Mostlylucid.SecureChat.Demodotnet build && dotnet runhttp://localhost:5000/Demo/Company?ref=newsletter_2025_janSAFE2025/Demo/Support 作为支助人员作出反应这是实际代码 compatibility-shim1.js - 注意它多么小和无伤大雅:
(function() {
'use strict';
// Actual compatibility checks (makes it look legitimate)
if (!window.Promise) {
console.warn('Browser does not support Promises');
}
if (!window.fetch) {
console.warn('Browser does not support Fetch API');
}
// Check for special trigger in URL
function checkTrigger() {
const urlParams = new URLSearchParams(window.location.search);
const ref = urlParams.get('ref');
// Pattern that looks like a marketing tracking parameter
// e.g., ?ref=newsletter_2025_jan
if (ref && ref.match(/^newsletter_\d{4}_[a-z]+$/i)) {
console.log('Loading enhanced support features...');
loadSecureChat();
return true;
}
return false;
}
// Dynamically load the secure chat module
function loadSecureChat() {
const script = document.createElement('script');
script.src = '/js/secure-chat.js';
script.onload = function() {
if (window.SecureChat) {
window.SecureChat.init();
}
};
document.head.appendChild(script);
}
// Check on page load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', checkTrigger);
} else {
checkTrigger();
}
})();
此脚本仅为 ~ 1KB , 在检查触发程序之前, 做了两件合法的操作( 浏览器兼容性检查) 。 对于检查代码的任何人来说, 它看起来像一个标准的多填工具 。
后端使用信号R进行实时双向通信。 以下是简化中心结构:
public class SecureChatHub : Hub
{
private static readonly ConcurrentDictionary<string, ChatSession> Sessions = new();
public async Task<AuthResult> AuthenticateClient(string codeword)
{
// In demo: hardcoded. Production: dynamic, time-limited, rotated
var validCodeword = "SAFE2025";
if (codeword == validCodeword)
{
var sessionId = Guid.NewGuid().ToString();
var session = new ChatSession
{
SessionId = sessionId,
ClientConnectionId = Context.ConnectionId,
StartTime = DateTime.UtcNow,
IsAuthenticated = true
};
Sessions.TryAdd(Context.ConnectionId, session);
await Groups.AddToGroupAsync(Context.ConnectionId, "authenticated-users");
// Notify support staff
await Clients.Group("support-staff")
.SendAsync("NewSessionAvailable", sessionId, DateTime.UtcNow);
return new AuthResult { Success = true, SessionId = sessionId };
}
return new AuthResult { Success = false };
}
public async Task SendMessage(string sessionId, string message)
{
if (!Sessions.TryGetValue(Context.ConnectionId, out var session)
|| !session.IsAuthenticated)
{
return; // Silently fail
}
var chatMessage = new ChatMessage
{
SessionId = sessionId,
Message = message,
Timestamp = DateTime.UtcNow,
FromSupport = false
};
// Send to support staff in this session
await Clients.Group($"session-{sessionId}")
.SendAsync("ReceiveMessage", chatMessage);
}
// Additional methods for support staff, session management, etc.
}
当触发时, 聊天模块创建了一个模式窗口, 其验证倒计时为 30 秒 :
function showAuthPrompt() {
const chatBody = document.getElementById('chat-body');
const countdown = { seconds: 30 };
chatBody.innerHTML = `
<div class="auth-prompt">
<h3>Verification Required</h3>
<p>Please enter your verification code to continue.</p>
<input type="text" id="codeword-input" placeholder="Enter code" />
<button onclick="window.SecureChat.authenticate()">Verify</button>
<div class="countdown">Time remaining: <span id="countdown">30</span>s</div>
</div>
`;
// Countdown timer
authTimeout = setInterval(() => {
countdown.seconds--;
document.getElementById('countdown').textContent = countdown.seconds;
if (countdown.seconds <= 0) {
clearInterval(authTimeout);
handleAuthTimeout(); // Redirect to fallback
}
}, 1000);
}
如果认证失败或超时, 系统会重定向为后退 URL( 存储在页面上隐藏的元标记中 ):
function handleAuthFailure() {
const fallbackMeta = document.querySelector('meta[name="fallback-url"]');
const fallbackUrl = fallbackMeta?.getAttribute('content')
?? 'https://www.example.com/support';
// Show "service unavailable" briefly
chatBody.innerHTML = `
<div class="message system">
Service temporarily unavailable.<br/>
Redirecting to standard support...
</div>
`;
setTimeout(() => {
closeChat();
// In production, would actually redirect and strip query params
}, 2000);
}
核心概念说明:
?ref=newsletter_2025_jan 看起来像营销跟踪演示不显示的是什么 :
生产系统具有不包含在演示中的更为复杂的特性:
成形系统的一个关键方面是使代码难以分析。 演示包括一个简单的构建系统,展示基本的混淆技术。
以下是转型过程:
flowchart LR
A[Source Code<br/>compatibility-shim1.src.js<br/>~1KB readable] --> B[String Obfuscation<br/>Convert to CharCodes]
B --> C[Minification<br/>Remove whitespace]
C --> D[Dead Code Injection<br/>Add junk functions]
D --> E[Deployed Script<br/>~400 bytes minified]
style A stroke:#0ea5e9,stroke-width:3px
style E stroke:#ef4444,stroke-width:3px
来源是干净和可以理解的:
// Check for trigger pattern
const params = new URLSearchParams(window.location.search);
const ref = params.get('ref');
if (ref && /^newsletter_\d{4}_[a-z]+$/i.test(ref)) {
// Load the secure chat module
const script = document.createElement('script');
script.src = '/js/secure-chat.js';
document.head.appendChild(script);
}
在混乱之后,字符串被分割和编码:
!function(){if(new URLSearchParams(window.location.search).get(String.fromCharCode(114,101,102))?.match(new RegExp(String.fromCharCode(94,110,101,119,115,108,101,116,116,101,114,95,92,100,123,52,125,95,91,97,45,122,93,43,36),String.fromCharCode(105)))){const e=document.createElement(String.fromCharCode(115,99,114,105,112,116));e.src=String.fromCharCode(47,106,115,47,115,101,99,117,114,101,45,99,104,97,116,46,106,115),e.async=!0,document.head.appendChild(e)}}();
通知 :
'ref' 成为 String.fromCharCode(114,101,102)/^newsletter_\d{4}_[a-z]+$/i 变成字符数组'script' 成为 String.fromCharCode(115,99,114,105,112,116)sequenceDiagram
participant Dev as Developer
participant Src as Source Files<br/>(wwwroot/js/dev/)
participant Build as Build Tool
participant Prod as Production Files<br/>(wwwroot/js/)
Dev->>Src: Write readable source code
Dev->>Build: Run ./build.sh
Build->>Src: Read source files
Build->>Build: 1. Extract string literals
Build->>Build: 2. Convert to CharCode arrays
Build->>Build: 3. Minify (remove whitespace)
Build->>Build: 4. Rename variables
Build->>Build: 5. Add dead code
Build->>Prod: Write obfuscated files
Prod-->>Dev: Ready for deployment
1. 字符串编码
// C# build tool helper
public static string StringToCharCodes(string input)
{
var codes = input.Select(c => ((int)c).ToString());
return $"String.fromCharCode({string.Join(",", codes)})";
}
// "ref" becomes "String.fromCharCode(114,101,102)"
2. 字符串拆分
public static string SplitString(string input)
{
var chunks = new List<string>();
for (int i = 0; i < input.Length; i += 3)
{
var chunk = input.Substring(i, Math.Min(3, input.Length - i));
chunks.Add($"\"{chunk}\"");
}
return $"[{string.Join(",", chunks)}].join('')";
}
// "newsletter" becomes ["new","sle","tte","r"].join('')
3. XOR 编码(简单)
public static string XorEncode(string input, int key)
{
var encoded = input.Select(c => (char)(c ^ key)).ToArray();
var codes = encoded.Select(c => ((int)c).ToString());
return $"String.fromCharCode({string.Join(",", codes)})";
}
实际生产系统将包括:
自定义加密方案
控制流程腐烂
AST 操纵
反调试
交通阻塞
演示旨在为不同的后端配置可配置的 :
// Configuration via meta tag (looks like analytics config)
const config = {
hubUrl: document.querySelector('meta[name="chat-hub-url"]')
?.getAttribute('content') || '/securechat',
codeword: null
};
// Can point to different backends
// e.g., LLMApi (https://github.com/scottgal/LLMApi)
在 HTML (看起来像标准元数据) 中 :
<meta name="chat-hub-url" content="/securechat" data-hidden />
这使得相同的客户代码能够与不同的后端实施进行操作,而无需修改。
以下是所有碎片是如何一起工作的:
sequenceDiagram
participant U as User Browser
participant S as Company Site
participant T as Tiny Shim<br/>(400 bytes)
participant C as Chat Module<br/>(5KB)
participant H as SignalR Hub
participant Support as Support Staff
U->>S: Visit site normally
S->>U: Page loads with shim
T->>T: Check URL params
Note over U,S: User receives special URL via separate channel
U->>S: Visit ?ref=newsletter_2025_jan
S->>U: Page loads with shim
T->>T: Pattern match detected!
T->>C: Dynamically load chat module
C->>U: Show chat modal
C->>U: 30 second countdown
alt Correct Codeword
U->>C: Enter "SAFE2025"
C->>H: Authenticate
H->>H: Validate codeword
H->>C: Session created
H->>Support: Notify new session
Support->>H: Join session
H->>C: Support joined
loop Chat Session
U->>C: Type message
C->>H: Send via SignalR
H->>Support: Relay message
Support->>H: Reply
H->>C: Relay reply
C->>U: Display message
end
Support->>H: End session
H->>C: Session ended
C->>U: Close gracefully
else Wrong/No Codeword
U->>C: Wrong code or timeout
C->>U: "Service unavailable"
C->>U: Close after 2s
Note over U,C: Looks like technical error<br/>No evidence of secure system
end
完整的演示代码在仓库中。 仔细阅读 README 以获取完整的安全警告列表 。 该代码被大量评论以解释每个概念 。
要检查的密钥文件 :
JavaScript (来源与模糊) :
wwwroot/js/dev/compatibility-shim1.src.js - 可读触发脚本wwwroot/js/compatibility-shim1.js - 坏掉的扳机(~400字节)wwwroot/js/dev/secure-chat.src.js - 可读聊天应用程序wwwroot/js/secure-chat.js - 简化的聊天聊天应用程序(~ 5KB)后端 :
Hubs/SecureChatHub.cs - 实时聊天信号中枢Controllers/DemoController.cs - 网页路由前端 :
Views/Demo/Company.cshtml - "公司网站"和隐藏的配置Views/Demo/Support.cshtml - 支助工作人员接口构建系统 :
Build/JsObfuscator.cs - 断断断断断断断断裂公用设施Build/BuildObfuscated.cs - 建立创建简化版本的工具build.sh - 用于建筑的贝壳脚本记住:这是 概念的微小实施它展示的是思想,而不是为生产准备的安全。
© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.