@jshookmcp/jshook 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -4
- package/README.zh.md +19 -4
- package/dist/AntiCheatDetector-B-mz4DK_.mjs +1 -0
- package/dist/{BrowserSessionCoordinator-QIt3tetp.mjs → BrowserSessionCoordinator-Cdic8FsH.mjs} +1 -1
- package/dist/CodeAnalyzerDataFlow-a-NkwcaG.mjs +2 -0
- package/dist/CodeInjector-B099WO6x.mjs +1 -0
- package/dist/ConsoleMonitor-BZRqrBH-.mjs +306 -0
- package/dist/CpuEngine-BC8jayy9.mjs +1 -0
- package/dist/DartAotExecutor-B7WVTKsd.mjs +1 -0
- package/dist/DartAotLoader-BxdhW-K2.mjs +2 -0
- package/dist/DarwinAPI-DzojdfjF.mjs +1 -0
- package/dist/{DetailedDataManager-Z77fDl9Z.mjs → DetailedDataManager-Dgh402Gp.mjs} +2 -2
- package/dist/ExecutionSandbox-QbWQmzuC.mjs +45 -0
- package/dist/ExtensionManager.tools-D3h818Xs.mjs +1 -0
- package/dist/FingerprintManager-D9Zlr6be.mjs +1 -0
- package/dist/HardwareBreakpoint-C_lJ22bj.mjs +1 -0
- package/dist/HeapAnalyzer-bJbLvzp6.mjs +1 -0
- package/dist/HookPatternScanner-yx4vJ9sd.mjs +1 -0
- package/dist/InstrumentationSession-Cv1wikLA.mjs +1 -0
- package/dist/IntegrityScanner-BB7sw-SA.mjs +1 -0
- package/dist/JScramblerDeobfuscator-NVR5VatT.mjs +1 -0
- package/dist/MCPServer.activation.ttl-C2wOCMLV.mjs +1 -0
- package/dist/MCPServer.search.helpers-DlassAew.mjs +2 -0
- package/dist/MemoryController-CCsGuGJS.mjs +2 -0
- package/dist/{MemoryScanSession-zfoVZJB0.mjs → MemoryScanSession-BZ2A9Ph1.mjs} +1 -1
- package/dist/MemoryScanner-DAxsq7Sx.mjs +1 -0
- package/dist/NativeMemoryManager.impl-BIJzXMqH.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-Bu8srMEF.mjs → NativeMemoryManager.utils-CMoul2an.mjs} +1 -1
- package/dist/PEAnalyzer-CB_kaTis.mjs +1 -0
- package/dist/PackerDeobfuscator-BpwGjxDL.mjs +7 -0
- package/dist/PointerChainEngine-B6SYv6ZM.mjs +1 -0
- package/dist/ProcessRegistry-C5W1Tkn9.mjs +1 -0
- package/dist/QuickJSSandbox-CIde-jzG.mjs +299 -0
- package/dist/{ResponseBuilder-nPXl_khE.mjs → ResponseBuilder-BLicSCjn.mjs} +1 -1
- package/dist/ReverseEvidenceGraph-DJzk0GQz.mjs +2 -0
- package/dist/ServerRuntimeState-DGXNv8Ji.mjs +1 -0
- package/dist/Speedhack-MGoeq1ZS.mjs +1 -0
- package/dist/StructureAnalyzer-CCTWAXR3.mjs +2 -0
- package/dist/ToolHandlerMap-C40EmuLT.mjs +1 -0
- package/dist/{ToolProbe-DQiREmNp.mjs → ToolProbe-B02GC3ZY.mjs} +1 -1
- package/dist/ToolRegistry-CzqQxFqf.mjs +1 -0
- package/dist/{ToolRouter.policy-UKBlFlbh.mjs → ToolRouter.policy-Bgb3S8jc.mjs} +2 -2
- package/dist/TraceRecorder-BfeCTQUj.mjs +407 -0
- package/dist/VMDeobfuscator-BHtkV850.mjs +1 -0
- package/dist/Win32API-G7QPyckq.mjs +1 -0
- package/dist/{Win32Debug-DwF8mQGm.mjs → Win32Debug-6yzmtv5b.mjs} +1 -1
- package/dist/allocation-track-CiI-CnaI.mjs +1 -0
- package/dist/analysis-CojUzwX-.mjs +27 -0
- package/dist/{antidebug-CsnpOR9z.mjs → antidebug-CgU84TE1.mjs} +1 -1
- package/dist/apk-DrPBsOq8.mjs +1 -0
- package/dist/artifactRetention-Bk6fW2uF.mjs +1 -0
- package/dist/artifacts-Bx9GLx4J.mjs +1 -0
- package/dist/ast-bridge-BlOrmVAv.mjs +1 -0
- package/dist/ast-utils-B9E5k_v1.mjs +1 -0
- package/dist/binary-instrument-DiE1BP0x.mjs +12 -0
- package/dist/boringssl-inspector-C6M3sOga.mjs +2 -0
- package/dist/browser-QDUu5ML9.mjs +29 -0
- package/dist/{canvas-396ieNv5.mjs → canvas-g5kmLdY-.mjs} +1098 -24
- package/dist/{capabilities-L1ax5EHS.mjs → capabilities-DwzyxL2w.mjs} +1 -1
- package/dist/cdp-session-Dy4OwMOP.mjs +1 -0
- package/dist/collector-Cld4i-E4.mjs +1 -0
- package/dist/config-5ODJ3Aj0.mjs +3 -0
- package/dist/constants-nvsLpSri.mjs +1 -0
- package/dist/coordination-C6y2gM9O.mjs +98 -0
- package/dist/coverage-and-block--cWjjEe5.mjs +1 -0
- package/dist/dart-inspector-D4IKxZ6u.mjs +0 -0
- package/dist/debugger-C2SpiXoO.mjs +1 -0
- package/dist/definitions-0mtilYzG.mjs +1 -0
- package/dist/definitions-9csunmeX.mjs +1 -0
- package/dist/definitions-B11MudW_.mjs +1 -0
- package/dist/definitions-BKpRDjcI.mjs +1 -0
- package/dist/definitions-BXE3H4re.mjs +1 -0
- package/dist/definitions-BlPHe5DX.mjs +1 -0
- package/dist/definitions-Bob4XMxI.mjs +27 -0
- package/dist/definitions-BpIQN2nm.mjs +1 -0
- package/dist/{definitions-Ym8niHDb.mjs → definitions-BvolWeSu.mjs} +1 -1
- package/dist/definitions-C-6j3Ejl.mjs +1 -0
- package/dist/definitions-C-AdFfFu.mjs +1 -0
- package/dist/definitions-CArdw_9T.mjs +1 -0
- package/dist/definitions-CCvIcRrT.mjs +1 -0
- package/dist/definitions-CJPE5PIl.mjs +1 -0
- package/dist/definitions-CbqeW06u.mjs +1 -0
- package/dist/definitions-Cexmkypg.mjs +1 -0
- package/dist/definitions-D1dxl8qt.mjs +1 -0
- package/dist/definitions-D3uT-ZbU.mjs +1 -0
- package/dist/definitions-DtOY5iUc.mjs +1 -0
- package/dist/{definitions-Cv5r8xwq.mjs → definitions-DvrYdDCJ2.mjs} +1 -1
- package/dist/definitions-ihxOqOC4.mjs +1 -0
- package/dist/deopt-trace-qnAcC931.mjs +17 -0
- package/dist/disasm-DoxSucGp.mjs +1 -0
- package/dist/dumpsys-parser-Du-5ruEe.mjs +2 -0
- package/dist/encoding-UMtwgy4M.mjs +2 -0
- package/dist/ensure-browser-core-BP70x0TB.mjs +285 -0
- package/dist/factory-BeND77hf.mjs +2 -0
- package/dist/graphql-CF7QKJME.mjs +68 -0
- package/dist/grpc-raw-Dp7ps2sv.mjs +1 -0
- package/dist/handlers--qCl9vNv.mjs +1 -0
- package/dist/handlers-BHIu1LqA.mjs +1 -0
- package/dist/{handlers-DB6xVVWq.mjs → handlers-BQ4K8Jbr.mjs} +1 -1
- package/dist/handlers-BxQv-wtf.mjs +8 -0
- package/dist/handlers-ByYG27-5.mjs +1 -0
- package/dist/handlers-C0I9-BtX.mjs +5 -0
- package/dist/{handlers-CWKBBjai.mjs → handlers-CL0Iokmw.mjs} +1 -1
- package/dist/handlers-CNbhIdSK.mjs +4 -0
- package/dist/handlers-CnTTSJFs.mjs +109 -0
- package/dist/handlers-CoDx6akJ2.mjs +49 -0
- package/dist/{handlers-BbLxNbbT.mjs → handlers-DASJI0Pn.mjs} +1 -1
- package/dist/handlers-DRKMaA-_.mjs +74 -0
- package/dist/handlers-Dalu0olz.mjs +2 -0
- package/dist/handlers-KY0g31ny.mjs +9 -0
- package/dist/handlers-oGo60aVv.mjs +1 -0
- package/dist/handlers.impl-BTXLw6Qc.mjs +1 -0
- package/dist/heap-sampling-BqdiU-5j.mjs +1 -0
- package/dist/{hooks-DPouiS7I.mjs → hooks-COK3t5rT.mjs} +51 -32
- package/dist/index.mjs +11 -11
- package/dist/logger-BGCcd-jJ.mjs +1 -0
- package/dist/macro-nUYUjKNZ.mjs +2 -0
- package/dist/maintenance-CfnE7ZKU.mjs +4 -0
- package/dist/manifest-7EOTUc0D.mjs +1 -0
- package/dist/manifest-B5ujuQmf.mjs +1 -0
- package/dist/manifest-BErXl3zn.mjs +1 -0
- package/dist/manifest-BKA-mD3J.mjs +1 -0
- package/dist/manifest-BUXj23bX.mjs +1 -0
- package/dist/manifest-BfXt9cau.mjs +1 -0
- package/dist/manifest-Bx-tpURK.mjs +1 -0
- package/dist/manifest-C0owVAdq.mjs +1 -0
- package/dist/manifest-C5XqYc9o.mjs +1 -0
- package/dist/manifest-CVKzLjsA.mjs +1 -0
- package/dist/manifest-CaeFjdhj.mjs +1 -0
- package/dist/manifest-CegBgip0.mjs +1 -0
- package/dist/manifest-CoJHqlgS.mjs +1 -0
- package/dist/manifest-D0dbtDqd.mjs +1 -0
- package/dist/manifest-D5Gr8ujd.mjs +12 -0
- package/dist/manifest-D82z-5og.mjs +1 -0
- package/dist/manifest-DA2afIwh.mjs +1 -0
- package/dist/manifest-DAbiFP5o.mjs +1 -0
- package/dist/manifest-DEY0s1O72.mjs +1 -0
- package/dist/manifest-DTOqNqiA.mjs +1 -0
- package/dist/manifest-DZ6ELNgX.mjs +1 -0
- package/dist/manifest-DjHkjddT.mjs +1 -0
- package/dist/manifest-DocA_itf2.mjs +1 -0
- package/dist/manifest-Dpnhvfq0.mjs +1 -0
- package/dist/manifest-DucPMG_a.mjs +1 -0
- package/dist/manifest-Dw5yYEac.mjs +1 -0
- package/dist/manifest-Ic_Cg66S.mjs +1 -0
- package/dist/manifest-JHaG6GMN.mjs +1 -0
- package/dist/manifest-QdkIzmYM.mjs +1 -0
- package/dist/manifest-YZqaCe25.mjs +1 -0
- package/dist/manifest-f0lUeXwq.mjs +1 -0
- package/dist/manifest-h-Ebisf8.mjs +1 -0
- package/dist/manifest-oOfTymBS.mjs +1 -0
- package/dist/manifest-qXqrO6KC.mjs +2 -0
- package/dist/mapsParser-DrJoeC0c.mjs +1 -0
- package/dist/modules-CC_ADmwi.mjs +333 -0
- package/dist/mojo-ipc-kVztXYw-.mjs +140 -0
- package/dist/native-D9ouskXO.mjs +961 -0
- package/dist/native-bridge-Dzd7hYoq.mjs +1 -0
- package/dist/network-C5Y-S87J.mjs +7 -0
- package/dist/one-gadget-CiWFE17F.mjs +1 -0
- package/dist/outputPaths-CHtELDyi.mjs +1 -0
- package/dist/parse-args-B6dwWc9k.mjs +1 -0
- package/dist/platform-BIXgJaM3.mjs +94 -0
- package/dist/process-aDIfLC0v.mjs +6 -0
- package/dist/proxy-DsHsQ1I4.mjs +2 -0
- package/dist/registry-7h8jJ9y9.mjs +1 -0
- package/dist/{registry-xB8Wgmyj.mjs → registry-DJDnkQW2.mjs} +1 -1
- package/dist/response-R8ghbZSb.mjs +1 -0
- package/dist/retry-policy-DtYv0kDi.mjs +1 -0
- package/dist/reverseEngineeringConfig-BhZLOa3C.mjs +1 -0
- package/dist/safeOutput-Dt4mfjXA.mjs +1 -0
- package/dist/{search-defaults-CJik67or.mjs → search-defaults-BBRJNAzC.mjs} +1 -1
- package/dist/server/search/EmbeddingWorker.d.mts +1 -0
- package/dist/server/search/EmbeddingWorker.mjs +1 -0
- package/dist/shared-BKtWZDGN.mjs +1 -0
- package/dist/sourcemap-2VIeVeKw.mjs +3 -0
- package/dist/streaming-DkpE3GGU.mjs +15 -0
- package/dist/syscall-DGZoYM_U.mjs +1 -0
- package/dist/transform-BJqsBC_-.mjs +105 -0
- package/dist/turbofan-graph-CbGHNVtl.mjs +1 -0
- package/dist/turbofan-inspect--NdCuYXi.mjs +23 -0
- package/dist/types-CWSvzmIh.mjs +1 -0
- package/dist/v8-inspector-CTJo08-K.mjs +297 -0
- package/dist/wasm-DX4Qm2Vs.mjs +235 -0
- package/dist/weakrefs-inspect-CnhaF-rN.mjs +57 -0
- package/dist/webgpu-D4-DxbxZ.mjs +6 -0
- package/dist/workflow-DHktRNF2.mjs +108 -0
- package/package.json +33 -27
- package/dist/AntiCheatDetector-CUpZBh5O.mjs +0 -1
- package/dist/CodeInjector-Btj9upnf.mjs +0 -1
- package/dist/ConsoleMonitor-DIjN5Afa.mjs +0 -306
- package/dist/DarwinAPI-BuMPGzHm.mjs +0 -1
- package/dist/ExtensionManager.tools-CIGOWViz.mjs +0 -1
- package/dist/FingerprintManager-BkDSsjjP.mjs +0 -1
- package/dist/HardwareBreakpoint-DMAMcPyB.mjs +0 -1
- package/dist/HeapAnalyzer-Yj348FYt.mjs +0 -1
- package/dist/InstrumentationSession-c5qZyp7d.mjs +0 -1
- package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +0 -1
- package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +0 -1
- package/dist/MemoryController-DjtgiING.mjs +0 -2
- package/dist/MemoryScanner-Dxd657li.mjs +0 -1
- package/dist/PEAnalyzer-CMu9Ua9T.mjs +0 -1
- package/dist/PointerChainEngine-CaSC1Mry.mjs +0 -1
- package/dist/ProcessRegistry-D5y1yuP2.mjs +0 -1
- package/dist/ReverseEvidenceGraph-BksOpsPs.mjs +0 -2
- package/dist/ServerRuntimeState-CgqBBwfd.mjs +0 -1
- package/dist/Speedhack-pwXTHxOY.mjs +0 -1
- package/dist/StructureAnalyzer-BseGzsSl.mjs +0 -2
- package/dist/ToolCatalog-DgmQXdsm.mjs +0 -1
- package/dist/ToolHandlerMap-7HWoIgQO.mjs +0 -1
- package/dist/ToolRegistry-eMZEBiR1.mjs +0 -1
- package/dist/TraceRecorder-B5ktv3nP.mjs +0 -272
- package/dist/VersionDetector-CmPJmaJg.mjs +0 -1
- package/dist/Win32API-DoP3MMHS.mjs +0 -1
- package/dist/WorkflowEngine-CldHG5b4.mjs +0 -1
- package/dist/analysis-C-ln0Brh.mjs +0 -6
- package/dist/artifactRetention-DkYKLOvi.mjs +0 -1
- package/dist/artifacts-D-4pSS_N.mjs +0 -1
- package/dist/binary-instrument-BeZ224mZ.mjs +0 -9
- package/dist/boringssl-inspector-ZOCkaipa.mjs +0 -2
- package/dist/browser-BUaB25bk.mjs +0 -11
- package/dist/collector-CB2syQEg.mjs +0 -1
- package/dist/constants-DMv3svps.mjs +0 -2
- package/dist/coordination-Dbohmj6D.mjs +0 -1
- package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
- package/dist/debugger-CLzkObIO.mjs +0 -1
- package/dist/definitions-0hxnrDU72.mjs +0 -1
- package/dist/definitions-B3a9QC2t.mjs +0 -1
- package/dist/definitions-BOvju5t2.mjs +0 -1
- package/dist/definitions-CXj_cEVt.mjs +0 -1
- package/dist/definitions-Co6AvTjH.mjs +0 -1
- package/dist/definitions-DBYSxChX.mjs +0 -1
- package/dist/definitions-D_dTDX9B.mjs +0 -1
- package/dist/definitions-Db9t2ddh.mjs +0 -1
- package/dist/definitions-DbN2CjI2.mjs +0 -1
- package/dist/definitions-DlmmHmZc.mjs +0 -1
- package/dist/definitions-DnYpoGig.mjs +0 -1
- package/dist/definitions-DtZ6Ktx2.mjs +0 -1
- package/dist/definitions-DuIPS8gq.mjs +0 -1
- package/dist/definitions-DywfwPMb.mjs +0 -1
- package/dist/definitions-EGmqr85H.mjs +0 -1
- package/dist/definitions-Fetw_Cge.mjs +0 -26
- package/dist/definitions-LdkeuOeA.mjs +0 -1
- package/dist/definitions-cnG6tj17.mjs +0 -1
- package/dist/encoding-B4xZWErf.mjs +0 -2
- package/dist/ensure-browser-core-JHwDo5ql.mjs +0 -285
- package/dist/factory-BxNdBiZa.mjs +0 -1
- package/dist/graphql-GBWsZ9xC.mjs +0 -62
- package/dist/handlers-5nzR8B0a.mjs +0 -5
- package/dist/handlers-6iNsXOVT.mjs +0 -7
- package/dist/handlers-BZ8n6Hvf.mjs +0 -1
- package/dist/handlers-BbS4hssc.mjs +0 -4
- package/dist/handlers-CIKOP4aI.mjs +0 -2
- package/dist/handlers-Cmb6SoRC.mjs +0 -1
- package/dist/handlers-CrJsKnEI.mjs +0 -1
- package/dist/handlers-DOOCWUNR.mjs +0 -31
- package/dist/handlers-Z_B5aVaU.mjs +0 -54
- package/dist/handlers-gVscChvl.mjs +0 -1
- package/dist/handlers-xFvI9P_y.mjs +0 -1
- package/dist/handlers.impl-BsFTW6SD.mjs +0 -1
- package/dist/logger-CCikqqvj.mjs +0 -1
- package/dist/macro-p8kuJVcm.mjs +0 -2
- package/dist/maintenance-DAqADb6Z.mjs +0 -302
- package/dist/manifest-4lmM6MZR.mjs +0 -1
- package/dist/manifest-AxaxRSt6.mjs +0 -2
- package/dist/manifest-BIqRE1Qz.mjs +0 -1
- package/dist/manifest-Box-jWfr.mjs +0 -1
- package/dist/manifest-Bp33di0Q.mjs +0 -1
- package/dist/manifest-BvRX4nRP.mjs +0 -1
- package/dist/manifest-C6KoB1XE.mjs +0 -1
- package/dist/manifest-C7TdXCWY.mjs +0 -1
- package/dist/manifest-CM-n64K0.mjs +0 -1
- package/dist/manifest-CUokxCUN.mjs +0 -1
- package/dist/manifest-CWJS45iO.mjs +0 -1
- package/dist/manifest-Cdxdgo-D.mjs +0 -1
- package/dist/manifest-Cf6SmamD.mjs +0 -1
- package/dist/manifest-Cgxu2qdv.mjs +0 -1
- package/dist/manifest-CowGSURa2.mjs +0 -1
- package/dist/manifest-CsGIrh34.mjs +0 -1
- package/dist/manifest-CvDpVToN.mjs +0 -1
- package/dist/manifest-D8TL9RLE.mjs +0 -1
- package/dist/manifest-DIhtCBe6.mjs +0 -1
- package/dist/manifest-DJbruNOg.mjs +0 -1
- package/dist/manifest-DLGtZH-0.mjs +0 -1
- package/dist/manifest-DXHdPt2T.mjs +0 -1
- package/dist/manifest-Dg5ScOyW.mjs +0 -1
- package/dist/manifest-DzGoTS0R.mjs +0 -1
- package/dist/manifest-G2H52LKz.mjs +0 -131
- package/dist/manifest-P0Futrgb.mjs +0 -1
- package/dist/manifest-Qw7xgvjv.mjs +0 -1
- package/dist/manifest-W3qvVrP2.mjs +0 -1
- package/dist/manifest-dG6MuR1U.mjs +0 -1
- package/dist/manifest-nWXtgq5Y2.mjs +0 -1
- package/dist/manifest-vp1upSSq.mjs +0 -1
- package/dist/modules-DO3jXCgj.mjs +0 -333
- package/dist/mojo-ipc-Be-ccWrc.mjs +0 -9
- package/dist/native-g095qhpK.mjs +0 -961
- package/dist/network-Dvxm7eEI.mjs +0 -7
- package/dist/outputPaths-D2ddHrOJ.mjs +0 -2
- package/dist/parse-args-ngRrvF9e.mjs +0 -1
- package/dist/platform-DjWbuiF8.mjs +0 -93
- package/dist/process-Dq5I-KZW.mjs +0 -2
- package/dist/proxy-DPNgM7TE.mjs +0 -2
- package/dist/renderer-pid-7jbTR8f5.mjs +0 -1
- package/dist/response-B1RuVVfD.mjs +0 -1
- package/dist/sourcemap-DqEW15Ao.mjs +0 -1
- package/dist/streaming-Dbk4eStJ.mjs +0 -1
- package/dist/transform-D-peM3aO.mjs +0 -103
- package/dist/wasm-CZajRaad.mjs +0 -174
- package/dist/webcrack-phEfVt5y.mjs +0 -46
- package/dist/workflow-wkXb3x-U.mjs +0 -101
- /package/dist/{chunk-88NL7fhV.mjs → rolldown-runtime-88NL7fhV.mjs} +0 -0
|
@@ -0,0 +1,961 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-88NL7fhV.mjs";import{t}from"./logger-BGCcd-jJ.mjs";import{Ar as n,Cr as r,D as i,Dr as a,Er as o,Fr as s,I as c,Ir as l,L as u,La as d,Lr as f,Mr as p,Nr as m,Or as h,Rr as g,Sr as _,Tr as v,_a as y,_r as b,br as x,et as S,gr as ee,jr as C,kr as te,va as w,vr as ne,wr as T,xr as E,yr as re,zr as ie}from"./constants-nvsLpSri.mjs";import{t as D}from"./ProcessRegistry-C5W1Tkn9.mjs";import{S as ae}from"./Win32API-G7QPyckq.mjs";import{n as O,t as oe}from"./mapsParser-DrJoeC0c.mjs";import{r as k,t as se}from"./NativeMemoryManager.utils-CMoul2an.mjs";import{t as A}from"./NativeMemoryManager.impl-BIJzXMqH.mjs";import{existsSync as j,promises as ce,readFileSync as le}from"fs";import{platform as ue,tmpdir as M}from"node:os";import{closeSync as de,createReadStream as fe,existsSync as pe,openSync as me,promises as N,readFileSync as he,readSync as ge,statSync as _e}from"node:fs";import{join as P}from"node:path";import{fileURLToPath as ve}from"node:url";import{createHash as ye}from"node:crypto";import{execSync as be}from"node:child_process";import{exec as F,execFile as xe,spawn as Se}from"child_process";import{promisify as I}from"util";let L=null;function Ce(){if(L)return L;try{return L=ve(new URL(`.`,import.meta.url)),L}catch{return null}}var R=class{scriptCache=new Map;scriptsDir;constructor(){let e=Ce();e&&j(P(e,`native`,`scripts`))?this.scriptsDir=P(e,`native`,`scripts`):e&&j(P(e,`scripts`))?this.scriptsDir=P(e,`scripts`):j(P(process.cwd(),`dist`,`native`,`scripts`))?this.scriptsDir=P(process.cwd(),`dist`,`native`,`scripts`):j(P(process.cwd(),`src`,`native`,`scripts`))?this.scriptsDir=P(process.cwd(),`src`,`native`,`scripts`):this.scriptsDir=P(process.cwd(),`dist`,`native`,`scripts`)}async loadScript(e){if(this.scriptCache.has(e))return this.scriptCache.get(e);let t=ue(),n=t===`win32`?`windows`:t===`darwin`?`macos`:`linux`,r=P(this.scriptsDir,n,e),i=await ce.readFile(r,`utf-8`);return this.scriptCache.set(e,i),i}getScriptPath(e){let t=ue(),n=t===`win32`?`windows`:t===`darwin`?`macos`:`linux`;return P(this.scriptsDir,n,e)}clearCache(){this.scriptCache.clear()}},we=class{scriptLoader;browserSignatures=new Map([[`chrome`,{windowClasses:[`Chrome_WidgetWin_0`,`Chrome_WidgetWin_1`,`Chrome_WidgetWin_*`],processNames:[`chrome.exe`,`chrome`],mainWindowTitle:/.*- Google Chrome$/,debugPorts:[9222,9229,9333]}],[`edge`,{windowClasses:[`Edge_WidgetWin_0`,`Edge_WidgetWin_1`,`Edge_WidgetWin_*`],processNames:[`msedge.exe`,`msedge`],mainWindowTitle:/.*- Microsoft Edge$/,debugPorts:[9222,9229]}],[`firefox`,{windowClasses:[`MozillaWindowClass`],processNames:[`firefox.exe`,`firefox`],mainWindowTitle:/.*- Mozilla Firefox$/,debugPorts:[9222]}]]);constructor(){this.scriptLoader=new R}sanitizePsInput(e){return e.replace(/[`$"'{}();|<>@#%!\\\n\r]/g,``)}escapePowerShellSingleQuoted(e){return this.sanitizePsInput(e).replace(/'/g,`''`)}async discoverBrowsers(){let e=[];for(let[t,n]of this.browserSignatures){let r=await this.findBySignature(t,n);e.push(...r)}return e}async findBySignature(e,t){let n=[],r=new Set;for(let i of t.processNames){let t=await this.findByProcessName(i);for(let i of t)r.has(i.pid)||(r.add(i.pid),n.push({type:e,pid:i.pid,hwnd:i.hwnd,title:i.title}))}for(let i of t.windowClasses){let t=await this.findByWindowClass(i);for(let i of t)r.has(i.pid)||(r.add(i.pid),n.push({type:e,pid:i.pid,hwnd:i.hwnd,title:i.title}))}for(let e of n){let n=await this.detectDebugPort(e.pid,t.debugPorts);n&&(e.debugPort=n)}return n}async findByWindowClass(e){let t=this.scriptLoader.getScriptPath(`enum-windows-by-class.ps1`);try{let n=this.escapePowerShellSingleQuoted(e),{execFile:r}=await import(`child_process`),{promisify:i}=await import(`util`),{stdout:a}=await i(r)(`powershell.exe`,[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,t,`-ClassPattern`,n],{maxBuffer:1024*1024*10});return this.parseWindowsResult(a,e)}catch(t){return console.error(`Failed to find windows by class '${e}':`,t),[]}}async findByProcessName(e){try{let t=`$Pattern='${this.escapePowerShellSingleQuoted(e)}'; Get-Process -Name "*$Pattern*" -ErrorAction SilentlyContinueSelect-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64ConvertTo-Json -Compress`,{execFile:n}=await import(`child_process`),{promisify:r}=await import(`util`),{stdout:i}=await r(n)(`powershell.exe`,[`-NoProfile`,`-Command`,t],{maxBuffer:1024*1024*10});return this.parseProcessResult(i,e)}catch(t){return console.error(`Failed to find process by name '${e}':`,t),[]}}parseWindowsResult(e,t){let n=[];if(!e.trim()||e.trim()===`null`)return n;try{let t=JSON.parse(e.trim()),r=Array.isArray(t)?t:[t];for(let e of r){let t=`unknown`,r=e.Title||``;for(let[e,n]of this.browserSignatures)if(n.mainWindowTitle?.test(r)){t=e;break}if(t===`unknown`)for(let[n,r]of this.browserSignatures){for(let i of r.windowClasses){let r=i.replace(/\*/g,`.*`);if(new RegExp(r).test(e.ClassName||``)){t=n;break}}if(t!==`unknown`)break}n.push({type:t,pid:e.ProcessId,hwnd:e.Handle,title:e.Title})}}catch(e){console.error(`Failed to parse windows result:`,e)}return n}parseProcessResult(e,t){let n=[];if(!e.trim()||e.trim()===`null`)return n;try{let t=JSON.parse(e.trim()),r=Array.isArray(t)?t:[t];for(let e of r){let t=`unknown`,r=(e.ProcessName||``).toLowerCase();r.includes(`chrome`)?t=`chrome`:r.includes(`msedge`)||r.includes(`edge`)?t=`edge`:r.includes(`firefox`)&&(t=`firefox`),n.push({type:t,pid:e.Id,hwnd:e.MainWindowHandle?.toString(),title:e.MainWindowTitle})}}catch(e){console.error(`Failed to parse process result:`,e)}return n}async detectDebugPort(e,t){let n=await this.checkDebugPortFromCommandLine(e);if(n)return n;for(let n of t)if(await this.checkPort(e,n))return n;return null}async checkDebugPortFromCommandLine(e){let{execFile:t}=await import(`child_process`),{promisify:n}=await import(`util`),r=n(t);try{if(!Number.isFinite(e)||e<=0)return null;let{stdout:t}=await r(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-CimInstance Win32_Process -Filter "ProcessId = ${Math.trunc(e)}"Select-Object CommandLine, ParentProcessId | ConvertTo-Json -Compress`],{maxBuffer:1024*1024});if(!t.trim()||t.trim()===`null`)return null;let n=(JSON.parse(t.trim()).CommandLine||``).match(/--remote-debugging-port=(\d+)/);return n?.[1]?parseInt(n[1],10):null}catch{return null}}async checkPort(e,t){let{execFile:n}=await import(`child_process`),{promisify:r}=await import(`util`),i=r(n);try{if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)return!1;let{stdout:n}=await i(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-NetTCPConnection -OwningProcess ${Math.trunc(e)} -State Listen -ErrorAction SilentlyContinueSelect-Object LocalPort | ConvertTo-Json -Compress`],{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return!1;let r=JSON.parse(n.trim()),a=Array.isArray(r)?r:[r];for(let e of a)if(e.LocalPort===t)return!0;return!1}catch{return!1}}};function Te(e,t){return t?typeof t==`string`?e.includes(t):t.test(e):!1}async function Ee(e,t){let n={rendererProcesses:[],utilityProcesses:[]};try{let r;if(e.processNamePattern instanceof RegExp){let n=await t.findProcesses(``),i=e.processNamePattern;r=n.filter(e=>i.test(e.name))}else{let n=e.processNamePattern||`chromium`;r=await t.findProcesses(n)}for(let e of r){let r=await t.getProcessCommandLine(e.pid);if(r?.commandLine){let t=r.commandLine.toLowerCase();t.includes(`--type=renderer`)?n.rendererProcesses.push({...e,...r}):t.includes(`--type=gpu-process`)?n.gpuProcess={...e,...r}:t.includes(`--type=utility`)?n.utilityProcesses.push({...e,...r}):t.includes(`--type=`)||(n.mainProcess={...e,...r})}else n.mainProcess||=e}let i=[n.mainProcess?.pid,...n.rendererProcesses.map(e=>e.pid)].filter(Boolean),a=t=>Te(t.title,e.windowTitlePattern)||Te(t.className,e.windowClassPattern);for(let e of i){let r=(await t.getProcessWindows(e)).find(a);if(r){n.targetWindow=r;break}}return t.logInfo(`Chromium processes found:`,{main:n.mainProcess?.pid,renderers:n.rendererProcesses.length,hasTargetWindow:!!n.targetWindow}),n}catch(e){return t.logError(`Failed to find Chromium processes:`,e),n}}const De={processNamePattern:/^(chromium|chrome|msedge)$/i,windowClassPattern:`Chrome_WidgetWin`},z=I(F);function Oe(e){return String(e||``).replace(/[`$"'{}();|<>@#%!\\\n\r]/g,``)}function B(e){let t=Math.trunc(Number(e));if(!Number.isFinite(t)||t<=0)throw Error(`Invalid PID: ${e}`);return t}var ke=class{powershellPath=`powershell.exe`;scriptLoader;browserDiscovery;processCache=new Map;constructor(){this.scriptLoader=new R,this.browserDiscovery=new we,t.info(`ProcessManager initialized for Windows platform`)}async findProcesses(e){try{let n=Oe(String(e||``).trim()),r=n.toLowerCase()||`*`,i=Date.now(),a=this.processCache.get(r);if(a&&a.expiresAt>i)return a.snapshot;let o;o=n?`Get-Process -Name "*${n.replace(/"/g,`""`)}*" -ErrorAction SilentlyContinue Select-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64 ConvertTo-Json -Compress`:`Get-Process -ErrorAction SilentlyContinue | Select-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64 | ConvertTo-Json -Compress`;let{stdout:s}=await z(`${this.powershellPath} -NoProfile -Command "${o}"`,{maxBuffer:d}),c=s.trim(),l=[];if(c&&c!==`null`){let e=JSON.parse(c),t=Array.isArray(e)?e:[e];for(let e of t)l.push({pid:e.Id,name:e.ProcessName,executablePath:e.Path})}let u=new Map;for(let e of l)u.set(e.pid,e);let f=this.computeProcessDiff(a?.byPid??new Map,u);this.processCache.set(r,{expiresAt:i+3e3,snapshot:l,byPid:u,lastDelta:f});let p=n.length>0?`'${n}'`:`all`;return t.info(`Found ${l.length} processes matching ${p}`),l}catch(n){return t.error(`Failed to find processes with pattern '${e}':`,n),[]}}computeProcessDiff(e,t){let n=[],r=[],i=[];for(let[r,a]of t){let t=e.get(r);if(!t){n.push(a);continue}(t.pid!==a.pid||t.name!==a.name||t.executablePath!==a.executablePath)&&i.push({before:t,after:a})}for(let[n,i]of e)t.has(n)||r.push(i);return{added:n,removed:r,changed:i}}async getProcessByPid(e){try{e=B(e);let t=`Get-Process -Id ${e} -ErrorAction SilentlyContinue | Select-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64, StartTime | ConvertTo-Json -Compress`,{stdout:n}=await z(`${this.powershellPath} -NoProfile -Command "${t}"`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return null;let r=JSON.parse(n.trim());return{pid:r.Id,name:r.ProcessName,executablePath:r.Path,windowTitle:r.MainWindowTitle,windowHandle:r.MainWindowHandle?.toString(),cpuUsage:r.CPU,memoryUsage:r.WorkingSet64}}catch(n){return t.error(`Failed to get process by PID ${e}:`,n),null}}async getProcessWindows(e){try{e=B(e);let t=await this.scriptLoader.getScriptPath(`enum-windows.ps1`),{stdout:n}=await z(`${this.powershellPath} -NoProfile -ExecutionPolicy Bypass -File "${t}" -TargetPid ${e}`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return[];let r=JSON.parse(n.trim()),i=[],a=Array.isArray(r)?r:[r];for(let e of a)i.push({handle:e.Handle,title:e.Title,className:e.ClassName,processId:e.ProcessId,threadId:0});return i}catch(n){return t.error(`Failed to get windows for PID ${e}:`,n),[]}}async findChromiumProcesses(e=De){return Ee(e,{findProcesses:e=>this.findProcesses(e),getProcessCommandLine:e=>this.getProcessCommandLine(e),getProcessWindows:e=>this.getProcessWindows(e),logInfo:(e,n)=>t.info(e,n),logError:(e,n)=>t.error(e,n)})}async findChromiumAppProcesses(){return this.findChromiumProcesses()}async getProcessCommandLine(e){try{e=B(e);let t=`Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}' | Select-Object CommandLine, ParentProcessId | ConvertTo-Json -Compress`,{stdout:n}=await z(`${this.powershellPath} -NoProfile -Command "${t}"`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return{};let r=JSON.parse(n.trim());return{commandLine:r.CommandLine,parentPid:r.ParentProcessId}}catch(n){return t.error(`Failed to get command line for PID ${e}:`,n),{}}}async checkDebugPort(e,n){try{e=B(e);let t=n?.commandLine??(await this.getProcessCommandLine(e)).commandLine;if(t){let e=t.match(/--remote-debugging-port=(\d+)/);if(e?.[1])return parseInt(e[1],10)}let r=`Get-NetTCPConnection -OwningProcess ${e} -State Listen -ErrorAction SilentlyContinueSelect-Object LocalPort | ConvertTo-Json -Compress`,{stdout:i}=await z(`${this.powershellPath} -NoProfile -Command "${r}"`,{maxBuffer:1024*1024});if(i.trim()&&i.trim()!==`null`){let e=JSON.parse(i.trim()),t=Array.isArray(e)?e:[e];for(let e of t)if(y.includes(e.LocalPort))return e.LocalPort}return null}catch(n){return t.error(`Failed to check debug port for PID ${e}:`,n),null}}async findPidByListeningPort(e){try{let t=`Get-NetTCPConnection -LocalPort ${e} -State Listen -ErrorAction SilentlyContinueSelect-Object -First 1 OwningProcess | ConvertTo-Json -Compress`,{stdout:n}=await z(`${this.powershellPath} -NoProfile -Command "${t}"`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return null;let r=JSON.parse(n.trim()),i=Array.isArray(r)?r[0]:r,a=i?.OwningProcess??i?.owningProcess??i,o=Number(a);return Number.isFinite(o)&&o>0?o:null}catch{return null}}async launchWithDebug(e,n=w,r=[]){try{let i=Se(e,[`--remote-debugging-port=${n}`,...r],{detached:!0,stdio:`ignore`});i.unref(),D.register(i);let a=i.pid||0,o=e.split(/[\\/]/).pop()||`unknown`,s=a>0?a:null;for(let r=0;r<c;r++){let r=await this.findPidByListeningPort(n);if(r&&r>0&&(s=r),s&&s>0){let a=await this.getProcessByPid(s);if(a)return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,resolvedPid:s,executable:e}),a;if(r&&r===s)return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,resolvedPid:s,executable:e}),{pid:s,name:o,executablePath:e}}await new Promise(e=>setTimeout(e,u))}return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,resolvedPid:s,executable:e}),s&&s>0?{pid:s,name:o,executablePath:e}:null}catch(e){return t.error(`Failed to launch process with debug:`,e),null}}async injectDll(e,n){try{if(!Number.isFinite(e)||e<=0)return t.error(`Invalid PID for injectDll: ${e}`),!1;let r=this.scriptLoader.getScriptPath(`inject-dll.ps1`),i=Math.trunc(e),a=String(n).replace(/'/g,`''`);return await z(`${this.powershellPath} -NoProfile -ExecutionPolicy Bypass -File "${r}" -TargetPid ${i} -DllPath '${a}'`,{maxBuffer:1024*1024}),t.warn(`DLL injection is disabled for safety in this implementation`),!1}catch(e){return t.error(`DLL injection failed:`,e),!1}}async killProcess(e){try{if(!Number.isFinite(e)||e<=0)return t.error(`Invalid PID for killProcess: ${e}`),!1;let n=Math.trunc(e),r=`Stop-Process -Id ${n} -Force -ErrorAction SilentlyContinue; Write-Output "Process ${n} killed"`;return await z(`${this.powershellPath} -NoProfile -Command "${r}"`,{maxBuffer:1024*1024}),t.info(`Process ${n} killed successfully`),!0}catch(n){return t.error(`Failed to kill process ${e}:`,n),!1}}async discoverBrowsers(){try{let e=await this.browserDiscovery.discoverBrowsers();return t.info(`Discovered ${e.length} browser instances`),e}catch(e){return t.error(`Failed to discover browsers:`,e),[]}}async findBrowserByWindowClass(e){try{let n=await this.browserDiscovery.findByWindowClass(e);return t.info(`Found ${n.length} browsers matching window class '${e}'`),n}catch(n){return t.error(`Failed to find browser by window class '${e}':`,n),[]}}async findBrowserByProcessName(e){try{let n=await this.browserDiscovery.findByProcessName(e);return t.info(`Found ${n.length} browsers matching process name '${e}'`),n}catch(n){return t.error(`Failed to find browser by process name '${e}':`,n),[]}}async detectBrowserDebugPort(e,n){try{let r=n||y,i=await this.browserDiscovery.detectDebugPort(e,r);return i?t.info(`Detected debug port ${i} for process ${e}`):t.warn(`No debug port detected for process ${e}`),i}catch(n){return t.error(`Failed to detect debug port for PID ${e}:`,n),null}}};const V=I(F);function Ae(e){return String(e||``).replace(/[^\w\s.@/\-:,+]/g,``)}function H(e){let t=Math.trunc(Number(e));if(!Number.isFinite(t)||t<=0)throw Error(`Invalid PID: ${e}`);return t}var je=class{isWayland=!1;constructor(){this.detectDisplayServer(),t.info(`LinuxProcessManager initialized`,{displayServer:this.isWayland?`Wayland`:`X11`})}async detectDisplayServer(){try{let{stdout:e}=await V(`echo $XDG_SESSION_TYPE`);this.isWayland=e.trim()===`wayland`}catch{this.isWayland=!1}}async findProcesses(e){try{let{stdout:n}=await V(`ps aux | grep -i "${Ae(e)}" | grep -v grep || true`,{maxBuffer:d}),r=[],i=n.trim().split(`
|
|
2
|
+
`).filter(e=>e.trim());for(let e of i){let t=e.trim().split(/\s+/);if(t.length>=11){let e=parseInt(t[1]||`0`,10);if(isNaN(e))continue;let n=parseFloat(t[2]||`0`),i=parseFloat(t[3]||`0`),a=t.slice(10).join(` `);r.push({pid:e,name:t[10]||a.split(` `)[0]||`unknown`,commandLine:a,cpuUsage:n,memoryUsage:i*1024*1024})}}return t.info(`Found ${r.length} processes matching '${e}'`),r}catch(n){return t.error(`Failed to find processes with pattern '${e}':`,n),[]}}async getProcessByPid(e){try{e=H(e);let{stdout:t}=await V(`cat /proc/${e}/status 2>/dev/null || echo ""`),{stdout:n}=await V(`cat /proc/${e}/cmdline 2>/dev/null | tr '\0' ' ' || echo ""`),{stdout:r}=await V(`cat /proc/${e}/stat 2>/dev/null || echo ""`);if(!t.trim())return null;let i={};for(let e of t.split(`
|
|
3
|
+
`)){let[t,n]=e.split(`:`);t&&n&&(i[t.trim()]=n.trim())}let a=r.trim().split(` `),o=a.length>13?parseInt(a[13]||`0`,10):0,s=a.length>14?parseInt(a[14]||`0`,10):0;return{pid:e,name:i.Name||`unknown`,executablePath:await this.getProcessPath(e),commandLine:n.trim()||void 0,parentPid:i.PPid?parseInt(i.PPid,10):void 0,memoryUsage:i.VmRSS?parseInt(i.VmRSS.replace(/\D/g,``),10)*1024:void 0,cpuUsage:o+s}}catch(n){return t.error(`Failed to get process by PID ${e}:`,n),null}}async getProcessPath(e){try{e=H(e);let{stdout:t}=await V(`readlink -f /proc/${e}/exe 2>/dev/null || echo ""`);return t.trim()||void 0}catch{return}}async getProcessWindows(e){let n=[];try{if(e=H(e),this.isWayland){t.debug(`Attempting Wayland window enumeration via compositor-specific APIs`);try{let{stdout:t}=await V(`hyprctl clients -j 2>/dev/null`);if(t.trim()){let r=JSON.parse(t);for(let t of r)t.pid===e&&n.push({handle:t.address||t.window||`0`,title:t.title||``,className:t.class||``,processId:e,threadId:0});if(n.length>0)return n}}catch{}try{let{stdout:n}=await V(`gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell --method org.gnome.Shell.Eval "global.get_window_actors().filter(w => w.meta_window.get_pid() === ${e}).map(w => w.meta_window.get_title() + '|' + w.meta_window.get_wm_class())" 2>/dev/null`);(n.includes(String(e))||n.includes(`,`))&&t.debug(`GNOME Wayland window query returned data, but reliable parsing is not yet implemented`)}catch{}}let{stdout:r}=await V(`which xdotool 2>/dev/null || echo ""`);if(!r.trim())return this.isWayland&&n.length===0?t.warn(`Wayland native enumeration failed and xdotool is missing. Install xdotool for XWayland fallback.`):this.isWayland||t.warn(`xdotool not found. Install it for window management: sudo apt-get install xdotool`),n;let{stdout:i}=await V(`xdotool search --all --pid ${e} 2>/dev/null || true`),a=i.trim().split(`
|
|
4
|
+
`).filter(e=>e.trim());for(let t of a)try{let{stdout:r}=await V(`xdotool getwindowname ${t} 2>/dev/null || echo ""`),{stdout:i}=await V(`xdotool getwindowclassname ${t} 2>/dev/null || echo ""`);n.push({handle:t,title:r.trim(),className:i.trim(),processId:e,threadId:0})}catch{}return n}catch(r){return t.error(`Failed to get windows for PID ${e}:`,r),n}}async findChromeProcesses(){let e={rendererProcesses:[],utilityProcesses:[]};try{let n=await this.findProcesses(`chrome`),r=await Promise.all(n.map(e=>this.getProcessByPid(e.pid)));for(let t=0;t<n.length;t++){let i=n[t],a=r[t];if(a?.commandLine){let t=a.commandLine.toLowerCase();t.includes(`--type=renderer`)?e.rendererProcesses.push({...i,...a}):t.includes(`--type=gpu-process`)?e.gpuProcess={...i,...a}:t.includes(`--type=utility`)?e.utilityProcesses.push({...i,...a}):t.includes(`--type=`)||(e.mainProcess={...i,...a})}else e.mainProcess||=i}let i=[e.mainProcess?.pid,...e.rendererProcesses.map(e=>e.pid)].filter(Boolean);for(let t of i){let n=(await this.getProcessWindows(t)).find(e=>e.title.includes(`Chrome`)||e.className.includes(`Chrome`)||e.title.includes(`Chromium`));if(n){e.targetWindow=n;break}}return t.info(`Chrome processes found:`,{main:e.mainProcess?.pid,renderers:e.rendererProcesses.length,hasTargetWindow:!!e.targetWindow}),e}catch(n){return t.error(`Failed to find Chrome processes:`,n),e}}async getProcessCommandLine(e){try{e=H(e);let{stdout:t}=await V(`cat /proc/${e}/cmdline 2>/dev/null | tr '\0' ' ' || echo ""`),{stdout:n}=await V(`cat /proc/${e}/status 2>/dev/null | grep PPid || echo ""`),r=n.match(/PPid:\s*(\d+)/);return{commandLine:t.trim()||void 0,parentPid:r?.[1]?parseInt(r[1],10):void 0}}catch(n){return t.error(`Failed to get command line for PID ${e}:`,n),{}}}async checkDebugPort(e,n){try{e=H(e);let t=n?.commandLine??(await this.getProcessCommandLine(e)).commandLine;if(t){let e=t.match(/--remote-debugging-port=(\d+)/);if(e?.[1])return parseInt(e[1],10)}let{stdout:r}=await V(`ss -tlnp 2>/dev/null | grep "pid=${e}" || netstat -tlnp 2>/dev/null | grep "${e}" || true`,{maxBuffer:1024*1024});for(let e of y)if(r.includes(`:${e}`))return e;return null}catch(n){return t.error(`Failed to check debug port for PID ${e}:`,n),null}}async launchWithDebug(e,n=w,r=[]){try{let a=Se(e,[`--remote-debugging-port=${n}`,...r],{detached:!0,stdio:`ignore`});if(a.unref(),D.register(a),await new Promise(e=>setTimeout(e,i)),!a.pid)return t.error(`Failed to spawn process: PID is undefined for ${e}`),null;let o=await this.getProcessByPid(a.pid);return t.info(`Launched process with debug port ${n}:`,{pid:a.pid,executable:e}),o}catch(e){return t.error(`Failed to launch process with debug:`,e),null}}async killProcess(e){try{return e=H(e),await V(`kill -9 ${e} 2>/dev/null || kill -15 ${e}`),t.info(`Process ${e} killed successfully`),!0}catch(n){return t.error(`Failed to kill process ${e}:`,n),!1}}isRunningOnWayland(){return this.isWayland}};const U=I(F),Me=I(xe);function Ne(e){return String(e||``).replace(/[^\w\s.@/\-:,+]/g,``)}function W(e){let t=Math.trunc(Number(e));if(!Number.isFinite(t)||t<=0)throw Error(`Invalid PID: ${e}`);return t}function Pe(e,t){let n=e;for(let[e,r]of Object.entries(t)){let t=RegExp(`\\{\\{${e}\\}\\}`,`g`);n=n.replace(t,String(r))}return n}var Fe=class{constructor(){t.info(`MacProcessManager initialized`)}async findProcesses(e){try{let{stdout:n}=await U(`ps aux | grep -i "${Ne(e)}" | grep -v grep || true`,{maxBuffer:d}),r=[],i=n.trim().split(`
|
|
5
|
+
`).filter(e=>e.trim());for(let e of i){let t=e.trim().split(/\s+/);if(t.length>=11){let e=parseInt(t[1]||`0`,10);if(isNaN(e))continue;let n=parseFloat(t[2]||`0`),i=parseFloat(t[3]||`0`),a=t.slice(10).join(` `);r.push({pid:e,name:t[10]||a.split(` `)[0]||`unknown`,commandLine:a,cpuUsage:n,memoryUsage:i*1024*1024})}}return t.info(`Found ${r.length} processes matching '${e}'`),r}catch(n){return t.error(`Failed to find processes with pattern '${e}':`,n),[]}}async getProcessByPid(e){try{e=W(e);let{stdout:t}=await U(`ps -p ${e} -o pid,ppid,pcpu,pmem,comm,args 2>/dev/null || echo ""`),n=t.trim().split(`
|
|
6
|
+
`).filter(e=>e.trim());if(n.length<2)return null;let r=(n[1]||``).trim().split(/\s+/);return r.length>=6?{pid:parseInt(r[0]||`0`,10),parentPid:parseInt(r[1]||`0`,10),name:r[4]||`unknown`,executablePath:await this.getProcessPath(e),commandLine:r.slice(5).join(` `),cpuUsage:parseFloat(r[2]||`0`),memoryUsage:parseFloat(r[3]||`0`)*1024*1024}:null}catch(n){return t.error(`Failed to get process by PID ${e}:`,n),null}}async getProcessPath(e){try{e=W(e);let{stdout:t}=await U(`ps -p ${e} -o comm= 2>/dev/null || echo ""`);return t.trim()||void 0}catch{return}}async getProcessWindows(e){try{e=W(e);let t=await this.getProcessByPid(e);if(!t)return[];let{stdout:n}=await U(`osascript -e '${`
|
|
7
|
+
tell application "System Events"
|
|
8
|
+
set processList to {}
|
|
9
|
+
try
|
|
10
|
+
set targetProcess to first process whose unix id is ${e}
|
|
11
|
+
set procName to name of targetProcess
|
|
12
|
+
set windowList to {}
|
|
13
|
+
|
|
14
|
+
tell targetProcess
|
|
15
|
+
repeat with win in windows
|
|
16
|
+
set winInfo to {|
|
|
17
|
+
title:name of win,
|
|
18
|
+
className:procName,
|
|
19
|
+
processId:${e},
|
|
20
|
+
handle:"applescript-window"
|
|
21
|
+
|}
|
|
22
|
+
set end of windowList to winInfo
|
|
23
|
+
end repeat
|
|
24
|
+
end tell
|
|
25
|
+
|
|
26
|
+
return windowList
|
|
27
|
+
on error
|
|
28
|
+
return {}
|
|
29
|
+
end try
|
|
30
|
+
end tell
|
|
31
|
+
`.replace(/'/g,`'"'"'`)}' 2>/dev/null || echo "[]"`,{timeout:S}),r=[];if(n.trim()&&n.trim()!==`[]`){let i=n.match(/title:([^,}]+)/g);if(i)for(let n of i){let i=n.replace(`title:`,``).trim();r.push({handle:`mac-window-${e}`,title:i,className:t.name,processId:e,threadId:0})}}return r}catch(n){return t.error(`Failed to get windows for PID ${e}:`,n),[]}}async getProcessWindowsCG(e){try{e=W(e);let{stdout:t}=await Me(`python3`,[`-c`,Pe(await new R().loadScript(`process_list.py`),{PID:e})],{timeout:ie*2,windowsHide:!0}),n=[];try{let e=JSON.parse(t.trim());for(let t of e)n.push({handle:t.handle,title:t.title,className:t.className,processId:t.processId,threadId:0,bounds:t.bounds?{x:t.bounds.X||0,y:t.bounds.Y||0,width:t.bounds.Width||0,height:t.bounds.Height||0}:void 0})}catch{}return n}catch(n){return t.error(`Failed to get windows via CoreGraphics for PID ${e}:`,n),[]}}async findChromeProcesses(){let e={rendererProcesses:[],utilityProcesses:[]};try{let n=await this.findProcesses(`chrome`),r=await Promise.all(n.map(e=>this.getProcessByPid(e.pid)));for(let t=0;t<n.length;t++){let i=n[t],a=r[t];if(a?.commandLine){let t=a.commandLine.toLowerCase();t.includes(`--type=renderer`)?e.rendererProcesses.push({...i,...a}):t.includes(`--type=gpu-process`)?e.gpuProcess={...i,...a}:t.includes(`--type=utility`)?e.utilityProcesses.push({...i,...a}):t.includes(`--type=`)||(e.mainProcess={...i,...a})}else e.mainProcess||=i}if(e.mainProcess){let t=await this.getProcessWindowsCG(e.mainProcess.pid);t.length>0&&(e.targetWindow=t[0])}return t.info(`Chrome processes found:`,{main:e.mainProcess?.pid,renderers:e.rendererProcesses.length,hasTargetWindow:!!e.targetWindow}),e}catch(n){return t.error(`Failed to find Chrome processes:`,n),e}}async getProcessCommandLine(e){try{e=W(e);let{stdout:t}=await U(`ps -p ${e} -o ppid=,args= 2>/dev/null || echo ""`),n=t.trim().split(/\s+/);return n.length>=2?{parentPid:parseInt(n[0]||`0`,10),commandLine:n.slice(1).join(` `)||void 0}:{}}catch(n){return t.error(`Failed to get command line for PID ${e}:`,n),{}}}async checkDebugPort(e,n){try{e=W(e);let t=n?.commandLine??(await this.getProcessCommandLine(e)).commandLine;if(t){let e=t.match(/--remote-debugging-port=(\d+)/);if(e?.[1])return parseInt(e[1],10)}let{stdout:r}=await U(`lsof -Pan -p ${e} -i 2>/dev/null | grep LISTEN || true`,{maxBuffer:1024*1024});for(let e of y)if(r.includes(`:${e}`))return e;return null}catch(n){return t.error(`Failed to check debug port for PID ${e}:`,n),null}}async launchWithDebug(e,n=w,r=[]){try{let a=Se(e,[`--remote-debugging-port=${n}`,...r],{detached:!0,stdio:`ignore`});if(a.unref(),D.register(a),await new Promise(e=>setTimeout(e,i)),!a.pid)return t.error(`Failed to spawn process: PID is undefined for ${e}`),null;let o=await this.getProcessByPid(a.pid);return t.info(`Launched process with debug port ${n}:`,{pid:a.pid,executable:e}),o}catch(e){return t.error(`Failed to launch process with debug:`,e),null}}async killProcess(e){try{return e=W(e),await U(`kill -9 ${e} 2>/dev/null || kill -15 ${e}`),t.info(`Process ${e} killed successfully`),!0}catch(n){return t.error(`Failed to kill process ${e}:`,n),!1}}},G=e({execAsync:()=>K,execFileAsync:()=>q,executePowerShellScript:()=>J});const K=I(F),q=I(xe);function Ie(){return process.platform===`win32`?`powershell.exe`:`powershell`}async function J(e,t={}){let n=[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,Buffer.from(e,`utf16le`).toString(`base64`)],{stdout:r,stderr:i}=await q(Ie(),n,{maxBuffer:t.maxBuffer??1024*1024,timeout:t.timeout,windowsHide:!0});return{stdout:String(r??``),stderr:String(i??``)}}const Le=/^(?:0x)?[0-9a-fA-F]{1,16}$/;async function Re(e,n,r){try{let{stdout:t}=await J(`
|
|
32
|
+
Add-Type @"
|
|
33
|
+
using System;
|
|
34
|
+
using System.Runtime.InteropServices;
|
|
35
|
+
using System.ComponentModel;
|
|
36
|
+
|
|
37
|
+
public class MemoryReader {
|
|
38
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
39
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
40
|
+
|
|
41
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
42
|
+
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int read);
|
|
43
|
+
|
|
44
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
45
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
46
|
+
|
|
47
|
+
const int PROCESS_VM_READ = 0x0010;
|
|
48
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
49
|
+
|
|
50
|
+
public static string ReadMemory(int pid, long address, int size) {
|
|
51
|
+
IntPtr hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pid);
|
|
52
|
+
if (hProcess == IntPtr.Zero) {
|
|
53
|
+
int error = Marshal.GetLastWin32Error();
|
|
54
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
byte[] buffer = new byte[size];
|
|
59
|
+
int bytesRead;
|
|
60
|
+
bool success = ReadProcessMemory(hProcess, (IntPtr)address, buffer, size, out bytesRead);
|
|
61
|
+
|
|
62
|
+
if (!success) {
|
|
63
|
+
int error = Marshal.GetLastWin32Error();
|
|
64
|
+
throw new Win32Exception(error, "Failed to read memory");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return BitConverter.ToString(buffer, 0, bytesRead).Replace("-", " ");
|
|
68
|
+
} finally {
|
|
69
|
+
CloseHandle(hProcess);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
"@
|
|
74
|
+
|
|
75
|
+
try {
|
|
76
|
+
$result = [MemoryReader]::ReadMemory(${e}, ${n}, ${r})
|
|
77
|
+
@{ success = $true; data = $result } | ConvertTo-Json -Compress
|
|
78
|
+
} catch {
|
|
79
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
80
|
+
}
|
|
81
|
+
`,{maxBuffer:1024*1024*10}),i=t.trim();if(!i)throw Error(`PowerShell returned empty output`);let a=JSON.parse(i);return{success:a.success,data:a.data,error:a.error}}catch(e){return t.error(`Windows memory read failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed. Run as Administrator.`}}}let Y=null,ze=!1;async function Be(){if(ze)return Y;try{let{createPlatformProvider:e}=await import(`./factory-BeND77hf.mjs`).then(e=>e.n),t=e();(await t.checkAvailability()).available&&(Y=t)}catch{}return ze=!0,Y}function Ve(e,t){return e.subarray(0,t).toString(`hex`).toUpperCase().replace(/../g,`$& `)}async function He(e,n,r){try{let i=await Be();if(i){let a=i.openProcess(e,!1);try{let e=i.readMemory(a,BigInt(n),r);return t.debug(`Native Linux memory read succeeded`),{success:!0,data:Ve(e.data,e.bytesRead).trim()}}finally{i.closeProcess(a)}}}catch(e){t.debug(`Native Linux read failed, falling back to dd:`,e)}try{let{stdout:t}=await K(`dd if=/proc/${e}/mem bs=1 skip=${n} count=${r} 2>/dev/null | xxd -p | tr -d '\\n' || echo ""`,{maxBuffer:1024*1024*10,timeout:h});return t.trim()?{success:!0,data:(t.trim().match(/.{1,2}/g)?.join(` `)||t.trim()).toUpperCase()}:{success:!1,error:`Failed to read memory. Requires ptrace access or root. Check kernel.yama.ptrace_scope if access denied.`}}catch(e){return t.error(`Linux memory read failed:`,e),{success:!1,error:`Memory read failed. Requires ptrace access or root (check kernel.yama.ptrace_scope).`}}}async function Ue(e,n,r,i){if(n===0)return{success:!1,error:`Invalid address: null pointer (0x0)`};if(r<=0||r>E)return{success:!1,error:`Invalid size: must be 1–${E} bytes`};let a=`0x${n.toString(16)}`;try{let{createPlatformProvider:i}=await import(`./factory-BeND77hf.mjs`).then(e=>e.n),a=i();if((await a.checkAvailability()).available){let i=a.openProcess(e,!1);try{let e=a.readMemory(i,BigInt(n),r),o=Array.from(e.data.subarray(0,e.bytesRead)).map(e=>e.toString(16).padStart(2,`0`).toUpperCase()).join(` `);return t.debug(`Native Mach memory read succeeded (zero-pause)`),{success:!0,data:o}}finally{a.closeProcess(i)}}}catch(e){t.debug(`Native Mach read failed, falling back to lldb:`,e)}let o=await i(e,a);if(!o.success)return{success:!1,error:`Cannot verify memory region: ${o.error}`};if(!o.isReadable)return{success:!1,error:`Address ${a} is not readable (protection: ${o.protection??`unknown`})`};let s=`/tmp/mread_${e}_${Date.now()}.bin`;try{let{stdout:t}=await K(`lldb --batch -p ${e} -o "memory read --outfile ${s} --binary ${a} -c ${r}" -o "process detach"`,{timeout:f,maxBuffer:1024*1024*10});if(!t.includes(`bytes written`))return{success:!1,error:`lldb memory read failed: ${(t.split(`
|
|
82
|
+
`).find(e=>e.includes(`error:`))??t).trim()}`};let n=await N.readFile(s);return{success:!0,data:Array.from(n).map(e=>e.toString(16).padStart(2,`0`).toUpperCase()).join(` `)}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{await N.unlink(s).catch(()=>{})}}async function We(e,n,r,i,a){try{if(!Le.test(r))return{success:!1,error:`Invalid address format. Use hex like "0x12345678"`};let o=parseInt(r,16);if(isNaN(o))return{success:!1,error:`Invalid address format. Use hex like "0x12345678"`};if(i<=0||i>E)return{success:!1,error:`Read size must be 1–${E} bytes (${(E/1024/1024).toFixed(0)} MB)`};if(e===`win32`&&ae())try{let e=await A.readMemory(n,r,i);if(e.success)return t.debug(`Native memory read succeeded`),e;t.warn(`Native memory read failed, falling back to PowerShell:`,e.error)}catch(e){t.warn(`Native memory read error, falling back to PowerShell:`,e)}switch(e){case`win32`:return Re(n,o,i);case`linux`:return He(n,o,i);case`darwin`:return Ue(n,o,i,a);default:return{success:!1,error:`Memory operations not supported on platform: ${e}`}}}catch(e){return t.error(`Memory read failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Ge(e,n,r){try{let{stdout:t}=await J(`
|
|
83
|
+
Add-Type @"
|
|
84
|
+
using System;
|
|
85
|
+
using System.Runtime.InteropServices;
|
|
86
|
+
using System.ComponentModel;
|
|
87
|
+
|
|
88
|
+
public class MemoryWriter {
|
|
89
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
90
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
91
|
+
|
|
92
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
93
|
+
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int written);
|
|
94
|
+
|
|
95
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
96
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
97
|
+
|
|
98
|
+
const int PROCESS_VM_WRITE = 0x0020;
|
|
99
|
+
const int PROCESS_VM_OPERATION = 0x0008;
|
|
100
|
+
|
|
101
|
+
public static int WriteMemory(int pid, long address, string hexData) {
|
|
102
|
+
IntPtr hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, false, pid);
|
|
103
|
+
if (hProcess == IntPtr.Zero) {
|
|
104
|
+
int error = Marshal.GetLastWin32Error();
|
|
105
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
try {
|
|
109
|
+
byte[] buffer = new byte[hexData.Length / 2];
|
|
110
|
+
for (int i = 0; i < hexData.Length; i += 2) {
|
|
111
|
+
buffer[i / 2] = Convert.ToByte(hexData.Substring(i, 2), 16);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
int bytesWritten;
|
|
115
|
+
bool success = WriteProcessMemory(hProcess, (IntPtr)address, buffer, buffer.Length, out bytesWritten);
|
|
116
|
+
|
|
117
|
+
if (!success) {
|
|
118
|
+
int error = Marshal.GetLastWin32Error();
|
|
119
|
+
throw new Win32Exception(error, "Failed to write memory");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return bytesWritten;
|
|
123
|
+
} finally {
|
|
124
|
+
CloseHandle(hProcess);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
"@
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
$bytesWritten = [MemoryWriter]::WriteMemory(${e}, ${n}, "${r.toString(`hex`).toUpperCase()}")
|
|
132
|
+
@{ success = $true; bytesWritten = $bytesWritten } | ConvertTo-Json -Compress
|
|
133
|
+
} catch {
|
|
134
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
135
|
+
}
|
|
136
|
+
`,{maxBuffer:1024*1024}),i=t.trim();if(!i)throw Error(`PowerShell returned empty output`);let a=JSON.parse(i);return{success:a.success,bytesWritten:a.bytesWritten,error:a.error}}catch(e){return t.error(`Windows memory write failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed. Run as Administrator.`}}}let X=null,Ke=!1;async function qe(){if(Ke)return X;try{let{createPlatformProvider:e}=await import(`./factory-BeND77hf.mjs`).then(e=>e.n),t=e();(await t.checkAvailability()).available&&(X=t)}catch{}return Ke=!0,X}async function Je(e,n,r){try{let i=await qe();if(i){let a=i.openProcess(e,!0);try{let e=i.writeMemory(a,BigInt(n),r);return t.debug(`Native Linux memory write succeeded`),{success:!0,bytesWritten:e.bytesWritten}}finally{i.closeProcess(a)}}}catch(e){t.debug(`Native Linux write failed, falling back to dd:`,e)}try{let{stderr:t}=await K(`printf "${r.toString(`hex`)}" | xxd -r -p | dd of=/proc/${e}/mem bs=1 seek=${n} conv=notrunc`,{maxBuffer:1024*1024,timeout:g});return t&&/error|denied|cannot/i.test(t)?{success:!1,error:`Memory write failed. Requires ptrace access or root. Check kernel.yama.ptrace_scope if access denied.`}:{success:!0,bytesWritten:r.length}}catch(e){return t.error(`Linux memory write failed:`,e),{success:!1,error:`Memory write failed. Requires ptrace access or root (check kernel.yama.ptrace_scope).`}}}async function Ye(e,n,r,i){if(n===0)return{success:!1,error:`Invalid address: null pointer (0x0)`};if(r.length===0||r.length>_)return{success:!1,error:`Invalid write size: must be 1–${_} bytes`};let a=`0x${n.toString(16)}`;try{let{createPlatformProvider:i}=await import(`./factory-BeND77hf.mjs`).then(e=>e.n),a=i();if((await a.checkAvailability()).available){let i=a.openProcess(e,!0);try{let e=a.writeMemory(i,BigInt(n),r);return t.debug(`Native Mach memory write succeeded (zero-pause)`),{success:!0,bytesWritten:e.bytesWritten}}finally{a.closeProcess(i)}}}catch(e){t.debug(`Native Mach write failed, falling back to lldb:`,e)}let o=await i(e,a);if(!o.success)return{success:!1,error:`Cannot verify memory region: ${o.error}`};if(!o.isWritable)return{success:!1,error:`Address ${a} is not writable (protection: ${o.protection??`unknown`})`};try{let{stdout:t}=await K(`lldb --batch -p ${e} -o "memory write ${a} ${Array.from(r).map(e=>`0x${e.toString(16).padStart(2,`0`)}`).join(` `)}" -o "process detach"`,{timeout:g,maxBuffer:1024*1024});return t.includes(`error:`)?{success:!1,error:`lldb memory write failed: ${(t.split(`
|
|
137
|
+
`).find(e=>e.includes(`error:`))??t).trim()}`}:{success:!0,bytesWritten:r.length}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}const Xe=/^(?:0x)?[0-9a-fA-F]{1,16}$/;async function Ze(e,n,r,i,a=`hex`,o){try{if(!Xe.test(r))return{success:!1,error:`Invalid address format. Use hex like "0x12345678"`};let s=parseInt(r,16);if(isNaN(s))return{success:!1,error:`Invalid address format`};let c;try{if(a===`base64`)c=Buffer.from(i,`base64`);else{let e=i.replace(/\s/g,``);c=Buffer.from(e,`hex`)}}catch{return{success:!1,error:`Invalid ${a} data`}}if(c.length===0||c.length>_)return{success:!1,error:`Write size must be 1–${_} bytes (${(_/1024).toFixed(0)} KB)`};if(e===`win32`&&ae())try{let e=await A.writeMemory(n,r,i,a);if(e.success)return t.debug(`Native memory write succeeded`),e;t.warn(`Native memory write failed, falling back to PowerShell:`,e.error)}catch(e){t.warn(`Native memory write error, falling back to PowerShell:`,e)}switch(e){case`win32`:return Ge(n,s,c);case`linux`:return Je(n,s,c);case`darwin`:return Ye(n,s,c,o);default:return{success:!1,error:`Memory operations not supported on platform: ${e}`}}}catch(e){return t.error(`Memory write failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}}const Qe=1e3;async function $e(e,t,n){if(t.length>Qe)return{success:!1,results:[],error:`Too many patches (${t.length}), max ${Qe}`};let r=[];for(let i of t){let t=await n(e,i.address,i.data,i.encoding||`hex`);r.push({address:i.address,success:t.success,error:t.error})}let i=r.every(e=>e.success);return{success:i,results:r,error:i?void 0:`Failed to write ${r.filter(e=>!e.success).length} of ${r.length} patches`}}function et(e,t){let n=[],r=[];switch(t){case`hex`:{let t=e.trim().split(/\s+/);for(let e of t)if(e===`??`||e===`**`||e===`?`)n.push(0),r.push(0);else{let t=parseInt(e,16);isNaN(t)||(n.push(t),r.push(1))}break}case`int32`:{let t=parseInt(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(4);e.writeInt32LE(t,0),n=Array.from(e),r=[1,1,1,1]}break}case`int64`:{let t=BigInt.asIntN(64,BigInt(e)),i=Buffer.allocUnsafe(8);i.writeBigInt64LE(t,0),n=Array.from(i),r=[1,1,1,1,1,1,1,1];break}case`float`:{let t=parseFloat(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(4);e.writeFloatLE(t,0),n=Array.from(e),r=[1,1,1,1]}break}case`double`:{let t=parseFloat(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(8);e.writeDoubleLE(t,0),n=Array.from(e),r=[1,1,1,1,1,1,1,1]}break}case`string`:{let t=Buffer.from(e,`utf8`);n=Array.from(t),r=n.map(()=>1);break}}if(n.length===0)throw Error(`Invalid pattern`);return{patternBytes:n,mask:r}}function tt(e,t){let n=[],r=[];switch(t){case`hex`:{let t=e.trim().split(/\s+/);for(let e of t)if(e===`??`||e===`?`||e===`**`)n.push(0),r.push(0);else{let t=parseInt(e,16);if(isNaN(t))throw Error(`Invalid hex byte: ${e}`);n.push(t),r.push(1)}if(!n.length)throw Error(`Pattern is empty`);break}case`int32`:{let t=parseInt(e);if(isNaN(t))throw Error(`Invalid int32 value`);let i=Buffer.allocUnsafe(4);i.writeInt32LE(t,0);let a=Array.from(i);n.push(...a),r.push(...a.map(()=>1));break}case`int64`:{let t=Buffer.allocUnsafe(8);t.writeBigInt64LE(BigInt.asIntN(64,BigInt(e)),0);let i=Array.from(t);n.push(...i),r.push(...i.map(()=>1));break}case`float`:{let t=parseFloat(e);if(isNaN(t))throw Error(`Invalid float value`);let i=Buffer.allocUnsafe(4);i.writeFloatLE(t,0);let a=Array.from(i);n.push(...a),r.push(...a.map(()=>1));break}case`double`:{let t=parseFloat(e);if(isNaN(t))throw Error(`Invalid double value`);let i=Buffer.allocUnsafe(8);i.writeDoubleLE(t,0);let a=Array.from(i);n.push(...a),r.push(...a.map(()=>1));break}case`string`:{let t=Array.from(Buffer.from(e,`utf8`));n.push(...t),r.push(...t.map(()=>1));break}default:throw Error(`Unsupported pattern type: ${t}`)}return{bytes:n,mask:r}}function nt(e,t,r){let{patternBytes:i,mask:a}=et(t,r);return`
|
|
138
|
+
Add-Type @"
|
|
139
|
+
using System;
|
|
140
|
+
using System.Runtime.InteropServices;
|
|
141
|
+
using System.Collections.Generic;
|
|
142
|
+
using System.ComponentModel;
|
|
143
|
+
|
|
144
|
+
public class MemoryScanner {
|
|
145
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
146
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
147
|
+
|
|
148
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
149
|
+
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int read);
|
|
150
|
+
|
|
151
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
152
|
+
public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr addr, out MEMORY_BASIC_INFORMATION info, int size);
|
|
153
|
+
|
|
154
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
155
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
156
|
+
|
|
157
|
+
const int PROCESS_VM_READ = 0x0010;
|
|
158
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
159
|
+
|
|
160
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
161
|
+
public struct MEMORY_BASIC_INFORMATION {
|
|
162
|
+
public IntPtr BaseAddress;
|
|
163
|
+
public IntPtr AllocationBase;
|
|
164
|
+
public uint AllocationProtect;
|
|
165
|
+
public IntPtr RegionSize;
|
|
166
|
+
public uint State;
|
|
167
|
+
public uint Protect;
|
|
168
|
+
public uint Type;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const uint MEM_COMMIT = 0x1000;
|
|
172
|
+
const uint PAGE_READONLY = 0x02;
|
|
173
|
+
const uint PAGE_READWRITE = 0x04;
|
|
174
|
+
const uint PAGE_WRITECOPY = 0x08;
|
|
175
|
+
const uint PAGE_EXECUTE_READ = 0x20;
|
|
176
|
+
const uint PAGE_EXECUTE_READWRITE = 0x40;
|
|
177
|
+
|
|
178
|
+
public static List<string> ScanMemory(int pid, byte[] pattern, byte[] mask, int maxResults = ${C}) {
|
|
179
|
+
var results = new List<string>();
|
|
180
|
+
IntPtr hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pid);
|
|
181
|
+
if (hProcess == IntPtr.Zero) {
|
|
182
|
+
int error = Marshal.GetLastWin32Error();
|
|
183
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
try {
|
|
187
|
+
IntPtr addr = IntPtr.Zero;
|
|
188
|
+
MEMORY_BASIC_INFORMATION info;
|
|
189
|
+
int infoSize = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));
|
|
190
|
+
int scannedRegions = 0;
|
|
191
|
+
|
|
192
|
+
while (VirtualQueryEx(hProcess, addr, out info, infoSize) == infoSize) {
|
|
193
|
+
scannedRegions++;
|
|
194
|
+
bool isReadable = (info.State == MEM_COMMIT) &&
|
|
195
|
+
((info.Protect & PAGE_READONLY) != 0 ||
|
|
196
|
+
(info.Protect & PAGE_READWRITE) != 0 ||
|
|
197
|
+
(info.Protect & PAGE_WRITECOPY) != 0 ||
|
|
198
|
+
(info.Protect & PAGE_EXECUTE_READ) != 0 ||
|
|
199
|
+
(info.Protect & PAGE_EXECUTE_READWRITE) != 0);
|
|
200
|
+
|
|
201
|
+
if (isReadable && info.RegionSize.ToInt64() > 0 && info.RegionSize.ToInt64() < 1073741824) {
|
|
202
|
+
long regionSize = info.RegionSize.ToInt64();
|
|
203
|
+
if (regionSize > ${p}) regionSize = ${p};
|
|
204
|
+
byte[] buffer = new byte[(int)regionSize];
|
|
205
|
+
int bytesRead;
|
|
206
|
+
|
|
207
|
+
if (ReadProcessMemory(hProcess, info.BaseAddress, buffer, buffer.Length, out bytesRead)) {
|
|
208
|
+
for (int i = 0; i <= bytesRead - pattern.Length; i++) {
|
|
209
|
+
if (PatternMatch(buffer, i, pattern, mask)) {
|
|
210
|
+
long foundAddr = info.BaseAddress.ToInt64() + i;
|
|
211
|
+
results.Add("0x" + foundAddr.ToString("X"));
|
|
212
|
+
if (results.Count >= maxResults) break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (results.Count >= maxResults) break;
|
|
219
|
+
if (scannedRegions >= ${n}) break;
|
|
220
|
+
long baseAddr = info.BaseAddress.ToInt64();
|
|
221
|
+
long regionSizeRaw = info.RegionSize.ToInt64();
|
|
222
|
+
if (regionSizeRaw <= 0) break;
|
|
223
|
+
long nextAddr = baseAddr + regionSizeRaw;
|
|
224
|
+
if (nextAddr <= baseAddr) break;
|
|
225
|
+
addr = new IntPtr(nextAddr);
|
|
226
|
+
if (addr.ToInt64() >= 0x7FFFFFFF0000) break;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return results;
|
|
230
|
+
} finally {
|
|
231
|
+
CloseHandle(hProcess);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private static bool PatternMatch(byte[] buffer, int offset, byte[] pattern, byte[] mask) {
|
|
236
|
+
for (int i = 0; i < pattern.Length; i++) {
|
|
237
|
+
if (mask[i] == 1 && buffer[offset + i] != pattern[i]) {
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
"@
|
|
245
|
+
|
|
246
|
+
try {
|
|
247
|
+
$patternBytes = @(${i.join(`,`)})
|
|
248
|
+
$maskBytes = @(${a.join(`,`)})
|
|
249
|
+
$results = [MemoryScanner]::ScanMemory(${e}, $patternBytes, $maskBytes, ${C})
|
|
250
|
+
@{
|
|
251
|
+
success = $true;
|
|
252
|
+
addresses = $results;
|
|
253
|
+
stats = @{
|
|
254
|
+
patternLength = $patternBytes.Length;
|
|
255
|
+
resultsFound = $results.Count
|
|
256
|
+
}
|
|
257
|
+
} | ConvertTo-Json -Compress
|
|
258
|
+
} catch {
|
|
259
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
260
|
+
}
|
|
261
|
+
`.trim()}async function rt(e,n,r){try{if(k())try{let i=await A.scanMemory(e,n,r);if(i.success)return i;t.warn(`Native Windows memory scan failed, falling back to PowerShell`,{pid:e,patternType:r,error:i.error,nativeAvailable:k()})}catch(n){t.warn(`Native Windows memory scan threw, falling back to PowerShell`,{pid:e,patternType:r,error:n instanceof Error?n.message:String(n),nativeAvailable:k()})}let{stdout:i,stderr:a}=await J(nt(e,n,r),{maxBuffer:te,timeout:m});if(a&&a.includes(`Error`))return{success:!1,addresses:[],error:a};let o=i.trim();if(!o)throw Error(`PowerShell returned empty output`);let s=JSON.parse(o);return{success:s.success,addresses:s.addresses||[],error:s.error,stats:s.stats}}catch(e){return t.error(`Windows memory scan failed:`,e),{success:!1,addresses:[],error:e instanceof Error?e.message:`PowerShell execution failed. Run as Administrator.`}}}function it(e,t,n){let r=n;switch(r?.code){case`ENOENT`:case`ESRCH`:return`Process ${e} no longer exists or /proc/${e}/${t} is unavailable.`;case`EACCES`:case`EPERM`:return`Cannot access /proc/${e}/${t}. Requires root privileges or ptrace access.`;default:return r instanceof Error?r.message:String(n)}}async function at(e,n,r){let i,a;try{let e=et(n,r);i=e.patternBytes,a=e.mask}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:`Invalid pattern`}}try{let n;try{n=he(`/proc/${e}/maps`,`utf-8`)}catch(t){return{success:!1,addresses:[],error:it(e,`maps`,t)}}let r=O(n),o=Array.isArray(r)?r.filter(e=>e.permissions.read):[],s;try{s=me(`/proc/${e}/mem`,`r`)}catch(t){return{success:!1,addresses:[],error:it(e,`mem`,t)}}let c=new Set,l=16*1024*1024,u=1e4,d=Math.max(i.length-1,0);try{for(let n of o){if(c.size>=u)break;if(n.end<=n.start)continue;let r=0n,o=Buffer.alloc(0),f=n.end-n.start;for(;r<f&&c.size<u;){let p=f-r,m=Number(p>BigInt(l)?BigInt(l):p),h=Buffer.allocUnsafe(m),g;try{g=ge(s,h,0,m,n.start+r)}catch(i){let a=i;if(a?.code===`EIO`||a?.code===`EFAULT`||a?.code===`EACCES`||a?.code===`EPERM`){t.debug(`Skipping unreadable Linux memory region chunk`,{pid:e,start:`0x${n.start.toString(16)}`,offset:r.toString(),code:a.code});break}throw i}if(g<=0)break;let _=g===m?h:h.subarray(0,g),v=o.length>0?Buffer.concat([o,_]):_,y=n.start+r-BigInt(o.length),b=BigInt(g),x=r+b>=f||g<m,S=x?0:Math.min(d,v.length),ee=v.length-S,C=se(v,i,a);for(let e of C){if(!x&&e>=ee)continue;let t=y+BigInt(e);if(!(t<n.start||t>=n.end)&&(c.add(`0x${t.toString(16)}`),c.size>=u))break}if(o=S>0?v.subarray(v.length-S):Buffer.alloc(0),r+=b,g<m){t.debug(`Linux memory scan stopped after short read`,{pid:e,start:`0x${n.start.toString(16)}`,requested:m,bytesRead:g});break}}}}finally{de(s)}let f=Array.from(c);return{success:!0,addresses:f,stats:{patternLength:i.length,resultsFound:f.length}}}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:String(e)}}}async function ot(e,n,r){let i,a;try{let e=tt(n,r);i=e.bytes,a=e.mask}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:`Invalid pattern`}}try{let t=await st(e,i,a);if(t)return t}catch(e){t.debug(`Native Mach scan failed, falling back to lldb:`,e)}return ct(e,i,a)}async function st(e,n,r){let{createPlatformProvider:i}=await import(`./factory-BeND77hf.mjs`).then(e=>e.n),a=i();if(!(await a.checkAvailability()).available)return null;let o=a.openProcess(e,!1),s=[],c=1e3;try{let e=0n;for(let t=0;t<5e4&&s.length<c;t++){let t=a.queryRegion(o,e);if(!t)break;if(t.isReadable&&t.size>0&&t.size<=33554432)try{let e=se(a.readMemory(o,t.baseAddress,t.size).data,n,r);for(let n of e)if(s.push(`0x${(t.baseAddress+BigInt(n)).toString(16)}`),s.length>=c)break}catch{}if(e=t.baseAddress+BigInt(t.size),e<=t.baseAddress)break}}finally{a.closeProcess(o)}return t.debug(`Native Mach scan completed (zero-pause): ${s.length} results`),{success:!0,addresses:s,stats:{patternLength:n.length,resultsFound:s.length}}}async function ct(e,t,n){let r=t.map(e=>`0x${e.toString(16)}`).join(`,`),i=n.join(`,`),a=`${e}_${Date.now()}`,o=`/tmp/lldb_scan_${a}.py`,s=`/tmp/lldb_scan_${a}.txt`,c=`
|
|
262
|
+
import lldb, json, sys
|
|
263
|
+
|
|
264
|
+
def __lldb_init_module(debugger, internal_dict):
|
|
265
|
+
proc = debugger.GetSelectedTarget().GetProcess()
|
|
266
|
+
pat = bytes([${r}])
|
|
267
|
+
mask = [${i}]
|
|
268
|
+
results = []
|
|
269
|
+
rl = proc.GetMemoryRegions()
|
|
270
|
+
for i in range(rl.GetSize()):
|
|
271
|
+
info = lldb.SBMemoryRegionInfo()
|
|
272
|
+
rl.GetMemoryRegionAtIndex(i, info)
|
|
273
|
+
if not info.IsReadable():
|
|
274
|
+
continue
|
|
275
|
+
s = info.GetRegionBase()
|
|
276
|
+
sz = info.GetRegionEnd() - s
|
|
277
|
+
if sz > 32 * 1024 * 1024:
|
|
278
|
+
continue
|
|
279
|
+
err = lldb.SBError()
|
|
280
|
+
data = proc.ReadMemory(s, sz, err)
|
|
281
|
+
if not err.Success():
|
|
282
|
+
continue
|
|
283
|
+
n = len(pat)
|
|
284
|
+
for j in range(len(data) - n + 1):
|
|
285
|
+
match = True
|
|
286
|
+
for k in range(n):
|
|
287
|
+
if mask[k] == 1 and data[j+k] != pat[k]:
|
|
288
|
+
match = False
|
|
289
|
+
break
|
|
290
|
+
if match:
|
|
291
|
+
results.append(hex(s + j))
|
|
292
|
+
if len(results) >= 1000:
|
|
293
|
+
break
|
|
294
|
+
if len(results) >= 1000:
|
|
295
|
+
break
|
|
296
|
+
sys.stdout.write('SCAN_RESULT:' + json.dumps({
|
|
297
|
+
'success': True,
|
|
298
|
+
'addresses': results,
|
|
299
|
+
'stats': {'patternLength': len(pat), 'resultsFound': len(results)}
|
|
300
|
+
}) + '\\n')
|
|
301
|
+
sys.stdout.flush()
|
|
302
|
+
`;await N.writeFile(o,c,`utf8`),await N.writeFile(s,`command script import ${o}\nprocess detach\n`,`utf8`);try{let{stdout:t}=await K(`lldb --batch -p ${e} --source ${s}`,{timeout:m,maxBuffer:1024*1024*5}),n=t.split(`
|
|
303
|
+
`).find(e=>e.startsWith(`SCAN_RESULT:`));if(!n)return{success:!1,addresses:[],error:`lldb scan returned no result. ${t.split(`
|
|
304
|
+
`).find(e=>e.includes(`error:`))??``}`.trim()};try{return JSON.parse(n.slice(12))}catch{let e=t.split(`
|
|
305
|
+
`).find(e=>e.includes(`error:`))??``;if(e)return{success:!1,addresses:[],error:e.trim()};throw Error(`Unexpected end of JSON input`)}}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:String(e)}}finally{await N.unlink(o).catch(()=>{}),await N.unlink(s).catch(()=>{})}}var lt=e({resumeProcess:()=>mt,scanMemory:()=>ut,scanMemoryFiltered:()=>dt,suspendProcess:()=>pt});async function ut(e,n,r,i=`hex`,a=!1){let o=!1;try{switch(a&&(o=await pt(e,n),o?t.info(`Suspended process ${n} for consistent memory scan`):t.warn(`Could not suspend process ${n} — scanning unsuspended`)),e){case`win32`:return await rt(n,r,i);case`linux`:return await at(n,r,i);case`darwin`:return await ot(n,r,i);default:return{success:!1,addresses:[],error:`Memory scan not supported on ${e}`}}}catch(e){return t.error(`Memory scan failed:`,e),{success:!1,addresses:[],error:e instanceof Error?e.message:String(e)}}finally{o&&(await mt(e,n),t.info(`Resumed process ${n} after memory scan`))}}async function dt(e,t,n,r=`hex`,i,a){let o=[];for(let e of n){let t=parseInt(e,16);isNaN(t)||o.push(t)}if(o.length===0)return{success:!1,addresses:[],error:`No valid addresses provided`};let s=await a(e,t,r);if(!s.success||s.addresses.length===0)return{success:!0,addresses:[],stats:{resultsFound:0,patternLength:t.length}};let c=[];for(let e of s.addresses){let t=parseInt(e,16);o.some(e=>Math.abs(e-t)<256)&&(c.includes(e)||c.push(e))}return{success:!0,addresses:c,stats:{resultsFound:c.length,patternLength:t.length}}}async function ft(e,t){let{machTaskSelf:n,taskForPid:r,machPortDeallocate:i,KERN:a}=await import(`./DarwinAPI-DzojdfjF.mjs`).then(e=>e.t),o=n(),{kr:s,task:c}=r(o,e);if(s!==a.SUCCESS)return!1;try{return t(c)}finally{i(o,c)}}async function pt(e,n){try{switch(e){case`darwin`:{let{taskSuspend:e,KERN:t}=await import(`./DarwinAPI-DzojdfjF.mjs`).then(e=>e.t);return ft(n,n=>e(n)===t.SUCCESS)}case`linux`:{let{execAsync:e}=await Promise.resolve().then(()=>G);return await e(`kill -STOP ${n}`,{timeout:v}),!0}case`win32`:{let{execAsync:e}=await Promise.resolve().then(()=>G);return await e(`powershell -NoProfile -Command "(Add-Type -MemberDefinition '[DllImport("ntdll.dll")] public static extern int NtSuspendProcess(IntPtr h);' -Name W -Namespace N -PassThru)::NtSuspendProcess((Get-Process -Id ${n}).Handle)"`,{timeout:T}),!0}default:return!1}}catch(e){return t.warn(`Failed to suspend process ${n}:`,e),!1}}async function mt(e,n){try{switch(e){case`darwin`:{let{taskResume:e}=await import(`./DarwinAPI-DzojdfjF.mjs`).then(e=>e.t);await ft(n,t=>{e(t)});break}case`linux`:{let{execAsync:e}=await Promise.resolve().then(()=>G);await e(`kill -CONT ${n}`,{timeout:v});break}case`win32`:{let{execAsync:e}=await Promise.resolve().then(()=>G);await e(`powershell -NoProfile -Command "(Add-Type -MemberDefinition '[DllImport("ntdll.dll")] public static extern int NtResumeProcess(IntPtr h);' -Name W -Namespace N -PassThru)::NtResumeProcess((Get-Process -Id ${n}).Handle)"`,{timeout:T});break}}}catch(e){t.error(`CRITICAL: Failed to resume process ${n} — may need manual SIGCONT:`,e)}}function ht(e,t,n,r){return`
|
|
306
|
+
Add-Type @"
|
|
307
|
+
using System;
|
|
308
|
+
using System.Runtime.InteropServices;
|
|
309
|
+
using System.IO;
|
|
310
|
+
using System.ComponentModel;
|
|
311
|
+
|
|
312
|
+
public class MemoryDumper {
|
|
313
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
314
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
315
|
+
|
|
316
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
317
|
+
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int read);
|
|
318
|
+
|
|
319
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
320
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
321
|
+
|
|
322
|
+
const int PROCESS_VM_READ = 0x0010;
|
|
323
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
324
|
+
|
|
325
|
+
public static string DumpMemory(int pid, long address, int size, string outputPath) {
|
|
326
|
+
IntPtr hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pid);
|
|
327
|
+
if (hProcess == IntPtr.Zero) {
|
|
328
|
+
int error = Marshal.GetLastWin32Error();
|
|
329
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
try {
|
|
333
|
+
byte[] buffer = new byte[size];
|
|
334
|
+
int bytesRead;
|
|
335
|
+
|
|
336
|
+
if (!ReadProcessMemory(hProcess, (IntPtr)address, buffer, size, out bytesRead)) {
|
|
337
|
+
int error = Marshal.GetLastWin32Error();
|
|
338
|
+
throw new Win32Exception(error, "Failed to read memory");
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
File.WriteAllBytes(outputPath, buffer);
|
|
342
|
+
return "Dumped " + bytesRead + " bytes to " + outputPath;
|
|
343
|
+
} finally {
|
|
344
|
+
CloseHandle(hProcess);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
"@
|
|
349
|
+
|
|
350
|
+
try {
|
|
351
|
+
$result = [MemoryDumper]::DumpMemory(${e}, ${t}, ${n}, "${r.replace(/\\/g,`\\\\`).replace(/"/g,'`"').replace(/\$/g,"`$")}")
|
|
352
|
+
@{ success = $true; message = $result } | ConvertTo-Json -Compress
|
|
353
|
+
} catch {
|
|
354
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
355
|
+
}
|
|
356
|
+
`.trim()}async function gt(e,n,r,i,a){if(e!==`win32`&&e!==`darwin`)return{success:!1,error:`Memory dump currently only implemented for Windows and macOS`};if(e===`darwin`){let e=parseInt(r,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};if(!Number.isInteger(n)||n<=0)return{success:!1,error:`Invalid pid`};if(!Number.isInteger(i)||i<=0)return{success:!1,error:`Invalid size`};let t=`0x${e.toString(16)}`;try{let{stdout:e}=await q(`lldb`,[`--batch`,`-p`,String(n),`-o`,`memory read --outfile ${a} --binary ${t} -c ${i}`,`-o`,`process detach`],{timeout:b,maxBuffer:1024*1024});return e.includes(`bytes written`)?{success:!0}:{success:!1,error:`lldb dump failed: ${(e.split(`
|
|
357
|
+
`).find(e=>e.includes(`error:`))??e).trim()}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}try{let e=parseInt(r,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};if(!Number.isInteger(n)||n<=0)return{success:!1,error:`Invalid pid`};if(!Number.isInteger(i)||i<=0)return{success:!1,error:`Invalid size`};let{stdout:t}=await J(ht(n,e,i,a),{maxBuffer:1024*1024,timeout:b}),o=t.trim();if(!o)throw Error(`PowerShell returned empty output`);let s=JSON.parse(o);return{success:s.success,error:s.error}}catch(e){return t.error(`Memory dump failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function _t(e){return`
|
|
358
|
+
Add-Type @"
|
|
359
|
+
using System;
|
|
360
|
+
using System.Runtime.InteropServices;
|
|
361
|
+
using System.Collections.Generic;
|
|
362
|
+
using System.ComponentModel;
|
|
363
|
+
|
|
364
|
+
public class RegionEnumerator {
|
|
365
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
366
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
367
|
+
|
|
368
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
369
|
+
public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr addr, out MEMORY_BASIC_INFORMATION info, int size);
|
|
370
|
+
|
|
371
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
372
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
373
|
+
|
|
374
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
375
|
+
|
|
376
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
377
|
+
public struct MEMORY_BASIC_INFORMATION {
|
|
378
|
+
public IntPtr BaseAddress;
|
|
379
|
+
public IntPtr AllocationBase;
|
|
380
|
+
public uint AllocationProtect;
|
|
381
|
+
public IntPtr RegionSize;
|
|
382
|
+
public uint State;
|
|
383
|
+
public uint Protect;
|
|
384
|
+
public uint Type;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const uint MEM_COMMIT = 0x1000;
|
|
388
|
+
const uint MEM_FREE = 0x10000;
|
|
389
|
+
const uint MEM_RESERVE = 0x2000;
|
|
390
|
+
const uint PAGE_READONLY = 0x02;
|
|
391
|
+
const uint PAGE_READWRITE = 0x04;
|
|
392
|
+
const uint PAGE_WRITECOPY = 0x08;
|
|
393
|
+
const uint PAGE_EXECUTE = 0x10;
|
|
394
|
+
const uint PAGE_EXECUTE_READ = 0x20;
|
|
395
|
+
const uint PAGE_EXECUTE_READWRITE = 0x40;
|
|
396
|
+
|
|
397
|
+
public static List<object> EnumerateRegions(int pid) {
|
|
398
|
+
var regions = new List<object>();
|
|
399
|
+
IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
|
|
400
|
+
if (hProcess == IntPtr.Zero) {
|
|
401
|
+
int error = Marshal.GetLastWin32Error();
|
|
402
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
try {
|
|
406
|
+
IntPtr addr = IntPtr.Zero;
|
|
407
|
+
MEMORY_BASIC_INFORMATION info;
|
|
408
|
+
int infoSize = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));
|
|
409
|
+
int scannedRegions = 0;
|
|
410
|
+
|
|
411
|
+
while (VirtualQueryEx(hProcess, addr, out info, infoSize) == infoSize) {
|
|
412
|
+
scannedRegions++;
|
|
413
|
+
string state = info.State == MEM_COMMIT ?
|
|
414
|
+
"COMMIT" :
|
|
415
|
+
(info.State == MEM_RESERVE ? "RESERVE" : (info.State == MEM_FREE ? "FREE" : "UNKNOWN"));
|
|
416
|
+
string protect = GetProtectionString(info.Protect);
|
|
417
|
+
bool isReadable = (info.State == MEM_COMMIT) && ((info.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE)) != 0);
|
|
418
|
+
|
|
419
|
+
regions.Add(new {
|
|
420
|
+
baseAddress = "0x" + info.BaseAddress.ToInt64().ToString("X"),
|
|
421
|
+
size = info.RegionSize.ToInt64(),
|
|
422
|
+
state = state,
|
|
423
|
+
protection = protect,
|
|
424
|
+
isReadable = isReadable,
|
|
425
|
+
type = info.Type == 0x1000000 ? "IMAGE" : (info.Type == 0x40000 ? "MAPPED" : "PRIVATE")
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
if (regions.Count >= ${re} || scannedRegions >= ${n}) break;
|
|
429
|
+
long baseAddr = info.BaseAddress.ToInt64();
|
|
430
|
+
long regionSize = info.RegionSize.ToInt64();
|
|
431
|
+
if (regionSize <= 0) break;
|
|
432
|
+
long nextAddr = baseAddr + regionSize;
|
|
433
|
+
if (nextAddr <= baseAddr) break;
|
|
434
|
+
addr = new IntPtr(nextAddr);
|
|
435
|
+
if (addr.ToInt64() >= 0x7FFFFFFF0000) break;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
return regions;
|
|
439
|
+
} finally {
|
|
440
|
+
CloseHandle(hProcess);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
private static string GetProtectionString(uint protect) {
|
|
445
|
+
if (protect == 0) return "NOACCESS";
|
|
446
|
+
string s = "";
|
|
447
|
+
if ((protect & 0x100) != 0) s += "NOACCESS ";
|
|
448
|
+
if ((protect & PAGE_READONLY) != 0) s += "R ";
|
|
449
|
+
if ((protect & PAGE_READWRITE) != 0) s += "RW ";
|
|
450
|
+
if ((protect & PAGE_WRITECOPY) != 0) s += "W ";
|
|
451
|
+
if ((protect & PAGE_EXECUTE) != 0) s += "X ";
|
|
452
|
+
if ((protect & PAGE_EXECUTE_READ) != 0) s += "RX ";
|
|
453
|
+
if ((protect & PAGE_EXECUTE_READWRITE) != 0) s += "RWX ";
|
|
454
|
+
if ((protect & 0x100) != 0) s += "GUARD ";
|
|
455
|
+
return s.Trim();
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
"@
|
|
459
|
+
|
|
460
|
+
try {
|
|
461
|
+
$regions = [RegionEnumerator]::EnumerateRegions(${e})
|
|
462
|
+
@{ success = $true; regions = $regions; count = $regions.Count } | ConvertTo-Json -Compress -Depth 10
|
|
463
|
+
} catch {
|
|
464
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
465
|
+
}
|
|
466
|
+
`.trim()}async function vt(e,n){if(e===`linux`)try{return{success:!0,regions:O(le(`/proc/${n}/maps`,`utf-8`)).filter(e=>e.permissions.read).map(e=>({baseAddress:`0x${e.start.toString(16)}`,size:Number(e.end-e.start),state:`COMMIT`,protection:oe(e.permissions),isReadable:!0,type:e.pathname||`anonymous`}))}}catch(e){return t.error(`Linux region enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}if(e!==`win32`&&e!==`darwin`)return{success:!1,error:`Region enumeration currently only implemented for Windows, Linux, and macOS`};if(e===`darwin`)try{let{stdout:e}=await K(`vmmap -v ${n}`,{timeout:s,maxBuffer:l}),t=[],r=/^(\S[^\t]*?)\s{2,}([0-9a-f]+)-([0-9a-f]+)\s+\[.*?\]\s+([a-z-]+)\/([a-z-]+)/;for(let n of e.split(`
|
|
467
|
+
`)){let e=n.match(r);if(!e)continue;let i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=parseInt(a,16),u=parseInt(o,16);t.push({baseAddress:`0x${a}`,size:u-l,type:i.trim(),protect:s,maxProtect:c,isReadable:s.includes(`r`),isWritable:s.includes(`w`),isExecutable:s.includes(`x`)})}return{success:!0,regions:t}}catch(e){return t.error(`macOS region enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}if(k())try{let e=await A.enumerateRegions(n);if(e.success)return e;t.warn(`Native Windows region enumeration failed, falling back to PowerShell`,{pid:n,error:e.error,nativeAvailable:k()})}catch(e){t.warn(`Native Windows region enumeration threw, falling back to PowerShell`,{pid:n,error:e instanceof Error?e.message:String(e),nativeAvailable:k()})}try{let{stdout:e}=await J(_t(n),{maxBuffer:ne,timeout:r}),t=e.trim();if(!t)throw Error(`PowerShell returned empty output`);let i=JSON.parse(t);return{success:i.success,regions:i.regions,error:i.error}}catch(e){return t.error(`Region enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function yt(e,t){return`
|
|
468
|
+
Add-Type @"
|
|
469
|
+
using System;
|
|
470
|
+
using System.Runtime.InteropServices;
|
|
471
|
+
using System.ComponentModel;
|
|
472
|
+
|
|
473
|
+
public class ProtectionChecker {
|
|
474
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
475
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
476
|
+
|
|
477
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
478
|
+
public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr addr, out MEMORY_BASIC_INFORMATION info, int size);
|
|
479
|
+
|
|
480
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
481
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
482
|
+
|
|
483
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
484
|
+
|
|
485
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
486
|
+
public struct MEMORY_BASIC_INFORMATION {
|
|
487
|
+
public IntPtr BaseAddress;
|
|
488
|
+
public IntPtr AllocationBase;
|
|
489
|
+
public uint AllocationProtect;
|
|
490
|
+
public IntPtr RegionSize;
|
|
491
|
+
public uint State;
|
|
492
|
+
public uint Protect;
|
|
493
|
+
public uint Type;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const uint MEM_COMMIT = 0x1000;
|
|
497
|
+
const uint PAGE_NOACCESS = 0x01;
|
|
498
|
+
const uint PAGE_READONLY = 0x02;
|
|
499
|
+
const uint PAGE_READWRITE = 0x04;
|
|
500
|
+
const uint PAGE_WRITECOPY = 0x08;
|
|
501
|
+
const uint PAGE_EXECUTE = 0x10;
|
|
502
|
+
const uint PAGE_EXECUTE_READ = 0x20;
|
|
503
|
+
const uint PAGE_EXECUTE_READWRITE = 0x40;
|
|
504
|
+
const uint PAGE_EXECUTE_WRITECOPY = 0x80;
|
|
505
|
+
const uint PAGE_GUARD = 0x100;
|
|
506
|
+
|
|
507
|
+
public static object CheckProtection(int pid, long address) {
|
|
508
|
+
IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
|
|
509
|
+
if (hProcess == IntPtr.Zero) {
|
|
510
|
+
int error = Marshal.GetLastWin32Error();
|
|
511
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
try {
|
|
515
|
+
MEMORY_BASIC_INFORMATION info;
|
|
516
|
+
int infoSize = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));
|
|
517
|
+
int result = VirtualQueryEx(hProcess, (IntPtr)address, out info, infoSize);
|
|
518
|
+
|
|
519
|
+
if (result != infoSize) {
|
|
520
|
+
return new { success = false, error = "Failed to query memory region" };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
if (info.State != MEM_COMMIT) {
|
|
524
|
+
return new {
|
|
525
|
+
success = true,
|
|
526
|
+
protection = "NOT_COMMITTED",
|
|
527
|
+
isWritable = false,
|
|
528
|
+
isReadable = false,
|
|
529
|
+
isExecutable = false,
|
|
530
|
+
regionStart = "0x" + info.BaseAddress.ToInt64().ToString("X"),
|
|
531
|
+
regionSize = info.RegionSize.ToInt64()
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
uint protect = info.Protect;
|
|
536
|
+
string protectionStr = "";
|
|
537
|
+
bool isWritable = false;
|
|
538
|
+
bool isReadable = false;
|
|
539
|
+
bool isExecutable = false;
|
|
540
|
+
|
|
541
|
+
if ((protect & PAGE_NOACCESS) != 0) protectionStr += "NOACCESS ";
|
|
542
|
+
if ((protect & PAGE_READONLY) != 0) { protectionStr += "R "; isReadable = true; }
|
|
543
|
+
if ((protect & PAGE_READWRITE) != 0) { protectionStr += "RW "; isReadable = true; isWritable = true; }
|
|
544
|
+
if ((protect & PAGE_WRITECOPY) != 0) { protectionStr += "WC "; isReadable = true; isWritable = true; }
|
|
545
|
+
if ((protect & PAGE_EXECUTE) != 0) { protectionStr += "X "; isExecutable = true; }
|
|
546
|
+
if ((protect & PAGE_EXECUTE_READ) != 0) { protectionStr += "RX "; isReadable = true; isExecutable = true; }
|
|
547
|
+
if ((protect & PAGE_EXECUTE_READWRITE) != 0) {
|
|
548
|
+
protectionStr += "RWX ";
|
|
549
|
+
isReadable = true;
|
|
550
|
+
isWritable = true;
|
|
551
|
+
isExecutable = true;
|
|
552
|
+
;
|
|
553
|
+
}
|
|
554
|
+
if ((protect & PAGE_EXECUTE_WRITECOPY) != 0) {
|
|
555
|
+
protectionStr += "RWCX ";
|
|
556
|
+
isReadable = true;
|
|
557
|
+
isWritable = true;
|
|
558
|
+
isExecutable = true;
|
|
559
|
+
;
|
|
560
|
+
}
|
|
561
|
+
if ((protect & PAGE_GUARD) != 0) protectionStr += "GUARD ";
|
|
562
|
+
|
|
563
|
+
return new {
|
|
564
|
+
success = true,
|
|
565
|
+
protection = protectionStr.Trim(),
|
|
566
|
+
isWritable = isWritable,
|
|
567
|
+
isReadable = isReadable,
|
|
568
|
+
isExecutable = isExecutable,
|
|
569
|
+
regionStart = "0x" + info.BaseAddress.ToInt64().ToString("X"),
|
|
570
|
+
regionSize = info.RegionSize.ToInt64()
|
|
571
|
+
};
|
|
572
|
+
} finally {
|
|
573
|
+
CloseHandle(hProcess);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
"@
|
|
578
|
+
|
|
579
|
+
try {
|
|
580
|
+
$result = [ProtectionChecker]::CheckProtection(${e}, ${t})
|
|
581
|
+
$result | ConvertTo-Json -Compress
|
|
582
|
+
} catch {
|
|
583
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
584
|
+
}
|
|
585
|
+
`.trim()}async function Z(e,n,r){let i=BigInt(r.startsWith(`0x`)?r:`0x${r}`);if(e===`linux`)try{let e=O(await ce.readFile(`/proc/${n}/maps`,`utf-8`)).find(e=>i>=e.start&&i<e.end);return e?{success:!0,protection:oe(e.permissions),isReadable:e.permissions.read,isWritable:e.permissions.write,isExecutable:e.permissions.exec,regionStart:`0x${e.start.toString(16)}`,regionSize:Number(e.end-e.start)}:{success:!1,error:`Address ${r} not found in any memory region`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}if(e===`darwin`){try{let{createPlatformProvider:e}=await import(`./factory-BeND77hf.mjs`).then(e=>e.n),t=e();if((await t.checkAvailability()).available){let e=t.openProcess(n,!1);try{let n=t.queryRegion(e,i);return n?{success:!0,protection:[n.isReadable?`r`:`-`,n.isWritable?`w`:`-`,n.isExecutable?`x`:`-`].join(``),isReadable:n.isReadable,isWritable:n.isWritable,isExecutable:n.isExecutable,regionStart:`0x${n.baseAddress.toString(16)}`,regionSize:n.size}:{success:!1,error:`Address ${r} not found in any memory region`}}finally{t.closeProcess(e)}}}catch{}try{let e=parseInt(r,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};let{stdout:t}=await K(`vmmap -v ${n}`,{timeout:a,maxBuffer:1024*1024*5}),i=/^(\S[^\t]*?)\s{2,}([0-9a-f]+)-([0-9a-f]+)\s+\[.*?\]\s+([a-z-]+)\/([a-z-]+)/;for(let n of t.split(`
|
|
586
|
+
`)){let t=n.match(i);if(!t)continue;let r=parseInt(t[2],16),a=parseInt(t[3],16);if(e>=r&&e<a){let e=t[4];return{success:!0,protection:e,isReadable:e.includes(`r`),isWritable:e.includes(`w`),isExecutable:e.includes(`x`),regionStart:`0x${t[2]}`,regionSize:a-r}}}return{success:!1,error:`Address ${r} not found in any memory region`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}if(k())try{let e=await A.checkMemoryProtection(n,r);if(e.success)return e;t.warn(`Native Windows memory protection check failed, falling back to PowerShell`,{pid:n,address:r,error:e.error,nativeAvailable:k()})}catch(e){t.warn(`Native Windows memory protection check threw, falling back to PowerShell`,{pid:n,address:r,error:e instanceof Error?e.message:String(e),nativeAvailable:k()})}try{let e=parseInt(r,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};let{stdout:t}=await J(yt(n,e),{maxBuffer:1024*1024,timeout:o}),i=t.trim();if(!i)throw Error(`PowerShell returned empty output`);let a=JSON.parse(i);return{success:a.success,protection:a.protection,isWritable:a.isWritable,isReadable:a.isReadable,isExecutable:a.isExecutable,regionStart:a.regionStart,regionSize:a.regionSize,error:a.error}}catch(e){return t.error(`Memory protection check failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}async function bt(e,n){if(e!==`win32`)return{success:!1,error:`Module enumeration currently only implemented for Windows`};try{let{stdout:e}=await J(`
|
|
587
|
+
Add-Type @"
|
|
588
|
+
using System;
|
|
589
|
+
using System.Runtime.InteropServices;
|
|
590
|
+
using System.Collections.Generic;
|
|
591
|
+
using System.ComponentModel;
|
|
592
|
+
|
|
593
|
+
public class ModuleEnumerator {
|
|
594
|
+
[DllImport("psapi.dll", SetLastError = true)]
|
|
595
|
+
public static extern bool EnumProcessModules(IntPtr hProcess, [Out] IntPtr[] lphModule, int cb, out int lpcbNeeded);
|
|
596
|
+
|
|
597
|
+
[DllImport("psapi.dll", SetLastError = true)]
|
|
598
|
+
public static extern int GetModuleBaseName(IntPtr hProcess, IntPtr hModule, [Out] System.Text.StringBuilder lpBaseName, int nSize);
|
|
599
|
+
|
|
600
|
+
[DllImport("psapi.dll", SetLastError = true)]
|
|
601
|
+
public static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out MODULEINFO lpmodinfo, int cb);
|
|
602
|
+
|
|
603
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
604
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
605
|
+
|
|
606
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
607
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
608
|
+
|
|
609
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
610
|
+
const int PROCESS_VM_READ = 0x0010;
|
|
611
|
+
|
|
612
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
613
|
+
public struct MODULEINFO {
|
|
614
|
+
public IntPtr lpBaseOfDll;
|
|
615
|
+
public int SizeOfImage;
|
|
616
|
+
public IntPtr EntryPoint;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
public static object Enumerate(int pid) {
|
|
620
|
+
IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
|
|
621
|
+
if (hProcess == IntPtr.Zero) {
|
|
622
|
+
int error = Marshal.GetLastWin32Error();
|
|
623
|
+
throw new Win32Exception(error, "Failed to open process");
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
try {
|
|
627
|
+
IntPtr[] modules = new IntPtr[1024];
|
|
628
|
+
int cbNeeded;
|
|
629
|
+
|
|
630
|
+
if (!EnumProcessModules(hProcess, modules, modules.Length * IntPtr.Size, out cbNeeded)) {
|
|
631
|
+
int error = Marshal.GetLastWin32Error();
|
|
632
|
+
throw new Win32Exception(error, "EnumProcessModules failed");
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
int numModules = cbNeeded / IntPtr.Size;
|
|
636
|
+
var result = new List<object>();
|
|
637
|
+
|
|
638
|
+
for (int i = 0; i < numModules; i++) {
|
|
639
|
+
System.Text.StringBuilder baseName = new System.Text.StringBuilder(256);
|
|
640
|
+
if (GetModuleBaseName(hProcess, modules[i], baseName, baseName.Capacity) > 0) {
|
|
641
|
+
MODULEINFO modInfo;
|
|
642
|
+
if (GetModuleInformation(hProcess, modules[i], out modInfo, Marshal.SizeOf(typeof(MODULEINFO)))) {
|
|
643
|
+
result.Add(new {
|
|
644
|
+
name = baseName.ToString(),
|
|
645
|
+
baseAddress = "0x" + modInfo.lpBaseOfDll.ToInt64().ToString("X"),
|
|
646
|
+
size = modInfo.SizeOfImage
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
return new { success = true, modules = result };
|
|
653
|
+
} finally {
|
|
654
|
+
CloseHandle(hProcess);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
"@
|
|
659
|
+
|
|
660
|
+
try {
|
|
661
|
+
$result = [ModuleEnumerator]::Enumerate(${n})
|
|
662
|
+
$result | ConvertTo-Json -Compress -Depth 10
|
|
663
|
+
} catch {
|
|
664
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
665
|
+
}
|
|
666
|
+
`,{maxBuffer:1024*1024*10,timeout:r}),t=e.trim();if(!t)throw Error(`PowerShell returned empty output`);return JSON.parse(t)}catch(e){return t.error(`Module enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}let xt=function(e){return e.STRICT=`strict`,e.BALANCED=`balanced`,e.PERMISSIVE=`permissive`,e.DISABLED=`disabled`,e}({});const St={win32:[`csrss.exe`,`smss.exe`,`winlogon.exe`,`services.exe`,`lsass.exe`,`wininit.exe`,`System`],linux:[`init`,`systemd`,`kthreadd`],darwin:[`launchd`,`kernel_task`]};var Ct=class{config;constructor(e){this.config=e}async validateTargetProcess(e){let n={valid:!0,processExists:!1,processAccessible:!1,isCriticalSystemProcess:!1,warnings:[],errors:[]};if(this.config.mode===`disabled`)return n.processExists=!0,n.processAccessible=!0,n;if(!Number.isInteger(e)||e<=0)return n.valid=!1,n.errors.push(`Invalid PID: ${e}`),n;try{let{UnifiedProcessManager:t}=await Promise.resolve().then(()=>Ht),r=new t,i=await r.getProcessByPid(e);if(!i)return n.valid=!1,n.errors.push(`Process ${e} does not exist or is not accessible`),n;n.processExists=!0,n.processAccessible=!0,n.processName=i.name,n.executablePath=i.executablePath??``;let a=r.getPlatform(),o=St[a]??[],s=i.name?.toLowerCase()??``;if(o.some(e=>s.includes(e.toLowerCase())))return n.valid=!1,n.isCriticalSystemProcess=!0,n.errors.push(`Target process is a critical system process: ${i.name}`),n;if(a===`win32`&&this.config.mode!==`permissive`){let e=await this.checkWindowsSignature(i.executablePath??``);n.isSigned=e.isSigned,n.signatureValid=e.isValid,!e.isSigned&&this.config.mode===`balanced`&&n.warnings.push(`Process is not digitally signed: ${i.name}`)}}catch(e){n.valid=!1,n.errors.push(`Failed to validate process: ${e instanceof Error?e.message:String(e)}`),t.debug(`Process validation error:`,e)}return n}async validateDllPayload(e,n){let r={valid:!0,payloadType:`dll`,warnings:[],errors:[]};if(this.config.mode===`disabled`)return r;try{if(r.fileExists=pe(e),!r.fileExists)return r.valid=!1,r.errors.push(`DLL file not found: ${e}`),r;r.fileSize=_e(e).size,r.fileSize>52428800&&r.warnings.push(`DLL file is unusually large (${Math.round(r.fileSize/1024/1024)}MB). Verify this is correct.`),this.config.requireHashForDll&&!n?.expectedHash&&(r.valid=!1,r.errors.push(`DLL hash validation required but no expectedHash provided`)),n?.expectedHash&&(r.expectedHash=n.expectedHash,r.actualHash=await this.computeFileHash(e),r.hashMatch=r.actualHash===n.expectedHash,r.hashMatch||(r.valid=!1,r.errors.push(`DLL hash mismatch`)))}catch(e){r.valid=!1,r.errors.push(`Failed to validate DLL: ${e instanceof Error?e.message:String(e)}`),t.debug(`DLL validation error:`,e)}return r}async validateShellcodePayload(e,n){let r={valid:!0,payloadType:`shellcode`,encodingValid:!1,warnings:[],errors:[]};if(this.config.mode===`disabled`)return r.encodingValid=!0,r;if(!e||e.length===0)return r.valid=!1,r.errors.push(`Shellcode is empty`),r;try{let t;if(n===`hex`){let n=e.replace(/\s/g,``);if(!/^[0-9A-Fa-f]*$/.test(n))return r.valid=!1,r.errors.push(`Invalid hex encoding in shellcode`),r;t=Buffer.from(n,`hex`)}else try{if(t=Buffer.from(e,`base64`),t.toString(`base64`)!==e.replace(/\s/g,``))return r.valid=!1,r.errors.push(`Invalid base64 encoding in shellcode`),r}catch{return r.valid=!1,r.errors.push(`Invalid base64 encoding in shellcode`),r}r.encodingValid=!0,r.shellcodeSize=t.length,r.shellcodeSize>this.config.maxShellcodeSize&&(r.valid=!1,r.errors.push(`Shellcode size (${r.shellcodeSize} bytes) exceeds maximum allowed (${this.config.maxShellcodeSize} bytes)`)),r.shellcodeSize<4&&r.warnings.push(`Shellcode is suspiciously small (${r.shellcodeSize} bytes). Verify this is correct.`)}catch(e){r.valid=!1,r.errors.push(`Failed to validate shellcode: ${e instanceof Error?e.message:String(e)}`),t.debug(`Shellcode validation error:`,e)}return r}requireConfirmation(e,t){let n={required:!1,overrideFlag:`confirmed`};if(this.config.mode===`disabled`||this.config.mode===`permissive`||this.config.mode===`balanced`)return n;if(this.config.mode===`strict`){let r=[];e.isSigned===!1&&r.push(`target process is not digitally signed`),e.warnings.length>0&&r.push(`target process has validation warnings`),t.warnings.length>0&&r.push(`payload has validation warnings`),r.length>0&&(n.required=!0,n.reason=`Confirmation required: ${r.join(`, `)}`)}return n}async computeFileHash(e){return new Promise(n=>{let r=ye(`sha256`),i=fe(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>n(r.digest(`hex`))),i.on(`error`,e=>{t.debug(`Failed to compute file hash:`,e),n(``)})})}async checkWindowsSignature(e){if(!e||process.platform!==`win32`||!pe(e))return{isSigned:!1,isValid:!1};try{let[t,n]=be(`(Get-AuthenticodeSignature -LiteralPath '${e.replace(/'/g,`''`)}') | ForEach-Object { $_.Status.ToString() + '|' + ($_.SignerCertificate.Subject ?? '') }`,{encoding:`utf8`,timeout:1e4,windowsHide:!0,stdio:[`ignore`,`pipe`,`ignore`]}).trim().split(`|`),r=(t??``).trim();return{isSigned:r!==``&&r!==`NotSigned`&&r!==`UnknownError`&&r!==`NotSupportedFileFormat`,isValid:r===`Valid`,signer:(n??``).trim()||void 0}}catch(e){return t.debug(`Windows signature check failed:`,e),{isSigned:!1,isValid:!1}}}};function wt(){let e=(process.env.JSHOOK_INJECTION_VALIDATION_MODE??`balanced`).toLowerCase(),t=Object.values(xt).includes(e)?e:`balanced`;return new Ct({mode:t,maxShellcodeSize:1024*1024,requireHashForDll:t===`strict`})}function Tt(e){if(/[`$"';|<>&()\\\n\r]/.test(e))throw Error(`Path contains unsafe characters: ${e}`)}let Et=null;function Dt(e){if(e){let t=Object.values(xt).includes(e)?e:`balanced`;return new Ct({mode:t,maxShellcodeSize:1024*1024,requireHashForDll:t===`strict`})}return Et||=wt(),Et}function Ot(e,t){return`
|
|
667
|
+
Add-Type @"
|
|
668
|
+
using System;
|
|
669
|
+
using System.Runtime.InteropServices;
|
|
670
|
+
using System.ComponentModel;
|
|
671
|
+
using System.IO;
|
|
672
|
+
|
|
673
|
+
public class DllInjector {
|
|
674
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
675
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
676
|
+
|
|
677
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
678
|
+
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr addr, int size, int allocType, int protect);
|
|
679
|
+
|
|
680
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
681
|
+
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int written);
|
|
682
|
+
|
|
683
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
684
|
+
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr attr, int stackSize, IntPtr startAddr, IntPtr param, int flags, out int threadId);
|
|
685
|
+
|
|
686
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
687
|
+
public static extern IntPtr GetModuleHandle(string name);
|
|
688
|
+
|
|
689
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
690
|
+
public static extern IntPtr GetProcAddress(IntPtr hModule, string name);
|
|
691
|
+
|
|
692
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
693
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
694
|
+
|
|
695
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
696
|
+
public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr addr, int size, int freeType);
|
|
697
|
+
|
|
698
|
+
const int PROCESS_CREATE_THREAD = 0x0002;
|
|
699
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
700
|
+
const int PROCESS_VM_OPERATION = 0x0008;
|
|
701
|
+
const int PROCESS_VM_WRITE = 0x0020;
|
|
702
|
+
const int MEM_COMMIT = 0x1000;
|
|
703
|
+
const int MEM_RESERVE = 0x2000;
|
|
704
|
+
const int PAGE_READWRITE = 0x04;
|
|
705
|
+
const int MEM_RELEASE = 0x8000;
|
|
706
|
+
|
|
707
|
+
public static object Inject(int pid, string dllPath) {
|
|
708
|
+
if (!File.Exists(dllPath)) {
|
|
709
|
+
return new { success = false, error = "DLL not found: " + dllPath };
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid);
|
|
713
|
+
if (hProcess == IntPtr.Zero) {
|
|
714
|
+
int error = Marshal.GetLastWin32Error();
|
|
715
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
try {
|
|
719
|
+
byte[] dllBytes = System.Text.Encoding.ASCII.GetBytes(dllPath + "\\0");
|
|
720
|
+
IntPtr remoteMem = VirtualAllocEx(hProcess, IntPtr.Zero, dllBytes.Length, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
|
721
|
+
if (remoteMem == IntPtr.Zero) {
|
|
722
|
+
int error = Marshal.GetLastWin32Error();
|
|
723
|
+
throw new Win32Exception(error, "Failed to allocate memory in target");
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
try {
|
|
727
|
+
int written;
|
|
728
|
+
if (!WriteProcessMemory(hProcess, remoteMem, dllBytes, dllBytes.Length, out written)) {
|
|
729
|
+
int error = Marshal.GetLastWin32Error();
|
|
730
|
+
throw new Win32Exception(error, "Failed to write DLL path to target");
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
IntPtr hKernel32 = GetModuleHandle("kernel32.dll");
|
|
734
|
+
IntPtr loadLibraryAddr = GetProcAddress(hKernel32, "LoadLibraryA");
|
|
735
|
+
if (loadLibraryAddr == IntPtr.Zero) {
|
|
736
|
+
throw new Exception("Failed to get LoadLibraryA address");
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
int threadId;
|
|
740
|
+
IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, loadLibraryAddr, remoteMem, 0, out threadId);
|
|
741
|
+
if (hThread == IntPtr.Zero) {
|
|
742
|
+
int error = Marshal.GetLastWin32Error();
|
|
743
|
+
throw new Win32Exception(error, "Failed to create remote thread");
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
CloseHandle(hThread);
|
|
747
|
+
return new { success = true, remoteThreadId = threadId };
|
|
748
|
+
} finally {
|
|
749
|
+
VirtualFreeEx(hProcess, remoteMem, 0, MEM_RELEASE);
|
|
750
|
+
}
|
|
751
|
+
} finally {
|
|
752
|
+
CloseHandle(hProcess);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
"@
|
|
757
|
+
|
|
758
|
+
try {
|
|
759
|
+
$result = [DllInjector]::Inject(${e}, "${t.replace(/\\/g,`\\\\`).replace(/"/g,'`"').replace(/`/g,"``").replace(/\$/g,"`$")}")
|
|
760
|
+
$result | ConvertTo-Json -Compress
|
|
761
|
+
} catch {
|
|
762
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
763
|
+
}
|
|
764
|
+
`.trim()}async function kt(e,n,r,i){let a=Dt(i?.validationMode);if(!i?.confirmed)try{let e=await a.validateTargetProcess(n);if(!e.valid)return{success:!1,error:e.errors.join(`; `),validationFailed:!0};let o=await a.validateDllPayload(r,{expectedHash:i?.payloadHash});if(!o.valid)return{success:!1,error:o.errors.join(`; `),validationFailed:!0};let s=a.requireConfirmation(e,o);if(s.required)return{success:!1,error:s.reason||`Confirmation required`,confirmationRequired:!0,validationFailed:!0};e.warnings.length>0&&t.warn(`DLL injection warnings (target): ${e.warnings.join(`; `)}`),o.warnings.length>0&&t.warn(`DLL injection warnings (payload): ${o.warnings.join(`; `)}`)}catch(e){return t.error(`Validation error during DLL injection:`,e),{success:!1,error:`Validation error: ${e instanceof Error?e.message:String(e)}`,validationFailed:!0}}if(e===`linux`)try{Tt(r);let{stderr:e}=await K(`gdb -p ${n} -batch -ex "call (void*)dlopen(\\"${r}\\", 1)" -ex "quit"`,{timeout:x});if(e.includes(`Operation not permitted`)||e.includes(`ptrace:`))throw Error(`GDB injection failed (ptrace blocked): ${e}`);return{success:!0}}catch(e){return t.error(`Linux DLL injection failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}else if(e===`darwin`)try{Tt(r);let{stdout:e,stderr:t}=await K(`lldb --batch -p ${n} -o "expr (void*)dlopen(\\"${r}\\", 1)"`,{timeout:x});if(t.includes(`error:`)||e.includes(`error:`))throw Error(`LLDB injection failed: ${t||e}`);return{success:!0}}catch(e){return t.error(`macOS DLL injection failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}else if(e!==`win32`)return{success:!1,error:`DLL injection not supported on this platform`};try{let{stdout:e}=await J(Ot(n,r),{maxBuffer:1024*1024,timeout:x}),t=e.trim();if(!t)throw Error(`PowerShell returned empty output`);let i=JSON.parse(t);return{success:i.success,remoteThreadId:i.remoteThreadId,error:i.error}}catch(e){return t.error(`DLL injection failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function At(e,t){return`
|
|
765
|
+
Add-Type @"
|
|
766
|
+
using System;
|
|
767
|
+
using System.Runtime.InteropServices;
|
|
768
|
+
using System.ComponentModel;
|
|
769
|
+
|
|
770
|
+
public class ShellcodeInjector {
|
|
771
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
772
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
773
|
+
|
|
774
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
775
|
+
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr addr, int size, int allocType, int protect);
|
|
776
|
+
|
|
777
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
778
|
+
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int written);
|
|
779
|
+
|
|
780
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
781
|
+
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr attr, int stackSize, IntPtr startAddr, IntPtr param, int flags, out int threadId);
|
|
782
|
+
|
|
783
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
784
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
785
|
+
|
|
786
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
787
|
+
public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr addr, int size, int newProtect, out int oldProtect);
|
|
788
|
+
|
|
789
|
+
const int PROCESS_CREATE_THREAD = 0x0002;
|
|
790
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
791
|
+
const int PROCESS_VM_OPERATION = 0x0008;
|
|
792
|
+
const int PROCESS_VM_WRITE = 0x0020;
|
|
793
|
+
const int MEM_COMMIT = 0x1000;
|
|
794
|
+
const int MEM_RESERVE = 0x2000;
|
|
795
|
+
const int PAGE_READWRITE = 0x04;
|
|
796
|
+
const int PAGE_EXECUTE_READWRITE = 0x40;
|
|
797
|
+
|
|
798
|
+
public static object Inject(int pid, byte[] shellcode) {
|
|
799
|
+
IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid);
|
|
800
|
+
if (hProcess == IntPtr.Zero) {
|
|
801
|
+
int error = Marshal.GetLastWin32Error();
|
|
802
|
+
throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
try {
|
|
806
|
+
IntPtr remoteMem = VirtualAllocEx(hProcess, IntPtr.Zero, shellcode.Length, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
|
807
|
+
if (remoteMem == IntPtr.Zero) {
|
|
808
|
+
int error = Marshal.GetLastWin32Error();
|
|
809
|
+
throw new Win32Exception(error, "Failed to allocate memory in target");
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
try {
|
|
813
|
+
int written;
|
|
814
|
+
if (!WriteProcessMemory(hProcess, remoteMem, shellcode, shellcode.Length, out written)) {
|
|
815
|
+
int error = Marshal.GetLastWin32Error();
|
|
816
|
+
throw new Win32Exception(error, "Failed to write shellcode to target");
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
int oldProtect;
|
|
820
|
+
if (!VirtualProtectEx(hProcess, remoteMem, shellcode.Length, PAGE_EXECUTE_READWRITE, out oldProtect)) {
|
|
821
|
+
int error = Marshal.GetLastWin32Error();
|
|
822
|
+
throw new Win32Exception(error, "Failed to change memory protection to executable");
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
int threadId;
|
|
826
|
+
IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, remoteMem, IntPtr.Zero, 0, out threadId);
|
|
827
|
+
if (hThread == IntPtr.Zero) {
|
|
828
|
+
int error = Marshal.GetLastWin32Error();
|
|
829
|
+
throw new Win32Exception(error, "Failed to create remote thread");
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
CloseHandle(hThread);
|
|
833
|
+
return new { success = true, remoteThreadId = threadId };
|
|
834
|
+
} finally {
|
|
835
|
+
// Note: Memory is not freed to allow shellcode to execute
|
|
836
|
+
}
|
|
837
|
+
} finally {
|
|
838
|
+
CloseHandle(hProcess);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
"@
|
|
843
|
+
|
|
844
|
+
try {
|
|
845
|
+
$shellcode = @(${Array.from(t).join(`,`)})
|
|
846
|
+
$result = [ShellcodeInjector]::Inject(${e}, $shellcode)
|
|
847
|
+
$result | ConvertTo-Json -Compress
|
|
848
|
+
} catch {
|
|
849
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
850
|
+
}
|
|
851
|
+
`.trim()}async function jt(e,n,r,i=`hex`,a){let o=Dt(a?.validationMode);if(!a?.confirmed)try{let e=await o.validateTargetProcess(n);if(!e.valid)return{success:!1,error:e.errors.join(`; `),validationFailed:!0};let a=await o.validateShellcodePayload(r,i);if(!a.valid)return{success:!1,error:a.errors.join(`; `),validationFailed:!0};let s=o.requireConfirmation(e,a);if(s.required)return{success:!1,error:s.reason||`Confirmation required`,confirmationRequired:!0,validationFailed:!0};e.warnings.length>0&&t.warn(`Shellcode injection warnings (target): ${e.warnings.join(`; `)}`),a.warnings.length>0&&t.warn(`Shellcode injection warnings (payload): ${a.warnings.join(`; `)}`)}catch(e){return t.error(`Validation error during shellcode injection:`,e),{success:!1,error:`Validation error: ${e instanceof Error?e.message:String(e)}`,validationFailed:!0}}try{let t;if(i===`base64`)t=Buffer.from(r,`base64`);else{let e=r.replace(/\s/g,``);t=Buffer.from(e,`hex`)}if(e===`linux`){let e=Array.from(t).map(e=>`\\x${e.toString(16).padStart(2,`0`)}`).join(``),r=`
|
|
852
|
+
import gdb
|
|
853
|
+
import sys
|
|
854
|
+
|
|
855
|
+
def inject():
|
|
856
|
+
try:
|
|
857
|
+
# mmap: PROT_READ|PROT_WRITE|PROT_EXEC (7), MAP_PRIVATE|MAP_ANONYMOUS (34)
|
|
858
|
+
mmap_res = gdb.parse_and_eval("(void*)mmap(0, ${t.length}, 7, 34, -1, 0)")
|
|
859
|
+
addr = int(mmap_res)
|
|
860
|
+
if addr == -1 or addr == 0:
|
|
861
|
+
print("ERROR_INJECT: mmap failed")
|
|
862
|
+
return
|
|
863
|
+
|
|
864
|
+
inf = gdb.selected_inferior()
|
|
865
|
+
inf.write_memory(addr, b"${e}")
|
|
866
|
+
|
|
867
|
+
# Call it directly (creates a crash potentially) or via pthread_create
|
|
868
|
+
# Let's use pthread_create
|
|
869
|
+
thread_t = gdb.parse_and_eval("(void*)malloc(8)")
|
|
870
|
+
res = gdb.parse_and_eval(f"(int)pthread_create({int(thread_t)}, 0, {addr}, 0)")
|
|
871
|
+
|
|
872
|
+
print(f"SUCCESS_INJECT: {int(res)}")
|
|
873
|
+
except Exception as e:
|
|
874
|
+
print(f"ERROR_INJECT: {str(e)}")
|
|
875
|
+
|
|
876
|
+
inject()
|
|
877
|
+
`,i=P(M(),`gdb_inject_${n}_${Date.now()}.py`);await N.writeFile(i,r,`utf8`);try{let{stdout:e,stderr:t}=await K(`gdb -p ${n} -batch -x ${i}`,{timeout:x});if(e.includes(`ERROR_INJECT:`)||t.includes(`ERROR_INJECT:`))throw Error(`GDB injection failed: ${e||t}`);return{success:!0}}finally{await N.unlink(i).catch(()=>{})}}else if(e===`darwin`){let e=Array.from(t).map(e=>e.toString()).join(`,`),r=`
|
|
878
|
+
import lldb
|
|
879
|
+
import sys
|
|
880
|
+
|
|
881
|
+
def __lldb_init_module(debugger, internal_dict):
|
|
882
|
+
try:
|
|
883
|
+
target = debugger.GetSelectedTarget()
|
|
884
|
+
process = target.GetProcess()
|
|
885
|
+
|
|
886
|
+
# mmap: PROT_READ|PROT_WRITE|PROT_EXEC (7), MAP_PRIVATE|MAP_ANON (4098 on macOS)
|
|
887
|
+
res = lldb.SBCommandReturnObject()
|
|
888
|
+
debugger.GetCommandInterpreter().HandleCommand("expr (void*)mmap(0, ${t.length}, 7, 4098, -1, 0)", res)
|
|
889
|
+
|
|
890
|
+
if not res.Succeeded():
|
|
891
|
+
print("ERROR_INJECT: " + res.GetError())
|
|
892
|
+
return
|
|
893
|
+
|
|
894
|
+
addr_str = res.GetOutput().split()[-1]
|
|
895
|
+
addr = int(addr_str, 16)
|
|
896
|
+
|
|
897
|
+
err = lldb.SBError()
|
|
898
|
+
bytes_data = bytes([${e}])
|
|
899
|
+
process.WriteMemory(addr, bytes_data, err)
|
|
900
|
+
|
|
901
|
+
if not err.Success():
|
|
902
|
+
print("ERROR_INJECT: write failed")
|
|
903
|
+
return
|
|
904
|
+
|
|
905
|
+
# create thread
|
|
906
|
+
res2 = lldb.SBCommandReturnObject()
|
|
907
|
+
debugger.GetCommandInterpreter().HandleCommand(f"expr (int)pthread_create((void*)malloc(8), 0, (void*){addr}, 0)", res2)
|
|
908
|
+
|
|
909
|
+
print("SUCCESS_INJECT")
|
|
910
|
+
except Exception as e:
|
|
911
|
+
print("ERROR_INJECT: " + str(e))
|
|
912
|
+
`,i=P(M(),`lldb_inject_${n}_${Date.now()}.py`),a=P(M(),`lldb_inject_cmd_${n}_${Date.now()}.txt`);await N.writeFile(i,r,`utf8`),await N.writeFile(a,`command script import ${i}\\nprocess detach\\n`,`utf8`);try{let{stdout:e}=await K(`lldb --batch -p ${n} --source ${a}`,{timeout:x});if(e.includes(`ERROR_INJECT:`))throw Error(`LLDB injection failed: ${e}`);return{success:!0}}finally{await N.unlink(i).catch(()=>{}),await N.unlink(a).catch(()=>{})}}else if(e!==`win32`)return{success:!1,error:`Shellcode injection not supported on this platform`};let{stdout:a}=await J(At(n,t),{maxBuffer:1024*1024,timeout:x}),o=a.trim();if(!o)throw Error(`PowerShell returned empty output`);let s=JSON.parse(o);return{success:s.success,remoteThreadId:s.remoteThreadId,error:s.error}}catch(e){return t.error(`Shellcode injection failed:`,e),{success:!1,error:e instanceof Error?e.message:`Execution failed`}}}var Mt=class{activeMonitors=new Map;start(e,t,n=4,r=1e3,i,a){let o=`monitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=setInterval(async()=>{let r=this.activeMonitors.get(o);if(r&&!r.inFlight){r.inFlight=!0;try{let o=await i(e,t,n);o.success&&o.data&&r.lastValue!==o.data&&(a&&r.lastValue!==``&&a(r.lastValue,o.data),r.lastValue=o.data)}finally{r.inFlight=!1}}},r);return typeof s.unref==`function`&&s.unref(),this.activeMonitors.set(o,{pid:e,address:t,interval:r,lastValue:``,timer:s,inFlight:!1}),o}stop(e){let t=this.activeMonitors.get(e);return t?(clearInterval(t.timer),this.activeMonitors.delete(e),!0):!1}};const Nt=ee;let Q=null;function Pt(e,t){if(typeof e!=`object`||!e)return``;let n=e[t];return typeof n==`string`?n:``}function Ft(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${Pt(e,`stderr`)}`.toLowerCase();return n.includes(`enoent`)||n.includes(`command not found`)||n.includes(`is not recognized as an internal or external command`)||n.includes(`cannot find`)&&n.includes(`powershell`)?`PowerShell is unavailable. Windows memory operations require powershell.exe to verify Administrator privileges.`:`PowerShell command execution failed while checking Administrator privileges: ${t}`}async function It(){try{let{stdout:e}=await J(`([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)`,{timeout:T}),t=e.trim().toLowerCase();return t===`true`?{available:!0}:t===`false`?{available:!1,reason:`Windows memory operations require Administrator privileges. Please run your terminal/IDE as Administrator and retry.`}:{available:!1,reason:`PowerShell command execution failed while checking Administrator privileges: unexpected output "${e.trim()} '(empty)'}".`}}catch(e){return{available:!1,reason:Ft(e)}}}async function Lt(){let e=Date.now();if(Q&&Q.expiresAt>e)return Q.result;let t=await It();return Q={expiresAt:e+Nt,result:t},t}async function Rt(e){switch(e){case`win32`:return Lt();case`linux`:try{let{stdout:e}=await K(`id -u`,{timeout:v});if(e.trim()===`0`)return{available:!0};try{return await K(`capsh --print 2>/dev/null | grep -q "cap_sys_ptrace"`,{timeout:v}),{available:!0}}catch{return{available:!1,reason:`Linux memory operations require root privileges or CAP_SYS_PTRACE capability. Run with sudo.`}}}catch{return{available:!1,reason:`Requires root privileges for /proc/pid/mem access. Run with sudo.`}}case`darwin`:try{return await K(`which lldb`,{timeout:v}),{available:!0,reason:process.getuid?.()===0?void 0:`Running without root — memory access works for own processes only. Use sudo for other processes.`}}catch{return{available:!1,reason:`lldb not found. Install Xcode Command Line Tools: xcode-select --install`}}default:return{available:!1,reason:`Platform ${e} not supported for memory operations.`}}}async function zt(e,t){if(e!==`win32`)return{success:!1,error:`Debug port check currently only implemented for Windows`};try{let{stdout:e}=await J(`
|
|
913
|
+
Add-Type @"
|
|
914
|
+
using System;
|
|
915
|
+
using System.Runtime.InteropServices;
|
|
916
|
+
using System.ComponentModel;
|
|
917
|
+
|
|
918
|
+
public class DebugChecker {
|
|
919
|
+
[DllImport("ntdll.dll")]
|
|
920
|
+
public static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, out IntPtr processInformation, int processInformationLength, out int returnLength);
|
|
921
|
+
|
|
922
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
923
|
+
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
|
|
924
|
+
|
|
925
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
926
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
927
|
+
|
|
928
|
+
const int PROCESS_QUERY_INFORMATION = 0x0400;
|
|
929
|
+
const int ProcessDebugPort = 7;
|
|
930
|
+
|
|
931
|
+
public static object Check(int pid) {
|
|
932
|
+
IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
|
|
933
|
+
if (hProcess == IntPtr.Zero) {
|
|
934
|
+
int error = Marshal.GetLastWin32Error();
|
|
935
|
+
throw new Win32Exception(error, "Failed to open process");
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
try {
|
|
939
|
+
IntPtr debugPort;
|
|
940
|
+
int returnLength;
|
|
941
|
+
int status = NtQueryInformationProcess(hProcess, ProcessDebugPort, out debugPort, IntPtr.Size, out returnLength);
|
|
942
|
+
|
|
943
|
+
if (status != 0) {
|
|
944
|
+
return new { success = false, error = "NtQueryInformationProcess failed with status: 0x" + status.ToString("X") };
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
return new { success = true, isDebugged = debugPort != IntPtr.Zero };
|
|
948
|
+
} finally {
|
|
949
|
+
CloseHandle(hProcess);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
"@
|
|
954
|
+
|
|
955
|
+
try {
|
|
956
|
+
$result = [DebugChecker]::Check(${t})
|
|
957
|
+
$result | ConvertTo-Json -Compress
|
|
958
|
+
} catch {
|
|
959
|
+
@{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
|
|
960
|
+
}
|
|
961
|
+
`,{maxBuffer:1024*1024,timeout:T*2}),n=e.trim();if(!n)throw Error(`PowerShell returned empty output`);try{return JSON.parse(n)}catch{throw Error(`PowerShell returned empty output`)}}catch(e){return{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function Bt(){switch(process.platform){case`win32`:return`win32`;case`linux`:return`linux`;case`darwin`:return`darwin`;default:return`unknown`}}var Vt=class{platform;monitorManager=new Mt;constructor(){this.platform=Bt(),t.info(`MemoryManager initialized for platform: ${this.platform}`)}async readMemory(e,t,n){return We(this.platform,e,t,n,(e,t)=>Z(this.platform,e,t))}async writeMemory(e,t,n,r=`hex`){return Ze(this.platform,e,t,n,r,(e,t)=>Z(this.platform,e,t))}async batchMemoryWrite(e,t){return $e(e,t,(e,t,n,r)=>this.writeMemory(e,t,n,r))}async scanMemory(e,t,n=`hex`,r=!1){return ut(this.platform,e,t,n,r)}async scanMemoryFiltered(e,t,n,r=`hex`){return dt(e,t,n,r,(e,t,n)=>this.readMemory(e,t,n),(e,t,n)=>this.scanMemory(e,t,n))}async dumpMemoryRegion(e,t,n,r){return gt(this.platform,e,t,n,r)}async enumerateRegions(e){return vt(this.platform,e)}async checkMemoryProtection(e,t){return Z(this.platform,e,t)}async enumerateModules(e){return bt(this.platform,e)}async injectDll(e,t,n){return kt(this.platform,e,t,n)}async injectShellcode(e,t,n=`hex`,r){return jt(this.platform,e,t,n,r)}async checkDebugPort(e){return zt(this.platform,e)}startMemoryMonitor(e,t,n=4,r=1e3,i){return this.monitorManager.start(e,t,n,r,(e,t,n)=>this.readMemory(e,t,n),i)}stopMemoryMonitor(e){return this.monitorManager.stop(e)}async checkAvailability(){return Rt(this.platform)}},Ht=e({LinuxProcessManager:()=>je,MacProcessManager:()=>Fe,UnifiedProcessManager:()=>Wt,WindowsProcessManager:()=>ke,createProcessManager:()=>Ut,detectPlatform:()=>$});function $(){let e=process.platform;switch(e){case`win32`:return`win32`;case`linux`:return`linux`;case`darwin`:return`darwin`;default:return t.warn(`Unsupported platform: ${e}`),`unknown`}}function Ut(){let e=$();switch(t.info(`Creating ProcessManager for platform: ${e}`),e){case`win32`:return new ke;case`linux`:return new je;case`darwin`:return new Fe;default:throw Error(`Unsupported platform: ${e}. ProcessManager requires Windows, Linux, or macOS.`)}}var Wt=class{manager;platform;constructor(){this.platform=$(),this.manager=Ut()}getPlatform(){return this.platform}async findProcesses(e){return this.manager.findProcesses(e)}async getProcessByPid(e){return this.manager.getProcessByPid(e)}async getProcessWindows(e){return this.manager.getProcessWindows(e)}async checkDebugPort(e,t){return this.manager.checkDebugPort(e,t)}async launchWithDebug(e,t,n){return this.manager.launchWithDebug(e,t,n)}async killProcess(e){return this.manager.killProcess(e)}async getProcessCommandLine(e){return this.manager.getProcessCommandLine(e)}async findBrowserProcesses(e){return this.platform===`win32`?e?.processNamePattern||e?.windowClassPattern?this.manager.findChromiumProcesses({processNamePattern:e.processNamePattern,windowClassPattern:e.windowClassPattern}):this.manager.findChromiumAppProcesses():this.platform===`linux`||this.platform===`darwin`?this.manager.findChromeProcesses():null}};export{Vt as n,lt as r,Wt as t};
|