• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2016 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
10 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 //! untrusted.rs: Safe, fast, zero-panic, zero-crashing, zero-allocation
16 //! parsing of untrusted inputs in Rust.
17 //!
18 //! <code>git clone https://github.com/briansmith/untrusted</code>
19 //!
20 //! untrusted.rs goes beyond Rust's normal safety guarantees by  also
21 //! guaranteeing that parsing will be panic-free, as long as
22 //! `untrusted::Input::as_slice_less_safe()` is not used. It avoids copying
23 //! data and heap allocation and strives to prevent common pitfalls such as
24 //! accidentally parsing input bytes multiple times. In order to meet these
25 //! goals, untrusted.rs is limited in functionality such that it works best for
26 //! input languages with a small fixed amount of lookahead such as ASN.1, TLS,
27 //! TCP/IP, and many other networking, IPC, and related protocols. Languages
28 //! that require more lookahead and/or backtracking require some significant
29 //! contortions to parse using this framework. It would not be realistic to use
30 //! it for parsing programming language code, for example.
31 //!
32 //! The overall pattern for using untrusted.rs is:
33 //!
34 //! 1. Write a recursive-descent-style parser for the input language, where the
35 //!    input data is given as a `&mut untrusted::Reader` parameter to each
36 //!    function. Each function should have a return type of `Result<V, E>` for
37 //!    some value type `V` and some error type `E`, either or both of which may
38 //!    be `()`. Functions for parsing the lowest-level language constructs
39 //!    should be defined. Those lowest-level functions will parse their inputs
40 //!    using `::read_byte()`, `Reader::peek()`, and similar functions.
41 //!    Higher-level language constructs are then parsed by calling the
42 //!    lower-level functions in sequence.
43 //!
44 //! 2. Wrap the top-most functions of your recursive-descent parser in
45 //!    functions that take their input data as an `untrusted::Input`. The
46 //!    wrapper functions should call the `Input`'s `read_all` (or a variant
47 //!    thereof) method. The wrapper functions are the only ones that should be
48 //!    exposed outside the parser's module.
49 //!
50 //! 3. After receiving the input data to parse, wrap it in an `untrusted::Input`
51 //!    using `untrusted::Input::from()` as early as possible. Pass the
52 //!    `untrusted::Input` to the wrapper functions when they need to be parsed.
53 //!
54 //! In general parsers built using `untrusted::Reader` do not need to explicitly
55 //! check for end-of-input unless they are parsing optional constructs, because
56 //! `Reader::read_byte()` will return `Err(EndOfInput)` on end-of-input.
57 //! Similarly, parsers using `untrusted::Reader` generally don't need to check
58 //! for extra junk at the end of the input as long as the parser's API uses the
59 //! pattern described above, as `read_all` and its variants automatically check
60 //! for trailing junk. `Reader::skip_to_end()` must be used when any remaining
61 //! unread input should be ignored without triggering an error.
62 //!
63 //! untrusted.rs works best when all processing of the input data is done
64 //! through the `untrusted::Input` and `untrusted::Reader` types. In
65 //! particular, avoid trying to parse input data using functions that take
66 //! byte slices. However, when you need to access a part of the input data as
67 //! a slice to use a function that isn't written using untrusted.rs,
68 //! `Input::as_slice_less_safe()` can be used.
69 //!
70 //! It is recommend to use `use untrusted;` and then `untrusted::Input`,
71 //! `untrusted::Reader`, etc., instead of using `use untrusted::*`. Qualifying
72 //! the names with `untrusted` helps remind the reader of the code that it is
73 //! dealing with *untrusted* input.
74 //!
75 //! # Examples
76 //!
77 //! [*ring*](https://github.com/briansmith/ring)'s parser for the subset of
78 //! ASN.1 DER it needs to understand,
79 //! [`ring::der`](https://github.com/briansmith/ring/blob/master/src/der.rs),
80 //! is built on top of untrusted.rs. *ring* also uses untrusted.rs to parse ECC
81 //! public keys, RSA PKCS#1 1.5 padding, and for all other parsing it does.
82 //!
83 //! All of [webpki](https://github.com/briansmith/webpki)'s parsing of X.509
84 //! certificates (also ASN.1 DER) is done using untrusted.rs.
85 
86 #![doc(html_root_url = "https://briansmith.org/rustdoc/")]
87 // `#[derive(...)]` uses `#[allow(unused_qualifications)]` internally.
88 #![deny(unused_qualifications)]
89 #![forbid(
90     anonymous_parameters,
91     box_pointers,
92     missing_docs,
93     trivial_casts,
94     trivial_numeric_casts,
95     unsafe_code,
96     unstable_features,
97     unused_extern_crates,
98     unused_import_braces,
99     unused_results,
100     variant_size_differences,
101     warnings
102 )]
103 // ANDROID: This lint is included in warnings and thus forbidden, but this version of the library
104 // is not compatible with it.
105 #![allow(rustdoc::bare_urls)]
106 #![no_std]
107 
108 /// A wrapper around `&'a [u8]` that helps in writing panic-free code.
109 ///
110 /// No methods of `Input` will ever panic.
111 #[derive(Clone, Copy, Debug, Eq)]
112 pub struct Input<'a> {
113     value: no_panic::Slice<'a>,
114 }
115 
116 impl<'a> Input<'a> {
117     /// Construct a new `Input` for the given input `bytes`.
from(bytes: &'a [u8]) -> Self118     pub const fn from(bytes: &'a [u8]) -> Self {
119         // This limit is important for avoiding integer overflow. In particular,
120         // `Reader` assumes that an `i + 1 > i` if `input.value.get(i)` does
121         // not return `None`. According to the Rust language reference, the
122         // maximum object size is `core::isize::MAX`, and in practice it is
123         // impossible to create an object of size `core::usize::MAX` or larger.
124         Self {
125             value: no_panic::Slice::new(bytes),
126         }
127     }
128 
129     /// Returns `true` if the input is empty and false otherwise.
130     #[inline]
is_empty(&self) -> bool131     pub fn is_empty(&self) -> bool { self.value.is_empty() }
132 
133     /// Returns the length of the `Input`.
134     #[inline]
len(&self) -> usize135     pub fn len(&self) -> usize { self.value.len() }
136 
137     /// Calls `read` with the given input as a `Reader`, ensuring that `read`
138     /// consumed the entire input. If `read` does not consume the entire input,
139     /// `incomplete_read` is returned.
read_all<F, R, E>(&self, incomplete_read: E, read: F) -> Result<R, E> where F: FnOnce(&mut Reader<'a>) -> Result<R, E>,140     pub fn read_all<F, R, E>(&self, incomplete_read: E, read: F) -> Result<R, E>
141     where
142         F: FnOnce(&mut Reader<'a>) -> Result<R, E>,
143     {
144         let mut input = Reader::new(*self);
145         let result = read(&mut input)?;
146         if input.at_end() {
147             Ok(result)
148         } else {
149             Err(incomplete_read)
150         }
151     }
152 
153     /// Access the input as a slice so it can be processed by functions that
154     /// are not written using the Input/Reader framework.
155     #[inline]
as_slice_less_safe(&self) -> &'a [u8]156     pub fn as_slice_less_safe(&self) -> &'a [u8] { self.value.as_slice_less_safe() }
157 }
158 
159 impl<'a> From<&'a [u8]> for Input<'a> {
160     #[inline]
from(value: &'a [u8]) -> Self161     fn from(value: &'a [u8]) -> Self { Self { value: no_panic::Slice::new(value)} }
162 }
163 
164 // #[derive(PartialEq)] would result in lifetime bounds that are
165 // unnecessarily restrictive; see
166 // https://github.com/rust-lang/rust/issues/26925.
167 impl PartialEq<Input<'_>> for Input<'_> {
168     #[inline]
eq(&self, other: &Input) -> bool169     fn eq(&self, other: &Input) -> bool {
170         self.as_slice_less_safe() == other.as_slice_less_safe()
171     }
172 }
173 
174 impl PartialEq<[u8]> for Input<'_> {
175     #[inline]
eq(&self, other: &[u8]) -> bool176     fn eq(&self, other: &[u8]) -> bool { self.as_slice_less_safe() == other }
177 }
178 
179 impl PartialEq<Input<'_>> for [u8] {
180     #[inline]
eq(&self, other: &Input) -> bool181     fn eq(&self, other: &Input) -> bool { other.as_slice_less_safe() == self }
182 }
183 
184 /// Calls `read` with the given input as a `Reader`, ensuring that `read`
185 /// consumed the entire input. When `input` is `None`, `read` will be
186 /// called with `None`.
read_all_optional<'a, F, R, E>( input: Option<Input<'a>>, incomplete_read: E, read: F, ) -> Result<R, E> where F: FnOnce(Option<&mut Reader<'a>>) -> Result<R, E>,187 pub fn read_all_optional<'a, F, R, E>(
188     input: Option<Input<'a>>, incomplete_read: E, read: F,
189 ) -> Result<R, E>
190 where
191     F: FnOnce(Option<&mut Reader<'a>>) -> Result<R, E>,
192 {
193     match input {
194         Some(input) => {
195             let mut input = Reader::new(input);
196             let result = read(Some(&mut input))?;
197             if input.at_end() {
198                 Ok(result)
199             } else {
200                 Err(incomplete_read)
201             }
202         },
203         None => read(None),
204     }
205 }
206 
207 /// A read-only, forward-only* cursor into the data in an `Input`.
208 ///
209 /// Using `Reader` to parse input helps to ensure that no byte of the input
210 /// will be accidentally processed more than once. Using `Reader` in
211 /// conjunction with `read_all` and `read_all_optional` helps ensure that no
212 /// byte of the input is accidentally left unprocessed. The methods of `Reader`
213 /// never panic, so `Reader` also assists the writing of panic-free code.
214 ///
215 /// \* `Reader` is not strictly forward-only because of the method
216 /// `get_input_between_marks`, which is provided mainly to support calculating
217 /// digests over parsed data.
218 #[derive(Debug)]
219 pub struct Reader<'a> {
220     input: no_panic::Slice<'a>,
221     i: usize,
222 }
223 
224 /// An index into the already-parsed input of a `Reader`.
225 pub struct Mark {
226     i: usize,
227 }
228 
229 impl<'a> Reader<'a> {
230     /// Construct a new Reader for the given input. Use `read_all` or
231     /// `read_all_optional` instead of `Reader::new` whenever possible.
232     #[inline]
new(input: Input<'a>) -> Self233     pub fn new(input: Input<'a>) -> Self {
234         Self {
235             input: input.value,
236             i: 0,
237         }
238     }
239 
240     /// Returns `true` if the reader is at the end of the input, and `false`
241     /// otherwise.
242     #[inline]
at_end(&self) -> bool243     pub fn at_end(&self) -> bool { self.i == self.input.len() }
244 
245     /// Returns an `Input` for already-parsed input that has had its boundaries
246     /// marked using `mark`.
247     #[inline]
get_input_between_marks( &self, mark1: Mark, mark2: Mark, ) -> Result<Input<'a>, EndOfInput>248     pub fn get_input_between_marks(
249         &self, mark1: Mark, mark2: Mark,
250     ) -> Result<Input<'a>, EndOfInput> {
251         self.input
252             .subslice(mark1.i..mark2.i)
253             .map(|subslice| Input { value: subslice })
254             .ok_or(EndOfInput)
255     }
256 
257     /// Return the current position of the `Reader` for future use in a call
258     /// to `get_input_between_marks`.
259     #[inline]
mark(&self) -> Mark260     pub fn mark(&self) -> Mark { Mark { i: self.i } }
261 
262     /// Returns `true` if there is at least one more byte in the input and that
263     /// byte is equal to `b`, and false otherwise.
264     #[inline]
peek(&self, b: u8) -> bool265     pub fn peek(&self, b: u8) -> bool {
266         match self.input.get(self.i) {
267             Some(actual_b) => b == *actual_b,
268             None => false,
269         }
270     }
271 
272     /// Reads the next input byte.
273     ///
274     /// Returns `Ok(b)` where `b` is the next input byte, or `Err(EndOfInput)`
275     /// if the `Reader` is at the end of the input.
276     #[inline]
read_byte(&mut self) -> Result<u8, EndOfInput>277     pub fn read_byte(&mut self) -> Result<u8, EndOfInput> {
278         match self.input.get(self.i) {
279             Some(b) => {
280                 self.i += 1; // safe from overflow; see Input::from().
281                 Ok(*b)
282             },
283             None => Err(EndOfInput),
284         }
285     }
286 
287     /// Skips `num_bytes` of the input, returning the skipped input as an
288     /// `Input`.
289     ///
290     /// Returns `Ok(i)` if there are at least `num_bytes` of input remaining,
291     /// and `Err(EndOfInput)` otherwise.
292     #[inline]
read_bytes(&mut self, num_bytes: usize) -> Result<Input<'a>, EndOfInput>293     pub fn read_bytes(&mut self, num_bytes: usize) -> Result<Input<'a>, EndOfInput> {
294         let new_i = self.i.checked_add(num_bytes).ok_or(EndOfInput)?;
295         let ret = self
296             .input
297             .subslice(self.i..new_i)
298             .map(|subslice| Input { value: subslice })
299             .ok_or(EndOfInput)?;
300         self.i = new_i;
301         Ok(ret)
302     }
303 
304     /// Skips the reader to the end of the input, returning the skipped input
305     /// as an `Input`.
306     #[inline]
read_bytes_to_end(&mut self) -> Input<'a>307     pub fn read_bytes_to_end(&mut self) -> Input<'a> {
308         let to_skip = self.input.len() - self.i;
309         self.read_bytes(to_skip).unwrap()
310     }
311 
312     /// Calls `read()` with the given input as a `Reader`. On success, returns a
313     /// pair `(bytes_read, r)` where `bytes_read` is what `read()` consumed and
314     /// `r` is `read()`'s return value.
read_partial<F, R, E>(&mut self, read: F) -> Result<(Input<'a>, R), E> where F: FnOnce(&mut Reader<'a>) -> Result<R, E>,315     pub fn read_partial<F, R, E>(&mut self, read: F) -> Result<(Input<'a>, R), E>
316     where
317         F: FnOnce(&mut Reader<'a>) -> Result<R, E>,
318     {
319         let start = self.i;
320         let r = read(self)?;
321         let bytes_read = Input {
322             value: self.input.subslice(start..self.i).unwrap()
323         };
324         Ok((bytes_read, r))
325     }
326 
327     /// Skips `num_bytes` of the input.
328     ///
329     /// Returns `Ok(i)` if there are at least `num_bytes` of input remaining,
330     /// and `Err(EndOfInput)` otherwise.
331     #[inline]
skip(&mut self, num_bytes: usize) -> Result<(), EndOfInput>332     pub fn skip(&mut self, num_bytes: usize) -> Result<(), EndOfInput> {
333         self.read_bytes(num_bytes).map(|_| ())
334     }
335 
336     /// Skips the reader to the end of the input.
337     #[inline]
skip_to_end(&mut self) -> ()338     pub fn skip_to_end(&mut self) -> () { let _ = self.read_bytes_to_end(); }
339 }
340 
341 /// The error type used to indicate the end of the input was reached before the
342 /// operation could be completed.
343 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
344 pub struct EndOfInput;
345 
346 mod no_panic {
347     use core;
348 
349     /// A wrapper around a slice that exposes no functions that can panic.
350     #[derive(Clone, Copy, Debug, Eq, PartialEq)]
351     pub struct Slice<'a> {
352         bytes: &'a [u8],
353     }
354 
355     impl<'a> Slice<'a> {
356         #[inline]
new(bytes: &'a [u8]) -> Self357         pub const fn new(bytes: &'a [u8]) -> Self { Self { bytes } }
358 
359         #[inline]
get(&self, i: usize) -> Option<&u8>360         pub fn get(&self, i: usize) -> Option<&u8> { self.bytes.get(i) }
361 
362         #[inline]
subslice(&self, r: core::ops::Range<usize>) -> Option<Self>363         pub fn subslice(&self, r: core::ops::Range<usize>) -> Option<Self> {
364             self.bytes.get(r).map(|bytes| Self { bytes })
365         }
366 
367         #[inline]
is_empty(&self) -> bool368         pub fn is_empty(&self) -> bool { self.bytes.is_empty() }
369 
370         #[inline]
len(&self) -> usize371         pub fn len(&self) -> usize { self.bytes.len() }
372 
373         #[inline]
as_slice_less_safe(&self) -> &'a [u8]374         pub fn as_slice_less_safe(&self) -> &'a [u8] { self.bytes }
375     }
376 
377 } // mod no_panic
378