onc-rpc 0.3.3

Open Network Computing / Sun RPC types and fast serialisation
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::{
    io::{Cursor, Write},
    iter::FromIterator,
    ops::Deref,
};

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

use crate::{Error, Opaque};

const MAX_GIDS: usize = 16;
const MAX_MACHINE_NAME_LEN: u32 = 255;

/// A variable length array of GID values with a maximum capacity of
/// [`MAX_GIDS`].
#[derive(Clone, PartialEq, Default)]
struct Gids {
    /// The GID values container.
    values: [u32; MAX_GIDS],

    /// 1-indexed length (number of elements) in `values`.
    len: u8,
}

impl Deref for Gids {
    type Target = [u32];

    fn deref(&self) -> &Self::Target {
        &self.values[..self.len as usize]
    }
}

impl std::fmt::Debug for Gids {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.deref().fmt(f)
    }
}

impl FromIterator<u32> for Gids {
    fn from_iter<T: IntoIterator<Item = u32>>(iter: T) -> Self {
        let mut values = [0; MAX_GIDS];
        let mut len = 0;

        // Populate up to MAX_GIDS number of elements
        for v in iter.into_iter() {
            // Never silently drop extra values.
            assert!(len < MAX_GIDS);

            values[len] = v;
            len += 1;
        }

        Self {
            values,
            len: len as u8,
        }
    }
}

/// `AuthUnixParams` represents the structures referred to as both `AUTH_UNIX`
/// and `AUTH_SYS` in the various RFCs, used to identify the client as a Unix
/// user.
///
/// The structure is implemented as specified in `APPENDIX A` of
/// [RFC1831](https://tools.ietf.org/html/rfc1831).
///
/// The client-provided machine name is limited to, at most, 255 bytes. If
/// additional group IDs ([`AuthUnixParams::gids()`]) are provided, the protocol
/// allows for at most 16 values.
///
/// These values are trivial to forge and provide no actual security.
#[derive(Debug, PartialEq, Clone)]
pub struct AuthUnixParams<T>
where
    T: AsRef<[u8]>,
{
    stamp: u32,
    machine_name: Opaque<T>,
    uid: u32,
    gid: u32,
    gids: Gids,
}

impl<'a> AuthUnixParams<&'a [u8]> {
    /// Constructs a new `AuthUnixParams` by parsing the wire format read from
    /// `r`, validating it has read exactly `expected_len` number of bytes.
    ///
    /// `from_cursor` advances the position of `r` to the end of the `AUTH_UNIX`
    /// structure.
    pub(crate) fn from_cursor(r: &mut Cursor<&'a [u8]>, expected_len: u32) -> Result<Self, Error> {
        // Get the start length the parser can validate it read the expected
        // amount of data at the end of the function
        let start_pos = r.position();

        // Read the stamp
        let stamp = r.read_u32::<BigEndian>()?;

        // Read the string without copying
        let machine_name = Opaque::from_wire(&mut *r, MAX_MACHINE_NAME_LEN as _)?;

        // UID & GID
        let uid = r.read_u32::<BigEndian>()?;
        let gid = r.read_u32::<BigEndian>()?;

        // Gids
        let gids_count = r.read_u32::<BigEndian>()? as usize;
        let gids = match gids_count {
            0 => Gids::default(),
            c if c <= 16 => (0..c)
                .map(|_| r.read_u32::<BigEndian>())
                .collect::<Result<Gids, _>>()?,
            _ => return Err(Error::InvalidAuthData),
        };

        // Validate the parser read the expected amount of data to construct
        // this type
        if (r.position() - start_pos) != expected_len as u64 {
            return Err(Error::InvalidAuthData);
        }

        Ok(AuthUnixParams {
            stamp,
            machine_name,
            uid,
            gid,
            gids,
        })
    }
}

impl<T> AuthUnixParams<T>
where
    T: AsRef<[u8]>,
{
    /// Initialise a new `AuthUnixParams` instance containing the specified unix
    /// account identifiers.
    ///
    /// # Panics
    ///
    /// Panics if the machine name exceeds 255 bytes, or `gids` contains more
    /// than 16 elements.
    pub fn new(
        stamp: u32,
        machine_name: T,
        uid: u32,
        gid: u32,
        gids: impl IntoIterator<Item = u32>,
    ) -> Self {
        assert!(machine_name.as_ref().len() <= MAX_MACHINE_NAME_LEN as usize);

        Self {
            stamp,
            machine_name: Opaque::from_user_payload(machine_name),
            uid,
            gid,
            gids: gids.into_iter().collect::<Gids>(),
        }
    }

    /// Serialises this `AuthUnixParams` into `buf`, advancing the cursor
    /// position by [`AuthUnixParams::serialised_len()`] bytes.
    pub fn serialise_into<W: Write>(&self, mut buf: W) -> Result<(), std::io::Error> {
        buf.write_u32::<BigEndian>(self.stamp)?;
        self.machine_name.serialise_into(&mut buf)?;
        buf.write_u32::<BigEndian>(self.uid)?;
        buf.write_u32::<BigEndian>(self.gid)?;

        // Gids array length prefix
        buf.write_u32::<BigEndian>(self.gids.deref().len() as u32)?;

        // Gids values
        for g in &*self.gids {
            buf.write_u32::<BigEndian>(*g)?;
        }
        Ok(())
    }

    /// An arbitrary ID generated by the caller.
    pub fn stamp(&self) -> u32 {
        self.stamp
    }

    /// The hostname of the caller's machine.
    pub fn machine_name(&self) -> &[u8] {
        self.machine_name.as_ref()
    }

    /// The hostname of the caller's machine as a reference to a UTF8 string.
    ///
    /// # Panics
    ///
    /// If the machine name cannot be expressed as a valid UTF8 string, this
    /// method panics.
    pub fn machine_name_str(&self) -> &str {
        std::str::from_utf8(self.machine_name.as_ref()).unwrap()
    }

    /// The caller's Unix user ID.
    pub fn uid(&self) -> u32 {
        self.uid
    }

    /// The caller's primary Unix group ID.
    pub fn gid(&self) -> u32 {
        self.gid
    }

    /// Returns a copy of the `gids` array, a set of Unix group IDs the caller
    /// is a member of.
    pub fn gids(&self) -> Option<&[u32]> {
        if self.gids.len == 0 {
            return None;
        }
        Some(&*self.gids)
    }

    /// Returns the on-wire length of this message once serialised, including
    /// the message header.
    pub fn serialised_len(&self) -> u32 {
        // uid, gid, stamp
        let mut l = std::mem::size_of::<u32>() * 3;

        // machine_name length
        l += self.machine_name.serialised_len() as usize;

        // gids length prefix u32 + values
        l += (self.gids.deref().len() + 1) * std::mem::size_of::<u32>();

        l as u32
    }

    /// Returns the byte sizes of the fields within this data (excluding
    /// serialisation overhead).
    pub(crate) fn associated_data_len(&self) -> u32 {
        // uid, gid, stamp
        let mut l = std::mem::size_of::<u32>() * 3;

        // machine_name without length prefix
        l += self.machine_name.len();

        // gids without length prefix
        l += std::mem::size_of_val(self.gids.deref());

        l as u32
    }
}

#[cfg(feature = "bytes")]
impl TryFrom<crate::Bytes> for AuthUnixParams<crate::Bytes> {
    type Error = Error;

    fn try_from(mut v: crate::Bytes) -> Result<Self, Self::Error> {
        use crate::bytes_ext::BytesReaderExt;

        let stamp = v.try_u32()?;

        let name = v.try_array(MAX_MACHINE_NAME_LEN as _)?;
        let uid = v.try_u32()?;
        let gid = v.try_u32()?;

        let gids_count = v.try_u32()? as usize;
        let gids = match gids_count {
            0 => Gids::default(),
            c if c <= 16 => (0..c).map(|_| v.try_u32()).collect::<Result<Gids, _>>()?,
            _ => return Err(Error::InvalidAuthData),
        };

        Ok(Self {
            stamp,
            machine_name: Opaque::from_user_payload(name),
            uid,
            gid,
            gids,
        })
    }
}

#[cfg(test)]
mod tests {
    use hex_literal::hex;

    #[cfg(feature = "bytes")]
    use crate::Bytes;

    use super::*;

    #[test]
    fn test_serialise_deserialise() {
        let gids = [
            501, 12, 20, 61, 79, 80, 81, 98, 701, 33, 100, 204, 250, 395, 398, 399,
        ];
        let params = AuthUnixParams::new(0, b"".as_ref(), 501, 20, gids);

        let mut buf = Cursor::new(Vec::new());
        params
            .serialise_into(&mut buf)
            .expect("failed to serialise");

        #[rustfmt::skip]
        // Known good wire value trimmed of flavor + length bytes.
        //
        // Credentials
        //     Flavor: AUTH_UNIX (1)
        //     Length: 84
        //     Stamp: 0x00000000
        //     Machine Name: <EMPTY>
        //         length: 0
        //         contents: <EMPTY>
        //     UID: 501
        //     GID: 20
        //     Auxiliary GIDs (16) [501, 12, 20, 61, 79, 80, 81, 98, 701, 33, 100, 204, 250, 395, 398, 399]
        //         GID: 501
        //         GID: 12
        //         GID: 20
        //         GID: 61
        //         GID: 79
        //         GID: 80
        //         GID: 81
        //         GID: 98
        //         GID: 701
        //         GID: 33
        //         GID: 100
        //         GID: 204
        //         GID: 250
        //         GID: 395
        //         GID: 398
        //         GID: 399
        //
        let want = hex!(
            "0000000000000000000001f50000001400000010000001f50000000c0000001400
            00003d0000004f000000500000005100000062000002bd000000210000006400000
            0cc000000fa0000018b0000018e0000018f"
        );

        let buf = buf.into_inner();
        assert_eq!(want.len(), buf.len());
        assert_eq!(want.as_ref(), buf.as_slice());

        let mut c = Cursor::new(want.as_ref());
        let s = AuthUnixParams::from_cursor(&mut c, 84).expect("deserialise failed");

        assert_eq!(s.serialised_len(), 84);
        assert_eq!(params, s);
    }

    #[test]
    fn test_empty() {
        // Known good wire value trimmed of flavor + length bytes.
        //
        // Credentials
        //     Flavor: AUTH_UNIX (1)
        //     Length: 24
        //     Stamp: 0x00000000
        //     Machine Name: <EMPTY>
        //         length: 0
        //         contents: <EMPTY>
        //     UID: 0
        //     GID: 0
        //     Auxiliary GIDs (1) [0]
        //         GID: 0
        let want = hex!("000000000000000000000000000000000000000100000000");
        let mut c = Cursor::new(want.as_ref());

        let s = AuthUnixParams::from_cursor(&mut c, 24).expect("deserialise failed");

        assert_eq!(s.stamp(), 0);
        assert_eq!(s.machine_name_str(), "");
        assert_eq!(s.uid(), 0);
        assert_eq!(s.gid(), 0);
        assert_eq!(s.gids(), Some([0].as_slice()));
        assert_eq!(s.serialised_len(), 24);

        let mut buf = Cursor::new(Vec::new());
        s.serialise_into(&mut buf).expect("failed to serialise");

        let buf = buf.into_inner();
        assert_eq!(want.len(), buf.len());
        assert_eq!(want.as_ref(), buf.as_slice());
    }

    #[test]
    #[cfg(feature = "bytes")]
    fn test_deserialise_bytes() {
        #[rustfmt::skip]
        // Known good wire value trimmed of flavor + length bytes.
        //
        // Credentials
        //     Flavor: AUTH_UNIX (1)
        //     Length: 84
        //     Stamp: 0x00000000
        //     Machine Name: <EMPTY>
        //         length: 0
        //         contents: <EMPTY>
        //     UID: 501
        //     GID: 20
        //     Auxiliary GIDs (16) [501, 12, 20, 61, 79, 80, 81, 98, 701, 33, 100, 204, 250, 395, 398, 399]
        //         GID: 501
        //         GID: 12
        //         GID: 20
        //         GID: 61
        //         GID: 79
        //         GID: 80
        //         GID: 81
        //         GID: 98
        //         GID: 701
        //         GID: 33
        //         GID: 100
        //         GID: 204
        //         GID: 250
        //         GID: 395
        //         GID: 398
        //         GID: 399
        //
        let want = hex!(
            "0000000000000000000001f50000001400000010000001f50000000c0000001400
            00003d0000004f000000500000005100000062000002bd000000210000006400000
            0cc000000fa0000018b0000018e0000018f"
        );
        let static_want: &'static [u8] = Box::leak(Box::new(want));

        let got =
            AuthUnixParams::try_from(Bytes::from(static_want)).expect("failed to deserialise");

        assert_eq!(got.stamp(), 0);
        assert_eq!(got.machine_name_str(), "");
        assert_eq!(got.uid(), 501);
        assert_eq!(got.gid(), 20);
        assert_eq!(
            got.gids(),
            Some(
                [501, 12, 20, 61, 79, 80, 81, 98, 701, 33, 100, 204, 250, 395, 398, 399].as_slice()
            )
        );
        assert_eq!(got.serialised_len(), 84);
    }

    #[test]
    #[cfg(feature = "bytes")]
    fn test_empty_bytes() {
        // Known good wire value trimmed of flavor + length bytes.
        //
        // Credentials
        //     Flavor: AUTH_UNIX (1)
        //     Length: 24
        //     Stamp: 0x00000000
        //     Machine Name: <EMPTY>
        //         length: 0
        //         contents: <EMPTY>
        //     UID: 0
        //     GID: 0
        //     Auxiliary GIDs (1) [0]
        //         GID: 0
        let want = hex!("000000000000000000000000000000000000000100000000");
        let static_want: &'static [u8] = Box::leak(Box::new(want));

        let s = AuthUnixParams::try_from(Bytes::from(static_want)).expect("deserialise failed");

        assert_eq!(s.stamp(), 0);
        assert_eq!(s.machine_name_str(), "");
        assert_eq!(s.uid(), 0);
        assert_eq!(s.gid(), 0);
        assert_eq!(s.gids(), Some([0].as_slice()));
        assert_eq!(s.serialised_len(), 24);

        let mut buf = Cursor::new(Vec::new());
        s.serialise_into(&mut buf).expect("failed to serialise");

        let buf = buf.into_inner();
        assert_eq!(want.len(), buf.len());
        assert_eq!(want.as_ref(), buf.as_slice());
    }

    #[test]
    fn test_max_machine_name() {
        AuthUnixParams::new(42, [1_u8; 255], 42, 42, None);
    }

    #[test]
    #[should_panic]
    fn test_long_machine_name_panic() {
        AuthUnixParams::new(42, [1_u8; 256], 42, 42, None);
    }

    #[test]
    #[should_panic]
    fn test_long_gids_panic() {
        AuthUnixParams::new(
            42,
            Opaque::from_user_payload([].as_slice()),
            42,
            42,
            [
                1_u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
            ],
        );
    }
}