Thursday, 29 April 2021

Cisco Switch MAC Address Flapping Alerts

MAC address table instability can impact a switch's performance & on lower end switches cause high CPU utilisation that may impact other functions. Cisco switches can generate a syslog entry when they see a MAC address flap between ports, but it’s not enabled by default. Some NX-OS platforms actually temporarily disable MAC address table updates if a certain number of MAC address flaps occur within a set timeframe: https://www.cisco.com/c/en/us/support/docs/ios-nx-os-software/nx-os-software/213906-nexus-9000-mac-move-troubleshooting-and.html
The different switch platforms generate slightly different syslog messages, but the common factor is they all have MAC_MOVE in the text for NX-OS, or MACFLAP or HOSTFLAP for IOS / IOS XE. So I created an alert in Splunk to match these keywords in the last hour's log entries.

Commands

IOS / IOX XE:
mac address table notification mac-move

N3K:
mac address table notification mac-move
logging level fwm 6
logging monitor 6


N4K:
mac address table notification mac-move
logging level fwm 6
logging monitor 6


N5K / N6K:
mac address table notification mac-move
logging level fwm 6
logging monitor 6


N7K / N9K:
logging level l2fm 5

Monday, 22 February 2021

Parsing Cisco Extended ACLs in Python

A little toy project to entertain myself, as kept being asked to document & explain the ACLs on some perimeter routers. Takes the output of show access-list & does an incomplete parse of the extended ACL, then outputs it in semi-human readable or plain English form. I say an incomplete parse as only implemented enough syntax to parse the ACLs I was being asked about (e.g. IPv4 only). Some tinkering with the core regex & if/elif statements would make it parse a more complete extended ACL syntax.

Usage: ACL_parser.py [filename] [translate]
Where 'translate' is optional argument to display the ACL lines in English also.


Example ACL:

Extended IP access list MyACL
    10 permit tcp host 21.35.80.22 eq telnet host 21.23.77.101
    20 permit tcp 21.35.80.0 0.0.0.255 eq 16100 21.23.77.0 0.0.0.255 range 8192 8921 (149407 matches)
    30 permit udp 21.35.80.0 0.0.0.3 lt 17600 host 21.23.77.101 eq www (80592 matches)
    40 permit tcp host 21.35.80.27 eq 10701 host 21.23.77.101 established (26008 matches)
    50 permit udp host 21.35.80.22 neq telnet 21.23.77.128 0.0.0.127 gt 1023
    60 permit tcp host 21.35.80.25 eq 16100 host 21.23.77.101 range 8192 8921 (149407 matches)
    70 permit udp 21.35.80.0 0.0.0.127 lt 17600 21.23.77.128 0.0.0.127 (80592 matches)
    75 permit icmp any 192.168.0.0 0.0.0.255 echo log
    80 deny ip any any log (1 match)


Example output from above ACL:

python ACL_parser.py test_acl.txt translate


10 permit tcp host 21.35.80.22 eq 23 host 21.23.77.101
line 10 permit tcp connections from IP address 21.35.80.22 where port equals 23, to IP address 21.23.77.101

20 permit tcp 21.35.80.0/24 eq 16100 21.23.77.0/24 range 8192 8921
line 20 permit tcp connections from IP addresses 21.35.80.0 - 21.35.80.255 where port equals 16100, to IP addresses 21.23.77.0 - 21.23.77.255 where port between 8192 - 8921

30 permit udp 21.35.80.0/30 lt 17600 host 21.23.77.101 eq 80
line 30 permit udp connections from IP addresses 21.35.80.0 - 21.35.80.3 where port less than 17600, to IP address 21.23.77.101 where port equals 80

40 permit tcp host 21.35.80.27 eq 10701 host 21.23.77.101 established
line 40 permit tcp connections from IP address 21.35.80.27 where port equals 10701, to IP address 21.23.77.101 if the connection is already established

50 permit udp host 21.35.80.22 neq 23 21.23.77.128/25 gt 1023
line 50 permit udp connections from IP address 21.35.80.22 where port doesn't equal 23, to IP addresses 21.23.77.128 - 21.23.77.255 where port greater than 1023

60 permit tcp host 21.35.80.25 eq 16100 host 21.23.77.101 range 8192 8921
line 60 permit tcp connections from IP address 21.35.80.25 where port equals 16100, to IP address 21.23.77.101 where port between 8192 - 8921

70 permit udp 21.35.80.0/25 lt 17600 21.23.77.128/25
line 70 permit udp connections from IP addresses 21.35.80.0 - 21.35.80.127 where port less than 17600, to IP addresses 21.23.77.128 - 21.23.77.255

75 permit icmp any 192.168.0.0/24 echo log
line 75 permit icmp connections from IP address any, to IP addresses 192.168.0.0 - 192.168.0.255 for ICMP echo, and log

80 deny ip any any log
line 80 deny ip connections from IP address any, to IP address any, and log

 

Source Code

#!/usr/bin/env python3

import re
import ipaddress
import sys

"""
Written by Chris Perkins in 2021
Licence: BSD 3-Clause

Parse Cisco extended ACL output from show access-list command & display in a human readable format
"""

# Subnet / wildcard mask to CIDR prefix length lookup table
SUBNET_MASKS = {
    "128.0.0.0": "1",
    "127.255.255.255": "1",
    "192.0.0.0": "2",
    "63.255.255.255": "2",
    "224.0.0.0": "3",
    "31.255.255.255": "3",
    "240.0.0.0": "4",
    "15.255.255.255": "4",
    "248.0.0.0": "5",
    "7.255.255.255": "5",
    "252.0.0.0": "6",
    "3.255.255.255": "6",
    "254.0.0.0": "7",
    "1.255.255.255": "7",
    "255.0.0.0": "8",
    "0.255.255.255": "8",
    "255.128.0.0": "9",
    "0.127.255.255": "9",
    "255.192.0.0": "10",
    "0.63.255.255": "10",
    "255.224.0.0": "11",
    "0.31.255.255": "11",
    "255.240.0.0": "12",
    "0.15.255.255": "12",
    "255.248.0.0": "13",
    "0.7.255.255": "13",
    "255.252.0.0": "14",
    "0.3.255.255": "14",
    "255.254.0.0": "15",
    "0.1.255.255": "15",
    "255.255.0.0": "16",
    "0.0.255.255": "16",
    "255.255.128.0": "17",
    "0.0.0.127.255": "17",
    "255.255.192.0": "18",
    "0.0.63.255": "18",
    "255.255.224.0": "19",
    "0.0.31.255": "19",
    "255.255.240.0": "20",
    "0.0.15.255": "20",
    "255.255.248.0": "21",
    "0.0.7.255": "21",
    "255.255.252.0": "22",
    "0.0.3.255": "22",
    "255.255.254.0": "23",
    "0.0.1.255": "23",
    "255.255.255.0": "24",
    "0.0.0.255": "24",
    "255.255.255.128": "25",
    "0.0.0.127": "25",
    "255.255.255.192": "26",
    "0.0.0.63": "26",
    "255.255.255.224": "27",
    "0.0.0.31": "27",
    "255.255.255.240": "28",
    "0.0.0.15": "28",
    "255.255.255.248": "29",
    "0.0.0.7": "29",
    "255.255.255.252": "30",
    "0.0.0.3": "30",
    "255.255.255.254": "31",
    "0.0.0.1": "31",
    "255.255.255.255": "32",
    "0.0.0.0": "32",
}

# Port names to port numbers lookup table
PORT_NAMES = {
    "aol": "5190",
    "bgp": "179",
    "biff": "512",
    "bootpc": "68",
    "bootps": "67",
    "chargen": "19",
    "cifs": "3020",
    "citrix-ica": "1494",
    "cmd": "514",
    "ctiqbe": "2748",
    "daytime": "13",
    "discard": "9",
    "dnsix": "195",
    "domain": "53",
    "echo": "7",
    "exec": "512",
    "finger": "79",
    "ftp": "21",
    "ftp-data": "20",
    "gopher": "70",
    "h323": "1720",
    "hostname": "101",
    "http": "80",
    "https": "443",
    "ident": "113",
    "imap4": "143",
    "irc": "194",
    "isakmp": "500",
    "kerberos": "750",
    "klogin": "543",
    "kshell": "544",
    "ldap": "389",
    "ldaps": "636",
    "login": "513",
    "lotusnotes": "1352",
    "lpd": "515",
    "mobile-ip": "434",
    "nameserver": "42",
    "netbios-dgm": "138",
    "netbios-ns": "137",
    "netbios-ssn": "139",
    "nfs": "2049",
    "nntp": "119",
    "ntp": "123",
    "pcanywhere-data": "5631",
    "pcanywhere-status": "5632",
    "pim-auto-rp": "496",
    "pop2": "109",
    "pop3": "110",
    "pptp": "1723",
    "radius": "1645",
    "radius-acct": "1646",
    "rip": "520",
    "rsh": "514",
    "rtsp": "554",
    "secureid-udp": "5510",
    "sip": "5060",
    "smtp": "25",
    "snmp": "161",
    "snmptrap": "162",
    "sqlnet": "1521",
    "ssh": "22",
    "sunrpc": "111",
    "syslog": "514",
    "tacacs": "49",
    "talk": "517",
    "telnet": "23",
    "tftp": "69",
    "time": "37",
    "uucp": "540",
    "vxlan": "4789",
    "who": "513",
    "whois": "43",
    "www": "80",
    "xdmcp": "177",
}

# ACL operator names lookup table
OPERATOR_NAMES = {
    "eq": "equals",
    "neq": "doesn't equal",
    "lt": "less than",
    "gt": "greater than",
    "range": "between",
}


def main():
    """Parse ACL from text file"""
    mansplain = False
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} [filename] [translate]")
        print(
            "Where 'translate' is optional argument to display the ACL lines in English also."
        )
        sys.exit(1)
    elif len(sys.argv) == 3:
        if sys.argv[2].lower() == "translate":
            mansplain = True

    try:
        with open(sys.argv[1]) as f:
            acl_string = f.read()
    except FileNotFoundError:
        print(f"Unable to open {sys.argv[1]}")
        sys.exit(1)

    for line in acl_string.splitlines():
        acl_parts = re.search(
            r"^\s*(\d+)\s+(permit|deny)\s(\w+)\s(\d+\.\d+\.\d+\.\d+|any|host)\s*(\d+\.\d+\.\d+\.\d+)?"
            r"\s*(eq|neq|lt|gt|range)?\s*([\w\-]+|[\w\-]+\s[\w\-]+)?\s*(established|echo|echo\-reply)?\s(\d+\.\d+\.\d+\.\d+|any|host)"
            r"\s*(\d+\.\d+\.\d+\.\d+)?\s*(eq|neq|lt|gt|range)?\s*([\w\-]+|[\w\-]+\s[\w\-]+)?\s*(established|echo|echo\-reply)?"
            r"\s*(log\-input|log)?\s*(\(\d+ match(es)?\))?$",
            line.lower(),
        )
        ace_dict = {
            "line_num": "",
            "action": "",
            "protocol": "",
            "source_network": "",
            "source_operator": "",
            "source_ports": "",
            "source_modifier": "",
            "destination_network": "",
            "destination_operator": "",
            "destination_ports": "",
            "destination_modifier": "",
            "optional_action": "",
        }

        if not acl_parts:
            continue

        # Parse the Access Control Entry items into a dictionary
        for item in acl_parts.groups():
            item = item if item is not None else ""
            if not ace_dict["line_num"] and re.search(r"^\d+", item):
                ace_dict["line_num"] = item
            elif not ace_dict["action"] and item in ["permit", "deny"]:
                ace_dict["action"] = item
            elif not ace_dict["protocol"] and item in [
                "ahp",
                "esp",
                "eigrp",
                "gre",
                "icmp",
                "igmp",
                "igrp",
                "ip",
                "ipv4",
                "ipinip",
                "nos",
                "ospf",
                "pim",
                "pcp",
                "tcp",
                "udp",
            ]:
                ace_dict["protocol"] = item
            elif not ace_dict["source_network"] and re.search(
                r"\d+\.\d+\.\d+\.\d+|any|host", item
            ):
                ace_dict["source_network"] = item
            elif (
                ace_dict["source_network"]
                and not ace_dict["destination_network"]
                and item in SUBNET_MASKS
            ):
                ace_dict["source_network"] += f"/{SUBNET_MASKS[item]}"
            elif (
                ace_dict["source_network"]
                and ace_dict["source_network"] == "host"
                and not ace_dict["destination_network"]
                and re.search(r"\d+\.\d+\.\d+\.\d+", item)
            ):
                ace_dict["source_network"] += f" {item}"
            elif (
                ace_dict["source_network"]
                and not ace_dict["destination_network"]
                and item in OPERATOR_NAMES
            ):
                ace_dict["source_operator"] = item
            elif (
                ace_dict["source_operator"]
                and not ace_dict["source_ports"]
                and re.search(r"\w+|\w+\s\w+", item)
            ):
                for port_number in item.split():
                    if port_number in PORT_NAMES:
                        ace_dict["source_ports"] += f" {PORT_NAMES[port_number]}"
                    else:
                        ace_dict["source_ports"] += f" {port_number}"
                ace_dict["source_ports"] = ace_dict["source_ports"].strip()
            elif (
                ace_dict["source_network"]
                and not ace_dict["destination_network"]
                and item in ["established", "echo", "echo-reply"]
            ):
                ace_dict["source_modifier"] = item
            elif not ace_dict["destination_network"] and re.search(
                r"\d+\.\d+\.\d+\.\d+|any|host", item
            ):
                ace_dict["destination_network"] = item
            elif ace_dict["destination_network"] and item in SUBNET_MASKS:
                ace_dict["destination_network"] += f"/{SUBNET_MASKS[item]}"
            elif (
                ace_dict["destination_network"]
                and ace_dict["destination_network"] == "host"
                and re.search(r"\d+\.\d+\.\d+\.\d+", item)
            ):
                ace_dict["destination_network"] += f" {item}"
            elif ace_dict["destination_network"] and item in OPERATOR_NAMES:
                ace_dict["destination_operator"] = item
            elif (
                ace_dict["destination_operator"]
                and not ace_dict["destination_ports"]
                and re.search(r"\w+|\w+\s\w+", item)
            ):
                for port_number in item.split():
                    if port_number in PORT_NAMES:
                        ace_dict["destination_ports"] += f" {PORT_NAMES[port_number]}"
                    else:
                        ace_dict["destination_ports"] += f" {port_number}"
                ace_dict["destination_ports"] = ace_dict["destination_ports"].strip()
            elif ace_dict["destination_network"] and item in [
                "established",
                "echo",
                "echo-reply",
            ]:
                ace_dict["destination_modifier"] = item
            elif (
                ace_dict["source_network"]
                and ace_dict["destination_network"]
                and item in ["log", "log-input"]
            ):
                ace_dict["optional_action"] = item

        parsed_ace = (
            f"{ace_dict['line_num']} "
            f"{ace_dict['action']} "
            f"{ace_dict['protocol']} "
            f"{ace_dict['source_network']} "
            f"{ace_dict['source_operator']} "
            f"{ace_dict['source_ports']} "
            f"{ace_dict['source_modifier']} "
            f"{ace_dict['destination_network']} "
            f"{ace_dict['destination_operator']} "
            f"{ace_dict['destination_ports']} "
            f"{ace_dict['destination_modifier']} "
            f"{ace_dict['optional_action']} "
        )
        print(re.sub(r" +", " ", parsed_ace))

        if mansplain:
            mansplained = (
                f"line {ace_dict['line_num']} {ace_dict['action']} {ace_dict['protocol']}"
                " connections"
            )
            if (
                "host" in ace_dict["source_network"]
                or "/" not in ace_dict["source_network"]
            ):
                mansplained += (
                    f" from IP address {ace_dict['source_network'].split()[-1]}"
                )
            else:
                ip_network = ipaddress.IPv4Network(ace_dict["source_network"])
                mansplained += (
                    f" from IP addresses {ip_network.network_address} - "
                    f"{ip_network.broadcast_address}"
                )
            if ace_dict["source_operator"]:
                if len(ace_dict["source_ports"].split()) == 2:
                    mansplained += (
                        f" where port {OPERATOR_NAMES[ace_dict['source_operator']]} "
                        f"{ace_dict['source_ports'].split()[0]} - {ace_dict['source_ports'].split()[1]}"
                    )
                else:
                    mansplained += (
                        f" where port {OPERATOR_NAMES[ace_dict['source_operator']]} "
                        f"{ace_dict['source_ports']}"
                    )
            if ace_dict["source_modifier"]:
                if ace_dict["source_modifier"] == "established":
                    mansplained += f" if the connection is already established"
                if ace_dict["source_modifier"] == "echo":
                    mansplained += f" for ICMP echo"
                if ace_dict["source_modifier"] == "echo-reply":
                    mansplained += f" for ICMP echo reply"
            if (
                "host" in ace_dict["destination_network"]
                or "/" not in ace_dict["destination_network"]
            ):
                mansplained += (
                    f", to IP address {ace_dict['destination_network'].split()[-1]}"
                )
            else:
                ip_network = ipaddress.IPv4Network(ace_dict["destination_network"])
                mansplained += f", to IP addresses {ip_network.network_address} - {ip_network.broadcast_address}"
            if ace_dict["destination_operator"]:
                if len(ace_dict["destination_ports"].split()) == 2:
                    mansplained += (
                        f" where port {OPERATOR_NAMES[ace_dict['destination_operator']]} "
                        f"{ace_dict['destination_ports'].split()[0]} - {ace_dict['destination_ports'].split()[1]}"
                    )
                else:
                    mansplained += (
                        f" where port {OPERATOR_NAMES[ace_dict['destination_operator']]} "
                        f"{ace_dict['destination_ports']}"
                    )
            if ace_dict["destination_modifier"]:
                if ace_dict["destination_modifier"] == "established":
                    mansplained += f" if the connection is already established"
                if ace_dict["destination_modifier"] == "echo":
                    mansplained += f" for ICMP echo"
                if ace_dict["destination_modifier"] == "echo-reply":
                    mansplained += f" for ICMP echo reply"
            if ace_dict["optional_action"]:
                mansplained += f", and {ace_dict['optional_action']}"
            print(f"{mansplained}\n")


if __name__ == "__main__":
    main()

Sunday, 3 January 2021

Debugging .1x / RADIUS on 3850 Switches

It used to be you could simply enable the AAA and/or RADIUS debugs & review the outputs at your leisure via your favourite syslog analysis tool, such as Splunk or ELK stack. But on the 3650 & 3850 switches that's not the case, you have to use traces which aren't sent to syslog. Amended process below, though do note that the commands changed between IOS XE 3.x & 16.x releases.

 

First of all enable rotating the traces between files, so that you don't overwrite the outputs accidentally:

request platform software trace rotate all

Enable the traces that cover .1x, AAA & RADIUS:

set platform software trace smd R0 radius debug
set platform software trace smd R0 dot1x-all debug
set platform software trace smd R0 auth-mgr-all debug
set platform software trace smd R0 epm-all debug


Reproduce the issue & view the last 1,000 lines of traces:

show platform software trace message smd switch active R0

To view more traces requires exporting the traces for a set time period, then uploading off the switch:

request platform software trace archive last x days target flash:blah
copy flash:blah ftp:


Once you're done, return the traces to their usual state:

set platform software trace smd R0 radius notice
set platform software trace smd R0 dot1x-all notice
set platform software trace smd R0 auth-mgr-all notice
set platform software trace smd R0 epm-all notice



Which segways into why I'm writing about this...Had to diagnose wired .1x authentication failures that turned out to be a bug where a 3850 with equal cost uplinks (pretty common!) will chew up some of the RADIUS Access-Requests. Fun part is the RADIUS server never replies to the broken RADIUS message, so the switch then thinks the RADIUS server is timing out & marks it dead, which you'll see along with incrementing timeouts under show aaa servers. This was fixed in IOS XE 16.9.6.

Friday, 10 April 2020

Automated CUCM CDR Exception Analyser

So Covid-19 containment has resulted in some spare time that would otherwise have been spent commuting, so I finally got around to creating something I've been meaning to do ever since I left AT&T Global Network Services, which is try to replicate their CDR exception analysis reporting. For customer's managed CUCM deployments AT&T would do an analysis of the CDR/CMR files & pick out repeated instances of non-normal call termination cause codes, as well as instances of poor call quality.
My automated version doesn't do quite the same depth of analysis, but does provide an interesting insight into the surprisingly varied & many things going wrong behind the scenes in a CUCM deployment. A CDR exception being:
  • For a given source device, all instances of a particular source cause code
  • For a given source device, all instances of a particular destination cause code
  • For a given destination device, all instances of a particular source cause code
  • For a given destination device, all instances of a particular destination cause code
  • For a given source device, all instances of poor MoS or CCR
  • For a given destination device, all instances of poor MoS or CCR

 Project hosted on my GitHub

Monday, 20 January 2020

Some Open Source Python Networking Tools

I've been tinkering on & off for a while now with using Python to create tools to automate repetitive tasks & occasionally posting the source code on this blog. I've now published them all on GitHub under the BSD 3-clause licence, so that hopefully others can use & adapt them. Links below:

Data Tools

Voice Tools

Long term I'm thinking about putting together a front end using Flask to tie this all together into a self-service portal, but motivation terms & conditions apply (*need recertify my CCIE again this year).

Wednesday, 27 November 2019

Converting Monitor Capture Dump to PCAP

Most recent Cisco platforms support the Embedded Packet Capture feature, which allows us to take packet captures directly on a router or switch without having to use SPAN to an attached device. Detailed instructions here: Embedded Packet Capture for Cisco IOS and IOS-XE Configuration Example

Normally you can export the resulting packet capture to an FTP or TFTP server, however if this is blocked by firewalls or you don't have access to a suitable server, this is a workaround. Using the show monitor capture buffer dump command we can view the raw packet capture data, but it isn't in a format that Wireshark understands:

router1#show monitor capture buffer CAP dump
03:57:20.288 EST Nov 27 2019 : IPv4 LES CEF : Gi0/0 None

45ED3640: 3890A5D2 BDE07486 0BAD7BC0 08004500 8.%R=`t..-{@..E.
45ED3650: 0028928F 40003106 8B850A52 7A1E0A53 .(..@.1....Rz..S
45ED3660: 9CF8AD60 00161620 FB112DB5 2E9C5010 .x-`... {.-5..P.
45ED3670: F88C7092 00000000 00000000 00       x.p..........

03:57:20.288 EST Nov 27 2019 : IPv4 LES CEF : Gi0/0 None

45ED3640: 3890A5D2 BDE07486 0BAD7BC0 08004500 8.%R=`t..-{@..E.
45ED3650: 00289290 40003106 8B840A52 7A1E0A53 .(..@.1....Rz..S
45ED3660: 9CF8AD60 00161620 FB112DB5 2E9C5010 .x-`... {.-5..P.
45ED3670: F88C7092 00000000 00000000 00       x.p..........


If you copy this raw data to a text file, there is an open source tool to help with this: ciscoText2pcap

First pipe the saved output into ciscoText2pcap & in turn pipe its output into another text file:

cat input.txt | ./ciscoText2pcap.pl > output.txt

Then use Wireshark's text2pcap tool to convert it to a valid PCAP file:

text2pcap -d output.txt output.pcap

Note that you'll need both Perl & Wireshark installed to be able to do this.

UPDATE: Alternatively I knocked together a Python version that can also handle timestamps, source code below.

#!/usr/bin/env python
# (c) 2019, Chris Perkins
# Converts Cisco EPC "show monitor capture buffer dump" into format usable by text2pcap
# Use text2pcap -d -t "%Y-%m-%d %H:%M:%S." to convert output to PCAP whilst showing parsing info
# Based on ciscoText2pcap https://github.com/mad-ady/ciscoText2pcap

# v1.1 - added time stamp handling, converts into UTC
# v1.0 - initial release

import sys, re, pytz, datetime

if __name__ == "__main__":
    # Parse command line parameters
    if len(sys.argv) != 3:
        print("Please specify source & destination files as parameters.")
        sys.exit(1)
    # Parse input file via regex
    try:
        with open(sys.argv[1]) as in_file:
            with open(sys.argv[2], 'w') as out_file:
                packet_start = 0
                for line in in_file:
                    # Regex to find timestamp, then manipulate into format text2pcap can use, as %z or %Z is failing
                    time_date = re.search(r"^(\d\d:\d\d:\d\d\.\d+) (\w+) ([\w ]+) : ", line)
                    if time_date:
                        # Use pytz to parse timezone, then make datetime object TZ aware & convert into UTC
                        try:
                            tz = pytz.timezone(time_date.group(2))
                            dt = datetime.datetime.strptime(f"{time_date.group(3).rstrip()} {time_date.group(1).rstrip()}",
                                "%b %d %Y %H:%M:%S.%f")
                            dt = dt.replace(tzinfo=tz)
                            dt = dt.astimezone(tz=datetime.timezone.utc)
                            out_file.write(f"{dt.strftime('%Y-%m-%d %H:%M:%S.%f')}\n")
                        except IndexError:
                            pass
                        # Continue to next line in input file
                        continue
                    # Regex to find valid blocks of hexadecimal
                    hex_dump = re.search(r"^[0-9A-F]+:\s+((?:[0-9A-F]+ ){1,4}) (.+)\n", line)
                    if hex_dump:
                        # Iterate through each block of hex & split into sets of 2 digits with spaces inbetween
                        char_list = hex_dump.group(1).split()
                        for chars in char_list:
                            packet_hex = ''
                            for i in range(1,len(chars),2):
                                packet_hex += f"{chars[i-1:i+1]} "
                            packet_hex = packet_hex.rstrip()
                            # Output packet as offset (8 hex digits) + hex string
                            out_file.write(f"{packet_start:08X} {packet_hex}\n")
                            packet_start += len(chars) // 2
                    else:
                        # End of packet
                        packet_start = 0
    except FileNotFoundError:
        print(f"Unable to open file {sys.argv[1]}")
        sys.exit(1)
    except OSError:
        print(f"Unable to write file {sys.argv[2]}")
        sys.exit(1)

Thursday, 5 September 2019

Nexus Switch PTP Intervals

There's a number of timers you can adjust to control the frequency of various PTP messages on Nexus switches. However the values to configure are somewhat obtuse in Cisco's documentation. For example if you read the NX-OS config guide it says:

ptp announce [interval log seconds | timeout count]
Configures the interval between PTP announce messages on an interface or the number of PTP intervals before a timeout occurs on an interface.
The range for the PTP announcement interval is from 0 to 4 seconds, and the range for the interval timeout is from 2 to 10.

ptp delay request minimum interval log seconds
Configures the minimum interval allowed between PTP delay-request messages when the port is in the master state.
The range is from log(-6) to log(1) seconds.

ptp sync interval log seconds
Configures the interval between PTP synchronization messages on an interface.
The range for the PTP synchronization interval is from -3 log second to 1 log second

But how to interpret the log seconds values? It is described as the logarithmic mean interval in seconds. Which basically means number of seconds between PTP messages = 2 ^ interval value. For example 2 ^ -3 = 0.125s between messages, or 8 messages a second. So some common values are:

Interval 2 = 1 packet every 4 seconds
Interval 1 = 1 packet every 2 seconds
Interval 0 = 1 packet every second
Interval -1 = 1 packet every second
Interval -2 = 4 packets every second
Interval -3 = 8 packets every second


On a related note, by default Nexus switches can act as a grandmaster clock & Cisco best practice is to disable this functionality via "no ptp grandmaster-capable". As it is default configuration you'll need to use  "show run all | inc ptp grandmaster-capable" in order to see the default command enabling it. Some further reading https://www.cisco.com/c/en/us/support/docs/ip/network-time-protocol-ntp/212139-Configure-and-troubleshoot-PTP-in-Nexus.html