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
//! Windows `CommandLineToArgvW`-compatible command-line construction.
//!
//! Operates on UTF-16 code units so the algorithm is testable on any host;
//! a `#[cfg(windows)]` test validates it against the real OS parser.
//!
//! This module builds ([`join_wide`]) and parses ([`split_wide`]) the
//! command-line string for PE images launched via `CreateProcess`,
//! implementing exactly the quoting rules `CommandLineToArgvW` uses in both
//! directions (MSVCRT / Win32 argv parsing). It does NOT handle `cmd.exe`
//! metacharacter escaping: `.bat`/`.cmd` invocation (the actual BatBadBut /
//! CVE-2024-24576 vector) requires a separate escaping layer, which this
//! module does not provide.
use crateQuoteError;
const SPACE: u16 = b' ' as u16;
const TAB: u16 = b'\t' as u16;
const QUOTE: u16 = b'"' as u16;
const BACKSLASH: u16 = b'\\' as u16;
/// Join argv into a single command-line string per the MSVCRT rules that
/// `CommandLineToArgvW` reverses. Intended for argv[1..]; the program name
/// (`argv[0]`) is passed separately as `lpApplicationName`.
/// Like [`first_token_wide`], but also returns the remainder of the command
/// line AFTER the first token (with the separating whitespace consumed). Used
/// to feed `raw_arg` the args-only portion (std prepends the program itself).
/// Returns `None` only for empty/whitespace-only input.
///
/// # Behaviour change from `CreateProcessW`'s own NULL-`lpApplicationName` heuristic
///
/// An UNQUOTED, unescaped token containing a space (e.g. `C:\Program Files\svc.exe arg`, with no
/// surrounding `"`) stops at the first space here, same as any other unquoted token: the "program"
/// extracted is just `C:\Program`, which then fails to resolve (`NotFound`) rather than launching
/// anything. This is a deliberate, documented deviation from `CreateProcessW`'s own behaviour when
/// `lpApplicationName` is NULL: the OS instead tries successive whitespace-delimited PREFIXES of
/// the line as candidate images (`C:\Program.exe`, then `C:\Program Files\svc.exe`, ...) — the
/// classic "unquoted service path" hijack vector, where a writable `C:\Program.exe` hijacks a
/// service whose real, legitimate target is `C:\Program Files\svc.exe`. Failing closed instead of
/// retrying is the safer choice cosca makes deliberately, but it IS an observable behaviour change
/// versus that OS heuristic for anyone relying on it: an unquoted, spaced program path that the OS
/// would previously have found (correctly or via the hijack vector) now reliably errors instead.
/// The fix is on the caller: quote the path (`"C:\Program Files\svc.exe" arg`).
/// Extract the program token (`argv[0]`) from a command line, for deriving
/// `lpApplicationName` from a user-supplied `commandline`.
///
/// Deliberate deviation from `CommandLineToArgvW`'s `argv[0]` handling: leading
/// whitespace is skipped and empty/whitespace-only input returns `None`. The OS
/// does not skip leading whitespace: on an empty string it substitutes the
/// module path as `argv[0]`; on a whitespace-only string it returns `""` as
/// `argv[0]`. In both cases this function returns `None`. The token shape
/// otherwise matches: a leading `"` runs to the next `"` (or to the end if
/// unterminated); an unquoted token runs to the next space/tab; backslashes
/// are literal here (no escaping).
/// Split a Windows command line into argv — the inverse of [`join_wide`] and
/// of the real `CommandLineToArgvW` (shell32.dll), mirroring
/// [`crate::quote::posix::split`]'s shape over UTF-16 code units.
///
/// # `argv[0]`
///
/// `argv[0]` is parsed by [`first_token_and_rest_wide`] — see its docs (and
/// [`first_token_wide`]'s) for the exact OS deviation on leading
/// whitespace/empty input and the program-token quoting rule.
///
/// # `argv[1..]`
///
/// Parsed with the full MSVCRT backslash/quote rules `CommandLineToArgvW`
/// applies past the first argument: a run of `n` backslashes immediately
/// before a `"` collapses to `n/2` literal backslashes, and the quote either
/// becomes a literal `"` (`n` odd) or toggles "inside quotes" (`n` even) —
/// this much is documented and is the direct inverse of `append_arg`
/// ([`join_wide`]'s internal encoder). Beyond that, *bare* (non-backslash-
/// escaped) quotes are counted by a running total that persists across the
/// whole token — ordinary characters do not touch it, and neither does a
/// backslash-escaped quote — and is undocumented but not arbitrary: verified
/// against Wine's/ReactOS's `CommandLineToArgvW` source
/// (`dll/win32/shell32/wine/shell32_main.c`), the total resets to 0 in
/// exactly two cases: as soon as it reaches 3 (emitting one literal `"`), or
/// when a maximal run of *consecutive* bare quotes ends while the total sits
/// at 2 (no literal `"` either way). Because the total is not reset by
/// ordinary characters in between, the same two-bare-quote shape means
/// different output depending on what came before: `a""b` -> `ab` (a fresh
/// run of exactly 2 bare quotes — the total goes 0->1->2 and the run ends
/// there, hitting the reset-at-2 case, no literal `"`), but `"a""b"` -> `a"b`
/// (the opening `"` already left the total at 1, so the embedded `""` — part
/// of the same consecutive run as far as the total is concerned — pushes it
/// 1->2->3, hitting the reset-at-3 case instead: one literal `"` is
/// emitted). This differs from the simpler even/odd-only rule the MSVCRT
/// `main()` startup parser uses (reimplemented by `std::env::args()`), which
/// is a different, more limited parser than shell32's actual
/// `CommandLineToArgvW`.
///
/// # Errors
///
/// `CommandLineToArgvW`'s grammar has no error states — an unterminated
/// quote just runs to the end, and a backslash not before a quote is always
/// literal — so this function always returns `Ok`. It still returns
/// `Result<_, QuoteError>` to match [`crate::quote::posix::split`]'s shape;
/// no Windows-specific [`crate::error::QuoteErrorKind`] variant exists.
/// Parse `argv[1..]` from the remainder of a command line, after `argv[0]`
/// and its separating whitespace have already been removed. See
/// [`split_wide`]'s doc comment for the exact rules, including the mod-3
/// bare-quote-run rule. Ported directly from the verified
/// `CommandLineToArgvW` reference algorithm, using eager backslash-writing
/// plus retroactive `Vec::truncate` in place of that algorithm's in-place
/// pointer rewind.