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
//! SNMP Parser
//!
//! SNMP is defined in the following RFCs:
//!   - [RFC1157](https://tools.ietf.org/html/rfc1157): SNMP v1
//!   - [RFC1902](https://tools.ietf.org/html/rfc1902): SNMP v2 SMI
//!   - [RFC3416](https://tools.ietf.org/html/rfc3416): SNMP v2
//!   - [RFC2570](https://tools.ietf.org/html/rfc2570): Introduction to SNMP v3

use std::{fmt,str};
use std::net::Ipv4Addr;
use std::slice::Iter;
use nom::{IResult,ErrorKind};
use der_parser::*;
use der_parser::oid::Oid;

#[derive(Clone, Copy, Eq, PartialEq)]
pub struct PduType(pub u8);

#[allow(non_upper_case_globals)]
impl PduType {
    pub const GetRequest     : PduType = PduType(0);
    pub const GetNextRequest : PduType = PduType(1);
    pub const Response       : PduType = PduType(2);
    pub const SetRequest     : PduType = PduType(3);
    pub const TrapV1         : PduType = PduType(4); // Obsolete, was the old Trap-PDU in SNMPv1
    pub const GetBulkRequest : PduType = PduType(5);
    pub const InformRequest  : PduType = PduType(6);
    pub const TrapV2         : PduType = PduType(7);
    pub const Report         : PduType = PduType(8);
}

impl fmt::Debug for PduType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
           0 => f.write_str("GetRequest"),
           1 => f.write_str("GetNextRequest"),
           2 => f.write_str("Response"),
           3 => f.write_str("SetRequest"),
           4 => f.write_str("TrapV1"),
           5 => f.write_str("GetBulkRequest"),
           6 => f.write_str("InformRequest"),
           7 => f.write_str("TrapV2"),
           8 => f.write_str("Report"),
           n => f.debug_tuple("PduType").field(&n).finish(),
        }
    }
}

#[derive(Clone, Copy, Eq, PartialEq)]
pub struct TrapType(pub u8);

impl TrapType {
    pub const COLD_START             : TrapType = TrapType(0);
    pub const WARM_START             : TrapType = TrapType(1);
    pub const LINK_DOWN              : TrapType = TrapType(2);
    pub const LINK_UP                : TrapType = TrapType(3);
    pub const AUTHENTICATION_FAILURE : TrapType = TrapType(4);
    pub const EGP_NEIGHBOR_LOSS      : TrapType = TrapType(5);
    pub const ENTERPRISE_SPECIFIC    : TrapType = TrapType(6);
}

impl fmt::Debug for TrapType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
           0 => f.write_str("coldStart"),
           1 => f.write_str("warmStart"),
           2 => f.write_str("linkDown"),
           3 => f.write_str("linkUp"),
           4 => f.write_str("authenticationFailure"),
           5 => f.write_str("egpNeighborLoss"),
           6 => f.write_str("enterpriseSpecific"),
           n => f.debug_tuple("TrapType").field(&n).finish(),
        }
    }
}

/// This CHOICE represents an address from one of possibly several
/// protocol families.  Currently, only one protocol family, the Internet
/// family, is present in this CHOICE.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum NetworkAddress {
    IPv4(Ipv4Addr),
}

/// This application-wide type represents a non-negative integer which
/// monotonically increases until it reaches a maximum value, when it
/// wraps around and starts increasing again from zero.  This memo
/// specifies a maximum value of 2^32-1 (4294967295 decimal) for
/// counters.
pub type Counter = u32;

/// This application-wide type represents a non-negative integer, which
/// may increase or decrease, but which latches at a maximum value.  This
/// memo specifies a maximum value of 2^32-1 (4294967295 decimal) for
/// gauges.
pub type Gauge = u32;

/// This application-wide type represents a non-negative integer which
/// counts the time in hundredths of a second since some epoch.  When
/// object types are defined in the MIB which use this ASN.1 type, the
/// description of the object type identifies the reference epoch.
pub type TimeTicks = u32;

#[derive(Clone, Copy, Eq, PartialEq)]
pub struct ErrorStatus(pub u32);

#[allow(non_upper_case_globals)]
impl ErrorStatus {
    pub const NoError    : ErrorStatus = ErrorStatus(0);
    pub const TooBig     : ErrorStatus = ErrorStatus(1);
    pub const NoSuchName : ErrorStatus = ErrorStatus(2);
    pub const BadValue   : ErrorStatus = ErrorStatus(3);
    pub const ReadOnly   : ErrorStatus = ErrorStatus(4);
    pub const GenErr     : ErrorStatus = ErrorStatus(5);
}

impl fmt::Debug for ErrorStatus {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
           0 => f.write_str("NoError"),
           1 => f.write_str("TooBig"),
           2 => f.write_str("NoSuchName"),
           3 => f.write_str("BadValue"),
           4 => f.write_str("ReadOnly"),
           5 => f.write_str("GenErr"),
           n => f.debug_tuple("ErrorStatus").field(&n).finish(),
        }
    }
}

#[derive(Debug,PartialEq)]
pub struct SnmpGenericPdu<'a> {
    pub pdu_type: PduType,
    pub req_id: u32,
    pub err: ErrorStatus,
    pub err_index: u32,
    pub var: Vec<SnmpVariable<'a>>,
}

#[derive(Debug,PartialEq)]
pub struct SnmpTrapPdu<'a> {
    pub enterprise: Oid,
    pub agent_addr: NetworkAddress,
    pub generic_trap: TrapType,
    pub specific_trap: u32,
    pub timestamp: TimeTicks,
    pub var: Vec<SnmpVariable<'a>>,
}

#[derive(Debug,PartialEq)]
pub enum SnmpPdu<'a> {
    Generic(SnmpGenericPdu<'a>),
    TrapV1(SnmpTrapPdu<'a>),
}

#[derive(Debug,PartialEq)]
pub struct SnmpMessage<'a> {
    pub version: u32,
    pub community: String,
    pub pdu: SnmpPdu<'a>,
}

impl<'a> SnmpGenericPdu<'a> {
    pub fn vars_iter(&'a self) -> Iter<SnmpVariable> {
        self.var.iter()
    }
}

impl<'a> SnmpTrapPdu<'a> {
    pub fn vars_iter(&'a self) -> Iter<SnmpVariable> {
        self.var.iter()
    }
}

impl<'a> SnmpPdu<'a> {
    pub fn pdu_type(&self) -> PduType {
        match *self {
            SnmpPdu::Generic(ref pdu) => pdu.pdu_type,
            SnmpPdu::TrapV1(_)        => PduType::TrapV1,
        }
    }

    pub fn vars_iter(&'a self) -> Iter<SnmpVariable> {
        match *self {
            SnmpPdu::Generic(ref pdu) => pdu.var.iter(),
            SnmpPdu::TrapV1(ref pdu)  => pdu.var.iter(),
        }
    }
}

impl<'a> SnmpMessage<'a> {
    pub fn pdu_type(&self) -> PduType {
        self.pdu.pdu_type()
    }

    pub fn vars_iter(&'a self) -> Iter<SnmpVariable> {
        self.pdu.vars_iter()
    }
}

#[derive(Debug,PartialEq)]
pub struct SnmpVariable<'a> {
    pub oid: Oid,
    pub val: ObjectSyntax<'a>
}

#[derive(Debug,PartialEq)]
pub enum ObjectSyntax<'a> {
    Number(DerObject<'a>),
    String(&'a[u8]),
    Object(Oid),
    Empty,
    Address(NetworkAddress),
    Counter(Counter),
    Gauge(Gauge),
    Ticks(TimeTicks),
    Arbitrary(DerObject<'a>),
}

pub fn parse_der_octetstring_as_slice(i:&[u8]) -> IResult<&[u8],&[u8]> {
    match parse_der_octetstring(i) {
        IResult::Done(rem,ref obj) => {
            match obj.content {
                DerObjectContent::OctetString(s) => {
                    IResult::Done(rem, s)
                }
                _ => IResult::Error(error_code!(ErrorKind::Custom(DER_TAG_ERROR))),
            }
        }
        IResult::Incomplete(i) => IResult::Incomplete(i),
        IResult::Error(e) => IResult::Error(e)
    }
}

fn parse_objectsyntax<'a>(i:&'a[u8]) -> IResult<&'a[u8],ObjectSyntax> {
    match der_read_element_header(i) {
        IResult::Done(rem,hdr) => {
            if hdr.is_application() {
                match hdr.tag {
                    0 => {
                        map_res!(
                            rem,
                            apply!(der_read_element_content_as,DerTag::OctetString as u8, hdr.len as usize),
                            |x:DerObjectContent| {
                                match x {
                                    DerObjectContent::OctetString(s) if s.len() == 4 => {
                                        Ok(ObjectSyntax::Address(NetworkAddress::IPv4(Ipv4Addr::new(s[0],s[1],s[2],s[3]))))
                                    },
                                    _ => Err(DER_TAG_ERROR),
                                }
                            }
                        )
                    },
                    1 ... 3 => {
                        map_res!(
                            rem,
                            apply!(der_read_element_content_as, DerTag::Integer as u8, hdr.len as usize),
                            |x:DerObjectContent| {
                                x.as_u32().map(|x| {
                                    match hdr.tag {
                                        1 => ObjectSyntax::Counter(x),
                                        2 => ObjectSyntax::Gauge(x),
                                        3 => ObjectSyntax::Ticks(x),
                                        _ => unreachable!(),
                                    }
                                })
                            }
                        )
                    },
                    4 => {
                        let r = der_read_element_content_as(rem, DerTag::OctetString as u8, hdr.len as usize);
                        r.map(|x| ObjectSyntax::Arbitrary(DerObject::from_obj(x)))
                    },
                    _ => IResult::Error(error_code!(ErrorKind::Custom(DER_TAG_ERROR))),
                }
            } else {
                        map_res!(
                            rem,
                            apply!(der_read_element_content_as, hdr.tag, hdr.len as usize),
                            |x:DerObjectContent<'a>| {
                                match x {
                                    DerObjectContent::Integer(_)     => Ok(ObjectSyntax::Number(DerObject::from_obj(x))),
                                    DerObjectContent::OctetString(s) => Ok(ObjectSyntax::String(s)),
                                    DerObjectContent::OID(o)         => Ok(ObjectSyntax::Object(o)),
                                    DerObjectContent::Null           => Ok(ObjectSyntax::Empty),
                                    _                                => Err(DER_TAG_ERROR),
                                }
                            }
                        )
            }
        },
        IResult::Incomplete(i) => IResult::Incomplete(i),
        IResult::Error(e)      => IResult::Error(e)
    }
}

#[inline]
fn parse_varbind(i:&[u8]) -> IResult<&[u8],SnmpVariable> {
    parse_der_struct!(
        i,
        TAG DerTag::Sequence,
        oid: map_res!(parse_der_oid, |x:DerObject| x.as_oid_val()) >>
        val: parse_objectsyntax >>
             // eof!() >>
        (
            SnmpVariable{ oid, val }
        )
    ).map(|x| x.1)
}

#[inline]
fn parse_varbind_list(i:&[u8]) -> IResult<&[u8],Vec<SnmpVariable>> {
    parse_der_struct!(
        i,
        TAG DerTag::Sequence,
        l: many0!(parse_varbind) >>
           // eof!() >>
        ( l )
    ).map(|x| x.1)
}

/// <pre>
///  NetworkAddress ::=
///      CHOICE {
///          internet
///              IpAddress
///      }
/// IpAddress ::=
///     [APPLICATION 0]          -- in network-byte order
///         IMPLICIT OCTET STRING (SIZE (4))
/// </pre>
fn parse_networkaddress(i:&[u8]) -> IResult<&[u8],NetworkAddress> {
    match parse_der(i) {
        IResult::Done(rem,obj) => {
            if obj.tag != 0 || obj.class != 0b01 {
                return IResult::Error(error_code!(ErrorKind::Custom(DER_TAG_ERROR)));
            }
            match obj.content {
                DerObjectContent::Unknown(s) if s.len() == 4 => {
                    IResult::Done(rem, NetworkAddress::IPv4(Ipv4Addr::new(s[0],s[1],s[2],s[3])))
                },
                _ => IResult::Error(error_code!(ErrorKind::Custom(DER_TAG_ERROR))),
            }
        },
        IResult::Incomplete(i) => IResult::Incomplete(i),
        IResult::Error(e)      => IResult::Error(e),
    }
}

/// <pre>
/// TimeTicks ::=
///     [APPLICATION 3]
///         IMPLICIT INTEGER (0..4294967295)
/// </pre>
fn parse_timeticks(i:&[u8]) -> IResult<&[u8],TimeTicks> {
    fn der_read_integer_content(i:&[u8], _tag:u8, len: usize) -> IResult<&[u8],DerObjectContent,u32> {
        der_read_element_content_as(i, DerTag::Integer as u8, len)
    }
    map_res!(i, apply!(parse_der_implicit, 3, der_read_integer_content), |x: DerObject| {
        match x.as_context_specific() {
            Ok((_,Some(x))) => x.as_u32(),
            _               => Err(DerError::DerTypeError),
        }
    })
}




fn parse_snmp_v1_generic_pdu(pdu: &[u8], tag:PduType) -> IResult<&[u8],SnmpPdu> {
    do_parse!(pdu,
              req_id:       parse_der_u32 >>
              err:          parse_der_u32 >>
              err_index:    parse_der_u32 >>
                            error_if!(true == false, ErrorKind::Custom(128)) >>
              var_bindings: parse_varbind_list >>
              (
                  SnmpPdu::Generic(
                      SnmpGenericPdu {
                          pdu_type:  tag,
                          req_id,
                          err:       ErrorStatus(err),
                          err_index,
                          var:       var_bindings
                      }
                  )
              ))
}

fn parse_snmp_v1_trap_pdu(pdu: &[u8]) -> IResult<&[u8],SnmpPdu> {
    do_parse!(
        pdu,
        enterprise:    map_res!(parse_der_oid, |x: DerObject| x.as_oid_val()) >>
        agent_addr:    parse_networkaddress >>
        generic_trap:  parse_der_u32 >>
        specific_trap: parse_der_u32 >>
        timestamp:     parse_timeticks >>
        var_bindings:  parse_varbind_list >>
        (
            SnmpPdu::TrapV1(
                SnmpTrapPdu {
                    enterprise,
                    agent_addr,
                    generic_trap:  TrapType(generic_trap as u8),
                    specific_trap,
                    timestamp,
                    var:           var_bindings
                }
            )
        )
    )
}

/// Top-level message
///
/// <pre>
/// Message ::=
///         SEQUENCE {
///             version          -- version-1 for this RFC
///                 INTEGER {
///                     version-1(0)
///                 },
///
///             community        -- community name
///                 OCTET STRING,
///
///             data             -- e.g., PDUs if trivial
///                 ANY          -- authentication is being used
///         }
/// </pre>
pub fn parse_snmp_v1(i:&[u8]) -> IResult<&[u8],SnmpMessage> {
    parse_der_struct!(
        i,
        TAG DerTag::Sequence,
        version:   parse_der_u32 >>
        community: map_res!(
            parse_der_octetstring_as_slice,
            |s| str::from_utf8(s)
        ) >>
        pdu:       parse_snmp_v1_pdu >>
        (
            SnmpMessage{
                version,
                community: community.to_string(),
                pdu
            }
        )
    ).map(|x| x.1)
}

pub fn parse_snmp_v1_pdu(i:&[u8]) -> IResult<&[u8],SnmpPdu> {
    match der_read_element_header(i) {
        IResult::Done(rem,hdr) => {
            match PduType(hdr.tag) {
                PduType::GetRequest |
                PduType::GetNextRequest |
                PduType::Response |
                PduType::SetRequest |
                PduType::Report     => parse_snmp_v1_generic_pdu(rem, PduType(hdr.tag)),
                PduType::TrapV1     => parse_snmp_v1_trap_pdu(rem),
                _                   => IResult::Error(error_code!(ErrorKind::Custom(128))),
                // _                   => { return IResult::Error(error_code!(ErrorKind::Custom(SnmpError::InvalidPdu))); },
            }
        },
        IResult::Incomplete(i) => IResult::Incomplete(i),
        IResult::Error(_)      => IResult::Error(error_code!(ErrorKind::Custom(129))),
        // IResult::Error(_)      => IResult::Error(error_code!(ErrorKind::Custom(SnmpError::InvalidScopedPduData))),
    }
}