URL

publicité
Quelques compléments Java
réseaux et sécurité
H. Fauconnier
M2-Internet
1
Sommaire
 URL et URI
 html et swing
 URLconnections
 URLStreamHandler URLStreamHandlerFactory
 ContentHandler ContentHandlerFactory
H. Fauconnier
M2-Internet
2
URL
 la classe URL permet d'utiliser les URL
 les classes URLDecoder et URLEncoder
permettent de traiter les formulaires HTML
 Une URI est une sorte de généralisation des URL
qui inclut de Uniform Resource Location (URL)
mais aussi de Uniform Ressource Names (URN)

exemples
• tel:1-800-9988-9938
• http://www.xml.comp/pub/stax.html#id =_hdbc
 (la classe URLConnection sera décrite plus loin)
H. Fauconnier
M2-Internet
3
URL
 http://www.bib.org:80/javafaq/book/index.html?i
sbn=56888#toc
 ftp://anonymous:[email protected]/c%3a/stuf
f
protocol
 port
 authority
 chemin
 référence
 requête
 user

H. Fauconnier
M2-Internet
4
Construire une URL
 public URL(String url) throws MalformedURLException
 public URL(String protocol, String hostname, String file) throws
MalformedURLException
 public URL(String protocol, String host, int port, String file) throws
MalformedURLException
 public URL(URL base, String relative) throws
MalformedURLException
H. Fauconnier
M2-Internet
5
Remarques
 tous les protocoles ne sont pas compris par
la machine virtuelle…
 exception MalFormedURLException
H. Fauconnier
M2-Internet
6
Exemple: Quels protocoles?
import java.net.*;
public class ProtocolTester {
public static void main(String[] args) {
testProtocol("http://www.adc.org");
testProtocol("https://www.amazon.com/exec/obidos/order2/");
testProtocol("ftp://metalab.unc.edu/pub/languages/java/javafaq/");
testProtocol("mailto:[email protected]");
testProtocol("telnet://dibner.poly.edu/");
testProtocol("file:///etc/passwd");
testProtocol("gopher://gopher.anc.org.za/");
testProtocol(
"ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US?postalAddress");
testProtocol( "jar:http://cafeaulait.org/books/javaio/ioexamples/javaio.jar!"
+"/com/macfaq/io/StreamCopier.class");
testProtocol("nfs://utopia.poly.edu/usr/tmp/");
testProtocol("jdbc:mysql://luna.metalab.unc.edu:3306/NEWS");
testProtocol("rmi://metalab.unc.edu/RenderEngine");
testProtocol("doc:/UsersGuide/release.html");
testProtocol("netdoc:/UsersGuide/release.html");
testProtocol("systemresource://www.adc.org/+/index.html");
testProtocol("verbatim:http://www.adc.org/");
}
H. Fauconnier
M2-Internet
7
Quels protocoles (suite)
private static void testProtocol(String url) {
try {
URL u = new URL(url);
System.out.println(u.getProtocol() +
" is supported");
}
catch (MalformedURLException ex) {
String protocol = url.substring(0,url.indexOf(':'));
System.out.println(protocol + " is not supported");
}
}
http is supported
https is supported
ftp is supported
mailto is supported
telnet is not supported
file is supported
gopher is supported
ldap is not supported
jar is supported
nfs is not supported
jdbc is not supported
rmi is not supported
doc is supported
netdoc is supported
systemresource is supported
verbatim is supported
H. Fauconnier
M2-Internet
8
Décomposer l'url
public static void decomposeURL(String st) {
try{
URL u = new URL(st);
System.out.println("URL :" + u);
System.out.println("Protocole : " + u.getProtocol( ));
System.out.println("UserInfo :" + u.getUserInfo( ));
String host = u.getHost( );
if (host != null) {
int atSign = host.indexOf('@');
if (atSign != -1) host = host.substring(atSign+1);
System.out.println("hôte " + host);
}
else {
System.out.println("hôte null.");
}
H. Fauconnier
M2-Internet
9
suite
System.out.println("Port :" + u.getPort( ));
System.out.println("Path : " + u.getPath( ));
System.out.println("Ref : " + u.getRef( ));
System.out.println("Query: " + u.getQuery( ));
}
catch (MalformedURLException ex)
{System.err.println(st + " URL malformée"); }
}
H. Fauconnier
M2-Internet
10
Résultat
http://www.bib.org:80/javafaq/book/index.html?isb
n=56888#toc
URL
:http://www.bib.org:80/javafaq/book/index.html?
isbn=56888#toc
Protocole : http
UserInfo :null
hôte www.bib.org
Port :80
Path : /javafaq/book/index.html
Ref : toc
Query: isbn=56888
H. Fauconnier
M2-Internet
11
Obtenir des données
 public InputStream openStream( ) throws




IOException
public URLConnection openConnection( )
throws IOException
public URLConnection
openConnection(Proxy proxy) throws
IOException
public Object getContent( ) throws
IOException
public Object getContent(Class[]
classes) throws IOException
H. Fauconnier
M2-Internet
12
Charger le contenu d'une URL
public static void chargerFichier(String url) {
try {
URL u = new URL(url);
InputStream in = u.openStream();
in = new BufferedInputStream(in);
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
} catch (MalformedURLException ex) {
System.err.println(url + " mauvaise URL");
} catch (IOException e) {
System.err.println(e + " problème de lecture url "
+
url);
}
}
H. Fauconnier
M2-Internet
13
Type du contenu
public static void typeObjetURL(String st) {
try {
URL u = new URL(st);
try {
Object o = u.getContent();
System.out.println("L'objet est un " +
o.getClass().getName());
} catch (IOException ex) {System.err.println(ex);}
} catch (MalformedURLException ex) {
System.err.println(st + " URL malformée");
}
}
http://www.liafa.jussieu.fr
L'objet est un
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
H. Fauconnier
M2-Internet
14
Et encore
 URLEncoder
 URLDecoder
H. Fauconnier
M2-Internet
15
URLEncode: Exemple
public class QueryString {
private StringBuffer query = new StringBuffer();
public QueryString(String name, String value) {
encode(name, value);
}
public synchronized void add(String name, String value) {
query.append('&');
encode(name, value);
}
private synchronized void encode(String name, String value){
try {
query.append(URLEncoder.encode(name, "UTF-8"));
query.append('=');
query.append(URLEncoder.encode(value, "UTF-8"));
}
catch (UnsupportedEncodingException ex) {
throw new RuntimeException("??");
}
//...
H. Fauconnier
M2-Internet
16
Exemple (suite)
/…
public String getQuery() {
return query.toString();
}
public String toString() {
return getQuery();
}
}
H. Fauconnier
M2-Internet
17
Authentication
 Classe (abstraite) Authenticator
PasswordAuthentication représente un couple
password + user
 Méthode getPasswordAuthentication() à
redéfinir pour obtenir un
PasswordAuthenitcation
 Méthode setDefault(Authenticator) définit
l'Authenticator pour le système

• C'est à lui que s'adressera le système à chaque fois
que nécessaire
H. Fauconnier
M2-Internet
18
Pour apache:
 Fichier .htaccess: (il faut aussi un
AllowOverride AuthConfig dans
httpd.conf)
AuthType Basic
AuthName "restreint"
AuthUserFile /Users/hf/Sites/.psswd
Require user hf
.psswd est le fichier des mots de passe
 htpasswd –c /Users/hf/Sites/.passwd
hf

H. Fauconnier
M2-Internet
19
Exemple
H. Fauconnier
M2-Internet
20
html et swing
 plusieurs packages permettent de
visualiser et travailler avec html

swing peut utiliser html
H. Fauconnier
M2-Internet
21
Swing
 le texte de la plupart des composants utilisant du texte de
Swing (labels, buttons, menu items, …) peut être du HTML
Exemple:
import javax.swing.*;
public class HTMLLabelApplet extends JApplet {
public void init() {
JLabel theText = new JLabel(
"<html>Voilà un exemple de HTML dans label <b>bold</b> "
+ "en <i>italic</i> ici. <P> "
+ "avce des paragrahes, des nouvelles lignes,<hr> "
+ "<font color=red>couleurs</font> "
+ "et plus généralement les constructions htmn</html>");
this.getContentPane().add(theText);
}
}
H. Fauconnier
M2-Internet
22
JEditorPane
 JEditorPane contient une implémentation de HTML
3.2:
 constructeurs:




JEditorPane()
JEditorPane(String url)
JEditorPane(String type, String text)
JEditorPane(URL initialPage)
 méthodes
 public void setPage(URL page) throws
IOException
 public void setPage(String url) throws
IOException
 public void setText(String html)
H. Fauconnier
M2-Internet
23
Exemple
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class BrowserMinimal {
public BrowserMinimal(String st) {
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
try {
jep.setPage(st);
}
catch (IOException ex) {
jep.setContentType("text/html");
jep.setText("<html>impossible de charger "+st+" </html>");
}
JScrollPane scrollPane = new JScrollPane(jep);
JFrame f = new JFrame("exemple");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setContentPane(scrollPane);
f.setSize(512, 342);
f.setVisible(true);}
}
H. Fauconnier
M2-Internet
24
Hyperliens
 Pour manipuler les hyperliens:
HyperlinkEvent
 HyperlinkListener

• avec une seule méthode
– public hyperlinkUpdate(HyperlinkEvent e);
H. Fauconnier
M2-Internet
25
Exemple
import javax.swing.JEditorPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class SuivreLien implements HyperlinkListener{
private JEditorPane pane;
public SuivreLien(JEditorPane pane) {
this.pane = pane;
}
public void hyperlinkUpdate(HyperlinkEvent evt) {
if (evt.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED) {
try {
pane.setPage(evt.getURL());
}
catch (Exception ex) {
pane.setText("<html>impossible de trouver " +
evt.getURL() + "</html>");
}
}
}
H.}Fauconnier
M2-Internet
26
Exemple SimpleBrowser
import java.awt.EventQueue;
import java.awt.Frame;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class SimpleBrowser {
public SimpleBrowser(String initialPage) {
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
jep.addHyperlinkListener(new SuivreLien(jep));
try {
jep.setPage(initialPage);
} catch (IOException ex) {
jep.setContentType("text/html");
jep.setText("<html>impossible de charger"
+initialPage+" </html>");
ex.printStackTrace();
}
H. Fauconnier
M2-Internet
27
Exemple (suite)
JScrollPane scrollPane = new JScrollPane(jep);
JFrame f = new JFrame("Un Browser Simple");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setContentPane(scrollPane);
f.setSize(512, 342);
EventQueue.invokeLater(new FrameShower(f));
}
private static class FrameShower implements Runnable {
private final Frame frame;
FrameShower(Frame frame) {
this.frame = frame;
}
public void run() {
frame.setVisible(true);
}
}
}
H. Fauconnier
M2-Internet
28
URLConnection
 URLConnection est une classe abstraite qui
représente une connexion active spécifiée par une
URL
 Principe:







construire un objet URL
invoquer openConnection() de cet objet URL: retourne un
objet URLConnection
configurer la connexion
lire les "headers"
construire une input stream et lire les données
construire une output stream et écrire les données
fermer la connexion
H. Fauconnier
M2-Internet
29
Méthodes
 setAllowUserInteraction autorise/interdit l'interaction














avec un utilisateur
setDoInput autorise/interdit l'entrée
setDoOutput autorise/interdit la sortie
setIfModifiedSince
setUseCaches
getContent
getHeaderField
getInputStream
getOutputStream
getContentEncoding
getContentLength
getContentType
getDate
getExpiration
getLastModifed
H. Fauconnier
M2-Internet
30
Ouverture d'une page:
import java.net.*;
import java.io.*;
public class ConnexionURL {
public static void main(String[] args) {
BufferedReader Entree = new BufferedReader(new InputStreamReader(System.in));
String url;
try {
while ((url = Entree.readLine()) != null) {
URL u = new URL(url);
URLConnection uc = u.openConnection();
InputStream raw = uc.getInputStream();
InputStream buffer = new BufferedInputStream(raw);
Reader r = new InputStreamReader(buffer);
int c;
while ((c = r.read()) != -1) {System.out.print((char) c);}
}
} catch (MalformedURLException ex) { System.err.println(url + " URL
Malformée");
} catch (IOException ex) {System.err.println(ex);
}
}
H. Fauconnier
M2-Internet
31
Ouverture d'une page (avec
codage correct)
public class SourceViewer3 {
public static void main (String[] args) {
for (int i = 0; i < args.length; i++) {
try {
// set default encoding
String encoding = "ISO-8859-1";
URL u = new URL(args[i]);
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int encodingStart = contentType.indexOf("charset=");
if (encodingStart != -1) {
encoding = contentType.substring(encodingStart+8);
}
InputStream in = new
BufferedInputStream(uc.getInputStream());
Reader r = new InputStreamReader(in, encoding);
/...
H. Fauconnier
M2-Internet
32
Date dernière modification
public class DerniereModif {
public static void main(String args[]) {
for (int i=0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
HttpURLConnection http=(HttpURLConnection)u.openConnection();
http.setRequestMethod("HEAD");
System.out.println(u + "a été modifiée "
+ new Date(http.getLastModified()));
} // end try
catch (MalformedURLException ex) {
System.err.println(args[i] + " URL??");
}
catch (IOException ex) {
System.err.println(ex);
}
} // end for
} // end main
} // end DernierModif
H. Fauconnier
M2-Internet
33
//...
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException ex) {
System.err.println(args[0] + " URL?");
}
catch (IOException ex) {
System.err.println(ex);
}
} // end if
} // end main
} // end SourceViewer3
H. Fauconnier
M2-Internet
34
Lire les headers
public class HeaderViewer {
public static void main(String args[]) {
for (int i=0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
URLConnection uc = u.openConnection();
System.out.println("Content-type: " + uc.getContentType());
System.out.println("Content-encoding: "
+ uc.getContentEncoding());
System.out.println("Date: " + new Date(uc.getDate()));
System.out.println("Last modified: "
+ new Date(uc.getLastModified()));
System.out.println("Expiration date: "
+ new Date(uc.getExpiration()));
System.out.println("Content-length: " + uc.getContentLength());
} // end try
H. Fauconnier
M2-Internet
35
(Suite)
//...
catch (MalformedURLException ex) {
System.err.println(args[i] + "URL?? ");
}
catch (IOException ex) {
System.err.println(ex);
}
System.out.println();
} // end for
} // end main
} // end HeaderViewer
H. Fauconnier
M2-Internet
36
Afficher le header
public class afficheHeaders {
public static void main(String args[]) {
for (int i=0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
URLConnection uc = u.openConnection();
for (int j = 1; ; j++) {
String header = uc.getHeaderField(j);
if (header == null) break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
} // end for
} // end try
catch (MalformedURLException ex) {
System.err.println(args[i] + "URL ???");
}
catch (IOException ex) {
System.err.println(ex);
}
System.out.println();
} // end for
} // end main
} // end afficheHeaders
H. Fauconnier
M2-Internet
37
Protocoles
 À partir d'une url, openConnection()
permet d'obtenir une URLConnection
La classe concrète correspondante est
déterminée par la partie protocole (exemple
http) de l'url.
 Protocole: interactions avec le client,
génération des requêtes, interprétation des
headers etc.
 Content: conversion des données dans un format
java

H. Fauconnier
M2-Internet
38
Protocoles
 Classes
URL
 URLConnection (abstraite)
 URLStreamHandler (abstraite)
 URLStreamHandlerFactory (interface)
 Pour un nouveau protocole:

• Écrire une sous classe concrète URLConnection, une
sous classe concrète URLStreamHandler
• Pour utiliser ce protocole: implémenter
URLStreamHnadlerFactory
H. Fauconnier
M2-Internet
39
Protocoles…
 À partir d'une url extraction de la partie
protocole (exemple mailto)
transmettre à URLStreamHandlerFactory
 qui détermine l'URLStreamHandler
correspondant au protocole

H. Fauconnier
M2-Internet
40
Protocole…
 Construction d'un objet URL
 Extraction partie protocole
 Le constructeur de l'URL détermine l'URLStreamHandler:




Dans le cache
Si un URLStreamHandlerFactory est installé lui demander
Essayer plusieurs instanciations (…)
Si échec MalformedURLException
 Appel openConnection()
 Demander à l'URLStreamHandler de retourner une
URLConnnection adaptée (IOExeception)
 Interagir avec la ressource distante par cette
URLConnection
H. Fauconnier
M2-Internet
41
Exemple (finger)
% telnet rama.poly.edu 79
Trying 128.238.10.212...
Connected to rama.poly.edu.
Escape character is '^]'.
Login
Name
TTY Idle When Where
jacola Jane Colaginae *pts/7
Tue 08:01 208.34.37.104
marcus Marcus Tullius pts/15 13d Tue 17:33 farm-dialup11.poly.e
matewan Sepin Matewan *pts/17 17: Thu 15:32 128.238.10.177
hengpi Heng Pin
*pts/10
Tue 10:36 128.238.18.119
nadats Nabeel Datsun
pts/12 56 Mon 10:38 128.238.213.227
H. Fauconnier
M2-Internet
42
FingerURLConnection
public class FingerURLConnection extends URLConnection {
private Socket connection = null;
public final static int DEFAULT_PORT = 79;
public FingerURLConnection(URL u) {
super(u);
}
public synchronized InputStream getInputStream( ) throws IOException {
if (!connected) this.connect( );
InputStream in = this.connection.getInputStream( );
return in;
}
public String getContentType( ) {
return "text/plain";
}//…
H. Fauconnier
M2-Internet
43
(Suite)
public synchronized void connect( ) throws IOException {
if (!connected) { int port = DEFAULT_PORT; }
this.connection = new Socket(url.getHost( ), port);
OutputStream out = this.connection.getOutputStream( );
String names = url.getFile( );
if (names != null && !names.equals("")) {
names = names.substring(1);
names = URLDecoder.decode(names);
byte[] result;
try {
result = names.getBytes("ASCII");
}
catch (UnsupportedEncodingException ex) {
result = names.getBytes( );
}
out.write(result);
}
out.write('\r'); out.write('\n');out.flush( ); this.connected = true;
}
}
}
H. Fauconnier
M2-Internet
44
Handler
import java.net.*;
import java.io.*;
public class Handler extends URLStreamHandler {
public int getDefaultPort( ) {
return 79;
}
protected URLConnection openConnection(URL u) throws
IOException {
return new FingerURLConnection(u);
}
}
H. Fauconnier
M2-Internet
45
URLStreamHandlerFactory
import java.net.*;
public class MaFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String
protocol) {
if (protocol.equalsIgnoreCase("finger")) {
return new Handler( );
}
else {
//...
return null;
}
}
}
H. Fauconnier
M2-Internet
46
Et ensuite
public class SourceViewer {
public static void main (String[] args) {
URL.setURLStreamHandlerFactory(new MaFactory( ));
try {
URL u = new URL(args[0]);
InputStream in = new BufferedInputStream(u.openStream( ));
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read( )) != -1) {System.out.print((char) c); }
}
catch (MalformedURLException ex) {System.err.println(args[0]+" mauvaise URL"); }
catch (IOException ex) { System.err.println(ex); }
}
}
H. Fauconnier
M2-Internet
47
Cookies (RFC 2965)
set-cookie
=
"Set-Cookie2:" cookies
cookies
=
1#cookie
cookie
=
NAME "=" VALUE *(";" set-cookie-av)
NAME
=
attr
VALUE
=
value
set-cookie-av =
"Comment" "=" value
|
"CommentURL" "=" <"> http_URL <">
|
"Discard"
|
"Domain" "=" value
|
"Max-Age" "=" value
|
"Path" "=" value
|
"Port" [ "=" <"> portlist <"> ]
|
"Secure"
|
"Version" "=" 1*DIGIT
portlist
=
1#portnum
portnum
=
1*DIGIT
H. Fauconnier
M2-Internet
48
Cookies en java
 Gestion par un CookieHandler de
java.net.CookieHandler (abstraite)

Définit un "callback" permettant de gérer les
états http.
• Une url de protocole http gérera les cookies par un
CookieHandler (les cookies seront traités et mis en
cache et insérés dans les requêtes)
H. Fauconnier
M2-Internet
49
CookieHandler
 Définir le "CookieHandler"
• setDefault(cookieHandler)
• getDefault()
 Deux méthodes
 put(uri, responseHeaders)
• Met les cookies du cache dans la réponse

get(uri, requestHeaders)
• Retourne les cookies applicables pour l'uri de la
requête (un Map<String,List<String>>)

(requestHeader est un Map<StringList<String>>
H. Fauconnier
M2-Internet
50
Une implémentation
 CookieManager est une implémentation de
CookieHandler:
Une politique de gestion CookiePolicy
 Un stockage des cookies CookieStore



Mise en place:
java.net.CookieManager cm = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cm);
H. Fauconnier
M2-Internet
51
Exemple:
public class FetchCookie {
public static void monCookie(String urlString) throws Exception {
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
Object obj = connection.getContent();
CookieStore cStore = manager.getCookieStore();
List<URI> luri = cStore.getURIs();
for (URI uri : luri) {
System.out.println("url:" + uri + " cookie:" + cStore.get(uri));
}
H. Fauconnier
M2-Internet
52
Cookies
 Par défaut les cookies ne sont pas
persistants

On peut redéfinir la politique (CookiePolicy) et
le stockage (CookieStore) et définir un nouveau
CookieManager.
H. Fauconnier
M2-Internet
53
Autre politique
public class BlacklistPolicy implements CookiePolicy{
String[] blacklist;
public BlacklistPolicy(String[] list) {blacklist = list; }
public boolean shouldAccept(URI uri, HttpCookie cookie) {
String host;
try {
host = InetAddress.getByName(uri.getHost()).getCanonicalHostName();
} catch (UnknownHostException e) { host = uri.getHost(); }
for (int i=0; i<blacklist.length; i++) {
if (HttpCookie.domainMatches(blacklist[i], host)) {
return false;
}
}
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
}
}
H. Fauconnier
M2-Internet
54
Et…
String[] list = new String[]{ ".bar.com" };
CookieManager cm = new CookieManager(null,
new BlacklistPolicy(list));
CookieHandler.setDefault(cm);
H. Fauconnier
M2-Internet
55
Autre stockage
H. Fauconnier
M2-Internet
56
Servlets
H. Fauconnier
M2-Internet
57
Contenu dynamique
 Perl/cgi indépendant de la plateforme
 Extensions du serveur exemple ASP
H. Fauconnier
M2-Internet
58
Contenu dynamique…
 Un serveur transmet des pages html…
 Comment le rendre dynamique?
 CGI et variantes

Traiter des requêtes des clients: méthodes post et get:
un requête un processus
H. Fauconnier
M2-Internet
59
Contenu dynamique servlet
 Servlet: utiliser la machine virtuelle java du
serveur
H. Fauconnier
M2-Internet
60
Avec quoi utiliser les servlets?
 Serveur tomcat (java) d’apache utilise les
packages javax.servlet et
javax.servlet.http
peut s’utiliser avec un serveur apache
 De nombreux autres serveurs
 Plug-in sur des serveurs
 http://www.servlets.com
H. Fauconnier
M2-Internet
61
Servlets
 Portabilité
 Puissance (java)
 Efficacité
 Sûreté (par l’intermédiaire de la jvm)
 Extensibilité et flexibilité:
Produire du html directement ou transformer du xml
Uitlisation des JavaServer Pages (script qui génère des
servlets)
H. Fauconnier
M2-Internet
62
Servlet
 Rappel: les requêtes des clients
(essentiellement) par post ou get
 Package javax.servlet classes et interfaces
pour les servlets (indépendant du
protocole)
 Package javax.servlet.http
H. Fauconnier
M2-Internet
63
Servlet et java
 Pas de main() mais une méthode service()
 Version générique: Version http
H. Fauconnier
M2-Internet
64
Exemple basique
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Bonjour</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Bonjour à tous</BIG>");
out.println("</BODY></HTML>");
}
}
H. Fauconnier
M2-Internet
65
Et maintenant comment faire?
 Avec Apache tomcat:






Le code source de l’applet dans
server_root/webapps/ROOT/WEB-INF/classes
Compiler avec javax.servlet et javax.servlet.http dans le
« classpath » (présents dans server_root/lib/servlet.jar )
Lancer le serveur tomcat (startup.sh dans server_root/bin)
(le serveur écoute sur le port 8080 par défaut)
Le client demande l’url:
• http://localhost: 8080/servlet/HelloWorld
H. Fauconnier
M2-Internet
66
Et pour traiter des données
 Une page:
<HTML>
<HEAD>
<TITLE>Introductions</TITLE>
</HEAD>
<BODY>
<FORM METHOD=GET ACTION="/servlet/Hello">
If you don't mind me asking, what is your name?
<INPUT TYPE=TEXT NAME="name"><P>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
H. Fauconnier
M2-Internet
67
 server_root/webapps/ROOT.
 url: http://server:8080/form.html
 http://server:8080/servlet/Hello?name=Jacques+Dupont
H. Fauconnier
M2-Internet
68
Traiter la réponse
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}
public String getServletInfo() {
return "Une servlet qui sait dire bonjour à quelqu’un" ;
}
}
H. Fauconnier
M2-Internet
69
Pour les autres requêtes
 Pour POST
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
doGet(req, res);
}
 Et
<FORM METHOD=POST ACTION="/servlet/Hello">
H. Fauconnier
M2-Internet
70
Pour head
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
if (req.getMethod().equals("HEAD")) return;
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}
}
H. Fauconnier
M2-Internet
71
Web app
 Collection de servlets, de JSP, de document html, images
etc…
 Les web apps sont dans des répertoires de
server_root/webapps/ROOT
 Exemple dans le répertoire essai:
index.html
feedback.jsp
images/banner.gif
images/jumping.gif
WEB-INF/web.xml
WEB-INF/lib/bhawk4j.jar
WEB-INF/classes/MyServlet.class
WEB-INF/classes/com/mycorp/frontend/CorpServlet.class
WEB-INF/classes/com/mycorp/frontend/SupportClass.class
H. Fauconnier
M2-Internet
72
WEB-INF
 Contient les informations de configuration
de la webapp
 WEB-INF/classes contient les classes
 WEB-INF/lib les bibliothèques
 web.xml est le descripteur de déploiement
H. Fauconnier
M2-Internet
73
Web.xml
Exemple:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>
hi
</servlet-name>
<servlet-class>
HelloWorld
</servlet-class>
</servlet>
</web-app>

H. Fauconnier
M2-Internet
74
suite
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>
hi
</servlet-name>
<servlet-class>
HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
hi
</servlet-name>
<url-pattern>
/hello.html
</url-pattern>
</servlet-mapping>
</web-app>
H. Fauconnier
M2-Internet
75
Plus précisément…
H. Fauconnier
M2-Internet
76
généralités
 Une servlet reçoit une requête soit d'une
autre servlet soit d'un navigateur et
fournit une réponse vers le navigateur, soit
effectue un forward() vers une autre
servlet.
 Session: activité mise en œuvre par le
même utilisateur
 Application
: toute l'activité.

Nom + attributs
H. Fauconnier
M2-Internet
77
Classes
H. Fauconnier
M2-Internet
78
Servlet
 Package javax.servlet.http
• HttpServlet gestion des servlet pour recevoir des
requêtes et envoyer des réponses
• HttpServletRequest interface des requêtes
• HttpServletResponse interface des réponses
• HttpSession gestion de la session
• ServletContext gestion du contexte de l'application
• RequestDispatcher lancement de servlet (forward())
H. Fauconnier
M2-Internet
79
HttpServlet
 protected void doGet(HttpServletRequest req,




HttpServletResponse resp) throws
ServletException, IOException
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException
void init()
void destroy()
ServletContext getServletContext()
H. Fauconnier
M2-Internet
80
HttpServletRequest
 String getParameter(nom) valeur d'un paramètre






de formulaire
String[] getParamterValues(nom) idem pour
plusieurs valeurs
Enumeration getParameterNames() nom de tous les
paramètres du formulaire
void setAttribute(nom, objet)
Object getAttribute(nom)
Enumeration getAttributeNames()
void removeAttribute()
H. Fauconnier
M2-Internet
81
HttpServletRequest suite
 Cookie[] getCookies()
 HttpSession getSession()
 RequestDispatcher getRequestDispatcher
(path)
H. Fauconnier
M2-Internet
82
HttpServletResponse
 PrintWriter getWriter() pour obtenir où
écrire le texte
 void setContentType("text/html")
 Void addCookie(cookie)
H. Fauconnier
M2-Internet
83
RequestDispatcher
 Permet de transmettre le contrôle à une
autre servlet

forward(): le flux de sortie de la servlet est
annulé, seul le flux de sortie de la servlet
destination du forward est pris en compte
• getRequestDispatcher("index.html").forward()

Include() : inclusion dynamique du flux de la
servlet destination
H. Fauconnier
M2-Internet
84
Quelques exemples de servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
H. Fauconnier
M2-Internet
85
requete
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestInfo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Request Information Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Request Information Example</h3>");
//…
H. Fauconnier
M2-Internet
86
suite
out.println("Method: " + request.getMethod());
out.println("Request URI: " + request.getRequestURI());
out.println("Protocol: " + request.getProtocol());
out.println("PathInfo: " + request.getPathInfo());
out.println("Remote Address: " + request.getRemoteAddr());
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws IOException, ServletException
{
doGet(request, response);
}
}
H. Fauconnier
M2-Internet
87
formulaire
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestParamExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("GET Request. No Form Data Posted");
}
//…
H. Fauconnier
M2-Internet
88
Suite
public void doPost(HttpServletRequest request,
HttpServletResponse res)
throws IOException, ServletException
{
Enumeration e = request.getParameterNames();
PrintWriter out = res.getWriter ();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = request.getParameter(name);
out.println(name + " = " + value);
}
}
}
H. Fauconnier
M2-Internet
89
header
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestHeaderExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = request.getHeader(name);
out.println(name + " = " + value);
}
}
}
H. Fauconnier
M2-Internet
90
Cookies
public class CookieExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
String name = c.getName();
String value = c.getValue();
out.println(name + " = " + value);
}
String name = request.getParameter("cookieName");
if (name != null && name.length() > 0) {
String value = request.getParameter("cookieValue");
Cookie c = new Cookie(name, value);
response.addCookie(c);
}
}
}
H. Fauconnier
M2-Internet
91
Session
public class SessionExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
Date created = new Date(session.getCreationTime());
Date accessed = new Date(session.getLastAccessedTime());
out.println("ID " + session.getId());
out.println("Created: " + created);
out.println("Last Accessed: " + accessed);
String dataName = request.getParameter("dataName");
if (dataName != null && dataName.length() > 0) {
String dataValue = request.getParameter("dataValue");
session.setAttribute(dataName, dataValue);
} //…
H. Fauconnier
M2-Internet
92
Suite
// print session contents
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value =
session.getAttribute(name).toString();
out.println(name + " = " + value);
}
}
}
H. Fauconnier
M2-Internet
93
JSP
 Script pour générer des servlets
Des données statiques (HTML)
 Des directives JSP

• exemple:
<jsp:directive.include file="unAutreFichier" />

Eléments de script
• exemple:
<%! int variableDeClasse = 0; %>

Actions JSP
• Exemple:
<jsp:useBean id="nomDeBean" class="package.Bean"
scope="request" />
H. Fauconnier
M2-Internet
94
Un exemple (netbeans)
 index.jsp un formulaire simple
 reponse.jsp la réponse
 La javabean pour le traitement:
TraiteNom.java
H. Fauconnier
M2-Internet
95
Remarque…
 Netbeans ou eclipse permettent de gérer
les servlets et les jsp aisément…
H. Fauconnier
M2-Internet
96
Chapter 8
Network Security
A note on the use of these ppt slides:
We’re making these slides freely available to all (faculty, students, readers).
They’re in PowerPoint form so you can add, modify, and delete slides
(including this one) and slide content to suit your needs. They obviously
represent a lot of work on our part. In return for use, we only ask the
following:
 If you use these slides (e.g., in a class) in substantially unaltered form,
that you mention their source (after all, we’d like people to use our book!)
 If you post any slides in substantially unaltered form on a www site, that
you note that they are adapted from (or perhaps identical to) our slides, and
note our copyright of this material.
Thanks and enjoy! JFK/KWR
Computer Networking:
A Top Down Approach
Featuring the Internet,
3rd edition.
Jim Kurose, Keith Ross
Addison-Wesley, July
2004.
All material copyright 1996-2004
J.F Kurose and K.W. Ross, All Rights Reserved
H. Fauconnier
M2-Internet
8-97
Chapter 8: Network Security
Chapter goals:
 understand principles of network security:
cryptography and its many uses beyond
“confidentiality”
 authentication
 message integrity
 key distribution

 security in practice:
 firewalls
 security in application, transport, network, link
layers
H. Fauconnier
M2-Internet
8-98
Chapter 8 roadmap
8.1 What is network security?
8.2 Principles of cryptography
8.3 Authentication
8.4 Integrity
8.5 Key Distribution and certification
8.6 Access control: firewalls
8.7 Attacks and counter measures
8.8 Security in many layers
H. Fauconnier
M2-Internet
8-99
What is network security?
Confidentiality: only sender, intended receiver
should “understand” message contents
 sender encrypts message
 receiver decrypts message
Authentication: sender, receiver want to confirm
identity of each other
Message Integrity: sender, receiver want to ensure
message not altered (in transit, or afterwards)
without detection
Access and Availability: services must be accessible
and available to users
H. Fauconnier
M2-Internet
8-
Friends and enemies: Alice, Bob, Trudy
 well-known in network security world
 Bob, Alice (lovers!) want to communicate “securely”
 Trudy (intruder) may intercept, delete, add messages
Alice
Bob
channel data, control
messages
data
secure
sender
secure
receiver
data
Trudy
H. Fauconnier
M2-Internet
8-
Who might Bob, Alice be?
 … well, real-life Bobs and Alices!
 Web browser/server for electronic
transactions (e.g., on-line purchases)
 on-line banking client/server
 DNS servers
 routers exchanging routing table updates
 other examples?
H. Fauconnier
M2-Internet
8-
There are bad guys (and girls) out there!
Q: What can a “bad guy” do?
A: a lot!
eavesdrop: intercept messages
 actively insert messages into connection
 impersonation: can fake (spoof) source address
in packet (or any field in packet)
 hijacking: “take over” ongoing connection by
removing sender or receiver, inserting himself
in place
 denial of service: prevent service from being
used by others (e.g., by overloading resources)

more on this later ……
H. Fauconnier
M2-Internet
8-
Chapter 8 roadmap
8.1 What is network security?
8.2 Principles of cryptography
8.3 Authentication
8.4 Integrity
8.5 Key Distribution and certification
8.6 Access control: firewalls
8.7 Attacks and counter measures
8.8 Security in many layers
H. Fauconnier
M2-Internet
8-
The language of cryptography
Alice’s
K encryption
A
key
plaintext
encryption
algorithm
Bob’s
K decryption
B key
ciphertext
decryption plaintext
algorithm
symmetric key crypto: sender, receiver keys identical
public-key crypto: encryption key public, decryption key
secret (private)
H. Fauconnier
M2-Internet
8-
Symmetric key cryptography
substitution cipher: substituting one thing for another

monoalphabetic cipher: substitute one letter for another
plaintext:
abcdefghijklmnopqrstuvwxyz
ciphertext:
mnbvcxzasdfghjklpoiuytrewq
E.g.:
Plaintext: bob. i love you. alice
ciphertext: nkn. s gktc wky. mgsbc
Q: How hard to break this simple cipher?:
 brute force (how hard?)
 other?
H. Fauconnier
M2-Internet
8-
Symmetric key cryptography
KA-B
KA-B
plaintext
message, m
encryption ciphertext
algorithm
K (m)
A-B
decryption plaintext
algorithm
m = K ( KA-B(m) )
A-B
symmetric key crypto: Bob and Alice share know same
(symmetric) key: K
A-B
 e.g., key is knowing substitution pattern in mono
alphabetic substitution cipher
 Q: how do Bob and Alice agree on key value?
H. Fauconnier
M2-Internet
8-
Symmetric key crypto: DES
DES: Data Encryption Standard
 US encryption standard [NIST 1993]
 56-bit symmetric key, 64-bit plaintext input
 How secure is DES?
DES Challenge: 56-bit-key-encrypted phrase
(“Strong cryptography makes the world a safer
place”) decrypted (brute force) in 4 months
 no known “backdoor” decryption approach
 making DES more secure:
 use three keys sequentially (3-DES) on each datum
 use cipher-block chaining

H. Fauconnier
M2-Internet
8-
Symmetric key
crypto: DES
DES operation
initial permutation
16 identical “rounds” of
function application,
each using different
48 bits of key
final permutation
H. Fauconnier
M2-Internet
8-
AES: Advanced Encryption Standard
 new (Nov. 2001) symmetric-key NIST
standard, replacing DES
 processes data in 128 bit blocks
 128, 192, or 256 bit keys
 brute force decryption (try each key)
taking 1 sec on DES, takes 149 trillion
years for AES
H. Fauconnier
M2-Internet
8-
Public Key Cryptography
symmetric key crypto
 requires sender,
receiver know shared
secret key
 Q: how to agree on key
in first place
(particularly if never
“met”)?
H. Fauconnier
public key cryptography
 radically different
approach [DiffieHellman76, RSA78]
 sender, receiver do
not share secret key
 public encryption key
known to all
 private decryption
key known only to
receiver
M2-Internet
8-
Public key cryptography
+ Bob’s public
B key
K
K
plaintext
message, m
H. Fauconnier
encryption ciphertext
algorithm
+
K (m)
B
- Bob’s private
B key
decryption plaintext
algorithm message
+
m = K B(K (m))
B
M2-Internet
8-
Public key encryption algorithms
Requirements:
1
2
+
need K ( ) and K - ( ) such that
B
B
- +
K (K (m)) = m
B B
.
.
+
given public key KB , it should be
impossible to compute
private key KB
RSA: Rivest, Shamir, Adelson algorithm
H. Fauconnier
M2-Internet
8-
RSA: Choosing keys
1. Choose two large prime numbers p, q.
(e.g., 1024 bits each)
2. Compute n = pq, z = (p-1)(q-1)
3. Choose e (with e<n) that has no common factors
with z. (e, z are “relatively prime”).
4. Choose d such that ed-1 is exactly divisible by z.
(in other words: ed mod z = 1 ).
5. Public key is (n,e). Private key is (n,d).
+
KB
H. Fauconnier
-
KB
M2-Internet
8-
RSA: Encryption, decryption
0. Given (n,e) and (n,d) as computed above
1. To encrypt bit pattern, m, compute
e
e
c = m mod n (i.e., remainder when m is divided by n)
2. To decrypt received bit pattern, c, compute
d
m = c dmod n (i.e., remainder when c is divided by n)
Magic
d
m = (m e mod n) mod n
happens!
c
H. Fauconnier
M2-Internet
8-
RSA example:
Bob chooses p=5, q=7. Then n=35, z=24.
e=5 (so e, z relatively prime).
d=29 (so ed-1 exactly divisible by z.
encrypt:
decrypt:
H. Fauconnier
letter
m
me
l
12
1524832
c
17
d
c
481968572106750915091411825223071697
c = me mod n
17
m = cd mod n letter
12
l
M2-Internet
8-
RSA: Why is that
m = (m e mod n)
d
mod n
Useful number theory result: If p,q prime and
n = pq, then:
y
y mod (p-1)(q-1)
x mod n = x
mod n
e
(m mod n) d mod n = medmod n
= m
ed mod (p-1)(q-1)
mod n
(using number theory result above)
1
= m mod n
(since we chose ed to be divisible by
(p-1)(q-1) with remainder 1 )
= m
H. Fauconnier
M2-Internet
8-
RSA: another important property
The following property will be very useful later:
-
+
B
B
K (K (m))
+ = m = K (K (m))
B B
use public key
first, followed
by private key
use private key
first, followed
by public key
Result is the same!
H. Fauconnier
M2-Internet
8-
Chapter 8 roadmap
8.1 What is network security?
8.2 Principles of cryptography
8.3 Authentication
8.4 Integrity
8.5 Key Distribution and certification
8.6 Access control: firewalls
8.7 Attacks and counter measures
8.8 Security in many layers
H. Fauconnier
M2-Internet
8-
Authentication
Goal: Bob wants Alice to “prove” her identity
to him
Protocol ap1.0: Alice says “I am Alice”
“I am Alice”
H. Fauconnier
Failure scenario??
M2-Internet
8-
Authentication
Goal: Bob wants Alice to “prove” her identity
to him
Protocol ap1.0: Alice says “I am Alice”
“I am Alice”
H. Fauconnier
in a network,
Bob can not “see”
Alice, so Trudy simply
declares
herself to be Alice
M2-Internet
8-
Authentication: another try
Protocol ap2.0: Alice says “I am Alice” in an IP packet
containing her source IP address
Alice’s
“I am Alice”
IP address
Failure scenario??
H. Fauconnier
M2-Internet
8-
Authentication: another try
Protocol ap2.0: Alice says “I am Alice” in an IP packet
containing her source IP address
Alice’s
IP address
H. Fauconnier
Trudy can create
a packet
“spoofing”
“I am Alice” Alice’s address
M2-Internet
8-
Authentication: another try
Protocol ap3.0: Alice says “I am Alice” and sends her
secret password to “prove” it.
Alice’s Alice’s
“I’m Alice”
IP addr password
Alice’s
IP addr
H. Fauconnier
OK
Failure scenario??
M2-Internet
8-
Authentication: another try
Protocol ap3.0: Alice says “I am Alice” and sends her
secret password to “prove” it.
Alice’s Alice’s
“I’m Alice”
IP addr password
Alice’s
IP addr
OK
playback attack: Trudy
records Alice’s packet
and later
plays it back to Bob
Alice’s Alice’s
“I’m Alice”
IP addr password
H. Fauconnier
M2-Internet
8-
Authentication: yet another try
Protocol ap3.1: Alice says “I am Alice” and sends her
encrypted secret password to “prove” it.
Alice’s encrypted
“I’m Alice”
IP addr password
Alice’s
IP addr
H. Fauconnier
OK
Failure scenario??
M2-Internet
8-
Authentication: another try
Protocol ap3.1: Alice says “I am Alice” and sends her
encrypted secret password to “prove” it.
Alice’s encrypted
“I’m Alice”
IP addr password
Alice’s
IP addr
OK
record
and
playback
still works!
Alice’s encrypted
“I’m Alice”
IP addr password
H. Fauconnier
M2-Internet
8-
Authentication: yet another try
Goal: avoid playback attack
Nonce: number (R) used only once –in-a-lifetime
ap4.0: to prove Alice “live”, Bob sends Alice nonce, R. Alice
must return R, encrypted with shared secret key
“I am Alice”
R
KA-B(R)
Failures, drawbacks?
H. Fauconnier
Alice is live, and
only Alice knows
key to encrypt
nonce, so it must
be Alice!
M2-Internet
8-
Authentication: ap5.0
ap4.0 requires shared symmetric key
 can we authenticate using public key techniques?
ap5.0: use nonce, public key cryptography
“I am Alice”
R
Bob computes
+ -
-
K A (R)
“send me your public key”
+
KA
H. Fauconnier
KA(KA (R)) = R
and knows only Alice
could have the private
key, that encrypted R
such that
+ K (K (R)) = R
A A
M2-Internet
8-
ap5.0: security hole
Man (woman) in the middle attack: Trudy poses as
Alice (to Bob) and as Bob (to Alice)
I am Alice
R
I am Alice
R
K (R)
T
K (R)
A
Send me your public key
+
K
T
Send me your public key
+
K
A
- +
m = K (K (m))
A A
H. Fauconnier
+
K (m)
A
Trudy gets
- +
m = K (K (m))
sends T
m toTAlice
+
K (m)
T
encrypted with
Alice’s public key
M2-Internet
8-
ap5.0: security hole
Man (woman) in the middle attack: Trudy poses as
Alice (to Bob) and as Bob (to Alice)
Difficult to detect:
 Bob receives everything that Alice sends, and vice
versa. (e.g., so Bob, Alice can meet one week later and
recall conversation)
 problem is that Trudy receives all messages as well!
H. Fauconnier
M2-Internet
8-
Chapter 8 roadmap
8.1 What is network security?
8.2 Principles of cryptography
8.3 Authentication
8.4 Message integrity
8.5 Key Distribution and certification
8.6 Access control: firewalls
8.7 Attacks and counter measures
8.8 Security in many layers
H. Fauconnier
M2-Internet
8-
Digital Signatures
Cryptographic technique analogous to handwritten signatures.
 sender (Bob) digitally signs document,
establishing he is document owner/creator.
 verifiable, nonforgeable: recipient (Alice) can
prove to someone that Bob, and no one else
(including Alice), must have signed document
H. Fauconnier
M2-Internet
8-
Digital Signatures
Simple digital signature for message m:
 Bob signs m by encrypting with his private key
-
KB, creating “signed” message, KB(m)
Bob’s message, m
Dear Alice
Oh, how I have missed
you. I think of you all the
time! …(blah blah blah)
Bob
H. Fauconnier
K B Bob’s private
key
Public key
encryption
algorithm
-
K B(m)
Bob’s message,
m, signed
(encrypted) with
his private key
M2-Internet
8-
Digital Signatures (more)
-
 Suppose Alice receives msg m, digital signature KB(m)
 Alice verifies m signed by Bob by applying Bob’s
+
-
+
-
public key KB to KB(m) then checks KB(KB(m) ) = m.
+
-
 If KB(KB(m) ) = m, whoever signed m must have used
Bob’s private key.
Alice thus verifies that:
 Bob signed m.
 No one else signed m.
 Bob signed m and not m’.
Non-repudiation:
 Alice can take m, and signature KB(m) to
court and prove that Bob signed m.
H. Fauconnier
M2-Internet
8-
Message Digests
Computationally expensive
to public-key-encrypt
long messages
Goal: fixed-length, easyto-compute digital
“fingerprint”
 apply hash function H
to m, get fixed size
message digest, H(m).
H. Fauconnier
large
message
m
H: Hash
Function
H(m)
Hash function properties:
 many-to-1
 produces fixed-size msg
digest (fingerprint)
 given message digest x,
computationally
infeasible to find m such
that x = H(m)
M2-Internet
8-
Internet checksum: poor crypto hash
function
Internet checksum has some properties of hash function:
 produces fixed length digest (16-bit sum) of message
 is many-to-one
But given message with given hash value, it is easy to find
another message with same hash value:
message
I O U 1
0 0 . 9
9 B O B
ASCII format
49 4F 55 31
30 30 2E 39
39 42 D2 42
B2 C1 D2 AC
H. Fauconnier
message
I O U 9
0 0 . 1
9 B O B
ASCII format
49 4F 55 39
30 30 2E 31
39 42 D2 42
B2 C1 D2 AC
different messages
but identical checksums!
M2-Internet
8-
Digital signature = signed message digest
Alice verifies signature and
integrity of digitally signed
message:
Bob sends digitally signed
message:
large
message
m
H: Hash
function
Bob’s
private
key
+
-
KB
encrypted
msg digest
H(m)
digital
signature
(encrypt)
encrypted
msg digest
KB(H(m))
large
message
m
H: Hash
function
KB(H(m))
Bob’s
public
key
+
KB
digital
signature
(decrypt)
H(m)
H(m)
equal
?
H. Fauconnier
M2-Internet
8-
Hash Function Algorithms
 MD5 hash function widely used (RFC 1321)
computes 128-bit message digest in 4-step
process.
 arbitrary 128-bit string x, appears difficult to
construct msg m whose MD5 hash is equal to x.
 SHA-1 is also used.
 US standard [NIST, FIPS PUB 180-1]
 160-bit message digest

H. Fauconnier
M2-Internet
8-
Chapter 8 roadmap
8.1 What is network security?
8.2 Principles of cryptography
8.3 Authentication
8.4 Integrity
8.5 Key distribution and certification
8.6 Access control: firewalls
8.7 Attacks and counter measures
8.8 Security in many layers
H. Fauconnier
M2-Internet
8-
Trusted Intermediaries
Symmetric key problem:
Public key problem:
 How do two entities
 When Alice obtains
establish shared secret
key over network?
Solution:
 trusted key distribution
center (KDC) acting as
intermediary between
entities
H. Fauconnier
Bob’s public key (from
web site, e-mail,
diskette), how does she
know it is Bob’s public
key, not Trudy’s?
Solution:
 trusted certification
authority (CA)
M2-Internet
8-
Key Distribution Center (KDC)
 Alice, Bob need shared symmetric key.
 KDC: server shares different secret key with each
registered user (many users)
 Alice, Bob know own symmetric keys, KA-KDC KB-KDC , for
communicating with KDC.
KDC
KA-KDCKP-KDC
KP-KDC
KB-KDC
KA-KDC
H. Fauconnier
KX-KDC
KY-KDC
KB-KDC
KZ-KDC
M2-Internet
8-
Key Distribution Center (KDC)
Q: How does KDC allow Bob, Alice to determine shared
symmetric secret key to communicate with each other?
KDC
generates
R1
KA-KDC(A,B)
Alice
knows
R1
KA-KDC(R1, KB-KDC(A,R1) )
KB-KDC(A,R1)
Bob knows to
use R1 to
communicate
with Alice
Alice and Bob communicate: using R1 as
session key for shared symmetric encryption
H. Fauconnier
M2-Internet
8-
Certification Authorities
 Certification authority (CA): binds public key to
particular entity, E.
 E (person, router) registers its public key with CA.



E provides “proof of identity” to CA.
CA creates certificate binding E to its public key.
certificate containing E’s public key digitally signed by CA
– CA says “this is E’s public key”
Bob’s
public
key
Bob’s
identifying
information
H. Fauconnier
+
KB
digital
signature
(encrypt)
CA
private
key
K-
CA
+
KB
certificate for
Bob’s public key,
signed by CA
M2-Internet
8-
Certification Authorities
 When Alice wants Bob’s public key:
gets Bob’s certificate (Bob or elsewhere).
 apply CA’s public key to Bob’s certificate, get
Bob’s public key

+
KB
digital
signature
(decrypt)
CA
public
key
H. Fauconnier
Bob’s
public
+
key
KB
+
K CA
M2-Internet
8-
Téléchargement