Saltar a contenido

Wireshark hoja de trucos

Overview

Wireshark is the world's most widely used network protocolo analyzer and packet capture tool, providing comprehensive capabilities for network solución de problemas, security analysis, protocolo development, and educational purposes. As an open-source Análisis de Red platform, Wireshark enables security professionals, network administrators, and researchers to capture, inspect, and analyze network traffic in real-time or from previously captured packet files. The tool's sophisticated protocolo dissection engine suppuertos hundreds of network protocolos, from common protocolos like HTTP, TCP, and DNS to specialized industrial and proprietary protocolos, making it an indispensable tool for understanding network behavior and identifying security issues.

The core strength of Wireshark lies in its powerful packet analysis capabilities, combining deep protocolo inspection with an intuitive graphical user interface that makes complex Análisis de Red accessible to both novice and expert users. The platform provides multiple analysis views including packet lists, protocolo trees, and hexadecimal dumps, enabling users to examine network traffic at various levels of detail. Advanced features include statistical analysis tools, protocolo-specific analyzers, conversation tracking, and expert analysis systems that automatically identify potential network problems and security issues. The tool's filtering capabilities allow users to focus on specific traffic patterns, protocolos, or communication flows within large packet captures.

Wireshark's extensible architecture suppuertos custom protocolo dissectors, advanced scripting capabilities through Lua, and integration with external tools and databases for enhanced analysis workflows. The platform includes specialized features for security analysis such as SSL/TLS descifrado, VoIP call analysis, wireless protocolo suppuerto, and malware Análisis de Tráfico. With its active development community, comprehensive documentación, and continuous updates to suppuerto emerging protocolos and technologies, Wireshark remains the gold standard for Análisis de Red and an essential tool for cybersecurity professionals conducting network forensics, respuesta a incidentes, and security assessments.

instalación

Ubuntu/Debian instalación

Installing Wireshark on Ubuntu/Debian systems:

# Update system packages
sudo apt update && sudo apt upgrade -y

# Install Wireshark
sudo apt install -y wireshark

# Configure Wireshark for non-root users
sudo dpkg-reconfigure wireshark-common
# Select "Yes" to allow non-superusers to capture packets

# Add user to wireshark group
sudo usermod -a -G wireshark $USER

# Install additional tools
sudo apt install -y tshark dumpcap editcap mergecap text2pcap \
    capinfos rawshark wireshark-dev

# Verify instalación
wireshark --version
tshark --version

# Install development headers (for custom dissectors)
sudo apt install -y libwireshark-dev libwiretap-dev libwsutil-dev

# Log out and log back in for group changes to take effect
# Or use: newgrp wireshark

CentOS/RHEL instalación

# Install EPEL repository
sudo yum install -y epel-release

# Install Wireshark
sudo yum install -y wireshark wireshark-gnome

# Alternative: Install from source
sudo yum groupinstall -y "Development Tools"
sudo yum install -y cmake glib2-devel libpcap-devel zlib-devel \
    openssl-devel lua-devel qt5-qtbase-devel qt5-qtmultimedia-devel

# Download and compile Wireshark
cd /tmp
wget https://www.wireshark.org/download/src/wireshark-latest.tar.xz
tar -xf wireshark-latest.tar.xz
cd wireshark-*

mkdir build && cd build
cmake ..
make -j$(nproc)
sudo make install

# Configure capabilities for packet capture
sudo setcap cap_net_raw,cap_net_admin+eip /usr/local/bin/dumpcap

macOS instalación

# Install using Homebrew
brew install wireshark

# Install with GUI suppuerto
brew install --cask wireshark

# Alternative: Download from official website
# https://www.wireshark.org/download.html

# Install comando-line tools only
brew install wireshark --without-qt

# Verify instalación
wireshark --version

Windows instalación

# Download installer from official website
# https://www.wireshark.org/download.html

# Run installer as Administrator
# Follow instalación wizard
# Install WinPcap/Npcap when prompted

# comando-line instalación with Chocolatey
choco install wireshark

# Verify instalación
# Open comando Prompt or PowerShell
wireshark --version

Docker instalación

Running Wireshark in Docker:

# Create Dockerfile for Wireshark
cat > Dockerfile.wireshark << 'EOF'
FROM ubuntu:22.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    wireshark \
    tshark \
    xvfb \
    x11vnc \
    fluxbox \
    && rm -rf /var/lib/apt/lists/*

# Configure Wireshark
RUN echo "wireshark-common wireshark-common/install-setuid boolean true"|debconf-set-selections
RUN dpkg-reconfigure -f noninteractive wireshark-common

# Create startup script
RUN echo '#!/bin/bash\nXvfb :1 -screen 0 1024x768x16 &\nexpuerto DISPLAY=:1\nfluxbox &\nx11vnc -display :1 -nopw -listen localhost -xkb &\nwireshark' > /start.sh
RUN chmod +x /start.sh

EXPOSE 5900

CMD ["/start.sh"]
EOF

# Build Docker image
docker build -f Dockerfile.wireshark -t wireshark .

# Run Wireshark in Docker with network access
docker run -d --name wireshark \
    --net=host \
    --privileged \
    -p 5900:5900 \
    -v $(pwd)/captures:/captures \
    wireshark

# Access via VNC
# Connect to localhost:5900 with VNC client

Basic uso

Interface Overview

Understanding Wireshark's interface:

# Main Interface Components:
# 1. Menu Bar: File, Edit, View, Go, Capture, Analyze, Statistics, Tools, Help
# 2. Toolbar: Quick access to common functions
# 3. Filter Bar: Display and capture filters
# 4. Packet List Pane: List of captured packets
# 5. Packet Details Pane: protocolo tree for selected packet
# 6. Packet Bytes Pane: Hexadecimal and ASCII view

# Starting Wireshark
wireshark

# Start with specific interface
wireshark -i eth0

# Open existing capture file
wireshark -r capture.pcap

# Start capture immediately
wireshark -i eth0 -k

# comando-line capture with tshark
tshark -i eth0 -w capture.pcap

Packet Capture

Capturing network traffic:

# Start Live Capture
# 1. Select Capture > Interfaces
# 2. Choose network interface
# 3. Click Start button
# 4. Packets appear in real-time

# Capture opcións
# 1. Capture > opcións
# 2. Configure interface settings:
#    - Promiscuous mode: Capture all traffic
#    - Buffer size: Memory for packet storage
#    - Capture filter: Limit captured traffic
#    - File opcións: Auto-save settings

# Common Capture Filters
# Capture only HTTP traffic:
puerto 80

# Capture specific host:
host 192.168.1.100

# Capture subnet traffic:
net 192.168.1.0/24

# Capture specific protocolo:
tcp
udp
icmp

# Capture excluding specific traffic:
not puerto 22

# Complex capture filter:
host 192.168.1.100 and puerto 80

# Stop Capture
# 1. Click Stop button (red square)
# 2. Or use Ctrl+E
# 3. Save capture if needed

Display Filters

Filtering displayed packets:

# Basic Display Filters
# Show only HTTP traffic:
http

# Show specific IP address:
ip.addr == 192.168.1.100

# Show traffic between two hosts:
ip.addr == 192.168.1.100 and ip.addr == 192.168.1.200

# Show specific puerto:
tcp.puerto == 80

# Show protocolo:
dns
smtp
ftp

# Advanced Display Filters
# HTTP GET requests:
http.request.method == "GET"

# HTTP responses with specific status:
http.response.code == 404

# TCP SYN packets:
tcp.banderas.syn == 1

# Large packets:
frame.len > 1000

# Packets containing specific string:
frame contains "contraseña"

# Time-based filters:
frame.time >= "2023-01-01 00:00:00"

# Logical Operators
# AND operator:
tcp and puerto 80

# OR operator:
tcp or udp

# NOT operator:
not icmp

# Parentheses for grouping:
(tcp and puerto 80) or (udp and puerto 53)

# Filter Expressions
# Source/destination specific:
ip.src == 192.168.1.100
ip.dst == 192.168.1.200

# protocolo-specific fields:
tcp.seq == 0
udp.length > 100
dns.qry.name contains "ejemplo.com"

# String matching:
http.host contains "google"
http.user_agent contains "Mozilla"

protocolo Analysis

Analyzing specific protocolos:

# HTTP Analysis
# Filter: http
# Look for:
# - Request methods (GET, POST, PUT, DELETE)
# - Response codes (200, 404, 500)
# - Headers and cookies
# - Request/response bodies

# DNS Analysis
# Filter: dns
# Examine:
# - Query types (A, AAAA, MX, TXT)
# - Response codes
# - Authoritative answers
# - DNS tunneling indicators

# TCP Analysis
# Filter: tcp
# Analyze:
# - Three-way handshake (SYN, SYN-ACK, ACK)
# - conexión termination (FIN, RST)
# - Sequence and acknowledgment numbers
# - Window sizes and scaling

# SSL/TLS Analysis
# Filter: ssl or tls
# Review:
# - Handshake proceso
# - certificado information
# - Cipher suites
# - protocolo versions

# SMTP Analysis
# Filter: smtp
# Check:
# - Email headers
# - autenticación methods
# - Message content
# - Relay information

Advanced Features

Statistical Analysis

Using Wireshark's statistical tools:

# protocolo Hierarchy
# Statistics > protocolo Hierarchy
# Shows distribution of protocolos in capture
# Useful for understanding traffic composition

# Conversations
# Statistics > Conversations
# Shows communication between endpoints
# Available for Ethernet, IPv4, IPv6, TCP, UDP

# Endpoints
# Statistics > Endpoints
# Shows traffic statistics for individual hosts
# Includes packet counts and byte counts

# I/O Graphs
# Statistics > I/O Graphs
# Visual representation of traffic over time
# Customizable filters and display opcións

# Flow Graphs
# Statistics > Flow Graph
# Visual representation of packet flow
# Useful for understanding communication patterns

# Expert Information
# Analyze > Expert Information
# Automatic analysis of potential problems
# Categories: Chat, Note, Warn, Error

# Response Time Analysis
# Statistics > servicio Response Time
# Measures response times for various protocolos
# Useful for performance analysis

Advanced Filtering

Complex filtering techniques:

# Regular Expressions
# Use matches operator for regex:
http.host matches ".*\.ejemplo\.com"
dns.qry.name matches ".*\.evil\.com"

# Field Existence
# Check if field exists:
http.autorización
tcp.opcións.mss

# Arithmetic Operations
# Compare calculated values:
tcp.window_size_value < 1000
frame.time_delta > 1.0

# Bit Operations
# Check specific bits:
tcp.banderas & 0x02  # SYN bandera
ip.banderas.df == 1  # Don't Fragment

# Function Filters
# Use built-in functions:
upper(http.host) contains "ejemplo"
len(http.request.uri) > 100

# Slice Operators
# Extract specific bytes:
eth.src[0:3] == 00:50:56  # OUI check
ip.addr[0:2] == 192.168   # Network check

# Multiple Value Matching
# Match any of several values:
tcp.puerto in \\\\{80 443 8080 8443\\\\}
ip.addr in \\\\{192.168.1.0/24\\\\}

# Time-based Filtering
# Relative time filters:
frame.time_relative > 10.0
frame.time_delta > 0.1

# Advanced protocolo Filters
# HTTP-specific:
http.request.method in \\\\{"GET" "POST"\\\\}
http.response.code >= 400
http.content_type contains "application/json"

# DNS-specific:
dns.banderas.response == 1
dns.count.answers > 1
dns.resp.ttl < 300

# TCP-specific:
tcp.analysis.retransmission
tcp.analysis.duplicate_ack
tcp.analysis.zero_window

Packet Manipulation

Working with packet data:

# Expuerto Packet Data
# File > Expuerto Packet Dissections
# Formats: Plain text, CSV, JSON, XML

# Expuerto Objects
# File > Expuerto Objects > HTTP/SMB/TFTP
# Extract files transferred over protocolos

# Follow Streams
# Right-click packet > Follow > TCP/UDP/SSL Stream
# View complete conversation
# Save stream content

# Decode As
# Analyze > Decode As
# Force protocolo interpretation
# Useful for non-standard puertos

# Custom Columns
# Right-click column header > Column Preferencias
# Add custom fields as columns
# ejemplos:
# - Source puerto: tcp.srcpuerto
# - Destination puerto: tcp.dstpuerto
# - HTTP Method: http.request.method

# Time Display Formats
# View > Time Display Format
# opcións:
# - Absolute time
# - Relative to first packet
# - Delta from previous packet
# - UTC time

# Colorization Rules
# View > Coloring Rules
# Highlight packets based on criteria
# Create custom color rules
# ejemplos:
# - Red for TCP errors
# - Green for HTTP success
# - Blue for DNS queries

SSL/TLS descifrado

Decrypting encrypted traffic:

# Pre-Master Secret Method
# 1. Set SSLclaveLOGFILE environment variable
expuerto SSLclaveLOGFILE=/tmp/sslclaves.log

# 2. Start application (browser, curl, etc.)
# 3. Capture traffic with Wireshark
# 4. Configure SSL descifrado:
#    Edit > Preferencias > protocolos > TLS
#    (Pre)-Master-Secret log filename: /tmp/sslclaves.log

# Private clave Method
# 1. Obtain server private clave
# 2. Configure in Wireshark:
#    Edit > Preferencias > protocolos > TLS
#    RSA claves list: Add clave file
#    Format: IP,puerto,protocolo,clave file

# ejemplo RSA clave configuración:
# 192.168.1.100,443,http,/path/to/server.clave

# Verify descifrado
# Look for "Decrypted TLS" in protocolo column
# HTTP traffic should be visible in decrypted sesións

# Common Issues
# - Perfect Forward Secrecy (PFS) prevents descifrado with private clave only
# - Need pre-master secrets for PFS conexións
# - Ensure correct clave format (PEM)
# - Verify IP and puerto match exactly

Automation Scripts

Automated Analysis Script

#!/usr/bin/env python3
# Wireshark automation and analysis script

impuerto subproceso
impuerto json
impuerto csv
impuerto sys
impuerto os
impuerto time
from datetime impuerto datetime
impuerto argparse

class WiresharkAnalyzer:
    def __init__(self, pcap_file=None, interface=None):
        self.pcap_file = pcap_file
        self.interface = interface
        self.tshark_path = self.find_tshark()

    def find_tshark(self):
        """Find tshark executable"""
        for path in ['/usr/bin/tshark', '/usr/local/bin/tshark', 'tshark']:
            if os.path.exists(path) or subproceso.run(['which', path],
                                                    capture_output=True).returncode == 0:
                return path
        raise Exception("tshark not found in PATH")

    def capture_traffic(self, duration=60, output_file=None):
        """Capture network traffic"""
        if not self.interface:
            raise Exception("No interface specified for capture")

        if not output_file:
            output_file = f"capture_\\\\{datetime.now().strftime('%Y%m%d_%H%M%S')\\\\}.pcap"

        cmd = [
            self.tshark_path,
            '-i', self.interface,
            '-a', f'duration:\\\\{duration\\\\}',
            '-w', output_file
        ]

        print(f"Starting capture on \\\\{self.interface\\\\} for \\\\{duration\\\\} seconds...")
        result = subproceso.run(cmd, capture_output=True, text=True)

        if result.returncode == 0:
            print(f"Capture saved to: \\\\{output_file\\\\}")
            self.pcap_file = output_file
            return output_file
        else:
            raise Exception(f"Capture failed: \\\\{result.stderr\\\\}")

    def get_basic_statistics(self):
        """Get basic packet statistics"""
        if not self.pcap_file:
            raise Exception("No pcap file specified")

        cmd = [
            self.tshark_path,
            '-r', self.pcap_file,
            '-q', '-z', 'conv,ip'
        ]

        result = subproceso.run(cmd, capture_output=True, text=True)

        if result.returncode == 0:
            return self.parse_statistics(result.stdout)
        else:
            raise Exception(f"Statistics failed: \\\\{result.stderr\\\\}")

    def parse_statistics(self, output):
        """Parse tshark statistics output"""
        stats = \\\\{
            'total_packets': 0,
            'total_bytes': 0,
            'conversations': [],
            'protocolos': \\\\{\\\\}
        \\\\}

        lines = output.split('\n')
        for line in lines:
            if 'packets' in line and 'bytes' in line:
                # Parse conversation line
                parts = line.split()
                if len(parts) >= 6:
                    try:
                        conv = \\\\{
                            'src': parts[0],
                            'dst': parts[2],
                            'packets_ab': int(parts[3]),
                            'bytes_ab': int(parts[4]),
                            'packets_ba': int(parts[5]),
                            'bytes_ba': int(parts[6]) if len(parts) > 6 else 0
                        \\\\}
                        stats['conversations'].append(conv)
                        stats['total_packets'] += conv['packets_ab'] + conv['packets_ba']
                        stats['total_bytes'] += conv['bytes_ab'] + conv['bytes_ba']
                    except (ValueError, IndexError):
                        continue

        return stats

    def analyze_protocolos(self):
        """Analyze protocolo distribution"""
        cmd = [
            self.tshark_path,
            '-r', self.pcap_file,
            '-q', '-z', 'io,phs'
        ]

        result = subproceso.run(cmd, capture_output=True, text=True)

        if result.returncode == 0:
            return self.parse_protocolo_hierarchy(result.stdout)
        else:
            raise Exception(f"protocolo analysis failed: \\\\{result.stderr\\\\}")

    def parse_protocolo_hierarchy(self, output):
        """Parse protocolo hierarchy statistics"""
        protocolos = \\\\{\\\\}
        lines = output.split('\n')

        for line in lines:
            if '%' in line and 'frames' in line:
                # Parse protocolo line
                parts = line.strip().split()
                if len(parts) >= 3:
                    try:
                        protocolo = parts[0]
                        frames = int(parts[1])
                        bytes_count = int(parts[2])
                        protocolos[protocolo] = \\\\{
                            'frames': frames,
                            'bytes': bytes_count
                        \\\\}
                    except (ValueError, IndexError):
                        continue

        return protocolos

    def extract_http_requests(self):
        """Extract HTTP requests"""
        cmd = [
            self.tshark_path,
            '-r', self.pcap_file,
            '-Y', 'http.request',
            '-T', 'fields',
            '-e', 'frame.time',
            '-e', 'ip.src',
            '-e', 'ip.dst',
            '-e', 'http.request.method',
            '-e', 'http.request.uri',
            '-e', 'http.host',
            '-e', 'http.user_agent'
        ]

        result = subproceso.run(cmd, capture_output=True, text=True)

        if result.returncode == 0:
            return self.parse_http_requests(result.stdout)
        else:
            raise Exception(f"HTTP extraction failed: \\\\{result.stderr\\\\}")

    def parse_http_requests(self, output):
        """Parse HTTP request data"""
        requests = []
        lines = output.strip().split('\n')

        for line in lines:
            if line.strip():
                fields = line.split('\t')
                if len(fields) >= 7:
                    request = \\\\{
                        'timestamp': fields[0],
                        'src_ip': fields[1],
                        'dst_ip': fields[2],
                        'method': fields[3],
                        'uri': fields[4],
                        'host': fields[5],
                        'user_agent': fields[6]
                    \\\\}
                    requests.append(request)

        return requests

    def detect_suspicious_activity(self):
        """Detect suspicious network activity"""
        suspicious = \\\\{
            'puerto_scans': [],
            'dns_tunneling': [],
            'large_uploads': [],
            'suspicious_user_agents': []
        \\\\}

        # Detect puerto scans
        puerto_scan_cmd = [
            self.tshark_path,
            '-r', self.pcap_file,
            '-Y', 'tcp.banderas.syn==1 and tcp.banderas.ack==0',
            '-T', 'fields',
            '-e', 'ip.src',
            '-e', 'ip.dst',
            '-e', 'tcp.dstpuerto'
        ]

        result = subproceso.run(puerto_scan_cmd, capture_output=True, text=True)
        if result.returncode == 0:
            suspicious['puerto_scans'] = self.analyze_puerto_scans(result.stdout)

        # Detect DNS tunneling
        dns_cmd = [
            self.tshark_path,
            '-r', self.pcap_file,
            '-Y', 'dns and frame.len > 100',
            '-T', 'fields',
            '-e', 'dns.qry.name',
            '-e', 'frame.len'
        ]

        result = subproceso.run(dns_cmd, capture_output=True, text=True)
        if result.returncode == 0:
            suspicious['dns_tunneling'] = self.analyze_dns_tunneling(result.stdout)

        # Detect large uploads
        upload_cmd = [
            self.tshark_path,
            '-r', self.pcap_file,
            '-Y', 'http.request.method=="POST" and frame.len > 10000',
            '-T', 'fields',
            '-e', 'ip.src',
            '-e', 'http.host',
            '-e', 'frame.len'
        ]

        result = subproceso.run(upload_cmd, capture_output=True, text=True)
        if result.returncode == 0:
            suspicious['large_uploads'] = self.analyze_large_uploads(result.stdout)

        return suspicious

    def analyze_puerto_scans(self, output):
        """Analyze potential puerto scans"""
        scans = \\\\{\\\\}
        lines = output.strip().split('\n')

        for line in lines:
            if line.strip():
                fields = line.split('\t')
                if len(fields) >= 3:
                    src_ip = fields[0]
                    dst_ip = fields[1]
                    dst_puerto = fields[2]

                    clave = f"\\\\{src_ip\\\\}->\\\\{dst_ip\\\\}"
                    if clave not in scans:
                        scans[clave] = \\\\{'puertos': set(), 'count': 0\\\\}

                    scans[clave]['puertos'].add(dst_puerto)
                    scans[clave]['count'] += 1

        # Filter for potential scans (multiple puertos)
        potential_scans = []
        for clave, data in scans.items():
            if len(data['puertos']) > 10:  # Threshold for puerto scan
                potential_scans.append(\\\\{
                    'conexión': clave,
                    'unique_puertos': len(data['puertos']),
                    'total_attempts': data['count'],
                    'puertos': list(data['puertos'])[:20]  # Limit output
                \\\\})

        return potential_scans

    def analyze_dns_tunneling(self, output):
        """Analyze potential DNS tunneling"""
        tunneling = []
        lines = output.strip().split('\n')

        for line in lines:
            if line.strip():
                fields = line.split('\t')
                if len(fields) >= 2:
                    query_name = fields[0]
                    frame_length = int(fields[1]) if fields[1].isdigit() else 0

                    # Check for suspicious patterns
                    if (frame_length > 200 or
                        len(query_name) > 50 or
                        query_name.count('.') > 5):
                        tunneling.append(\\\\{
                            'query': query_name,
                            'length': frame_length,
                            'suspicious_reason': self.get_dns_suspicion_reason(query_name, frame_length)
                        \\\\})

        return tunneling

    def get_dns_suspicion_reason(self, query, length):
        """Determine reason for DNS suspicion"""
        reasons = []
        if length > 200:
            reasons.append("Large packet size")
        if len(query) > 50:
            reasons.append("Long query name")
        if query.count('.') > 5:
            reasons.append("Many subdomains")
        return ", ".join(reasons)

    def analyze_large_uploads(self, output):
        """Analyze large HTTP uploads"""
        uploads = []
        lines = output.strip().split('\n')

        for line in lines:
            if line.strip():
                fields = line.split('\t')
                if len(fields) >= 3:
                    src_ip = fields[0]
                    host = fields[1]
                    size = int(fields[2]) if fields[2].isdigit() else 0

                    uploads.append(\\\\{
                        'src_ip': src_ip,
                        'host': host,
                        'size_bytes': size,
                        'size_mb': round(size / 1024 / 1024, 2)
                    \\\\})

        return sorted(uploads, clave=lambda x: x['size_bytes'], reverse=True)

    def generate_repuerto(self, output_file="wireshark_analysis_repuerto.html"):
        """Generate comprehensive analysis repuerto"""
        print("Generating analysis repuerto...")

        # Gather all analysis data
        basic_stats = self.get_basic_statistics()
        protocolos = self.analyze_protocolos()
        http_requests = self.extract_http_requests()
        suspicious = self.detect_suspicious_activity()

        # Generate HTML repuerto
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Wireshark Analysis Repuerto</title>
    <style>
        body \\\\{\\\\{ font-family: Arial, sans-serif; margin: 20px; \\\\}\\\\}
        .section \\\\{\\\\{ margin: 20px 0; padding: 15px; border: 1px solid #ddd; \\\\}\\\\}
        .suspicious \\\\{\\\\{ color: red; font-weight: bold; \\\\}\\\\}
        .warning \\\\{\\\\{ color: orange; font-weight: bold; \\\\}\\\\}
        .info \\\\{\\\\{ color: blue; \\\\}\\\\}
        table \\\\{\\\\{ border-collapse: collapse; width: 100%; \\\\}\\\\}
        th, td \\\\{\\\\{ border: 1px solid #ddd; padding: 8px; text-align: left; \\\\}\\\\}
        th \\\\{\\\\{ background-color: #f2f2f2; \\\\}\\\\}
        pre \\\\{\\\\{ background: #f5f5f5; padding: 10px; overflow-x: auto; \\\\}\\\\}
    </style>
</head>
<body>
    <h1>Wireshark Análisis de Red Repuerto</h1>
    <p>Generated: \\\\{datetime.now().isoformat()\\\\}</p>
    <p>Source: \\\\{self.pcap_file or self.interface\\\\}</p>

    <div class="section">
        <h2>Executive Summary</h2>
        <ul>
            <li>Total Packets: \\\\{basic_stats['total_packets']\\\\}</li>
            <li>Total Bytes: \\\\{basic_stats['total_bytes']:,\\\\}</li>
            <li>Unique Conversations: \\\\{len(basic_stats['conversations'])\\\\}</li>
            <li>HTTP Requests: \\\\{len(http_requests)\\\\}</li>
            <li>Suspicious Activities: \\\\{len(suspicious['puerto_scans']) + len(suspicious['dns_tunneling']) + len(suspicious['large_uploads'])\\\\}</li>
        </ul>
    </div>

    <div class="section">
        <h2>protocolo Distribution</h2>
        <table>
            <tr><th>protocolo</th><th>Frames</th><th>Bytes</th><th>Percentage</th></tr>
"""

        total_frames = sum(p['frames'] for p in protocolos.values())
        for protocolo, data in sorted(protocolos.items(), clave=lambda x: x[1]['frames'], reverse=True)[:10]:
            percentage = (data['frames'] / total_frames * 100) if total_frames > 0 else 0
            html_content += f"""
            <tr>
                <td>\\\\{protocolo\\\\}</td>
                <td>\\\\{data['frames']\\\\}</td>
                <td>\\\\{data['bytes']:,\\\\}</td>
                <td>\\\\{percentage:.2f\\\\}%</td>
            </tr>"""

        html_content += """
        </table>
    </div>

    <div class="section">
        <h2>Top Conversations</h2>
        <table>
            <tr><th>Source</th><th>Destination</th><th>Packets A→B</th><th>Bytes A→B</th><th>Packets B→A</th><th>Bytes B→A</th></tr>
"""

        top_conversations = sorted(basic_stats['conversations'],
                                 clave=lambda x: x['bytes_ab'] + x['bytes_ba'], reverse=True)[:10]

        for conv in top_conversations:
            html_content += f"""
            <tr>
                <td>\\\\{conv['src']\\\\}</td>
                <td>\\\\{conv['dst']\\\\}</td>
                <td>\\\\{conv['packets_ab']\\\\}</td>
                <td>\\\\{conv['bytes_ab']:,\\\\}</td>
                <td>\\\\{conv['packets_ba']\\\\}</td>
                <td>\\\\{conv['bytes_ba']:,\\\\}</td>
            </tr>"""

        html_content += """
        </table>
    </div>

    <div class="section">
        <h2 class="suspicious">Suspicious Activities</h2>
"""

        if suspicious['puerto_scans']:
            html_content += """
        <h3>Potential puerto Scans</h3>
        <table>
            <tr><th>conexión</th><th>Unique puertos</th><th>Total Attempts</th></tr>
"""
            for scan in suspicious['puerto_scans'][:10]:
                html_content += f"""
            <tr>
                <td>\\\\{scan['conexión']\\\\}</td>
                <td>\\\\{scan['unique_puertos']\\\\}</td>
                <td>\\\\{scan['total_attempts']\\\\}</td>
            </tr>"""
            html_content += "</table>"

        if suspicious['dns_tunneling']:
            html_content += """
        <h3>Potential DNS Tunneling</h3>
        <table>
            <tr><th>Query</th><th>Length</th><th>Reason</th></tr>
"""
            for tunnel in suspicious['dns_tunneling'][:10]:
                html_content += f"""
            <tr>
                <td>\\\\{tunnel['query'][:50]\\\\}...</td>
                <td>\\\\{tunnel['length']\\\\}</td>
                <td>\\\\{tunnel['suspicious_reason']\\\\}</td>
            </tr>"""
            html_content += "</table>"

        if suspicious['large_uploads']:
            html_content += """
        <h3>Large HTTP Uploads</h3>
        <table>
            <tr><th>Source IP</th><th>host</th><th>Size (MB)</th></tr>
"""
            for upload in suspicious['large_uploads'][:10]:
                html_content += f"""
            <tr>
                <td>\\\\{upload['src_ip']\\\\}</td>
                <td>\\\\{upload['host']\\\\}</td>
                <td>\\\\{upload['size_mb']\\\\}</td>
            </tr>"""
            html_content += "</table>"

        html_content += """
    </div>

    <div class="section">
        <h2>HTTP Requests Summary</h2>
        <table>
            <tr><th>Method</th><th>host</th><th>URI</th><th>Source IP</th></tr>
"""

        for request in http_requests[:20]:
            html_content += f"""
            <tr>
                <td>\\\\{request['method']\\\\}</td>
                <td>\\\\{request['host']\\\\}</td>
                <td>\\\\{request['uri'][:50]\\\\}...</td>
                <td>\\\\{request['src_ip']\\\\}</td>
            </tr>"""

        html_content += """
        </table>
    </div>
</body>
</html>
"""

        with open(output_file, 'w') as f:
            f.write(html_content)

        print(f"Repuerto generated: \\\\{output_file\\\\}")
        return output_file

def main():
    parser = argparse.ArgumentParser(Descripción='Wireshark Analysis Automation')
    parser.add_argument('--pcap', help='PCAP file to analyze')
    parser.add_argument('--interface', help='Network interface for live capture')
    parser.add_argument('--duration', type=int, default=60, help='Capture duration in seconds')
    parser.add_argument('--output', default='wireshark_analysis_repuerto.html', help='Output repuerto file')

    args = parser.parse_args()

    if not args.pcap and not args.interface:
        print("Error: Must specify either --pcap file or --interface for capture")
        sys.exit(1)

    try:
        # Initialize analyzer
        analyzer = WiresharkAnalyzer(args.pcap, args.interface)

        # Capture traffic if interface specified
        if args.interface and not args.pcap:
            analyzer.capture_traffic(args.duration)

        # Generate analysis repuerto
        repuerto_file = analyzer.generate_repuerto(args.output)

        print(f"Analysis completed successfully!")
        print(f"Repuerto available at: \\\\{repuerto_file\\\\}")

    except Exception as e:
        print(f"Error: \\\\{e\\\\}")
        sys.exit(1)

if __name__ == "__main__":
    main()

Integration ejemplos

SIEM Integration

#!/bin/bash
# Wireshark SIEM integration script

# configuración
INTERFACE="eth0"
CAPTURE_DURATION="300"  # 5 minutes
SPLUNK_HEC_URL="https://splunk.company.com:8088/servicios/collector/event"
SPLUNK_token="your-hec-token"
ELASTICSEARCH_URL="http://elasticsearch.company.com:9200"

# Function to send events to Splunk
send_to_splunk() \\\\{
    local event_data="$1"

    curl -k -X POST "$SPLUNK_HEC_URL" \
        -H "autorización: Splunk $SPLUNK_token" \
        -H "Content-Type: application/json" \
        -d "$event_data"
\\\\}

# Function to send events to Elasticsearch
send_to_elasticsearch() \\\\{
    local event_data="$1"
    local index_name="wireshark-$(date +%Y.%m.%d)"

    curl -X POST "$ELASTICSEARCH_URL/$index_name/_doc" \
        -H "Content-Type: application/json" \
        -d "$event_data"
\\\\}

# Capture and analyze traffic
capture_and_analyze() \\\\{
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local capture_file="/tmp/capture_$timestamp.pcap"

    echo "Starting packet capture..."

    # Capture traffic
    timeout $CAPTURE_DURATION tshark -i $INTERFACE -w $capture_file

    if [ ! -f "$capture_file" ]; then
        echo "Capture failed"
        return 1
    fi

    echo "Analyzing captured traffic..."

    # Extract HTTP requests
    tshark -r $capture_file -Y "http.request" -T fields \
        -e frame.time -e ip.src -e ip.dst -e http.request.method \
        -e http.request.uri -e http.host -e http.user_agent|\
    while IFS=

## solución de problemas

### Common Issues

**Permission Issues:**
```bash
# Add user to wireshark group
sudo usermod -a -G wireshark $USER

# Set capabilities for dumpcap
sudo setcap cap_net_raw,cap_net_admin+eip /usr/bin/dumpcap

# Check current capabilities
getcap /usr/bin/dumpcap

# Alternative: Run as root (not recommended)
sudo wireshark

Interface Issues:

# List available interfaces
tshark -D
ip link show

# Check interface status
ip addr show eth0

# Bring interface up
sudo ip link set eth0 up

# Check for conflicting procesoes
sudo lsof -i :interface
sudo netstat -tulpn|grep :interface

Performance Issues:

# Increase buffer size
tshark -i eth0 -B 100  # 100MB buffer

# Use ring buffer for continuous capture
tshark -i eth0 -b filesize:100000 -b files:10 -w capture.pcap

# Optimize display filters
# Use specific filters instead of broad ones
# ejemplo: tcp.puerto == 80 instead of tcp

# Disable name resolution for performance
tshark -i eth0 -n -w capture.pcap

Performance Optimization

Optimizing Wireshark performance:

# Memory Optimization
# Edit > Preferencias > Appearance > Layout
# Reduce pane sizes for better performance

# Capture Optimization
# Use capture filters to reduce data
# Capture only necessary protocolos
# Use appropriate buffer sizes

# Display Optimization
# Limit packet list size
# Use specific display filters
# Disable unnecessary columns

# File Handling
# Use multiple smaller files instead of one large file
# Compress capture files when storing
# Regular cleanup of old captures

Security Considerations

Operational Security

Data Protection: - Encrypt captured packet files containing sensitive data - Implement secure data retention policies for network captures - Control access to packet capture data and analysis results - Secure transmission and storage of network forensics data - Regular cleanup of temporary capture files

Legal and Ethical Considerations: - Only capture traffic on networks you own or have permission to monitor - Understand legal requirements for network monitoring in your jurisdiction - Implement proper data handling procedures for captured traffic - Respect privacy and confidentiality of network communications - Document monitoring activities for compliance purposes

Network Security

Monitoring Best Practices: - Deploy network monitoring in strategic locations - Implement network segmentation for monitoring infrastructure - Use dedicated monitoring interfaces when possible - Regular security assessments of monitoring systems - Integration with network intrusion detection systems

referencias

  1. Wireshark Official documentación
  2. Wireshark User's Guide
  3. Network protocolo Analysis
  4. Packet Analysis Best Practices
  5. Network Forensics Guide

\t' read -r time src_ip dst_ip method uri host user_agent; do if [ -n "$time" ]; then event_json=$(cat << EOF \\{ "time": "$time", "source": "wireshark", "sourcetype": "wireshark:http", "event": \\{ "timestamp": "$time", "src_ip": "$src_ip", "dst_ip": "$dst_ip", "method": "$method", "uri": "$uri", "host": "$host", "user_agent": "$user_agent", "event_type": "http_request" \\} \\} EOF )

        send_to_splunk "$event_json"
        send_to_elasticsearch "$event_json"
    fi
done

# Extract DNS queries
tshark -r $capture_file -Y "dns.banderas.response == 0" -T fields \
    -e frame.time -e ip.src -e dns.qry.name -e dns.qry.type|\
while IFS=

solución de problemas

Common Issues

Permission Issues: CODE_BLOCK_15

Interface Issues: CODE_BLOCK_16

Performance Issues: CODE_BLOCK_17

Performance Optimization

Optimizing Wireshark performance:

CODE_BLOCK_18

Security Considerations

Operational Security

Data Protection: - Encrypt captured packet files containing sensitive data - Implement secure data retention policies for network captures - Control access to packet capture data and analysis results - Secure transmission and storage of network forensics data - Regular cleanup of temporary capture files

Legal and Ethical Considerations: - Only capture traffic on networks you own or have permission to monitor - Understand legal requirements for network monitoring in your jurisdiction - Implement proper data handling procedures for captured traffic - Respect privacy and confidentiality of network communications - Document monitoring activities for compliance purposes

Network Security

Monitoring Best Practices: - Deploy network monitoring in strategic locations - Implement network segmentation for monitoring infrastructure - Use dedicated monitoring interfaces when possible - Regular security assessments of monitoring systems - Integration with network intrusion detection systems

referencias

  1. Wireshark Official documentación
  2. Wireshark User's Guide
  3. Network protocolo Analysis
  4. Packet Analysis Best Practices
  5. Network Forensics Guide

\t' read -r time src_ip query_name query_type; do if [ -n "$time" ]; then event_json=$(cat << EOF \\{ "time": "$time", "source": "wireshark", "sourcetype": "wireshark:dns", "event": \\{ "timestamp": "$time", "src_ip": "$src_ip", "query_name": "$query_name", "query_type": "$query_type", "event_type": "dns_query" \\} \\} EOF )

        send_to_splunk "$event_json"
        send_to_elasticsearch "$event_json"
    fi
done

# Clean up
rm -f $capture_file

echo "Analysis completed and events sent to SIEM"

\\}

Main execution

while true; do capture_and_analyze sleep 60 # Wait 1 minute before next capture done ```

solución de problemas

Common Issues

Permission Issues: CODE_BLOCK_15

Interface Issues: CODE_BLOCK_16

Performance Issues: CODE_BLOCK_17

Performance Optimization

Optimizing Wireshark performance:

CODE_BLOCK_18

Security Considerations

Operational Security

Data Protection: - Encrypt captured packet files containing sensitive data - Implement secure data retention policies for network captures - Control access to packet capture data and analysis results - Secure transmission and storage of network forensics data - Regular cleanup of temporary capture files

Legal and Ethical Considerations: - Only capture traffic on networks you own or have permission to monitor - Understand legal requirements for network monitoring in your jurisdiction - Implement proper data handling procedures for captured traffic - Respect privacy and confidentiality of network communications - Document monitoring activities for compliance purposes

Network Security

Monitoring Best Practices: - Deploy network monitoring in strategic locations - Implement network segmentation for monitoring infrastructure - Use dedicated monitoring interfaces when possible - Regular security assessments of monitoring systems - Integration with network intrusion detection systems

referencias

  1. Wireshark Official documentación
  2. Wireshark User's Guide
  3. Network protocolo Analysis
  4. Packet Analysis Best Practices
  5. Network Forensics Guide