Skip to main content

vault_core/
php_config.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! A reader for PHP array literals, enough for application config files such as
4//! Nextcloud's `config/config.php` (Phase 38.1, ADR-0148).
5//!
6//! Nothing here executes anything. The file is *data written in PHP syntax*:
7//! `$CONFIG = array ( 'key' => 'value', ... );`, with the short `[ ... ]` form
8//! accepted too. What is understood is strings (single and double quoted),
9//! integers, floats, `true`/`false`/`null`, nested arrays, and the three comment
10//! styles. Anything else - a function call, a constant, a concatenation, a
11//! variable - cannot be known without running PHP, so its value becomes `null`
12//! and a warning naming the key and line is recorded instead of guessing.
13//!
14//! Every length the file can control is bounded: nesting depth and total node
15//! count, so a hostile file cannot make this recurse or allocate without limit.
16
17use serde_json::{Map, Value};
18
19const MAX_DEPTH: usize = 32;
20const MAX_NODES: usize = 100_000;
21
22/// The parsed array and anything that could not be read.
23#[derive(Debug, PartialEq)]
24pub struct Parsed {
25    pub value: Value,
26    pub warnings: Vec<String>,
27}
28
29/// Parse the array assigned to the first `=` in `src`.
30pub fn parse(src: &str) -> Result<Parsed, String> {
31    parse_inner(src, None)
32}
33
34/// Parse the array assigned to `$name` (for Nextcloud, `CONFIG`). A file that is a
35/// script rather than a config array - one that sets other variables first - is
36/// read from the right assignment instead of the first `=`.
37pub fn parse_var(src: &str, name: &str) -> Result<Parsed, String> {
38    parse_inner(src, Some(name))
39}
40
41fn parse_inner(src: &str, var: Option<&str>) -> Result<Parsed, String> {
42    let mut p = P {
43        s: src.as_bytes(),
44        i: 0,
45        nodes: 0,
46        warnings: Vec::new(),
47    };
48    p.skip_to_array(var)?;
49    let value = p.array(0)?;
50    Ok(Parsed {
51        value,
52        warnings: p.warnings,
53    })
54}
55
56struct P<'a> {
57    s: &'a [u8],
58    i: usize,
59    nodes: usize,
60    warnings: Vec<String>,
61}
62
63impl P<'_> {
64    fn line(&self) -> usize {
65        self.line_at(self.i)
66    }
67
68    /// Computed on demand only: counting newlines is O(n), and doing it per value
69    /// made a large file quadratic.
70    fn line_at(&self, at: usize) -> usize {
71        1 + self.s[..at.min(self.s.len())]
72            .iter()
73            .filter(|&&b| b == b'\n')
74            .count()
75    }
76
77    fn peek(&self) -> Option<u8> {
78        self.s.get(self.i).copied()
79    }
80
81    fn ws(&mut self) {
82        loop {
83            match self.peek() {
84                Some(b' ' | b'\t' | b'\r' | b'\n') => self.i += 1,
85                Some(b'#') => self.line_comment(),
86                Some(b'/') if self.s.get(self.i + 1) == Some(&b'/') => self.line_comment(),
87                Some(b'/') if self.s.get(self.i + 1) == Some(&b'*') => {
88                    self.i += 2;
89                    while self.i < self.s.len()
90                        && !(self.s[self.i] == b'*' && self.s.get(self.i + 1) == Some(&b'/'))
91                    {
92                        self.i += 1;
93                    }
94                    self.i = (self.i + 2).min(self.s.len());
95                }
96                _ => return,
97            }
98        }
99    }
100
101    fn line_comment(&mut self) {
102        while let Some(b) = self.peek() {
103            if b == b'\n' {
104                return;
105            }
106            self.i += 1;
107        }
108    }
109
110    /// Move to the opening of the array that follows the wanted `=`: the first one,
111    /// or the one assigned to `$var`.
112    fn skip_to_array(&mut self, var: Option<&str>) -> Result<(), String> {
113        while self.i < self.s.len() {
114            self.ws();
115            match self.peek() {
116                Some(b'$') if var.is_some() => {
117                    let want = var.unwrap_or("").as_bytes();
118                    let name_end = self.i + 1 + want.len();
119                    let named = self.s.get(self.i + 1..name_end) == Some(want)
120                        && !self
121                            .s
122                            .get(name_end)
123                            .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
124                    self.i += 1;
125                    if named {
126                        self.i = name_end;
127                        self.ws();
128                        if self.peek() == Some(b'=') && self.s.get(self.i + 1) != Some(&b'=') {
129                            self.i += 1;
130                            self.ws();
131                            return Ok(());
132                        }
133                    }
134                }
135                Some(b'=') if var.is_none() => {
136                    self.i += 1;
137                    self.ws();
138                    return Ok(());
139                }
140                Some(b'\'' | b'"') => {
141                    self.string()?;
142                }
143                Some(_) => self.i += 1,
144                None => break,
145            }
146        }
147        Err("No `$CONFIG = array(...)` assignment found".into())
148    }
149
150    fn keyword_ci(&mut self, kw: &str) -> bool {
151        let end = self.i + kw.len();
152        if end <= self.s.len() && self.s[self.i..end].eq_ignore_ascii_case(kw.as_bytes()) {
153            let after = self.s.get(end).copied();
154            if !after.is_some_and(|b| b.is_ascii_alphanumeric() || b == b'_') {
155                self.i = end;
156                return true;
157            }
158        }
159        false
160    }
161
162    fn array(&mut self, depth: usize) -> Result<Value, String> {
163        if depth > MAX_DEPTH {
164            return Err(format!(
165                "Arrays nest deeper than {MAX_DEPTH} (line {})",
166                self.line()
167            ));
168        }
169        self.ws();
170        let close = if self.keyword_ci("array") {
171            self.ws();
172            if self.peek() != Some(b'(') {
173                return Err(format!(
174                    "Expected `(` after `array` on line {}",
175                    self.line()
176                ));
177            }
178            self.i += 1;
179            b')'
180        } else if self.peek() == Some(b'[') {
181            self.i += 1;
182            b']'
183        } else {
184            return Err(format!("Expected an array on line {}", self.line()));
185        };
186
187        let mut items: Vec<(Option<Value>, Value)> = Vec::new();
188        loop {
189            self.ws();
190            match self.peek() {
191                None => return Err("The array is never closed".into()),
192                Some(b) if b == close => {
193                    self.i += 1;
194                    break;
195                }
196                Some(b',') => {
197                    self.i += 1;
198                    continue;
199                }
200                _ => {}
201            }
202            self.nodes += 1;
203            if self.nodes > MAX_NODES {
204                return Err("The file has too many entries to read".into());
205            }
206            let first = self.value(depth, close)?;
207            self.ws();
208            if self.s[self.i..].starts_with(b"=>") {
209                self.i += 2;
210                let v = self.value(depth, close)?;
211                items.push((Some(first), v));
212            } else {
213                items.push((None, first));
214            }
215        }
216
217        // A list when no key was written, or the keys are exactly 0..n.
218        let sequential = items.iter().enumerate().all(|(n, (k, _))| match k {
219            None => true,
220            Some(Value::Number(x)) => x.as_u64() == Some(n as u64),
221            _ => false,
222        });
223        if sequential {
224            return Ok(Value::Array(items.into_iter().map(|(_, v)| v).collect()));
225        }
226        let mut m = Map::new();
227        for (n, (k, v)) in items.into_iter().enumerate() {
228            let key = match k {
229                Some(Value::String(s)) => s,
230                Some(Value::Number(x)) => x.to_string(),
231                Some(_) | None => n.to_string(),
232            };
233            m.insert(key, v);
234        }
235        Ok(Value::Object(m))
236    }
237
238    fn value(&mut self, depth: usize, close: u8) -> Result<Value, String> {
239        self.ws();
240        let start = self.i;
241        let v = match self.peek() {
242            Some(b'\'' | b'"') => Value::String(self.string()?),
243            Some(b'[') => self.array(depth + 1)?,
244            Some(b) if b.is_ascii_digit() || b == b'-' || b == b'+' => self.number(),
245            _ if self.keyword_ci("array") => {
246                self.i -= "array".len();
247                self.array(depth + 1)?
248            }
249            _ if self.keyword_ci("true") => Value::Bool(true),
250            _ if self.keyword_ci("false") => Value::Bool(false),
251            _ if self.keyword_ci("null") => Value::Null,
252            _ => {
253                self.skip_expression(close);
254                self.warnings.push(format!(
255                    "line {}: an expression that needs PHP to evaluate was left out",
256                    self.line_at(start)
257                ));
258                return Ok(Value::Null);
259            }
260        };
261        // A string followed by `.` is a concatenation: its value is not what was read.
262        self.ws();
263        if self.peek() == Some(b'.') {
264            self.skip_expression(close);
265            self.warnings.push(format!(
266                "line {}: a concatenation was left out",
267                self.line_at(start)
268            ));
269            return Ok(Value::Null);
270        }
271        Ok(v)
272    }
273
274    /// Skip to the next `,`, `=>` or closing bracket at this nesting level.
275    fn skip_expression(&mut self, close: u8) {
276        let mut depth = 0usize;
277        while let Some(b) = self.peek() {
278            match b {
279                b'\'' | b'"' => {
280                    let _ = self.string();
281                    continue;
282                }
283                b'(' | b'[' => depth += 1,
284                b')' | b']' if depth > 0 => depth -= 1,
285                b',' if depth == 0 => return,
286                b'=' if depth == 0 && self.s.get(self.i + 1) == Some(&b'>') => return,
287                b if depth == 0 && b == close => return,
288                _ => {}
289            }
290            self.i += 1;
291        }
292    }
293
294    fn number(&mut self) -> Value {
295        let start = self.i;
296        let negative = self.peek() == Some(b'-');
297        if matches!(self.peek(), Some(b'-' | b'+')) {
298            self.i += 1;
299        }
300        // PHP's integer syntax: `0x1A` hex, `0b101` binary, `0o17` and a leading-zero
301        // `0755` octal. Read as decimal, a file mode of 0755 would come out as 755.
302        let radix = match (
303            self.peek(),
304            self.s.get(self.i + 1).map(u8::to_ascii_lowercase),
305        ) {
306            (Some(b'0'), Some(b'x')) => Some(16),
307            (Some(b'0'), Some(b'b')) => Some(2),
308            (Some(b'0'), Some(b'o')) => Some(8),
309            _ => None,
310        };
311        if let Some(radix) = radix {
312            self.i += 2;
313            let digits_from = self.i;
314            while matches!(self.peek(), Some(b) if (b as char).is_digit(radix) || b == b'_') {
315                self.i += 1;
316            }
317            let digits = String::from_utf8_lossy(&self.s[digits_from..self.i]).replace('_', "");
318            return match i64::from_str_radix(&digits, radix) {
319                Ok(n) => Value::from(if negative { -n } else { n }),
320                Err(_) => Value::Null,
321            };
322        }
323        while matches!(self.peek(), Some(b) if b.is_ascii_digit() || b == b'.' || b == b'_') {
324            self.i += 1;
325        }
326        // An exponent may carry its own sign: `2.5E-2`, `1e+6`.
327        if matches!(self.peek(), Some(b'e' | b'E')) {
328            self.i += 1;
329            if matches!(self.peek(), Some(b'-' | b'+')) {
330                self.i += 1;
331            }
332            while matches!(self.peek(), Some(b) if b.is_ascii_digit()) {
333                self.i += 1;
334            }
335        }
336        let text: String = String::from_utf8_lossy(&self.s[start..self.i]).replace('_', "");
337        let unsigned = text.trim_start_matches(['-', '+']);
338        let all_digits = !unsigned.is_empty() && unsigned.bytes().all(|b| b.is_ascii_digit());
339        if all_digits && unsigned.len() > 1 && unsigned.starts_with('0') {
340            return match i64::from_str_radix(unsigned, 8) {
341                Ok(n) => Value::from(if negative { -n } else { n }),
342                Err(_) => Value::Null,
343            };
344        }
345        if let Ok(n) = text.parse::<i64>() {
346            return Value::from(n);
347        }
348        text.parse::<f64>()
349            .ok()
350            .and_then(serde_json::Number::from_f64)
351            .map_or(Value::Null, Value::Number)
352    }
353
354    fn string(&mut self) -> Result<String, String> {
355        let quote = self.s[self.i];
356        let start = self.i;
357        self.i += 1;
358        let mut out: Vec<u8> = Vec::new();
359        loop {
360            let Some(b) = self.peek() else {
361                return Err(format!(
362                    "The string opened on line {} is never closed",
363                    self.line_at(start)
364                ));
365            };
366            self.i += 1;
367            if b == quote {
368                break;
369            }
370            if b != b'\\' {
371                out.push(b);
372                continue;
373            }
374            let Some(e) = self.peek() else {
375                return Err(format!(
376                    "The string opened on line {} is never closed",
377                    self.line_at(start)
378                ));
379            };
380            self.i += 1;
381            if quote == b'\'' {
382                // Single quotes: only `\\` and `\'` are escapes; any other backslash stays.
383                match e {
384                    b'\\' | b'\'' => out.push(e),
385                    _ => {
386                        out.push(b'\\');
387                        out.push(e);
388                    }
389                }
390            } else {
391                match e {
392                    b'n' => out.push(b'\n'),
393                    b't' => out.push(b'\t'),
394                    b'r' => out.push(b'\r'),
395                    b'v' => out.push(0x0b),
396                    b'e' => out.push(0x1b),
397                    b'f' => out.push(0x0c),
398                    b'\\' | b'"' | b'$' => out.push(e),
399                    b'0'..=b'7' => {
400                        let mut n = u32::from(e - b'0');
401                        for _ in 0..2 {
402                            match self.peek() {
403                                Some(d @ b'0'..=b'7') => {
404                                    n = n * 8 + u32::from(d - b'0');
405                                    self.i += 1;
406                                }
407                                _ => break,
408                            }
409                        }
410                        out.push((n & 0xff) as u8);
411                    }
412                    b'x' => {
413                        let mut n = 0u32;
414                        let mut got = 0;
415                        while got < 2 {
416                            match self.peek().and_then(|d| (d as char).to_digit(16)) {
417                                Some(d) => {
418                                    n = n * 16 + d;
419                                    self.i += 1;
420                                    got += 1;
421                                }
422                                None => break,
423                            }
424                        }
425                        if got == 0 {
426                            out.extend_from_slice(b"\\x");
427                        } else {
428                            out.push(n as u8);
429                        }
430                    }
431                    _ => {
432                        out.push(b'\\');
433                        out.push(e);
434                    }
435                }
436            }
437        }
438        // `$name` inside double quotes would be interpolated by PHP; it is kept
439        // literally, and the caller sees a `$` in the value.
440        Ok(String::from_utf8_lossy(&out).into_owned())
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447    use serde_json::json;
448
449    #[test]
450    fn reads_the_shape_nextcloud_writes() {
451        let src = r#"<?php
452$CONFIG = array (
453  'passwordsalt' => 'abc\'def',
454  'secret' => "line\nbreak $x",
455  'trusted_domains' =>
456  array (
457    0 => 'localhost',
458    1 => 'cloud.example.com',
459  ),
460  'dbtype' => 'sqlite3',
461  'version' => '29.0.4.1',
462  'installed' => true,
463  'maintenance' => false,
464  'port' => 3306,
465  'ratio' => 1.5,
466  'objectstore' =>
467  array (
468    'class' => '\\OC\\Files\\ObjectStore\\S3',
469    'arguments' =>
470    array (
471      'bucket' => 'b',
472      'key' => 'AKIA',
473      'secret' => 's3cret',
474    ),
475  ),
476);
477"#;
478        let p = parse(src).unwrap();
479        assert!(p.warnings.is_empty(), "{:?}", p.warnings);
480        assert_eq!(p.value["passwordsalt"], "abc'def");
481        assert_eq!(p.value["secret"], "line\nbreak $x");
482        assert_eq!(
483            p.value["trusted_domains"],
484            json!(["localhost", "cloud.example.com"])
485        );
486        assert_eq!(p.value["installed"], true);
487        assert_eq!(p.value["port"], 3306);
488        assert_eq!(p.value["ratio"], 1.5);
489        assert_eq!(
490            p.value["objectstore"]["class"],
491            "\\OC\\Files\\ObjectStore\\S3"
492        );
493        assert_eq!(p.value["objectstore"]["arguments"]["secret"], "s3cret");
494    }
495
496    #[test]
497    fn short_arrays_comments_and_trailing_commas() {
498        let p = parse("<?php\n// a\n$c = [ # b\n 'a' => 1, /* c */ 'b' => [1, 2,], ];").unwrap();
499        assert_eq!(p.value, json!({"a": 1, "b": [1, 2]}));
500    }
501
502    #[test]
503    fn expressions_that_need_php_are_left_out_and_reported() {
504        let p = parse(
505            "<?php $c = array('a' => getenv('X'), 'b' => 'x' . 'y', 'c' => OC::$ROOT . '/d', 'e' => 'ok');",
506        )
507        .unwrap();
508        assert_eq!(p.value["e"], "ok");
509        assert_eq!(p.value["a"], Value::Null);
510        assert_eq!(p.value["b"], Value::Null);
511        assert_eq!(p.value["c"], Value::Null);
512        assert_eq!(p.warnings.len(), 3, "{:?}", p.warnings);
513    }
514
515    #[test]
516    fn reads_the_named_variable_from_a_script_and_not_the_first_equals() {
517        let src = "<?php\n$use = getenv('X');\nif ($use) {\n  $CONFIG = array('a' => getenv('A') ?: 'd', 'b' => 'ok');\n}";
518        assert!(parse(src).is_err(), "the first `=` is not an array");
519        let p = parse_var(src, "CONFIG").unwrap();
520        assert_eq!(p.value["b"], "ok");
521        assert!(!p.warnings.is_empty());
522        assert!(parse_var("<?php $CONFIGX = [1];", "CONFIG").is_err());
523        assert!(parse_var("<?php $CONFIG == [1];", "CONFIG").is_err());
524    }
525
526    #[test]
527    fn refuses_what_it_cannot_bound_or_close() {
528        assert!(parse("<?php $c = array('a' => 'unterminated);").is_err());
529        assert!(parse("<?php nothing here").is_err());
530        assert!(parse("<?php $c = array('a' => 1").is_err());
531        let deep = format!("<?php $c = {}{}", "[".repeat(200), "]".repeat(200));
532        assert!(parse(&deep).unwrap_err().contains("nest deeper"));
533        let wide = format!("<?php $c = [{}];", "1,".repeat(150_000));
534        assert!(parse(&wide).unwrap_err().contains("too many"));
535    }
536}