blob: f9ad08a1411bb6662e9efd3645c4bb205020a22f [file] [log] [blame]
You Wangb0590a72020-09-22 15:31:49 -07001#!/usr/bin/env python3
2
3# Copyright 2020-present Open Networking Foundation
4#
5# SPDX-License-Identifier: Apache-2.0
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18
19# This script iterates through packets captured in pcap file and maps UE IDs to
20# corresponding packet indices. Then for each UE it validates if the packet sequence
21# looks correct (e.g. including attach/detach request/accept etc.). Otherwise print
22# missing packets associtated with UE ID and IMSI.
23#
24# Usage: pcap-analyze.py xxx.pcap
25
26import sys
27import re
28import pyshark
29
30# Map from UE ID to packet index
31packetMap = {}
32# All the packets captured in pcap file
33captures = None
34
35def groupPacket(pkt, i):
36 if 's1ap' in pkt:
37 #ueId = pkt.s1ap.enb_ue_s1ap_id
38
39 # Looks like pyshark cannot handle packets with multiple sctp data chunks
40 # So use regex match as a workaround
41 ueIds = re.findall(r'ENB-UE-S1AP-ID: (\d+)', str(pkt))
42 for ueId in ueIds:
43 if not ueId in packetMap.keys():
44 packetMap[ueId] = []
45 packetMap[ueId].append(i)
46
47def validate(ueId, packets):
48 # Get IMSI value from the first packet (assuming it's attach request)
49 # Again using regex is a workaround as pyshark cannot handle multiple sctp data chunks
50
51 # FIXME: IMSI value could be wrong if the first packet is not attach request (e.g.
52 # when packet contains multiple sctp data chunks)
53 imsi = re.findall(r'IMSI: (\d+)', str(captures[packets[0]]))
54 # TODO: validate more attach/detach messages in addition to request and accept
55 for keyword in ['Attach request', 'Attach accept', 'Detach request', 'Detach accept']:
56 try:
57 assert any(keyword in str(captures[packet]) for packet in packets)
58 except Exception:
59 print('UE #{} (IMSI: {}): missing "{}"'.format(ueId, imsi, keyword))
60 break
61
62if __name__ == "__main__":
63 pcapFile = str(sys.argv[1])
64 captures = pyshark.FileCapture(pcapFile)
65 p = captures[0]
66 i = 0
67 # Extract UE ID for each packet and group packets with the same UE ID
68 while(p):
69 groupPacket(p, i)
70 try:
71 p = captures.next()
72 except Exception:
73 break
74 i += 1
75
76 # Check attach/detach packets for each UE
77 for ueId, packets in packetMap.items():
78 validate(ueId, packets)