Sie sind auf Seite 1von 172

Sandrine VATON

Professor
Tlcom Bretagne
Brest, France
E-mail : sandrine.vaton@telecom-bretagne.eu

Network Security Course


Material for lectures, practicals and exercices
November 2014

Table des matires


Introduction to Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Crypto Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41

RSA Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

49

RSA Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

69

Public Key Cryptography Exercices . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

79

Attack Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

89

Network Audit Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

97

Introduction to IDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105


IDS Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
VPN Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

Introduction to Cryptography

An Introduction to Network Security


S. Vaton & C.Fontaine
Tlcom Bretagne

November 2014

S. Vaton & C.Fontaine (TB)

November 2014

1 / 62

Short Bio
Dr Sandrine VATON
Professor, Tlcom Bretagne (Brest, France), dept of Computer
Science
As a lecturer I am teaching topics such as performance evaluation,
statistical methods, cryptography and network security, algorithmics
and programming ...
Research field : network monitoring
I
I

traffic measurement and analysis (in particular, statistical methods)


to discover threats in the traffic, to characterize the traffic
(classification of the applications), to evaluate performance and
dimension the network
design of monitoring architectures (in particular, hardware acceleration
on FPGA)

long term collaboration with the group of P.Belzarena (2 PhD


co-advised, several internships) ; agreement for a double degree
(engineers, PhDs) between IIE and Tlcom Bretagne ; sabbatical at
IIE in 2010 (with my husband, Prof. Thierry Chonavel)
5
S. Vaton & C.Fontaine (TB)

November 2014

2 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
S. Vaton & C.Fontaine (TB)

November 2014

3 / 62

November 2014

4 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion

6
S. Vaton & C.Fontaine (TB)

Network Security

Definition
In the field of networking, the specialist area of Network Security consists
of the provisions made in an underlying computer network infrastructure,
policies adopted by the network administrator to protect the network
and the network-accessible resources from unauthorized access, and
consistent and continuous monitoring and measurement of its
effectiveness (or lack) combined together.
Network Security and Networking Protocols, A.K.Sharma and C.S.Lamba

S. Vaton & C.Fontaine (TB)

November 2014

5 / 62

The challenges of Information Systems Security


Confidentiality : Only authorized people can access to information.
Any undesirable access must be prohibited. [remark : here, access =
access in terms of information]

7
S. Vaton & C.Fontaine (TB)

November 2014

6 / 62

The challenges of Information Systems Security


Confidentiality : Only authorized people can access to information.
Any undesirable access must be prohibited. [remark : here, access =
access in terms of information]
Availability : The system must operate without failures when it has
been planned to operate, services and ressources must be accessible
(within a good throughput and response time).

S. Vaton & C.Fontaine (TB)

November 2014

6 / 62

The challenges of Information Systems Security


Confidentiality : Only authorized people can access to information.
Any undesirable access must be prohibited. [remark : here, access =
access in terms of information]
Availability : The system must operate without failures when it has
been planned to operate, services and ressources must be accessible
(within a good throughput and response time).
Integrity : Data must be consistent with what they should be, they
should not be altered (by mistake or maliciously).

8
S. Vaton & C.Fontaine (TB)

November 2014

6 / 62

The challenges of Information Systems Security


Confidentiality : Only authorized people can access to information.
Any undesirable access must be prohibited. [remark : here, access =
access in terms of information]
Availability : The system must operate without failures when it has
been planned to operate, services and ressources must be accessible
(within a good throughput and response time).
Integrity : Data must be consistent with what they should be, they
should not be altered (by mistake or maliciously).
Authentication : Users identification is a cornerstone to manage the
access to appropriate workspaces and to maintain confidence in the
exchanges.

S. Vaton & C.Fontaine (TB)

November 2014

6 / 62

The challenges of Information Systems Security


Confidentiality : Only authorized people can access to information.
Any undesirable access must be prohibited. [remark : here, access =
access in terms of information]
Availability : The system must operate without failures when it has
been planned to operate, services and ressources must be accessible
(within a good throughput and response time).
Integrity : Data must be consistent with what they should be, they
should not be altered (by mistake or maliciously).
Authentication : Users identification is a cornerstone to manage the
access to appropriate workspaces and to maintain confidence in the
exchanges.
Non-repudiation and imputation : No user should be able to
contest the operations he has realized in the framework of authorized
actions, and no third party should be able to claim for himself the
actions of another user.
Source : Wikipedia
9
S. Vaton & C.Fontaine (TB)

November 2014

6 / 62

Confidentiality

Definition
Confidentiality has been defined by the International Organization for
Standardization (ISO) in ISO-17799 as ensuring that information is
accessible only to those authorized to have access"

Related Attacks
Passive attacks (e.g., eavesdropping)
Possible solutions : cryptography, IPSec, SSL, TLS

S. Vaton & C.Fontaine (TB)

November 2014

7 / 62

Availability

Definition
The degree to which a system, subsystem, or equipment is operable and in
a committable state at the start of a mission, when the mission is called for
at an unknown, i.e., a random, time. Simply put, availability is the
proportion of time a system is in a functioning condition.

Related Attacks
Denial of Service (DoS, Distributed Denial of Service DDoS)

10
S. Vaton & C.Fontaine (TB)

November 2014

8 / 62

Integrity
Definition
Data integrity is related to the state of data that, during their treatment,
their storage, or their transmission, have not encountered any modification
or destruction (be it voluntarily or not). Data must be in a state that permit
their utilization, they should not have been modified. Data integrity covers
four elements : precision, completeness, exactitude/authenticity and validty.
Integrity can be guaranteed by several security mechanisms (e.g., hash
function, data authentication, digital signature)
Trivial examples : checksums, error detection codes such as CRC in
packet/frame headers

Related Attacks
downloading a malware instead of the expected program, modification of
the amount of a bank operation, etc.
S. Vaton & C.Fontaine (TB)

November 2014

9 / 62

Authenticity
Definition
Authentication is the act of establishing or confirming something (or
someone) as authentic, that is, that claims made by or about the subject
are true

Attaques associes
Man in the Middle, Masquerade, spoofing
Authentication mechanisms :
A difficult-to-reproduce physical artifact, such as a seal, signature,
fingerprint.
A shared secret such as a passphrase
An electronic signature ; public key infrastructure is often used to
cryptographically guarantee that a message has been signed by the
holder of a particular private key.
S. Vaton & C.Fontaine (TB)

November 2014

11
10 / 62

Non-rpudiation

Definition
Non-repudiation is the concept of ensuring that a party in a dispute cannot
repudiate, or refute the validity of a statement or contract
The most common method of asserting the origin of data is through
digital certificates, that can be considered as "digital ID cards". A
certification authority is the trusted third party that ensures the
correspondence between the physical identity and the digital identity. A
common standard for digital certificates : X509.

S. Vaton & C.Fontaine (TB)

November 2014

11 / 62

Security triangle

"It is very important to understand that in security, one simply cannot say "whats the
best firewall ?" There are two extremes : absolute security and absolute access. The
closest we can get to an absolutely secure machine is one unplugged from the network,
power supply, locked in a safe, and thrown at the bottom of the ocean. Unfortunately, it
isnt terribly useful in this state." Network Security and Networking Protocols,
A.K.Sharma and C.S.Lamba

12
S. Vaton & C.Fontaine (TB)

November 2014

12 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
S. Vaton & C.Fontaine (TB)

November 2014

13 / 62

What is cryptography useful for ?


to cipher messages (since Antiquity) :
I

to protect the confidentiality of messages (against eavesdropping)

to digitally sign messages (since 1978) :


I
I
I

to authenticate the author of a message, i.e. to make sure that the


author of the message is who he pretends to be
to guarantee non repudiation i.e. to make sure that the author of a
message cannot pretend not having built this message
to guarantee the integrity of a message i.e. to make sure that the
message has not been altered, that its content has not been modified

to authenticate oneself with a system (since 1978) :


I

to prove ones identity, by demonstrating that one holds a secret (such


as a passphrase) that no one knows (except the owner), without letting
this secret circulate as plaintext on the network

and many other applications (since 1978) :


I

key key exchange, Multi-Party Computation, electronic voting,


oblivious transfer, anonymous digital money, ...
13

S. Vaton & C.Fontaine (TB)

November 2014

14 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
S. Vaton & C.Fontaine (TB)

November 2014

15 / 62

Basic concepts (1/2)

Cryptography : conception of information protection systems. Different


application fields : encryption = ciphering, digital signature,
authentication.
Cipher : algorithm used to perform encryption or decryption ; series of
steps that transform a plain text, in a cipher text (and vice versa)
Cryptosystem : any computer system that involves cryptography ;
usually includes methods for digital signatures, key management
techniques, cryptographic hash functions

14
S. Vaton & C.Fontaine (TB)

November 2014

16 / 62

Basic concepts (2/2)


Encrypt = encipher = encode , decrypt = decode = decipher : the
sender encrypts the plain text m (with the encryption key) to produce
the cipher text c ; the receiver decrypts the cipher text c (with the
decryption key) and recovers the plain text m
Eve

(oreille indiscrte)

Canal jarretire

dchiffrement

chiffrement

Alice
Message en clair

Cl de chiffrement

Message chiffr

Bob
Message en clair

Cl de dchiffrement

Cryptanalysis : used to breach cryptographic security systems and gain


access to the contents of encrypted messages even if the cryptographic
key is unknown. How ? By analyzing the flow of information in order
to deduce hidden aspects (some bits of the key) ; in side channel
attacks, by the analysis of physical parameters (such as power
consumption for example).
S. Vaton & C.Fontaine (TB)

November 2014

17 / 62

History (1/6)

Antiquity
Scytale : tool to perform a transposition cipher (permutation of the
letters of the message) ; easy to breach

15
S. Vaton & C.Fontaine (TB)

November 2014

18 / 62

History (2/6)
Caesar cipher : it is a particular mono-alphabetic substitution cipher :
each letter is replaced by a letter some fixed number of positions down
the alphabet, the value of the shift is fixed by the key k :
ci = mi + k
plain alphabet
cipher alphabet

mod [26]

ABCDEFGHIJKLMNOPQRSTUVWXYZ
CDEFGHIJKLMNOPQRSTUVWXYZAB

plain text
cipher text

LETRO ISJAN VIERA TREIZ EHEUR ESETD


NGVTQ KULCP XKGTC VTGKB GJGWT GUGVF

Easily breachable by analysis of the frequency of letters in the alphabet


250

250

Clair (franais)

Csar (franais)

200

200

150

150

100

100

50

50

0
A

S. Vaton & C.Fontaine (TB)

November 2014

19 / 62

History (3/6)
16th century : Vigenre cipher
poly-alphabetic substitution cipher with periodicity
ci = (mi + ki mod |k| ) mod [26]
ex : with key k=LEROI
plain alphabet
cipher alphabet
cipher alphabet
cipher alphabet
cipher alphabet
cipher alphabet
plain
key
ciphered

L
E
R
O
I

ABCDEFGHIJKLMNOPQRSTUVWXYZ
LMNOPQRSTUVWXYZABCDEFGHIJK
EFGHIJKLMNOPQRSTUVWXYZABCD
RSTUVWXYZABCDEFGHIJKLMNOPQ
OPQRSTUVWXYZABCDEFGHIJKLMN
IJKLMNOPQRSTUVWXYZABCDEFGH

LETRO ISJAN VIERA TREIZ EHEUR ESETD


LEROI LEROI LEROI LEROI LEROI LEROI
WIKFW TWAOV GMVFI EVVWH PLVIZ PWVHL

19th century
cryptanalysis of the Vigenre cipher (Babbage, Kasiski and then
coincidence index in 1920)
16
S. Vaton & C.Fontaine (TB)

November 2014

20 / 62

History (4/6)
20th century
1st world war : Vernam cipher (1917, published in 1926) or
"one-time pad" : ci = mi + ki mod [2], where the plain text m and
the cipher text c are represented as a series of bits, and where the key
k is a random bit stream, of the same length as the message, and used
one and only one time. It can be seen as an extension of the Vigenre
cipher with randomness and no period in the key.
key
stream
plain text
(encoding)



?
?
- cipher text 

6

key
stream
- plain text

(decoding)

Rem : it is the only cipher that has been proved to be unconditionnally


secure but it requires a key as long as the message itself (proven by C.
Shannon in 1949).
S. Vaton & C.Fontaine (TB)

November 2014

21 / 62

History (5/6)
2nd world war : Enigma machine
German electro-mechanical rotor cipher
machine.
German military texts enciphered on
the Enigma machine were first broken by Polish cryptanalysts. Poles then
initiated French and British cryptanalysts into their Enigma decryption techniques. During the war, British cryptologists decrypted a vast number of messages enciphered on Enigma.
1948 : development by Claude Shannon of information theory.
Theoretical framework to coding and information security.
17
S. Vaton & C.Fontaine (TB)

November 2014

22 / 62

History (6/6)
1977 : standardization of DES (Data Encryption Standard) by NIST
(National Institute of Standards, USA), after a call for proposals
1987 : RC4 (Ronald Rivest) ; very popular cipher because of its speed
and simplicity ; supported in SSL/TLS (for https) and WEP (for WiFi
networks)
1999 : E0 (Bluetooth)
1999 : A5 (GSM)
2000 : standardization of the AES (Advanced Encryption Standard)
by NIST in the US, after a call for proposals
regular call for proposals for new algorithms and benchmarks
(NIST, NoE ECRYPT)
S. Vaton & C.Fontaine (TB)

November 2014

23 / 62

Cipher Keys
Kerckhoffs principle (1883) : the cipher (i.e. the algorithm used for
encryption/decryption) is known by the cryptanalyst ; the security is
based on the secret of the (decryption) key,
standardization of the cipher
in most cases the security cannot be perfect, the security is based on
the tremendous computational burden of an attack that would
attempt to retrieve decipher the cipher text without decryption key
it must be "impossible" to do so, except for entities with an extremely
large computational power
the number of possible keys must be large enough to prevent brute
force attacks constraints on minimum key lengths.
18
S. Vaton & C.Fontaine (TB)

November 2014

24 / 62

Notion of Key : Symetric Cryptography


vs. Public Key Cryptography
Taxonomy of Ciphers
Symetric Cryptography :
I
I
I

the ssame (secret) key is used for encryption and decryption 1 ,


Exemples : Caesar, Vigenre, Vernam, DES, RC4, RC6, Idea, Blowfish,
AES, A5, E0, etc
Remark : all the ciphers that we have mentioned up to now belong to
this category

Public Key Cryptography :


I

I
I
I

each user in the system has a pair of keys (public key, private key), the
public key is used for encryption and the private key is used for
decryption
in a context of signature, the private key is used for signing and the
public key is used for verifying the signature
Exemples : RSA, El Gamal, elliptic curve cryptography
Remark : those ciphers have been developed after 1977

1. more precisely the decryption key can be deduced very easily from the encryption
key ; ex : k et -k.
S. Vaton & C.Fontaine (TB)

November 2014

25 / 62

History (7)
Public key cryptography
1977 : W. Diffie and M. Hellmann, key exchange protocol, first step
towards public key cryptography
1978 : R. Rivest, A. Shamir et L. Adleman, RSA cipher (based on
number theory, prime numbers)
1978 : Mc Eliece cipher Niederreiter cipher (both of them are based
on error correcting codes theory)
1985 : El Gamal cipher (probabilistic)
1987 : first cipher based on elliptic curves
1994 : OAEP (Optimal Asymetric Encryption Padding), a way to use
RSA in real life (probabilistic)
19
S. Vaton & C.Fontaine (TB)

November 2014

26 / 62

Keystone of public key cryptography : one way functions


One way functions : functions which are easy to compute (polynomial
time) but very difficult to reverse, except for the person who knows a
particular secret ;-).
In order to find out the secret key from the public key it is necessary
to reverse a one way function, which is "impossible" except for the
owner of the key who knows the secret

S. Vaton & C.Fontaine (TB)

November 2014

27 / 62

Keystone of public key cryptography : one way functions


One way functions : functions which are easy to compute (polynomial
time) but very difficult to reverse, except for the person who knows a
particular secret ;-).
In order to find out the secret key from the public key it is necessary
to reverse a one way function, which is "impossible" except for the
owner of the key who knows the secret
Examples :
I

factorisation in a product of two very large prime numbers : N = p q.


The security of the RSA cryptosystem is based on the difficulty of this
problem.
discret logarithm : x is the discrete logarithm of a in base g , denoted
as logg (a), if a = g x mod [N] (where g is the generator of (Z/NZ) ).
The security of cryptographic schemes such as Diffie Hellman or El
Gamal is based on the difficulty of this problem.

20
S. Vaton & C.Fontaine (TB)

November 2014

27 / 62

RSA Cryptosystem (1/2)


RSA : Rivest, Shamir, Adleman, 1977 ; one of the first public key
cryptosystem and still the most important one

S. Vaton & C.Fontaine (TB)

November 2014

28 / 62

RSA Cryptosystem (1/2)


RSA : Rivest, Shamir, Adleman, 1977 ; one of the first public key
cryptosystem and still the most important one
RSA Keys
I
I
I
I
I

2 large prime numbers p and q and their product N = p q,


e, integer coprime to (N) = (p 1)(q 1) (and consequently e is
invertible modulo (N)),
The public key is the couple (e, N) (e : encryption exponent ; N : RSA
modulus).
let d be the inverse of e modulo (N)
The private key is d (decryption exponent). The prime factors p and q
of N have to remain private.

21
S. Vaton & C.Fontaine (TB)

November 2014

28 / 62

RSA Cryptosystem (1/2)


RSA : Rivest, Shamir, Adleman, 1977 ; one of the first public key
cryptosystem and still the most important one
RSA Keys
I
I
I
I
I

2 large prime numbers p and q and their product N = p q,


e, integer coprime to (N) = (p 1)(q 1) (and consequently e is
invertible modulo (N)),
The public key is the couple (e, N) (e : encryption exponent ; N : RSA
modulus).
let d be the inverse of e modulo (N)
The private key is d (decryption exponent). The prime factors p and q
of N have to remain private.

RSA encryption and decryption


I
I
I
I

the plain text is identified to an integer M such that 2 M N 1


encryption : C = M e mod [N] (modular exponentiation)
decryption : C d mod [N]
it can be proven, thanks to the Euler theorem, that C d mod [N] = M

S. Vaton & C.Fontaine (TB)

November 2014

28 / 62

RSA Cryptosystem (2/2)

RSA Security
I

2 equivalent problems :
F
F

factorize N = pq
knowing e and N (public key) find out d (private key)

RSA security is based on the difficulty ot the problem of large integers


factorization

Exercice
1
2

prove that C d mod [N] = M


prove that the 2 above mentioned problems are equivalent

22
S. Vaton & C.Fontaine (TB)

November 2014

29 / 62

Pros and Cons (1/4)


Symmetric Cryptography
fast encryption and decryption
Encryption and decryption are based on simple basic operations
(permutations, substitutions, XOR, shifts, etc...) which are adapted to
fast data processing and hardware acceleration.
Perfect security for Vernam cryptosystem (One-Time Pad),
computational security for other cryptosystems
but requires a shared secret key ; how is it possible to share a secret
key on an unsecure channel ?

S. Vaton & C.Fontaine (TB)

November 2014

30 / 62

Pros and Cons (1/4)


Symmetric Cryptography
fast encryption and decryption
Encryption and decryption are based on simple basic operations
(permutations, substitutions, XOR, shifts, etc...) which are adapted to
fast data processing and hardware acceleration.
Perfect security for Vernam cryptosystem (One-Time Pad),
computational security for other cryptosystems
but requires a shared secret key ; how is it possible to share a secret
key on an unsecure channel ?
Public key cryptography
encryption and decryption are much slower (non trivial mathematical
computations, such as modular exponentiation)
computational security only, even if there are"arguments of proofs" of
security
doesnt require a shared secret
necessary to certify public keys (PKI, Public Key Infrastructures)
23
S. Vaton & C.Fontaine (TB)

November 2014

30 / 62

Pros and Cons (2/4)


In practice : combination of public key and symmetric cryptography
key exchange protocol (such as Diffie-Hellmann) to build a shared
secret. This shared secret is then used as the key in a symmetric
cryptosystem.
OR : hybrid cryptosystem
I
I

key encapsulation scheme : public key cryptography is used to cipher


the key and share it between sender and receiver
data encapsulation scheme : the shared secret key is used to encrypt
and decrypt the data

Pub(Bob)
?

Priv(Bob)
(K )

RSA

RSA

Alice

?
- RSA1

K
?

m - AES

(m)

AES

K
-

?
AES1

S. Vaton & C.Fontaine (TB)

Bob
-m
November 2014

31 / 62

Pros and cons (3/4)


Key lengths
For an equivalent security level :
Symmetric Cryptography
I
I

smaller keys
at least 128 bits for a good security level

Public Key Cryptography


I
I
I

in general, longer keys


example : RSA modulus, at least 1024 bits
other example : elliptic curve cryptography, smaller keys than RSA

http://www.keylength.com/fr/5/ sums up recommandations about key


lengths for different cryptosystems, different time horizons, and different security
levels
24
S. Vaton & C.Fontaine (TB)

November 2014

32 / 62

Pros and Cons (4/4)


Example : recommandations of ECRYPT II (2012).

S. Vaton & C.Fontaine (TB)

November 2014

33 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
25
S. Vaton & C.Fontaine (TB)

November 2014

34 / 62

Digital Signature (1/2)


Digital Signature goals : authentification of the sender, integrity of the
data, non repudiation (the sender cannot pretend not having signed the
data because it is impossible to coin a valid signature without the secret
key)
Legal value : (France) law of march 2000, decree of march 2001
Digital signature is enabled by public key cryptography
The private key is used to sign,
the validity of the signature is checked with the public key.
Examples :
RSA (factorisation),
El Gamal (discrete logarithm),
DSA, Digital Signature Algorithm : variation of El Gamal ; developped
by NIST and NSA (1994) ; governmental origin, doubts on the
existence of backdoors
S. Vaton & C.Fontaine (TB)

November 2014

35 / 62

Naive implementation
Alice

Bob
-

Priv(Alice)

=?

Pub(Alice)

Problem : computation workload


(public key cryptography on a big file).

26
S. Vaton & C.Fontaine (TB)

November 2014

36 / 62

Implementation with a hash function


Alice

Bob

Hash Function

Hash

6
=?
?
Hash Function

Hash

Hash
Priv(Alice)

Pub(Alice)

h : {0, 1} {0, 1}m fixed size hash value, easy to compute, difficult to reverse
Examples : MD5 (128), SHA-1 (160), RIPE-MD 160, SHA-256, . . .
The problem of computational burden has been solved.
But possible collision problems ! Cryptographic has functions must be used,
sufficiently secure (not MD5 !).

S. Vaton & C.Fontaine (TB)

November 2014

37 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
27
S. Vaton & C.Fontaine (TB)

November 2014

38 / 62

Public Key Infrastructures (PKI)


Public Key Infrastructures (PKI) : in charge of the management and
distribution of keys for public key cryptography
terminology : certification authority
missions :
I
I

generation for any entity that requires it of a pair of keys (public key,
private key) after verification of the identity of this entity
creation and management of digital certificates

digital certificate : includes


I
I
I
I
I

identity of the entity (institution, DNS server, email adress...)


value of the public key
validity date and utilizations of the key
identity of the authority that has delivered the certificate
signature of the certificate

NB : Only the certification authority is able to sign the public key (the private key
of the certification authority is necessary to sign the certificate). The validity of
the signature can be checked with the public key of the certification authority.
S. Vaton & C.Fontaine (TB)

November 2014

39 / 62

Digital Certificates
X.509 Certificates
X.509 : recommandation of the UIT (Int. Tlcom. Union)
X.509 certificates are used in many solutions such as S/MIME (digital
signature of emails), IPSec or SSL (secure tunnels)
format des certificats X.509

Certificate Version
Serial Number
Algo. used to sign the certificate
Name of the certification authority
Validity Period
Certificates Owner
Owners Public Key
Additional Information (on the owner or on the ciphers)
Signature of the Certificate (algotithms used for signature, and signature)

28
S. Vaton & C.Fontaine (TB)

November 2014

40 / 62

Example of X.509 certificate : emitted by "Direction des Impts" during


2004 tax declaration

S. Vaton & C.Fontaine (TB)

November 2014

41 / 62

Digital certificates
Example usage of a digital certificate : setting up a secure connection to an
enterprise server
1

the client browser connects to the enterprise server to pick up the


name of the PKI and the reference of the enterprise certificate (serial
number)

the client connects to the PKI site and downloads the certificate

it checks the validity period


it checks the certificate authenticity ; for example :

I
I
I
I

if the signature has been produced with MD5 hash followed by RSA
encryption
it decodes the RSA signature with the public key of the certification
authority
it hashes the public key of the enterprise server with MD5
if both quantities are equal then the certificate is authenticated
29

S. Vaton & C.Fontaine (TB)

November 2014

42 / 62

Certification authorities
Hierarchy of certification authorities
AC

AC

AC

AC

Panoramix

ALICE

BOB

Limits of PKI infrastructures


many certification autorithies : inter-operability problems
lack of trust of users in the reliability of certification authorities ;
example : fake Microsoft certificates emitted by Diginotar
S. Vaton & C.Fontaine (TB)

November 2014

43 / 62

Certification authorities : who are you trusting ?


Consciously or not . . .

30
S. Vaton & C.Fontaine (TB)

November 2014

44 / 62

The PGP model


PGP (Pretty Good Privacy ; Phil Zimmermann, 1991)
I
I

used to sign data, to encode/decode emails, folders, drive partitions, to


ensure the security of emails
uses symmetric cryptography and public key cryptography (hybrid
cryptography)
F
F

encryption/decryption with a secret key IDEA


the IDEA secret key is encrypted with the RSA public key of the
receiver

standard OpenPGP (IETF, RFC 4880) : initially, encryption and


authentication of emails ; extended to OpenSSH and to secure web
(TLS)

S. Vaton & C.Fontaine (TB)

November 2014

45 / 62

The PGP model


PGP (Pretty Good Privacy ; Phil Zimmermann, 1991)
I
I

used to sign data, to encode/decode emails, folders, drive partitions, to


ensure the security of emails
uses symmetric cryptography and public key cryptography (hybrid
cryptography)
F
F

encryption/decryption with a secret key IDEA


the IDEA secret key is encrypted with the RSA public key of the
receiver

standard OpenPGP (IETF, RFC 4880) : initially, encryption and


authentication of emails ; extended to OpenSSH and to secure web
(TLS)

Key certification in PGP


I
I
I

digital seal that guarantees the authenticity of public keys


trust is based on the notion of social proximity rather than on a central
certification authority
each user releases his own public key ; each user can sign the public key
of another user ; trust in a public key signed by someone who is trusted
31

S. Vaton & C.Fontaine (TB)

November 2014

45 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
S. Vaton & C.Fontaine (TB)

November 2014

46 / 62

Zero knowledge proofs (1/3)


Zero-knowledge proof
used for authentication
principle : prove that one knows a secret without making possible for
an eavesdropper to catch any information about this secret on the
unsecure channel
how ? prove that one is capable to answer successfully to a particular
"challenge"
public key cryptography :
I
I

uses one way functions ; examples : discrete logarithm, quadratic


residues (Fiat-Shamir), ...
uses random masks

32
S. Vaton & C.Fontaine (TB)

November 2014

47 / 62

Zero knowledge proofs (2/3)


Proofs of knowledge of discrete logarithms
Public values : p, prime integer and , primitive root modulo p.
The prover P needs to convince the verifier V that he knows the discrete
logarithm s of I = s mod [p] (without transmitting s as plain text on the
channel) ; the prover P is identified by I in the eyes of V .
3 Steps Protocol
1

Commitment : P chooses r modulo p 1 randomly and transmits


t = r mod [p] to V .

Challenge : V chooses  randomly in {0, 1} and communicates his


choice  to P.
Answer : P must provide to V :

I
I

x = r mod [p 1] if  = 0
x = r + s mod [p 1] if  = 1

V then computes x mod [p] which must be equal to t if  = 0 and


to It if  = 1.
S. Vaton & C.Fontaine (TB)

November 2014

48 / 62

Zero knowledge proofs (3/3)

Proof of knowledge of discrete logarithms


Exercice
1

Is it possible for an intruder to authenticate oneself in the eyes of V


without knowing the secret s ? What is the probability that he is
caught ? And what if the same protocol is applied n times ?

What is the quantity r useful for ?

What happens if  is taken off from the protocol ? Is it possible for the
intruder to authenticate himself ? And what if the random number
generator used to produce  is not good ?

33
S. Vaton & C.Fontaine (TB)

November 2014

49 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
S. Vaton & C.Fontaine (TB)

November 2014

50 / 62

November 2014

51 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion

34
S. Vaton & C.Fontaine (TB)

Authentication : particular case of Kerberos (1/2)


Kerberos
network authentication service, developped by MIT ; standard
Kerberos v5 (RFC 1510 )
key distribution center : authentication server to identify distant
clients, ticket delivery server to authorize them to use the network
services
based on symmetric cryptography (DES), and the usage of tickets
(with limited validity)
The Kerberos server knows some servers and clients who are in his
domain. It shares a secret key with each client or server in his domain.
Possibility of inter-domain authentification thanks to a dialog between
Kerberos servers.

S. Vaton & C.Fontaine (TB)

November 2014

52 / 62

Authentication : particular case of Kerberos (2/2)


Usage : a user wants to proceed to a transaction with a server
the user sends its identifier to the authentication server
the authentication checks the access rights of the user and sends him
an initial ticket. The initial ticket is encrypted with a key derived from
the clients password. It contains : a ticket for access to the ticket
delivery service, a session key (used to cipher the next
communications)
the user decrypts the initial ticket with his password
with this access ticket and his session key he sends an encrypted
request to the ticket delivery service to ask for an access to a service
there exists a mutual authentication system that enables the client
and the server to identify each other
Kerberos Security
temporary validity of tickets, which limits the possibility of replay
attacks
sensitive to password cracking attacks
35
vulnerability of Kerberos servers which must be very well secured
S. Vaton & C.Fontaine (TB)

November 2014

53 / 62

Sommaire
1

Introduction
Requirements in terms of security
Why cryptography ?

Confidentiality through Encryption

Digital Signature

Trusting Public Keys . . .

Zero knowledge proofs

In practice
Authentication : Kerberos
Authentification et cl de session : SSL/TLS et SSH

Conclusion
S. Vaton & C.Fontaine (TB)

November 2014

54 / 62

SSL/TLS Protocol
SSL/TLS
SSL : Secure Socket Layer (originally developped by Netscape)
then TLS = Transport Layer Security [TLS v1.1 = SSL v3.1].
(developped at IETF Internet Engineering Task Force)
Goals of SSL/TLS
authentication of both parties thanks to certificates
confidentiality of exchanged data ; symmetric encryption : DES,
3-DES, RC4, AES
integrity of data ; hash functions : MD5, SHA-1
OpenSSL
open implementation of SSL/TLS http://www.openssl.org
encryption/decryption, signature, certificates management
36
S. Vaton & C.Fontaine (TB)

November 2014

55 / 62

Operation of SSL/TLS (1/2)


establishment of a secure tunnel (encrypted) between client and server
after an authentication step
independant from the used protocol (HTTP, FTP, POP, IMAP...)
acts as an additional security layer between transport layer and
application layer
APPLICATIONS

APPLICATIONS

HTTPS

HTTP

IMAP

IMAPS

etcs ...

etc ...

SSL, TLS

TCP/IP

TCP/IP

S. Vaton & C.Fontaine (TB)

November 2014

56 / 62

Operation of SSL/TLS (2/2)


Initial handshake
Hello, can we talk ?

Hello, here is my certificate, and here are the ciphers that I support


OK, (here is my certificate), we are going to talk in XXX, with key YYY

secure tunnel

37
S. Vaton & C.Fontaine (TB)

November 2014

57 / 62

Operation of SSL/TLS
HTTPS : secure Web
URL starting by https :// and padlock
Note : some servers use weak cryptography (40 bits) ; configure your
browser to accept only what you consider as sufficient in terms of
security !

IMAPS
same functionalities as IMAP
with moreover encrypted identification
S. Vaton & C.Fontaine (TB)

November 2014

58 / 62

SSH Secure SHell


SSH
secure connection to a machine on an unsecure network (secure
tunnel)
I
I
I

handled functionalities : secure data communication (downloading),


remote command-line login, remote command execution
secure channel over an insecure network between two computers, a
server and a client running SSH server and SSH client programs
designed as a replacement for Telnet (and other insecure remote
protocols) which send information, notably passwords, as plaintext

Puts in operation :
I
I
I

authentication (password, key, Kerberos token)


encryption (symmetric cryptography, public key cryptography)
signature, integrity (hashing)

two versions of the protocol :


I
I

38

SSH-1 : unsecure ; possible to gain root privileges


SSH-2 : more secure (several session keys, client-server and server-client
transactions are independent, certification, tokens to avoid replay...)

S. Vaton & C.Fontaine (TB)

November 2014

59 / 62

Crypto Lab
Network Security Course - November 2014

Crypto Lab Secure mail, Public-Key Cryptography and PKI


1

Overview

The learning objective of this lab is for students to get familiar with the concepts in the Public-Key encryption and Public-Key Infrastructure (PKI). Furthermore, this lab is going to be illustrated with the help of
secure mail exchange. After finishing the lab, students should be able to gain a first-hand experience on
secure mail exchange, public-key encryption, digital signature, public-key certificate, certificate authority,
authentication based on PKI.

Lab Environment and organization

2.1

Work organization

1. Work in a group of THREE people.


2. This Lab will be evaluated based on the reports you are going to submit. Please, see the last section
regarding the submission and the format of the report.

2.2

Installing OpenSSL.

In this lab, we will use openssl commands and libraries. They should be present on the computers of the
university. If you wish to perform this lab on your own computer, you have to install it in addition. Note,
that OpenSSL also exists under Windows, but some of the exercises may not function in the same way as
under Linux, so if you chose to do it on your own computer under Windows, be prepared to spend some
more time resolving the issues.

2.3

Some links you might find helpful

This Lab requires a significant amount of autonomous work. Read the tasks and the provided supporting
material very carefully.
Do not hesitate to do your own research and to seek solutions to the problems you encounter on the web.
Here is an example resource related to OpenSSL:
http://www.madboa.com/geek/openssl/

Lab Tasks

A Certificate Authority (CA) is a trusted entity that issues digital certificates. The digital certificate certifies the ownership of a public key by the named subject of the certificate. A number of commercial CAs
are treated as root CAs; VeriSign is the largest CA at the time of writing. Users who want to get digital
certificates issued by the commercial CAs need to pay those CAs.
For the first task we will be using a free, but not widely accepted CA. For the rest of the tasks we will
be creating our own CA (which will be even less widely accepted).

41

Network Security Course - November 2014

3.1

Task 1: Obtain a personal certificate and send signed mails

This task can be performed under Windows or Linux with no restrictions or differences.
In this task we will see how to obtain free personal certificates and use them to sign our outgoing emails.
This task requires the configuration of a full email client (or more formally a mail user agent (MUA)).
There exist multiple MUAs for Linux, Windows and Mac OS X. We will be using the open-source, multiplatform email client Mozilla Thunderbird, which is already installed on the universitys computers.
3.1.1

E-mail client configuration

We will be using our university e-mail accounts for this task. Configure Thunderbird to access your e-mail
account by specifying the appropriate parameters:
E-mail address: your email at FING
Incoming mail server (IMAPS): the FING IMAPS server
Outgoing mail server (SMTPS): the FING SMTPS server
Account name: user login
Verify that youve correctly configured your MUA by sending an email to yourself and then receiving it.
What is the difference between the protocols IMAP and IMAPS, and SMTP and SMTPS?
3.1.2

Client certificate generation

Obtain a free client certificate from the following provider http://www.cacert.org/ for your school
e-mail address. Please note, that the procedure may vary depending on your browser and OS. Use the
information provided on the web site of CACert to generate the certificate.
Thanks to a special code contained in the html page, the web site instructs the browser to generate a
key pair. The private key of the user remains on the local disk. The public key is then sent to the authority
that generates the certificate. Finally, the CA will send you an e-mail informing you when your certificate is
ready.
Describe the procedure youve followed to generate your certificate and answer the following questions:
1. Why do we have to download and install the certificate of the Certificate Authority (CA) before
installing our own certificate?
2. Which is the precise identity of the CA?
3. The certificate is valid from which date to which date?
4. In which field of the certificate you find your e-mail? Your public key? The CA?
When downloading the root certificate you are provided with several possible download formats and the
checksum (also known as thumbprint in this context) with two algorithms (SHA1 and MD5).
Answer the following questions:
1. What is the use of this information?
2. How can these checksums be verified? Try looking at the openssl package and related resources for
help.
3. Is it possible for a dedicated attacker with unlimited resources to circumvent this protection mechanism?

42

Network Security Course - November 2014

4. If it is possible, why is this mechanism still in place?


5. Propose a way of distributing the root certificate that does not suffer the problems youve pointed out
Thunderbird has its own certificate store and does not share it with other applications. In order to be
able to send signed and/or encrypted e-mails, you have to import it to Thunderbird (and potentially export it
first from the browser) by using a file in the format pkcs12.
Import certificate to Thunderbird:
Tools / Options / Privacy / Security /
Show certificates / Authorities / Import
Why do we need to install the certificates in the MUA and the web browser separately? Is there a
system repository of certificates? Is it used by all browsers and all MUAs?
3.1.3

Exchange of encrypted and/or signed e-mails

Exchange e-mails with your teammate. Make a table containing the sizes of the different e-mails:
1. raw content exchanged whenever you have a signed mail
2. signed and encrypted mail
3. an encrypted mail
4. a non-signed and non-encrypted mail
You can access the raw content exchange via the menu View/Message Source. Describe your observation
and analysis.

3.2

Task 2: Become a Certificate Authority (CA)

In this lab, we need to create digital certificates, but we are not going to pay any commercial CA. We will
become a root CA ourselves, and then use this CA to issue certificate for others (e.g. servers). In this
task, we will make ourselves a root CA, and generate a certificate for this CA. Unlike other certificates,
which are usually signed by another CA, the root CAs certificates are self-signed. Root CAs certificates are
usually pre-loaded into most operating systems, web browsers, and other software that rely on PKI. Root
CAs certificates are unconditionally trusted.
Include all generated files (certificates, etc.) in your submission.
The Configuration File openssl.conf. In order to use OpenSSL to create certificates, you have to
have a configuration file. The configuration file usually has an extension .cnf. It is used by three OpenSSL
commands: ca, req and x509. The manual page of it can be found at http://wwwneu.secit.at/
web/documentation/openssl/openssl_cnf.html. You can also get a copy of the configuration
file from /usr/lib/ssl/openssl.cnf. After copying this file into your current directly, you need to
create several sub-directories as specified in the configuration file (look at the [CA default] section):
dir
certs
crl_dir
new_certs_dir

=
=
=
=

./demoCA
$dir/certs
$dir/crl
$dir/newcerts

#
#
#
#

Where everything is kept


Where the issued certs are kept
Where the issued crl are kept
default place for new certs.

43

Network Security Course - November 2014

database
serial

= $dir/index.txt
= $dir/serial

# database index file.


# The current serial number

For the index.txt file, simply create an empty file. For the serial file, put a single number in
string format (e.g. 1000) in the file. Once you have set up the configuration file openssl.cnf, you can
create and issue certificates.
Certificate Authority (CA). As we described before, we need to generate a self-signed certificate for our
CA. This means that this CA is totally trusted, and its certificate will serve as the root certificate. You can
run the following command to generate the self-signed certificate for the CA:
$ openssl req -new -x509 -keyout ca.key -out ca.crt -config openssl.cnf
You will be prompted for information and a password. Do not lose this password, because you will
have to type the passphrase each time you want to use this CA to sign certificates for others. You will also
be asked to fill in some information, such as the Country Name, Common Name, etc. The output of the
command are stored in two files: ca.key and ca.crt. The file ca.key contains the CAs private key,
while ca.crt contains the public-key certificate.

3.3

Task 3: Create a Certificate for PKILabServer.com

If you do this part on a university computer, please use the name of the computer you are currently working
on (of the form pc-df-XXX.priv.enst-bretagne.fr) instead of PKILabServer.com.
Now, we become a root CA, we are ready to sign digital certificates for our customers. Our first customer
is a company called PKILabServer.com. For this company to get a digital certificate from a CA, it needs
to go through three steps.
Step 1: Generate public/private key pair. The company needs to first create its own public/private key
pair. We can run the following command to generate an RSA key pair (both private and public keys).
You will also be required to provide a password to protect the keys. The keys will be stored in the file
server.key:
$ openssl genrsa -des3 -out server.key 1024
Step 2: Generate a Certificate Signing Request (CSR). Once the company has the key file, it should
generates a Certificate Signing Request (CSR). The CSR will be sent to the CA, who will generate a certificate for the key (usually after ensuring that identity information in the CSR matches with the servers true
identity). Please use PKILabServer.com as the common name of the certificate request.
$ openssl req -new -key server.key -out server.csr -config openssl.cnf
Step 3: Generating Certificates. The CSR file needs to have the CAs signature to form a certificate. In
the real world, the CSR files are usually sent to a trusted CA for their signature. In this lab, we will use our
own trusted CA to generate certificates:

44

Network Security Course - November 2014

$ openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key \


-config openssl.cnf
If OpenSSL refuses to generate certificates, it is very likely that the names in your requests do not match
with those of CA. The matching rules are specified in the configuration file (look at the [policy match]
section). You can change the names of your requests to comply with the policy, or you can change the policy.
The configuration file also includes another policy (called policy anything), which is less restrictive.
You can choose that policy by changing the following line:
"policy = policy_match"

change to "policy = policy_anything".

Include all generated files (certificates, etc.) in your submission.

3.4

Task 4: Use PKI for Web Sites

If you do this part on a university computer, you will be unable to modify the hosts file. In this case, please
take a look at it, but continue on without changing it.
In this lab, we will explore how public-key certificates are used by web sites to secure web browsing.
First, we need to get our domain name. Let us use PKILabServer.com as our domain name. To get our
computers recognize this domain name, the following entry should be added to /etc/hosts; this entry
basically maps the domain name PKILabServer.com to our localhost (i.e., 127.0.0.1):
127.0.0.1

PKILabServer.com

In Windows, this file can be found under


C:\Windows\System32\Drivers\etc\hosts
Please, after adding this line to the file, make sure that it works:
$ ping pkilabserver.com
PING PKILabServer.com (127.0.0.1): 56 data
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64

bytes
time=0.058 ms
time=0.103 ms
time=0.081 ms

Next, let us launch a simple web server with the certificate generated in the previous task. OpenSSL
allows us to start a simple web server using the s server command:
# Combine the secret key and certificate into one file
% cp server.key server.pem
% cat server.crt >> server.pem
# Launch the web server using server.pem
% openssl s_server -cert server.pem -www
By default, the server will listen on port 4433. You can alter that using the -accept option. If you
are doing the lab on the university computers, please choose a port number between 30000 and 39999,
and use it throughout the rest of the exercise instead of 4433. Now, you can access the server using the
following URL: https://PKILabServer.com:4433/. Most likely, you will get an error message

45

Network Security Course - November 2014

from the browser. In your browser, you will see a message like the following: pkilabserver.com:4433 uses
an invalid security certificate. The certificate is not trusted because the issuer certificate is unknown.
Had this certificate been assigned by VeriSign, we will not have such an error message, because VeriSigns
certificate is very likely preloaded into your browsers certificate repository already. Unfortunately, the
certificate of PKILabServer.com is signed by our own CA (i.e., using ca.crt), and this CA is not
recognized by the browser. There are two ways to get Firefox to accept our CAs self-signed certificate.
1. We can request Mozilla to include our CAs certificate in its Firefox software, so everybody using
Firefox can recognize our CA. This is how the real CAs, such as VeriSign, get their certificates into
Firefox. Unfortunately, our own CA does not have a large enough market for Mozilla to include our
certificate, so we will not pursue this direction.
2. Load ca.crt into Firefox: We can manually add our CAs certificate to the Firefox browser by
clicking the following menu sequence:
Edit -> Preference -> Advanced -> View Certificates.
You will see a list of certificates that are already accepted by Firefox. From here, we can import our
own certifcate. Please import ca.crt, and select the following option: Trust this CA to identify
web sites. You will see that our CAs certificate is now in Firefoxs list of the accepted certificates.
Now, point the browser to https://PKILabServer.com:4433. Please describe and explain your
observations. Please also do the following tasks:
1. Modify a single byte of server.pem, and reload the URL. What do you observe? Make sure you
restore the original server.pem afterward.
2. Since PKILabServer.com points to the localhost, if we use https://localhost:4433 instead, we will be connecting to the same web server. Please do so, describe and explain your observations.
Include screenshots of your navigator showing the stages through which you have passed during
this task.

3.5

Task 5: Performance Comparison: RSA versus AES

In this task, we will study the performance of public-key algorithms. Please prepare a file (message.txt)
that contains a 16-byte message. Please also generate an 1024-bit RSA public/private key pair. Then, do the
following:
1. Encrypt message.txt using the public key; save the the output in message enc.txt.
2. Decrypt message enc.txt using the private key.
3. Encrypt message.txt using a 128-bit AES key.
4. Compare the time spent on each of the above operations, and describe your observations. If an operation is too fast, you may want to repeat it for many times, and then take an average. You might want
to look at the Linux command time which measures the duration of the execution of a command.
5. Try running the tests over a significant number of repetitions, e.g. 1000 or more executions of the
command. Hint: use a script that runs the command the required number of times, and then use the
command time to calculate the overall time of execution.

46

Network Security Course - November 2014

Submission

You need to submit a detailed lab report to describe what you have done and what you have observed; you
also need to provide explanation to the observations that are interesting or surprising. In your report, you
need to answer all the questions listed in this lab.
The rules for the submission are:
1. Submit an archive containing all generated files, along with your report. (except the certificates you
generated from CACert, which you may wish to continue using afterwards).
2. Provide your report in PDF format.
3. Name the file of the archive youre submitting in the following way : NAME1 NAME2 NAME3TP Crypto
4. Limit the size of your report to no more than 11 pages.
Please, send your report by email to sandrine.vaton@telecom-bretagne.eu

This Lab is based on the Labs developed by Sylvain Gombault, TELECOM Bretagne and Wenliang Du,
Syracuse University.
0

The development of this document is funded by three grants from the US National Science Foundation:
Awards No. 0231122 and 0618680 from TUES/CCLI and Award No. 1017771 from Trustworthy Computing.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free
Documentation License, Version 1.2 or any later version published by the Free Software Foundation. A copy
of the license can be found at http://www.gnu.org/licenses/fdl.html.

47

RSA Tutorial

Tutorial sur lalgorithme RSA


Sandrine Vaton
Tlcom Bretagne, Dpartement Informatique

Juin 2013

S. Vaton (TB/INFO)

RES201

Juin 2013

1 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit
49
S. Vaton (TB/INFO)

RES201

Juin 2013

2 / 36

Algorithme RSA
RSA : Rivest, Shamir, Adleman ; premier algorithme de chiffrement
cl publique et toujours le plus rpandu
trs utilis dans le commerce lectronique, et plus gnralement pour
changer des donnes confidentielles sur Internet.
invent en 1977, brevet par le MIT en 1983, brevet tomb dans le
domaine public en 2000
scurit base sur la difficult du problme de factorisation de grands
entiers (en un produit de deux nombres premiers) :
N = p q,
I
I

avec p et q premiers

le calcul de N partir de p et q a une complexit polynmiale


(multiplication) ;
par contre, retrouver p et q premiers partir de leur produit N est un
problme NP-complet

S. Vaton (TB/INFO)

RES201

Juin 2013

3 / 36

Le RSA en bref (1/2)


Gnration de Cls
1

choisir 2 grands entiers premiers p et q et calculer leur produit


N = p q.

calculer (N) = (p 1)(q 1) et choisir un entier e premier avec


(N),

calculer laide de lalgorithme dEuclide tendu linverse d de e


modulo (N) : d = e 1 mod (N).

La cl publique est le couple (e, N) et la cl prive est d . Les facteurs


premiers p et q de N doivent tre maintenus privs.
Exemple :
p = 11 q = 23 N = p q = 253
(N) = (p 1)(q 1) = 10 22 = 220
e = 3 d = 147

50
S. Vaton (TB/INFO)

RES201

Juin 2013

4 / 36

Chiffrement et dchiffrement avec RSA


Chiffrement avec RSA
Le message en clair est identifi un entier M dfini modulo N et
premier avec N : 2 M N 1, M 6= p, M 6= q.

Pour envoyer un message Bob, Alice cherche la cl publique (e, N)


de Bob (dans un annuaire appropri), et elle calcule le message chiffr
C = M e mod [N] quelle envoie Bob.
Dchiffrement avec RSA
Pour dchiffrer le message C , Bob prend sa cl prive d et calcule
C d mod [N].
On peut montrer que la valeur obtenue C d mod [N] = (M e )d
mod [N] est gale M.
N est le module RSA ; e est lexposant de chiffrement (cl publique) ; d est
lexposant de dchiffrement (cl secrte) ; les facteurs p et q de N sont
maintenus privs.
S. Vaton (TB/INFO)

RES201

Juin 2013

5 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit
51
S. Vaton (TB/INFO)

RES201

Juin 2013

6 / 36

Bases pour le RSA

Nous avons besoin de quelques bases pour prsenter lalgorithme


RSA :
I
I
I
I
I

bases sur larithmtique modulaire


tests de primalit (Fermat, Miller-Rabin) gnration de la cl secrte
algorithme dEuclide tendu gnration de lexposant de
dchiffrement partir de lexposant de chiffrement
algorithme dexponentiation rapide fonctions de chiffrement et
dchiffrement
fonction indicatrice dEuler, thorme dEuler preuve du RSA

sance de Travaux Pratiques :


I

implmentation de lalgorithme RSA en langage C

S. Vaton (TB/INFO)

RES201

Juin 2013

7 / 36

Juin 2013

8 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit

52
S. Vaton (TB/INFO)

RES201

Arithmtique Modulaire
Elments de ZN :
un entier a est dit quivalent un autre entier b si la diffrence entre
a et b est un multiple de N
ceci dfinit une relation dquivalence entre nombres entiers
la classe dquivalence de a est identifie au reste de la division entire
de a par N
Oprations lmentaires dans ZN :
somme : amod [N] + bmod [N] = (a + b)mod [N],
diffrence : amod [N] bmod [N] = (a b)mod [N],
produit : (amod [N]).(bmod [N]) = (a.b)mod [N].

A partir du produit modulaire on dfinit lexponentiation modulaire :


a0 mod [N] = 1, a1 mod [N] = a, a2 mod [N] = a.amod [N] et par rcurrence
an mod [N] = an1 mod [N].amod [N].
S. Vaton (TB/INFO)

RES201

Juin 2013

9 / 36

Inversion Modulaire

Soit N un entier. Un entier a est inversible modulo N si et seulement si il


existe un entier b tel que a b = 1 mod [N]. Lentier b est appel linverse
de a modulo N et est not a1 dans larithmtique modulo[N] note ZN .
a est inversible modulo N si et seulement si a et N sont premiers entre eux.
Exemples :
N = 30, a = 17, a est inversible modulo N et son inverse est b = 23
car 23 17 = 391 = 1 mod[N].
a = 18 nest pas inversible modulo N = 30 car 18 et 30 ne sont pas
premiers entre eux.

53
S. Vaton (TB/INFO)

RES201

Juin 2013

10 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit

S. Vaton (TB/INFO)

RES201

Juin 2013

11 / 36

Thorme dEuler

Thorme dEuler : si N est un entier naturel et si a est premier avec N


alors
a(N) = 1 mod [N]
o (N) est la fonction indicatrice dEuler.
Rem1 : le thorme dEuler gnralise le petit thorme de Fermat.
Rem2 : ce thorme fonde le test de primalit dit test de Fermat.
Rem3 : la preuve du RSA repose sur le thorme dEuler.

54
S. Vaton (TB/INFO)

RES201

Juin 2013

12 / 36

Preuve du RSA
La preuve repose sur le fait que ZN (ensemble des entiers plus petits
que N, diffrents de p et q, pris modulo N et muni de la
multiplication) est un groupe cyclique dordre (N).
Nous devons montrer que C d mod [N] = M quand C = M e
mod [N] avec M diffrent de 1, p et q.
C d mod [N] = (M e )d mod [N] = M e d
e d = 1 mod [(N)] = 1 + k (N)
M e d mod [N] = M 1+k (N) mod [N]
= M (M (N) )k mod [N]

mod [N]

et daprs le th. dEuler M (N) = 1 mod [N] donc


Cd

S. Vaton (TB/INFO)

mod [N] = M

RES201

Juin 2013

13 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit
55
S. Vaton (TB/INFO)

RES201

Juin 2013

14 / 36

Algorithme dEuclide (1/2)


Entres : deux nombres entiers N et K (N > K )
Sortie : PGCD(N,K), le plus grand commun diviseur de N et K .
N
K
r0

= K q0 + r0
= r0 q1 + r1
= r1 q2 + r2
..
.

rm2 = rm1 qm + rm
rm1 = rm qm+1
Lalgorithme se termine quand le reste est nul. Le PGCD de N et de K est
le dernier reste non nul rm .

S. Vaton (TB/INFO)

RES201

Juin 2013

15 / 36

Juin 2013

16 / 36

Algorithme dEuclide (2/2)

Exemple 1 : N = 72, K=54


72 = 54 1 + 18
54 = 3 18

PGCD(N, K ) = 18
Exemple 2 : N=1848, K=945, PGCD(N,K)= ?
Exemple 3 : N=4862, K=1320, PGCD(N,K)= ?

56
S. Vaton (TB/INFO)

RES201

Algorithme dEuclide tendu (1/3)

Entres : deux entiers N et K (N > K )


Sorties : PGCD(N,K) ainsi que les coefficients u et v de lidentit de Bezout
u N + v K = PGCD(N, K )
Principe :
construire rcursivement des coefficients ai et bi tels que
ai N + bi K = ri en combinant les galits euclidiennes ;
terme on obtient u = am et v = bm puisque pgcd(N, K ) = rm
(dernier reste non nul).

S. Vaton (TB/INFO)

RES201

Juin 2013

17 / 36

Algorithme dEuclide tendu (2/3)


Egalits euclidiennes :
ri2 = ri1 qi + ri
en posant N = r2 , et K = r1
Initialisation :
r2 = N
r1 = K

donc a2 = 1, b2 = 0
donc a1 = 0, b1 = 1

Rcursion :
ri
ai
bi

=
=
=
=
=

ri2 ri1 qi
(ai2 N + bi2 K ) (ai1 N + bi1 K )qi
(ai2 ai1 qi )N + (bi2 bi1 qi )K
ai2 ai1 qi
bi2 bi1 qi
57

S. Vaton (TB/INFO)

RES201

Juin 2013

18 / 36

Algorithme dEuclide tendu (3/3)

Complexit
chaque itration la valeur du reste est au minimum divise par 2 ;
par consquent le nombre ditrations est born par 2 log2 (N) ;
chaque itration requiert une division, un reste, deux multiplications et
deux soustractions sur des nombres de longueur au plus log2 (N) bits ;
par consquent la complexit de chaque itration est borne par
C1 (log2 N)2
au total la complexit de lAEE est borne par C2 (log2 N)3 , donc
complexit polynmiale.

S. Vaton (TB/INFO)

RES201

Juin 2013

19 / 36

Inversion Modulaire
Soit un entier N et a, un entier premier avec N. Lalgorithme dEuclide
tendu donne un moyen de calculer linverse de a modulo N.
En effet PGCD(a, N) = 1 et lidentit de Bezout scrit :
u N + v a = 1 et donc v a = 1mod [N]
Par consquent le coefficient v de lidentit de Bezout est linverse de a
modulo N :
v = a1 mod [N]
Utilis pour calculer lexposant de dchiffrement d qui doit vrifier d = e 1
mod (N).

58
S. Vaton (TB/INFO)

RES201

Juin 2013

20 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit

S. Vaton (TB/INFO)

RES201

Juin 2013

21 / 36

Algorithme dexponentiation rapide (1/2)


Objectif : calculer rapidement me mod [N]
un calcul direct ncessiterait e multiplications modulaires
Remarque : e peut aussi scrire (reprsentation binaire pure)
P
e = i ei 2i
ei {0, 1}
et donc

me

mod [n] =

2
i/ei =1 m

mod [n]

Il suffit donc de calculer les facteurs m2 mod [n]


()2

()2

()2

()2

m m2 m2 m2
log2 (e) + 1 carrs modulaires au lieu de e multiplications modulaires
59
S. Vaton (TB/INFO)

RES201

Juin 2013

22 / 36

Algorithme dexponentiation rapide (2/2)

Complexit
log2 (e) + 1 multiplications,
chaque multiplication se fait sur des nombres de longueur au plus
log2 (N) + 1 bit donc la complexit de chaque multiplication est
C1 (log2 (N))2 [si multiplication scolaire],
par consquent la complexit de lalgorithme dexponentiation rapide
est C2 (log2 (N))2 log2 (e).

S. Vaton (TB/INFO)

RES201

Juin 2013

23 / 36

Juin 2013

24 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit

60
S. Vaton (TB/INFO)

RES201

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit

S. Vaton (TB/INFO)

RES201

Juin 2013

25 / 36

Scurit du RSA (1/3)

La scurit du RSA repose sur la difficult du problme de


factorisation dun entier en produit de deux grands facteurs premiers.
On peut montrer que les deux problmes suivants sont quivalents :
1
2

connaissant e et N (cl publique) retrouver la valeur de d (cl prive) ;


trouver les facteurs p et q de N.

61
S. Vaton (TB/INFO)

RES201

Juin 2013

26 / 36

Scurit du RSA (2/3)


Si on connat p et q alors on peut calculer (N) = (p 1).(q 1) et,
partir de e (cl publique), retrouver la valeur de d par inversion
modulaire.
Si on connat (e, N) (cl publique) et d (cl prive) on peut retrouver
raisonnablement facilement p et q.
En effet si on connaissait non seulement N mais aussi (N) on
trouverait p et q comme les racines de lquation du second degr :
()

x 2 (N + 1 (N))x + N = 0

En effet le produit des racines de (*) est N = p.q et la somme des


racines est p + q == N + 1 (N) puisque
(N) = (p 1)(q 1) = p.q (p + q) + 1 = N (p + q) + 1.

S. Vaton (TB/INFO)

RES201

Juin 2013

27 / 36

Scurit du RSA (3/3)


Supposons connatre e et d . On sait que (N) divise e d 1 puisque
e d = 1 mod (N) = 1 + k (N).
e est gnralement petit (rapidit du chiffrement), par ailleurs d < (N)
par consquent k est petit (de lordre de quelques milliers) et (N) est
grand.
On explore les diffrentes valeurs possibles de k (en commenant par les
plus petites), et pour chaque valeur (N) correspondante, on dtermine si
lquation (*) a des racines entires. Si (*) a des racines entires alors ces
racines sont p et q.

62
S. Vaton (TB/INFO)

RES201

Juin 2013

28 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit

S. Vaton (TB/INFO)

RES201

Juin 2013

29 / 36

Construction de Cls en RSA (1/2)

aujourdhui on considre que pour que lalgorithme soit sr il faut que


N soit de longueur minimale 1024 bits ; les longueurs de cl sont
habituellement comprises entre 1024 et 2048 bits.
par ailleurs, pour viter que lon puisse factoriser N il faut que chacun
des facteurs p et q soit grand (longueur de lordre de 512 bits au
minimum) ;
il faut que la diffrence entre p et q soit elle-mme grande (longueur
minimale de 500 bits cest--dire que p et q doivent prsenter au
moins une diffrence sur les 12 premiers bits).

63
S. Vaton (TB/INFO)

RES201

Juin 2013

30 / 36

Construction de Cls en RSA (2/2)

Mthode de factorisation de Fermat :


Supposons par exemple que p > q et notons p = s + t et q = s t. Alors
N = p.q = (s + t).(s t) = s 2 t 2 .
Si la diffrence 2t entre p et q est petite on retrouve facilement p et q.
En effet on remarque que N + t 2 = s 2 et on retrouve s et t en testant une
par une les valeurs de t de longueur faible (disons quelques millions de
valeurs) et on cherche la valeur t pour laquelle lquation N + t 2 = s 2
possde une solution s entire.

S. Vaton (TB/INFO)

RES201

Juin 2013

31 / 36

Juin 2013

32 / 36

Sommaire
1

Description

Bases
Arithmtique modulaire
Preuve du RSA
Inversion Modulaire
Exponentiation Modulaire

Scurit du RSA
Factorisation dun grand entier
Cls RSA

Tests de primalit

64
S. Vaton (TB/INFO)

RES201

Tests de Primalit

Pour pouvoir gnrer les facteurs p et q il faut tre capable


de gnrer un nombre au hasard : gnrateurs pseudo-alatoires,
de tester si ce nombre est un nombre premier : tests de primalit
Les tests de primalit sont donc un sujet particulirement important en
cryptographie cl publique.
Dans le cadre de ce cours nous allons tudier deux tests de primalit (dits
probabilistes) :
le test de Fermat,
le test de Miller-Rabin.

S. Vaton (TB/INFO)

RES201

Juin 2013

33 / 36

Test de Fermat (1/2)


Thorme de Fermat :
Soit p un entier premier. Alors pour tout nombre a 6= 0 mod [p] on a le
rsultat suivant :
ap1 = 1 mod [p]
Rem : Le thorme de Fermat est un cas particulier du thorme dEuler.
Test de Fermat :
Cest un des tests de primalit les plus simples. Le test repose sur le
principe suivant :
choisir une base a au hasard (2 a p 1) et calculer ap1 mod [p] ;
si le rsultat est diffrent de 1 alors p est composite ;
si le rsultat est 1 alors p est peut-tre premier ;
rpter la procdure un grand nombre de fois tant quon na pas trouv de
base a pour laquelle p ne passe pas le test.
65
S. Vaton (TB/INFO)

RES201

Juin 2013

34 / 36

Test de Fermat (2/2)


Le test de Fermat est un test probabiliste :
sil existe une base a0 pour laquelle p ne passe pas le test alors p ne
passe pas le test pour au moins la moiti des bases ;
il est alors trs peu probable que, quand on augmente le nombre de
bases a, on nen trouve pas au moins une pour laquelle p ne passe pas
le test ;
par contre on ne peut jamais tre sr que p nest pas un nombre
composite car il existe de (trs rares) nombres composites p qui
passent le test pour toute valeur de a ;
ces nombres sont appels nombres pseudo-premiers ou nombres de
Carmichael ; le plus petit dentre eux est 561 = 3 11 17.

Malgr lexistence de nombres de Carmichael, le standard RSA a utilis le


test de Fermat comme test de primalit jusquen 1997.

S. Vaton (TB/INFO)

RES201

Juin 2013

35 / 36

Juin 2013

36 / 36

Tests probabilistes de primalit

Il existe diffrents tests probabilistes de primalit.


Les plus connus dentre eux sont :
test de Fermat
test de Miller-Rabin
test de Solovay-Strassen
Voir la description de ces tests sur Wikipedia par exemple.

66
S. Vaton (TB/INFO)

RES201

RSA Lab

Travaux Pratiques RSA


Module F2B401B, Introduction `a la Cryptographie
janvier 2007
1. Algorithme dEuclide : cet algorithme fournit le plus grand commun diviseur de deux nombres (PGCD).
Questions :
Completer la procedure PGCD dans le programme euclide.c
Compiler et tester pour differents couples dentiers (A,B).
Voir la description de lalgorithme dEuclide en annexe.
2. Algorithme dEuclide etendu : cet algorithme fournit les coefficients (u, v, d) de lidentite de Bezout o`
u
d = P GCD(A, B) et o`
u u et v sont deux entiers tels que u A + v B = d.
Utilisation : cet algorithme sert `
a determiner lexposant de dechiffrement RSA d tel que e d = (n) o`
u d,
lexposant de chiffrement RSA, est premier avec (n) = (p 1)(q 1) (n = pq etant le module RSA).
Principe : construire recursivement des coefficients ui et vi tels que ui A + vi B = ri o`
u ri est le reste de la
division euclidienne dans lalgorithme dEuclide.
Voir la description de lalgorithme dEuclide etendu et de son implementation en annexe.
Dans le programme euclidee.c,
La fonction Update realise h = hh et hh = h hh k.
A quoi va servir la fonction Update ?
Remarquer lutilisation des pointeurs dans la fonction Update. Quel est linteret de lutilisation de
pointeurs ?
La procedure EuclideExtended calcule les coefficients (u, v, d) de lidentite de Bezout. Cette procedure
fait appel `
a la procedure Update.
Completer la procedure EuclideExtended.
Completer le main par un appel `
a la procedure EuclideExtended.

Le main permet de calculer les coefficients de lidentite de Bezout pour 2 entiers saisis au clavier.
Compiler et tester avec differentes valeurs de A et B.

69

3. Inversion Modulaire.
Lorsque A et N sont premiers entre eux lidentite de Bezout secrit u A + v N = 1 et donc u est linverse de
A modulo N puisque u A = 1 + v N = 1 mod [N ].
Le programme invmod.c fournit linverse modulo N de A si A et N sont premiers entre eux.
Dans le programme invmod.c,
completer la procedure EuclideExtended
completer le main :

appel `
a la procedure EuclideExtended,
faire afficher linverse de A modulo N .
compiler et tester.
4. Exponentiation modulaire.
Lalgorithme dexponentation rapide permet de calculer lexponentielle modulaire ax mod [n] avec une complexite numerique de lordre de log2 (x) au lieu de x pour la methode directe.
Le programme expmod.c permet de comparer la methode directe et la methode rapide.
La methode directe est donnee (fonction ModExp2). On vous demande :
dimplemeter la methode rapide (completer la fonction ModExp1),

comparer les resultats donnes par ModExp1 et ModExp2.


5. Tests de primalite.

De nombreux algorithmes cryptographiques necessitent de generer des tr`es grands nombres premiers. En
particulier, le module RSA n est le produit de deux facteurs premiers p et q. Il est donc vital de savoir
generer des nombres premiers avec un co
ut de calcul aussi faible que possible.
Dans ce TP on propose de generer des nombres entiers aleatoires et de tester leur primalite par le test de
Fermat. Le test de Fermat est expose en Annexe.
Dans primal.c :
completer la procedure Premier

completer et tester pour differentes valeurs de N


6. Chiffrement et Dechiffrement RSA.
Ecrire votre propre programme qui :
gen`ere aleatoirement les facteurs p et q premiers

gen`ere aleatoirement lexposant de chiffrement e, premier avec (n) = (p 1)(q 1)


calcule lexposant de dechiffrement correspondant d

70

produit aleatoirement un message (entier compris dans [1...N-1]), le chiffre, puis oublie ce message
et le retrouve en dechiffrant le cryptogramme ; afficher les valeurs du message en clair, du chiffre et du
message obtenu apr`es dechiffrement `
a lecran.
Question subsidiaire : densite des nombres premiers.
On rappelle le theor`eme de Tchebichev : le nombre dentiers premiers plus petits que N est approximativement
egal `a N/ log(N ). Verifier par simulation le theor`eme de Tchebichev sur la densite des nombres premiers.

71

Chiffrement RSA
n est un entier produit de deux nombres premiers p et q :
n=pq
n est appele module RSA.
Lexposant de chiffrement e est un entier premier avec (n) = (p 1)(q 1) ((n) est lindicateur dEuler de
n).
Lexposant de dechiffrement d est linverse de e modulo (n) :
d e = 1 mod (n)
Le message m est un entier compris entre 1 et n 1, le chiffre c est egalement un entier compris entre 1 et n 1.
Chiffrement
Le chiffre c est obtenu par :
c = me mod [n]
Dechiffrement
Le message est obtenu par :
m = cd

mod [n]

72

Algorithme dEuclide
Lalgorithme dEuclide permet de determiner le p.g.c.d. de 2 entiers A et B (B < A) sans faire appel `a leur
factorisation.
A
= B q0 + r0
B
= r0 q1 + r1
r0
= r1 q2 + r2
..
.
rm2 = rm1 qm + rm
rm1 = rm qm+1
Lalgorithme se termine quand le reste est nul. Le pgcd de A et de B est le dernier reste non nul rm .

73

Algorithme dEuclide
etendu
Cet algorithme determine, en plus de PGCD(A,B), 2 entiers u et v tels que
u A + v B = P GCD(A, B).
Comment ? On construit recursivement, en combinant les egalites euclidiennes, des coefficients ui et vi tels que ui A +
vi B = ri .
A terme on obtient u = um et v = vm puisque P GCD(A, B) = rm (dernier reste non nul).
Egalites euclidiennes :
ri2 = ri1 qi + ri
avec A = r2 , et B = r1
Initialisation :
r2 = A
r1 = B

donc
donc

u2 = 1, v2 = 0
u1 = 0, v1 = 1

Puis, par recurrence :


ri

=
=
=

ui
vi

=
=

ri2 ri1 qi
(ui2 A + vi2 B) (ui1 A + vi1 B)qi
(ui2 ui1 qi ) A + (vi2 vi1 qi ) B
|
{z
}
|
{z
}
ui2 ui1 qi
vi2 vi1 qi

Impl
ementation de lalgorithme dEuclide
etendu
Initialisation :
dividende = A diviseur = B
u=1
v=0
uu = 0
vv = 1
Tant que (diviseur <> 0) faire
quotient = dividende / diviseur (division enti`ere)
reste = dividende-diviseur*quotient
dividende diviseur
diviseur reste
unew = = u-uu*quotient
u uu
uu unew
vnew = v-vv*quotient
v vv
vv vnew

74

Exponentiation modulaire
Objectif : calculer me mod [n].
Remarque : e peut aussi secrire (representation binaire pure)
e=

ei 2i

ei {0, 1}

et donc
me
i

Il suffit donc de calculer les facteurs m2

mod [n] =

i/ei =1

m2

mod [n]

mod [n]
()2

()2

2 ()2

m m2 m2

3 ()2

m2

log2 (e) carr


es modulaires au lieu de e multiplications modulaires

75

Rappels sur le test de Fermat


Ce test repose sur le petit theor`eme de Fermat qui dit que :
si N est premier, et si a 6= 0 mod [N ] alors aN1 = 1 mod [N ].
On sait aussi que :
si N est premier on a toujours cette egalite (quelque soit la base a)
si N nest pas premier il se peut que, pour certaines valeurs de la base a, cette egalite soit quand meme verifiee : mais
rassurez-vous, cest quand meme rare...
Soit N un entier (impair). On cherche `
a determiner, avec une probabilite derreur aussi petite que possible, si N est
premier.
Test de Fermat :
generer un nombre aleatoire a dans 2, 3, . . . , N 1

calculer a(N1)/2 mod [n]

si a(N1)/2 mod [n] est different de 1 et 1 alors N nest pas premier (et cest sr)

si a(N1)/2 mod [n] est egal `


a 1 ou 1 alors N a de grandes chances detre premier
Bien sr, les grincheux vous diront que cela ne marche pas `
a tous les coups :
il existe des nombres N non premiers pour lesquels legalite a(N1)/2 mod [N ] {1, 1} est verifiee pour certaines
valeurs de la base a : ce sont les nombres pseudo premiers (qui portent aussi le joli nom de nombres de Poulet).
Exemple : 341 est pseudo-premier pour la base 2.
Il y en a meme (les coquins) pour lesquels legalite a(N1)/2 mod [N ] {1, 1} est toujours vraie, quelque soit la
base a choisie ! Ces nombres sont appeles nombres de Carmichael, ou encore nombres pseudo premiers absolus.
Exemple : le plus petit dentre eux est 561 (561 = 11 3 17).
Si on a lidee de se dire que le test de Fermat ne marche pas mais quen essayant differentes valeurs de la base a, par
recoupement on devrait y arriver, on a perdu puisque N peut tr`es bien etre un nombre de Carcmichael.
Cependant, les nombres de Carmichael sont tr`es rares. Ainsi la proportion de nombres pseudo premiers pour la base 2
est inferieure `
a 1 sur 1 million pour les entiers jusqu`
a 25 milliards, et cette proportion est encore plus petite pour N grand.
Donc on peut appliquer le test de Fermat avec une fiabilite relativement grande.

76

Public Key Cryptography Exercices

FORMULAIRE DEXERCICES DE CRYPTOGRAPHIE


TELECOM Bretagne
Novembre 2014
Question1
Chiffrement de Csar
Le chiffrement de Csar est le schma de chiffrement par substitution mono-alphabtique le plus
simple. Il sagit dun chiffrement par dcalage qui consiste simplement dcaler les lettres de lalphabet dun nombre de crans constant vers la droite.
Dcrypter le texte suivant qui a t obtenu en appliquant le chiffre de Csar sur un texte en langue
franaise dans lequel les espaces ont t supprims :

Indice : lhistogramme suivant vous donne la frquence dapparition des lettres en franais

Question2
Algorithme dEuclide tendu
Calculer linverse de 7 modulo 40.

79

Question3
Exponentiation modulaire
Calculer 27 mod 55, puis 1823 mod 55.
Question4
Echange de cl de Diffie Hellman
1. Vrifier que g = 2 est un gnrateur du groupe multiplicatif Z11 .
2. Quel est le secret commun qutablissent Alice et Bob en utilisant le protocole de Diffie-Hellman
avec p = 11 et g = 2 si les nombres alatoires quils ont choisi sont xA = 7 et xB = 8.
Question5
RSA
Soit p = 3, q = 13, n = pq = 39 et e = 29.
1. Calculer d tel que ed = 1mod(n).
2. Chiffrer le message m = 2 et vrifi
er le rsultat en le dchiffrant.
Question6
RSA
Vous interceptez le cryptogramme c = 10 qui a t obtenu par chiffrement RSA avec la cl publique
n = 35 et e = 5. Quel est le message clair ?
Question7
O lon apprend quil est dangereux de partager les modules RSA
Supposons que dans un systme de chiffrement RSA on attribue des couples (cl publique, cl secrte),
(e1 , d1 ) et (e2 , d2 ), associs un mme module RSA N deux utilisateurs diffrents.
1. Montrer quun utilisateur peut facilement retrouver la factorisation de N partir de son propre
couple (e, d) et du module N .
2. Que peut-on en dduire quant la scurit du systme ?
Supposons maintenant que dans le systme on attribue le mme module RSA un groupe dutilisateurs qui se font mutuellement confiance. Nous allons voir quune personne externe peut facilement
attaquer ce systme.
Supposons quon envoie un mme message m, en le chiffrant, deux utilisateurs dont les cls publiques
e1 et e2 sont premires entre elles. Lattaquant externe peut retrouver le clair m partir des chiffrs
c1 et c2 .
3. Enoncer lidentit de Bezout vrifie par e1 et e2 . Quel algorithme ladversaire peut-il utiliser
pour retrouver les coefficients u et v de cette identit ?
4. Lattaquant externe calcule cu1 cv2 modulo N. Pourquoi ?
Question8
Gnrateur de cls RSA
Voici un gnrateur de cls RSA crit en Java

Page 2

80

import java.io.*;
import java.math.BigInteger;
import java.util.Random;
class genRSA {
public static void main(String arg[]) {
BigInteger P,P1,Q,Q1,N,PHI,E,D;
Random alea = new Random();
E = BigInteger.valueOf(65537);
do {
P = new BigInteger(512,20,alea);
P1 = P.subtract(BigInteger.ONE);
} while (P1.gcd(E).equals(BigInteger.ONE) == false);
do {
Q = new BigInteger(512,20,alea);
Q1 = Q.subtract(BigInteger.ONE);
} while (Q1.gcd(E).equals(BigInteger.ONE) == false);
N = P.multiply(Q);
PHI = P1.multiply(Q1);
D = E.modInverse(PHI);
System.out.println("n = " + N.toString(16));
System.out.println("e = " + E.toString(16));
System.out.println("d = " + D.toString(16));
}
}
dont voici une trace dexcution
$ java genRSA
n = b3414836c17988f4399739494cbc39ffd5727dd7b16a065ddb84afa749e080d616b0a10ede6
19b8e698fb5d2848632033d2c94dde6500ccb543c6a50ba65269c6320a8db75da4aee8f09f49072
d413fb7d347c05ef6c5a427d4366f46d6b6f4f20bce39dc3f89b9bec805bb7251f2ddc994ce88af
4e646760b7802be3f049a81
e = 10001
d = 6d02a356e13bf6c4870d6702238f483a43e4f790a74cd2085c0a0a0453121b6796aedd933c3
be1acae977dbc4369949a91a63df5e02d084ad2b456f7371372719d443012b6d18f1376d4a1a8ab
5af4e3f01cd22e3561f0f353b711a981d35ab45e900111676b01d5e1e20f7577033e4b25103264f
a6f5c8f1b485055e8a86f7d
$
Voici un extrait de la spcification de la classe Random

Page 3

81

public class Random


extends Object
implements Serializable
An instance of this class is used to generate a stream of pseudorandom numbers.
The class uses a 48-bit seed, which is modified using a linear congruential formula.
(See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)
[...]
Random
public Random()
Creates a new random number generator. Its seed is initialized to a value based
on the current time:
public Random() { this(System.currentTimeMillis()); }
Two Random objects created within the same millisecond will have the same sequence
of random numbers.
et un extrait de celle de BigInteger
BigInteger
public BigInteger(int bitLength,
int certainty,
Random rnd)
Constructs a randomly generated positive BigInteger that is probably prime,
with the specified bitLength.
It is recommended that the probablePrime method be used in preference to this
constructor unless there is a compelling need to specify a certainty.
Parameters:
bitLength - bitLength of the returned BigInteger.
certainty - a measure of the uncertainty that the caller is willing to
The probability that the new BigInteger represents a prime
will exceed (1 - 1/2certainty). The execution time of this
is proportional to the value of this parameter.
rnd - source of random bits used to select candidates to be tested for

tolerate.
number
constructor
primality.

1. Daprs vous que reprsente la variable E ? Quel est le poids de Hamming de E (nombre de bits
1) ? Pourquoi avoir choisi cette valeur ?
2. Que reprsentent les variables P et Q ? Quel est le rle des boucles do ... while (...) qui les
dfinissent ?
3. Quelle est la taille des cls RSA gnres ?
4. Indiquez pourquoi ce gnrateur noffre pas une scurit suffisante en proposant une mthode
dattaque dont vous valuerez la complexit.
Question9
Monnaie numrique anonyme
On propose un protocole cryptographique permettant de produire une monnaie numrique. Cette
monnaie numrique doit avoir les mmes proprits que la monnaie papier, savoir que :
seule la banque est capable de forger des units montaires
il ny a pas de traabilit des transactions entre vendeur et acheteur

Page 4

82

La Banque rend publiques une fonction sens unique f () et une cl publique RSA (n, e). La cl d
correspondante est garde secrte.
LAcheteur utilise les services de la Banque pour produire une unit montaire (x, X) comme spcifi
sur le schma. Le Vendeur vrifie que lunit montaire est valide, cest--dire sassure que lAcheteur
a bien utilis les services de la Banque pour produire cette unit. La mthode de vrification est
donne sur le schma.

Monnaie numrique anonyme.


1. Comment est garantie lanonymisation de la transaction ?
2. Quest-ce-qui garantit que la banque est la seule pouvoir fabriquer de la monnaie ?

Page 5

83

Question10
3-coloriabilit dun graphe
Soit G un graphe k sommets. Le graphe possde des artes. Chaque arte relie deux sommets du
graphe. Dun sommet peut partir un nombre arbitraire dartes.
Un graphe G est dit 3-coloriable si on peut affecter chaque sommet de G une couleur parmi trois
(par exemple, jaune, rouge et bleu) de telle faon quaucune arte de G ne soit colorie de la mme
couleur ses deux sommets extrmit.
Le problme gnral du 3-coloriage est un problme NP-complet : si G est un graphe quelconque,
trouver un 3-coloriage de G (sil en a effectivement un) est un problme trs difficile.
On se propose de construire un protocole zero-knowledge en utilisant ce problme. On rappelle les
trois principes dun protocole zero-knowledge :
toute personne autorise arrive toujours sauthentifier,
une personne non autorise finit toujours par se trahir,
un espion qui observe une personne autorise sauthentifier ne doit rien apprendre qui lui permettrait de sauthentifier.
Dans cet exercice nous allons considrer quatres personnes : le Prouveur, le Vrifieur, le Tricheur et
lEspion.
Le Prouveur commence par gnrer un graphe 3-coloriable : par exemple, il gnre k sommets auxquels il affecte alatoirement une des trois couleurs. Ensuite il gnre alatoirement des paires de
sommets (s1, s2) et il connecte s1 et s2 par une arte si s1 et s2 ne sont pas coloris avec la mme
couleur. Il continue jusqu ce que par exemple tous les sommets quil a gnrs initialement soient
connects au moins deux sommets et que le graphe soit connexe (il existe toujours un chemin entre
deux sommets s1 et s2). Par construction le graphe quil obtient est 3-coloriable et il en connat un
coloriage.
Le Prouveur publie son graphe G qui devient alors public et garde son coloriage secret. Le coloriage
secret est not C, la couleur dun sommet s est C(s) et C(s) prend seulement les trois valeurs
possibles : jaune, rouge ou bleu.
On suppose en plus que lon a une fonction de hachage h sens unique et connue de tout le monde.
Le Prouveur veut sidentifier auprs du Vrifieur. UN ROUND du protocole se droule de la manire
suivante :
1. Pour chaque sommet s de G, Prouveur tire un nombre alatoire Rs (diffrent chaque round
et pour chaque sommet) et envoie Vrifieur tous les messages h(s, C(s), Rs ) pour tous les
sommets.
2. Vrifieur tire au hasard deux sommets de G, s1 et s2, relis par une arte.
3. Prouveur envoie Vrifieur les deux messages < s1, C(s1), Rs1 > et < s2, C(s2), Rs2 >.
4. Vrifieur calcule les hachs des deux messages et vrifie que ce sont bien les valeurs que Prouveur
lui avait donnes la premire tape. Si en plus, C(s1) 6= C(s2) alors le round sest bien pass.

Avec un tel protocole, il est clair que Prouveur arrive toujours sauthentifier puisque il connat la
fonction C.
Question a : A quoi servent les nombres alatoires Rs ? Que se passe-t-il si on les retire
systmatiquement du protocole ? Que se passe-t-il si le mme nombre alatoire R est
utilis pour tous les sommets s ?
On sintresse maintenant au cas de Tricheur. Il ne connat pas le secret de Prouveur ( savoir le 3coloriage de G) mais va quand mme essayer de se faire passer pour Prouveur. Il rcupre donc le
graphe G de Prouveur (qui est public) et essaye de le colorier en respectant la rgle du 3-coloriage.
Comme il ne sait pas comment le graphe a t construit et que le problme est NP-complet, il choue.
On suppose donc quil arrive colorier correctement G en partie. Sur la partie de G quil narrive
pas colorier sans conflits, Tricheur commet des erreurs (i.e. des artes ayant la mme couleur aux
deux extrmits). Pour simplifier, on considre quil ny a quune seule erreur sur le coloriage ralis
par Tricheur. Son coloriage est donc imparfait, on le note C 0 dans ce qui suit.
Tricheur dcide dadopter lattitude suivante. Il envoie Vrifieur le hach de son coloriage C 0 la
premire tape du protocole. Si Vrifieur le questionne sur une arte (s1,s2) quil a russi colorier
convenablement, il envoie les messages < s1, C 0 (s1), Rs1 > et < s2, C 0 (s2), Rs2 > . Si Vrifieur

Page 6

84

le questionne sur larte quil na pas russi colorier correctement, il va rpondre par exemple
< s1, jaune, Rs1 > et < s2, rouge, Rs2 >, du moment que les deux couleurs soient diffrentes.
Question b : Est-ce que Tricheur peut donner le change de cette manire ?
On suppose que h est une fonction de hachage mal construite. En particulier, elle est vulnrable aux
collisions. Soit s un sommet, c une couleur et r un nombre quelconque, alors on peut trouver assez
facilement quelle que soit la couleur c0 , un nombre alatoire r0 tel que h(s, c, r) = h(s, c0 , r0 ).
Question c : Montrer en ce cas que Tricheur arrive toujours sidentifier mme sil ne
connat pas le 3-coloriage de G.
On suppose que h est une fonction de hachage sre. Soit n le nombre dartes du graphe G.
Question d : Quelle est la probabilit que Tricheur sauthentifie correctement pendant
un round ? Montrer que si n est grand, la probabilit que Tricheur sauthentifie correctement pendant n rounds est proche de 1/e.
On voit donc quen multipliant le nombre de rounds Tricheur finira toujours par se trahir. Nous allons
maintenant nous intresser au cas dEspion : il observe toutes les procdures dauthentifications de
Prouveur et espre en tirer les informations quil faut pour se faire passer pour Prouveur.
Question e : Montrer quEspion finit par dcouvrir entirement le coloriage de Prouveur
si on utilise le protocole prcdent.
On modifie le protocole de la manire suivante. A la premire tape de chaque round, avant toute autre
opration, Prouveur modifie alatoirement ses conventions de coloriage : il permute alatoirement le
nom des trois couleurs dans son coloriage initial.
Prouveur dvoile des informations claires sur son coloriage uniquement dans la 3me tape du protocole.
Question f : Avec cette modification, quelle information Espion peut-il dduire du message ?
Question g : Quel est le principal dsavantage de ce protocole par rapport un protocole
comme le Fiat-Shamir ?
Question11
Problme de sac dos
Pk
Soit a1 , a2 , . . . , ak des entiers positifs. Soit M un nombre entier avec M < i=1 ai . On veut rsoudre
Pk
lquation M = i=1 ei ai avec ei {0, 1}. Ce problme sappelle le problme du sac dos et sa
rsolution dans le cas gnral est un problme NP-complet.
Pi1
1. On suppose que ai > k=1 ai , i 2. On parle alors de sac--dos super croissant. Montrer que
le problme est alors simple rsoudre.
Pk
2. Soit a1 , a2 , . . . , ak un sac dos super-croissant. Soit N > i=1 ai avec N premier avec tous les
Pk
ai , i = 1, k. Soit A un entier premier avec N . On pose bi = ai A mod [N ]. Soit C = i=1 ei bi
avec ei {0, 1}. Montrer que si on connat A et les ai alors on peut retrouver les valeurs des ei
au vu de C.
3. En dduire un protocole cl publique permettant dencoder un message de k bits.
4. Calculer les cls pour un protocole permettant dencoder 1 octet. Quelle est la taille de la
cl publique et la taille des messages ? Comparer un RSA permettant dencoder un octet.
Conclusion ?
Rem : ce systme de chiffrement est le premier algorithme de chiffrement cl publique invent (un
an avant le RSA). Il a t abandonn car, avec des outils mathmatiques adapts, on peut le dcoder
mme sans connatre A.
Question12
Protocole de Fiat Shamir
On admet dans ce qui suit le rsultat suivant : soit p et q deux entiers premiers et soit N = p q
alors il est impossible, au vu de Y = X 2 mod [N ], de deviner la valeur de X.
Ce problme dit des rsidus quadratiques est la base dun protocole dauthentification sans transfert
de connaissance, le protocole de Fiat-Shamir.
Protocole de Fiat Shamir :
Alice veut sidentifier auprs de Bob. Elle choisit N = p q produit de deux nombres premiers et elle
choisit X (0 < X < N ). Elle calcule Y = X 2 mod [N ]. Elle publie le couple (Y, N ) que Bob garde

Page 7

85

en mmoire, elle conserve X secret, elle dtruit p et q. A chaque fois quelle veut sidentifier auprs
de Bob il faut quelle prouve Bob quelle dtient X sans pour autant rvler la valeur de X.
1. Soit le protocole suivant : Alice gnre un nombre alatoire a (0 < a < N ). Elle calcule y = a2 Y
mod [N ] quelle envoie Bob. Bob accuse rception de y et Alice lui envoit alors x = a X. Bob
vrifie alors que y = x2 mod [N ].
Montrer que Eve, sans connatre le secret X peut sauthentifier la place de Alice.
On modifie alors le protocole de la faon suivante :
Alice gnre un nombre alatoire a (0 < a < N ) et transmet Bob la quantit t = a2 mod [N ].
Bob tire une variable alatoire  qui vaut 0 ou 1 de manire quiprobable et communique 
Alice. Si  = 0 Alice transmet a Bob qui vrifie t = a2 mod [N ]. Si  = 1 alors Alice transmet
a X mod [N ] Bob qui vrifie (a X)2 mod [N ] = t Y mod [N ].
2. A quoi sert le nombre a ? A quoi sert la variable  ?
3. Eve veut sidentifier la place de Alice. Elle espionne au pralable les authentifications de Alice.
On suppose de plus que le gnrateur alatoire  utilis par Bob est connu par Eve. Montrer
alors que Eve peut toujours sidentifier la place de Alice.
4. Eve ne connat pas parfaitement le gnrateur alatoire utilis par Bob mais essaie de parier
lavance sur les valeurs que va lui proposer Bob. Elle est capable de dterminer avec probabilit
p la valeur de . Quelle est la probabilit pour Eve de sauthentifier correctement sur un round ?
sur k rounds ?
5. On suppose maintenant que le gnrateur de Bob est uniformment rparti et secret. Par contre
le gnrateur dAlice est mal conu et une valeur de a sort avec une probabilit p nettement
suprieure 1/(N 1). Eve espionne toutes les authentifications. Combien dauthentifications
doit-elle espionner en moyenne pour tre capable de sauthentifier la place de Alice ?
6. Le protocole est modifi de la faon suivante : Alice connat secrtement un ensemble de nombres
X1 , X2 , . . . , Xk et publie les nombres Y1 , Y2 , . . . , Yk correspondants.QBob au lieu denvoyer un bit
 unique, envoie K bits 1 , 2 , . . . , k . Alice doit alors lui fournir a i/i =1 Xi . Quel est lintrt
de cette modification ?

Question13
Gnrateur de Geffe
On considre 3 suites pseudo-alatoires (ak )kN , (bk )kN et (ck )kN couples en parallle au travers
dun gnrateur de Geffe : sk = ak bk bk ck .
Quelle est linformation mutuelle entre ak et sk ?
On suppose que la suite ak a t produite par un LFSR dont la structure est connue (le polynome
de rtroaction est connu). Le secret est la valeur dinitialisation du LFSR (cl). Combien de valeurs
successives de la squence sk suffit-il de connatre pour, en thorie, tre parfaitement en mesure
de retrouver la valeur de la cl ?
Question14
Attaque par corrlation du gnrateur de Geffe
On considre trois registres dcalage rtroaction linaire (LFSR) nots R1 , R2 et R3 de longueurs
respectives l1 , l2 et l3 (nombres dlments de mmoire).
On note x1 (t), x2 (t) et x3 (t) les sorties respectives des LFSR R1 , R2 et R3 . Ces sorties sont combines
par un gnrateur de Geffe pour produire la suite chiffrante z(t) = x1 (t)x2 (t) x2 (t)x3 (t). La notation
reprsente le "ou exclusif" (XOR) et la notation x2 reprsente le complment 1 de x2 .

1. En supposant que les valeurs xi (t) sont binaires quiprobables calculer les probabilits P(z(t) =
x1 (t), P(z(t) = x2 (t) et P(z(t) = x3 (t).
2. En dduire une attaque contre ce gnrateur. Commenter la complexit calculatoire de la mise
en oeuvre de cette attaque.

Question15
Contrefaon existentielle sur le schma de signature dEl Gamal
Une attaque de type contrefaon existentielle contre un schma de signature est un mcanisme par
lequel lattaquant est capable dexhiber un couple message/signature valide. Dans ce type dattaque

Page 8

86

le message nest pas quelconque mais construit par lattaquant de faon ce que ce dernier soit
capable de produire la signature correspondante. Au contraire dans une attaque de type contrefaon
universelle lattaquant est capable de signer tous les messages.
Nous allons montrer que le schma de signature dEl Gamal est sensible une attaque de type
contrefaon existentielle. On rappelle tout dabord le schma de signature dEl Gamal.
Gnration des cls : le signataire choisit un entier premier p et un lment gnrateur g de Zp . Il
tire uniformment alatoirement x Zp1 et calcule y = g x mod [p]. La cl publique est (p, g, y)
et la cl secrte est x.
Signature : pour signer un message m Zp1 le signataire tire uniformment alatoirement k
Zp1 et calcule r = g k mod [p]. Il calcule s = (m xr)/k mod [p 1] et la signature est le couple
(r, s).
Vrification : un couple (r, s) est une signature valide de m Zp1 si et seulement si (r, s)
Zp Zp1 et g m = y r rs mod [p]
Supposons que lattaquant pose r = g a y b mod [p] puis calcule ensuite s = r/b mod [p 1]. De
quel message le couple (r, s) est-il une signature valide ?

Page 9

87

Attack Lab
Network Security Course - November 2014

Attack Lab
Attacks on TCP/IP Protocols
Part I - Preparation (Homework)
1

Lab Overview

The learning objective of this lab is for students to gain the first-hand experience on the vulnerabilities
of TCP/IP protocols, as well as on attacks against these vulnerabilities. The vulnerabilities in the TCP/IP
protocols represent a special genre of vulnerabilities in protocol designs and implementations; they provide
an invaluable lesson as to why security should be designed in from the beginning, rather than being added as
an afterthought. Moreover, studying these vulnerabilities help students understand the challenges of network
security and why many network security measures are needed. Vulnerabilities of the TCP/IP protocols occur
at several layers.
1. This part of the Lab should be prepared before the Lab.
2. Work in a group of THREE people.
3. This Lab will be evaluated based on the reports you are going to submit. Please, see the last section
regarding the submission and the format of the report.

Questions
How does ARP work?
In a few sentences describe what is ARP cache poisoning.
What is the purpose of the following ICMP messages:
ICMP Redirect
ICMP Blind Connection-Reset
ICMP Source-Quench

How does TCP SYN flood work?


How does SYN Cookie mechanism help address some of the aspects of TCP SYN flooding?

Submission

You need to submit a report in which you answer the above questions.
The rules for the submission are:
1. Provide your report in PDF format.
2. Name the file of the archive youre submitting in the following way : NAME1 NAME2 NAME3TP TCPIP
3. Limit the size of your report to no more than 2 pages.
Please, send your report by email to sandrine.vaton@telecom-bretagne.eu

89

Network Security Course - November 2014

Part II - Practical
4
4.1

Lab Environment and Work Organization


Work Organization

You will be working by yourself or in binome, with a teammate of your choice. Try to structure your work
and take notes based on the following aspects:
Design: The design of your attacks, including the attacking strategies, the packets that you use in
your attacks, the tools that you used, etc.
Observation: Is your attack successful? How do you know whether it has succeeded or not? What
do you expect to see? What have you observed? Is the observation a surprise to you?
Explanation: Some of the attacks might fail. If so, you need to find out what makes them fail. You
can find the explanations from your own experiments (preferred) or from the Internet. If you get the
explanation from the Internet, you still need to find ways to verify those explanations through your
own experiments.
Note that you may be unable to demonstrate some of the attacks, e.g. due to protection mechanisms
integrated in the OSes under study. If this is the case a given exercise, concentrate on describing what you
want to achieve, how you planned achieving it, the result, and a hypothesis why it didnt work as expected.

4.2

Environment Setup

Network Setup. To conduct this lab, you will have 3 virtual machines at your disposal. One computer is
used for attacking (Machine1), the second computer is used as the victim (Machine3), and the third computer is used as the observer (Machine2). For this lab, we put all these three machines on the same LAN in
the following configuration:

Machine 1
Machine 2
Machine 3
192.168.0.122
192.168.0.123
192.168.0.124
|
|
|
|_______________________|_______________________|
|
LAN (Virtual Network)
|
|_______________________________________________|
The logins for these machines are the following:
user/userpass
root/rootpass
The virtual machines are named RES411-TP3-Machine1, RES411-TP3-Machine2 and RES411-TP3Machine3.

90

Network Security Course - November 2014

Tools For this Lab you will be using a tool called Netwox. You can look up the tutorials/documentation
supplied on Moodle of the module.
Netwox consists of a suite of tools, each having a specific number. You can run the command like the
following (the parameters depend on which tool you are using). For some of the tool, you have to run it with
the root privilege:
# netwox number [parameters ... ]
If you are not sure how to set the parameters, you can look at the manual by issuing "netwox number
--help".
Wireshark Tool. You also need a good network-traffic sniffer tool for this lab. Although Netwox
comes with a sniffer, you will find that another tool called Wireshark is a much better sniffer tool.

Lab Tasks

In this lab you will to conduct attacks on the TCP/IP protocols by using Netwox. All the attacks are
performed on Linux operating systems.
To simplify the guess of TCP sequence numbers and source port numbers, we assume that attacks are
on the same physical network as the victims. Therefore, you can use sniffer tools to get that information.
The following is the list of attacks that need to be implemented.
A short reminder - you are attacking Machine 3 and observing the attacks from Machine 2. Machine 1
is the attacker.

5.1

Task (1) : ARP cache poisoning

The ARP cache is an important part of the ARP protocol. Once a mapping between a MAC address and an
IP address is resolved as the result of executing the ARP protocol, the mapping will be cached. Therefore,
there is no need to repeat the ARP protocol if the mapping is already in the cache. However, because the
ARP protocol is stateless, the cache can be easily poisoned by maliciously crafted ARP messages. Such an
attack is called the ARP cache poisoning attack.
In such an attack, attackers use spoofed ARP messages to trick the victim to accept an invalid MAC-toIP mapping, and store the mapping in its cache. There can be various types of consequences depending on
the motives of the attackers. For example, attackers can launch a DoS attack against a victim by associating
a nonexistent MAC address to the IP address of the victims default gateway; attackers can also redirect the
traffic to and from the victim to another machine, etc.
In this task, you need to demonstrate how the ARP cache poisoning attack work. Several commands
can be useful in this task. In Linux we can use command arp to check the current mapping between IP
address and MAC.
Hints:
1. Use Wireshark to observe the exchanged packets (on Machine 2)
2. Try checking the ARP table of the victim before sending any traffic to it (it should be empty)
3. Send some traffic (e.g. ping) from the attacker to the victim and check the ARP table again
4. Understand the way ARP spoofing works (request, response)

91

Network Security Course - November 2014

5.2

Task (2) : ICMP Redirect Attack

The ICMP redirect message is used by routers to provide the up-to-date routing information to hosts, which
initially have minimal routing information. When a host receives an ICMP redirect message, it will modify
its routing table according to the message. Because of the lack of validation, if attackers want the victim to
set its routing information in a particular way, they can send spoofed ICMP redirect messages to the victim,
and trick the victim to modify its routing table.
In this task, you should demonstrate how the ICMP redirect attack works, and describe the observed
consequence. To check the routing information in Linux, you can use the command route.
Hints:
1. Use Wireshark to observe the exchanged packets (on Machine 2)
2. Verify the routing table of the victim, both the kernels FIB routing table and the routing cache
3. Try to send an ICMP Redirect packet from the attacker to the victim indicating that the new default
router is the attackers IP address
4. In case the attack doesnt work, try looking for a way to disable secure redirect protection in the victim

5.3

Task (3) : SYN Flooding Attack

SYN flood is a form of DoS attack in which attackers send many SYN requests to a victims TCP port, but
the attackers have no intention to finish the 3-way handshake procedure. Attackers either use spoofed IP
address or do not continue the procedure. Through this attack, attackers can flood the victims queue that is
used for half-opened connections, i.e. the connections that has finished SYN, SYN-ACK, but has not yet got
a final ACK back. When this queue is full, the victim cannot take any more connection. Figure 1 illustrates
the attack.
attacker
SYN
server
user

SYNACK

SYN

server

server
SYNACK
user

SYN

user
ACK

user

server oos

server
SYN flood: attacker sends many SYN to server without
ACK. The server is not able to process request from user.

Normal TCP 3 way handshake between user and server

Figure 1: SYN Flood

92

Network Security Course - November 2014

The size of the queue has a system-wide setting. In Linux, we can check the system queue size setting
using the following command:
# sysctl -q net.ipv4.tcp_max_syn_backlog
We can use command "netstat -na" to check the usage of the queue, i.e., the number of halfopened connection associated with a listening port. The state for such connections is SYN-RECV. If the
3-way handshake is finished, the state of the connections will be ESTABLISHED.
In this task, you need to demonstrate the SYN flooding attack. You can use the Netwox tool to conduct
the attack, and then use a sniffer tool to capture the attacking packets. While the attack is ongoing, run the
"netstat -na" command on the victim machine, and compare the result with that before the attack.
Please also describe how you know whether the attack is successful or not.
SYN Cookie Countermeasure: If your attack seems unsuccessful, one thing that you can investigate is
whether the SYN cookie mechanism is turned on. SYN cookie is a defense mechanism to counter the SYN
flooding attack. The mechanism will kick in if the machine detects that it is under the SYN flooding attack.
You can use the sysctl command to turn on/off the SYN cookie mechanism:
# sysctl -a | grep cookie
(Display the SYN cookie flag)
# sysctl -w net.ipv4.tcp_syncookies=0 (turn off SYN cookie)
# sysctl -w net.ipv4.tcp_syncookies=1 (turn on SYN cookie)
Please run your attacks with the SYN cookie mechanism on and off, and compare the results. Try to
describe why the SYN cookie can effectively protect the machine against the SYN flooding attack. You can
find how the SYN cookie mechanism works from the Internet.

5.4

Task (4) : TCP RST Attacks on telnet and ssh Connections

The TCP RST Attack can terminate an established TCP connection between two victims. For example, if
there is an established telnet connection (TCP) between two users A and B, attackers can spoof a RST
packet from A to B, breaking this existing connection. To succeed in this attack, attackers need to correctly
construct the TCP RST packet.
In this task, you need to launch an TCP RST attack to break an existing telnet connection between A
and B. After that, try the same attack on an ssh connection. Please describe your observations. To simply
the lab, we assume that the attackers and the victims are on the same LAN, i.e., attackers can observe the
TCP traffic between A and B.

5.5

Task (5) : ICMP Blind Connection-Reset and Source-Quench Attacks

ICMP messages can also be used achieve the connection-reseting attack. To do this, attackers send an
ICMP error message that indicates a hard error to either of the two endpoints of a TCP connection. The
connection can be immediately torn down as RFC 1122 states that a host should abort the corresponding
connection when receiving such an ICMP error message. RFC 1122 defines hard errors as ICMP error
messages of type 3 (Destination Unreachable) with code 2 (protocol unreachable), 3 (port unreachable), or
4 (fragmentation needed and DF bit set).
The ICMP source quench message is used by the congested routers to tell the TCP senders to slow down.
Attackers can forge such messages to conduct the denial of services attacks on TCP senders.
In this task, you need to launch the ICMP blind connect-reset attacks and the ICMP source quench
attacks. You need to be noted that some systems may reasonably ignore this type of ICMP errors in certain
TCP state.

93

Network Security Course - November 2014

5.6

Task (6) : TCP Session Hijacking

The objective of the TCP Session Hijacking attack is to hijack an existing TCP connection (session) between
two victims by injecting malicious contents into this session. If this connection is a telnet session,
attackers can inject malicious commands into this session, causing the victims to execute the malicious
commands. We will use telnet in this task. We also assume that the attackers and the victims are on the
same LAN.
client

SYN, Seqence Number X

server

client

server
Acknowledge Number X+1

SYNACK, Sequence Number Y


Ack Number X+1

ACK, Acknowledge Number Y+1

Data: "A", Sequence Number X+1

Data: "Z", Sequence Number X+2


attacker

Acknowledge Number X+2

Normal TCP 3 way handshake and sending data


between client and server

Attacker Hijack the TCP session and send data


"Z" to server on behalf of client

Figure 2: TCP Session Hijacking

Note: If you use Wireshark to observe the network traffic, you should be aware that when Wireshark
displays the TCP sequence number, by default, it displays the relative sequence number, which equals to the
actual sequence number minus the initial sequence number. If you want to see the actual sequence number
in a packet, you need to right click the TCP section of the Wireshark output, and select "Protocol
Preference". In the popup window, uncheck the "Relative Sequence Number and Window
Scaling" option.

5.7

Note

It should be noted that because some vulnerabilities have already been fixed in Linux, some of the above
attacks will fail in Linux, but they might still be successful against other operating systems.

This Lab is based on the Labs developed by Wenliang Du, Syracuse University.
0

94

The development of this document is funded by three grants from the US National Science Foundation:
Awards No. 0231122 and 0618680 from TUES/CCLI and Award No. 1017771 from Trustworthy Computing.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free
Documentation License, Version 1.2 or any later version published by the Free Software Foundation. A copy
of the license can be found at http://www.gnu.org/licenses/fdl.html.

Network Audit Lab


Network Security Course November 2014

Network Audit Lab


Perform an Audit of a Company Network
Part I - Preparation (Homework)
1

Overview

The learning objective of this lab is for students to get familiar with some of the fundamental mechanisms
for network audit, including OS and service identification and network port scanning. At the end of this Lab
you will have a working knowledge of these mechanisms.
1. This part of the Lab should be prepared before the Lab.
2. Work in a group of THREE people.
3. This Lab will be evaluated based on the reports you are going to submit.
Warning - it is ILLEGAL to perform network scans and investigations on a network you do not own or on
which you dont have the written permission to do so. You ISP (FAI) and/or the network/computer you are
scanning can detect easily the fact that you are performing a scan, which can lead to serious legal
consequences!

Protocols, techniques and tools for network auditing

The purpose of this home preparation is to describe the functioning of the following protocols, tools and
techniques used for basic network auditing:
1. DNS, DNS queries
2. Host and port scanning (ping, nmap)
3. Network mapping (traceroute)

2.1

DNS queries with dig

The Domain Name System (DNS) is a hierarchical naming system built on a distributed database for computers, services, or any resource connected to the Internet or a private network1 . Often it is reasonable to
have two DNS servers - one for the internal network and one for servicing the external requests. One of the
most versatile utilities for sending DNS queries is dig which we will be using to query the DNS servers of
the internal network.
Every OS has a DNS resolver which finds the correspondence name IP address. Under normal
circumstances all programs use the integrated OS resolver. However, it is possible to specify ANY opened
DNS server on the Internet to perform the name resolution. When badly configured, an opened end-user
1

http://en.wikipedia.org/wiki/Domain_Name_System

97

Network Security Course November 2014

DNS server can be instructed to perform a resolution for a third party domain, which is one of the ways to
perform DNS cache poisoning attack (by responding before the third party DNS server).

Questions :
1. What is the potential usage of a utility such as dig?
2. Give an example of an alternative utility which does a similar work, but is more popular than dig.
3. Give a brief description of the following types of DNS records:
(a) A
(b) AAAA
(c) PTR
(d) MX
(e) NS
4. Find examples of the following DNS queries with dig for a given domain (e.g. example.com):
(a) Get the MX record for a domain
(b) Get the A record for a specific host in a given domain (e.g. ftp.example.com)
(c) Get the NS record for a specific host in a given domain (e.g. ftp.example.com)
(d) Get the A, AAAA and/or NS records for any record without a label
(e) Get all records with no label for the domain (e.g. SOA, MX, ... in addition to A, AAAA and
NS)
(f) Get all domain records if allowed
(g) Specify the DNS server to be used for the query
(h) Perform a reverse-lookup
Example:
Get the A, AAAA and/or NS records for any record without a label:
dig example.com

2.2

Host and port scanning

Nmap is a free and open source utility for network exploration or security auditing. Many systems and
network administrators also find it useful for tasks such as network inventory, managing service upgrade
schedules, and monitoring host or service uptime. Nmap uses raw IP packets in novel ways to determine
what hosts are available on the network, what services (application name and version) those hosts are offering, what operating systems (and OS versions) they are running, what type of packet filters/firewalls are in
use, and dozens of other characteristics.2
You can find a very complete description of the available options and the techniques used by nmap in its
Reference Guide http://nmap.org/book/man.html.
2

98

http://nmap.org/

Network Security Course November 2014

Additionally, you can use the nmap cheat sheet containing a relatively long list of all possible options at
the following address: http://nmapcookbook.blogspot.com/2010/02/nmap-cheat-sheet.
html.
Hint: Note that during a scan operation you can press ENTER to see the current progress and the remaining scan time.

Questions :
1. What is the purpose of ping? How does it work?
2. What is the difference between host scanning and port scanning?
3. Why is it good to start with a simple -sn scan?
4. What are the default host discovery scan options?
5. What are the default port scan options?
6. What is the difference between TCP SYN Ping, TCP ACK Ping, UDP Ping, ICMP Ping, ARP Ping,
TCP SYN scan, UDP scan and TCP ACK scan?
7. How does nmap classify a port as being opened, closed or filtered?
8. What does the -sV option do and how does it achieve it?
9. What does the -O option do and how does it achieve it?
10. Is it possible to disable DNS name resolution during nmap scans or to select a different DNS server?
How?
11. Provide examples of the following nmap scans of a 192.168.1.0/24 network:
(a) Scan the entire subnet with no port scanning (256 hosts between 192.168.1.0 and 192.168.1.255)
(b) Perform TCP SYN Ping on the ports 22-25,80,113,1050,35000 of the following IP addresses:
192.168.3.1, 192.168.4.1, 192.168.5.1, and 192.168.7.1
(c) Perform a scan of all IPs of the form 192.168.5.10, 192.168.5.11, 192.168.5.12, . . . , 192.168.5.19,
192.168.5.20; 192.168.6.10, . . . , 192.168.6.20; 192.168.7.10, . . . , 192.168.7.20; . . . . . . . . . ; 192.168.15.10,
. . . , 192.168.15.20;
(d) TCP SYN scan on port 80 of scanme.nmap.org and name resolution via 192.168.1.1
(e) (Bonus question - optional) Write a short description of the Idle scan (-sI) technique and the
usage of scan decoys (-D)
Example:
Scan the entire subnet with no port scanning (256 hosts between 192.168.1.0 and 192.168.1.255)
nmap -sP 192.168.1.0/24

99

Network Security Course November 2014

2.3

Network topology mapping

Traceroute is a utility used to determine the path a packet takes between two endpoints. Traceroute does this
by sending a series of packets with particular TTL (Time To Live) values and examining the ICMP replies
seen.
Sometimes, when a packet filter firewall is configured incorrectly, an attacker can traceroute the firewall
to gain knowledge of the network topology inside the firewall. This information may allow an attacker to
determine trusted routers and other network information.3
Questions :
1. Briefly describe the technique used by traceroute to map the routers traversed by packets going to a
given destination.
2. Which option disables DNS name resolution?
3. What is the command for IPv6 route tracing ?
4. Give an example how an intruder can determine the network topology of a badly configured corporate
network. As an example, imagine that there are 3 routers - one facing the Internet which routes the
traffic to the two others, assuming that you know the IP addresses of some of the hosts behind the 3
routers.
5. (Bonus question - optional) When tracerouting to a distant IP address on the Internet is it possible that
we get different routes at different times? Explain why.

Submission

You need to submit a report in which you answer the above questions.
The rules for the submission are:
1. Provide your report in PDF format.
2. Name the file of the archive youre submitting in the following way : NAME1 NAME2 NAME3TP Audit
3. Limit the size of your report to no more than 2 pages.
Please, send your report to sandrine.vaton@telecom-bretagne.eu
3

100

http://www.iss.net/security_center/reference/vuln/traceroute.htm

Network Security Course November 2014

Part II - Practical
4
4.1

Lab Environment and Organization


Work organization

You will be working by yourself or in binome, with a teammate of your choice.


For this Lab you will be using 2 virtual machines. You will be using the machine called Scanner which
has all the necessary tools installed. You will be investigating the network created by the machine called
ComputerNetworkAudit.

4.2

Running the Virtual Machines

Run the virtual machines from the list of VMs (the link should be on your Desktop):
First start the ComputerNetworkAudit virtual machine
Then, start the Scanner virtual machine.
The two machines are connected to each other with no connection to the outside world. In this Lab we
have used IP addresses and domain names inspired by real addressing schemes, so be careful to perform
your experiments ONLY in the virtual machines (e.g. pay attention not to use a wrong terminal by mistake
and thus scan a real network).
ComputerNetworkAudit

Scanner

Internet
213.228.11.190

213.228.11.195
ISP
(Routing and DNS
services)

www.stupid.com

You cannot login to the ComputerNetworkAudit machine. The logins for the Scanner are:
Normal user: user/userpass
Root: root/rootpass
Login to the Scanner machine and make sure that the network is functioning correctly by pinging the IP
of your ISP as it may take some time for the Network machine to start. The machine will have successfully
started once it responds to pings. Note that because we are emulating real routers with real routing protocol
implementations, it may take some time (up to 2 minutes) for www.stupid.com to respond to ping requests
after the Network machine has started (why?).

101

Network Security Course November 2014

Lab Tasks

You have been invited to audit the network of a medium-sized company. The only piece of information that
is available to you is the name of their website - www.stupid.com. Your job will be to try to obtain as much
information as possible regarding their corporate network and if there are any problems to propose ways to
secure the network.
The major task of this Lab would be to draw a diagram of all routers and hosts in the
network, the paths between them, their names, presumed functions and opened ports.
Once you have done this, point the possible threats and propose changes to the network of the
company.
Follow the principle of going from less intrusive to more intrusive methods. For example, try first
collecting all the information you can get from any DNS server you detect (e.g. reverse lookup of IP
addresses (dig -x), mail servers (mx), other nameservers (ns), or even if you are lucky - domain transfer
information (axfr)). Then, if you need to discover more hosts use host scanning, but limit the number of
scanned hosts (e.g. max a /24 segment, or preferably smaller!). Finally, on some selected hosts perform port
scan to determine the services, with OS identification for a subset of them.
Whenever you find a new DNS server, or new IP subnet go through these steps from the beginning.
Here are some questions that will guide you in your efforts to collect this information:
What route is taken by the packets to arrive at the companys network. Do they follow the same path
for all computers of the network? How about the IPv6 routes?
Can you infer the approximate geographic location of the company network from the routers?
What network services exist on each of the servers/computers?
What is the topology of the network. How are the routers interconnected? And the machines? Can
you obtain the netmask of each subnet?
Observe the naming convention of the discovered computers. Can you guess what is the role of each
of these equipments ?
You can use the following tools in order to gain the information you need:
ping and ping6 - confirm the existence of a host (unless a firewall is filtering ICMP requests);
traceroute and traceroute6 - map the route of the packets to a given destination, and thus help discovering the topology;
dig - query a DNS server of your choice;
nmap - scan for hosts and services, OS identification.
Note that by default traceroute(6) and nmap perform DNS lookups for all matching IPs, so if you are
scanning a private network segment you may want to provide a private DNS server or to disable the DNS
lookup altogether.

102

Introduction to IDS

Introduction aux Systmes de Dtection dIntrusion


(IDS)
Sandrine Vaton
Tlcom Bretagne

Dpartement INFO

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

1 / 78

Crdits

Certains transparents sont issus de :


KeyNote Speech sur la dtection dintrusion de Dr. Christian Callegari
(PhD, Universit de Pise, Dpartement dIngnierie de lInformation)
la confrence IWCMC 2012 (Limassol, Chypre, aot 2012).

105
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

2 / 78

Crdits

Certains transparents sont issus de :


KeyNote Speech sur la dtection dintrusion de Dr. Christian Callegari
(PhD, Universit de Pise, Dpartement dIngnierie de lInformation)
la confrence IWCMC 2012 (Limassol, Chypre, aot 2012).
Cours sur la dtection dintrusions, Prof. Ludovic M, Suplec, Rennes

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

2 / 78

Crdits

Certains transparents sont issus de :


KeyNote Speech sur la dtection dintrusion de Dr. Christian Callegari
(PhD, Universit de Pise, Dpartement dIngnierie de lInformation)
la confrence IWCMC 2012 (Limassol, Chypre, aot 2012).
Cours sur la dtection dintrusions, Prof. Ludovic M, Suplec, Rennes
Cours sur la dtection dintrusions donn Tlcom Bretagne en
2010, Pierre Crgut (HDR), Orange Labs

106
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

2 / 78

Sommaire

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

3 / 78

Sommaire
1

Introduction
Besoins en scurit
Les diffrents types dintrusion

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux

107
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

4 / 78

Sommaire
1

Introduction
Besoins en scurit
Les diffrents types dintrusion

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

5 / 78

Scurit des Rseaux

Dfinition
In the field of networking, the specialist area of Network Security consists
of the provisions made in an underlying computer network infrastructure,
policies adopted by the network administrator to protect the network
and the network-accessible resources from unauthorized access, and
consistent and continuous monitoring and measurement of its
effectiveness (or lack) combined together.
Network Security and Networking Protocols, A.K.Sharma and C.S.Lamba

108
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

6 / 78

Enjeux de la scurit des systmes dinformation


Confidentialit : Seules les personnes autorises ont accs aux
informations qui leur sont destines. Tout accs indsirable doit tre
empch.

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

7 / 78

Enjeux de la scurit des systmes dinformation


Confidentialit : Seules les personnes autorises ont accs aux
informations qui leur sont destines. Tout accs indsirable doit tre
empch.
Disponibilit : Le systme doit fonctionner sans faille durant les
plages dutilisation prvues, garantir laccs aux services et ressources
installes avec le temps de rponse attendu.

109
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

7 / 78

Enjeux de la scurit des systmes dinformation


Confidentialit : Seules les personnes autorises ont accs aux
informations qui leur sont destines. Tout accs indsirable doit tre
empch.
Disponibilit : Le systme doit fonctionner sans faille durant les
plages dutilisation prvues, garantir laccs aux services et ressources
installes avec le temps de rponse attendu.
Intgrit : Les donnes doivent tre celles que lon sattend ce
quelles soient, et ne doivent pas tre altres de faon fortuite ou
volontaire.

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

7 / 78

Enjeux de la scurit des systmes dinformation


Confidentialit : Seules les personnes autorises ont accs aux
informations qui leur sont destines. Tout accs indsirable doit tre
empch.
Disponibilit : Le systme doit fonctionner sans faille durant les
plages dutilisation prvues, garantir laccs aux services et ressources
installes avec le temps de rponse attendu.
Intgrit : Les donnes doivent tre celles que lon sattend ce
quelles soient, et ne doivent pas tre altres de faon fortuite ou
volontaire.
Authentification : Lidentification des utilisateurs est fondamentale
pour grer les accs aux espaces de travail pertinents et maintenir la
confiance dans les relations dchange.

110
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

7 / 78

Enjeux de la scurit des systmes dinformation


Confidentialit : Seules les personnes autorises ont accs aux
informations qui leur sont destines. Tout accs indsirable doit tre
empch.
Disponibilit : Le systme doit fonctionner sans faille durant les
plages dutilisation prvues, garantir laccs aux services et ressources
installes avec le temps de rponse attendu.
Intgrit : Les donnes doivent tre celles que lon sattend ce
quelles soient, et ne doivent pas tre altres de faon fortuite ou
volontaire.
Authentification : Lidentification des utilisateurs est fondamentale
pour grer les accs aux espaces de travail pertinents et maintenir la
confiance dans les relations dchange.
Non-repudiation et imputation : Aucun utilisateur ne doit pouvoir
contester les oprations quil a ralises dans le cadre de ses actions
autorises, et aucun tiers ne doit pouvoir sattribuer les actions dun
autre utilisateur.
Source : Wikipdia
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

7 / 78

Confidentialit

Definition
Dfinition de la confidentialit par lInternational Organization for
Standardization (ISO) dans le standard ISO-17799 comme le fait dassurer
que linformation est accessible uniquement ceux qui sont autoriss y
avoir accs"

Attaques associes
Attaques passives (e.g., coutes indiscrtes)
Parades : cryptographie, IPSec, SSL, TLS

111
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

8 / 78

Disponibilit

Dfinition
Le degr auquel un systme, un quipement est dans un tat oprationnel
pour une mission quand on veut y faire appel un instant quelconque
(alatoire). Cest une mesure de performance quon obtient en divisant la
dure durant laquelle ledit quipement ou systme est oprationnel par la
dure totale durant laquelle on aurait souhait quil le soit.

Attaques associes
Dni de Service (Denial of Service DoS, Distributed Denial of Service
DDoS)

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

9 / 78

Integrit
Dfinition
Lintgrit des donnes dsigne ltat de donnes qui, lors de leur
traitement, de leur conservation ou de leur transmission, ne subissent
aucune altration ou destruction volontaire ou accidentelle, et conservent
un format permettant leur utilisation. Lintgrit des donnes comprend
quatre lments : lintgralit, la prcision, lexactitude/authenticit et la
validit.
Lintgrit peut tre garantie par diffrents mchanismes (e.g.,
fonctions de hachage, signature numrique)
Exemples simples : Somme de contrle (checksum), Code dtecteur
derreur de type CRC dans lentte des paquets/trame

Attaque associe
Homme au Milieu (Man in the Middle)
112
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

10 / 78

Authenticit
Definition
Lauthentification est laction dtablir ou de confirmer quune entit (ou
une personne) est authentique, cest--dire que son identit correspond
bien ce quelle prtend tre.

Attaques associes
Masquarade, spoofing
Mchanismes dauthentification :
Un artefact physique difficile reproduire comme une signature, une
empreinte digitale (biomtrie), du watermarking
Un secret partag comme un mot de passe
Une signature lectronique ; et lutilisation dun mchanisme de
certification de cls (PKI)...
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

11 / 78

Non-rpudiation

Definition
La non-rpudiation est le fait de sassurer quune des parties lors dun litige
ne peut pas prtendre ne pas tre lorigine dun certain message.
Pour garantir lorigine des donnes on utilise des certificats numriques qui
peut tre vu comme une carte didentit numrique. Un tiers de confiance
atteste du lien entre lidentit physique et lentit numrique. Exemple de
standard utilis pour la cration de certificats numriques : X509

113
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

12 / 78

Le triangle de la scurit

"It is very important to understand that in security, one simply cannot say "whats the
best firewall ?" There are two extremes : absolute security and absolute access. The
closest we can get to an absolutely secure machine is one unplugged from the network,
power supply, locked in a safe, and thrown at the bottom of the ocean. Unfortunately, it
isnt terribly useful in this state." Network Security and Networking Protocols,
A.K.Sharma and C.S.Lamba

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

13 / 78

Dpt. INFO

14 / 78

Sommaire
1

Introduction
Besoins en scurit
Les diffrents types dintrusion

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux

114
S. Vaton (Tlcom Bretagne)

UV F2B505

Pourquoi un systme de dtection dintrusions ?


La scurit cest avant tout la PREVENTION
I
I
I
I
I
I
I
I

Protection physique au niveau hardware


Mots de passe et autres moyens dauthentification
Listes daccs pour grer les autorisations
Cryptographie pour la confidentialit
Sauvegardes (backup) pour la restauration de donnes
Filtrage (firewalls) pour limiter le trafic celui autoris
Sensibilisation des utilisateurs (ingnierie sociale, maladresses...)
etc... . . .

MAIS . . .
. . . la scurit absolue nest JAMAIS garantie !

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

15 / 78

Quest-ce-quun IDS ?
IDS : Intrusion Detection System
La prvention fonctionne lorsque :
I
I

les utilisateurs internes du systme sont des personnes de confiance


il y a peu dinteractions avec lextrieur (accs rseau, cls USB,
disques externes...)

Besoin dun systme qui vienne complter la prvention

Intrusion Detection System


Un systme de dtection dintrusions (IDS) est un dispositif logiciel ou
matriel utilis pour dtecter les tentatives daccs non autorises un
ordinateur ou un rseau.

115
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

16 / 78

Taxonomie des intrus


On distingue diffrents types dintrus (J.P.Anderson, Computer Security
Threat Monitoring and Surveillance) :
External penetrator : un individu non autoris utiliser un
ordinateur qui russit dune faon ou dune autre contourner les
mcanismes de contrle daccs

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

17 / 78

Taxonomie des intrus


On distingue diffrents types dintrus (J.P.Anderson, Computer Security
Threat Monitoring and Surveillance) :
External penetrator : un individu non autoris utiliser un
ordinateur qui russit dune faon ou dune autre contourner les
mcanismes de contrle daccs
Masquerador : intrus, interne ou externe, qui a pu avoir accs au
systme en utilisant lauthentification dun utilisateur autoris

116
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

17 / 78

Taxonomie des intrus


On distingue diffrents types dintrus (J.P.Anderson, Computer Security
Threat Monitoring and Surveillance) :
External penetrator : un individu non autoris utiliser un
ordinateur qui russit dune faon ou dune autre contourner les
mcanismes de contrle daccs
Masquerador : intrus, interne ou externe, qui a pu avoir accs au
systme en utilisant lauthentification dun utilisateur autoris
Misfeasor : utilisateur lgitime qui outrepasse ses droits pour accder
des donnes, programmes, ressources pour lesquelles laccs ne lui
est normalement pas autoris

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

17 / 78

Taxonomie des intrus


On distingue diffrents types dintrus (J.P.Anderson, Computer Security
Threat Monitoring and Surveillance) :
External penetrator : un individu non autoris utiliser un
ordinateur qui russit dune faon ou dune autre contourner les
mcanismes de contrle daccs
Masquerador : intrus, interne ou externe, qui a pu avoir accs au
systme en utilisant lauthentification dun utilisateur autoris
Misfeasor : utilisateur lgitime qui outrepasse ses droits pour accder
des donnes, programmes, ressources pour lesquelles laccs ne lui
est normalement pas autoris
Clandestine User : type dintrus trs difficile dtecter car il a russi
accder au systme avec un trs haut niveau de privilges de sorte
quil peut supprimer les enregistrements daudit des actions quil vient
daccomplir
117
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

17 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)

118
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)
Tampering : attenter lintgrit des donnes ; modification malicieuse de
donnes, de logs...

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)
Tampering : attenter lintgrit des donnes ; modification malicieuse de
donnes, de logs...
Spoofing : vol didentit, se faire passer pour quelquun dautre ; exemple :
IP Spoofing (modification de ladresse source des paquets IP)

119
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)
Tampering : attenter lintgrit des donnes ; modification malicieuse de
donnes, de logs...
Spoofing : vol didentit, se faire passer pour quelquun dautre ; exemple :
IP Spoofing (modification de ladresse source des paquets IP)
Flooding, Denial of Service : faire crouler un systme en le submergeant
de requtes ; exemple : TCP SYN flooding

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)
Tampering : attenter lintgrit des donnes ; modification malicieuse de
donnes, de logs...
Spoofing : vol didentit, se faire passer pour quelquun dautre ; exemple :
IP Spoofing (modification de ladresse source des paquets IP)
Flooding, Denial of Service : faire crouler un systme en le submergeant
de requtes ; exemple : TCP SYN flooding
Phishing (hameonnage) : ingnierie sociale, exploiter la navet
dutilisateurs autoriss

120
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)
Tampering : attenter lintgrit des donnes ; modification malicieuse de
donnes, de logs...
Spoofing : vol didentit, se faire passer pour quelquun dautre ; exemple :
IP Spoofing (modification de ladresse source des paquets IP)
Flooding, Denial of Service : faire crouler un systme en le submergeant
de requtes ; exemple : TCP SYN flooding
Phishing (hameonnage) : ingnierie sociale, exploiter la navet
dutilisateurs autoriss
Injection de Code ; exemples : injections SQL

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)
Tampering : attenter lintgrit des donnes ; modification malicieuse de
donnes, de logs...
Spoofing : vol didentit, se faire passer pour quelquun dautre ; exemple :
IP Spoofing (modification de ladresse source des paquets IP)
Flooding, Denial of Service : faire crouler un systme en le submergeant
de requtes ; exemple : TCP SYN flooding
Phishing (hameonnage) : ingnierie sociale, exploiter la navet
dutilisateurs autoriss
Injection de Code ; exemples : injections SQL
Exploitation de failles dimplmentation (e.g., buffer overflow)
121
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

Taxonomie des intrusions


Diffrents types d"intrusion" :
EavesDropping (coutes indiscrtes, "sniffing" du trafic) : interception
passive du trafic sur une interface rseau (outils : TCPdump, WireShark)
Snooping and Downloading : rcupration dinformations personnelles
comme des emails, des donnes business, des mots de passe... (outils :
keyloggers, coute sur rseau WiFi...)
Tampering : attenter lintgrit des donnes ; modification malicieuse de
donnes, de logs...
Spoofing : vol didentit, se faire passer pour quelquun dautre ; exemple :
IP Spoofing (modification de ladresse source des paquets IP)
Flooding, Denial of Service : faire crouler un systme en le submergeant
de requtes ; exemple : TCP SYN flooding
Phishing (hameonnage) : ingnierie sociale, exploiter la navet
dutilisateurs autoriss
Injection de Code ; exemples : injections SQL
Exploitation de failles dimplmentation (e.g., buffer overflow)
Craquage de mots de passe et de cls

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

18 / 78

UV F2B505

Dpt. INFO

19 / 78

Etat de lart des attaques

122
S. Vaton (Tlcom Bretagne)

Qui est vulnrable ?


Institutions financires, banques ... Exemple : attaques contre
PayPal par les Anonymous (DDoS) suite la fermeture de
MegaUpload

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

20 / 78

Qui est vulnrable ?


Institutions financires, banques ... Exemple : attaques contre
PayPal par les Anonymous (DDoS) suite la fermeture de
MegaUpload
Institutions gouvernementales ... Exemple : intrusion russie sur
lIntranet de lElyse (hameonnage), attaque (DoS) contre le site du
Snat (site de la dpute UMP Valrie Boyer, proposition de loi sur les
gnocides dont lArmnie)

123
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

20 / 78

Qui est vulnrable ?


Institutions financires, banques ... Exemple : attaques contre
PayPal par les Anonymous (DDoS) suite la fermeture de
MegaUpload
Institutions gouvernementales ... Exemple : intrusion russie sur
lIntranet de lElyse (hameonnage), attaque (DoS) contre le site du
Snat (site de la dpute UMP Valrie Boyer, proposition de loi sur les
gnocides dont lArmnie)
Sites industriels... Exemple : perturbation de systmes de commande
industrielle (Iran)

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

20 / 78

Qui est vulnrable ?


Institutions financires, banques ... Exemple : attaques contre
PayPal par les Anonymous (DDoS) suite la fermeture de
MegaUpload
Institutions gouvernementales ... Exemple : intrusion russie sur
lIntranet de lElyse (hameonnage), attaque (DoS) contre le site du
Snat (site de la dpute UMP Valrie Boyer, proposition de loi sur les
gnocides dont lArmnie)
Sites industriels... Exemple : perturbation de systmes de commande
industrielle (Iran)
Fournisseurs daccs

124
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

20 / 78

Qui est vulnrable ?


Institutions financires, banques ... Exemple : attaques contre
PayPal par les Anonymous (DDoS) suite la fermeture de
MegaUpload
Institutions gouvernementales ... Exemple : intrusion russie sur
lIntranet de lElyse (hameonnage), attaque (DoS) contre le site du
Snat (site de la dpute UMP Valrie Boyer, proposition de loi sur les
gnocides dont lArmnie)
Sites industriels... Exemple : perturbation de systmes de commande
industrielle (Iran)
Fournisseurs daccs
Fournisseurs de services (Over The Top OTT ; YouTube,
FaceBook...)

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

20 / 78

Qui est vulnrable ?


Institutions financires, banques ... Exemple : attaques contre
PayPal par les Anonymous (DDoS) suite la fermeture de
MegaUpload
Institutions gouvernementales ... Exemple : intrusion russie sur
lIntranet de lElyse (hameonnage), attaque (DoS) contre le site du
Snat (site de la dpute UMP Valrie Boyer, proposition de loi sur les
gnocides dont lArmnie)
Sites industriels... Exemple : perturbation de systmes de commande
industrielle (Iran)
Fournisseurs daccs
Fournisseurs de services (Over The Top OTT ; YouTube,
FaceBook...)
Multinationales
125
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

20 / 78

Qui est vulnrable ?


Institutions financires, banques ... Exemple : attaques contre
PayPal par les Anonymous (DDoS) suite la fermeture de
MegaUpload
Institutions gouvernementales ... Exemple : intrusion russie sur
lIntranet de lElyse (hameonnage), attaque (DoS) contre le site du
Snat (site de la dpute UMP Valrie Boyer, proposition de loi sur les
gnocides dont lArmnie)
Sites industriels... Exemple : perturbation de systmes de commande
industrielle (Iran)
Fournisseurs daccs
Fournisseurs de services (Over The Top OTT ; YouTube,
FaceBook...)
Multinationales
TOUT LE MONDE !
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

20 / 78

UV F2B505

Dpt. INFO

21 / 78

Sommaire
1

Introduction

Vue densemble des IDS


Taxonomie
Evolution historique

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux

126
S. Vaton (Tlcom Bretagne)

Sommaire
1

Introduction

Vue densemble des IDS


Taxonomie
Evolution historique

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

22 / 78

Taxonomie des IDS


Les IDS peuvent tre classs sur la base de diffrents critres :
1 Systme surveill
I
I
2

Architecture
I
I

Centralise
Distribue

Techniques danalyse
I
I

IDS hte (Host IDS, HIDS)


IDS rseau (NIDS)

Stateful
Stateless

Techniques de dtection
I
I

IDS bas signature


IDS bas anomalies
127

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

23 / 78

IDS hte vs. IDS rseau


IDS hte
A pour objet de dtecter des tentatives dintrusion au niveau dun
hte particulier
Dpend de larchitecture de machine et du systme dexploitation
utilis
Traite des donnes haut niveau (par ex. des appels systme)
Utile pour dtecter des intrusions venant de l"intrieur"

IDS rseau
A pour objet de dtecter des attaques destination de machines sur
un rseau local
Dpend des architectures de machines et des systmes dexploitation
Traite des donnes un niveau de granularit trs fin (paquets IP)
Utile pour dtecter des attaques venant de l"extrieur"
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

24 / 78

IDS centralis vs. IDS distribu


IDS centralis
Toutes les oprations sont ralises au niveau dun seul point
Plus simple raliser
Un seul point de dysfonctionnement

IDS distribu
Constitu de plusieurs composants
I
I
I

Capteurs qui gnrent des vnements de scurit


Console pour surveiller les vnements et les alertes et contrler les capteurs
Moteur central qui enregistre/corrle les vnements et gnre les alarmes

Besoin de travailler avec diffrents formats de donnes


Standards :
I
I

IPFIX pour remonter des mesures de niveau flot des points de capture
au collecteur centralis
IDMEF pour changer des alarmes

128
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

25 / 78

Stateless IDS vs. Stateful IDS


Stateless IDS
Traite chaque vnement indpendamment des autres
Simple concevoir
Passe lchelle en termes de vitesse de traitement

Stateful IDS
Maintient une information sur les vnements prcdents
Linterprtation dun vnement dpend de sa position dans un flot
dvnements
Plus complexe concevoir
Traitements lourds, problmes potentiels de passage lchelle

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

26 / 78

IDS bass signature vs. IDS bass anomalie


IDS bass signature
Identifient les intrusions en reconnaissant des patterns spcifiques
supposment malicieux ("signatures") dans le trafic ou dans les
donnes applicatives
Base de donnes de signatures devant tre mise jour rgulirement
Ne peuvent dtecter que des attaques connues ; problmes avec les
attaques "zero day"

IDS bass anomalie


Identifient les intrusions en dtectant des comportements inhabituels
Ncessitent une phase pralable de calibration pour apprendre les
comportements normaux
Capables de dtecter des attaques "nouvelles"
Gnrent plus de fausses alarmes que les IDS bass signature
129
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

27 / 78

Caractristiques des IDS

L.M, Suplec

La dtection d'intrusions

Existe-t-il un meilleur choix ?


Combiner lutilisation des deux :
I
I
I

HIDS (pour les attaquants internes) & NIDS (pour les attaquants
externes)
IDS bas signature (taux de fausse alarme plus faible) & IDS bas
anomalie (pour les attaques "zero day")
Stateless IDS (traitement rapide et lger des donnes) & Stateful IDS
(pour les attaques plus complexes)

Architecture de lIDS
I

IDS distribu :
F
F
F

Pas un seul point de fonctionnement


Plus adapt pour la surveillance de grands rseaux
FP7 DEMONS : DEcentralized, cooperative, and privacy-preserving
MONitoring for trustworthinesS surveillance collaborative de trafic
en inter-domaine

IDS centralis :
I
I

pas de problme dorchestration des mesures, de corrlation des alarmes


mais vision "partielle" du rseau ?

130
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

28 / 78

Sommaire
1

Introduction

Vue densemble des IDS


Taxonomie
Evolution historique

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

29 / 78

Un peu dhistoire
On peut distinguer trois grandes poques dans lvolution des IDS
1 IDSs de Premire Gnration (fin des annes 1970s)
I

I
I

Apparition du concept dIDS la fin des annes 1970s, dbut des


annes 1980s (Anderson, Computer Security Monitoring and
Surveillance, Tech Rep 1980)
Audit de donnes sur une seule machine
Traitement hors ligne des donnes (post processing)

131
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

30 / 78

Un peu dhistoire
On peut distinguer trois grandes poques dans lvolution des IDS
1 IDSs de Premire Gnration (fin des annes 1970s)
I

I
I
2

Apparition du concept dIDS la fin des annes 1970s, dbut des


annes 1980s (Anderson, Computer Security Monitoring and
Surveillance, Tech Rep 1980)
Audit de donnes sur une seule machine
Traitement hors ligne des donnes (post processing)

IDSs de Seconde Gnration (1987)


I
I

Intrusion Detection Expert System (Denning, An intrusion Detection


Model, IEEE Trans. on Soft. Eng., 1987)
Analyse statistique de donnes

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

30 / 78

Un peu dhistoire
On peut distinguer trois grandes poques dans lvolution des IDS
1 IDSs de Premire Gnration (fin des annes 1970s)
I

I
I
2

IDSs de Seconde Gnration (1987)


I
I

Apparition du concept dIDS la fin des annes 1970s, dbut des


annes 1980s (Anderson, Computer Security Monitoring and
Surveillance, Tech Rep 1980)
Audit de donnes sur une seule machine
Traitement hors ligne des donnes (post processing)
Intrusion Detection Expert System (Denning, An intrusion Detection
Model, IEEE Trans. on Soft. Eng., 1987)
Analyse statistique de donnes

IDSs de Troisime Gnration (en cours)


I
I
I

IDS rseau
Dtection et raction en temps rel
Intrusion Detection System Intrusion Prevention System

132
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

30 / 78

Programme dvaluation DARPA

1998/1999 DARPA/MIT IDS evaluation program : programme


complet dvaluation des IDS (le plus complet ce jour)
Fournit un grand nombre de donnes pour le dveloppement,
lamlioration, lvaluation des IDS
Diffrents types de donnes disponibles :
I
I

logs au niveau systme


trafic rseau

Simulations de trafic rseau (entre une base de lUS Air Force et


lInternet) pour la gnration du trafic normal ; attaques
exprimentales

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

31 / 78

Le rseau DARPA

133
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

32 / 78

Dataset DARPA/MIT
5 semaines de donnes
I
I
I

semaines 1 et 3 : pas dattaques, utilisables pour lentranement du


systme
semaine 2 : attaques tiquetes ; peut tre utilis pour construire des
bases de signature
semaines 4 et 5 : diffrentes attaques ; peut tre utilis pour valuer les
performances en dtection des IDS

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

33 / 78

Dataset DARPA/MIT
5 semaines de donnes
I
I
I

semaines 1 et 3 : pas dattaques, utilisables pour lentranement du


systme
semaine 2 : attaques tiquetes ; peut tre utilis pour construire des
bases de signature
semaines 4 et 5 : diffrentes attaques ; peut tre utilis pour valuer les
performances en dtection des IDS

Diffrents types dattaques : Denial of Service (DoS), User to Root


(U2R), Remote to Local (R2L), ... ; 177 instances de 59 types
diffrents dattaques

134
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

33 / 78

Dataset DARPA/MIT
5 semaines de donnes
I
I
I

semaines 1 et 3 : pas dattaques, utilisables pour lentranement du


systme
semaine 2 : attaques tiquetes ; peut tre utilis pour construire des
bases de signature
semaines 4 et 5 : diffrentes attaques ; peut tre utilis pour valuer les
performances en dtection des IDS

Diffrents types dattaques : Denial of Service (DoS), User to Root


(U2R), Remote to Local (R2L), ... ; 177 instances de 59 types
diffrents dattaques
La vrit sur les attaques est fournie ("Attack Truth list") ce qui
permet dvaluer le taux de fausse alarme (faux positifs) et de non
dtection (faux ngatifs) des IDS tests

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

33 / 78

Dataset DARPA/MIT
5 semaines de donnes
I
I
I

semaines 1 et 3 : pas dattaques, utilisables pour lentranement du


systme
semaine 2 : attaques tiquetes ; peut tre utilis pour construire des
bases de signature
semaines 4 et 5 : diffrentes attaques ; peut tre utilis pour valuer les
performances en dtection des IDS

Diffrents types dattaques : Denial of Service (DoS), User to Root


(U2R), Remote to Local (R2L), ... ; 177 instances de 59 types
diffrents dattaques
La vrit sur les attaques est fournie ("Attack Truth list") ce qui
permet dvaluer le taux de fausse alarme (faux positifs) et de non
dtection (faux ngatifs) des IDS tests
MAIS... le jeu de donnes DARPA est considr comme obsolte car trop
ancien pour reflter la nature actuelle du trafic et des attaques.
135
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

33 / 78

Autres datasets
KDD99 :
autre trace publique tiquete disponible pour lvaluation dIDS
cre spcialement pour lvaluation dIDS lors du Third
International Knowledge Discovery and Data Mining Tools
Competition
comme DARPA, KDD99 est juge obsolte

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

34 / 78

Autres datasets
KDD99 :
autre trace publique tiquete disponible pour lvaluation dIDS
cre spcialement pour lvaluation dIDS lors du Third
International Knowledge Discovery and Data Mining Tools
Competition
comme DARPA, KDD99 est juge obsolte
Autres donnes publiques :
il existe diffrentes traces de trafic accessibles publiquement ; e.g.
CAIDA, Abilene (Internet2), GEANT, . . .
problme majeur : pas de "ground-truth" !

136
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

34 / 78

Autres datasets
KDD99 :
autre trace publique tiquete disponible pour lvaluation dIDS
cre spcialement pour lvaluation dIDS lors du Third
International Knowledge Discovery and Data Mining Tools
Competition
comme DARPA, KDD99 est juge obsolte
Autres donnes publiques :
il existe diffrentes traces de trafic accessibles publiquement ; e.g.
CAIDA, Abilene (Internet2), GEANT, . . .
problme majeur : pas de "ground-truth" !
Dune manire gnrale la recherche dans le domaine a besoin accder
des mesures qui soient la fois dans le domaine public et reprsentatives
Problme rcurrent, difficults lies la confidentialit des donnes
oprateurs
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

34 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS


Types de donnes analyses
Placement et configuration de lIDS
IDS distribus

Introduction SNORT

IDS comportementaux
137
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

35 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS


Types de donnes analyses
Placement et configuration de lIDS
IDS distribus

Introduction SNORT

IDS comportementaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

36 / 78

UV F2B505

Dpt. INFO

37 / 78

Schma fonctionnel

138
S. Vaton (Tlcom Bretagne)

Donnes rseaux
Sondes
Sondes captant linformation en sniffant le rseau (NIDS : Network
IDS)
Rassemblage des paquets fragments (IP et TCP)
Extractions des enttes et de la payload
Analyse plus ou moins pousse dans les couches applicatives

Avantages et incovnients
Avantages : Couverture large Aucun impact sur le systme (Sondes
ddies) Format standard de donnes de facto Travail en ligne
possible (IPS, Intrusion Prevention Systems)
Inconvnients : Rseaux switchs Monte en dbit des rseaux
Chiffrement
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

38 / 78

Donnes systmes
Sur la machine
Collectes sur la machine hte
Audit C2 ( Orange Book (DoD))
Exemples : NT Event Log Solaris BSM Linux snare Techniques
dacquisition ddies
SysLog : Service daudit fourni par le noyau lusage des applications
Bien intgr dans les outils de gestion rseau/Systme (standard IETF)

Avantages et incovnients
Avantages : Informations prcises lies aux utilisateurs Granularit
fine Un audit C2 est fourni avec tous les OS
Inconvnients : Impact sur les performances de lhte (CPU, disque)
Quantit dinfos importante Structure des donnes complexe
Informations trs bas niveau
139
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

39 / 78

Donnes Applicatives
Donnes de niveau applicatif
Logs fournis par les applications
Serveurs web (trs utilis), SGBD (rare)

Avantages et inconvnients
Avantage :
Quantit dinfos modre car donnes trs cibles
Inconvnient :
Donnes trop cibles ?
Toutes les applications doivent tre instrumentes
Un analyseur par format de log dapplication est ncessaire

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

40 / 78

Dpt. INFO

41 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS


Types de donnes analyses
Placement et configuration de lIDS
IDS distribus

Introduction SNORT

IDS comportementaux

140
S. Vaton (Tlcom Bretagne)

UV F2B505

Ou placer lIDS ? (1/3)


Devant et derrire le firewall :
Devant : beaucoup dalertes
Derrire (dans la DMZ) : voir ce que le firewall a laiss passer

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

42 / 78

Ou placer lIDS ? (2/3)


Dans la DMZ :
Protection minimale, cibles en premire ligne
Pas ou peu de donnes personnelles mais des serveurs
IDS applicatifs

Spcification du trafic autoris assez simple (HTTP, DNS, mail)

141
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

43 / 78

Ou placer lIDS ? (3/3)


Dans le systme dinformation :
HIDS : pb de limpact sur les htes
NIDS : pb des rseaux switchs
Problme : donnes personnelles/prives/confidentielles
Intgration lOS ?

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

44 / 78

Configuration de lIDS

Configurer lIDS : une tche complexe


Commencer par une couverture large puis rduire progressivement
Prendre en compte les caractristiques du SI (machine, services,
topologie), et la politique de scurit
Mesurer limpact/lintrt de chaque signature, et ventuellement en
dsactiver certaines (mais attention aux faux ngatifs !)
Tester la configuration de lIDS : trafic rel, analyse des alertes
(quantit de fausses alarmes)
Assurer une maintenance de la configuration de lIDS

142
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

45 / 78

Mode de fonctionnement
Analyse continue
Surveillance dynamique du systme
Permet une dtection "temps rel"
Majorit des IDS rseau
Pas toujours possible ...
I
I

Dpend du volume des donnes analyser


certaines actions ne peuvent tre qualifies "dintrusives" quaprs un
certain temps

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

46 / 78

Mode de fonctionnement
Analyse continue
Surveillance dynamique du systme
Permet une dtection "temps rel"
Majorit des IDS rseau
Pas toujours possible ...
I
I

Dpend du volume des donnes analyser


certaines actions ne peuvent tre qualifies "dintrusives" quaprs un
certain temps

Analyse priodique
Analyse priodique de log par la mme approche que celles de
lanalyse en continu
Vrification priodique de ltat du systme
I
I

Pas de dtection de lintrusion en elle-mme mais de ses effets


Exemple : usage de tripwire

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

143
46 / 78

Comportement post-dtection

Comportement de lIDS
Passif : gnration dalertes
I

Contre mesure laisse lapprciation de loprateur

Actif : contre mesure automatique


I
I
I

Kill processus, reset connexion, reconfiguration de firewall, fermeture


de compte, etc.
Risque de dni de service auto-inflig en cas de fausse alerte
Voire mme aubaine pour les attaquants...

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

47 / 78

Dpt. INFO

48 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS


Types de donnes analyses
Placement et configuration de lIDS
IDS distribus

Introduction SNORT

IDS comportementaux

144
S. Vaton (Tlcom Bretagne)

UV F2B505

Architecture dun IDS distribu


IDS distribu
Intrt dune approche hybride
Donnes rseau / systme / applicatives
Techniques comportementales et par signatures
Donc architecture multi-sondes distribution de la collecte (plusieurs
capteurs) et en partie de lanalyse (plusieurs analyseurs)

Orchestration des mesures et de lanalyse


Ncessit dune plateforme de gestion
Gestion des sondes : configuration, mises jour
Gestion des alertes : centralisation (stockage) et corrlation

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

49 / 78

Format des alertes

145
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

50 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT
SNORT : un IDS rseau bas signatures
Fonctionnement de Snort
Mcanismes dvasion

IDS comportementaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

51 / 78

Dpt. INFO

52 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT
SNORT : un IDS rseau bas signatures
Fonctionnement de Snort
Mcanismes dvasion

IDS comportementaux

146
S. Vaton (Tlcom Bretagne)

UV F2B505

Quest-ce-que Snort ?
SNORT : NIDS bas signatures
Snort est un systme de dtection dintrusion rseau (NIDS).
Snort est un IDS bas sur la signature de lattaque (bas "scnarios")
Snort est open-source la fois pour le code source et pour les rgles.

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

53 / 78

Quest-ce-que Snort ?
SNORT : NIDS bas signatures
Snort est un systme de dtection dintrusion rseau (NIDS).
Snort est un IDS bas sur la signature de lattaque (bas "scnarios")
Snort est open-source la fois pour le code source et pour les rgles.

Modes dutilisation de Snort


Mode Sniffer : "renifleur" de paquet o il se comporte comme
tcpdump.
Mode Logger : enregistreur de paquet : utile pour garder des traces
(dans des buts denqute lgale, pour confirmer des hypothses...)
Mode IDS classique.
Mode en ligne IPS. Il sappuie sur iptables (le firewall) pour
intercepter les paquets et pour interrompre les flux.
147
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

53 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT
SNORT : un IDS rseau bas signatures
Fonctionnement de Snort
Mcanismes dvasion

IDS comportementaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

54 / 78

Organisation fonctionnelle de snort :


Les plugins prparent le flux
pour lanalyse et contrent les
techniques classiques
dvasion.
Les rgles sont le coeur de
lanalyse.
Des modules de post
traitement ralisent des
gestions de la sortie et des
filtrages supplmentaires.
Les modules de sortie
mettent en forme et envoient
les rsultats pour traitement.
148
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

55 / 78

Format des rgles Snort :


Les rgles Snort sont dcrites dans un langage simple et suivant le schma
suivant :
len-tte de la rgle qui contient :
I
I
I
I

laction de la rgle (la raction de Snort)


le protocole qui est utilis pour la transmission des donnes (Snort en
considre trois : TCP, UDP et ICMP)
les adresses IP source et destination et leur masque
les ports source et destination sur lesquels il faudra vrifier les paquets.

les options de la rgle (entre parenthses) qui contiennent :


I
I

le message dalerte
les conditions qui dterminent lenvoi de lalerte en fonction du paquet
inspect.

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

56 / 78

Exemple simple de rgle Snort

Cette rgle dtecte les tentatives de login sous lutilisateur root, pour le
protocole ftp (port 21) :

Exemple :
alert tcp any any -> 192.168.1.0/24 21 (content : "USER root" ; nocase ;
msg : "Tentative daccs au FTP pour lutilisateur root" ;)
Les messages en direction de cette plage dadresse IP effectuant une
tentative de login root ("USER root" contenu dans le paquet) auront pour
consquence la gnration de lalerte "Tentative daccs au FTP pour
lutilisateur root".

149
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

57 / 78

Description des actions possibles


Les actions normales :
I
I
I
I
I

alert : gnre une alerte puis log


log : enregistre le paquet
pass : ignorer le paquet
activate : alerte et alors active une autre rgle dynamic
dynamic : reste passive jusqu tre active par une rgle activate,
alors agit comme une rgle log

Les actions IPS :


I
I
I

drop : le paquet est perdu par iptables et un log est fait.


reject : le paquet est perdu, un log est cr puis on envoie un RESET
des listes de port (TCP) ou un ICMP port unreachable (UDP).
sdrop : (silent drop) paquet perdu mais pas de log.

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

58 / 78

Les sorties de Snort :


Format de la sortie
Snort gnre deux types de sorties :
une sortie dalertes contenant au moins lidentifiant complet de la
rgle, les sources et destinations impliques et la date
en parallle un enregistrement des paquets impliqus dans lalerte.
Un identifiant est dfini par un groupe (module), un identifiant de rgle, et
lanalyse ainsi quun numro de rvision.

Gestion de la sortie
La sortie peut tre :
envoye dans des fichiers, dans une base de donnes, passe
directement syslog, etc
stocke dans un format intermdiaire pour laisser la charge du
traitement un autre processus
150
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

59 / 78

Les pr-processeurs :
Rle des pr-processeurs
dfragmentation : "voir" plusieurs paquets la fois
reconstruction des flots, corrlation des vnements
dcodage pour pemettre lanalyse des protocoles de haut niveau
ceci permet de contrer certaines techniques dinsertion/vasion

frag3
Reconstruit les paquets IP en tenant compte de larchitecture des
htes (pour comprendre comment ils dfragmentent).
On peut aussi lui spcifier une TTL minimale.

Stream5
Il reconstruit des sessions TCP et UDP.
Gre les donnes renvoyes et les superpositions de donnes comme
frag3
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

60 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT
SNORT : un IDS rseau bas signatures
Fonctionnement de Snort
Mcanismes dvasion

IDS comportementaux
151
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

61 / 78

Techniques dinsertion
Insertion
Les techniques dinsertion consistent insrer dans le flux des donnes :
qui seront vues par lIDS
qui ne seront pas vues par la cible finale du flot de datagramme.
Le but est de noyer la signature de lattaque et donc de tromper les
reconnaissances par filtrage de motifs.

Mise en oeuvre des techniques dinsertion


Il sagit de provoquer la perte du paquet entre lIDS et la cible.
Utilisation de TTL suffisamment faible pour sarrter au niveau de
lIDS (un traceroute permet de calculer la bonne valeur).
Utilisation de combinaisons doptions IP qui vont faire refuser le
paquet par la cible (par exemple en jouant avec les drapeaux rservs).
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

62 / 78

Techniques dvasion
Evasion
Les techniques dvasion consistent transformer le contenu du flux de
donnes qui seront vues par lIDS, par des oprations qui seront comprises
par la cible mais pas par lIDS.

Mise en oeuvre des techniques dvasion


Elles sont multiples et dpendantes des protocoles.
Par exemple HTTP permet de remplacer un caractre par son code
ascii prcd de
Le codage des caractres et en particulier UTF-8 permet de coder un
caractre de plusieurs manires.
Les octets nuls sont parfois interprts de manire bizarre (ignors
silencieusement).
152
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

63 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux
IDS systme
IDS rseaux

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

64 / 78

Approche comportementale
IDS comportementaux
Le principe est davoir un modle (par exemple statistique) du
comportement "normal" et de dtecter une dviation par rapport au
comportement normal.

153
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

65 / 78

Approche comportementale
IDS comportementaux
Le principe est davoir un modle (par exemple statistique) du
comportement "normal" et de dtecter une dviation par rapport au
comportement normal.

Apprentissage et dtection
Ncessite deux phases :
phase dapprentissage : apprendre les situations normales
(comportements habituels des utilisateurs, du trafic...) ; construire une
base de connaissances caractrisant "ce qui est normal"
phase de dtection : analyse des mesures (fichier daudit, sniffing
rseau...) pour vrifier la conformit au modle caractrisant un
comportement "normal"
Rem : la base dapprentissage doit tre mise jour rgulirement (non
stationnarits, volutions du comportement des utilisateurs, volution du
trafic...)
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

65 / 78

UV F2B505

Dpt. INFO

66 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux
IDS systme
IDS rseaux

154
S. Vaton (Tlcom Bretagne)

Modle statistique de DENNING


D.Denning, An Intrusion Detection Model, IEEE Trans. on Software
Engineering, 1987
Ce modle comprend six composantes :
Sujets : initiateurs des actions faites sur le systme (utilisateur, processus...)
Objets : rcepteurs de ces actions (fichiers, programmes...)
Enregistrements daudits : gnrs par le systme chaque action entreprise par les
sujets sur les objets ; ils contiennent lidentificateur du sujet, de lobjet, laction entreprise,
un horodatage...
Profils : structures caractrisant le comportement des sujets envers les objets ; sexpriment
en termes de mtriques statistiques sur le comportement des utilisateurs
Enregistrements danomalies : gnrs en cas de dtection dun comportement
"anormal" ; contient lhorodatage, le profil, lvnement...
Rgles dactivit : spcifient laction entreprendre lors dun enregistrement danomalie

Approche statistique : partir de n observations x1 , x2 , . . . , xn dune


variable alatoire X on dtermine si une nouvelle observation est
vraissemblable ou non.
Par exemple, sous un modle gaussien dcorrl ou corrl.
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

67 / 78

Approche immunologique
Forrest et al., A sense of self for Unix processes, Proceedings of the IEEE
Symposium on Security and Privacy, 1992. Vise caractriser le
comportement normal dutilisation du systme laide de courtes
squences dappels systme gnrs par les applications.
ensemble dappels systme : open, read, write, close, getrlimit, brk, sbrk...
construire une base de donnes de comportement normal pour chaque
application
comportement normal : courte squence de k appels systme conscutifs
(k= 5,6,11)
phase dapprentissage :
I
I

analyse de traces dappels systmes et construction de la base ;


objectif : numrer tous les N-grams possibles
tape dlicate ; possibilit de construire la base partir des
spcifications fonctionnelles de lapplication

phase de dtection : dtecter des N-grams qui ne sont pas connus dans la
base dapprentissage alarme !

155

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

68 / 78

Approche neuronale
H. Debar et al., A neural network component for an Intrusion Detection
System, Proc. of the IEEE Symposium on Research in Computer Security
and Privacy, 1992.
HyperView : IDS comprenant deux composants.
I
I

Systme expert analysant le fichier daudit pour dtecter des intrusions


connues.
Rseau de neurones apprenant le comportement normal de
lutilisateur et dtectant une dviation de laudit par rapport au
comportement appris.

Analyse la succession des commandes introduites par lutilisateur


(ls, chmod, pwd, vi, ...) ; travaille sur des squences de N commandes
successives
Architecture du rseau de neurones :
I
I

entres : (N-1) commandes successives ; sortie : la commande suivante


(N-ime commande)
prdit la N-ime commande la plus vraissemblable (au vu des
commandes 1 N-1)

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

69 / 78

UV F2B505

Dpt. INFO

70 / 78

Sommaire
1

Introduction

Vue densemble des IDS

Fonctionnement des IDS

Introduction SNORT

IDS comportementaux
IDS systme
IDS rseaux

156
S. Vaton (Tlcom Bretagne)

SPADE
Spade est un plugin pr-processeur pour Snort ; il ajoute une couche de
dtection danomalie de comportement Snort qui utilise des
scnarios.
Associe une mtrique de "bizarrerie" chaque paquet fonde sur un
certain nombre de caractristiques (ex : IP et port de destination) ; les
paquets les plus anormaux gnrent une alerte.
Maintient des tables de probabilits contenant une information sur la
frquence doccurrence de paquets de diffrents types sur le rseau .
Les tables de probabilits sont mises jour rgulirement et suivent
donc lactivit du systme. Les observations anciennes sont dprcies
par rapport aux observations rcentes.
Le dtecteur suit la frquence des paquets allant vers des ports clos,
des htes inconnus, des ports bizarres, les paquets ICMP rares...
Exemple pour les paquets DNS :
I
I

les tables de probabilit disent que la probabilit dun paquet vers le


serveur DNS sur le port 53 est 10%
tandis que la probabilit dun paquet vers le serveur DNS sur le port 80
est 0.1%

S. Vaton (Tlcom Bretagne)


UV F2B505
Attention
: Spade nest plus maintenu.

Dpt. INFO

71 / 78

Descripteurs de trafic
Niveau paquet :
Longueurs de paquets, temps inter-arrive des paquets
Diffrents champs dentte (adresses et ports source et destination,
protocole, ToS, drapeaux TCP ...)
etc...

Niveau flot :
Longueur du flot (nombre de paquets, quantit de donnes)
Dure du flot
5 uplet : @IP Source et Destination, Port Source et Destination,
Protocole
Les mesures de trafic de niveau flot ralises par un point de capture sont
remontes un collecteur. NetFlow de CISCO, Standard IPFIX.
157
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

72 / 78

Data Stream Mining (1/2)


Ide :
I
I
I
I

on ne peut pas dcouvrir danomalies dans un trafic trs agrg (ex :


volumes de trafic par seconde sur une interface rseau)
Par contre une observation du trafic un grain trs fin (adresses IP,
ports) rvle des anomalies trs riches.
Exemple : paquets par IP destination par seconde dtection de DoS
ou scan de port.
Autres "anomalies" pouvant tre dtectes par comptage de certains
types de paquets IP : scans de port, scans rseau, DoS, DDoS...

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

73 / 78

Data Stream Mining (1/2)


Ide :
I
I
I
I

on ne peut pas dcouvrir danomalies dans un trafic trs agrg (ex :


volumes de trafic par seconde sur une interface rseau)
Par contre une observation du trafic un grain trs fin (adresses IP,
ports) rvle des anomalies trs riches.
Exemple : paquets par IP destination par seconde dtection de DoS
ou scan de port.
Autres "anomalies" pouvant tre dtectes par comptage de certains
types de paquets IP : scans de port, scans rseau, DoS, DDoS...

MAIS problme : cardinalit de lespace des donnes. @IP en IPv4 :


32 bits soit 232 valeurs surveiller (comptage des paquets/volumes de
trafic par adresse IP).

158
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

73 / 78

Data Stream Mining (1/2)


Ide :
I
I
I
I

on ne peut pas dcouvrir danomalies dans un trafic trs agrg (ex :


volumes de trafic par seconde sur une interface rseau)
Par contre une observation du trafic un grain trs fin (adresses IP,
ports) rvle des anomalies trs riches.
Exemple : paquets par IP destination par seconde dtection de DoS
ou scan de port.
Autres "anomalies" pouvant tre dtectes par comptage de certains
types de paquets IP : scans de port, scans rseau, DoS, DDoS...

MAIS problme : cardinalit de lespace des donnes. @IP en IPv4 :


32 bits soit 232 valeurs surveiller (comptage des paquets/volumes de
trafic par adresse IP).
SOLUTION algorithmique : techniques de fouilles de donnes en
temps rel (data stream mining)

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

73 / 78

Data Stream Mining (2/2)

Techniques de comptage (par @IP, par port, etc...)


difficile de maintenir des listes du fait de la trs grande cardinalit de
lespace surveiller
des techniques existent pour maintenir des compteurs dune manire
"compacte" (efficace en utilisation de la mmoire)
I
I

filtrage de Bloom
algorithme Count Min Sketch (Cormode, Muthukrishran ; 2004)

159
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

74 / 78

Algorithme CMS : Count Min Sketch (1/2)


Principe du CMS
flot de donnes ; chaque lment du flot est caractris par un
identifiant (ex : IP dest.) i {1, 2, . . . , N} (N trs grand) et par un
label c R (ex : taille du paquet en octets)

on se donne d fonctions de hachage h1 , h2 , . . . , hd de {1, 2, . . . , N}


dans {0, 2, . . . , w 1} avec w << N ; elles doivent avoir de bonnes
proprits de dcorrlation entre elles
on maintient une table S appele sketch de taille d lignes et w
colonnes ; cette table est une "mmoire" du trafic analys (comptage
de la quantit de trafic par identifiant i {1, 2, . . . , N})

S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

75 / 78

Algorithme CMS : Count Min Sketch (2/2)


Mise jour du sketch : quand une nouvelle donne (it , ct ) arrive on
met jour la table : S[j, hj (it )]+ = ct , j {1, 2, . . . , d }

Estimation (du volume de trafic associ un identifiant


= minj1,...,d S[j, hj (i)]
i {1, 2, ..., N}) : A(i)

160
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

76 / 78

Techniques de dtection de changements


Objectif : dtecter un changement brusque dans un flot de donnes (par
ex. augmentation brutale du trafic vers une IP ou un port destination...)
Exemple de lalgorithme du CUSUM :
algorithme classique en thorie de la dcision squentielle
permet de dtecter un instant de changement ;
flot de donnes : x1 , x2 , x3 , ... ; distribution avant (respectivement
aprs) changement caractrise par sa densit de probabilit f1
(respectivement f2 )
la "statistique" du test du CUSUM est maintenue de manire
n+1 )
squentielle : Sn+1 = max(0, Sn + log ff21 (x
(xn+1 ) )
une alarme est leve lorsque la statistique Sn dpasse un certain seuil h
influence du seuil h : plus h est lev plus rares sont les fausses
alarmes mais plus long est le dlai de dtection
CUSUM : proprits doptimalits dmontres (minimise le dlai de
dtection pour un taux de fausse alarme borne)
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

77 / 78

Exemple : dtection dun changement de moyenne dans une srie temporelle avec le CUSUM

CUSUM non paramtrique :


Limitation : la distribution aprs changement est rarement connue
Il existe des versions non paramtriques du CUSUM qui font trs peu
dhypothses sur les distributions avant et aprs changement.
Exemple : NP-CUSUM
Sn+1 = Sn + xn ( + c )

avec et les moyenne et cart-type de la srie temporelle avant


changement. Capable de dtecter une augmentation de la moyenne de la
161
srie temporelle si son amplitude est suprieure c.
S. Vaton (Tlcom Bretagne)

UV F2B505

Dpt. INFO

78 / 78

IDS Lab
Network Security Course - November 2014

Intrusion Detection Systems Snort


1

Lab environment

Netkit is a tool able to simulate a network on a Linux computer. It is based on


User Mode Linux that is to say that Linux can be launched as a user application which makes it possible to create virtual machines. Virtual machines are
connected through collision domains which behave as an Ethernet network.
Each machine has its own file system and can use its own kernel so that the
heterogeneous machines can make up the network. Each machine is controlled
by the user (root) through a terminal (xterm).
Netkit is able to simulate quite large networks since memory is used efficiently.
In our case, we will use only five machines. The description of the network is
a laboratory which is entirely included in a folder (lab-vpn). The main control
commands must be executed in the folder of the laboratory:
lstart to start the different machines
lstop to stop the machines
lclean to clean up the temporary files in case of problem
Each machine provides access to folders /hostlab and /hosthome which respectively correspond to the description folder of the laboratory and to the
$HOME folder on the host machine.
During this practical we will mainly use the /hostlab where tools and traces
are stored. On the host machine this folder is lab-ids. We will mainly use
three machines: pc1 to launch attacks, pc8 (192.168.8.2) as target of attacks,
and the machine ids for the IDS. You can close the other windows.

Snort

Configure the eth0 interface of machine ids with the promisc option of the ifconfig command without
providing a network adress. Check the configuration with ifconfig without option. Snort can be used to
monitor traffic such as tcpdump. Launch Snort on ids with the option -vd. This makes it possible to observe
the contents of packets.
You can use services that are running on pc8 (192.168.8.2), for example ftp (anonymous, without password). Observe now the contents of packets.
Now stop snort (Ctrl-Z followed by kill -9 %1) and launch snort in intrusion detection mode with the
default configuration:
/etc/init.d/snort/start
Alerts are stored in /var/log/snort. Open once again the ftp connexion, followed by the command cd
dir where dir is the name of an arbitrary folder (not existing) and very long (at least 100 characters). Try
also the command ls ../...

163

Network Security Course - November 2014

Look at the result in the file alert that has been created in the log folder (tail -f /log/snort/alert). Observe
that two groups of rules have been activated by your action. Find out the meaning of one of those groups in
/etc/snort/gen-msg.map. The other group corresponds to the GID 1. The second number is the number of
the rule that can be found in /etc/snort/rules. Look at the rules which have been triggered and explain their
contents. Some rules use jointly content and pcre, check in which order are performed the operations.

Scanning a target

nmap is a tool that makes it possible to detect open ports on a machine and to collect some information on
running services and the operating system. Analyzing which ports are open is useful for system administration, but it is also a preliminary step for a targeted attack. Another approach consists in flooding a network
with a malware until a number of vulnerable computers have been found.
Use different options of nmap in order, starting from the IP adress of pc8, to discover the other machines,
the interfaces to other networks, and the operating system of the machine. Watch the alerts that are triggered
by the IDS. You can speed up ICMP scans with the -T 4 option.
Look at the different rules which are activated. Note that alert correlation is useful even with such a
simple example.

Exploiting a weakness

Now you are going to execute a server serv on pc8. It receives each command line and writes it on its output.
This application is vulnerable to a message that contains the words target real and attack. It is launched on
pc8. One knows that the used port number is between 2000 and 2100 and that the protocol is UDP. (Dont
use the -T 4 option with UDP scan).
Use a nmap scan in order to determine the port used by the server. Use the online manual in order to
find out the appropriate nmap options. What does happen when nmap tries the right application port?
You can now use the Python script /hostlab/client in order to send messages. Find the appropriate
parameters to make the attack succesfull. Check the behavior of the script with various strings and describe
a model of successfull attacks. (Hint: two words must be separated by a space and the third one must be
placed after this group of two words).

4.1

Writing a rule

You are now going to use your own configuration file. As a starting point you will use /hostlab/snort.conf.
Stop the standard version of Snort (/etc/init.d/snort stop) and launch your own version:
snort -l /hostlab/log -c /hostlab/snort.conf
Write a rule that captures the weakness. You must be careful about the following points:
the vulnerable machine is known
the rule must be valid for all the range and for the appropriate type of trafic
it must analyze the payload in order to find out exactly the sequence given above
Note: it is important to limit the number of packets analyzed in deep because this slows the IDS down
and consequently limits the packet rate that can be processed.
You can use the Snort documentation in order to establish the syntax of your rules.

164

Network Security Course - November 2014

IDS evasion techniques

5.1

Insertion

You have at disposal a number of PCAP files (in the folder /hostlab/pcap). These files correspond to captures
of diverse variants of the same attack. You are going to use tcpreplay on pc1 to replay those traces:
tcpreplay -i eth1 fichier.pcap
Check that each attack file is successfull. They have been numbered by increasing complexity level.
Note: if you try to replay these files elsewhere they will not work. Explain why. You can use tcprewrite
to find a solution.
Study each file with wireshark to understand how the UDP trafic has been manipulated in each example.
The snort manual is available in /hostlab/snort-manual.pdf. Look at the options of the frag3 preprocessor.
Activate one by one each of the options in order to capture the different problems. Explain in particular how
Snort makes it possible to fight against the evasion techniques. (Stop and restart completely Snort between
each modification since the modification of the preprocessors may not work with kill -1).
You can also use Snort to read the PCAP files rather than replaying them with tcpreplay:
snort -l log -c snort.conf -r pcap/traceX.pcap

5.2

Evasion techniques

The vulnerable server recognizes the syntax %xx where xx is the hexadecimal code of the Ascii character.
Adapt your rule (you have to use the pcre option).

The notion of state in an applicative protocol

You are now going to use serv2. This is a TCP server on port 2000 which is sensitive to the succession of
messages:
lock
attack
except if a message unlock is received between them. Each of them corresponds to a different command
and you can explore with telnet the behavior of the server. Use the notion of flowbits in order to write a rule
that captures this vulnerability.
The option is used as follows (see manual page 140):
flowbits: operation, nameOfFlow;
where nameOfFlow is an arbitrary name that identifies the tracked state. Possible operations are:
set
Sets the flowbit to 1
unset
Sets the flowbit to 0
isset
checks that the flowbit is equal to 1
isnotset checks that the flowbit is equal to 0
noalert Makes it possible to desactivate alerts related to that rule
0

This Lab was developed by Pierre Cregut, Orange Labs (Lannion, France).

165

VPN Lab

TP R
eseaux priv
es virtuels
1
1.1

Le r
eseau
emul
e
Netkit

Netkit permet de simuler un reseau sur un PC. Il repose sur User Mode Linux qui permet de lancer
un noyau Linux comme une application utilisateur et de creer ainsi une machine virtuelle. Les machines
virtuelles sont reliees entre elle par des zones de collision se comportant comme un reseau Ethernet.
Chaque machine a son propre syst`eme de fichier et peut utiliser son propre noyau. Il sagit donc dun
reseau de machines heterog`enes. Chaque machine est contr
olee par lutilisateur (root) via une console de
controle (ici un terminal xterm).
On peut simuler des reseaux assez importants avec netkit car la memoire est tr`es efficacement utilisee.
Dans le cas qui nous interesse, nous nous contenterons de 5 machines. La description du reseau constitue
un laboratoire. Elle est enti`erement contenue dans un repertoire (ici lab-vpn). Les principales commandes
de controle doivent etre executees dans le repertoire de base du laboratoire.
lstart permet de lancer les differentes machines
lstop permet de les arreter.
lclean permet de nettoyer tous les fichiers temporaires en cas de probl`eme.
Chaque machine donne acc`es aux repertoires /hostlab et /hosthome correspondant respectivement
au repertoire de description du labo et au repertoire ${HOME} sur la machine h
ote.

1.2

Topologie du r
eseau de test

Fig. 1 Le reseau utilise


La topologie du reseau est presentee sur la figure 1. Le reseau est constitue de trois sous reseaux :
un reseau federateur 100.0.0.0/16 ;
deux sous reseau prives (192.168.1.0 et 192.168.2.0) abritant chacun une machine (resp. pc1 et pc2)
et connectes au reseau federateur par une passerelle (resp. gw1 et gw2) ;
un PC isole sur le reseau federateur (pc3).
Pour simplifier les choses, les adresses sont fixes et on na pas active la traduction dadresse (NAT) sur
les passerelles. On souhaite relier les deux reseaux prives entre eux par un tunnel (configuration reseau
`a reseau).
Lancez le reseau avec lstart. Prenez une minute pour vous familiariser avec le reseau. Identifiez les
adresses et les interfaces utilisees par toutes les machines ifconfig. Verifiez le contenu des routes route.

167

Un VPN SSL : OpenVPN

2.1

Cr
eation dun VPN r
eseau `
a r
eseau

Il sagit de creer un reseau entre les machines passerelle gw1 et gw2. Ce reseau est un tunnel sur
lequel la machine 1 aura par exemple ladresse 192.168.0.1 et la machine 2 ladresse 192.168.0.2.
Sur chacune des machines (identifiee par A lautre etant la machine B), lancer :
openvpn --remote ipB --port 8000 --dev tun1 --ifconfig 192.168.0.A 192.168.0.B --verb 5
Reflechissez bien `a la valeur dipB et noubliez pas de substituer A et B
Quel est le role de tun1 ?
Il faut maintenant redefinir les routes. A laide de la commande route arreter et remplacer la route
vers le reseau controle par B. Expliquez le sens de loperation (`
a la fois interface et adresses). Faites
man route si vous ignorez la syntaxe.

Echangez
du trafic entre les deux machines : vous pouvez commencer par ping
Capturez le trafic avec tcpdump (par exemple sur pc1 et pc3). Utilisez par exemple
tcpdump -U -w /hostlab/capture[13].pcap -i /dev/eth0
Le fichier est ecrit dans le repertoire de base du TP. Vous pouvez le regarder avec wireshark :
quel type de trafic est echange ?
Il faut decoder la payload en choisissant le bon filtre.
Pouvez vous en tirer des conclusions ? Regardez les adresses et expliquez lencapsulation.
Loption compression Vous pouvez rajouter de la compression avec loption --comp-lzo. Recommencez lexperience (utilisez killall pour arreter openvpn et noubliez pas de remettre les routes en place).
Refates une capture sur pc3. Quavez vous perdu ?
Utilisez un fichier de configuration A partir de cette etape il est conseille dutiliser des fichiers
de configuration. Creez deux fichiers vpn-gw1.conf et vpn-gw2.conf en reprenant chacune des options
passees `a openvpn `a raison dune option par ligne et en supprimant les deux tirets () en tete doption. Verifiez que votre fichier est correct en relancant openvpn cette fois ci avec pour seule option
--config <fichier>.

2.2
2.2.1

S
ecurisation du VPN
Chiffrement

Vous allez creer une cle pour le chiffrement des donnees que vous mettrez dans /hostlab/key. Elle
sera ainsi accessible aux deux machines passerelles. Dans la realite, il faudrait probablement un coursier
pour les echanger.
La generation est tr`es simple et se fait directement avec openvpn :
openvpn --genkey --secret /hostlab/key
Ajoutez loption --secret /hostlab/key `
a la commande de lancement dopenvpn et relancez le
RPV. Regardez de nouveau le trafic avec tcpdump/wireshark. Que pouvez vous en conclure ?
2.2.2

G
en
eration de certificats

Nous allons creer des cles RSA et les faire signer par une autorite de certification (CA) qui sera
installee sur pc1 (la seule machine pour laquelle le fichier de configuration ssl a ete correctement defini
1
).
Rappel : lautorite de certification signe les certificats qui contiennent lidentite et la cle publique dune
machine. Ce faisant, il garantit que le possesseur de la cle prive est bien celui qui est decrit. Lautorite
de certification emet un certificat signe par elle meme. Cest par lui que nous allons commencer :
1. Generation de la cle prive et du certificat (sur pc1) :
1 Si les commandes
echouent en r
eclamant des fichiers dans demoCA, la cause probable est que vous
etes sur la mauvaise
machine.

168

openssl req -subj /C=fr/O=maboite/CN=ca.maboite.com/ -new -x509 \


-keyout priv-ca.pem -out crt-ca.pem
2. Generation de la cle prive et de la demande de certificat pour gw1 (sur gw1) :
openssl req -subj /C=fr/O=maboite/CN=gw1.maboite.com/ -new -nodes \
-keyout priv-gw1.pem -out csr-gw1.pem
3. Generation du certificat (sur pc1 apr`es transfert de la demande) :
openssl ca -cert crt-ca.pem -keyfile priv-ca.pem \
-out crt-gw1.pem -in csr-gw1.pem
4. rapatriez le certificat de gw1 et une copie du certificat de CA sur gw1.
Expliquez en regardant le manuel chaque option, en particulier :
que gen`ere-t-on `a chaque etape ?
quel est le role de -x509 dans la premi`ere operation ?
quel est le role de -nodes. Pourquoi ne lutilise-t-on pas avec la cle du CA ? Pourquoi est-elle utile
pour les cles des machines ?
que decrit largument de -subj. Vous pouvez aussi entrer interactivement le contenu en supprimant
cette option. Que signifient les differents champs declares ?
Repetez loperation pour gw2, normalement vous avez maintenant 3 fichiers sur chaque passerelle correspondant a` une cle privee et deux certificats.
2.2.3

G
en
eration du fichier de param`
etres pour l
echange de Diffie-Hellman

Ce fichier nest calcule que dun cote. Dans notre exemple sur gw1 :
openssl dhparam -out dh1024.pem 1024
Que venez vous de generer ?
2.2.4

D
emarrer openvpn

Vous devez ecrire les deux fichiers de configuration dans lesquels vous preciserez :
ladresse de lautre extremite, le port, linterface reseau virtuelle utilisee, la configuration des interfaces du tunnel (comme pour la version precedente)
le fait que lun est serveur et lautre client pour TLS (tls-server et tls-client)
du bon cote lemplacement du fichier de param`etre Diffie Helmann (dh)
lemplacement du certificat de lautorite de certification (ca)
lemplacement du certificat de la passerelle (cert)
lemplacement de la cle prive de la passerelle (key)
Lancez openvpn et remettez les routes en place.

VPN IPSEC - Openswan

3.1

Cr
eation de la configuration

Le fichier de configuration doit etre cree dans /etc/ipsec.conf.


config setup
interfaces="ipsec0=eth1"
uniqueids=yes
conn netkit
keyingtries=0
authby=secret
3

169

auto=start
# Definition of left side
# Definition of right side
Regardez dans le manuel (ipsec.conf) le sens de authby.
Pour chaque cote que nous appellerons dorenavant dir, vous devez preciser :
dir=<ip> ladresse externe de la passerelle
dirsubnet=<ip>/<size> la specification du sous reseau
dirnexthop=<ip> vers quel noeud externe sont relayes les messages de la passerelle pour atteindre
lautre cote
Enfin vous devez preciser la cle utilisee dans /etc/ipsec.secrets :
ipleft ipright : PSK "chaine de caract`
eres part
eg
ee"
Notez quen pratique vous pouvez omettre les adresses IP, tant que vous navez quune connexion.
Vous pouvez utiliser le meme fichier de configuration sur les deux machines, pourquoi ?
Vous devez copier le fichier decrivant la cle sur les deux machines.
Vous pouvez maintenant lancer le VPN en tapant :
ipsec setup start

3.2

Observation du r
esultat

Verifiez que vous pouvez bien echanger des donnees entre pc1 et pc2 et entre pc1 et pc3. Fates
une capture et regardez la avec Wireshark. Comment est encapsule le trafic ? Comparez avec la solution
OpenVPN. Vous pouvez regarder les negociations entre passerelles dans /var/log/auth.log. Cest un
bon endroit pour comprendre ce qui se passe si votre configuration ne marche pas.

3.3

Utilisation des cl
es RSA et certificats X509

Dans /etc/ipsec.d vous trouverez un certain nombre de repertoires. En particulier


private pour les cles privees de la passerelle.
cacerts pour les certificats de lautorite de confiance qui garantit lautre extremite.
certs pour les certificats assurant lidentite de la passerelle.
Copiez sur chacune des passerelles, les bons fichiers (dej`
a generes pour openvpn) dans ces trois repertoires.
Modifiez ipsec.secrets pour utiliser la cle prive RSA (regardez le manuel pour trouver quelle option
choisir et comment specifier le fichier de cle prive.2 Attention, la cle nest plus symetrique !
Modifiez ipsec.conf :
Modifiez la methode dauthentification en rsasig.
Ajoutez pour chaque cote. :
lidentification du certificat avec dircert=fichier.pem
lidentifiant attendu avec dirid="identifiant". Par exemple pour gw1, cest /C=fr/O=maboite/CN=gw1.maboite
Do`
u vient cet identifiant ?
Partagez votre fichier de configuration.
Vous pouvez maintenant arreter openswan (ipsec setup stop) et le redemarrer.

Configuration Road warrior

Si vous etes arrive ici avant la fin du TP, felicitations !


Pour terminer, je vous propose un sujet plus ouvert. Commencez par arreter les VPN et installer
une route statique entre gw1 et gw2. Desormais il sagit dinstaller un VPN `
a la demande de pc2 ou
pc3 leur permettant dacceder `a pc1. `a travers la passerelle gw1. Cest une configuration road-warrior.
Commencez par openvpn. Vous aurez besoin de nouveaux certificats, mais linfrastructure de base est en
place. Le probl`eme principal est lallocation des adresses pour pc2 et pc3.
2 Il

faut donner le nom complet du fichier mais pas son r


epertoire. Openswan (en fait le composant pluto assurant
l
echange de cl
e) la trouvera si elle est `
a sa place.

170

Das könnte Ihnen auch gefallen