cybersecurity fundamentals

Network Security and Threat Defense

In this chapter, we'll explore network security principles and practical threat defense mechanisms.

Network Security Fundamentals

Network Segmentation

# Create VLANs (Cisco IOS)
configure terminal
vlan 10
name USERS
exit
vlan 20
name SERVERS
exit
vlan 30
name DMZ
exit

# Configure trunk port
interface GigabitEthernet0/1
switchport mode trunk
switchport trunk allowed vlan 10,20,30

Firewall Configuration

iptables Rules

# Basic firewall setup
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH from specific network
iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 22 -j ACCEPT

# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Drop all other incoming traffic
iptables -P INPUT DROP

# Save rules
iptables-save > /etc/iptables/rules.v4

pfSense Configuration

<filter>
  <rule>
    <interface>wan</interface>
    <type>pass</type>
    <ipprotocol>inet</ipprotocol>
    <protocol>tcp</protocol>
    <source>
      <any></any>
    </source>
    <destination>
      <network>192.168.1.0/24</network>
      <port>443</port>
    </destination>
    <descr>Allow HTTPS to internal network</descr>
  </rule>
</filter>

Intrusion Detection and Prevention

Snort IDS Configuration

# snort.conf
# Network variables
ipvar HOME_NET 192.168.1.0/24
ipvar EXTERNAL_NET !$HOME_NET

# Rule sets
include $RULE_PATH/local.rules
include $RULE_PATH/emerging-threats.rules

# Preprocessor configuration
preprocessor stream5_global: max_tcp 8192
preprocessor http_inspect: global
preprocessor ssh: server_ports 22

Custom Snort Rules

# local.rules
# Detect SQL injection attempts
alert tcp $EXTERNAL_NET any -> $HOME_NET 80 (msg:"SQL Injection Attempt"; \
  flow:to_server,established; content:"%27"; nocase; \
  pcre:"/(\%27)|(\')|(\-\-)|(%23)|(#)/i"; \
  classtype:web-application-attack; sid:1000001; rev:1;)

# Detect port scanning
alert tcp $EXTERNAL_NET any -> $HOME_NET any (msg:"Potential Port Scan"; \
  flags:S; threshold:type threshold, track by_src, count 5, seconds 60; \
  classtype:attempted-recon; sid:1000002; rev:1;)

Secure Communication

OpenVPN Server Configuration

# server.conf
port 1194
proto udp
dev tun
ca ca.crt
cert server.crt
key server.key
dh dh2048.pem
server 10.8.0.0 255.255.255.0
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 8.8.8.8"
keepalive 10 120
cipher AES-256-CBC
auth SHA256
comp-lzo
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
verb 3

SSL/TLS Implementation

import ssl
import socket

def create_ssl_server():
    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    context.load_cert_chain(certfile="server.crt", keyfile="server.key")
    
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind(('0.0.0.0', 8443))
        sock.listen(5)
        
        with context.wrap_socket(sock, server_side=True) as ssock:
            while True:
                client_socket, addr = ssock.accept()
                handle_client(client_socket)

def handle_client(client_socket):
    try:
        data = client_socket.recv(1024)
        # Process encrypted data
        response = process_data(data)
        client_socket.send(response)
    finally:
        client_socket.close()

Security Monitoring

ELK Stack Configuration

Logstash Pipeline

input {
  beats {
    port => 5044
  }
}

filter {
  if [type] == "syslog" {
    grok {
      match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" }
    }
    date {
      match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
    }
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "logstash-%{+YYYY.MM.dd}"
  }
}

Elasticsearch Security

# elasticsearch.yml
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.transport.ssl.verification_mode: certificate
xpack.security.transport.ssl.keystore.path: elastic-certificates.p12
xpack.security.transport.ssl.truststore.path: elastic-certificates.p12

Threat Intelligence Integration

MISP Integration

from pymisp import PyMISP

def analyze_threat(indicator):
    misp = PyMISP('https://misp.example.com', 'your_api_key')
    
    # Search for indicators
    results = misp.search(value=indicator)
    
    threats = []
    for result in results:
        threat = {
            'type': result['Event']['info'],
            'tags': [tag['name'] for tag in result['Event']['Tag']],
            'attributes': result['Event']['Attribute']
        }
        threats.append(threat)
    
    return threats

def report_incident(incident_data):
    misp = PyMISP('https://misp.example.com', 'your_api_key')
    
    event = misp.new_event(
        distribution=0,  # Your organization only
        threat_level_id=2,  # Medium
        analysis=2,  # Completed
        info=f"Security Incident: {incident_data['title']}"
    )
    
    # Add attributes
    misp.add_named_attribute(
        event['Event']['id'],
        'ip-src',
        incident_data['source_ip']
    )
    
    return event['Event']['id']

Hands-on Exercise: Building a Security Operations Center

  1. Set up Security Monitoring
# Install Security Onion
sudo sosetup

# Configure network interfaces
sudo so-allow
sudo so-status

# Start services
sudo so-start
  1. Configure Alert Rules
# Wazuh agent configuration
<agent_config>
  <localfile>
    <location>/var/log/auth.log</location>
    <log_format>syslog</log_format>
  </localfile>
  
  <rootcheck>
    <frequency>43200</frequency>
    <skip_nfs>yes</skip_nfs>
  </rootcheck>
  
  <syscheck>
    <frequency>43200</frequency>
    <directories check_all="yes">/etc,/usr/bin,/usr/sbin</directories>
    <ignore>/etc/mtab</ignore>
    <ignore>/etc/hosts.deny</ignore>
  </syscheck>
</agent_config>
  1. Implement Incident Response
def handle_security_incident(incident):
    # Log incident
    logging.critical(f"Security Incident Detected: {incident['type']}")
    
    # Isolate affected systems
    isolate_systems(incident['affected_systems'])
    
    # Collect forensics
    evidence = collect_forensics(incident['affected_systems'])
    
    # Create incident ticket
    ticket_id = create_incident_ticket(incident, evidence)
    
    # Notify security team
    notify_security_team(ticket_id, incident)
    
    return ticket_id

def isolate_systems(systems):
    for system in systems:
        # Implement network isolation
        subprocess.run([
            'iptables',
            '-I', 'FORWARD',
            '-s', system,
            '-j', 'DROP'
        ])

In the next chapter, we'll explore advanced topics in application security and secure coding practices.