Networks and Security - UniPDconti/teaching/NS1617/1_lecture_ALL.pdf32 Step 3: Vulnerability...
Transcript of Networks and Security - UniPDconti/teaching/NS1617/1_lecture_ALL.pdf32 Step 3: Vulnerability...
1
Networks and Security“Key Security Concepts, tools & co.”
Mauro ContiDepartment of MathematicsUniversity of [email protected]
2
What “secure” means?
3
● Some Key concepts in security
● Vulnerability Assessment (and its best practices)
● NESSUS
● Intrusion Detection
● SNORT
● Linux Networking Tools
● SSL (usage) in(security): a practical attack to Android
Overview
4
● 1) Security is not just “a product” (e.g. a firewall); it is rather a “process”, which needs to be managed properly
● 2) Nothing is 100% secure● (do we need it? How much it would cost?)● Example: credit cards
Some key concepts to remember
“The three golden rules for ensuring computer security: do not own a computer; do not power it on; and do not use it.” – Robert (Bob) Morris (Former NSA Chief Scientist).
5
● 3) The security of a system is equivalent to the security of its less secure component(rule of the weakest link)
Some key concepts to remember
6
● 4) Security by obscurity never works● 5) Cryptography is a powerful tool but...
it is not enough!
Some key concepts to remember
"The protection provided by encryption is based on the fact that most people would rather eat liver than do mathematics"
Bill Neugent
7
● 4) Security by obscurity never works● 5) Cryptography is a powerful tool but...
it is not enough!
Some key concepts to remember
"The protection provided by encryption is based on the fact that most people would rather eat liver than do mathematics"
Bill Neugent
8
● 4) Security by obscurity never works● 5) Cryptography is a powerful tool but...
it is not enough!
Some key concepts to remember
"The protection provided by encryption is based on the fact that most people would rather eat liver than do mathematics"
Bill Neugent
9
● 4) Security by obscurity never works● 5) Cryptography is a powerful tool but...
it is not enough!
Some key concepts to remember
"The protection provided by encryption is based on the fact that most people would rather eat liver than do mathematics"
Bill Neugent
10
● 4) Security by obscurity never works● 5) Cryptography is a powerful tool but...
it is not enough!
Some key concepts to remember
"The protection provided by encryption is based on the fact that most people would rather eat liver than do mathematics"
Bill Neugent
11
“Given a choice between dancing pigs and security, users will pick dancing pigs everytime.” – Prof. Ed Felten (Princeton University)
“If the computer prompts him with a warning screen like: "The applet DANCING PIGS could contain malicious code that might do permanent damage to your computer, steal your life's savings, and impair your ability to have children," he'll click OK without even reading it. Thirty seconds later he won't even remember that the warning screen even existed”- Bruce Schneier
Some key concepts to remember
● 6) Do not rely on users!
12
So, what “secure” means? A network/system is secure when...
13
Basic security properties
• Confidentiality: to prevent unauthorised disclosure of the information
• Integrity: to prevent unauthorised modification of the information
• Availability: to guarantee access to information
• Authentication: to prove the claimed identity can be Data or Entity authentication
14
Auxiliary security properties
• Non repudiation: to prevent false denial of performed actions
• Authorisation: ”What Alice can do” • Auditing: to securely record evidence of
performed actions• Attack-tolerance: ability to provide some
degree of service after failures or attacks• Disaster Recovery: ability to recover a safe
state• Key-recovery, key-escrow, .....• Digital Forensics
15
Security mechanisms• Random Numbers (e.g. for Initialization Vectors)• Pseudo Random Numbers• Encryption/Decryption• Hash functions• Hash chain (inverted)• Message integrity code (MIC)• Message authentication code (MAC and HMAC)• Digital signatures
– Non repudiation • Key exchange (establishment) protocols• Key distribution protocols• Time stamping
16
Types of attacker
insiders
outsiderssecurity domain
adm1adm2
security domain and admin domain may differ
17
Types of attack
• Passive: the attacker can only read any information
– Tempest (signal intelligence)– Packet Sniffing
• Active: the attacker can read, modify, generate, destroy any information
18
TEMPEST
19
TEMPEST
• More recent attack approachesBig Data => User profiling
20
Vulnerability Assessment
21
A Quick Vocabulary Lesson
Vulnerability: A flaw or weakness in system security procedures, design, implementation, or internal controls that may result in a security breach or a violation of the system's security policy.
Threat: The potential for a specific vulnerability to be exercised
– either intentionally or accidentally (e.g. failure)
Control: measures taken
– to prevent, detect, minimize, or eliminate risk
– to protect the Integrity, Confidentiality, and Availability of information.
Vulnerability Assessment: The process of identifying, quantifying, and prioritizing (or ranking) the vulnerabilities in a system.
22
Vulnerability Assessment Basics
Vulnerability Assessment is a subset of Vulnerability Management
Proactive vs. reactive
Vulnerability assessment vs. penetration testing
Examples of IT vulnerability assessments
23
Why Do Vulnerability Assessments?
System accreditation
Risk assessment
Network auditing
Provide direction for security controls
Can help justify resource expenditure
Can provide greater insight into process and architecture
Compliance checking
Continuous monitoring
24
Vulnerabilities
Where do they come from?Flaws in software
Faulty configuration
Weak passwords
Human error
• Inappropriately assigned permission levels
• System inappropriately placed in infrastructure/environment
Vulnerabilities don’t go away by themselves
25
Best Practices
Establish chain of command/authority
Create official purpose and procedures
Decide on schedule
Build your reputation and relationships
26
Best Practices
Think in terms of risk
Document everything!
Know your environment
Be prepared
27
CERT Methodology
...CERT: Computer Emergency Response/Readiness Team
28
CERT Methodology
1) Setup
2) Test Execution
3) Vulnerability Analysis
4) Reporting
5) Remediation
Repeat!
29
Step 1: Setup
Begin documentation
Secure permission
Update tools
Configure tools
30
Step 2: Test Execution
Run the tools
Document as you go
Run a packet capture while running the assessment tools
31
Step 3: Vulnerability Analysis
Human interpretation is required to make results meaningful
That interpretation includes
• Assessing risk presented by vulnerabilities
• Comparing the results to security policy
• Verifying vulnerabilities
• Prioritizing vulnerabilities
32
Step 3: Vulnerability Analysis
Assessing risk and prioritizing vulnerabilitiesA subjective process but you can be objective by using CVSS
Common Vulnerability Scoring System (CVSS)
• NIST provides a CVSS calculator at http://nvd.nist.gov/cvss.cfm?calculator
• By adjusting the different values based on the characteristics of the vulnerability, the CVSS score will go either up or down depending on the risk presented to your specific environment
33
Step 3: Vulnerability Analysis
Researching vulnerabilities
The Common Vulnerabilities and Exposures (CVE) numbers
• http://cve.mitre.org
• Some tools will provide the CVE number
• CVE numbers can be used to look up additional vulnerability information from trusted sources
– US-CERT Vulnerability Notes Database: http://www.kb.cert.org/vuls/
– National Vulnerability Database: http://nvd.nist.gov
– Secunia.com
– Vendor Sites
34
Step 3: Vulnerability Analysis
35
Step 3: Vulnerability Analysis
Researching vulnerabilities
Without a CVE number
• Security Sites
• Security email list archives http://seclists.org
Be careful who you get information from/trust• Best to go to a known good security site (e.g. sans.org)
CERIAS Cassandra service - https://cassandra.cerias.purdue.edu
Verify with a trusted source or multiple sources if possible
36
Step 3: Vulnerability Analysis
Causes of errors during vulnerability analysis
Environmental Issues
Timing Issues
Privilege Issues
Tool Issues
People/knowledge Issue
37
Step 3: Vulnerability Analysis
Error types
False Positive - Identifying a vulnerability that is not present
False Negative - Failing to identify the presence of a vulnerability
Error prevention
Use several different tools for verification
Examine the traffic generate by tools
Consult with the system owner/administrator
38
Step 4: Reporting
Goals
Present a meaningful summary of the vulnerabilities found
Prioritize and explain vulnerabilities
Provide possible remediation suggestions
39
Step 4: Reporting
Anatomy of a reportHeaderSummaryList of vulnerabilities - For each vulnerability, at a minimum provide:
• Unique tracking number• Risk level
– High - Immediate action – Medium - Action required– Low - Action recommended
• Brief descriptionAppendices - At a minimum the following two should be included
• Vulnerability details• Assessment Setup
40
Step 4: Reporting
MetricsTracking progress of key metrics over time allows progress to be quantified
Also a good idea to tie metrics to cost savings
Examples:• Number of vulnerabilities found by criticality• Average number of vulnerabilities found• Number of vulnerabilities remediated• Time from vulnerability discovery to remediation• Time per assessment• Total assessments done
41
Step 4: Reporting
Best Practices
Standardization
Know your audience
Avoid fluff
Prioritize by risk
Track progress
42
Step 5: Remediation
Vulnerability remediation is the process of fixing vulnerabilities
Pick the issues you want to fix because you may not have enough resources to fix them all
Remediation choicesFor every vulnerability there are three choices for remediation:
• Fix - eliminate vulnerability altogether
• Accept - the cost of fixing outweighs the risk
• Mitigate - don't outright fix but use additional layers of security to lessen the risk presented by the vulnerability
43
Step 5: Remediation
Types of remediationManual
• Pros - less likely to cause system problems• Cons - does not scale well, time consuming
Automatic remediation• Pros - scales very well• Cons - may cause system problems, may not actually remediate, potential for
breaking something is greater
Manual - unique or critical system
Automatic - many similar items
44
Step 5: Remediation
Remediation PlanningPlan for remediating all vulnerabilities found in the system
Plan should include:
• Whether to fix, mitigate or accept vulnerabilities
• Whether to use automatic or manual remediation
• Strategy to mitigate any remaining vulnerabilities
• Justification for accepting any vulnerability
45
Step 5: Remediation
Test remediation on a dev instance before implementing on a production system
Verification
Cooperation required for successful remediation
Don’t forget change management
46
Vulnerability Assessment... Tools
Port Scanning
Protocol analyzer
Vulnerability scanner
Password Cracking
Penetration Testing
47
Port Scanning
Scanner analyzes the ports on a network and determines if they are:Open: actively listening and accepting connectionsClosed: port is not accepting connectionsFiltered : no response from the scanned system.
Tool: nMap(Windows/Linux)
48
Port Scanning
49
nMAP
50
nMAP
51
Protocol Analyzers
Also known as Packet SnifferLogs network trafficAnalyzes packetsAttempts to decrypt packets
Tool: WireShark(Windows/Linux)
52
WireShark
53
Vulnerability Scanner
Software designed to:• Map all network devices• Scan network/system• Find Vulnerabilities • Give suggestions on how to make secure
Doubled Edge SwordTool: Nessus
54
Password Cracking
Software that employs various algorithms in an attempt to discover passwords. Keyloggers, Cross-Scripting, Dictionary Tables, Rainbow tables.Tool: Hydra (Online), Rainbow Crack (Offline)
55
Hydra
56
Penetration Testing
Method of evaluating the security of a computer system or network by simulating an attack from a malicious source.“Ethical Hacker” is hired to performSecurity AuditExploit vulnerabilitiesHelp secure the week points.
Tool: Back Track 5 (linux distro for PenTest)
57
NESSUS
58
NESSUS: Installation
59
NESSUS: Installation
60
NESSUS: Installation
61
NESSUS: Installation
Once downloaded, let's install the package
62
NESSUS: Installation
Add the user...
...and register your code (obtained via the website)...
63
NESSUS: Installation
Start Nessus...
...and verify that it is running...
64
NESSUS
https://SERVERADDR:8834
65
NESSUS
66
NESSUS
67
NESSUS
68
NESSUS
69
NESSUS
70
NESSUS
71
NESSUS
72
Nmap
nmap –h
HOST DISCOVERY: -sP: Ping Scan - go no further than determining if host is online
-PN: Treat all hosts as online -- skip host discovery -PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports -n/-R: Never do DNS resolution/Always resolve [default: sometimes]SCAN TECHNIQUES: -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans -sU: UDP Scan -sN/sF/sX: TCP Null, FIN, and Xmas scansPORT SPECIFICATION AND SCAN ORDER: -p <port ranges>: Only scan specified ports -F: Fast mode - Scan fewer ports than the default scanSERVICE/VERSION DETECTION: -sV: Probe open ports to determine service/version infoSCRIPT SCAN: -sC: equivalent to --script=default --script=<Lua scripts>: <Lua scripts> is a comma separated list of directories, script-files or script-categoriesOS DETECTION: -O: Enable OS detectionOUTPUT: -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3, and Grepable format, respectively, to the given filename.
SYN scan...
Done via raw IP packets
Scanner generates a SYN packet.
If the target port is open, it will respond with a SYN-ACK packet.
The scanner host responds with a RST packet, closing the connection before the handshake is completed.
=> connection would not appear in the logs
...but IDS can detect this!
73
Nmap
nmap -sS -sV -O -F -n 10.0.40.69Starting Nmap 5.10BETA1 ( http://nmap.org ) at 2010-01-04 17:20 GTB Standard TimeNmap scan report for 10.254.40.69Host is up (0.00011s latency).Not shown: 98 filtered portsPORT STATE SERVICE VERSION139/tcp open netbios-ssn445/tcp open microsoft-ds Microsoft Windows XP microsoft-dsMAC Address: 00:0C:29:86:DF:91 (VMware)Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed portDevice type: general purposeRunning (JUST GUESSING) : Microsoft Windows XP|2000|2003 (97%)Aggressive OS guesses: Microsoft Windows XP SP2 (97%), Microsoft Windows XP SP3 (94%), Microsoft Windows 2000 SP4 or Windows XP SP2 or SP3 (94%), Microsoft Windows Server 2003 SP1 or SP2 (93%), Microsoft Windows XP (93%), Microsoft Windows XP SP2 or SP3 (93%), Microsoft Windows 2003 Small Business Server (92%), Microsoft Windows XP Professional SP2 (92%), Microsoft Windows Server 2003 SP2 (92%), Microsoft Windows 2000 SP4 (91%)No exact OS matches for host (test conditions non-ideal).Network Distance: 1 hopService Info: OS: WindowsOS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .Nmap done: 1 IP address (1 host up) scanned in 13.52 seconds
74
Intrusion Detection
75
Detecting Unauthorized Activity on Your Networkbreak-in attempts, successful breakins, suspicious traffic,known attacks, unusual traffic
Two Common Detection Methods: Signature Based, and Anomaly Detection
Two Common Applications:● IDS -- Out-of-Band, Passive Monitoring IDS,
● Notify Me When Something Bad Happens!
● IPS -- In-Line IPS, (Intrusion *Prevention* Systems)● But If I Know It is Bad, Why Not Block it!
See Also: Darknets, and HoneyPots
76
Signature Based• Like Anti-Virus, Not Protected Against Unknown Attacks• Processing Signatures is Resource Intensive• Maintaining Signature Updates Requires Management/Cost
Anomaly Based• Require a "Learning Period"• Can produce false-positives, The Mother's Day Restaurant Effect• May Not Be As Effective On Certain Attacks
77
IDS challenges
• It is difficult to distinguish "good" traffic from "bad" traffic in many cases.
• The closer you are to the Host, the more accurate your detection is going to be. For example, local system event logs, file system change logs, much more reliable
• Firewalls, System Integrity, Anti-Virus... May Take Priority
• IDS -- It's Not a Panacea, But Used Selectively It Can Help You IdentifyProblems
78
79
Intrusion Detection
• Per Intrusion Detection si intende il problema di identificare l'utilizzo o il tentativo di utilizzo di risorse informatiche da parte di persone non autorizzate
• Attenzione: intrusion detection non vuol dire intrusion prevention
80
Introduzione a Snort
• Cosa è Snort?– Snort è uno strumento per l'analisi dei pacchetti che
può funzionare in diverse modalità:• Sniffer• Packet Logger• Network Intrusion Detection System
• È stato sviluppato per soddisfare la necessità di riuscire a realizzare un'analisi del traffico in tempo reale e per un'analisi a posteriore
• Concepito come uno sniffer in grado di produrre un output “orientato al pacchetto” da contrapporre all’output “protocol-dependent” di TCPDump.
81
Introduzione a Snort
∙ Sniffer: “cattura” i pacchetti in transito sulla rete e li visualizza attenendosi alla forma (hex, ASCII..) ed al livello di dettaglio richiesti; è possibile inoltre creare dei filtri (BPF based) per individuare i soli pacchetti di interesse
∙ Packet Logger: i pacchetti “sniffati” possono essere inviati ad un database SQL e/o riportati su file di log nel formato (TCPDump binary format, ASCII) che si preferisce
∙ Network Intrusion Detection System: non tutti i pacchetti in transito sulla rete vengono “loggati” (scrivere in un log) ma solo quelli che vengono ritenuti “ sospetti ”, gli altri vengono scartati (droppati).
82
Caratteristiche di Snort
• Leggero• Portabile (Linux, Windows, MacOS X, Solaris, BSD, IRIX, Tru64, HP-UX, etc)
• Veloce• Altamente configurabile• Free (GPL/Open Source Software)
83
Motore di rilevazione
• Regole basate su “signature”• Diversi moduli sono combinati assieme per realizzare le signatures
• Ampio spettro di rilevazione● Scansioni di sistema, fingerprinting dei
sistemi operativi, buffer overflow, back doors, exploits, etc.
• Il sistema di regole è estremamente flessibile e la creazione di nuove regole è relativamente semplice
84
IDS Implementation Map
FilteringRouter
(Perimeter Logs)
Firewall(Perimeter
Logs)
Generic Server(Host-Based IDS)
(Snort 2.0)
Network IDS(Snort)
Internet
Honeypot(Deception System)
Statistical IDS (Snort)
85
Usare Snort
• Ha due diversi modi di funzionare– Passiva
•Sniffer Mode•Packet Logger Mode•NIDS Mode•(Forensic Data Analysis Mode)
– Attiva•Come un IPS, detto Inline (Inline-test)
• Il modo operativo è specificato dalle opzioni passate da riga di comando– Snort cerca automaticamente di andare in modalità NIDS se non
ci sono opzioni
• Il file di configurazione è solitamente /etc/snort.conf
86
Usare Snort – Sniffer Mode
• Funziona come tcpdump• Decodifica tutti i pacchetti e li trasmette sullo standard output
• Permette di applicare dei filtri in modo da mostrare solo i pacchetti interessati all'interno del traffico
• Si avvia con sudo snort -v oppure -vd oppure -vde
(v: verbose, d: app layer data; e: link layer header)
87
Usare Snort – Logger Mode
● Permette di salvare i pacchetti sniffati su disco
● Permette di salvare i paccheti in diversi formati:
● ASCII, tcpdump, XML, SQL, etc.● Permette di analizzare i pacchetti salvati
in modo da fare un'analisi a posteriori alla ricerca di attività maliziose
● Si avvia con l'opzione -lsudo snort -vde -l /var/log/snort
88
Usare Snort – NIDS Mode● Utilizza le combinazioni precedenti assieme ad
una serie di plug-ins per analizzare il traffico allo scopo di realizzare misuse e anomaly detection
● Può identificare attacchi di tipo portscan, IP defragmentation, oppure realizzare riassemblamento di flussi, analisi di livello application, etc.
● Si avvia con l'opzione -csnort -c snort.conf
osudo snort -c /etc/snort/snort.conf
(possiamo vedere che il file snort.conf ha degli “include” a delle regole, e.g.,
include $RULE_PATH/ddos.rules)
89
Usare Snort – NIDS Mode
L'output (gli alert) di snort in NIDS mode può essere letto in /var/log/snort/alert
e.g.:
90
Usare Snort – IPS mode
● Detta “inline”● Funziona come un Intrusion Prevention
System poiché può scartare i pacchetti al volo
● Viene attivato con l'opzione -Q econfig policy_mode:inline
INLINE:
snort -Q config policy_mode:inline
PASSIVE:
snort -Q config policy_mode:tap
INLINE TEST:
snort –enable-inline-test config policy_mode:inline_test
91
● Si considera che gli attacchi sono eventi anomali (infrequenti), e si estende questa osservazione ipotizzando che ogni evento anomalo sia un attacco
● Quindi, si raccolgono gli eventi considerati “normali“( frequenti ) e si ipotizza che tutto ciò che non ricade in questo insieme sia un attacco
● Tuttavia, possono essere identificati come attacchi anche eventi che non corrispondono ad attacchi reali
● In questo caso si parla di falsi positivi
Anomaly detection
92
● Il rilevamento di falsi positivi puo’ portare all’attivazione di contromisure da parte dell’IDS anche quando queste non sono effettivamente richieste
● Esiste anche il problema dei falsi negativi, ovvero quando un attaccante riesce a compiere il suo lavoro tramite eventi normali
Anomaly detection
93
Misuse detection
● In questo paradigma si individuano a priori gli eventi che caratterizzano gli attacchi e si codificano all’ interno dell' IDS
● Si individua quindi un insieme di eventi “patologici”, ovvero che sono associati ad aggressioni con probabilità molto alta.
● Sulla base di questo insieme l'IDS identifica gli attacchi potenziali o reali
● Se un attacco non è associato ad eventi riconosciuti come patologici, allora non viene rilevato
94
Anomaly vs Misuse
● I due approcci sono l'uno il duale dell'altro:
● nell’anomaly detection definiamo gli attacchi come l'insieme complementare degli eventi normali
● nel misuse detection l'insieme degli eventi accettati (e quindi ritenuti normali) è definito come complementare dell'insieme degli attacchi
95
Anomaly vs Misuse● Apparentemente l‘anomaly detection
garantisce una maggiore sicurezza rispetto all’approccio misuse, perché il suo tasso di falsi negativi è più basso rispetto al misuse detection.
● La realtà però è diversa poiché il numero di falsi positivi - potenzialmente enorme - tende a nascondere le vere intrusioni
● Inoltre sono richieste quindi notevoli capacità (e tempo) a chi gestisce l'IDS per discriminare tra veri e falsi allarmi.
● Infine, si rischia di bloccare molte azioni legittime solo perché rare, con conseguente aumento dell'intrusività dell’IDS.
96
NIDS
● Snort è basato sull'uso di un insieme di regole e plugin che determinano gli eventi che devono essere considerati anomali
● Snort ha una comunità molto attiva per lo sviluppo delle regole
● Inoltre offre la possibilità di funzionare in modalità statistica e verificare l'uso corretto dei protocolli
97
Architettura
98
Architettura
99
Preprocessor● I preprocessor, o plug-in di input, sono
dei moduli software in grado di effettuare, su singoli pacchetti e/o su loro sequenze, delle operazioni complesse che non posso essere svolte semplicemente applicando le regole.
● Ciascun plugin introduce un insieme di funzionalità il cui comportamento viene controllato da un certo numero di opzioni.
● Ogni pacchetto viene “vagliato” da TUTTI i preprocessor attivi: in questo modo è possibile rilevare attacchi che necessitano di più di un preprocessor per essere segnalati.
100
Preprocessor
● Molti dei preprocessor generano ALERT in caso di attacchi, ma non di rado alcuni di essi segnalano molti falsi positivi ed è pertanto necessario scegliere opportunamente quelli che si vogliono utilizzare e configurarli al meglio per la propria rete.
● Eseguire Snort senza alcun preprocessor vuol dire, tra le altre cose, lasciare che ciascun pacchetto venga considerato indipendentemente da tutti gli altri e questo non permette di rilevare la maggior parte degli attacchi, basati su sequenze precise di pacchetti
101
Esempi di preprocessorFlow
● Serve a classificare i flussi di dati. Viene poi utilizzato da altri plugin (ad esempio sfportscan) come base per successive analisi.
● Per flusso intende, in IPv4 un insieme di pacchetti tali che abbiano gli stessi valori nei campi ip_proto, source_ip,source_port, destination_ip e destination_port.
● Il “lavoro” di flow costituisce l’input per le analisi effettuate da altri plugins per la classificazione
Stream4● Riassembla i flussi di dati TCP e rileva tutti i
pacchetti anomali, identificando vari tipi di portscan, tentativi di OS fingerprinting, ed altre anomalie varie legate a possibili attacchi
102
Esempi di preprocessorDecoding e Normalizing Protocol: http_inspect,
RPC_decode, telnet_decode
Si occupano della normalizzazione dei pacchetti prima che questi siano passati al detection engine.
Tipicamente convertono dei caratteri esadecimali in ASCII per la rimozione di “trucchi” con UNICODE che potrebbero confondere (eludere) le regole
Esempio di normalizzazione:Supponiamo di avere una regola che faccia content matching alla
ricerca della stringa “/bin/bash” per riconoscere attacchi volti alla conquista di una shell remota.
Se snort non effettuasse normalizzazione l’attaccante, utilizzando la codifica UNICODE per il carattere /, potrebbe inviare la stringa %2Fbin%2Fbash , ed eludere l’IDS.
103
Output modules
● Questi particolari moduli software consentono di poter scegliere come, e dove, si vogliono registrare i dati (sia pacchetti che alert) rilevati da snort.
● Come per i preprocessor, ciascun plugin di output supporta un insieme di funzionalità e la relativa serie di opzioni di configurazione
● Esempi: log_tcpdump, alert_full, alert_fast, database
104
Regole per il Detection engine● Il vero cuore di snort è il detection engine ovvero il
motore di analisi per il rilevamento di traffico sospetto.
● E’ un elemento del quale possiamo anche customizzare il comportamento integrando il ruleset standard con delle regole personalizzate, composte utilizzando un linguaggio relativamente semplice ma piuttosto potente
● Si possono generare degli allarmi, eseguire altre azioni, registrare i pacchetti, sulla base di una enorme lista di proprietà sia dei pacchetti stessi che dei flussi di dati che le varie funzionalità permettono di identificare.
● Di fatto il detection engine prende in ingresso i pacchetti già “normalizzati ” e processati dai plugin di input per effettuare su di essi il controllo rispetto al rule-set a disposizione
● La sinergia preprocessor e detection engine permette di creare condizioni e controlli anche molto complessi
105
Regole
● Ogni regola è composta da un header e da un insieme di opzionialert tcp ![192.168.1.0/24,10.1.1.0/24] any ->\[192.168.1.0/24,10.1.1.0/24] 111
\ (content: "|00 01 86 a5|"; msg:"external mountd access";)
Vediamo ad esempio qualche regola in/etc/snort/rules/ e.g. il file
chat.rules
header
opzioni
106
Azioni possibili● alert
● genera un alert (usando il metodo di alerting scelto), e poi fa il log del pacchetto
● log
● fa il log del pacchetto● pass
● ignora il pacchetto● activate
● genera un alert e poi attiva una regola dynamic● dynamic
● rimane inattiva finchè non è attivata da una regola activate, poi agisce come un log
107
Azioni possibili in modalità inline
● drop – blocca e fa il log del pacchetto● reject – blocca il pacchetto, fa il log e
invia● un reset della connessione TCP se il
protocollo è TCP● un pacchetto ICMP di port unreachable se il
protocollo è UDP● sdrop – blocca il pacchetto senza fare il
log
108
Opzioni
● Le opzioni sono organizzate in quattro tipi● General – Forniscono informazioni sulla
regola senza avere alcun effetto sulla detection
● Payload – Ricercano all'interno del payload del pacchetto delle informazioni specifiche. Possono essere anche combinate tra loro
● Non-payload – Ricercano all'interno dei dati che non sono payload
● Post-detection – Specificano delle operazioni da fare dopo l'attivazione della regola
109
Esempi di opzioni● General
● msg – specifica un messaggio da inserire nel log● sid – specifica un identificativo per la regola
● Payload
● content – specifica i dati da cercare nel contenuto del pacchetto
● Non-payload
● dsize – testa la dimensione del pacchetto● ttl – testa il valore del time to live
● Post-detection
● logto – specifica un file alternativo in cui fare il log● tag – specifica informazioni aggiuntive per il file di
log
110
SNORT – Examples
111
Esercitazione Snort
● Snort parte di default con una lunga serie di opzioni
● Iniziamo con qualcosa di più semplice● Configuriamo Snort in modo che rilevi i
ping● Creiamo/modifichiamo il file
/etc/snort/snort-ping.conf● Inseriamo la riga
include /etc/snort/icmp-test.rules
112
Esercitazione Snort
● Creiamo/modifichiamo il file/etc/snort/icmp-test.rules
● Inseriamo la regolaalert icmp any any -> any any
(msg:"ICMP Packet"; sid:477; rev:3;)
113
Snortalert icmp any any -> any any (msg:"ICMP Packet"; sid:477;
rev:3;)
STRUTTURA ESEMPIO
Azione alert
Protocollo icmp
IP sorgente any
Porta sorgente any
Direzione →
IP destinazione any
Porta destinazione any
(opzioni) (msg:”ICMP Packet”; sid:477; rev:3;)
114
Avviare snort
● Da riga di comando digitiamosudo snort -i eth0 -c
/etc/snort/snort-ping.conf -l /var/log/snort
● Le opzioni:● -i è l'interfaccia da cui sniffare i dati● -c specifica il file di configurazione● -l specifica la directory in cui inserire il log
115
Avviare ping
● Eseguire qualche ping agli host della rete● Variare le caratteristiche del ping
● Consultare man ping per le opzioni● Consultiamo il log degli alert di snort
● less /var/log/snort/alert● Verificare chi ha inviato ping alla propria
macchina e scoprire le caratteristiche dei ping
● Interrompere snort (CTRL+C)
116
Avviare snort
117
Avviare snort
118
Ping alert in Snort
119
Catturare ping anomali● Modificare la regola snort in modo che segnali un allarme in
caso di ping di dimensioni anomale (superiori a 64 byte)
dsize:>64● Avviamo di nuovo snort
● Inviamo qualche ping particolarmente grande agli host della rete
● Consultare man ping per le opzioni-s packetsize
● Specify the number of data bytes to be sent. The default is 56, which translates into 64 ICMP data bytes when combined with the 8 bytes of ICMP header data.
● Consultiamo il log degli alert di snort
● less /var/log/snort/alert● Interrompere snort (CTRL+C)
120
Catturare ping anomali
● Cosa succede quando i ping superano i 1500 byte circa?
● Snort non li rivela più a causa della frammentazione
● Per riuscire a risolvere questo limite bisogna istruire snort in modo che “deframmenti” i pacchetti di echo request/echo reply
● Usiamo un preprocessore
121
Catturare ping frammentati● Modifichiamo il file di configurazione
/etc/snort/snort-ping.conf● Aggiungiamo l'uso del preprocessor
frag2 (OLD): preprocessor frag2
o frag 3preprocessor frag3_global preprocessor frag3_engine
● Modifichiamo il file della regola in modo da catturare soltanto ping superiori a 1500 byte
● Aggiungiamo l'opzione dsize:>1500
122
Aggiungere un modulo output
● Specifichiamo che vogliamo il formato alert full
● Modifichiamo il file di configurazione/etc/snort/snort-ping.conf
● Aggiungiamo l'uso del modulo alert_fulloutput
alert_full:/var/log/snort/alert-snort-ping
123
● Modifichiamo il file/etc/snort/snort.conf
● Modifichiamo la riga che definisce la rete da sniffare
var HOME_NET 192.168.56.0/24● Da riga di comando digitiamo
snort -i eth0 -c /etc/snort/snort.conf -l /var/log/snort
Avviare snort con configurazione di default
124
● ifconfig (ip)● dhclient● ping● netstat (ss)● route (ip r)● Netfilter/iptables
● Practice: install a WiFi/Router. A laptop with Internet connection is provided. Smartphones should be able to connect to WiFi and connect to the Internet through the laptop.(...this set up will be used for the practical Attack in the next practice
exercise)
(Linux) Networking Tools
125
● ifconfig (see also ip)– (interface configurator)– shows/sets properties of network
interfaces
(Linux) Networking Tools
126
(Linux) Networking Tools
MAC address
statistics
device
Maximum Transmission Unit
MAC address
● ifconfig
127
(Linux) Networking Tools
Implicit netmask
● ifconfig
Set/unset (-) promisc mode
Modify MTU for an interface
Activate/deactivate an interface
128
● dhclient– requests to a DHCP server the
assignment of an IP address.• Leases: /var/lib/dhcp/dhclient.leases
(Linux) Networking Tools
UDP Discovery
DHCP svr offering an IP addr.Client requests
the offered addr.Ack for addr. Assignment, with lease time and othre config.
129
● pinguses ICMP ECHO_REQUEST datagram to
elicit an ICMP ECHO_RESPONSE• Remind: ICMP is at network level (3).
ECHO_REQUEST: IP and ICMP header + struct timeval + arbitrary number of ``pad'' bytes used to fill out the packet.
(Linux) Networking Tools
130
● tcpdump (capture packets)● nslookup (resolve DNS)
● traceroute
(Linux) Networking Tools
“second hand” information (this DNS is not in charge of the domain)
IP/port of DNS svr
131
● netstat– Print network connections, routing
tables, interface statistics, masquerade connections, and multicast memberships
– no options: open sockets
– -l (listening ports)
– -s (statistics)
(Linux) Networking Tools
132
● route (netstat -r; ip r)– shows/sets routing tables
(Linux) Networking Tools
* = no gateway
U = upH = hostG = gatewayD = dynamicM = modified
Add a route for net 10.10.10.0/24 with a gw Add a route for net
20.20.20.0/24...
...and a default gw on this network
...flushes the routing table
133
● route (netstat -r; ip r)Problem example...
(Linux) Networking Tools
134
● route (netstat -r; ip r)Problem example...
analysis...
(Linux) Networking Tools
135
● route (netstat -r; ip r)...solution
test!
(Linux) Networking Tools
136
● Netfilter/iptables
– from Linux kernel 2.4.*• (Ipfwadm : Linux kernel 2.0.34)• (Ipchains : Linux kernel 2.2.*)
– Netfilter/Xtables (kernel-space) and iptables (user-space)
– Firewall– NAT– Mangle
(Linux) Networking Tools
137
● Netfilter/iptables concepts– Table
• All the firewall rules– Chain
• List of rules associated with the chain identifier (hook name)
– Match• When a rule’s field match the packet
– Target• Operation to execute on a packet given a
match
(Linux) Networking Tools
138
● Netfilter/iptables– Tables
• filter – for doing the actual packet filtering. This is
the default table if you do not specify one when entering rules.
• nat– for rewriting packet source and/or
destination• mangle table
– for altering packet headers and/or contents• raw
– for avoiding connection tracking, the NOTRACK target can be used
(Linux) Networking Tools
139
● Netfilter/iptables– Chains (built-in)
• INPUT– present in the mangle and filter tables.
Only packets terminating on localhost traverse this chain.
• OUTPUT– present in the raw, nat, mangle and filter
tables. Only packets originating on localhost traverse this chain.
• FORWARD– present in the mangle and filter tables.
Only packets that neither originate nor terminate at the local host traverse this chain.
(Linux) Networking Tools
140
● Netfilter/iptables– Chains (built-in)
• PREROUTING– present in the raw, nat and mangle tables.
Packets traverse this chain before a routing decision is made by the kernel.
• POSTROUTING– present in the nat and mangle tables.
Packets traverse this chain after a routing decision is made by the kernel.
(Linux) Networking Tools
141
● Netfilter/iptablesTargets (define what to do with the packet)
• ACCEPT/DROP• QUEUE (for user-space application)• LOG (any packet that matches)• REJECT (drops and returns error packet)• RETURN (enables packet to return to previous
chain)• MASQUERADE (all outgoing changed to seem to
come from a specific interface)• SNAT/DNAT (change the source/destination)
• <user-specified> (passes packet to that chain)
(Linux) Networking Tools
142
(Linux) Networking Tools
143
● Netfilter/iptables● iptables [-t table] <cmd> chain rule-spec [options]
(Linux) Networking Tools
144
● Netfilter/iptables
commands:
–A (append a rule to the end of chain)
-D (delete a specific rule in a chain)
-F (flush a chain)
–L (list all rules in a chain)
...
(Linux) Networking Tools
145
● Netfilter/iptablesparameters:
–p (protocol)
-s (source addr[/mask])
-d (destination addr[/mask])
–j (jump target)
-i (in interface)
-o (out interface)
-c (set counter PKTS or BYTES in APPEND operation)
-f (refer to second and further fragments. of frag. pkt)
(Linux) Networking Tools
146
● Netfilter/iptables... examples
● In your company you only have a public IP, while you have several services (e.g. one is a web server) behind a firewall.
How can you forward http requests to the web machine on the private network (i.e., 192.168.10.100)?
(Linux) Networking Tools
147
● Netfilter/iptables... examples
● In your company you only have a public IP, while you have several services (e.g. one is a web server) behind a firewall.
How can you forward http requests to the web machine on the private network (i.e., 192.168.10.100)?
iptables -t nat -A PREROUTING -i eth0 -p tcp –dport 80 -j DNAT –to 192.168.10.100
(Linux) Networking Tools
148
● Netfilter/iptables... examples
● For security reason, you want to drop any packet which contains “.exe” string.
(Linux) Networking Tools
149
● Netfilter/iptables... examples
● For security reason, you want to drop any packet which contains “.exe” string.
iptables -A INPUT -p tcp -m string --algo bm
--string ‘exe’ -j DROP
(Linux) Networking Tools
150
● Netfilter/iptables... examples
Remind...
● List (nat): sudo iptables -t nat -L -n
● Flush: sudo iptables -F -t nat
(Linux) Networking Tools
151
● Practice exercise: free WiFi for everyone!
(Linux) Networking Tools
Guests.Math.UniPD.it
Internet
WARNING: replicating this experiment in a real environment might be against security policies!
Tip to forward:In /etc/sysctl.confnet.ipv4.ip_forward=1(check with sudo sysctl -p)
152
● 1) Configure the WiFi
● 2) Configure the WANand connect laptop to WAN
● 3) Configure iptables for the laptop...
(Linux) Networking Tools
153
● 1) Configure the WiFi
● 2) Configure the WANand connect laptop to WAN
● 3) Configure iptables for the laptop...sudo iptables -t nat -A POSTROUTING -s
10.2.30.254 -j MASQUERADE
(Linux) Networking Tools
154
● Practice exercise: free WiFi for everyone!
– and... block ping from WiFi devices
(Linux) Networking Tools
Guests.Math.UniPD.it
Internet
WARNING: replicating this experiment in a real environment might be against security policies!
155
sudo iptables -A INPUT -s 10.20.30.254 -p icmp -j DROP
(Linux) Networking Tools
156
in that way we drop all ICMP...We should take care of echo-reply, etc.
iptables -A OUTPUT -p icmp -o eth0 -j ACCEPT iptables -A INPUT -p icmp --icmp-type
echo-reply -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp -i eth0 -j DROP
(Linux) Networking Tools
157
● Practice exercise: free WiFi for everyone!
– Can you block HTTP for a specific WiFi device?
(Linux) Networking Tools
Guests.Math.UniPD.it
Internet
WARNING: replicating this experiment in a real environment might be against security policies!
158
● ...on Android
– (in)security of SSL (usage)• “Android SSL Considered Harmful” (credits for slides: S.
Gottardo)
– Attack in practice
SSL MITM attack...
159
● Mitmproxy● Install
(http://mitmproxy.org/doc/install.html)$ sudo apt-get install python-pip python-dev
build-essential python-lxml $ sudo pip install --upgrade pip $ sudo pip install --upgrade virtualenv$ sudo pip install mitmproxy
SSL MITM attack...
160
● Mitmproxy● Start:
mitmproxy --upstream-cert -p 3128 -a $IP_ADDR
• IP_ADDR è l'indirizzo IP su cui gira il proxy
SSL MITM attack...
161
● The victim device
● Certificatehttp://mitmproxy.org/doc/certinstall/android.html
Download/install certificate available here:• http://www.math.unipd.it/~conti/mitm/
or you can install also using:http://www.realmb.com/droidCert/
SSL MITM attack...
162
SSL MITM attack...
163
● The victim device● Proxy
– Install ProxyDroid or...– Configure the proxy for the connection
or...– Set a transparent proxy
• (e.g. with iptables)
SSL MITM attack...
164
SSL MITM attack...
165
SSL MITM attack...
166
SSL MITM attack...
167
SSL Pinning
After interception (with SSL handshake ok), this app sends a null request
After interception (with SSL handshake ok), this app continue to send data...
● Check on certificate could be done after SSL handshake
168
Thanks
Thanks for your attention! Feedback? Suggestions?
...well, if you are looking for me you can find me here:
http://www.math.unipd.it/~conti/[email protected]