Dpkt tutorial #4: As paths from MRT/BGP

Source: Internet
Author: User
Tags dns spoofing
Dpkt tutorial #4: As paths from MRT/BGP

Previusly we looked at creating ICMP echo requests, parsing a pcap file, and doing DNS Spoofing with the dpkt framework. today I will show how to parse the as paths of BGP messages out of MRT routing dumps.

Parsing BGP routing information is fun. however, before projects like routeviews were around und, getting a global view of Internet routing in real-time simply wasn't possible. but thanks to routeviews, we can extract useful routing information from the MRT dumps from a number of providers 'Perspectives.

For our example today, we'll be Parsing Out The as path from bgp update messages within MRT dumps. perhaps you're interested in what or how many as hops are traversed between a source and destination. maybe you're inferring ISP peering relationships based on the asns in the path. or maybe you're trying to identify anomalous as paths that may indicate misconfiguration or malicious activity. whatever the case, we will show how dpkt can make the parsing easy.

The BGP module is by far the most complex and comprehensive of all the dpkt modules weighing in at almost 800 lines. it supports the Protocol format of the core bgp rfc as well as 8 rfcs that extend the BGP protocol. on top of dpkt's BGP module, we also have the pybgpdump library that controls acts away a few of the formalities of iterating through a MRT dump.

Before we begin, we need a sample MRT dump. A sample dump that comes distributed with pybgpdump is available here.

Pybgpdump defines a class called bgpdump that takes a filename as an argument (as can been seen in pybgpdump. PY ). the bgpdump can transparently handle gzip 'ed, bzip 'ed, or uncompressed MRT dumps. an instance of the bgpdump class can be iterated on to step through each MRT record in the dump. if the MRT record is determined to be of the bgp4 type, it will be handed to the user for processing.

For example, a simple snippet to count the number of BGP messages in a MRT dump:

cnt = 0dump = pybgpdump.BGPDump('sample.dump.gz')for mrt_h, bgp_h, bgp_m in dump:    cnt += 1print cnt, 'BGP messages in the MRT dump'

However, for our tutorial, We wowould like to print out the as path for each bgp update message. so instead of incrementing a counter within our for loop, we'll make e our bgp_m object, an instance of the BGP class in dpkt's BGP. py. a bgp instance contains a few miscellaneous attributes (Len, type, etc) and will contain a data attribute which is an instance of the open, update, notification, keepalive, or routerefresh class (depending on the message type ). since pybgpdump will only hand us update messages, we know that bgp_m.data is an instance of the update class.

Update messages in BGP contain NLRI (Network Layer Reachability Information), including routes that are withdrawn or announced. in addition, they contain a wide variety of attributes that specify additional information about the UPDATE message. one of these attributes is the as path, which itself is made up of segments of different types. to actually access the as path information, we have to reach down deep into the bgp_m object:

bgp_m: instance of BGP    .type: type of BGP message    .len: length of BGP message    .update/.data: instance of Update()        .withdrawn: list of withdrawn routes        .announced: list of announced routes        .attributes: list of instances of Attribute            .flags: attribute flags            .type: attribute type            .data/.as_path: instance of ASPath                .segments: list of instances of ASPathSegment                    .type: type of path segment (set, sequence, confed)                    .len: number of ASNs in the segment                    .data/.path: list of ASN integers in the segment

While things may look pretty crazy from that object hierarchy, the code to access the as path is fairly simple:

dump = BGPDump('sample.dump.gz')for mrt_h, bgp_h, bgp_m in dump:    for attr in bgp_m.update.attributes:        if attr.type == bgp.AS_PATH:            print path_to_str(attr.as_path)            break

We simply loop through the attributes of the update message until we find the as path attribute. however, as seen in the object hierarchy, ATTR. as_path is still a list of segments that needs to be decoded. we use the path_to_str () function to pretty-print this list of segments in the standard as path form that identifies sets, sequences, and confederations:

DELIMS = ( ('', ''),           ('{', '}'),  # AS_SET           ('', ''),    # AS_SEQUENCE           ('(', ')'),  # AS_CONFED_SEQUENCE           ('[', ']') ) # AS_CONFED_SETdef path_to_str(path):    str = ''    for seg in path.segments:        str += DELIMS[seg.type][0]        for AS in seg.path:            str += '%d ' % (AS)        str = str[:-1]        str += DELIMS[seg.type][1] + ' '    return str

Finally putting it all together, we can successfully extract the as paths from bgp update messages within a MRT table dump in only a few lines of code:

jonojono@dionysus ~/pybgpdump/samples $ python aspath.py3333 1103 3549 47553333 286 6762 175573333 1103 3549 8866 391633333 1103 3549 6762 17557...
the full script code as follow:
#!/usr/bin/env pythonfrom optparse import OptionParserfrom dpkt import bgpfrom pybgpdump import BGPDumpDELIMS = ( ('', ''),           ('{', '}'),  # AS_SET           ('', ''),    # AS_SEQUENCE           ('(', ')'),  # AS_CONFED_SEQUENCE           ('[', ']') ) # AS_CONFED_SETdef path_to_str(path):    str = ''    for seg in path.segments:        str += DELIMS[seg.type][0]        for AS in seg.path:            str += '%d ' % (AS)        str = str[:-1]        str += DELIMS[seg.type][1] + ' '    return strdef main():    parser = OptionParser()    parser.add_option('-i', '--input', dest='input', default='sample.dump.gz',                      help='read input from FILE', metavar='FILE')    (options, args) = parser.parse_args()    dump = BGPDump(options.input)    for mrt_h, bgp_h, bgp_m in dump:        path = ''        for attr in bgp_m.update.attributes:            if attr.type == bgp.AS_PATH:                print path_to_str(attr.as_path)                breakif __name__ == '__main__':    main()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.