├── Packet capture └── scripts │ ├── analyze_traffic.py │ └── data │ └── network_capture.pcap └── README.md /Packet capture/scripts/analyze_traffic.py: -------------------------------------------------------------------------------- 1 | import pyshark 2 | import os 3 | import sys 4 | from reportlab.lib.pagesizes import letter 5 | from reportlab.pdfgen import canvas 6 | import pathlib # Importar pathlib para manejar rutas 7 | 8 | def analyze_packet(packet, pdf, y_position): 9 | packet_info = f"Packet {packet.number}: {packet.highest_layer}\n" 10 | 11 | if 'IP' in packet: 12 | packet_info += f" Source IP: {packet.ip.src}\n" 13 | packet_info += f" Destination IP: {packet.ip.dst}\n" 14 | 15 | if 'TCP' in packet: 16 | packet_info += f" TCP - Source Port: {packet.tcp.srcport}, Destination Port: {packet.tcp.dstport}\n" 17 | if packet.tcp.flags_syn == '1' and packet.tcp.flags_ack == '0': 18 | packet_info += " TCP SYN packet detected\n" 19 | 20 | elif 'UDP' in packet: 21 | packet_info += f" UDP - Source Port: {packet.udp.srcport}, Destination Port: {packet.udp.dstport}\n" 22 | if int(packet.udp.length) > 1000: 23 | packet_info += " Large UDP packet detected\n" 24 | 25 | elif 'DNS' in packet: 26 | if hasattr(packet.dns, 'qry_name'): 27 | packet_info += f" DNS query: {packet.dns.qry_name}\n" 28 | 29 | packet_info += "\n" # Empty line for readability 30 | pdf.drawString(100, y_position, packet_info) 31 | y_position -= 100 32 | if y_position < 100: 33 | pdf.showPage() 34 | y_position = 750 35 | return y_position 36 | 37 | def main(pcap_file): 38 | print(f"Analyzing file: {pcap_file}") 39 | 40 | cap = pyshark.FileCapture(pcap_file) 41 | 42 | packet_count = 0 43 | pdf_path = os.path.join('docs', 'network_analysis_report.pdf') 44 | 45 | # Crear la carpeta 'docs' si no existe 46 | pathlib.Path('docs').mkdir(parents=True, exist_ok=True) 47 | 48 | pdf = canvas.Canvas(pdf_path, pagesize=letter) 49 | pdf.setFont("Helvetica", 12) 50 | y_position = 750 # Start at the top of the page 51 | 52 | for packet in cap: 53 | packet_count += 1 54 | y_position = analyze_packet(packet, pdf, y_position) 55 | 56 | pdf.save() 57 | print(f"Network analysis completed. Analyzed {packet_count} packets. Report saved as {pdf_path}") 58 | 59 | if __name__ == "__main__": 60 | default_file = os.path.join('data', 'network_capture.pcap') 61 | 62 | if len(sys.argv) > 1: 63 | pcap_file = os.path.join('data', sys.argv[1]) 64 | else: 65 | pcap_file = default_file 66 | 67 | if not os.path.exists(pcap_file): 68 | print(f"Error: The file '{pcap_file}' does not exist.") 69 | print("Available capture files:") 70 | for file in os.listdir('data'): 71 | if file.endswith('.pcap'): 72 | print(f" - {file}") 73 | sys.exit(1) 74 | 75 | main(pcap_file) 76 | -------------------------------------------------------------------------------- /Packet capture/scripts/data/network_capture.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elliotsecops/Packet-Capture/9e7fff030b76fbce975412b299e8b07f2c5ced0b/Packet capture/scripts/data/network_capture.pcap -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **Script de Análisis de Tráfico de Red** 2 | 3 | ## Resumen 4 | 5 | Este script está diseñado para analizar el tráfico de red capturado en un archivo `.pcap` utilizando la biblioteca `pyshark`. Los resultados del análisis se exportan luego a un informe PDF utilizando la biblioteca `reportlab`. 6 | 7 | ## Características 8 | 9 | - **Análisis de Paquetes**: El script analiza cada paquete en el archivo `.pcap` y extrae información relevante como las direcciones IP de origen y destino, los puertos TCP/UDP y las consultas DNS. 10 | - **Generación de Informe PDF**: Los resultados del análisis se guardan en un informe PDF llamado `network_analysis_report.pdf` ubicado en el directorio `docs`. 11 | - **Interfaz de Línea de Comandos**: Los usuarios pueden especificar el archivo `.pcap` a analizar a través de la línea de comandos. Si no se especifica ningún archivo, el script utiliza por defecto `data/network_capture.pcap`. 12 | 13 | ## Requisitos Previos 14 | 15 | Antes de ejecutar el script, asegúrate de tener instaladas las siguientes dependencias: 16 | 17 | - Python 3.x 18 | - Biblioteca `pyshark` 19 | - Biblioteca `reportlab` 20 | 21 | Puedes instalar las bibliotecas requeridas utilizando pip: 22 | 23 | ```bash 24 | pip install pyshark reportlab 25 | ``` 26 | 27 | ## Estructura de Directorios 28 | 29 | Asegúrate de que la estructura de directorios sea la siguiente: 30 | 31 | ``` 32 | Packet capture/ 33 | ├── docs/ 34 | ├── scripts/ 35 | │ ├── analyze_traffic.py 36 | │ └── data/ 37 | │ └── network_capture.pcap 38 | ``` 39 | 40 | ## Uso 41 | 42 | ### Ejecutar el Script 43 | 44 | Para ejecutar el script, navega al directorio `scripts` y ejecuta: 45 | 46 | ```bash 47 | python analyze_traffic.py 48 | ``` 49 | 50 | ### Especificar un Archivo `.pcap` Diferente 51 | 52 | Si deseas especificar un archivo `.pcap` diferente, puedes hacerlo pasando el nombre de archivo como argumento: 53 | 54 | ```bash 55 | python analyze_traffic.py another_capture.pcap 56 | ``` 57 | 58 | Esto buscará `another_capture.pcap` en el directorio `data` y generará un informe PDF llamado `network_analysis_report.pdf` en el directorio `docs`. 59 | 60 | ### Salida 61 | 62 | El script emitirá lo siguiente: 63 | 64 | - Un mensaje que indica el archivo que se está analizando. 65 | - Un mensaje que indica la finalización del análisis y el número de paquetes analizados. 66 | - Un mensaje que indica la ubicación del informe PDF generado. 67 | 68 | ## Ejemplo de Salida 69 | 70 | ```bash 71 | Analizando archivo: data/network_capture.pcap 72 | Análisis de red completado. Se analizaron 500 paquetes. Informe guardado como docs/network_analysis_report.pdf 73 | ``` 74 | 75 | ## Descripción del Código 76 | 77 | ### Función `analyze_packet` 78 | 79 | Esta función analiza un solo paquete y extrae información relevante como: 80 | 81 | - Número de paquete y capa más alta. 82 | - Direcciones IP de origen y destino. 83 | - Puertos TCP/UDP de origen y destino. 84 | - Paquetes TCP SYN. 85 | - Paquetes UDP grandes. 86 | - Consultas DNS. 87 | 88 | La información extraída se escribe luego en el informe PDF. 89 | 90 | ### Función `main` 91 | 92 | Esta función coordina el proceso de análisis: 93 | 94 | - Abre el archivo `.pcap` especificado utilizando `pyshark.FileCapture`. 95 | - Inicializa el informe PDF y establece la fuente. 96 | - Itera sobre cada paquete en el archivo de captura, llamando a `analyze_packet` para cada paquete. 97 | - Guarda el informe PDF en el directorio `docs`. 98 | 99 | ### Interfaz de Línea de Comandos 100 | 101 | El script admite argumentos de línea de comandos para especificar el archivo `.pcap` a analizar. Si no se especifica ningún archivo, se utiliza por defecto `data/network_capture.pcap`. 102 | 103 | ### Problemas de Dependencias 104 | 105 | Si experimentas problemas con dependencias faltantes, asegúrate de que tanto `pyshark` como `reportlab` estén instalados. Puedes instalarlos utilizando pip como se describe en la sección de Requisitos Previos. 106 | 107 | ## Contribuciones 108 | 109 | ¡Siéntete libre de contribuir a este proyecto enviando pull requests o informando problemas! ¡Tus contribuciones son bienvenidas! 110 | 111 | ## Agradecimientos 112 | 113 | - La biblioteca `pyshark` para el análisis de paquetes de red. 114 | - La biblioteca `reportlab` para la generación de PDF. 115 | 116 | --- 117 | 118 | # Network Traffic Analysis Script 119 | 120 | ## Overview 121 | 122 | This script is designed to analyze network traffic captured in a `.pcap` file using the `pyshark` library. The analysis results are then exported to a PDF report using the `reportlab` library. 123 | 124 | ## Features 125 | 126 | - **Packet Analysis**: The script analyzes each packet in the `.pcap` file and extracts relevant information such as source and destination IP addresses, TCP/UDP ports, and DNS queries. 127 | - **PDF Report Generation**: The analysis results are saved in a PDF report named `network_analysis_report.pdf` located in the `docs` directory. 128 | - **Command-Line Interface**: Users can specify the `.pcap` file to analyze via the command line. If no file is specified, the script defaults to `data/network_capture.pcap`. 129 | 130 | ## Prerequisites 131 | 132 | Before running the script, ensure you have the following dependencies installed: 133 | 134 | - Python 3.x 135 | - `pyshark` library 136 | - `reportlab` library 137 | 138 | You can install the required libraries using pip: 139 | 140 | ```bash 141 | pip install pyshark reportlab 142 | ``` 143 | 144 | ## Directory Structure 145 | 146 | Ensure your directory structure looks like this: 147 | 148 | ``` 149 | Packet capture/ 150 | ├── docs/ 151 | ├── scripts/ 152 | │ ├── analyze_traffic.py 153 | │ └── data/ 154 | │ └── network_capture.pcap 155 | ``` 156 | 157 | ## Usage 158 | 159 | ### Running the Script 160 | 161 | To run the script, navigate to the `scripts` directory and execute: 162 | 163 | ```bash 164 | python analyze_traffic.py 165 | ``` 166 | 167 | ### Specifying a Different `.pcap` File 168 | 169 | If you want to specify a different `.pcap` file, you can do so by passing the filename as an argument: 170 | 171 | ```bash 172 | python analyze_traffic.py another_capture.pcap 173 | ``` 174 | 175 | This will look for `another_capture.pcap` in the `data` directory and generate a PDF report named `network_analysis_report.pdf` in the `docs` directory. 176 | 177 | ### Output 178 | 179 | The script will output the following: 180 | 181 | - A message indicating the file being analyzed. 182 | - A message indicating the completion of the analysis and the number of packets analyzed. 183 | - A message indicating the location of the generated PDF report. 184 | 185 | ## Example Output 186 | 187 | ```bash 188 | Analyzing file: data/network_capture.pcap 189 | Network analysis completed. Analyzed 500 packets. Report saved as docs/network_analysis_report.pdf 190 | ``` 191 | 192 | ## Code Overview 193 | 194 | ### `analyze_packet` Function 195 | 196 | This function analyzes a single packet and extracts relevant information such as: 197 | 198 | - Packet number and highest layer. 199 | - Source and destination IP addresses. 200 | - TCP/UDP source and destination ports. 201 | - TCP SYN packets. 202 | - Large UDP packets. 203 | - DNS queries. 204 | 205 | The extracted information is then written to the PDF report. 206 | 207 | ### `main` Function 208 | 209 | This function orchestrates the analysis process: 210 | 211 | - It opens the specified `.pcap` file using `pyshark.FileCapture`. 212 | - It initializes the PDF report and sets the font. 213 | - It iterates over each packet in the capture file, calling `analyze_packet` for each packet. 214 | - It saves the PDF report to the `docs` directory. 215 | 216 | ### Command-Line Interface 217 | 218 | The script supports command-line arguments to specify the `.pcap` file to analyze. If no file is specified, it defaults to `data/network_capture.pcap`. 219 | 220 | ### Dependency Issues 221 | 222 | If you encounter issues with missing dependencies, ensure that both `pyshark` and `reportlab` are installed. You can install them using pip as described in the Prerequisites section. 223 | 224 | ## Contributing 225 | 226 | Feel free to contribute to this project by submitting pull requests or reporting issues. Your contributions are welcome! 227 | 228 | ## Acknowledgments 229 | 230 | - The `pyshark` library for network packet analysis. 231 | - The `reportlab` library for PDF generation. 232 | 233 | --- 234 | --------------------------------------------------------------------------------