diff --git a/documentation/content/de/books/handbook/advanced-networking/_index.adoc b/documentation/content/de/books/handbook/advanced-networking/_index.adoc index d9a4550430..c9d530b68b 100644 --- a/documentation/content/de/books/handbook/advanced-networking/_index.adoc +++ b/documentation/content/de/books/handbook/advanced-networking/_index.adoc @@ -1,2833 +1,2833 @@ --- title: Kapitel 31. Weiterführende Netzwerkthemen part: Teil IV. Netzwerke prev: books/handbook/firewalls next: books/handbook/partv showBookMenu: true weight: 36 path: "/books/handbook/" --- [[advanced-networking]] = Weiterführende Netzwerkthemen :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 31 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/advanced-networking/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[advanced-networking-synopsis]] == Übersicht Dieses Kapitel beschreibt verschiedene weiterführende Netzwerkthemen. Nachdem Sie dieses Kapitel gelesen haben, werden Sie * Die Grundlagen von Gateways und Routen kennen. * Wissen, wie man USB Tethering einrichtet. * Bluetooth(R)- sowie drahtlose, der Norm IEEE(R) 802.11 entsprechende, Geräte mit FreeBSD verwenden können. * Eine Bridge unter FreeBSD einrichten können. * Wissen, wie man mithilfe von PXE über ein Netzwerk von einem NFS Root-Dateisystem bootet. * IPv6 auf einem FreeBSD-Rechner einrichten können. * Das Common Address Redundancy Protocol (CARP) unter FreeBSD einsetzen können. * Wissen, wie VLANs unter FreeBSD konfiguriert werden. * Wissen, wie Bluetooth-Kopfhörer konfiguriert werden. Bevor Sie dieses Kapitel lesen, sollten Sie * Die Grundlagen der [.filename]#/etc/rc#-Skripte verstanden haben. * Mit der grundlegenden Netzwerkterminologie vertraut sein. * Einen neuen FreeBSD-Kernel konfigurieren und installieren können (crossref:kernelconfig[kernelconfig,Konfiguration des FreeBSD-Kernels]). * Wissen, wie man zusätzliche Software von Drittherstellern installiert (crossref:ports[ports,Installieren von Anwendungen: Pakete und Ports]). [[network-routing]] == Gateways und Routen Der Mechanismus mit dem ein Rechner einen Rechner über ein Netzwerk finden kann, wird als _Routing_ bezeichnet. Eine "Route" besteht aus einem definierten Adresspaar: Einem "Ziel" und einem "Gateway". Die Route zeigt an, dass Pakete über das _Gateway_ zum _Ziel_ gelangen können. Es gibt drei Arten von Zielen: Einzelne Rechner (Hosts), Subnetze und das "Standard"ziel. Die "Standardroute" wird verwendet, wenn keine andere Route zutrifft. Außerdem gibt es drei Arten von Gateways: Einzelne Rechner (Hosts), Schnittstellen (Interfaces, auch als "Links" bezeichnet), sowie Ethernet Hardware-Adressen (MAC). Bekannte Adressen werden in einer Routingtabelle gespeichert. Dieser Abschnitt bietet einen Überblick über die Grundlagen des Routings. Er demonstriert, wie ein FreeBSD-System als Router konfiguriert werden kann und bietet einige Tipps zur Fehlerbehebung. [[network-routing-default]] === Grundlagen des Routings man:netstat[1] zeigt die Routingtabellen eines FreeBSD-Systems an: [source,shell] .... % netstat -r Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default outside-gw UGS 37 418 em0 localhost localhost UH 0 181 lo0 test0 0:e0:b5:36:cf:4f UHLW 5 63288 re0 77 10.20.30.255 link#1 UHLW 1 2421 example.com link#1 UC 0 0 host1 0:e0:a8:37:8:1e UHLW 3 4601 lo0 host2 0:e0:a8:37:8:1e UHLW 0 5 lo0 => host2.example.com link#1 UC 0 0 224 link#1 UC 0 0 .... Die Einträge in diesem Beispiel sind wie folgt: default:: Die erste Route in der Ausgabe gibt die Standardroute (`default`) an. Wenn sich der lokale Rechner mit einem entfernten Rechner verbinden will, wird die Routingtabelle überprüft, um festzustellen, ob bereits ein bekannter Pfad vorhanden ist. Wird für den entfernten Rechner ein Eintrag in der Routingtabelle gefunden, so prüft das System ob es sich über die angegebene Schnittstelle verbinden kann. + Wenn das Zielsystem mit keinem Eintrag übereinstimmt, oder wenn alle bekannten Routen fehlschlagen, verwendet das System die Standardroute. Für die Rechner im lokalen Netzwerk ist das Feld `Gateway` auf das System gesetzt, welches direkt mit dem Internet verbunden ist. `UG` in der Spalte `Flags` zeigt an, dass das Gateway einsatzbereit ist. + Die Standardroute für einen Rechner, der selbst als Gateway zur Außenwelt fungiert, ist der Gateway-Rechner des Internetanbieters (ISP). localhost:: Die zweite Route zeigt die `localhost` Route. Die festgelegte Schnittstelle in der `Netif`-Spalte für `localhost` ist `lo0`, das auch als loopback-Gerät bekannt ist. Das bedeutet, dass der gesamte Datenverkehr für dieses Ziel intern bleibt, anstatt ihn über ein Netzwerk zu versenden. MAC-Adresse:: Bei den mit `0:e0:` beginnenden Adressen handelt es sich um MAC-Adressen. FreeBSD identifiziert Rechner im lokalen Netz, im Beispiel `test0`, automatisch und fügt eine direkte Route über die Ethernet-Schnittstelle [.filename]#re0# zu diesem Rechner hinzu. Außerdem existiert in der Spalte `Expire` ein Timeout, der verwendet wird, wenn dieser Rechner in einem definierten Zeitraum nicht reagiert. Wenn dies passiert, wird die Route zu diesem Rechner automatisch gelöscht. Rechner im lokalen Netz werden über das Routing Information Protocol (RIP) identifiziert, welches den kürzesten Weg zu den jeweiligen Rechnern berechnet. Subnetz:: FreeBSD wird automatisch Subnetzrouten für das lokale Subnetz hinzufügen. In diesem Beispiel ist `10.20.30.255` die Broadcast-Adresse für das Subnetz `10.20.30`, und `example.com` ist der zu diesem Subnetz gehörige Domainname. Das Ziel `link#1` bezieht sich auf die erste Ethernet-Karte im Rechner. + Routen für Rechner im lokalen Netz und lokale Subnetze werden automatisch durch den man:routed[8] Daemon konfiguriert. Ist dieser nicht gestartet, existieren nur statische Routen, die vom Administrator definiert werden. Host:: Die Zeile `host1` bezieht sich auf den Rechner, der durch seine Ethernetadresse bekannt ist. Da es sich um den sendenden Rechner handelt, verwendet FreeBSD automatisch das Loopback-Gerät ([.filename]#lo0#), anstatt den Datenverkehr über die Ethernet-Schnittstelle zu senden. + Die zwei `host2` Zeilen repräsentieren Aliase, die mit man:ifconfig[8] erstellt wurden. Das Symbol `=>` nach der [.filename]#lo0#-Schnittstelle sagt aus, dass zusätzlich zur Loopback-Adresse auch ein Alias eingestellt ist. Solche Routen sind nur auf Rechnern vorhanden, die den Alias bereitstellen. Alle anderen Rechner im lokalen Netz haben für solche Routen nur eine `link#1` Zeile. 224:: Die letzte Zeile (Zielsubnetz `224`) behandelt Multicasting. Schließlich gibt es für Routen noch verschiedene Attribute, die sich in der Spalte `Flags` befinden. <> fasst einige dieser Flags und deren Bedeutung zusammen: [[routeflags]] .Allgemeine Attribute in Routingtabellen [cols="1,1", frame="none", options="header"] |=== | Attribut | Bedeutung |U |Die Route ist aktiv (up). |H |Das Ziel der Route ist ein einzelner Rechner (Host). |G |Alle Daten, die an dieses Ziel gesendet werden, werden von dem Gateway an ihr jeweiliges Ziel weitergeleitet. |S |Diese Route wurde statisch konfiguriert. |C |Erzeugt eine neue Route, basierend auf der Route für den Rechner, mit dem wir uns verbinden. Diese Routenart wird normalerweise für lokale Netzwerke verwendet. |W |Eine Route, die automatisch konfiguriert wurde. Sie basiert auf einer lokalen Netzwerkroute (Clone). |L |Die Route beinhaltet einen Verweis auf eine Ethernetkarte (Link). |=== In FreeBSD kann die Standardroute durch die Angabe der IP-Adresse des Standard-Gateways in [.filename]#/etc/rc.conf# definiert werden: [.programlisting] .... defaultrouter="10.20.30.1" .... Die Standardroute kann mit `route` auch manuell gesetzt werden: [source,shell] .... # route add default 10.20.30.1 .... Beachten Sie, dass manuell hinzugefügte Routen bei einem Neustart des Systems verloren gehen. Weitere Informationen zum Bearbeiten von Netzwerk-Routingtabellen finden Sie in man:route[8]. [[network-static-routes]] === Statische Routen einrichten Ein FreeBSD-System kann als Standard-Gateway bzw. Router für ein Netzwerk konfiguriert werden, wenn es sich um einen Dual-Homed-Host handelt. Ein Dual-Homed-Host ist ein Rechner, der sich in mindestens zwei verschiedenen Netzwerken befindet. Typischerweise ist jedes Netzwerk über eine separate Netzwerkschnittstelle verbunden. Mit IP Aliasing können mehrere Adressen, die jeweils zu einem andren Subnetz gehören, an eine physikalische Schnittstelle gebunden werden. Damit Pakete zwischen den Schnittstellen weitergeleitet werden können, muss das FreeBSD-System als Router konfiguriert werden. Internetstandards und gute Ingenieurspraxis sorgten dafür, dass diese Funktion in FreeBSD in der Voreinstellung deaktiviert ist. Sie kann jedoch aktiviert werden, indem folgende Zeile in [.filename]#/etc/rc.conf# hinzugefügt wird: [.programlisting] .... gateway_enable="YES" # Auf YES setzen, wenn der Rechner als Gateway arbeiten soll .... Um das Routing zu aktivieren, setzen Sie die man:sysctl[8]-Variable `net.inet.ip.forwarding` auf `1`. Um das Routing zu stoppen, muss die Variable wieder auf `0` gesetzt werden. Die Routingtabelle eines Routers benötigt zusätzliche Routen, damit er weiß, wie er andere Netzwerke erreichen kann. Die Routen können entweder manuell als statische Routen hinzugefügt werden, oder aber der Router lernt automatisch die Routen anhand des Routing-Protokolls. Statische Routen eignen sich für kleine Netzwerke und dieser Abschnitt beschreibt, wie Sie eine statische Route für ein kleines Netzwerk hinzufügen. [NOTE] ==== In großen Netzwerken sind statische Routen schlecht skalierbar. FreeBSD beinhaltet den BSD-Routing-Daemon man:routed[8], der die Protokolle RIP (Version 1 und Version 2) sowie IRDP unterstützt. Die Routing-Protokolle BGP und OSPF können über den Port oder das Paket package:net/zebra[] installiert werden. ==== Nehmen wir an, dass wir über folgendes Netzwerk verfügen: image::static-routes.png[] `RouterA`, ein FreeBSD-Rechner, dient als Router für den Zugriff auf das Internet. Die Standardroute ist auf `10.0.0.1` gesetzt, damit ein Zugriff auf das Internet möglich wird. `RouterB` ist bereits konfiguriert, da er `192.168.1.1` als Standard-Gateway benutzt. Bevor die statischen Routen hinzugefügt werden, sieht die Routingtabelle auf `RouterA` in etwa so aus: [source,shell] .... % netstat -nr Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default 10.0.0.1 UGS 0 49378 xl0 127.0.0.1 127.0.0.1 UH 0 6 lo0 10.0.0/24 link#1 UC 0 0 xl0 192.168.1/24 link#2 UC 0 0 xl1 .... Mit dieser Routingtabelle hat `RouterA` keine Route zum Netzwerk `192.168.2.0/24`. Der folgende Befehl wird das interne Netz 2 in die Routingtabelle von `RouterA` aufnehmen und dabei `192.168.1.2` als nächsten Zwischenschritt (Hop) verwenden: [source,shell] .... # route add -net 192.168.2.0/24 192.168.1.2 .... Ab sofort kann `RouterA` alle Rechner des Netzwerks `192.168.2.0/24` erreichen. Allerdings gehen die Routing-Informationen verloren, wenn das FreeBSD-System neu gestartet wird. Um statische Routen dauerhaft einzurichten, müssen diese in [.filename]#/etc/rc.conf# eingetragen werden: [.programlisting] .... # Add Internal Net 2 as a persistent static route static_routes="internalnet2" route_internalnet2="-net 192.168.2.0/24 192.168.1.2" .... Die Variable `static_routes` enthält eine Reihe von Strings, die durch Leerzeichen getrennt sind. Jeder String bezieht sich auf den Namen einer Route. Die Variable `route__internalnet2_` enthält die statische Route. Wird mit der Variablen `static_routes` mehr als eine Variable angegeben, so werden auch mehrere Routen angelegt. Im folgenden Beispiel werden statische Routen zu den Netzwerken `192.168.0.0/24` und `192.168.1.0/24` angelegt. [.programlisting] .... static_routes="net1 net2" route_net1="-net 192.168.0.0/24 192.168.0.1" route_net2="-net 192.168.1.0/24 192.168.1.1" .... [[network-routing-troubleshooting]] === Problembehandlung Wenn ein Adressraum einem Netzwerk zugeordnet wird, konfiguriert der Dienstanbieter seine Routing-Tabellen, so dass der gesamte Verkehr für das Netzwerk über die Verbindung zu der Seite gesendet wird. Aber woher wissen externe Webseiten, dass sie die Daten an das Netzwerk des ISP senden sollen? Es gibt ein System, das alle zugewiesenen Adressräume verwaltet und die Verbindung zum Internet-Backbone definiert. Der "Backbone" ist das Netz aus Hauptverbindungen, die den Internetverkehr in der ganzen Welt transportieren und verteilen. Jeder Backbone-Rechner verfügt über eine Kopie von Master-Tabellen, die den Verkehr für ein bestimmtes Netzwerk hierarchisch vom Backbone über eine Kette von Dienstanbietern bis hin zu einem bestimmten Netzwerk leiten. Es ist die Aufgabe des Dienstanbieters, den Backbone-Seiten mitzuteilen, dass sie mit einer Seite verbunden wurden. Dieser Vorgang wird als _Bekanntmachung von Routen_ (routing propagation) bezeichnet. Manchmal kommt es zu Problemen bei der Bekanntmachung von Routen, und einige Seiten sind nicht in der Lage, sich zu verbinden. Der vielleicht nützlichste Befehl, um festzustellen wo das Routing nicht funktioniert, ist `traceroute`. Das Programm ist nützlich, falls `ping` fehlschlägt. Rufen Sie `traceroute` mit dem Namen des entfernten Rechners auf, mit dem eine Verbindung aufgebaut werden soll. Die Ausgabe zeigt die Gateway-Rechner entlang des Verbindungspfades an. Schließlich wird der Zielrechner erreicht oder es kommt zu einem Verbindungsabbruch. Weitere Informationen finden Sie in man:traceroute[8]. [[network-routing-multicast]] === Multicast-Routing FreeBSD unterstützt sowohl Multicast-Anwendungen als auch Multicast-Routing. Multicast-Anwendungen benötigen keine spezielle Konfiguration, um auf FreeBSD lauffähig zu sein. Damit Multicast-Routing unterstützt wird, muss die folgende Option in der Kernelkonfiguration aktiviert werden: [.programlisting] .... options MROUTING .... Der Multicast-Routing-Daemon mrouted kann als Port oder Paket package:net/mroute[] installiert werden. Dieser Daemon implementiert das DVMRP Multicast-Routing-Protokoll. Um die Tunnel und DVMRP einzurichten, muss [.filename]#/usr/local/etc/mrouted.conf# bearbeitet werden. Bei der Installation von mrouted wird auch map-mbone und mrinfo sowie die zugehörigen Manualpages installiert, in denen Sie auch Konfigurationsbeispiele finden können. [NOTE] ==== DVMRP wurde in vielen Multicast-Installationen weitgehend durch das PIM-Protokoll ersetzt. Weitere Informationen finden Sie in man:pim[4]. ==== [[network-wireless]] == Drahtlose Netzwerke === Grundlagen Die meisten drahtlosen Netzwerke basieren auf dem Standard IEEE(R) 802.11. Ein einfaches drahtloses Netzwerk besteht aus Stationen, die im 2,4 GHz- oder im 5 GHz-Band miteinander kommunizieren. Es ist aber auch möglich, dass regional andere Frequenzen, beispielsweise im 2,3 GHz- oder 4,9 GHz-Band, verwendet werden. 802.11-Netzwerke können auf zwei verschiedene Arten aufgebaut sein: Im _Infrastruktur-Modus_ agiert eine Station als Master, mit dem sich alle anderen Stationen verbinden. Die Summe aller Stationen wird als Basic Service Set (BSS), die Master-Station hingegen als Access Point (AP) bezeichnet. In einem BSS läuft jedwede Kommunikation über den Access Point. Die zweite Form drahtloser Netzwerke sind die sogenannten _Ad-hoc-Netzwerke_ (auch als IBSS bezeichnet), in denen es keinen Access Point gibt und in denen die Stationen direkt miteinander kommunizieren. Die ersten 802.11-Netzwerke arbeiteten im 2,4 GHz-Band und nutzten dazu Protokolle der IEEE(R)-Standards 802.11 sowie 802.11b. Diese Standards legen unter anderem Betriebsfrequenzen sowie Merkmale des MAC-Layers (wie Frames und Transmissionsraten) fest. Später kam der Standard 802.11a hinzu, der im 5 GHz-Band, im Gegensatz zu den ersten beiden Standards aber mit unterschiedlichen Signalmechanismen und höheren Transmissionsraten arbeitet. Der neueste Standard 802.11g implementiert die Signal- und Transmissionsmechanismen von 802.11a im 2,4 GHz-Band, ist dabei aber abwärtskompatibel zu 802.11b-Netzwerken. Unabhängig von den zugrundeliegenden Transportmechanismen verfügen 802.11-Netzwerke über diverse Sicherheitsmechanismen. Der ursprüngliche 802.11-Standard definierte lediglich ein einfaches Sicherheitsprotokoll namens WEP. Dieses Protokoll verwendet einen fixen, gemeinsam verwendeten Schlüssel sowie die RC4-Kryptografie-Chiffre, um Daten verschlüsselt über das drahtlose Netzwerk zu senden. Alle Stationen des Netzwerks müssen sich auf den gleichen fixen Schlüssel einigen, um miteinander kommunizieren zu können. Dieses Schema ist sehr leicht zu knacken und wird deshalb heute kaum mehr eingesetzt. Aktuelle Sicherheitsmechanismen bauen auf dem Standard IEEE(R) 802.11i auf, der neue kryptographische Schlüssel (Chiffren), ein neues Protokoll für die Anmeldung von Stationen an einem Access Point, sowie Mechanismen zum Austausch von Schlüsseln als Vorbereitung der Kommunikation zwischen verschiedenen Geräten festlegt. Kryptografische Schlüssel werden in regelmäßigen Abständen aktualisiert. Außerdem gibt es Mechanismen zur Feststellung und Prävention von Einbruchsversuchen. Ein weiteres häufig verwendetes Sicherheitsprotokoll ist WPA. Dabei handelt es sich um einen Vorläufer von 802.11i, der von einem Industriekonsortium als Zwischenlösung bis zur endgültigen Verabschiedung von 802.11i entwickelt wurde. WPA definiert eine Untergruppe der Anforderungen des 802.11i-Standards und ist für den Einsatz in älterer Hardware vorgesehen. WPA benötigt nur den TKIP-Chiffre, welcher auf dem ursprünglichen WEP-Code basiert. 802.11i erlaubt zwar auch die Verwendung von TKIP, benötigt aber zusätzlich eine stärkere Chiffre (AES-CCM) für die Datenverschlüsselung. AES war für WPA nicht vorgesehen, weil man es als zu rechenintensiv für den Einsatz in älteren Geräten ansah. Ein weiterer zu beachtender Standard ist 802.11e. Dieser definiert Protokolle zur Übertragung von Multimedia-Anwendungen, wie das Streaming von Videodateien oder Voice-over-IP (VoIP) in einem 802.11-Netzwerk. Analog zu 802.11i verfügt auch 802.11e über eine vorläufige Spezifikation namens WMM (ursprünglich WME), die von einem Industriekonsortium als Untergruppe von 802.11e spezifiziert wurde, um Multimedia-Anwendungen bereits vor der endgültigen Verabschiedung des 802.11e-Standards implementieren zu können. 802.11e sowie WME/WMM erlauben eine Prioritätenvergabe beim Datentransfer in einem drahtlosen Netzwerk. Möglich wird dies durch den Einsatz von Quality of Service-Protokollen (QoS) und erweiterten Medienzugriffsprotokollen. Werden diese Protokolle korrekt implementiert, erlauben sie hohe Datenübertragungsraten und einen priorisierten Datenfluss. FreeBSD unterstützt die Standards 802.11a, 802.11b und 802.11g. Ebenfalls unterstützt werden WPA sowie die Sicherheitsprotokolle gemäß 802.11i (sowohl für 11a, 11b als auch 11g). QoS und Verkehrspriorisierung, die von den WME/WMM-Protokollen benötigt werden, werden für einen begrenzten Satz von drahtlosen Geräten unterstützt. [[network-wireless-quick-start]] === Schnellstartanleitung Häufig soll ein Computer an ein vorhandenes Drahtlosnetzwerk angeschlossen werden. Diese Prozedur zeigt die dazu erforderlichen Schritte. [.procedure] . Besorgen Sie sich vom Netzwerkadministrator die SSID (Service Set Identifier) und den PSK (Pre Shared Key) für das Drahtlosnetzwerk. . Ermitteln Sie den drahtlosen Adapter. Der [.filename]#GENERIC#-Kernel von FreeBSD enthält Treiber für viele gängige Adapter. Wenn der drahtlose Adapter eines dieser Modelle ist, wird das in der Ausgabe von man:ifconfig[8] angezeigt: + [source,shell] .... % ifconfig | grep -B3 -i wireless .... + In FreeBSD 11 und neueren Versionen verwenden Sie stattdessen diesen Befehl: + [source,shell] .... % sysctl net.wlan.devices .... + Wenn der drahtlose Adapter nicht aufgeführt wird, könnte ein zusätzliches Kernelmodul erforderlich sein. Es besteht jedoch auch die Möglichkeit, dass der Adapter von FreeBSD nicht unterstützt wird. + Dieses Beispiel verwendet einen drahtlosen Atheros-Adapter `ath0`. . Fügen Sie in [.filename]#/etc/wpa_supplicant.conf# einen Eintrag für das Netzwerk hinzu. Wenn die Datei nicht existiert, müssen Sie diese erstellen. Ersetzen Sie _myssid_ und _psk_ durch die SSID und den PSK. Diese Informationen werden vom Netzwerkadministrator zur Verfügung gestellt. + [.programlisting] .... network={ ssid="myssid" psk="mypsk" } .... . Fügen Sie die entsprechenden Einträge in [.filename]#/etc/rc.conf# ein, um das Netzwerk beim Start zu konfigurieren: + [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA SYNCDHCP" .... . Starten Sie den Computer oder den Netzwerkdienst neu, um sich mit dem Netzwerk zu verbinden: + [source,shell] .... # service netif restart .... [[network-wireless-basic]] === Basiskonfiguration ==== Kernelkonfiguration Um ein drahtloses Netzwerk zu nutzen, wird eine drahtlose Netzwerkkarte benötigt und ein Kernel, der drahtlose Netzwerke unterstützt. Der Kernel unterstützt den Einsatz von Kernelmodulen. Daher muss nur die Unterstützung für die verwendeten Geräte aktiviert werden. Die meisten drahtlosen Geräte verwenden Bauteile von Atheros und werden deshalb vom man:ath[4]-Treiber unterstützt. Um diesen Treiber zu verwenden, muss die folgende Zeile in [.filename]#/boot/loader.conf# hinzugefügt werden: [.programlisting] .... if_ath_load="YES" .... Der Atheros-Treiber besteht aus drei Teilen: dem Treiber selbst (man:ath[4]), dem Hardware-Support-Layer für die chip-spezifischen Funktionen (man:ath_hal[4]) sowie einem Algorithmus zur Auswahl der Frame-Übertragungsrate (ath_rate_sample). Wenn diese Unterstützung als Kernelmodul geladen wird, kümmert sich das Modul automatisch um Abhängigkeiten. Um die Unterstützung für ein anderes drahtloses Gerät zu laden, geben Sie das entsprechende Modul für dieses Gerät an. Dieses Beispiel zeigt die Verwendung von Geräten, die auf Bauteilen von Intersil Prism basieren und den Treiber man:wi[4] benötigen: [.programlisting] .... if_wi_load="YES" .... [NOTE] ==== Die Beispiele in diesem Abschnitt verwenden den man:ath[4]-Treiber. Verwenden Sie ein anderes Gerät, muss der Gerätename an die Konfiguration angepasst werden. Eine Liste aller verfügbaren Treiber und unterstützten drahtlosen Geräte finden sich in den FreeBSD Hardware Notes unter https://www.FreeBSD.org/releases/[Release Information] der FreeBSD Homepage. Gibt es keinen nativen FreeBSD-Treiber für das drahtlose Gerät, kann möglicherweise mit crossref:config[config-network-ndis,NDIS] ein Windows(R)-Treiber verwendet werden. ==== Zusätzlich müssen die Module zur Verschlüsselung des drahtlosen Netzwerks geladen werden. Diese werden normalerweise dynamisch vom man:wlan[4]-Modul geladen. Im folgenden Beispiel erfolgt allerdings eine manuelle Konfiguration. Folgende Module sind verfügbar: man:wlan_wep[4], man:wlan_ccmp[4] und man:wlan_tkip[4]. Sowohl man:wlan_ccmp[4] als auch man:wlan_tkip[4] werden nur benötigt, wenn WPA und/oder die Sicherheitsprotokolle von 802.11i verwendet werden. Wenn das Netzwerk keine Verschlüsselung verwendet, wird die man:wlan_wep[4]-Unterstützung nicht benötigt. Um diese Module beim Systemstart zu laden, fügen Sie folgende Zeilen in [.filename]#/boot/loader.conf# ein: [.programlisting] .... wlan_wep_load="YES" wlan_ccmp_load="YES" wlan_tkip_load="YES" .... Sobald diese Einträge in [.filename]#/boot/loader.conf# vorhanden sind, muss das FreeBSD-System neu gestartet werden. Alternativ können die Kernelmodule auch manuell mit man:kldload[8] geladen werden. [NOTE] ==== Benutzer, die keine Kernelmodule verwenden wollen, können die benötigten Treiber auch in den Kernel kompilieren. Dazu müssen die folgenden Zeilen in die Kernelkonfigurationsdatei aufgenommen werden: [.programlisting] .... device wlan # 802.11 support device wlan_wep # 802.11 WEP support device wlan_ccmp # 802.11 CCMP support device wlan_tkip # 802.11 TKIP support device wlan_amrr # AMRR transmit rate control algorithm device ath # Atheros pci/cardbus NIC's device ath_hal # pci/cardbus chip support options AH_SUPPORT_AR5416 # enable AR5416 tx/rx descriptors device ath_rate_sample # SampleRate tx rate control for ath .... Mit diesen Informationen in der Kernelkonfigurationsdatei kann der Kernel neu gebaut, und das FreeBSD-System anschließend neu gestartet werden. ==== Informationen über das drahtlose Gerät sollten in den Boot-Meldungen folgendermaßen angezeigt werden: [source,shell] .... ath0: mem 0x88000000-0x8800ffff irq 11 at device 0.0 on cardbus1 ath0: [ITHREAD] ath0: AR2413 mac 7.9 RF2413 phy 4.5 .... ==== Konfiguration der entsprechenden Region Da die rechtliche Situation in verschiedenen Teilen der Welt unterschiedlich ist, ist es notwendig, die für Ihre Region geltenden Domänen korrekt einzustellen, um die richtigen Informationen darüber zu erhalten, welche Kanäle benutzt werden können. Die verfügbaren Definitionen der Regionen finden Sie in [.filename]#/etc/regdomain.xml#. Um die Daten zur Laufzeit einzustellen, benutzen Sie `ifconfig`: [source,shell] .... # ifconfig wlan0 regdomain ETSI country AT .... Um die Einstellungen beizubehalten, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# hinzu: [source,shell] .... # sysrc create_args_wlan0="country AT regdomain ETSI" .... === Infrastruktur-Modus Drahtlose Netzwerke werden in der Regel im Infrastruktur-Modus (BSS) betrieben. Dazu werden mehrere drahtlose Access Points zu einem gemeinsamen drahtlosen Netzwerk verbunden. Jedes dieser drahtlosen Netzwerke hat einen eigenen Namen, der als >SSID> bezeichnet wird. Alle Clients eines drahtlosen Netzwerks verbinden sich in diesem Modus mit einem Access Point. ==== FreeBSD-Clients ===== Einen Access Point finden Um nach verfügbaren drahtlosen Netzwerken zu suchen verwenden Sie man:ifconfig[8]. Dieser Scanvorgang kann einen Moment dauern, da jede verfügbare Frequenz auf verfügbare Access Points hin überprüft werden muss. Nur der Super-User kann einen Scanvorgang starten: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS dlinkap 00:13:46:49:41:76 11 54M -90:96 100 EPS WPA WME freebsdap 00:11:95:c3:0d:ac 1 54M -83:96 100 EPS WPA .... [NOTE] ==== Die Netzwerkkarte muss in den Status `up` versetzt werden, bevor der erste Scanvorgang gestartet werden kann. Für spätere Scans ist dies aber nicht mehr erforderlich. ==== Als Ergebnis erhalten Sie eine Liste mit allen gefundenen BSS/IBSS-Netzwerken. Zusätzlich zum Namen des Netzwerks, der `SSID`, wird auch die `BSSID` ausgegeben. Dabei handelt es sich um die MAC-Adresse des Access Points. Das Feld `CAPS` gibt den Typ des Netzwerks sowie die Fähigkeiten der Stationen innerhalb des Netzwerks an: .Station Capability Codes [cols="1,1", frame="none", options="header"] |=== | Capability Code | Bedeutung |`E` |Extended Service Set (ESS). Zeigt an, dass die Station Teil eines Infrastruktur-Netzwerks ist, und nicht eines IBSS/Ad-hoc-Netzwerks. |`I` |IBSS/Ad-hoc-Netzwerk. Die Station ist Teil eines Ad-hoc-Netzwerks und nicht eines ESS-Netzwerks. |`P` |Privacy. Alle Datenframes, die innerhalb des BSS ausgetauscht werden, sind verschlüsselt. Dieses BSS verwendet dazu kryptographische Verfahren wie WEP, TKIP oder AES-CCMP. |`S` |Short Preamble. Das Netzwerk verwendet eine kurze Präambel (definiert in 802.11b High Rate/DSSS PHY). Eine kurze Präambel verwendet ein 56 Bit langes Sync-Feld, im Gegensatz zu einer langen Präambel, die ein 128 Bit langes Sync-Feld verwendet. |`s` |Short slot time. Das 802.11g-Netzwerk verwendet eine kurze Slotzeit, da es in diesem Netzwerk keine veralteten (802.11b) Geräte gibt. |=== Um eine Liste der bekannten Netzwerke auszugeben, verwenden Sie den folgenden Befehl: [source,shell] .... # ifconfig wlan0 list scan .... Diese Liste kann entweder automatisch durch das drahtlose Gerät oder manuell durch eine `scan`-Aufforderung aktualisiert werden. Veraltete Informationen werden dabei automatisch entfernt. ===== Basiseinstellungen Dieser Abschnitt beschreibt, wie Sie eine drahtlose Netzwerkkarte ohne Verschlüsselung unter FreeBSD einrichten. Nachdem Sie sich mit den Informationen dieses Abschnitts vertraut gemacht haben, sollten Sie das drahtlose Netzwerk mit <> verschlüsseln. Das Einrichten eines drahtlosen Netzwerks erfolgt in drei Schritten: Der Auswahl eines Access Points, die Anmeldung der Station sowie der Konfiguration der IP-Adresse. ====== Einen Access Point auswählen Im Normalfall wird sich die Station automatisch mit einem der zur Verfügung stehenden Access Points verbinden. Dazu muss lediglich das drahtlose Gerät aktiviert, oder in [.filename]#/etc/rc.conf# eingetragen sein: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... Stehen mehrere Access Points zur Verfügung, kann ein spezifischer durch Angabe der SSID gewählt werden: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid Ihre_SSID DHCP" .... Gibt es in einem Netzwerk mehrere Access Points mit der gleichen SSID, was das Routing vereinfacht, kann es notwendig sein, dass ein bestimmtes Gerät verbunden werden muss. Dazu muss lediglich die BSSID des Access Points angeben werden. Die Angabe der SSID ist hierbei nicht zwingend notwendig: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid Ihre_SSID bssid xx:xx:xx:xx:xx:xx DHCP" .... Es gibt noch weitere Möglichkeiten, den Zugriff auf bestimmte Access Point zu beschränken, beispielsweise durch die Begrenzung der Frequenzen, auf denen eine Station nach einem Access Point sucht. Sinnvoll ist ein solches Vorgehen beispielsweise, wenn das drahtlose Gerät in verschiedenen Frequenzbereichen arbeiten kann, da in diesem Fall das Prüfen aller Frequenzen sehr zeitintensiv sein kann. Um nur innerhalb eines bestimmten Frequenzbereichs nach einem Access Point zu suchen, verwenden Sie die Option `mode`: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="mode 11g ssid Ihre_SSID DHCP" .... In diesem Beispiel sucht das drahtlose Gerät nur im 2,4 GHz-Band (802.11g), aber nicht innerhalb des 5 GHz-Bandes nach einem Access Point. Mit der Option `channel` kann eine bestimmte Frequenz vorgegeben werden, auf der gesucht werden soll. Die Option `chanlist` erlaubt die Angabe mehrerer erlaubter Frequenzen. Eine umfassende Beschreibung dieser Optionen finden Sie in man:ifconfig[8]. ====== Authentifizierung Sobald ein Access Point gefunden wurde, muss sich die Station am Access Point authentifizieren, bevor Daten übertragen werden können. Dazu gibt es verschiedene Möglichkeiten. Am häufigsten wird die sogenannte _offene Authentifizierung_ verwendet. Dabei wird es jeder Station erlaubt, sich mit einem Netzwerk zu verbinden und Daten zu übertragen. Aus Sicherheitsgründen sollte diese Methode allerdings nur zu Testzwecken bei der erstmaligen Einrichtung eines drahtlosen Netzwerks verwendet werden. Andere Authentifizierungsmechanismen erfordern den Austausch kryptographischer Informationen, bevor sie die Übertragung von Daten erlauben. Dazu gehören der Austausch fixer (vorher vereinbarter) Schlüssel oder Kennwörter, sowie der Einsatz komplexerer Verfahren mit Backend-Diensten wie RADIUS. Die offene Authentifizierung ist die Voreinstellung. Am zweithäufigsten kommt das im <> beschriebene WPA-PSK zum Einsatz, welches auch als WPA Personal bezeichnet wird. [NOTE] ==== Kommt eine Apple(R) AirPort(R) Extreme-Basisstation als Access Point zum Einsatz, muss sowohl die Shared-Key-Authentifizierung als auch ein WEP-Schlüssel konfiguriert werden. Die entsprechende Konfiguration erfolgt entweder in [.filename]#/etc/rc.conf# oder über das Programm man:wpa_supplicant[8]. Für eine einzelne AirPort(R)-Basisstation kann der Zugriff wie folgt konfiguriert werden: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="authmode shared wepmode on weptxkey 1 wepkey 01234567 DHCP" .... Normalerweise sollte Shared-Key-Authentifizierung nicht verwendet werden, da diese die Sicherheit des WEP-Schlüssel noch weiter verringert. Wenn WEP für Kompatibilität mit älteren Geräten verwendet werden muss, ist es besser, WEP mit offener Authentifizierung zu verwenden. Weitere Informationen zu WEP finden Sie im <>. ==== ====== Eine IP-Adresse über DHCP beziehen Sobald ein Access Point ausgewählt ist und die Authentifizierungsparameter festgelegt sind, wird eine IP-Adresse benötigt. In der Regel wird die IP-Adresse über DHCP bezogen. Um dies zu erreichen, bearbeiten Sie [.filename]#/etc/rc.conf# und fügen Sie `DHCP` für das drahtlose Gerät in die Konfiguration hinzu: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... Das drahtlose Gerät kann nun gestartet werden: [source,shell] .... # service netif start .... Nachdem das Gerät aktiviert wurde, kann mit man:ifconfig[8] der Status des Geräts [.filename]#ath0# abgefragt werden: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.1.100 netmask 0xffffff00 broadcast 192.168.1.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid dlinkap channel 11 (2462 Mhz 11g) bssid 00:13:46:49:41:76 country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... `status: associated` besagt, dass sich das Gerät mit dem drahtlosen Netzwerk verbunden hat. `bssid 00:13:46:49:41:76` ist die MAC-Adresse des Access Points und `authmode OPEN` zeigt an, dass die Kommunikation nicht verschlüsselt wird. ====== Statische IP-Adressen Wenn eine IP-Adresse nicht von einem DHCP-Server bezogen werden kann, vergeben Sie eine statische IP-Adresse. Ersetzten Sie dazu das oben gezeigte Schlüsselwort `DHCP` durch die entsprechende IP-Adresse. Beachten Sie dabei, dass Sie die anderen Konfigurationsparameter nicht versehentlich verändern: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="inet 192.168.1.100 netmask 255.255.255.0 ssid your_ssid_here" .... [[network-wireless-wpa]] ===== WPA Wi-Fi Protected Access (WPA) ist ein Sicherheitsprotokoll, das in 802.11-Netzwerken verwendet wird, um die fehlende Authentifizierung und Schwächen von WEP zu vermeiden. WPA stellt das aktuelle 802.1X-Authentifizierungsprotokoll dar und verwendet eine von mehreren Chiffren, um die Datensicherheit zu gewährleisten. Die einzige Chiffre, die von WPA verlangt wird, ist Temporary Key Integrity Protocol (TKIP). TKIP ist eine Chiffre, die die von WEP verwendete RC4-Chiffre um Funktionen zur Prüfung der Datenintegrität und zur Erkennung und Bekämpfung von Einbruchsversuchen erweitert. TKIP ist durch Softwaremodifikationen auch unter veralteter Hardware lauffähig. Im Vergleich zu WEP ist WPA zwar sehr viel sicherer, es ist aber dennoch nicht völlig immun gegen Angriffe. WPA definiert mit AES-CCMP noch eine weitere Chiffre als Alternative zu TKIP. AES-CCMP, welches häufig als WPA2 oder RSN bezeichnet wird, sollte bevorzugt eingesetzt werden. WPA definiert Authentifizierungs- und Verschlüsselungsprotokolle. Die Authentifizierung erfolgt in der Regel über eine der folgenden Techniken: 802.1X gemeinsam mit einem Backend-Authentifizierungsdienst wie RADIUS, oder durch einen Minimal-Handshake zwischen der Station und dem Access Point mit einem vorher vereinbarten gemeinsamen Schlüssel. Die erste Technik wird als WPA Enterprise, die zweite hingegen als WPA Personal bezeichnet. Da sich der Aufwand für das Aufsetzen eines RADIUS-Backend-Servers für die meisten drahtlosen Netzwerke nicht lohnt, wird WPA in der Regel als WPA-PSK konfiguriert. Die Kontrolle der drahtlosen Verbindung sowie das Aushandeln des Schlüssel, oder die Authentifizierung mit einem Server, erfolgt über man:wpa_supplicant[8]. Dieses Programm benötigt eine Konfigurationsdatei, [.filename]#/etc/wpa_supplicant.conf#. Weitere Informationen finden Sie in man:wpa_supplicant.conf[5]. [[network-wireless-wpa-wpa-psk]] ====== WPA-PSK WPA-PSK, das auch als WPA-Personal bekannt ist, basiert auf einem gemeinsamen, vorher vereinbarten Schlüssel (PSK), der aus einem Passwort generiert und danach als Master-Key des drahtlosen Netzwerks verwendet wird. Jeder Benutzer des drahtlosen Netzwerks verwendet daher _den gleichen_ Schlüssel. WPA-PSK sollte nur in kleinen Netzwerken eingesetzt werden, in denen die Konfiguration eines Authentifizierungsservers nicht möglich oder erwünscht ist. [WARNING] ==== Achten Sie darauf, immer starke Passwörter zu verwenden, die ausreichend lang sind und auch Sonderzeichen enthalten, damit diese nicht leicht erraten oder umgangen werden können. ==== Der erste Schritt zum Einsatz von WPA-PSK ist die Konfiguration der SSID und des gemeinsamen Schlüssels des Netzwerks in [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" psk="freebsdmall" } .... Danach wird in [.filename]#/etc/rc.conf# definiert, dass WPA zur Verschlüsselung eingesetzt werden soll und dass die IP-Adresse über DHCP bezogen wird: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Nun kann das drahtlose Gerät aktiviert werden: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 5 DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6 DHCPOFFER from 192.168.0.1 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 MHz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Alternativ kann das drahtlose Gerät manuell, mit Hilfe der Informationen aus [.filename]#/etc/wpa_supplicant.conf# konfiguriert werden: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:11:95:c3:0d:ac (SSID='freebsdap' freq=2412 MHz) Associated with 00:11:95:c3:0d:ac WPA: Key negotiation completed with 00:11:95:c3:0d:ac [PTK=CCMP GTK=CCMP] CTRL-EVENT-CONNECTED - Connection to 00:11:95:c3:0d:ac completed (auth) [id=0 id_str=] .... Im zweiten Schritt starten Sie nun man:dhclient[8], um eine IP-Adresse vom DHCP-Server zu beziehen: [source,shell] .... # dhclient wlan0 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 MHz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [NOTE] ==== Enthält [.filename]#/etc/rc.conf# bereits die Zeile `ifconfig_wlan0="DHCP"`, wird man:dhclient[8] automatisch gestartet, nachdem man:wpa_supplicant[8] sich mit dem Access Point verbunden hat. ==== Sollte der Einsatz von DHCP nicht möglich oder nicht gewünscht sein, konfigurieren Sie eine statische IP-Adresse, nachdem man:wpa_supplicant[8] die Station authentifiziert hat: [source,shell] .... # ifconfig wlan0 inet 192.168.0.100 netmask 255.255.255.0 # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 MHz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Falls DHCP nicht verwendet wird, müssen zusätzlich noch das Standard-Gateway sowie der Nameserver manuell festgelegt werden: [source,shell] .... # route add default your_default_router # echo "nameserver your_DNS_server" >> /etc/resolv.conf .... [[network-wireless-wpa-eap-tls]] ====== WPA und EAP-TLS Die zweite Möglichkeit, WPA einzusetzen, ist die Verwendung eines 802.1X-Backend-Authentifizierungsservers. Diese Variante wird als WPA-Enterprise bezeichnet, um sie vom weniger sicheren WPA-Personal abzugrenzen. Die bei WPA-Enterprise verwendete Authentifizierung basiert auf dem Extensible Authentication Protocol (EAP). EAP selbst bietet keine Verschlüsselung, sondern operiert in einem verschlüsselten Tunnel. Es gibt verschiedene auf EAP basierende Authentifizierungsmethoden, darunter EAP-TLS, EAP-TTLS und EAP-PEAP. EAP mit Transport Layers Security (EAP-TLS) ist ein sehr gut unterstütztes Authentifizierungsprotokoll, da es sich dabei um die erste EAP-Methode handelt, die von der http://www.wi-fi.org/[ Wi-Fi Alliance] zertifiziert wurde. EAP-TLS erfordert drei Zertifikate: Das auf allen Rechnern installierte CA-Zertifikat, das Server-Zertifikat des Authentifizierungsservers, sowie ein Client-Zertifikat für jeden drahtlosen Client. Sowohl der Authentifizierungsservers als auch die drahtlosen Clients authentifizieren sich gegenseitig über Zertifikate, wobei sie überprüfen, ob diese Zertifikate auch von der Zertifizierungs-Authorität (CA) des jeweiligen Unternehmens signiert wurden. Die Konfiguration erfolgt (analog zu WPA-PSK) über [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" <.> proto=RSN <.> key_mgmt=WPA-EAP <.> eap=TLS <.> identity="loader" <.> ca_cert="/etc/certs/cacert.pem" <.> client_cert="/etc/certs/clientcert.pem" <.> private_key="/etc/certs/clientkey.pem" <.> private_key_passwd="freebsdmallclient" <.> } .... <.> Der Name des Netzwerks (SSID). <.> Das als WPA2 bekannte RSN IEEE(R) 802.11i Protokoll wird verwendet. <.> Die `key_mgmt`-Zeile bezieht sich auf das verwendete Key-Management-Protokoll. In diesem Beispiel wird WPA gemeinsam mit der EAP-Authentifizierung verwendet. <.> Die für die Verbindung verwendete EAP-Methode. <.> Das `identity`-Feld enthält den von EAP verwendeten Identifizierungsstring. <.> Das Feld `ca_cert` gibt den Pfad zum CA-Zertifikat an. Diese Datei wird zur Verifizierung des Server-Zertifikats benötigt. <.> Die `client_cert`-Zeile gibt den Pfad zum Client-Zertifikat an. Jeder Client hat ein eigenes, innerhalb des Netzwerks eindeutiges, Zertifikat. <.> Das Feld `private_key` gibt den Pfad zum privaten Schlüssel des Client-Zertifikat an. <.> Das Feld `private_key_passwd` enthält die Passphrase für den privaten Schlüssel. Danach fügen Sie die folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Nun können Sie das drahtlose Gerät aktivieren: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 MHz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Alternativ kann das drahtlose Gerät manuell mit man:wpa_supplicant[8] und man:ifconfig[8] aktiviert werden. [[network-wireless-wpa-eap-ttls]] ====== WPA mit EAP-TTLS Bei EAP-TLS müssen sowohl der Authentifizierungsserver als auch die Clients jeweils ein eigenes Zertifikat aufweisen. Bei EAP-TTLS ist das Client-Zertifikat optional. EAP-TTLS geht dabei vor wie ein Webserver, der einen sicheren SSL-Tunnel erzeugen kann, ohne dass der Besucher dabei über ein clientseitiges Zertifikat verfügen muss. EAP-TTLS verwendet einen verschlüsselten TLS-Tunnel zum sicheren Transport der Authentifizierungsdaten. Die erforderliche Konfiguration erfolgt in [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=TTLS <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase2="auth=MD5" <.> } .... <.> Die für die Verbindung verwendete EAP-Methode. <.> Das `identity`-Feld enthält den Identifizierungsstring für die EAP-Authentifizierung innerhalb des verschlüsselten TLS-Tunnels. <.> Das `password`-Feld enthält die Passphrase für die EAP-Authentifizierung. <.> Das Feld `ca_cert` gibt den Pfad zum CA-Zertifikat an. Diese Datei wird zur Verifizierung des Server-Zertifikats benötigt. <.> Die innerhalb des verschlüsselten TLS-Tunnels verwendete Authentifizierungsmethode. In Fall von PEAP ist dies `auth=MSCHAPV2`. Folgende Zeilen müssen in [.filename]#/etc/rc.conf# aufgenommen werden: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Nun kann das drahtlose Gerät aktiviert werden: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 MHz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wpa-eap-peap]] ====== WPA mit EAP-PEAP [NOTE] ==== PEAPv0/EAP-MSCHAPv2 ist die gängigste PEAP-Methode. In diesem Kapitel wird der Begriff PEAP stellvertretend für diese Methode verwendet. ==== Protected EAP (PEAP) wurde als Alternative zu EAP-TTLS entwickelt und ist nach EAP-TLS der meist genutzte EAP-Standard. In einem Netzwerk mit verschiedenen Betriebssystemen sollte PEAP das am besten unterstützte Standard nach EAP-TLS sein. PEAP arbeitet ähnlich wie EAP-TTLS. Es verwendet ein serverseitiges Zertifikat, um einen verschlüsselten TLS-Tunnel, über den die sichere Authentifizierung zwischen den Clients und dem Authentifizierungsserver erfolgt. In Sachen Sicherheit unterscheiden sich EAP-TTLS und PEAP allerdings: PEAP überträgt den Benutzernamen im Klartext und verschlüsselt nur das Passwort, während EAP-TTLS sowohl den Benutzernamen, als auch das Passwort über den TLS-Tunnel überträgt. Um EAP-PEAP zu konfigurieren, fügen Sie die folgenden Zeilen in [.filename]#/etc/wpa_supplicant.conf# ein: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=PEAP <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase1="peaplabel=0" <.> phase2="auth=MSCHAPV2" <.> } .... <.> Die für die Verbindung verwendete EAP-Methode. <.> Das `identity`-Feld enthält den Identifizierungsstring für die innerhalb des verschlüsselten TLS-Tunnels erfolgende EAP-Authentifizierung. <.> Das Feld `password` enthält die Passphrase für die EAP-Authentifizierung. <.> Das Feld `ca_cert` gibt den Pfad zum CA-Zertifikat an. Diese Datei wird zur Verifizierung des Server-Zertifikats benötigt. <.> Dieses Feld enthält die Parameter für die erste Phase der Authentifizierung, den TLS-Tunnel. Je nachdem, welcher Authentifizierungsserver benutzt wird, kann ein spezifisches Label für die Authentifizierung verwendet werden. Meistens lautet das Label "client EAP encryption", dass durch `peaplabel=0` gesetzt wird. Weitere Informationen finden Sie in man:wpa_supplicant.conf[5]. <.> Das innerhalb des verschlüsselten TLS-Tunnels verwendete Authentifizierungsprotokoll. In unserem Beispiel handelt es sich dabei um `auth=MSCHAPV2`. Danach fügen Sie die folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... ifconfig_ath0="WPA DHCP" .... Nun kann das drahtlose Gerät aktiviert werden. [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 MHz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wep]] ===== WEP Wired Equivalent Privacy (WEP) ist Teil des ursprünglichen 802.11-Standards. Es enthält keinen Authentifzierungsmechanismus und verfügt lediglich über eine schwache Zugriffskontrolle, die sehr leicht umgangen werden kann. WEP kann über man:ifconfig[8] aktiviert werden: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 inet 192.168.1.100 netmask 255.255.255.0 \ ssid my_net wepmode on weptxkey 3 wepkey 3:0x3456789012 .... * `weptxkey` definiert den WEP-Schlüssel, der für die Datenübertragung verwendet wird. Dieses Beispiel verwendet den dritten Schlüssel. Der gleiche Schlüssel muss auch am Access Point eingestellt sein. Kennen Sie den vom Access Point verwendeten Schlüssel nicht, sollten Sie zuerst den Wert `1` (den ersten Schlüssel) für diese Variable verwenden. * `wepkey` legt den zu verwendenden WEP-Schlüssel in der Form _Nummer:Schlüssel_ fest. Schlüssel `1` wird standardmäßig verwendet. Die "Nummer" muss nur angegeben werden, wenn ein anderer als der erste Schlüssel verwendet werden soll. + [NOTE] ==== Ersetzen Sie `0x3456789012` durch den am Access Point konfigurierten Schlüssel. ==== Weitere Informationen finden Sie in man:ifconfig[8]. Das Programm man:wpa_supplicant[8] eignet sich ebenfalls dazu, WEP für drahtlose Geräte zu aktivieren. Obige Konfiguration lässt sich dabei durch die Aufnahme der folgenden Zeilen in [.filename]#/etc/wpa_supplicant.conf# realisieren: [.programlisting] .... network={ ssid="my_net" key_mgmt=NONE wep_key3=3456789012 wep_tx_keyidx=3 } .... Danach müssen Sie das Programm noch aufrufen: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:13:46:49:41:76 (SSID='dlinkap' freq=2437 MHz) Associated with 00:13:46:49:41:76 .... === Ad-hoc-Modus Der IBSS-Modus, der auch als Ad-hoc-Modus bezeichnet wird, ist für Punkt-zu-Punkt-Verbindungen vorgesehen. Um beispielsweise eine Ad-hoc-Verbindung zwischen den Rechnern `A` und `B` aufzubauen, werden lediglich zwei IP-Adressen und eine SSID benötigt. Auf Rechner `A`: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... Der `adhoc`-Parameter zeigt an, dass die Schnittstelle im IBSS-Modus läuft. Rechner `B` sollte nun in der Lage sein, Rechner `A` zu finden: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 02:11:95:c3:0d:ac 2 54M -64:-96 100 IS WME .... Der Wert `I` (Spalte CAPS) in dieser Ausgabe bestätigt, dass sich Rechner `A` im Ad-hoc-Modus befindet. Nun müssen Sie noch Rechner `B` eine andere IP-Adresse zuweisen: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... Damit sind die Rechner `A` und `B` bereit und können untereinander Daten austauschen. [[network-wireless-ap]] === FreeBSD Host Access Points FreeBSD kann als Access Point (AP) agieren. Dies verhindert, dass man sich einen Hardware AP kaufen oder ein Ad-hoc Netzwerk laufen lassen muss. Dies kann sinnvoll sein, falls der FreeBSD-Computer als Gateway zu einem anderen Netzwerk, wie dem Internet, fungiert. [[network-wireless-ap-basic]] ==== Grundeinstellungen Bevor Sie einen FreeBSD-Computer als AP konfigurieren, muss der Kernel mit der entsprechenden Netzwerkunterstützung für die drahtlose Karte, sowie die Sicherheitsprotokolle konfiguriert werden. Weitere Informationen finden Sie im <>. [NOTE] ==== Die Verwendung der NDIS Treiber für Windows(R) erlauben zur Zeit keinen AP-Modus. Nur die nativen FreeBSD-Wireless-Treiber unterstützen den AP-Modus. ==== Nachdem die Netzwerkunterstützung geladen ist, überprüfen Sie, ob das Wireless-Gerät den hostbasierenden Access-Point Modus, der auch als hostap-Modus bekannt ist, unterstützt: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 list caps drivercaps=6f85edc1 cryptocaps=1f .... Diese Ausgabe zeigt die Eigenschaften der Karte. Das Wort `HOSTAP` bestätigt, dass diese Wireless-Karte als AP agieren kann. Die verschiedenen unterstützten Algorithmen werden ebenfalls angezeigt: WEP, TKIP und AES. Diese Informationen zeigen an, welche Sicherheitsprotokolle auf dem AP nutzbar sind. Das Wireless-Gerät kann nur während der Erzeugung des Pseudo-Geräts in den hostap-Modus gesetzt werden. Zuvor erstellte Pseudo-Geräte müssen also vorher zerstört werden: [source,shell] .... # ifconfig wlan0 destroy .... Danach muss das Gerät erneut erstellt werden, bevor die restlichen Netzwerkparameter konfiguriert werden können: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1 .... Benutzen Sie danach erneut man:ifconfig[8], um den Status der [.filename]#wlan0#-Schnittstelle abzufragen: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... Die `hostap`-Parameter geben die Schnittstelle an, die im hostbasierenden Access Point Modus läuft. Die Konfiguration der Schnittstelle kann durch Hinzufügen der folgenden Zeilen in die Datei [.filename]#/etc/rc.conf# automatisch während des Bootvorganges erfolgen: [.programlisting] .... wlans_ath0="wlan0" create_args_wlan0="wlanmode hostap" ifconfig_wlan0="inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1" .... ==== Hostbasierender Access Point ohne Authentifizierung oder Verschlüsselung Obwohl es nicht empfohlen wird, einen AP ohne jegliche Authentifizierung oder Verschlüsselung laufen zu lassen, ist es eine einfache Art zu testen, ob der AP funktioniert. Diese Konfiguration ist auch wichtig für die Fehlersuche bei Client-Problemen. Nachdem der AP konfiguriert wurde, ist es möglich von einem anderen drahtlosen Computer eine Suche nach dem AP zu starten: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M -66:-96 100 ES WME .... Der Client-Rechner hat den AP gefunden und kann nun eine Verbindung aufbauen: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... [[network-wireless-ap-wpa]] ==== WPA2-hostbasierter Access Point Dieser Abschnitt beschäftigt sich mit der Konfiguration eines FreeBSD Access Point mit dem WPA2-Sicherheitsprotokoll. Weitere Einzelheiten zu WPA und der Konfiguration von Clients mit WPA finden Sie im <>. Der man:hostapd[8]-Dienst wird genutzt, um die Client-Authentifizierung und das Schlüsselmanagement auf dem AP mit aktiviertem WPA2 zu nutzen. Die folgende Konfiguration wird auf dem FreeBSD-Computer ausgeführt, der als AP agiert. Nachdem der AP korrekt arbeitet, sollte man:hostapd[8] automatisch beim Booten durch folgende Zeile in [.filename]#/etc/rc.conf# aktiviert werden: [.programlisting] .... hostapd_enable="YES" .... Bevor Sie versuchen man:hostapd[8] zu konfigurieren, konfigurieren Sie zunächst die Grundeinstellungen, wie im <> beschrieben. ===== WPA2-PSK WPA2-PSK ist für kleine Netzwerke gedacht, in denen die Verwendung eines Authentifizierungs-Backend-Server nicht möglich oder nicht erwünscht ist. Die Konfiguration wird in [.filename]#/etc/hostapd.conf# durchgeführt: [.programlisting] .... interface=wlan0 <.> debug=1 <.> ctrl_interface=/var/run/hostapd <.> ctrl_interface_group=wheel <.> ssid=freebsdap <.> wpa=2 <.> wpa_passphrase=freebsdmall <.> wpa_key_mgmt=WPA-PSK <.> wpa_pairwise=CCMP <.> .... <.> Die Wireless-Schnittstelle, die für den Access Point verwendet wird an. <.> Der debuglevel von man:hostapd[8] während der Ausführung. Ein Wert von `1` ist der kleinste zulässige Wert. <.> Der Pfadname des Verzeichnisses, der von man:hostapd[8] genutzt wird, um die Domain-Socket-Dateien zu speichern, die für die Kommunikation mit externen Programmen, wie z.B. man:hostapd_cli[8], benutzt werden. In diesem Beispiel wird der Standardwert verwendet. <.> Die Gruppe die Zugriff auf die Schnittstellendateien hat. <.> Der Name des drahtlosen Netzwerks (SSID). <.> Aktiviert WPA und gibt an welches WPA-Authentifizierungprotokoll benötigt wird. Ein Wert von `2` konfiguriert den AP mit WPA2. Setzen Sie den Wert nur auf `1`, wenn Sie das veraltete WPA benötigen. <.> Das ASCII-Passwort für die WPA-Authentifizierung. <.> Das verwendete Schlüsselmanagement-Protokoll. Dieses Beispiel nutzt WPA-PSK. <.> Die zulässigen Verschlüsselungsverfahren des Access-Points. In diesem Beispiel wird nur CCMP (AES) akzeptiert. CCMP ist eine Alternative zu TKIP und sollte wenn möglich eingesetzt werden. TKIP sollte nur da eingesetzt werden, wo kein CCMP möglich ist. Als nächstes wird hostapd gestartet: [source,shell] .... # service hostapd forcestart .... [source,shell] .... # ifconfig wlan0 wlan0: flags=8943 metric 0 mtu 1500 ether 04:f0:21:16:8e:10 inet6 fe80::6f0:21ff:fe16:8e10%wlan0 prefixlen 64 scopeid 0x9 nd6 options=21 media: IEEE 802.11 Wireless Ethernet autoselect mode 11na status: running ssid No5ignal channel 36 (5180 MHz 11a ht/40+) bssid 04:f0:21:16:8e:10 country US ecm authmode WPA2/802.11i privacy MIXED deftxkey 2 AES-CCM 2:128-bit AES-CCM 3:128-bit txpower 17 mcastrate 6 mgmtrate 6 scanvalid 60 ampdulimit 64k ampdudensity 8 shortgi wme burst dtimperiod 1 -dfs groups: wlan .... Sobald der AP läuft, können sich die Clients mit ihm verbinden. Weitere Informationen finden Sie im <>. Es ist möglich zu sehen, welche Stationen mit dem AP verbunden sind. Geben Sie dazu `ifconfig _wlan0_ list sta` ein. ==== WEP-hostbasierter Access Point Es ist nicht empfehlenswert, einen AP mit WEP zu konfigurieren, da es keine Authentifikationsmechanismen gibt und WEP leicht zu knacken ist. Einige ältere drahtlose Karten unterstützen nur WEP als Sicherheitsprotokoll. Diese Karten können nur mit einem AP ohne Authentifikation oder Verschlüsselung genutzt werden. Das Wireless-Gerät kann nun in den hostap-Modus versetzt werden und mit der korrekten SSID und IP-Adresse konfiguriert werden: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 \ ssid freebsdap wepmode on weptxkey 3 wepkey 3:0x3456789012 mode 11g .... * Der `weptxkey` zeigt an, welcher WEP-Schlüssel bei der Übertragung benutzt wird. In diesem Beispiel wird der dritte Schlüssel benutzt, da die Nummerierung bei `1` beginnt. Dieser Parameter muss angegeben werden, damit die Daten verschlüsselt werden. * Der `wepkey` gibt den gewählten WEP-Schlüssel an. Er sollte im folgenden Format _index:key_ vorliegen. Wenn kein Index vorhanden ist, wird der Schlüssel `1` benutzt. Ansonsten muss der Index manuell festgelegt werden. Benutzen Sie man:ifconfig[8] um den Status der [.filename]#wlan0#-Schnittstelle erneut anzuzeigen: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 4 (2427 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy ON deftxkey 3 wepkey 3:40-bit txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... Es ist möglich, von einem anderen drahtlosen Computer eine Suche nach dem AP zu starten: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M 22:1 100 EPS .... Der Client-Rechner hat den AP gefunden und kann nun eine Verbindung aufbauen. Weitere Informationen finden Sie im <>. === Benutzung von drahtgebundenen und drahtlosen Verbindungen Eine Verbindung per Kabel bietet eine bessere Leistung und eine höhere Zuverlässigkeit, während die Wireless-Verbindung eine höhere Flexibilität und Mobilität bietet. Benutzer von Laptops wollen normalerweise beides nutzen und zwischen beiden Verbindungen hin und her schalten. Unter FreeBSD ist es möglich zwei oder mehr Netzwerkschnittstellen in einem "failover"-Mode zu kombinieren. Diese Konfiguration nutzt die beste verfügbare Verbindung aus einer Gruppe von Netzwerkverbindungen. Sobald sich der Linkstatus ändert, wechselt das Betriebssystem automatisch auf eine andere Verbindung. Link-Aggregation und Failover werden im <> behandelt. Ein Beispiel für die Verwendung von kabelgebundenen und drahtlosen Verbindungen gibt es im <>. === Problembehandlung Dieser Abschnitt beschreibt eine Reihe von Maßnahmen zur Behebung von alltäglichen Problemen mit Drahtlosnetzwerken. * Wird der Access Point bei der Suche nicht gefunden, überprüfen Sie, dass die Konfiguration des drahtlosen Geräts nicht die Anzahl der Kanäle beschränkt. * Wenn sich das Gerät nicht mit dem Access Point verbinden kann, überprüfen Sie, ob die Konfiguration der Station auch der des Access Points entspricht. Dazu gehören auch die Authentifzierungsmethode und die Sicherheitsprotokolle. Halten Sie die Konfiguration so einfach wie möglich. Wenn Sie ein Sicherheitsprotokoll wie WPA oder WEP verwenden, können Sie testweise den Access Point auf _offene Authentifizierung_ und _keine Sicherheit_ einstellen. + Für die Fehlersuche steht man:wpa_supplicant[8] zur Verfügung. Starten Sie das Programm manuell mit der Option `-dd` und durchsuchen Sie anschließend die Systemprotokolle nach eventuellen Fehlermeldungen. * Sobald sich das Gerät mit dem Access Point verbinden kann, prüfen Sie die Netzwerkkonfiguration mit einfachen Werkzeugen wie man:ping[8]. * Zusätzlich gibt es auch zahlreiche Low-Level-Debugging-Werkzeuge. Die Ausgabe von Debugging-Informationen des 802.11 Protocol Support Layers lassen sich mit dem Programm man:wlandebug[8] aktivieren. Um beispielsweise während der Suche nach Access Points und des Aufbaus von 802.11-Verbindungen (Handshake) auftretende Systemmeldungen auf die Konsole auszugeben, verwenden Sie den folgenden Befehl: + [source,shell] .... # wlandebug -i wlan0 +scan+auth+debug+assoc net.wlan.0.debug: 0 => 0xc80000 .... + Der 802.11-Layer liefert umfangreiche Statistiken, die mit dem Werkzeug `wlanstats`, das sich in [.filename]#/usr/src/tools/tools/net80211# befindet, abgerufen werden können. Diese Statistiken sollten alle Fehler identifizieren, die im 802.11-Layer auftreten. Beachten Sie aber, dass einige Fehler bereits im darunterliegenden Gerätetreiber auftreten und daher in diesen Statistiken nicht enthalten sind. Wie Sie Probleme des Gerätetreibers identifizieren, entnehmen Sie bitte der Dokumentation des Gerätetreibers. Wenn die oben genannten Informationen nicht helfen das Problem zu klären, erstellen Sie einen Problembericht, der die Ausgabe der weiter oben genannten Werkzeuge beinhaltet. [[network-usb-tethering]] == USB Tethering Viele Mobiltelefone bieten die Möglichkeit, ihre Datenverbindung über USB (oft "Tethering" genannt) zu teilen. Diese Funktion verwendet entweder das RNDIS-, CDC- oder ein Apple(R) iPhone(R)/iPad(R)-Protokoll. * Android(TM)-Geräte benutzen in der Regel den man:urndis[4]-Treiber. * Apple(R)-Geräte benutzen den man:ipheth[4]-Treiber. * Ältere Geräte benutzen oft den man:cdce[4]-Treiber. Bevor Sie ein Gerät anschließen, laden Sie den entsprechenden Treiber in den Kernel: [source,shell] .... # kldload if_urndis # kldload if_cdce # kldload if_ipheth .... Sobald das Gerät angeschlossen ist, steht es unter ``ue``__0__ wie ein normales Netzwerkgerät zur Verfügung. Stellen Sie sicher, dass die Option "USB Tethering" auf dem Gerät aktiviert ist. Um diese Änderungen dauerhaft zu speichern und den Treiber beim Booten als Modul zu laden, müssen die entsprechenden Zeilen in [.filename]#/boot/loader.conf# konfiguriert werden: [.programlisting] .... if_urndis_load="YES" if_cdce_load="YES" if_ipteth_load="YES" .... [[network-bluetooth]] == Bluetooth Bluetooth ermöglicht die Bildung von persönlichen Netzwerken über drahtlose Verbindungen bei einer maximalen Reichweite von 10 Metern und operiert im unlizensierten 2,4-GHz-Band. Solche Netzwerke werden normalerweise spontan gebildet, wenn sich mobile Geräte, wie Mobiltelefone, Handhelds oder Notebooks miteinander verbinden. Im Gegensatz zu Wireless LAN ermöglicht Bluetooth auch höherwertige Dienste, wie FTP-ähnliche Dateiserver, Filepushing, Sprachübertragung, Emulation von seriellen Verbindungen und mehr. Dieses Kapitel beschreibt die Verwendung von USB-Bluetooth-Adaptern in FreeBSD. Weiterhin werden verschiedene Bluetooth-Protokolle und Programme vorgestellt. === Die Bluetooth-Unterstützung aktivieren Der Bluetooth-Stack von FreeBSD verwendet das man:netgraph[4]-Framework. Viele Bluetooth-USB-Adapter werden durch den man:ng_ubt[4]-Treiber unterstützt. Auf dem Chip BCM2033 von Broadcom basierende Bluetooth-Geräte werden von den Treibern man:ubtbcmfw[4] sowie man:ng_ubt[4] unterstützt. Die Bluetooth-PC-Card 3CRWB60-A von 3Com verwendet den man:ng_bt3c[4]-Treiber. Serielle sowie auf UART basierende Bluetooth-Geräte werden von man:sio[4], man:ng_h4[4] sowie man:hcseriald[8] unterstützt. Bevor ein Gerät angeschlossen wird, muss der entsprechende Treiber in den Kernel geladen werden. Hier verwendet das Gerät den man:ng_ubt[4]-Treiber: [source,shell] .... # kldload ng_ubt .... Ist das Bluetooth-Gerät beim Systemstart angeschlossen, kann das entsprechende Modul bei Booten geladen werden, indem der entsprechende Treiber in [.filename]#/boot/loader.conf# hinzugefügt wird: [.programlisting] .... ng_ubt_load="YES" .... Sobald der Treiber geladen ist, schließen Sie den USB-Adapter an. Eine Meldung ähnlich der folgenden wird auf der Konsole und in [.filename]#/var/log/messages# erscheinen: [source,shell] .... ubt0: vendor 0x0a12 product 0x0001, rev 1.10/5.25, addr 2 ubt0: Interface 0 endpoints: interrupt=0x81, bulk-in=0x82, bulk-out=0x2 ubt0: Interface 1 (alt.config 5) endpoints: isoc-in=0x83, isoc-out=0x3, wMaxPacketSize=49, nframes=6, buffer size=294 .... Verwenden Sie das Startskript zum Starten und Beenden des Bluetooth-Stacks. Es ist empfehlenswert, den Bluetooth-Stack zu beenden, bevor Sie den Adapter entfernen. Das Starten des Bluetooth-Stacks kann das Starten von man:hcsecd[8] erfordern. Wenn Sie den Bluetooth-Stack starten, erhalten Sie eine Meldung ähnlich der folgenden: [source,shell] .... # service bluetooth start ubt0 BD_ADDR: 00:02:72:00:d4:1a Features: 0xff 0xff 0xf 00 00 00 00 00 <3-Slot> <5-Slot> Max. ACL packet size: 192 bytes Number of ACL packets: 8 Max. SCO packet size: 64 bytes Number of SCO packets: 8 .... === Suche nach anderen Bluetooth-Geräten Das Host Controller Interface (HCI) bietet eine einheitliche Methode für den Zugriff auf Bluetooth-Basisband-Funktionen. In FreeBSD wird ein netgraph HCI-Knoten für jedes Bluetooth-Gerät erstellt. Weitere Einzelheiten finden Sie in man:ng_hci[4]. Eine der wichtigsten Aufgaben ist das Auffinden von sich in Reichweite befindenden Bluetooth-Geräten. Diese Funktion wird als _inquiry_ bezeichnet. Inquiry sowie andere mit HCI in Verbindung stehende Funktionen werden von man:hccontrol[8] zur Verfügung gestellt. Das folgende Beispiel zeigt, wie man herausfindet, welche Bluetooth-Geräte sich in Reichweite befinden. Eine solche Abfrage dauert nur wenige Sekunden. Beachten Sie, dass ein Gerät nur dann antwortet, wenn es sich im Modus _discoverable_ befindet. [source,shell] .... % hccontrol -n ubt0hci inquiry Inquiry result, num_responses=1 Inquiry result #0 BD_ADDR: 00:80:37:29:19:a4 Page Scan Rep. Mode: 0x1 Page Scan Period Mode: 00 Page Scan Mode: 00 Class: 52:02:04 Clock offset: 0x78ef Inquiry complete. Status: No error [00] .... `BD_ADDR` stellt, ähnlich der MAC-Adresse einer Netzwerkkarte, die eindeutige Adresse eines Bluetooth-Gerätes dar. Diese Adresse ist für die Kommunikation mit dem Gerät nötig. Es ist aber auch möglich, `BD_ADDR` einen Klartextnamen zuzuweisen. [.filename]#/etc/bluetooth/hosts# enthält Informationen über die bekannten Bluetooth-Rechner. Das folgende Beispiel zeigt, wie man den Klartextnamen eines entfernten Geräts in Erfahrung bringen kann: [source,shell] .... % hccontrol -n ubt0hci remote_name_request 00:80:37:29:19:a4 BD_ADDR: 00:80:37:29:19:a4 Name: Pav's T39 .... Wenn Sie ein entferntes Bluetooth-Gerät abfragen, wird dieses den Rechner unter dem Namen "your.host.name (ubt0)" finden. Dieser Name kann aber jederzeit geändert werden. Entfernten Geräten können Aliase in [.filename]#/etc/bluetooth/hosts# zugewiesen werden. Weitere Informationen zu [.filename]#/etc/bluetooth/hosts# finden Sie in man:bluetooth.hosts[5]. Bluetooth ermöglicht Punkt-zu-Punkt-Verbindungen an denen nur zwei Bluetooth-Geräte beteiligt sind, aber auch Punkt-zu-Multipunkt-Verbindungen, bei denen eine Verbindung von mehreren Bluetooth-Geräten gemeinsam genutzt wird. Das folgende Beispiel zeigt, wie man eine Verbindung zu einem entferntem Gerät aufbauen kann: [source,shell] .... % hccontrol -n ubt0hci create_connection BT_ADDR .... `create_connection` aktzeptiert `BT_ADDR` oder auch einen Alias aus [.filename]#/etc/bluetooth/hosts#. Das folgende Beispiel zeigt, wie man die aktiven Basisbandverbindungen des lokalen Gerätes anzeigen kann: [source,shell] .... % hccontrol -n ubt0hci read_connection_list Remote BD_ADDR Handle Type Mode Role Encrypt Pending Queue State 00:80:37:29:19:a4 41 ACL 0 MAST NONE 0 0 OPEN .... Ein _connection handle_ ist für die Beendigung einer Basisbandverbindung nützlich. Im Normalfall werden inaktive Verbindungen aber automatisch vom Bluetooth-Stack getrennt. [source,shell] .... # hccontrol -n ubt0hci disconnect 41 Connection handle: 41 Reason: Connection terminated by local host [0x16] .... Rufen Sie `hccontrol help` auf, wenn Sie eine komplette Liste aller verfügbaren HCI-Befehle benötigen. Die meisten dieser Befehle müssen nicht als `root` ausgeführt werden. === Erstmaliger Verbindungsaufbau zwischen zwei Bluetooth-Geräten (Pairing) In der Voreinstellung nutzt Bluetooth keine Authentifizierung, daher kann sich jedes Bluetoothgerät mit jedem anderen Gerät verbinden. Ein Bluetoothgerät, wie beispielsweise ein Mobiltelefon, kann jedoch für einen bestimmten Dienst, etwa eine Einwählverbindung, eine Authentifizierung anfordern. Bluetooth verwendet zu diesem Zweck _PIN-Codes_. Ein PIN-Code ist ein maximal 16 Zeichen langer ASCII-String. Damit eine Verbindung zustande kommt, muss auf beiden Geräten der gleiche PIN-Code verwendet werden. Nachdem der Code eingegeben wurde, erzeugen beide Geräte einen _link key_, der auf den Geräten gespeichert wird. Beim nächsten Verbindungsaufbau wird der zuvor erzeugte Link Key verwendet. Diesen Vorgang bezeichnet man als Pairing. Geht der Link Key auf einem Gerät verloren, muss das Pairing wiederholt werden. Der man:hcsecd[8]-Daemon verarbeitet Bluetooth-Authentifzierungsanforderungen und wird über die Datei [.filename]#/etc/bluetooth/hcsecd.conf# konfiguriert. Der folgende Ausschnitt dieser Datei zeigt die Konfiguration für ein Mobiltelefon, das den PIN-Code "1234" verwendet: [.programlisting] .... device { bdaddr 00:80:37:29:19:a4; name "Pav's T39"; key nokey; pin "1234"; } .... Von der Länge abgesehen, unterliegen PIN-Codes keinen Einschränkungen. Einige Geräte, beispielsweise Bluetooth-Headsets, haben einen festen PIN-Code eingebaut. Die Option `-d` sorgt dafür, dass der man:hcsecd[8]-Daemon im Vordergrund läuft. Dadurch kann der Ablauf einfach verfolgt werden. Stellen Sie das entfernte Gerät auf receive pairing und initiieren Sie die Bluetoothverbindung auf dem entfernten Gerät. Sie erhalten die Meldung, dass Pairing akzeptiert wurde und der PIN-Code benötigt wird. Geben Sie den gleichen PIN-Code ein, den Sie in [.filename]#hcsecd.conf# festgelegt haben. Der Computer und das entfernte Gerät sind nun miteinander verbunden. Alternativ können Sie das Pairing auch auf dem entfernten Gerät initiieren. man:hcsecd[8] kann durch das Einfügen der folgenden Zeile in [.filename]#/etc/rc.conf# beim Systemstart automatisch aktiviert werden: [.programlisting] .... hcsecd_enable="YES" .... Es folgt nun eine beispielhafte Ausgabe des man:hcsecd[8]-Daemons: [.programlisting] .... hcsecd[16484]: Got Link_Key_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', link key doesn't exist hcsecd[16484]: Sending Link_Key_Negative_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Got PIN_Code_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', PIN code exists hcsecd[16484]: Sending PIN_Code_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 .... === Einwahlverbindungen und Netzwerkverbindungen mit PPP-Profilen einrichten Ein Dial-Up Networking-Profil (DUN) kann dazu benutzt werden, ein Mobiltelefon als drahtloses Modem zu nutzen, um sich über einen Einwahlprovider mit dem Internet zu verbinden. Es kann auch dazu genutzt werden, einen Computer so zu konfigurieren, dass dieser Datenabfragen empfängt. Der Zugriff auf ein Netzwerk über ein PPP-Profil kann einen Zugriff auf das LAN für ein oder mehrere Bluetooth-Geräte bieten. Eine PC-zu-PC-Verbindung unter Verwendung einer PPP-Verbindung über eine serielle Verbindung ist ebenfalls möglich. Diese Profile werden unter FreeBSD durch man:ppp[8] sowie man:rfcomm_pppd[8] implementiert - einem Wrapper, der Bluetooth-Verbindungen unter PPP nutzbar macht. Bevor ein Profil verwendet werden kann, muss ein neuer PPP-Abschnitt in [.filename]#/etc/ppp/ppp.conf# erzeugt werden. Beispielkonfigurationen zu diesem Thema finden Sie in man:rfcomm_pppd[8]. Dieses Beispiel verwendet man:rfcomm_pppd[8], um eine Verbindung zu einem entfernten Gerät mit der `BD_ADDR 00:80:37:29:19:a4` auf dem RFCOMM-Kanal `DUN` aufzubauen: [source,shell] .... # rfcomm_pppd -a 00:80:37:29:19:a4 -c -C dun -l rfcomm-dialup .... Die aktuelle Kanalnummer des entfernten Geräts erhalten Sie über das SDP-Protokoll. Es ist auch möglich, manuell einen RFCOMM-Kanal festzulegen. In diesem Fall führt man:rfcomm_pppd[8] keine SDP-Abfrage durch. Verwenden Sie man:sdpcontrol[8], um die RFCOMM-Kanäle des entfernten Geräts herauszufinden. Der man:sdpd[8]-Server muss laufen, damit ein Netzzugriff mit dem PPPLAN-Profil möglich ist. Außerdem muss für den LAN-Client ein neuer Eintrag in [.filename]#/etc/ppp/ppp.conf# erzeugt werden. Beispielkonfigurationen zu diesem Thema finden Sie in man:rfcomm_pppd[8]. Danach starten Sie den RFCOMMPPP-Server über eine gültige RFCOMM-Kanalnummer. Der RFCOMMPPP-Server bindet dadurch den Bluetooth-LAN-Dienst an den lokalen SDP-Daemon. Das folgende Beispiel zeigt, wie man den RFCOMMPPP-Server startet. [source,shell] .... # rfcomm_pppd -s -C 7 -l rfcomm-server .... === Bluetooth-Protokolle Dieser Abschnitt gibt einen Überblick über die verschiedenen Bluetooth-Protokolle, ihre Funktionen sowie weitere Programme. ==== Das Logical Link Control and Adaptation Protocol (L2CAP) Das Logical Link Control and Adaptation Protocol (L2CAP) bietet höherwertigen Protokollen verbindungsorientierte und verbindungslose Datendienste an. L2CAP erlaubt höherwertigen Protokollen und Programmen den Versand und Empfang von L2CAP-Datenpaketen mit einer Länge von bis zu 64 Kilobytes. L2CAP arbeitet _kanal_basiert. Ein Kanal ist eine logische Verbindung innerhalb einer Basisbandverbindung. Jeder Kanal ist dabei an ein einziges Protokoll gebunden. Mehrere Geräte können an das gleiche Protokoll gebunden sein, es ist aber nicht möglich, einen Kanal an mehrere Protokolle zu binden. Jedes über einen Kanal ankommende L2CAP-Paket wird an das entsprechende höherwertige Protokoll weitergeleitet. Mehrere Kanäle können sich die gleiche Basisbandverbindung teilen. Unter FreeBSD wird eine netgraph-Gerätedatei vom Typ _l2cap_ für jedes einzelne Bluetooth-Gerät erzeugt. Diese Gerätedatei ist normalerweise mit der Bluetooth-HCI-Gerätedatei (downstream) sowie der Bluetooth-Socket-Gerätedatei (upstream) verbunden. Der Standardname für die L2CAP-Gerätedatei lautet "devicel2cap". Weitere Details finden Sie in man:ng_l2cap[4]. Ein nützlicher Befehl zum Anpingen von anderen Geräten ist man:l2ping[8]. Einige Bluetooth-Geräte senden allerdings nicht alle erhaltenen Daten zurück. Die Ausgabe `0 bytes` im folgenden Beispiel ist also kein Fehler: [source,shell] .... # l2ping -a 00:80:37:29:19:a4 0 bytes from 0:80:37:29:19:a4 seq_no=0 time=48.633 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=1 time=37.551 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=2 time=28.324 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=3 time=46.150 ms result=0 .... Das Programm man:l2control[8] liefert Informationen über L2CAP-Dateien. Das folgende Beispiel zeigt, wie man die Liste der logischen Verbindungen (Kanäle) sowie die Liste der Basisbandverbindungen abfragen kann: [source,shell] .... % l2control -a 00:02:72:00:d4:1a read_channel_list L2CAP channels: Remote BD_ADDR SCID/ DCID PSM IMTU/ OMTU State 00:07:e0:00:0b:ca 66/ 64 3 132/ 672 OPEN % l2control -a 00:02:72:00:d4:1a read_connection_list L2CAP connections: Remote BD_ADDR Handle Flags Pending State 00:07:e0:00:0b:ca 41 O 0 OPEN .... man:btsockstat[1] ist ein weiteres Diagnoseprogramm. Es funktioniert ähnlich wie man:netstat[1], arbeitet aber mit Bluetooth-Datenstrukturen. Das folgende Beispiel zeigt die gleiche Liste der logischen Verbindungen wie man:l2control[8] im vorherigen Beispiel. [source,shell] .... % btsockstat Active L2CAP sockets PCB Recv-Q Send-Q Local address/PSM Foreign address CID State c2afe900 0 0 00:02:72:00:d4:1a/3 00:07:e0:00:0b:ca 66 OPEN Active RFCOMM sessions L2PCB PCB Flag MTU Out-Q DLCs State c2afe900 c2b53380 1 127 0 Yes OPEN Active RFCOMM sockets PCB Recv-Q Send-Q Local address Foreign address Chan DLCI State c2e8bc80 0 250 00:02:72:00:d4:1a 00:07:e0:00:0b:ca 3 6 OPEN .... ==== Radio Frequency Communication (RFCOMM) Das RFCOMM-Protokoll emuliert serielle Verbindungen über das L2CAP-Protokoll. Bei RFCOMM handelt es sich um ein einfaches Transportprotokoll, das um Funktionen zur Emulation der 9poligen Schaltkreise von mit RS-232 (EIATIA-232-E) kompatiblen seriellen Ports ergänzt wurde. Es erlaubt bis zu 60 simultane Verbindungen (RFCOMM-Kanäle) zwischen zwei Bluetooth-Geräten. Eine RFCOMM-Kommunikation besteht aus zwei Anwendungen (den Kommunikationsendpunkten), die über das Kommunikationssegment miteinander verbunden sind. RFCOMM unterstützt Anwendungen, die auf serielle Ports angewiesen sind. Das Kommunikationssegment entspricht der direkten Bluetooth-Verbindung zwischen den beiden Geräten. RFCOMM kümmert sich um die direkte Verbindung von zwei Geräten, oder um die Verbindung zwischen einem Gerät und einem Modem über eine Netzwerkverbindung. RFCOMM unterstützt auch andere Konfigurationen. Ein Beispiel dafür sind Module, die drahtlose Bluetooth-Geräte mit einer verkabelten Schnittstelle verbinden können. Unter FreeBSD ist das RFCOMM-Protokoll im Bluetooth Socket-Layer implementiert. ==== Das Service Discovery Protocol (SDP) Das Service Discovery Protocol (SDP) erlaubt es Clientanwendungen, von Serveranwendungen angebotene Dienste sowie deren Eigenschaften abzufragen. Zu diesen Eigenschaften gehören die Art oder die Klasse der angebotenen Dienste sowie der Mechanismus oder das Protokoll, die zur Nutzung des Dienstes notwendig sind. SDP ermöglicht Verbindungen zwischen einem SDP-Server und einem SDP-Client. Der Server enthält eine Liste mit den Eigenschaften der vom Server angebotenen Dienste. Jeder Eintrag beschreibt jeweils einen einzigen Serverdienst. Ein Client kann diese Informationen durch eine SDP-Anforderung vom SDP-Server beziehen. Wenn der Client oder eine Anwendung des Clients einen Dienst nutzen will, muss eine separate Verbindung mit dem Dienstanbieter aufgebaut werden. SDP bietet einen Mechanismus zum Auffinden von Diensten und deren Eigenschaften an, es bietet aber keine Mechanismen zur Verwendung dieser Dienste. Normalerweise sucht ein SDP-Client nur nach Diensten, die bestimmte geforderte Eigenschaften erfüllen. Es ist aber auch möglich, anhand der Dienstbeschreibungen eine allgemeine Suche nach den von einem SDP-Server angebotenen Diensten durchzuführen. Diesen Vorgang bezeichnet man als Browsing. Der Bluetooth-SDP-Server man:sdpd[8] und der Kommandozeilenclient man:sdpcontrol[8] sind bereits in der Standardinstallation von FreeBSD enthalten. Das folgende Beispiel zeigt, wie eine SDP-Abfrage durchgeführt wird: [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec browse Record Handle: 00000000 Service Class ID List: Service Discovery Server (0x1000) Protocol Descriptor List: L2CAP (0x0100) Protocol specific parameter #1: u/int/uuid16 1 Protocol specific parameter #2: u/int/uuid16 1 Record Handle: 0x00000001 Service Class ID List: Browse Group Descriptor (0x1001) Record Handle: 0x00000002 Service Class ID List: LAN Access Using PPP (0x1102) Protocol Descriptor List: L2CAP (0x0100) RFCOMM (0x0003) Protocol specific parameter #1: u/int8/bool 1 Bluetooth Profile Descriptor List: LAN Access Using PPP (0x1102) ver. 1.0 .... Beachten Sie, dass jeder Dienst eine Liste seiner Eigenschaften, wie etwa den RFCOMM-Kanal, zurückgibt. Je nachdem, welche Dienste der Benutzer benötigt, sollten einige dieser Eigenschaften notiert werden. Einige Bluetooth-Implementationen unterstützen kein Service Browsing und geben daher eine leere Liste zurück. Ist dies der Fall, ist es dennoch möglich, nach einem bestimmten Dienst zu suchen. Das folgende Beispiel demonstriert die Suche nach dem OBEX Object Push (OPUSH) Dienst: [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec search OPUSH .... Unter FreeBSD ist es die Aufgabe des man:sdpd[8]-Servers, Bluetooth-Clients verschiedene Dienste anzubieten. Sie können diesen Server durch das Einfügen der folgenden Zeile in [.filename]#/etc/rc.conf# aktivieren: [.programlisting] .... sdpd_enable="YES" .... Nun kann der man:sdpd[8]-Daemon durch folgende Eingabe gestartet werden: [source,shell] .... # service sdpd start .... Der lokale Server, der den entfernten Clients Bluetooth-Dienste anbieten soll, bindet diese Dienste an den lokalen SDP-Daemon. Ein Beispiel für eine solche Anwendung ist man:rfcomm_pppd[8]. Einmal gestartet, wird der Bluetooth-LAN-Dienst an den lokalen SDP-Daemon gebunden. Die Liste der vorhandenen Dienste, die am lokalen SDP-Server registriert sind, lässt sich durch eine SDP-Abfrage über einen lokalen Kontrollkanal abfragen: [source,shell] .... # sdpcontrol -l browse .... ==== OBEX Object-Push (OPUSH) OBEX ist ein häufig verwendetes Protokoll für den Dateitransfer zwischen Mobilgeräten. Sein Hauptzweck ist die Kommunikation über die Infrarotschnittstelle. Es dient daher zum Datentransfer zwischen Notebooks oder PDAs sowie zum Austausch von Visitenkarten oder Kalendereinträgen zwischen Mobiltelefonen und anderen Geräten mit PIM-Funktionen. Server und Client von OBEX werden durch obexapp bereitgestellt, das als Paket oder Port package:comms/obexapp[] installiert werden kann. Mit dem OBEX-Client werden Objekte zum OBEX-Server geschickt oder angefordert. Ein Objekt kann etwa eine Visitenkarte oder ein Termin sein. Der OBEX-Client fordert über SDP die Nummer des RFCOMM-Kanals vom entfernten Gerät an. Dies kann auch durch die Verwendung des Servicenamens anstelle der RFCOMM-Kanalnummer erfolgen. Folgende Dienste werden unterstützt: `IrMC`, `FTRN` und `OPUSH`. Es ist möglich, den RFCOMM-Kanal als Nummer anzugeben. Es folgt ein Beispiel für eine OBEX-Sitzung, bei der ein Informationsobjekt vom Mobiltelefon angefordert und ein neues Objekt (hier eine Visitenkarte) an das Telefonbuch des Mobiltelefons geschickt wird: [source,shell] .... % obexapp -a 00:80:37:29:19:a4 -C IrMC obex> get telecom/devinfo.txt Success, response: OK, Success (0x20) obex> put new.vcf Success, response: OK, Success (0x20) obex> di Success, response: OK, Success (0x20) .... Um OBEX-Push-Dienste anbieten zu können, muss der sdpd-Server gestartet sein. Ein Wurzelverzeichnis, in dem alle ankommenden Objekte gespeichert werden, muss zusätzlich angelegt werden. In der Voreinstellung ist dies [.filename]#/var/spool/obex#. Starten Sie den OBEX-Server mit einer gültigen Kanalnummer. Der OBEX-Server registriert nun den OBEX-Push-Dienst mit dem lokalen SDP-Daemon. Das folgende Beispiel zeigt, wie der OBEX-Server gestartet wird: [source,shell] .... # obexapp -s -C 10 .... ==== Das Serial-Port Profil (SPP) Das Serial Port Profile (SSP) ermöglicht es Bluetooth-Geräten eine serielle Kabelverbindung zu emulieren. Anwendungen sind dadurch in der Lage, über eine virtuelle serielle Verbindung Bluetooth als Ersatz für eine Kabelverbindung zu nutzen. man:rfcomm_sppd[1] implementiert unter FreeBSD SSP und ein Pseudo-tty, das als virtuelle serielle Verbindung verwendet wird. Das folgende Beispiel zeigt, wie man eine Verbindung mit einem entfernten Serial-Port-Dienst herstellt. Ein RFCOMM-Kanal muss dabei nicht angegeben werden, da man:rfcomm_sppd[1] den Kanal über SDP abfragen kann. Um dies zu umgehen, geben Sie einen RFCOMM-Kanal auf der Kommandozeile an. [source,shell] .... # rfcomm_sppd -a 00:07:E0:00:0B:CA -t rfcomm_sppd[94692]: Starting on /dev/pts/6... /dev/pts/6 .... Sobald die Verbindung hergestellt ist, kann pseudo-tty als serieller Port verwenden werden. [source,shell] .... # cu -l /dev/pts/6 .... Das pseudo-tty wird auf der Standardausgabe ausgegeben und kann von Wrapper-Skripten gelesen werden: [.programlisting] .... PTS=`rfcomm_sppd -a 00:07:E0:00:0B:CA -t` cu -l $PTS .... === Problembehandlung Wenn FreeBSD eine neue Verbindung akzeptiert, versucht es, die Rolle zu tauschen, um zum Master zu werden. Einige ältere Geräte, die dies nicht unterstützen, können keine Verbindung aufbauen. Da der Rollentausch ausgeführt wird sobald eine neue Verbindung aufgebaut wird, ist es nicht möglich, das entfernte Gerät zu fragen ob es den Rollentausch unterstützt. Es gibt jedoch eine HCI-Option, die dieses Verhalten deaktiviert: [source,shell] .... # hccontrol -n ubt0hci write_node_role_switch 0 .... Verwenden Sie hcidump, das als Paket Port package:comms/hcidump[] installiert werden kann, um Bluetooth-Pakete anzuzeigen. Dieses Programm hat Ähnlichkeiten mit man:tcpdump[1] und kann zur Anzeige der Bluetooth-Pakete in einem Terminal, oder zur Speicherung von Paketen in einer Datei (Dump) verwendet werden. [[network-bridging]] == LAN-Kopplung mit einer Bridge Manchmal ist es nützlich, ein Netzwerk, wie ein Ethernetsegment, in separate Netzwerke aufzuteilen, ohne gleich IP-Subnetze zu erzeugen, die über einen Router miteinander verbunden sind. Ein Gerät, das zwei Netze auf diese Weise verbindet, wird als "Bridge" bezeichnet. Eine Bridge arbeitet, indem sie die MAC-Adressen der Geräte in ihren Netzwerksegmenten lernt. Der Verkehr wird nur dann zwischen zwei Segmenten weitergeleitet, wenn sich Sender und Empfänger in verschiedenen Netzwerksegmenten befinden. Jedes FreeBSD-System mit zwei Netzwerkkarten kann als Bridge fungieren. Bridging kann in den folgenden Situationen sinnvoll sein: Verbinden von Netzwerken:: Die Hauptaufgabe einer Bridge ist die Verbindung von zwei oder mehreren Netzwerksegmenten. Es gibt viele Gründe, eine hostbasierte Bridge einzusetzen, anstelle von Netzwerkkomponenten, wie beispielsweise Kabelverbindungen oder Firewalls. Eine Bridge kann außerdem ein drahtloses Gerät mit einem Kabelnetzwerk verbinden. Diese Fähigkeit der Bridge wird als HostAP-Modus bezeichnet. Die Bridge agiert in diesem Fall als Access Point für das drahtlose Gerät. Filtering / Traffic Shaping Firewall:: Eine Bridge kann eingesetzt werden, wenn Firewallfunktionen benötigt werden, ohne dabei Routing oder Network Adress Translation (NAT) zu verwenden. + Ein Beispiel dafür wäre ein kleines Unternehmen, das über DSL oder ISDN an einen ISP angebunden ist. Es verfügt über 13 erreichbare IP-Adressen und das Netzwerk besteht aus 10 Rechnern. In dieser Situation ist der Einsatz von Subnetzen sowie einer routerbasierten Firewall aufgrund der IP-Adressierung schwierig. Eine Bridge-basierte Firewall kann hingegen ohne Probleme konfiguriert werden. Netzwerküberwachung:: Eine Bridge kann zwei Netzwerksegmente miteinander verbinden und danach alle Ethernet-Rahmen überprüfen, die zwischen den beiden Netzwerksegmenten ausgetauscht werden. Dazu verwendet man entweder man:bpf[4] und man:tcpdump[1] auf dem Netzgerät der Bridge oder schickt Kopien aller Rahmen an ein zusätzliches Netzgerät, das als Span Port bekannt ist. Layer 2 VPN:: Zwei Ethernetnetzwerke können über einen IP-Link miteinander verbunden werden, indem die beiden Netzwerke über einen EtherIP-Tunnel gekoppelt werden, oder eine man:tap[4]-basierte Lösung wie OpenVPN eingesetzt wird. Layer 2 Redundanz:: Die Systeme eines Netzwerks können über das Spanning Tree Protocol (STP) redundant miteinander verbunden sein, um redundante Pfade zu blockieren. Dieser Abschnitt beschreibt, wie ein FreeBSD-System mit Hilfe von man:if_bridge[4] als Bridge konfiguriert wird. Ein netgraph-Bridge-Treiber ist ebenfalls verfügbar und wird in man:ng_bridge[4] beschrieben. [NOTE] ==== Paketfilter können mit allen Firewallpaketen verwendet werden, die das man:pfil[9]-Framework benutzen. Eine Bridge kann auch als Traffic Shaper verwendet werden, wenn Sie man:altq[4] oder man:dummynet[4] einsetzen. ==== === Die Bridge aktivieren In FreeBSD handelt es sich bei man:if_bridge[4] um ein Kernelmodul, das von man:ifconfig[8] automatisch geladen wird, wenn eine Bridge-Schnittstelle erzeugt wird. Es ist auch möglich, die Unterstützung für den Treiber in den Kernel zu kompilieren, indem die Zeile `device if_bridge` in die Kernelkonfigurationsdatei hinzugefügt wird. Eine Bridge wird durch das Klonen von Schnittstellen erzeugt. Um eine Bridge zu erzeugen, verwenden Sie: [source,shell] .... # ifconfig bridge create bridge0 # ifconfig bridge0 bridge0: flags=8802 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:00:00:00:00:00 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:00:00:00:00:00 priority 0 ifcost 0 port 0 .... Wenn eine Bridge erzeugt wird, erhält sie automatisch eine zufällig generierte Ethernet-Adresse. Die Parameter `maxaddr` sowie `timeout` legen fest, wie viele MAC-Adressen die Bridge in ihrer Forward-Tabelle halten kann und wie viele Sekunden jeder Eintrag erhalten bleiben soll, nachdem er zuletzt verwendet wurde. Die restlichen Parameter sind für die Konfiguration von STP notwendig. Im nächsten Schritt werden die Schnittstellen, die die Bridge verbinden soll, zugewiesen. Damit die Bridge Datenpakete weiterleiten kann, müssen sowohl die Bridge als auch die Schnittstellen der zu verbindenden Netzwerksegmente aktiviert sein: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 up # ifconfig fxp0 up # ifconfig fxp1 up .... Jetzt ist die Bridge in der Lage, Ethernet-Rahmen zwischen den Schnittstellen [.filename]#fxp0# und [.filename]#fxp1# weiterzuleiten. Um diese Konfiguration beim Systemstart automatisch zu aktivieren, müssen die folgenden Zeilen in [.filename]#/etc/rc.conf# hinzugefügt werden: [.programlisting] .... cloned_interfaces="bridge0" ifconfig_bridge0="addm fxp0 addm fxp1 up" ifconfig_fxp0="up" ifconfig_fxp1="up" .... Wenn die Bridge eine IP-Adresse benötigt, muss diese der Schnittstelle der Bridge zugewiesen werden und nicht der Schnittstelle der gekoppelten Netzwerksegmente. Die IP-Adresse kann manuell gesetzt, oder über DHCP bezogen werden. Dieses Beispiel verwendet eine statische IP-Adresse: [source,shell] .... # ifconfig bridge0 inet 192.168.0.1/24 .... Es ist auch möglich der Bridge-Schnittstelle eine IPv6-Adresse zuzuweisen. Um die Änderungen dauerhaft zu speichern, fügen Sie die Adressinformationen in [.filename]#/etc/rc.conf# ein. [NOTE] ==== Nachdem ein Paketfilter aktiviert wurde, können Datenpakete, die von den Schnittstellen der gekoppelten Netzwerksegmente gesendet und empfangen werden, über die Bridge weitergeleitet oder nach bestimmten Regeln gefiltert oder auch komplett geblockt werden. Ist die Richtung des Paketflusses wichtig, ist es am besten, eine Firewall auf den Schnittstellen der einzelnen Netzwerksegmente einzurichten und nicht auf der Bridge selbst. Eine Bridge verfügt über verschiedene Optionen zur Weiterleitung von Nicht-IP- und IP-Paketen, sowie Paketfilterung auf Layer 2 mittels man:ipfw[8]. Weitere Informationen finden Sie in man:if_bridge[4]. ==== === Spanning Tree aktivieren Damit ein Ethernet-Netzwerk richtig funktioniert, kann nur ein aktiver Pfad zwischen zwei Geräten existieren. Das STP-Protokoll erkennt Schleifen in einer Netzwerktopologie und setzt redundante Pfade in einen blockierten Zustand. Sollte eine der aktiven Verbindungen ausfallen, berechnet STP einen anderen Baum und ermöglicht es dann einem blockierten Pfad, alle Netzwerkverbindungen wiederherzustellen. Das Rapid Spanning Tree Protocol (RSTP oder 802.1w), ist abwärtskompatibel zum veralteten STP. RSTP arbeitet schneller und tauscht Informationen mit benachbarten Switchen aus, um Pakete korrekt weiterzuleiten und eine Schleifenbildung zu verhindern. FreeBSD unterstützt die Betriebsmodi RSTP und STP, wobei RSTP als Standardmodus voreingestellt ist. STP kann auf den Schnittstellen der durch die Bridge verbundenen Netzwerksegmente mittels man:ifconfig[8] aktiviert werden. Für eine Bridge, die die Schnittstellen [.filename]#fxp0# und [.filename]#fxp1# verbindet, aktivieren Sie STP wie folgt: [source,shell] .... # ifconfig bridge0 stp fxp0 stp fxp1 bridge0: flags=8843 metric 0 mtu 1500 ether d6:cf:d5:a0:94:6d id 00:01:02:4b:d4:50 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 0 port 0 member: fxp0 flags=1c7 port 3 priority 128 path cost 200000 proto rstp role designated state forwarding member: fxp1 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role designated state forwarding .... Diese Bridge hat die Spanning-Tree-ID `00:01:02:4b:d4:50` und die Priorität `32768`. Da diese ID mit der `Root-ID` identisch ist, handelt es sich um die Root-Bridge dieses Netzwerks. Auf einer anderen Bridge des Netzwerks ist STP ebenfalls aktiviert: [source,shell] .... bridge0: flags=8843 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:13:d4:9a:06:7a priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4 member: fxp0 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role root state forwarding member: fxp1 flags=1c7 port 5 priority 128 path cost 200000 proto rstp role designated state forwarding .... Die Zeile `root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4` zeigt an, dass die Root-Bridge die ID `00:01:02:4b:d4:50` hat. Die Pfadkosten hin zur Root-Bridge betragen `400000`, wobei der Pfad zur Root-Bridge über `port 4` geht, der wiederum der Schnittstelle [.filename]#fxp0# entspricht. === Parameter der Bridge-Schnittstelle Einige Parameter von `ifconfig` dienen ausschließlich der Konfiguration von Bridge-Schnittstellen. Dieser Abschnitt fasst die Verwendung dieser Parameter zusammen. Die vollständige Liste der verfügbaren Parameter wird in man:ifconfig[8] beschrieben. private:: Eine private Schnittstelle leitet keine Daten an einen Port weiter, bei dem es sich ebenfalls um eine private Schnittstelle handelt. Der Datenverkehr wird dabei komplett blockiert, auch Ethernet-Rahmen und ARP-Pakete werden nicht weitergeleitet. Wollen Sie hingegen nur spezifische Datenpakete blockieren, sollten Sie eine Firewall einsetzen. span:: Ein Span Port übertragt eine Kopie jedes Ethernet-Rahmens, der an der Bridge ankommt. Auf einer Bridge können beliebig viele Span Ports festgelegt werden. Wird eine Schnittstelle als Span Port konfiguriert, kann sie nicht mehr als normaler Bridge-Port verwendet werden. Eine derartige Konfiguration ist beispielsweise sinnvoll, um den Datenverkehr, der in einem Netzwerk über die Bridge läuft, auf einen Rechner zu übertragen, der mit einem Span Port der Bridge verbunden ist. Um beispielsweise eine Kopie aller Ethernet-Rahmen über die Schnittstelle [.filename]#fxp0# zu übertragen: + [source,shell] .... # ifconfig bridge0 span fxp4 .... sticky:: Wenn die Schnittstelle eines über eine Bridge verbundenen Netzwerksegments als sticky gekennzeichnet wird, werden alle dynamisch gelernten Adressen als statische Adressen behandelt, sobald sie in den Forward-Cache der Bridge aufgenommen wurden. Sticky-Einträge werden niemals aus dem Cache entfernt oder ersetzt. Selbst dann nicht, wenn die Adresse von einer anderen Schnittstelle verwendet wird. Sie können dadurch die Vorteile statischer Adresseinträge nutzen, ohne die Forward-Tabelle vor dem Einsatz der Bridge mit statischen Einträgen füllen zu müssen. Clients, die sich in einem bestimmten von der Bridge verwalteten Segmente befinden, können dabei nicht in ein anderes Segment wechseln. + Ein Beispiel für den Einsatz von Sticky-Adressen ist die Kombination einer Bridge mit mehreren VLANs, um einen Router zu konfigurieren, der einzelne Kundennetzwerke voneinander trennt, ohne dabei IP-Adressbereiche zu verschwenden. Für das folgende Beispiel nehmen wir an, dass sich der Client `CustomerA` im VLAN `vlan100` und der Client `CustomerB` im VLAN `vlan101` befinden. Die Bridge hat die IP-Adresse `192.168.0.1`: + [source,shell] .... # ifconfig bridge0 addm vlan100 sticky vlan100 addm vlan101 sticky vlan101 # ifconfig bridge0 inet 192.168.0.1/24 .... + In diesem Beispiel sehen beide Clients `192.168.0.1` als das Default-Gateway. Da der Brücken-Cache _sticky_ ist, sind Sie nicht dazu in der Lage, die MAC-Adresse des anderen Kunden zu spoofen und dessen Datenverkehr abzufangen. + Sie können die Kommunikation zwischen den VLANs vollständig unterbinden, wenn Sie private Schnittstellen oder eine Firewall einsetzen: + [source,shell] .... # ifconfig bridge0 private vlan100 private vlan101 .... + Die Kunden sind nun komplett voneinander isoliert und der komplette `/24`-Adressbereich kann zugewiesen werden, ohne dass Subnetze eingesetzt werden. + Die maximale mögliche Anzahl an eindeutigen MAC-Adressen hinter einer Schnittstelle kann festgelegt werden. Sobald das Limit erreicht ist, werden Pakete mit einer unbekannten Quell-Adresse solange verworfen, bis ein existierender Eintrag gelöscht wird oder abläuft. + Das folgende Beispiel setzt die maximale Anzahl von Netzgeräten für `CustomerA` für das VLAN `vlan100` auf 10. + [source,shell] .... # ifconfig bridge0 ifmaxaddr vlan100 10 .... Die Bridge unterstützt auch den Monitormodus. Dabei werden alle Pakete verworfen, nachdem sie von man:bpf[4] verarbeitet wurden. In diesem Modus erfolgt keine weitere Bearbeitung und auch keine Weiterleitung von Datenpaketen. Es ist daher möglich, die Eingabe von zwei oder mehr Netzwerkschnittstellen in einen einzigen gemeinsamen man:bpf[4]-Stream zu vereinen. Ein solcher Datenstrom ist beispielsweise nützlich, um den Datenverkehr für "network taps" zu rekonstruieren, die ihre RX/TX-Signale über verschiedene Schnittstellen senden. Um beispielsweise die Eingabe von vier Netzwerkschnittstellen in einzigen gemeinsamen Datenstrom zu vereinen: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 addm fxp2 addm fxp3 monitor up # tcpdump -i bridge0 .... === SNMP-Monitoring Die Schnittstelle der Bridge sowie die STP-Parameter können durch den im Basissystem enthaltenen man:bsnmpd[1] überwacht werden. Die exportierten Bridge-MIBs entsprechen den IETF-Standards, daher kann ein beliebiger SNMP-Client oder ein beliebiges Monitoring-Werkzeug eingesetzt werden, um die benötigten Daten zu erhalten. Um das Monitoring auf der Bridge zu aktivieren, kommentieren Sie diese Zeile in [.filename]#/etc/snmpd.config# aus, indem Sie das Zeichen `#` entfernen: [.programlisting] .... begemotSnmpdModulePath."bridge" = "/usr/lib/snmp_bridge.so" .... Weitere Konfigurationsparameter wie Community-Namen und Zugriffslisten müssen ebenfalls in dieser Datei angepasst werden. Weitere Informationen finden Sie in man:bsnmpd[1] und man:snmp_bridge[3]. Nachdem die Änderungen gespeichert wurden, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# hinzu: [.programlisting] .... bsnmpd_enable="YES" .... Danach starten Sie man:bsnmpd[1]: [source,shell] .... # service bsnmpd start .... Die folgenden Beispiele verwenden das Softwarepaket Net-SNMP (package:net-mgmt/net-snmp[]), um die Bridge vom Client aus abzufragen. Alternativ kann auch der Port package:net-mgmt/bsnmptools[] benutzt werden. Auf dem SNMP-Client müssen danach die folgenden Zeilen in [.filename]#$HOME/.snmp/snmp.conf# hinzugefügt werden, um die MIB-Definitionen der Bridge in Net-SNMP zu importieren: [.programlisting] .... mibdirs +/usr/shared/snmp/mibs mibs +BRIDGE-MIB:RSTP-MIB:BEGEMOT-MIB:BEGEMOT-BRIDGE-MIB .... Um eine einzelne Bridge über den IETF BRIDGE-MIB (RFC4188) zu überwachen: [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com mib-2.dot1dBridge BRIDGE-MIB::dot1dBaseBridgeAddress.0 = STRING: 66:fb:9b:6e:5c:44 BRIDGE-MIB::dot1dBaseNumPorts.0 = INTEGER: 1 ports BRIDGE-MIB::dot1dStpTimeSinceTopologyChange.0 = Timeticks: (189959) 0:31:39.59 centi-seconds BRIDGE-MIB::dot1dStpTopChanges.0 = Counter32: 2 BRIDGE-MIB::dot1dStpDesignatedRoot.0 = Hex-STRING: 80 00 00 01 02 4B D4 50 ... BRIDGE-MIB::dot1dStpPortState.3 = INTEGER: forwarding(5) BRIDGE-MIB::dot1dStpPortEnable.3 = INTEGER: enabled(1) BRIDGE-MIB::dot1dStpPortPathCost.3 = INTEGER: 200000 BRIDGE-MIB::dot1dStpPortDesignatedRoot.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedCost.3 = INTEGER: 0 BRIDGE-MIB::dot1dStpPortDesignatedBridge.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedPort.3 = Hex-STRING: 03 80 BRIDGE-MIB::dot1dStpPortForwardTransitions.3 = Counter32: 1 RSTP-MIB::dot1dStpVersion.0 = INTEGER: rstp(2) .... Der Wert der Variable `dot1dStpTopChanges.0` ist hier 2, die STP-Topologie der Bridge wurde also bereits zweimal geändert. Unter einer Änderung versteht man die Anpassung eines oder mehrerer Links und die Kalkulation eines neuen Baums. Der Wert der Variable `dot1dStpTimeSinceTopologyChange.0` gibt an, wann dies zuletzt geschah. Um mehrere Bridge-Schnittstellen zu überwachen, kann der private BEGEMOT-BRIDGE-MIB eingesetzt werden: [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com enterprises.fokus.begemot.begemotBridge BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge0" = STRING: bridge0 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge2" = STRING: bridge2 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge0" = STRING: e:ce:3b:5a:9e:13 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge2" = STRING: 12:5e:4d:74:d:fc BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge0" = INTEGER: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge2" = INTEGER: 1 ... BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge0" = Timeticks: (116927) 0:19:29.27 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge2" = Timeticks: (82773) 0:13:47.73 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge0" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge2" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge0" = Hex-STRING: 80 00 00 40 95 30 5E 31 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge2" = Hex-STRING: 80 00 00 50 8B B8 C6 A9 .... Um die über den `mib-2.dot1dBridge`-Subtree überwachte Bridge-Schnittstelle zu ändern: [source,shell] .... % snmpset -v 2c -c private bridge1.example.com BEGEMOT-BRIDGE-MIB::begemotBridgeDefaultBridgeIf.0 s bridge2 .... [[network-aggregation]] == Link-Aggregation und Failover Die von FreeBSD unterstützte man:lagg[4]-Schnittstelle erlaubt die Gruppierung von mehreren Netzwerkadaptern als eine virtuelle Schnittstelle, mit dem Ziel, Ausfallsicherheit (Failover) und Link Aggregation bereitzustellen. Bei Failover kann der Verkehr auch dann weiter fließen, wenn nur eine Schnittstelle verfügbar ist. Link Aggregation funktioniert am besten mit Switches, die LCAP unterstützen, da dieses Protokoll den Datenverkehr bidirektional verteilt, während es auch auf den Ausfall einzelner Verbindungen reagiert. Die von der lagg-Schnittstelle unterstützten Protokolle bestimmen, welche Ports für den ausgehenden Datenverkehr benutzt werden, und ob ein bestimmter Port eingehenden Datenverkehr akzeptiert. Die folgenden Protokolle werden von man:lagg[4] unterstützt: Failover (Ausfallsicherheit):: Dieser Modus sendet und empfängt Datenverkehr nur auf dem Masterport. Sollte der Masterport nicht zur Verfügung stehen, wird der nächste aktive Port verwendet. Der zuerst hinzugefügte Adapter der virtuellen Schnittstelle wird zum Masterport, jeder weitere Adapter dient als Gerät zur Ausfallsicherheit. Wenn ein Failover auf einem Nicht-Master Port stattfindet, wird der ursprüngliche Port wieder zum Master-Port, sobald er wieder verfügbar ist. fec / loadbalance (Lastverteilung):: Cisco(R) Fast EtherChannel(R) (FEC) findet sich auf älteren Cisco(R) Switches. Es bietet eine statische Konfiguration und handelt weder Aggregation mit der Gegenstelle aus, noch werden Frames zur Überwachung der Verbindung ausgetauscht. Wenn der Switch LACP unterstützt, sollte diese Option auch verwendet werden. lacp:: Das IEEE(R) 802.3ad Link-Aggregation Control Protokoll (LACP). Mit LACP wird eine Menge von aggregierbaren Verbindungen mit der Gegenstelle in einer oder mehreren Link Aggregated Groups (LAG) ausgehandelt. Jede LAG besteht aus Ports der gleichen Geschwindigkeit, eingestellt auf Voll-Duplex-Betrieb. Der Verkehr wird über die Ports in der LAG mit der größten Gesamtgeschwindigkeit balanciert. Typischerweise gibt es nur eine LAG, die alle Ports enthält. Im Falle von Änderungen in der physischen Anbindung wird LACP schnell zu einer neuen Konfiguration konvergieren. + LACP balanciert ausgehenden Verkehr über die aktiven Ports basierend auf der gehashten Protokollheaderinformation und akzeptiert eingehenden Verkehr auf jedem aktiven Port. Der Hash beinhaltet die Ethernet-Quell- und Zieladresse, und, soweit verfügbar, den VLAN-Tag, sowie die IPv4 oder IPv6 Quell- und Zieladresse. roundrobin:: Dieser Modus verteilt ausgehenden Verkehr mittels einer Round-Robin-Zuteilung über alle aktiven Ports und akzeptiert eingehenden Verkehr auf jedem aktiven Port. Da dieser Modus die Reihenfolge von Ethernet-Rahmen verletzt, sollte er mit Vorsicht eingesetzt werden. === Beispiele Dieser Abschnitt zeigt, wie man einen Cisco(R) Switch und ein FreeBSD-System für LACP Load Balancing konfiguriert. Weiterhin wird gezeigt, wie man zwei Ethernet-Schnittstellen, sowie eine Ethernet- und eine Drahtlos-Schnittstelle für den Failover-Modus konfigurieren kann. [[networking-lacp-aggregation-cisco]] .LACP Aggregation mit einem Cisco(R) Switch [example] ==== Dieses Beispiel verbindet zwei man:fxp[4] Ethernet-Schnittstellen einer FreeBSD-Maschine zu den ersten zwei Ethernet-Ports auf einem Cisco(R) Switch als eine einzelne, lastverteilte und ausfallsichere Verbindung. Weitere Adapter können hinzugefügt werden, um den Durchsatz zu erhöhen und die Ausfallsicherheit zu steigern. Ersetzen Sie die Namen der Cisco(R)-Ports, Ethernet-Geräte, channel-group Nummern und IP-Adressen im Beispiel durch Namen, die mit Ihrer lokalen Konfiguration übereinstimmen. Da die Reihenfolge der Frames bei Ethernet zwingend eingehalten werden muss, fließt auch jeglicher Verkehr zwischen zwei Stationen über den gleichen physischen Kanal, was die maximale Geschwindigkeit der Verbindung auf die eines einzelnen Adapters beschränkt. Der Übertragungsalgorithmus versucht, so viele Informationen wie möglich zu verwenden, um die verschiedenen Verkehrsflüsse zu unterscheiden und balanciert diese über die verfügbaren Adapter. Fügen Sie auf dem Cisco(R)-Switch die Adapter _FastEthernet0/1_ und _FastEthernet0/2_ zu der channel-group _1_ hinzu: [source,shell] .... interface FastEthernet0/1 channel-group 1 mode active channel-protocol lacp ! interface FastEthernet0/2 channel-group 1 mode active channel-protocol lacp .... Erstellen Sie auf der FreeBSD Maschine die man:lagg[4]-Schnittstelle unter Verwendung von _fxp0_ und _fxp1_ und starten Sie die Schnittstelle mit der IP-Adresse _10.0.0.3/24_: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24 .... Überprüfen Sie den Status der virtuellen Schnittstelle: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.3 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto lacp laggport: fxp1 flags=1c laggport: fxp0 flags=1c .... Ports, die als _ACTIVE_ markiert sind, sind Teil der aktiven Aggregations-Gruppe, die mit dem Switch ausgehandelt wurde. Der Verkehr wird über diese Gruppe übertragen und empfangen. Benutzen Sie man:ifconfig[8] mit `-v`, um sich die LAG-Bezeichner anzeigen zu lassen. Um den Status der Ports auf dem Switch anzuzeigen, benutzen Sie `show lacp neighbor`: [source,shell] .... switch# show lacp neighbor Flags: S - Device is requesting Slow LACPDUs F - Device is requesting Fast LACPDUs A - Device is in Active mode P - Device is in Passive mode Channel group 1 neighbors Partner's information: LACP port Oper Port Port Port Flags Priority Dev ID Age Key Number State Fa0/1 SA 32768 0005.5d71.8db8 29s 0x146 0x3 0x3D Fa0/2 SA 32768 0005.5d71.8db8 29s 0x146 0x4 0x3D .... Benutzen Sie `show lacp neighbor detail`, um weitere Informationen zu erhalten. Damit diese Konfiguration auch nach einem Neustart erhalten bleibt, fügen Sie auf dem FreeBSD-System folgende Einträge in [.filename]#/etc/rc.conf# hinzu: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0 ifconfig_lagg0="laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24" .... ==== [[networking-lagg-failover]] .Ausfallsicherer Modus [example] ==== Der ausfallsichere Modus kann verwendet werden, um zu einer zweiten Schnittstelle zu wechseln, sollte die Verbindung mit der Master-Schnittstelle ausfallen. Um den ausfallsicheren Modus zu konfigurieren, aktivieren Sie zunächst die zugrunde liegenden physikalischen Schnittstellen. Erstellen Sie dann die man:lagg[4]-Schnittstelle mit _fxp0_ als Master-Schnittstelle und _fxp1_ als sekundäre Schnittstelle. Der virtuellen Schnittstelle wird die IP-Adresse _10.0.0.15/24_ zugewiesen: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24 .... Die virtuelle Schnittstelle sollte in etwa so aussehen: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.15 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto failover laggport: fxp1 flags=0<> laggport: fxp0 flags=5 .... Der Verkehr wird auf _fxp0_ übertragen und empfangen. Wenn die Verbindung auf _fxp0_ abbricht, wird _fxp1_ die Verbindung übernehmen. Sobald die Verbindung auf der Master-Schnittstelle wiederhergestellt ist, wird diese wieder als aktive Schnittstelle genutzt. Damit diese Konfiguration auch nach einem Neustart erhalten bleibt, fügen Sie folgende Einträge in [.filename]#/etc/rc.conf# hinzu: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0 ifconfig_lagg0="laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24" .... ==== [[networking-lagg-wired-and-wireless]] .Failover Modus zwischen Ethernet- und drahtlosen Schnittstellen [example] ==== Für Laptop-Benutzer ist es normalerweise wünschenswert, "wireless" als sekundäre Schnittstelle einzurichten, die verwendet wird, wenn die Ethernet-Verbindung nicht verfügbar ist. Mit man:lagg[4] ist es möglich, ein Failover mit einer IP-Adresse zu konfigurieren, welches die Ethernet-Verbindung aus Performance- und Sicherheitsgründen bevorzugt, während es gleichzeitig möglich bleibt, Daten über die drahtlose Verbindung zu übertragen. Dies wird erreicht, indem die MAC-Adresse der Ethernet-Schnittstelle mit der MAC Adresse der drahtlosen Schnittstelle überschrieben wird. [NOTE] **** Theoretisch kann die Ethernet- oder die drahtlose MAC-Adresse so geändert werden, dass sie mit der jeweils anderen Adresse übereinstimmt. Bei einigen drahtlosen Schnittstellen fehlt jedoch die Unterstützung für das Überschreiben der MAC-Adresse. Daher wird empfohlen, die MAC-Adresse der Ethernet-Schnittstelle für diesen Zweck zu überschreiben. **** [NOTE] **** Wenn der Treiber für die drahtlose Schnittstelle nicht im `GENERIC`-Kernel oder in einem angepassten Kernel enthalten ist, kann unter FreeBSD {rel121-current} mit `_driver__load="YES"` die entsprechende [.filename]#.ko#-Datei in [.filename]#/boot/loader.conf# geladen werden. Dann muss das System neu gestartet werden. Ein anderer, besserer Weg ist es, den Treiber über [.filename]#/etc/rc.conf# zu laden, indem Sie ihn zu `kld_list` (siehe man:rc.conf[5]) hinzufügen und dann das System neu starten. Dies ist notwendig, da sonst der Treiber zum Zeitpunkt der Konfiguration der man:lagg[4]-Schnittstelle noch nicht geladen ist. **** In diesem Beispiel ist die Ethernet-Schnittstelle _re0_ der Master und die drahtlose Schnittstelle _wlan0_ der Failover. Die Schnittstelle _wlan0_ wurde aus der physischen Schnittstelle _ath0_ erstellt, und die Ethernet-Schnittstelle wird mit der MAC-Adresse der drahtlosen Schnittstelle konfiguriert. Im ersten Schritt wird die MAC-Adresse der drahtlosen Schnittstelle ermittelt: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether b8:ee:65:5b:32:59 groups: wlan ssid Bbox-A3BD2403 channel 6 (2437 MHz 11g ht/20) bssid 00:37:b7:56:4b:60 regdomain ETSI country FR indoor ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 2:128-bit txpower 30 bmiss 7 scanvalid 60 protmode CTS ampdulimit 64k ampdudensity 8 shortgi -stbctx stbcrx -ldpc wme burst roaming MANUAL media: IEEE 802.11 Wireless Ethernet MCS mode 11ng status: associated nd6 options=29 .... Ersetzen Sie _ath0_ durch den Namen der drahtlosen Schnittstelle. Die `ether`-Zeile wird die MAC-Adresse der angegebenen Schnittstelle enthalten. Ändern Sie nun die MAC-Adresse der zugrunde liegenden Ethernet-Schnittstelle: [source,shell] .... # ifconfig re0 ether b8:ee:65:5b:32:59 .... Starten Sie die drahtlose Schnittstelle, aber ohne eine IP-Adresse zu setzen. Ersetzen Sie _FR_ durch den entsprechenden Ländercode: [source,shell] .... # ifconfig wlan0 create wlandev iwn0 country FR ssid my_router up .... Stellen Sie sicher, dass die _re0_-Schnittstelle aktiv ist. Erstellen Sie die man:lagg[4]-Schnittstelle mit _re0_ als Master und _wlan0_ als Failover: [source,shell] .... # ifconfig re0 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport re0 laggport wlan0 .... Die virtuelle Schnittstelle sollte in etwa so aussehen: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether b8:ee:65:5b:32:59 laggproto failover lagghash l2,l3,l4 laggport: re0 flags=5 laggport: wlan0 flags=0<> groups: lagg media: Ethernet autoselect status: active .... Starten Sie dann den DHCP-Client, um eine IP-Adresse zu erhalten: [source,shell] .... # dhclient lagg0 .... Damit diese Konfiguration auch nach einem Neustart erhalten bleibt, fügen Sie folgende Einträge in [.filename]#/etc/rc.conf# hinzu: [.programlisting] .... ifconfig_re0="ether b8:ee:65:5b:32:59" wlans_ath0="wlan0" ifconfig_wlan0="WPA" create_args_wlan0="country FR" cloned_interfaces="lagg0" ifconfig_lagg0="up laggproto failover laggport re0 laggport wlan0 DHCP" .... ==== [[network-diskless]] == Plattenloser Betrieb mit PXE Das Intel(R) Preboot eXecution Environment (PXE) erlaubt es dem Betriebssystem über das Netzwerk zu starten. Zum Beispiel kann ein FreeBSD-System, ohne lokale Festplatte, über das Netzwerk gestartet und betrieben werden. Die Dateisysteme werden dabei über einen NFS-Server eingehangen. PXE-Unterstützung steht in der Regel im BIOS zur Verfügung. Um PXE beim Systemstart zu verwenden, müssen Sie im BIOS des Rechners die Option `Über das Netzwerk starten` aktivieren. Alternativ können Sie während der PC-Initialisierung auch eine Funktionstaste drücken. Um die notwendigen Dateien für ein Betriebssystem für den Start über das Netzwerk bereitzustellen, benötigt ein PXE-Setup einen richtig konfigurierten DHCP-, TFTP- und NFS-Server, wobei: * Die initialen Parameter, wie IP-Adresse, Dateiname und Speicherort der ausführbaren Bootdateien, Servername sowie Root-Pfad vom DHCP-Server bezogen werden. * Der Loader für das Betriebssystem über TFTP gestartet wird. * Die Dateisysteme über NFS geladen werden. Sobald das Gastsystem über PXE startet, erhält es vom DHCP-Server Informationen, wo der initiale Bootloader per TFTP zu bekommen ist. Nachdem das Gastsystem diese Informationen erhalten hat, lädt es den Bootloader über TFTP herunter und führt diesen anschließend aus. In FreeBSD ist [.filename]#/boot/pxeboot# der Bootloader. Nachdem [.filename]#/boot/pxeboot# ausgeführt und der FreeBSD-Kernel geladen wurde, wird mit dem Rest der FreeBSD-Bootsequenz, wie in crossref:boot[boot,FreeBSDs Bootvorgang] beschrieben, fortgefahren. Dieser Abschnitt beschreibt, wie Sie diese Dienste auf einem FreeBSD-System so konfigurieren, sodass andere Systeme FreeBSD über PXE starten können. Weitere Informationen finden Sie in man:diskless[8]. [CAUTION] ==== Wie beschrieben, ist das System, welches diese Dienste bereitstellt, unsicher. Daher sollte es in einem geschützten Bereich des Netzwerks aufgestellt und von anderen Hosts als nicht vertrauenswürdig eingestuft werden. ==== [[network-pxe-nfs]] === Konfiguration der PXE-Umgebung Die in diesem Abschnitt dargestellten Schritte konfigurieren die in FreeBSD enthaltenen NFS- und TFTP-Server. Der folgende Abschnitt beschreibt die Installation und Konfiguration des DHCP-Servers. In diesem Beispiel verwenden wir [.filename]#/b/tftpboot/FreeBSD/install#, welches die Dateien für PXE-Benutzer enthält. Es ist wichtig, dass dieses Verzeichnis existiert und das der gleiche Verzeichnisname ebenfalls in [.filename]#/etc/inetd.conf# und [.filename]#/usr/local/etc/dhcpd.conf# gesetzt wird. [.procedure] . Erstellen Sie das Root-Verzeichnis, welches eine FreeBSD-Installation enthält und über NFS eingehangen werden kann: + [source,shell] .... # export NFSROOTDIR=/b/tftpboot/FreeBSD/install # mkdir -p ${NFSROOTDIR} .... . Aktivieren Sie den NFS-Server, indem Sie folgende Zeile in [.filename]#/etc/rc.conf# hinzufügen: + [.programlisting] .... nfs_server_enable="YES" .... + Exportieren Sie das Root-Verzeichnis über NFS, indem Sie folgende Zeile in [.filename]#/etc/exports# hinzufügen: + [.programlisting] .... /b -ro -alldirs -maproot=root .... . Starten Sie den NFS-Server: + [source,shell] .... # service nfsd start .... . Aktivieren Sie man:inetd[8], indem Sie folgende Zeile in [.filename]#/etc/rc.conf# hinzufügen: + [.programlisting] .... inetd_enable="YES" .... . Kommentieren Sie die folgende Zeile in [.filename]#/etc/inetd.conf# aus, indem Sie sicherstellen, dass die Zeile nicht mit einem `#`-Zeichen beginnt: + [.programlisting] .... tftp dgram udp wait root /usr/libexec/tftp tftp -l -s /b/tftpboot .... + [NOTE] ==== Einige PXE-Versionen benötigen die TCP-Version von TFTP. In diesem Fall können Sie die zweite `tftp`-Zeile, welche `stream tcp` enthält, auskommentieren. ==== . Starten Sie man:inetd[8]: + [source,shell] .... # service inetd start .... . Installieren Sie das Basissystem nach [.filename]#${NFSROOTDIR}#, indem Sie die offiziellen Archive entpacken, oder ein neues Basissystem und einen FreeBSD-Kernel erstellen. Detaillierte Anweisungen hierzu finden Sie im crossref:cutting-edge[makeworld,“FreeBSD aus den Quellen aktualisieren”]. Vergessen Sie jedoch nicht `DESTDIR=_${NFSROOTDIR}_` hinzuzufügen, wenn Sie die Kommandos `make installkernel` und `make installworld` ausführen. . Testen Sie den TFTP-Server und vergewissern Sie sich, dass Sie den Bootloader herunterladen können, der über PXE bereitgestellt wird: + [source,shell] .... # tftp localhost tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... . Bearbeiten Sie [.filename]#${NFSROOTDIR}/etc/fstab# und erstellen Sie einen Eintrag, um das Root-Dateisystem über NFS einzuhängen: + [.programlisting] .... # Device Mountpoint FSType Options Dump Pass$ myhost.example.com:/b/tftpboot/FreeBSD/install / nfs ro 0 0 .... + Ersetzen Sie _myhost.example.com_ durch den Hostnamen oder die IP-Adresse des NFS-Servers. In diesem Beispiel wird das Root-Dateisystem schreibgeschützt eingehangen, um ein potenzielles Löschen des Inhalts durch die NFS-Clients zu verhindern. . Setzen Sie das root-Passwort in der PXE-Umgebung für Client-Maschinen, die über PXE starten: + [source,shell] .... # chroot ${NFSROOTDIR} # passwd .... . Falls erforderlich, aktivieren Sie man:ssh[1] root-Logins für Client-Maschinen, die über PXE starten, indem Sie die Option `PermitRootLogin` in [.filename]#${NFSROOTDIR}/etc/ssh/sshd_config# aktivieren. Dies ist in man:sshd_config[5] dokumentiert. . Führen Sie alle weiteren Anpassungen der PXE-Umgebung in [.filename]#${NFSROOTDIR}# durch, wie zum Beispiel die Installation weiterer Pakete, oder dass Bearbeiten der Passwortdatei mit man:vipw[8]. Booten Sie von einem NFS-Root-Volume, so erkennt [.filename]#/etc/rc# dies und startet daraufhin das [.filename]#/etc/rc.initdiskless# Skript. Lesen Sie die Kommentare in diesem Skript um zu verstehen, was dort vor sich geht. Weil das NFS-Root-Verzeichnis schreibgeschützt ist, wir aber Schreibzugriff für [.filename]#/etc# und [.filename]#/var# benötigen, müssen wir diese Verzeichnisse über Speicher-Dateisysteme (memory backed file system) einbinden. [source,shell] .... # chroot ${NFSROOTDIR} # mkdir -p conf/base # tar -c -v -f conf/base/etc.cpio.gz --format cpio --gzip etc # tar -c -v -f conf/base/var.cpio.gz --format cpio --gzip var .... Wenn das System bootet, werden Speicher-Dateisysteme für [.filename]#/etc# und [.filename]#/var# erstellt und eingehangen. Anschließend wird der Inhalt der [.filename]#cpio.gz#-Dateien in diese Dateisysteme kopiert. Standardmäßig haben diese Dateisysteme eine maximale Kapazität von 5 Megabyte. Wenn die Archive nicht passen, was für gewöhnlich bei [.filename]#/var# der Fall ist, erhöhen Sie die Kapazität indem Sie die Anzahl der benötigten 512 Byte Sektoren (5 Megabyte sind 10240 Sektoren) in [.filename]#${NFSROOTDIR}/conf/base/etc/md_size# und [.filename]#${NFSROOTDIR}/conf/base/var/md_size# für die Dateisysteme [.filename]#/etc# und [.filename]#/var# eintragen. [[network-pxe-setting-up-dhcp]] === Konfiguration des DHCP-Servers Der DHCP-Server muss nicht auf derselben Maschine laufen wie der TFTP- und NFS-Server, aber er muss über das Netzwerk erreichbar sein. -DHCP ist nicht Bestandteil des FreeBSD Basissystems, kann jedoch über den Port package:net/isc-dhcp43-server[] oder als Paket nachinstalliert werden. +DHCP ist nicht Bestandteil des FreeBSD Basissystems, kann jedoch über den Port package:net/isc-dhcp44-server[] oder als Paket nachinstalliert werden. Einmal installiert, bearbeiten Sie die Konfigurationsdatei [.filename]#/usr/local/etc/dhcpd.conf#. Konfigurieren Sie die `next-server`, `filename` und `root-path` Einstellungen, wie in diesem Beispiel zu sehen ist: [.programlisting] .... subnet 192.168.0.0 netmask 255.255.255.0 { range 192.168.0.2 192.168.0.3; option subnet-mask 255.255.255.0; option routers 192.168.0.1; option broadcast-address 192.168.0.255; option domain-name-servers 192.168.35.35, 192.168.35.36; option domain-name "example.com"; # IP address of TFTP server next-server 192.168.0.1; # path of boot loader obtained via tftp filename "FreeBSD/install/boot/pxeboot"; # pxeboot boot loader will try to NFS mount this directory for root FS option root-path "192.168.0.1:/b/tftpboot/FreeBSD/install/"; } .... Die Anweisung `next-server` wird benutzt, um die IP-Adresse des TFTP-Servers anzugeben. Die Anweisung `filename` definiert den Pfad zu [.filename]#/boot/pxeboot#. Da hier der relative Dateiname verwendet wird, bedeutet das, dass [.filename]#/b/tftpboot# nicht im Pfad enthalten ist. Die Option `root-path` bestimmt den Pfad zum NFS root-Dateisystem. Sobald die Änderungen gespeichert werden, aktivieren Sie DHCP beim Systemstart, indem Sie die folgende Zeile in [.filename]#/etc/rc.conf# hinzufügen: [.programlisting] .... dhcpd_enable="YES" .... Starten Sie anschließend den DHCP-Dienst: [source,shell] .... # service isc-dhcpd start .... === Fehlersuche bei PXE Problemen Sobald alle Dienste konfiguriert und gestartet wurden, sollten PXE-Clients in der Lage sein, FreeBSD automatisch über das Netzwerk zu starten. Wenn ein bestimmter Client beim hochfahren keine Verbindung herstellen kann, sehen Sie im BIOS nach, ob die Option für den Start über das Netzwerk konfiguriert ist. Dieser Abschnitt gibt einige Tipps zu Fehlerbehebung und zeigt, wie Sie Konfigurationsprobleme eingrezen können für den Fall, dass PXE-Clients nicht in der Lage sind über das Netzwerk zu starten. [.procedure] . Benutzen Sie den package:net/wireshark[] Port um Fehler im Netzwerkverkehr während des Bootvorgangs von PXE zu finden. Der Bootvorgang wird im folgenden Diagramm schematisch dargestellt. + .PXE-Bootvorgang mit NFS Root Mount image::pxe-nfs.png[] . Schauen Sie in [.filename]#/var/log/xferlog# auf dem TFTP-Server und vergewissern Sie sich, dass die [.filename]#pxeboot#-Datei von der richtigen Adresse heruntergeladen wurde. Um die obige Konfiguration von [.filename]#/usr/local/etc/dhcpd.conf# zu testen, geben Sie folgendes ein: + [source,shell] .... # tftp 192.168.0.1 tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... + Weitere Informationen finden Sie in man:tftpd[8] und man:tftp[1]. Die `BUGS`-Sektionen dieser Seiten dokumentieren einige Einschränkungen von TFTP. . Achten Sie darauf, dass Sie das Root-Dateisystem über NFS einhängen können. Auch hier können Sie Ihre Einstellungen aus [.filename]#/usr/local/etc/dhcpd.conf# wie folgt testen: + [source,shell] .... # mount -t nfs 192.168.0.1:/b/tftpboot/FreeBSD/install /mnt .... [[network-ipv6]] == IPv6 IPv6 ist die neueste Version des bekannten IP-Protokolls, das auch als IPv4 bezeichnet wird. IPv6 bietet gegenüber IPv4 mehrere Vorteile sowie viele neue Funktionen: * IPv6 hat einen 128 Bit großen Adressraum, der 340.282.366.920.938.463.463.374.607.431.768.211.456 Adressen erlaubt. Dies behebt das Problem der immer knapper werdenden IPv4-Adressen und einer eventuellen Erschöpfung des IPv4-Adressraums. * Router speichern nur noch Netzwerk-Aggregationsadressen in ihren Routingtabellen. Dadurch reduziert sich die durchschnittliche Größe einer Routingtabelle auf 8192 Einträge. Dies ist mit den Problemen bei der Skalierbarkeit von IPv4 verbunden, da jeder zugeordnete Block von IPv4-Adressen erfordert, dass Routing-Informationen zwischen vielen Routern im Internet ausgetauscht werden müssen. Die Routing-Tabellen wurden mit der Zeit so groß, dass ein effizientes Routing jetzt kaum noch möglich ist. * Die automatische Konfiguration von Adressen, die im http://www.ietf.org/rfc/rfc2462.txt[ RFC2462] beschrieben wird. * Verpflichtende Multicast-Adressen. * Integriertes IPsec (IP-Security). * Eine vereinfachte Headerstruktur. * Unterstützung für mobile IP-Adressen. * Die Umwandlung von IPv4- in IPv6-Adressen. FreeBSD enthält die IPv6-Referenzimplementation von link:http//www.kame.net/[KAME] und erfüllt damit bereits alle für die Nutzung von IPv6 nötigen Voraussetzungen. Dieser Abschnitt konzentriert sich auf die Konfiguration und den Betrieb von IPv6. === Hintergrundinformationen zu IPv6-Adressen Es gibt verschiedene Arten von IPv6-Adressen: Unicast:: Ein Paket, das an eine Unicast-Adresse gesendet wird, kommt nur an der Schnittstelle an, die dieser Adresse zugeordnet ist. Anycast:: Anycast-Adressen unterscheiden sich in ihrer Syntax nicht von Unicast-Adressen, sie wählen allerdings aus mehreren Schnittstellen eine Schnittstelle aus. Ein für eine Anycast-Adresse bestimmtes Paket kommt an der nächstgelegenen (entsprechend der Router-Metrik) Schnittstelle an. Anycast-Adressen werden nur von Routern verwendet. Mulitcast:: Multicast-Adressen bestimmen Gruppen, denen mehrere Schnittstellen angehören. Ein Paket, das an eine Multicast-Adresse geschickt wird, kommt an allen Schnittstellen an, die zur Multicast-Gruppe gehören. Die von IPv4 bekannte Broadcast-Adresse (normalerweise `xxx.xxx.xxx.255`) wird bei IPv6 durch Multicast-Adressen verwirklicht. Die kanonische Form einer IPv6-Adresse lautet `x:x:x:x:x:x:x:x`, wobei jedes "x" für einen 16-Bit-Hexadezimalwert steht. Ein Beispiel für eine IPv6-Adresse wäre etwa `FEBC:A574:382B:23C1:AA49:4592:4EFE:9982`. Eine IPv6-Adresse enthält oft Teilzeichenfolgen aus lauter Nullen. Eine solche Zeichenfolge kann zu "::" verkürzt werden. Bis zu drei führende Nullen eines Hexquads können ebenfalls weggelassen werden. `fe80::1` entspricht also der Adresse `fe80:0000:0000:0000:0000:0000:0000:0001`. Eine weitere Möglichkeit ist die Darstellung der letzten 32 Bit in der bekannten IPv4-Notation. `2002::10.0.0.1` ist also eine andere Schreibweise für die (hexadezimale) kanonische Form `2002:0000:0000:0000:0000:0000:0a00:0001`, die wiederum der Adresse `2002::a00:1` entspricht. Benutzen Sie man:ifconfig[8], um die IPv6-Adresse eines FreeBSD-Systems anzuzeigen: [source,shell] .... # ifconfig rl0: flags=8943 mtu 1500 inet 10.0.0.10 netmask 0xffffff00 broadcast 10.0.0.255 inet6 fe80::200:21ff:fe03:8e1%rl0 prefixlen 64 scopeid 0x1 ether 00:00:21:03:08:e1 media: Ethernet autoselect (100baseTX ) status: active .... Bei `fe80::200:21ff:fe03:8e1%rl0` handelt es sich um eine automatisch konfigurierte link-local-Adresse. Sie wird im Rahmen der automatischen Konfiguration aus der MAC-Adresse erzeugt. Einige IPv6-Adressen sind reserviert. Eine Zusammenfassung dieser Adressen finden Sie in <>: [[reservedip6]] .Reservierte IPv6-Adressen [cols="1,1,1,1", frame="none", options="header"] |=== | IPv6-Adresse | Präfixlänge | Beschreibung | Anmerkungen |`::` |128 Bit |nicht festgelegt |entspricht `0.0.0.0` bei IPv4. |`::1` |128 Bit |Loopback-Adresse |entspricht `127.0.0.1` bei IPv4. |`::00:xx:xx:xx:xx` |96 Bit |Eingebettete IPv4-Adresse |Die niedrigen 32 Bit sind die kompatiblen IPv4-Adressen. |`::ff:xx:xx:xx:xx` |96 Bit |Eine auf IPv6 abgebildete IPv4-Adresse. |Die niedrigen 32 Bit sind IPv4-Adressen für Hosts, die kein IPv6 unterstützen. |`fe80::/10` |10 Bit |link-local |Entspricht 196.254.0.0/16 bei IPv4. |`fc00::/7` |7 Bit |unique-local |Diese einzigartigen Adressen sind für die lokale Kommunikation bestimmt und werden nur innerhalb von abgegrenzten Standorten (Sites) weitergeleitet. |`ff00::` |8 Bit |Multicast | |`2000::-3fff::` |3 Bit |Globaler Unicast |Alle globalen Unicast-Adressen stammen aus diesem Pool. Die ersten 3 Bit lauten `001`. |=== Weitere Informationen zum Aufbau von IPv6-Adressen finden Sie im http://www.ietf.org/rfc/rfc3513.txt[ RFC3513]. === IPv6 konfigurieren Um ein FreeBSD-System als IPv6-Client zu konfigurieren, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... ifconfig_rl0_ipv6="inet6 accept_rtadv" rtsold_enable="YES" .... Die erste Zeile ermöglicht der angegebenen Schnittstelle, Router-Advertisement-Nachrichten zu empfangen. Die zweite Zeile aktiviert den Router-Solicitation-Daemon man:rtsold[8]. Falls die Schnittstelle eine statisch zugewiesene IPv6-Adresse benötigt, fügen Sie einen Eintrag mit der statischen Adresse und dem zugehörigen Präfix für das Subnetz hinzu: [.programlisting] .... ifconfig_rl0_ipv6="inet6 2001:db8:4672:6565:2026:5043:2d42:5344 prefixlen 64" .... Um einen Standardrouter festzulegen, fügen Sie die Adresse hinzu: [.programlisting] .... ipv6_defaultrouter="2001:db8:4672:6565::1" .... === Verbindung zu einem Provider aufbauen Um sich mit anderen IPv6-Netzwerken zu verbinden, benötigen Sie einen Provider oder einen Tunnel, der IPv6 unterstützt: * Fragen Sie einen Internetprovider, ob er IPv6 anbietet. * http://www.tunnelbroker.net[Hurricane Electric] bietet weltweit IPv6-Tunnelverbindungen an. [NOTE] ==== Die Verwendung des Ports [.filename]#/usr/ports/net/freenet6# für Einwahlverbindungen. ==== Dieser Abschnitt beschreibt, wie Sie die Anweisungen eines Tunnel-Providers dauerhaft in [.filename]#/etc/rc.conf# einrichten. Der erste Eintrag in [.filename]#/etc/rc.conf# erzeugt die generische Tunnelschnittstelle [.filename]#gif0#: [.programlisting] .... cloned_interfaces="gif0" .... Als nächstes konfigurieren Sie die IPv4-Adressen der lokalen und entfernten Endpunkte. Ersetzen Sie _MY_IPv4_ADDR_ und _REMOTE_IPv4_ADDR_ durch die tatsächlichen IPv4-Adressen: [.programlisting] .... cloned_interfaces_gif0="MY_IPv4_ADDR REMOTE_IPv4_ADDR" .... Um die zugewiesene IPv6-Adresse als Endpunkt für den IPv6-Tunnel zu verwenden, fügen Sie folgende Zeile für FreeBSD 9._x_ (und neuer) ein: [.programlisting] .... ifconfig_gif0_ipv6="inet6 MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR" .... Legen Sie dann die Standardroute für das andere Ende des IPv6-Tunnels fest. Ersetzen Sie _MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR_ mit der Adresse des Standard-Gateways des Providers: [.programlisting] .... ipv6_defaultrouter="MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR" .... Wenn das FreeBSD-System IPv6-Verkehr zwischen dem Netzwerk und der Außenwelt routen muss, aktivieren Sie das Gateway mit dieser Zeile: [.programlisting] .... ipv6_gateway_enable="YES" .... === Bekanntmachung von Routen und automatische Rechnerkonfiguration Dieser Abschnitt beschreibt die Einrichtung von man:rtadvd[8], das Sie bei der Bekanntmachung der IPv6-Standardroute unterstützt. Um man:rtadvd[8] zu aktivieren, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... rtadvd_enable="YES" .... Es ist wichtig, die Schnittstelle anzugeben, über die IPv6-Routen bekanntgemacht werden sollen. Soll man:rtadvd[8] [.filename]#rl0# verwenden, ist folgender Eintrag nötig: [.programlisting] .... rtadvd_interfaces="rl0" .... Danach erzeugen Sie die Konfigurationsdatei [.filename]#/etc/rtadvd.conf#. Dazu ein Beispiel: [.programlisting] .... rl0:\ :addrs#1:addr="2001:db8:1f11:246::":prefixlen#64:tc=ether: .... Ersetzen Sie dabei [.filename]#fxp0# durch die zu verwendende Schnittstelle, und `2001:db8:1f11:246::` durch das entsprechend zugewiesene Präfix. Bei einem `/64`-Subnetz müssen keine weiteren Anpassungen vorgenommen werden. Anderenfalls muss `prefixlen#` auf den korrekten Wert gesetzt werden. === IPv6 und Abbildung von IPv6-Adressen Wenn IPv6 auf einem Server aktiviert ist, kann es für die Kommunikation erforderlich sein, IPv4-Adressen auf IPv6-Adressen abzubilden. Diese Kompatibilität erlaubt es, das IPv4-Adressen als IPv6-Adressen dargestellt werden. Die Kommunikation von IPv6-Anwendungen mit IPv4 und umgekehrt kann jedoch ein Sicherheitsrisiko darstellen. Diese Option dient nur der Kompatibilität und wird in den meisten Fällen nicht erforderlich sein. Die Option ermöglicht es IPv6-Anwendungen zusammen mit IPv4 in einer Dual-Stack-Umgebung zu funktionieren. Dies ist besonders nützlich für Anwendungen von Drittanbietern, die evtl. keine IPv6-Umgebungen unterstützen. Um diese Funktion zu aktivieren, fügen Sie folgendes in [.filename]#/etc/rc.conf# hinzu: [.programlisting] .... ipv6_ip4mapping="YES" .... Für einige Administratoren können die Informationen im RFC 3493 (Sektion 3.6 und 3.7) und RFC 4038 (Sektion 4.2) hilfreich sein. [[carp]] == Common Address Redundancy Protocol (CARP) Das Common Address Redundancy Protocol (CARP) erlaubt es, mehreren Rechnern die gleiche IP-Adresse und Virtual Host ID (VHID) zuzuweisen und _Hochverfügbarkeit_ bereitzustellen. Das bedeutet, dass ein oder mehrere Rechner ausfallen können und die anderen Rechner transparent einspringen, ohne dass die Benutzer etwas von einem Ausfall mitbekommen. Neben der gemeinsamen IP-Adresse, haben die jeweiligen Rechner auch eine eindeutige IP-Adresse zur Verwaltung und Konfiguration. Alle Maschinen, die sich eine IP-Adresse teilen, verwenden die gleiche VHID. Die VHID für jede einzelne IP-Adresse muss, entsprechend der Broadcast-Domäne der Netzwerkschnittstelle, eindeutig sein. Hochverfügbarkeit mit CARP ist in FreeBSD enthalten, jedoch unterscheidet sich die Konfiguration von der eingesetzten FreeBSD-Version. Dieser Abschnitt enthält die gleichen Konfigurationsdateien für verschiedene Versionen von FreeBSD. Dieses Beispiel konfiguriert eine Failover-Unterstützung mit drei Servern (mit jeweils eigener, eindeutiger IP-Adresse), die alle den gleichen Web-Inhalt anbieten. Es werden zwei verschiedene Master namens `hosta.example.org` und `hostb.example.org` benutzt, mit einem gemeinsamen Backup namens `hostc.example.org`. Die Lastverteilung dieser Maschinen wird dabei über Round RobinDNS konfiguriert. Mit Ausnahme des Hostnamens und der IP-Management-Adresse sind Master- und Backup-Maschinen identisch konfiguriert. Die Server müssen die gleiche Konfiguration und die gleichen Dienste aktiviert haben. Tritt ein Failover auf, können Anfragen an den Dienst mit der gemeinsam genutzten IP-Adresse nur dann richtig beantwortet werden, wenn der Backup-Server Zugriff auf denselben Inhalt hat. Die Backup-Maschine verfügt über zwei zusätzliche CARP-Schnittstellen, eine für jede IP-Adresse des Master-Content-Servers. Sobald ein Fehler auftritt, übernimmt der Backup-Server die IP-Adresse des ausgefallenen Master-Servers. [[carp-10x]] === CARP mit FreeBSD 10 (und neuer) benutzen Unterstützung für CARP erhalten Sie durch das Laden des Kernelmoduls [.filename]#carp.ko# in [.filename]#/boot/loader.conf#: [.programlisting] .... carp_load="YES" .... So laden Sie das Modul ohne Neustart: [source,shell] .... # kldload carp .... Benutzer, die einen angepassten Kernel verwenden möchten, müssen die folgende Zeile in die Konfigurationsdatei aufnehmen. Anschließend muss der Kernel, wie in crossref:kernelconfig[kernelconfig,Konfiguration des FreeBSD-Kernels] beschrieben, neu gebaut werden: [.programlisting] .... device carp .... Hostname, IP-Management-Adresse, Subnetzmaske, gemeinsame IP-Adresse und VHID werden durch Einträge in [.filename]#/etc/rc.conf# gesetzt. Dieses Beispiel ist für `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_em0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 pass testpass alias 192.168.1.50/32" .... Die nächsten Einträge sind für `hostb.example.org`. Da der Rechner einen zweiten Master darstellt, verwendet er eine andere gemeinsame IP-Adresse und VHID. Die mittels `pass` angegebenen Passwörter müssen jedoch identisch sein, da CARP nur mit Systemen kommuniziert, die über das richtige Passwort verfügen. [.programlisting] .... hostname="hostb.example.org" ifconfig_em0="inet 192.168.1.4 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 2 pass testpass alias 192.168.1.51/32" .... Die dritte Maschine, `hostc.example.org` ist so konfiguriert, das sie aktiviert wird, wenn einer der beiden Masterserver ausfällt. Diese Maschine ist mit zwei CARPVHIDs konfiguriert, eine für jede virtuelle IP-Adresse der beiden Master-Server. Die CARP advertising skew, `advskew` wird gesetzt, um sicherzustellen, dass sich der Backup-Server später ankündigt wie der Master-Server, da `advskew` die Rangfolge steuert für den Fall, dass mehrere Backup-Server zur Verfügung stehen. [.programlisting] .... hostname="hostc.example.org" ifconfig_em0="inet 192.168.1.5 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 advskew 100 pass testpass alias 192.168.1.50/32" ifconfig_em0_alias1="inet vhid 2 advskew 100 pass testpass alias 192.168.1.51/32" .... Durch die beiden konfigurierten CARPVHIDs ist `hostc.example.org` in der Lage festzustellen, wenn einer der Master-Server nicht mehr reagiert. Wenn der Master-Server sich später ankündigt als der Backup-Server, übernimmt der Backup-Server die gemeinsame IP-Adresse, bis der Master-Server erneut verfügbar ist. [NOTE] ==== Auch wenn der ursprüngliche Master-Server wieder verfügbar wird, gibt `hostc.example.org` die virtuelle IP-Adresse nicht automatisch wieder frei. Dazu muss Preemption aktiviert werden. Preemption ist standardmäßig deaktiviert und wird über die man:sysctl[8]-Variable `net.inet.carp.preempt` gesteuert. Der Administrator kann den Backup-Server zwingen, die IP-Adresse an den Master zurückzugeben: [source,shell] .... # ifconfig em0 vhid 1 state backup .... ==== Sobald die Konfiguration abgeschlossen ist, muss das Netzwerk oder die Maschine neu gestartet werden. Hochverfügbarkeit ist nun aktiviert. Die Funktionalität von CARP kann, wie in der Manualpage man:carp[4] beschrieben, über verschiedene man:sysctl[8] Parameter kontrolliert werden. Mit dem Einsatz von man:devd[8] können weitere Aktionen zu CARP-Ereignissen ausgelöst werden. [[carp-9x]] === CARP mit FreeBSD 9 (und älter) benutzen Die Konfiguration für diese Versionen von FreeBSD ist ähnlich wie im vorhergehenden Abschnitt beschrieben, mit der Ausnahme, dass zuerst ein CARP-Gerät in der Konfiguration erstellt und bezeichnet werden muss. Unterstützung für CARP erhalten Sie durch das Laden des Kernelmoduls [.filename]#carp.ko# in [.filename]#/boot/loader.conf#: [.programlisting] .... if_carp_load="YES" .... So laden Sie das Modul ohne Neustart: [source,shell] .... # kldload carp .... Benutzer, die einen angepassten Kernel verwenden möchten, müssen die folgende Zeile in die Konfigurationsdatei aufnehmen. Anschließend muss der Kernel, wie in crossref:kernelconfig[kernelconfig,Konfiguration des FreeBSD-Kernels] beschrieben, neu gebaut werden: [.programlisting] .... device carp .... Als nächstes erstellen Sie auf jedem Rechner eine CARP-Schnittstelle: [source,shell] .... # ifconfig carp0 create .... Konfigurieren Sie Hostnamen, IP-Management-Adresse, die gemeinsam genutzte IP-Adresse und die VHID, indem Sie die erforderlichen Zeilen in [.filename]#/etc/rc.conf# hinzufügen. Da anstelle eines Alias eine virtuelles CARP-Gerät verwendet wird, wird die tatsächliche Subnetzmaske `/24` anstatt `/32` benutzt. Hier sind die Einträge für `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_fxp0="inet 192.168.1.3 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 1 pass testpass 192.168.1.50/24" .... Beispiel für `hostb.example.org`: [.programlisting] .... hostname="hostb.example.org" ifconfig_fxp0="inet 192.168.1.4 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 2 pass testpass 192.168.1.51/24" .... Die dritte Maschine, `hostc.example.org` ist so konfiguriert, das sie aktiviert wird, wenn einer der beiden Masterserver ausfällt: [.programlisting] .... hostname="hostc.example.org" ifconfig_fxp0="inet 192.168.1.5 netmask 255.255.255.0" cloned_interfaces="carp0 carp1" ifconfig_carp0="vhid 1 advskew 100 pass testpass 192.168.1.50/24" ifconfig_carp1="vhid 2 advskew 100 pass testpass 192.168.1.51/24" .... [NOTE] ==== Preemption ist im [.filename]#GENERIC#-Kernel deaktiviert. Haben Sie jedoch Preemption in einem angepassten Kernel aktiviert, dass `hostc.example.org` die virtuelle IP-Adresse nicht wieder an den Master-Server zurückgibt. Der Administrator kann jedoch den Backup-Server dazu zwingen, die übernommene IP-Adresse wieder an den Master-Server zurückzugeben: [source,shell] .... # ifconfig carp0 down && ifconfig carp0 up .... Dieser Befehl muss auf dem [.filename]#carp#-Gerät ausgeführt werden, dass dem betroffenen System zugeordnet ist. ==== Sobald die Konfiguration abgeschlossen ist, muss das Netzwerk oder die Maschine neu gestartet werden. Hochverfügbarkeit ist nun aktiviert. [[network-vlan]] == VLANs VLANs sind eine Möglichkeit ein Netzwerk virtuell in viele Subnetze zu unterteilen. Man spricht hier auch von Segmentierung. Jedes Subnetz hat seine eigene Broadcast-Domäne und ist von anderen VLANs isoliert. Unter FreeBSD müssen VLANs vom Treiber der Netzwerkkarte unterstützt werden. man:vlan[4] enthält eine Liste von Treibern mit integrierter VLAN-Unterstützung. Für die Konfiguration eines VLAN werden zwei Informationen benötigt: die verwendete Netzwerkschnittstelle und das VLAN-Tag. Das folgende Kommando konfiguriert ein VLAN mit der Netzwerkschnittstelle `em0` und dem VLAN-Tag `5`: [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 inet 192.168.20.20/24 .... [NOTE] ==== In diesem Beispiel fällt auf, dass der Name der Schnittstelle den Treibernamen und das VLAN-Tag enthält, getrennt durch einen Punkt. Diese Methode hat sich bewährt, da sie die Konfiguration von Systemen mit mehreren VLANs deutlich erleichtert. ==== Um VLANs beim Booten zu konfigurieren, muss [.filename]#/etc/rc.conf# angepasst werden. Für das obige Beispiel müssten folgende Zeilen in die Konfiguration aufgenommen werden: [.programlisting] .... vlans_em0="5" ifconfig_em0_5="inet 192.168.20.20/24" .... Das gleiche Schema kann benutzt werden, um weitere VLANs hinzuzufügen. Es ist sinnvoll, einer Schnittstelle einen symbolischen Namen zuzuweisen, so dass bei einem Wechsel der zugehörigen Hardware nur wenige Konfigurationsvariablen aktualisiert werden müssen. Nehmen wir beispielsweise an, dass Überwachungskameras im VLAN1 auf `em0` betrieben werden. Wenn später die Karte `em0` durch eine Karte ersetzt wird, die den man:ixgb[4] Treiber verwendet, müssen nicht alle Referenzen auf `em0.1` durch `ixgb0.1` ersetzt werden. Der folgende Befehl konfiguriert VLAN `5` auf der Netzwerkkarte `em0`. Die Schnittstelle bekommt den Namen `cameras` und eine IP-Adresse `_192.168.20.20_` mit einem `24`-Bit Präfix. [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 name cameras inet 192.168.20.20/24 .... Dieser Befehl konfiguriert die Schnittstelle mit dem Namen `video`: [source,shell] .... # ifconfig video.5 create vlan 5 vlandev video name cameras inet 192.168.20.20/24 .... Um die Änderungen beim Booten anzuwenden, fügen Sie folgenden Zeilen in [.filename]#/etc/rc.conf# ein: [.programlisting] .... vlans_video="cameras" create_args_cameras="vlan 5" ifconfig_cameras="inet 192.168.20.20/24" .... diff --git a/documentation/content/de/books/handbook/network-servers/_index.adoc b/documentation/content/de/books/handbook/network-servers/_index.adoc index 4b0d0f059f..3dfbb1f2bb 100644 --- a/documentation/content/de/books/handbook/network-servers/_index.adoc +++ b/documentation/content/de/books/handbook/network-servers/_index.adoc @@ -1,2477 +1,2477 @@ --- title: Kapitel 29. Netzwerkserver part: Teil IV. Netzwerke prev: books/handbook/mail next: books/handbook/firewalls showBookMenu: true weight: 34 path: "/books/handbook/" --- [[network-servers]] = Netzwerkserver :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 29 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/network-servers/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[network-servers-synopsis]] == Übersicht Dieses Kapitel beschreibt einige der häufiger verwendeten Netzwerkdienste auf UNIX(R)-Systemen. Dazu zählen Installation und Konfiguration sowie Test und Wartung verschiedener Netzwerkdienste. Zusätzlich sind im ganzen Kapitel Beispielkonfigurationen als Referenz enthalten. Nachdem Sie dieses Kapitel gelesen haben, werden Sie * Den inetd-Daemon konfigurieren können. * Wissen, wie das Network File System (NFS) eingerichtet wird. * Einen Network Information Server (NIS) einrichten können, um damit Benutzerkonten im Netzwerk zu verteilen. * Wissen, wie Sie FreeBSD einrichten, um als LDAP-Server oder -Client zu agieren. * Rechner durch Nutzung von DHCP automatisch für ein Netzwerk konfigurieren können. * In der Lage sein, einen Domain Name Server (DNS) einzurichten. * Den ApacheHTTP-Server konfigurieren können. * Wissen, wie man einen File Transfer Protocol (FTP)-Server einrichtet. * Mit Samba einen Datei- und Druckserver für Windows(R)-Clients konfigurieren können. * Unter Nutzung des NTP-Protokolls Datum und Uhrzeit synchronisieren sowie einen Zeitserver installieren können. * Wissen, wie iSCSI eingerichtet wird. Dieses Kapitel setzt folgende Grundkenntnisse voraus: * [.filename]#/etc/rc#-Skripte. * Netzwerkterminologie * Installation zusätzlicher Software von Drittanbietern (crossref:ports[ports,Installieren von Anwendungen: Pakete und Ports]). [[network-inetd]] == Der inetd"Super-Server" Der man:inetd[8]-Daemon wird manchmal auch als "Internet Super-Server" bezeichnet, weil er Verbindungen für viele Dienste verwaltet. Anstatt mehrere Anwendungen zu starten, muss nur der inetd-Dienst gestartet werden. Wenn eine Verbindung für einen Dienst eintrifft, der von inetd verwaltet wird, bestimmt inetd, welches Programm für die eingetroffene Verbindung zuständig ist, aktiviert den entsprechenden Prozess und reicht den Socket an ihn weiter. Der Einsatz von inetd an Stelle viele einzelner Daemonen kann auf nicht komplett ausgelasteten Servern zu einer Verringerung der Systemlast führen. inetd wird vor allem dazu verwendet, andere Daemonen zu aktivieren, einige Protokolle werden aber auch intern verwaltet. Dazu gehören chargen, auth, time, echo, discard sowie daytime. Dieser Abschnitt beschreibt die Konfiguration von inetd. [[network-inetd-conf]] === Konfigurationsdatei Die Konfiguration von inetd erfolgt über [.filename]#/etc/inetd.conf# Jede Zeile dieser Datei repräsentiert eine Anwendung, die von inetd gestartet werden kann. In der Voreinstellung beginnt jede Zeile mit einem Kommentar (`#`), was bedeutet dass inetd keine Verbindungen für Anwendungen akzeptiert. Entfernen Sie den Kommentar am Anfang der Zeile, damit inetd Verbindungen für diese Anwendung entgegennimmt. Nachdem Sie die Änderungen gespeichert haben, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# ein, damit inetd bei Booten automatisch gestartet wird: [.programlisting] .... inetd_enable="YES" .... Starten Sie jetzt inetd, so dass er Verbindungen für die von Ihnen konfigurierten Dienste entgegennimmt: [source,shell] .... # service inetd start .... Sobald inetd gestartet ist, muss der Dienst benachrichtigt werden, wenn eine Änderung in [.filename]#/etc/inetd.conf# gemacht wird: [[network-inetd-reread]] .Die Konfigurationsdatei von inetd neu einlesen [example] ==== [source,shell] .... # service inetd reload .... ==== Normalerweise müssen Sie lediglich den Kommentar vor der Anwendung entfernen. In einigen Situationen kann es jedoch sinnvoll sein, den Eintrag weiter zu bearbeiten. Als Beispiel dient hier der Standardeintrag für man:ftpd[8] über IPv4: [.programlisting] .... ftp stream tcp nowait root /usr/libexec/ftpd ftpd -l .... Die sieben Spalten in diesem Eintrag haben folgende Bedeutung: [.programlisting] .... service-name socket-type protocol {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]] user[:group][/login-class] server-program server-program-arguments .... service-name:: Der Dienstname eines bestimmten Daemons. Er muss einem in [.filename]#/etc/services# aufgelisteten Dienst entsprechen. Hier wird festgelegt, auf welchen Port inetd eingehende Verbindungen für diesen Dienst entgegennimmt. Wenn ein neuer Dienst benutzt wird, muss er zuerst in [.filename]#/etc/services# eingetragen werden. socket-type:: Entweder `stream`, `dgram`, `raw`, oder `seqpacket`. Nutzen Sie `stream` für TCP-Verbindungen und `dgram` für UDP-Dienste. protocol:: Benutzen Sie eines der folgenden Protokolle: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Protokoll | Bedeutung |tcp oder tcp4 |TCP (IPv4) |udp oder udp4 |UDP (IPv4) |tcp6 |TCP (IPv6) |udp6 |UDP (IPv6) |tcp46 |TCP sowohl unter IPv4 als auch unter IPv6 |udp46 |UDP sowohl unter IPv4 als auch unter IPv6 |=== {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]]:: In diesem Feld muss `wait` oder `nowait` angegeben werden. `max-child`, `max-connections-per-ip-per-minute` sowie `max-child-per-ip` sind optional. + `wait|nowait` gibt an, ob der Dienst seinen eigenen Socket verwalten kann oder nicht. `dgram`-Sockets müssen `wait` verwenden, während Daemonen mit `stream`-Sockets, die normalerweise auch aus mehreren Threads bestehen, `nowait` verwenden sollten. `wait` gibt in der Regel mehrere Sockets an einen einzelnen Daemon weiter, während `nowait` für jeden neuen Socket einen Childdaemon erzeugt. + Die maximale Anzahl an Child-Daemonen, die inetd erzeugen kann, wird durch die Option `max-child` festgelegt. Wenn ein bestimmter Daemon 10 Instanzen benötigt, wird der Wert `/10` hinter die Option `nowait` gesetzt. Der Wert `/0` gibt an, das es keine Beschränkung gibt. + `max-connections-per-ip-per-minute` legt die maximale Anzahl von Verbindungsversuchen pro Minute fest, die von einer bestimmten IP-Adresse aus unternommen werden können. Sobald das Limit erreicht ist, werden weitere Verbindungen von dieser IP-Adresse geblockt, bis die Minute vorüber ist. Ein Wert von `/10` würde die maximale Anzahl der Verindungsversuche einer bestimmten IP-Adresse auf zehn Versuche in der Minute beschränken. `max-child-per-ip` legt fest, wie viele Child-Daemonen von einer bestimmten IP-Adresse aus gestartet werden können. Durch diese Optionen lassen sich Ressourcenverbrauch sowie die Auswirkungen eines `Denial of Service (DoS)`-Angriffs begrenzen. + Ein Beispiel finden Sie in den Voreinstellungen für man:fingerd[8]: + [.programlisting] .... finger stream tcp nowait/3/10 nobody /usr/libexec/fingerd fingerd -k -s .... user:: Der Benutzername, unter dem der jeweilige Daemon laufen soll. Meistens laufen Daemonen als `root`, `daemon` oder `nobody`. server-program:: Der vollständige Pfad des Daemons. Wird der Daemon von inetd intern bereitgestellt, verwenden Sie `internal`. server-program-arguments:: Dieser Eintrag legt die Argumente fest, die bei der Aktivierung an den Daemon übergeben werden. Wenn es sich beim Daemon um einen internen Dienst handelt, verwenden Sie wiederum `internal`. [[network-inetd-cmdline]] === Kommandozeilenoptionen Wie die meisten anderen Server-Daemonen lässt sich auch inetd über verschiedene Optionen steuern. In der Voreinstellung wird inetd mit `-wW -C 60` gestartet. Durch das Setzen dieser Werte wird das TCP-Wrapping für alle inetd-Dienste aktiviert. Zudem wird verhindert, dass eine IP-Adresse eine Dienst öfter als 60 Mal pro Minute anfordern kann. Um die Voreinstellungen für inetd zu ändern, fügen Sie einen Eintrag für `inetd_flags` in [.filename]#/etc/rc.conf# hinzu. Wenn inetd bereits ausgeführt wird, starten Sie ihn mit `service inetd restart` neu. Die verfügbaren Optionen sind: -c maximum:: Legt die maximale Anzahl von parallelen Aufrufen eines Dienstes fest; in der Voreinstellung gibt es keine Einschränkung. Diese Einstellung kann für jeden Dienst durch Setzen des Parameters `max-child` in [.filename]#/etc/inetd.conf# festgelegt werden. -C rate:: Legt fest, wie oft ein Dienst von einer einzelnen IP-Adresse in einer Minute aufgerufen werden kann; in der Voreinstellung gibt es keine Einschränkung. Dieser Wert kann für jeden Dienst durch das Setzen des Parameters `max-connections-per-ip-per-minute` in [.filename]#/etc/inetd.conf# festgelegt werden. -R rate:: Legt fest, wie oft ein Dienst in der Minute aktiviert werden kann; in der Voreinstellung sind dies `256` Aktivierungen pro Minute. Ein Wert von `0` erlaubt unbegrenzt viele Aktivierungen. -s maximum:: Legt fest, wie oft ein Dienst in der Minute von einer einzelnen IP-Adresse aus aktiviert werden kann; in der Voreinstellung gibt es hier keine Beschränkung. Diese Einstellung kann für jeden Dienst durch die Angabe von `max-child-per-ip` in [.filename]#/etc/inetd.conf# angepasst werden. Es sind noch weitere Optionen verfügbar. Eine vollständige Liste der Optionen finden Sie in man:inetd[8]. [[network-inetd-security]] === Sicherheitsbedenken Viele Daemonen, die von inetd verwaltet werden, sind nicht auf Sicherheit bedacht. Einige Damonen, wie beispielsweise fingerd, liefern Informationen, die für einen Angreifer nützlich sein könnten. Aktivieren Sie nur erforderliche Dienste und überwachen Sie das System auf übermäßige Verbindungsversuche. `max-connections-per-ip-per-minute`, `max-child` und `max-child-per-ip` können verwendet werden, um solche Angriffe zu begrenzen. TCP-Wrapper ist in der Voreinstellung aktiviert. Lesen Sie man:hosts_access[5], wenn Sie weitere Informationen zum Setzen von TCP-Beschränkungen für verschiedene von inetd aktivierte Daemonen benötigen. [[network-nfs]] == Network File System (NFS) FreeBSD unterstützt das Netzwerkdateisystem NFS, das es einem Server erlaubt, Dateien und Verzeichnisse über ein Netzwerk mit Clients zu teilen. Mit NFS können Benutzer und Programme auf Daten entfernter Systeme zugreifen, und zwar so, als ob es sich um lokal gespeicherte Daten handeln würde. Die wichtigsten Vorteile von NFS sind: * Daten, die sonst auf jeden Client dupliziert würden, können an einem zentralen Ort aufbewahrt, und von den Clients über das Netzwerk aufgerufen werden. * Verschiedene Clients können auf ein gemeinsames Verzeichnis [.filename]#/usr/ports/distfiles# zugreifen. Die gemeinsame Nutzung dieses Verzeichnisses ermöglicht einen schnellen Zugriff auf die Quelldateien, ohne sie auf jede Maschine zu kopieren zu müssen. * In größeren Netzwerken ist es praktisch, einen zentralen NFS-Server einzurichten, auf dem die Heimatverzeichnisse der Benutzer gespeichert werden. Dadurch steht den Benutzern immer das gleiche Heimatverzeichnis zur Verfügung, unabhängig davon, an welchem Client im Netzwerk sie sich anmelden. * Die Verwaltung der NFS-Exporte wird vereinfacht. Zum Beispiel gibt es dann nur noch ein Dateisystem, für das Sicherheits- oder Backup-Richtlinien festgelegt werden müssen. * Wechselmedien können von anderen Maschinen im Netzwerk verwendet werden. Dies reduziert die Anzahl von Geräten im Netzwerk und bietet einen zentralen Ort für die Verwaltung. Oft ist es einfacher, über ein zentrales Installationsmedium Software auf mehreren Computern zu installieren. NFS besteht aus einem Server und einem oder mehreren Clients. Der Client greift über das Netzwerk auf die Daten zu, die auf dem Server gespeichert sind. Damit dies korrekt funktioniert, müssen einige Prozesse konfiguriert und gestartet werden: Folgende Daemonen müssen auf dem Server ausgeführt werden: [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Daemon | Beschreibung |nfsd |Der NFS-Daemon. Er bearbeitet Anfragen der NFS-Clients. |mountd |Der NFS-Mount-Daemon. Er bearbeitet die Anfragen von `nfsd`. |rpcbind |Der Portmapper-Daemon. Durch ihn erkennen die NFS-Clients, welchen Port der NFS-Server verwendet. |=== Der Einsatz von man:nfsiod[8] ist nicht zwingend erforderlich, kann aber die Leistung auf dem Client verbessern. [[network-configuring-nfs]] === Konfiguration des Servers Die Dateisysteme, die der NFS-Server exportieren soll, werden in [.filename]#/etc/exports# festgelegt. Jede Zeile in dieser Datei beschreibt ein zu exportierendes Dateisystem, Clients, die darauf Zugriff haben sowie alle Zugriffsoptionen. Die Optionen eines auf einen anderen Rechner exportierten Dateisystems müssen alle in einer Zeile stehen. Wird in einer Zeile kein Rechner festgelegt, dürfen alle Clients im Netzwerk das exportierte Dateisystem einhängen. Wie Dateisysteme exportiert werden, ist in der folgenden [.filename]#/etc/exports# zu sehen. Diese Beispiele müssen natürlich an die Arbeitsumgebung und die Netzwerkkonfiguration angepasst werden. Es existieren viele verschiedene Optionen, allerdings werden hier nur wenige von ihnen erwähnt. Eine vollständige Liste der Optionen finden Sie in man:exports[5]. Dieses Beispiel exportiert [.filename]#/cdrom# für drei Clients, _alpha_, _bravo_ und _charlie_: [.programlisting] .... /cdrom -ro alpha bravo charlie .... Die Option `-ro` kennzeichnet das exportierte Dateisystem als schreibgeschützt. Dadurch sind Clients nicht in der Lage, das exportierte Dateisystem zu verändern. Dieses Beispiel geht davon aus, dass die Hostnamen entweder über DNS oder über [.filename]#/etc/hosts# aufgelöst werden können. Lesen Sie man:hosts[5] falls das Netzwerk über keinen DNS-Server verfügt. Das nächste Beispiel exportiert [.filename]#/home# auf drei durch IP-Adressen bestimmte Clients. Diese Einstellung kann für Netzwerke ohne DNS-Server und [.filename]#/etc/hosts# nützlich sein. Die Option `-alldirs` ermöglicht es, auch Unterverzeichnisse als Mountpunkte festzulegen. Dies bedeutet aber nicht, dass alle Unterverzeichnisse eingehängt werden, vielmehr wird es dem Client ermöglicht, nur diejenigen Verzeichnisse einzuhängen, die auch benötigt werden. [.programlisting] .... /usr/home -alldirs 10.0.0.2 10.0.0.3 10.0.0.4 .... Das nächste Beispiel exportiert [.filename]#/a#, damit Clients von verschiedenen Domänen auf das Dateisystem zugreifen können. Die Option `-maproot=root` erlaubt es dem Benutzer `root` des Clients, als `root` auf das exportierte Dateisystem zu schreiben. Wenn diese Option nicht gesetzt ist, wird der `root`-Benutzer des Clients dem `nobody`-Konto des Servers zugeordnet und unterliegt somit den Zugriffsbeschränkungen dieses Kontos. [.programlisting] .... /a -maproot=root host.example.com box.example.org .... Ein Client kann für jedes Dateisystem nur einmal definiert werden. Wenn beispielsweise [.filename]#/usr# ein gesondertes Dateisystem ist, dann wären die folgenden Einträge falsch, da in beiden Einträgen der gleiche Rechner angegeben wird: [.programlisting] .... #Nicht erlaubt, wenn /usr ein einziges Dateisystem ist /usr/src client /usr/ports client .... Das richtige Format für eine solche Situation ist: [.programlisting] .... /usr/src /usr/ports client .... Das Folgende ist ein Beispiel für eine gültige Exportliste, in der [.filename]#/usr# und [.filename]#/exports# lokale Dateisysteme sind: [.programlisting] .... # Export src and ports to client01 and client02, but only # client01 has root privileges on it /usr/src /usr/ports -maproot=root client01 /usr/src /usr/ports client02 # The client machines have root and can mount anywhere # on /exports. Anyone in the world can mount /exports/obj read-only /exports -alldirs -maproot=root client01 client02 /exports/obj -ro .... Damit die vom NFS-Server benötigen Prozesse beim Booten gestartet werden, fügen Sie folgende Optionen in [.filename]#/etc/rc.conf# hinzu: [.programlisting] .... rpcbind_enable="YES" nfs_server_enable="YES" mountd_enable="YES" .... Der Server kann jetzt mit diesem Kommando gestartet werden: [source,shell] .... # service nfsd start .... Wenn der NFS-Server startet, wird auch mountd automatisch gestartet. Allerdings liest mountd [.filename]#/etc/exports# nur, wenn der Server gestartet wird. Um nachfolgende Änderungen an [.filename]#/etc/exports# wirksam werden zu lassen, kann mountd angewiesen werden, die Datei neu einzulesen: [source,shell] .... # service mountd reload .... === Konfiguration des Clients Um den NFS-Client zu aktivieren, setzen Sie folgende Option in [.filename]#/etc/rc.conf# auf jedem Client: [.programlisting] .... nfs_client_enable="YES" .... Der Client ist nun in der Lage, ein entferntes Dateisystem einzuhängen. In diesen Beispielen ist der Name des Servers `server` und der Name des Clients `client`. Fügen Sie folgenden Befehl aus, um das Verzeichnis [.filename]#/home# vom `server` auf dem `client` ins Verzeichnis [.filename]#/mnt# einzuhängen: [source,shell] .... # mount server:/home /mnt .... Die Dateien und Verzeichnisse in [.filename]#/home# stehen dem Rechner `client` nun im Verzeichnis [.filename]#/mnt# zur Verfügung. Um ein entferntes Dateisystem bei jedem Systemstart automatisch einzuhängen, fügen Sie das Dateisystem in [.filename]#/etc/fstab# ein: [.programlisting] .... server:/home /mnt nfs rw 0 0 .... man:fstab[5] enthält eine Beschreibung aller Optionen. === Dateien sperren (Locking) Einige Anwendungen erfordern die Sperrung von Dateien, damit sie korrekt arbeiten. Um diese Sperre zu aktivieren, müssen diese Zeilen in [.filename]#/etc/rc.conf# sowohl auf dem Client als auch auf dem Server hinzugefügt werden: [.programlisting] .... rpc_lockd_enable="YES" rpc_statd_enable="YES" .... Danach starten Sie die beiden Anwendungen: [source,shell] .... # service lockd start # service statd start .... Wenn keine Dateisperren zwischen den NFS-Clients und dem NFS-Server benötigt werden, können Sie den NFS-Client durch die Übergabe der Option `-L` an mount zu einer lokalen Sperrung von Dateien zwingen. Weitere Details finden Sie in man:mount_nfs[8]. [[network-autofs]] === Automatisches Einhängen mit man:autofs[5] [NOTE] ==== man:autofs[5] wird seit FreeBSD 10.1-RELEASE unterstützt. Um die Funktionalität des automatischen Einhängens in älteren FreeBSD-Versionen zu benutzen, verwenden Sie stattdessen man:amd[8]. In diesem Kapitel wird nur das automatische Einhängen mit Hilfe von man:autofs[5] beschrieben. ==== man:autofs[5] ist eine gebräuchliche Bezeichnung für verschiedene Komponenten, welche es erlauben, lokale und entfernte Dateisysteme automatisch einzuhängen, sobald auf eine Datei oder ein Verzeichnis in diesem Dateisystem zugegriffen wird. Es besteht aus einer Kernel-Komponente man:autofs[5] und mehreren Benutzerprogrammen: man:automount[8], man:automountd[8] und man:autounmountd[8]. man:autofs[5] ist eine Alternative für man:amd[8] aus früheren FreeBSD-Versionen. man:amd[8] steht nach wie vor zur Verfügung, da beide Programme ein unterschiedliches Format verwenden. Das Format welches man:autofs[5] verwendet ist das gleiche wie bei anderen SVR4 Automountern, beispielsweise denen aus Solaris(TM), Mac OS(R) X und Linux(R). Das virtuelle man:autofs[5]-Dateisystem wird von man:automount[8] in einen bestimmten Mountpunkt eingehängt. Dies geschieht gewöhnlich während des Bootens. Jedes Mal, wenn ein Prozess versucht auf eine Datei unterhalb des man:autofs[5]-Mountpunkts zuzugreifen, wird der Kernel den man:automountd[8]-Daemon benachrichtigen und den aktuellen Prozess anhalten. Der man:automountd[8]-Daemon wird dann die Anfrage des Kernels bearbeiten und das entsprechende Dateisystem einhängen. Anschließend wird der Daemon den Kernel benachrichtigen, dass der angehaltene Prozess wieder freigegeben werden kann. Der man:autounmountd[8]-Daemon hängt automatisch Dateisysteme nach einiger Zeit ab, sofern sie nicht mehr verwendet werden. Die primäre Konfigurationsdatei von autofs ist [.filename]#/etc/auto_master#. Sie enthält die einzelnen Zuordnungen zu den Mountpunkten. Eine Erklärung zu [.filename]#auto_master# und der Syntax für die Zuordnungen finden Sie in man:auto_master[5]. Eine spezielle Automounter Zuordnung wird in [.filename]#/net# eingehängt. Wenn auf eine Datei in diesem Verzeichnis zugegriffen wird, hängt man:autofs[5] einen bestimmten, entfernen Mountpunkt ein. Wenn beispielsweise auf eine Datei unterhalb von [.filename]#/net/foobar/usr# zugegriffen werden soll, würde man:automountd[8] das exportierte Dateisystem [.filename]#/usr# von dem Rechner `foobar` einhängen. .Ein exportiertes Dateisystem mit man:autofs[5] in den Verzeichnisbaum einhängen [example] ==== In diesem Beispiel zeigt `showmount -e` die exportierten Dateisysteme des NFS-Servers `foobar`: [source,shell] .... % showmount -e foobar Exports list on foobar: /usr 10.10.10.0 /a 10.10.10.0 % cd /net/foobar/usr .... ==== Die Ausgabe von `showmount` zeigt das exportierte Dateisystem [.filename]#/usr#. Wenn in das Verzeichnis [.filename]#/host/foobar/usr# gewechselt wird, fängt man:automountd[8] die Anforderung ab und versucht, den Rechnernamen `foobar` aufzulösen. Gelingt dies, wird man:automountd[8] automatisch das exportierte Dateisystem einhängen. Um man:autofs[5] beim Booten zu aktivieren, fügen Sie diese Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... autofs_enable="YES" .... Danach kann man:autofs[5] gestartet werden: [source,shell] .... # service automount start # service automountd start # service autounmountd start .... Obwohl das Format von man:autofs[5] das gleiche ist wie in anderen Betriebssystemen, kann es wünschenswert sein, Informationen von anderen Betriebssystemen zu Rate zu ziehen, wie dieses http://images.apple.com/business/docs/Autofs.pdf[Mac OS X Dokument]. Weitere Informationen finden Sie in den Manualpages man:automount[8], man:automountd[8], man:autounmountd[8] und man:auto_master[5]. [[network-nis]] == Network Information System (NIS) Das Network Information System (NIS) wurde entwickelt, um UNIX(R)-Systeme zentral verwalten zu können. Dazu zählen beispielsweise Solaris(TM), HP-UX, AIX(R), Linux(R), NetBSD, OpenBSD und FreeBSD. NIS war ursprünglich als _Yellow Pages_ bekannt, aus markenrechtlichen Gründen wurde der Name aber geändert. Dies ist der Grund, warum NIS-Kommandos mit `yp` beginnen. Bei NIS handelt es sich um ein RPC-basiertes Client/Server-System. Eine Gruppe von Rechnern greift dabei innerhalb einer NIS-Domäne auf gemeinsame Konfigurationsdateien zu. Dies erlaubt es einem Systemadministrator, NIS-Clients mit minimalem Aufwand einzurichten, sowie Änderungen an der Systemkonfiguration von einem zentralen Ort aus durchzuführen. FreeBSD verwendet die Version 2 des NIS-Protokolls. === NIS-Begriffe und -Prozesse Tabelle 30.1 fasst die Begriffe und Anwenderprozesse zusammen, die von NIS verwendet werden: .NIS Begriffe [cols="1,1", frame="none", options="header"] |=== | Begriff | Beschreibung |NIS-Domänenname |NIS-Masterserver und Clients benutzen einen gemeinsamen NIS-Domänennamen. In der Regel hat dieser Name nichts mit DNS zu tun. |man:rpcbind[8] |Dieser Dienst aktiviert RPC und muss gestartet sein, damit ein NIS-Server oder -Client ausgeführt werden kann. |man:ypbind[8] |Dieser Dienst "bindet" einen NIS-Client an seinen NIS-Server. Der Client bezieht den NIS-Domänennamen vom System und stellt über das RPC-Protokoll eine Verbindung zum NIS-Server her. ypbind ist der zentrale Bestandteil der Client-Server-Kommunikation in einer NIS-Umgebung. Wird der Dienst auf einem Client beendet, ist dieser nicht mehr in der Lage, auf den NIS-Server zuzugreifen. |man:ypserv[8] |Dies ist der Prozess für den NIS-Server. Wenn dieser Dienst nicht mehr läuft, kann der Server nicht mehr auf NIS-Anforderungen reagieren. Wenn ein Slaveserver existiert, kann dieser als Ersatz fungieren. Einige NIS-Systeme (allerdings nicht das von FreeBSD) versuchen allerdings erst gar nicht, sich mit einem anderen Server zu verbinden, wenn der Masterserver nicht mehr reagiert. Die einzige Lösung besteht darin, den Serverprozess oder den ypbind-Prozess auf dem Client neu zu starten. |man:rpc.yppasswdd[8] |Dieser Prozess läuft nur auf dem NIS-Masterserver. Es handelt sich um einen Daemonprozess, der es NIS-Clients ermöglicht, ihre NIS-Passwörter zu ändern. Wenn dieser Daemon nicht läuft, müssen sich die Benutzer am NIS-Masterserver anmelden und ihre Passwörter dort ändern. |=== === Arten von NIS-Rechnern * NIS-Masterserver + Dieser Server dient als zentraler Speicherort für Rechnerkonfigurationen. Zudem verwaltet er die maßgebliche Kopie, der von den NIS-Clients gemeinsam verwendeten Dateien. [.filename]#passwd#, [.filename]#group#, sowie verschiedene andere von den Clients verwendete Dateien existieren auf dem Masterserver. Obwohl ein Rechner auch für mehrere NIS-Domänen als Masterserver fungieren kann, wird diese Art von Konfiguration nicht behandelt, da sich dieser Abschnitt auf eine relativ kleine NIS-Umgebung konzentriert. * NIS-Slaveserver + NIS-Slaveserver verwalten Kopien der Daten des NIS-Masterservers um Redundanz zu bieten. Zudem entlasten Slaveserver den Masterserver: NIS-Clients verbinden sich immer mit dem NIS-Server, welcher zuerst reagiert. Dieser Server kann auch ein Slaveserver sein. * NIS-Clients + NIS-Clients identifizieren sich gegenüber dem NIS-Server während der Anmeldung. Mit NIS können Informationen aus verschiedenen Dateien von mehreren Rechnern gemeinsam verwendet werden. [.filename]#master.passwd#, [.filename]#group#, und [.filename]#hosts# werden oft gemeinsam über NIS verwendet. Immer, wenn ein Prozess auf einem Client auf Informationen zugreifen will, die normalerweise in lokalen Dateien vorhanden wären, wird stattdessen eine Anfrage an den NIS-Server gestellt, an den der Client gebunden ist. === Planung Dieser Abschnitt beschreibt eine einfache NIS-Umgebung, welche aus 15 FreeBSD-Maschinen besteht, für die keine zentrale Verwaltung existiert. Jeder Rechner hat also eine eigene Version von [.filename]#/etc/passwd# und [.filename]#/etc/master.passwd#. Diese Dateien werden manuell synchron gehalten; wird ein neuer Benutzer angelegt, so muss dies auf allen fünfzehn Rechnern manuell erledigt werden. In Zukunft soll die Konfiguration wie folgt aussehen: [.informaltable] [cols="1,1,1", frame="none", options="header"] |=== | Rechnername | IP-Adresse | Rechneraufgabe |`ellington` |`10.0.0.2` |NIS-Master |`coltrane` |`10.0.0.3` |NIS-Slave |`basie` |`10.0.0.4` |Workstation der Fakultät |`bird` |`10.0.0.5` |Clientrechner |`cli[1-11]` |`10.0.0.[6-17]` |Verschiedene andere Clients |=== Wenn erstmalig ein NIS-Schema eingerichtet wird, sollte es im Voraus sorgfältig geplant werden. Unabhängig von der Größe des Netzwerks müssen einige Entscheidungen im Rahmen des Planungsprozesses getroffen werden. ==== Einen NIS-Domänennamen wählen Wenn ein Client Informationen anfordert, ist in dieser Anforderung der Name der NIS-Domäne enthalten. Dadurch weiß jeder Server im Netzwerk, auf welche Anforderung er antworten muss. Stellen Sie sich den NIS-Domänennamen als einen Namen einer Gruppe von Rechnern vor. Manchmal wird der Name der Internetdomäne auch für die NIS-Domäne verwendet. Dies ist allerdings nicht empfehlenswert, da es bei der Behebung von Problemen verwirrend sein kann. Der Name der NIS-Domäne sollte innerhalb des Netzwerks eindeutig sein. Hilfreich ist es, wenn der Name die Gruppe der in ihr zusammengefassten Rechner beschreibt. Die Kunstabteilung von Acme Inc. hätte daher vielleicht die NIS-Domäne "acme-art". Für dieses Beispiel wird der Name `test-domain` verwendet. Es gibt jedoch auch Betriebssysteme, die als NIS-Domänennamen den Namen der Internetdomäne verwenden. Wenn dies für einen oder mehrere Rechner des Netzwerks zutrifft, _muss_ der Name der Internetdomäne als NIS-Domänennamen verwendet werden. ==== Anforderungen an den Server Bei der Wahl des NIS-Servers müssen einige Dinge beachtet werden. Da die NIS-Clients auf die Verfügbarkeit des Servers angewiesen sind, sollten Sie einen Rechner wählen, der nicht regelmäßig neu gestartet werden muss. Der NIS-Server sollte idealerweise ein alleinstehender Rechner sein, dessen einzige Aufgabe es ist, als NIS-Server zu dienen. Wenn das Netzwerk nicht zu stark ausgelastet ist, ist es auch möglich, den NIS-Server als weiteren Dienst auf einem anderen Rechner laufen zu lassen. Wenn jedoch ein NIS-Server ausfällt, wirkt sich dies negativ auf _alle_ NIS-Clients aus. === Einen NIS-Masterserver konfigurieren Die verbindlichen Kopien aller NIS-Dateien befinden sich auf dem Masterserver. Die Datenbanken, in denen die Informationen gespeichert sind, bezeichnet man als NIS-Maps. Unter FreeBSD werden diese Maps unter [.filename]#/var/yp/[domainname]# gespeichert, wobei [.filename]#[domainname]# der Name der NIS-Domäne ist. Da ein NIS-Server mehrere Domänen verwalten kann, können auch mehrere Verzeichnisse vorhanden sein. Jede Domäne verfügt über ein eigenes Verzeichnis sowie einen eigenen, von anderen Domänen unabhängigen Satz von NIS-Maps. NIS-Master- und Slaveserver verwenden man:ypserv[8], um NIS-Anfragen zu bearbeiten. Dieser Daemon ist für eingehende Anfragen der NIS-Clients verantwortlich. Er ermittelt aus der angeforderten Domäne und Map einen Pfad zur entsprechenden Datenbank und sendet die angeforderten Daten von der Datenbank zum Client. Abhängig von den Anforderungen ist die Einrichtung eines NIS-Masterservers relativ einfach, da NIS von FreeBSD bereits in der Standardkonfiguration unterstützt wird. Es kann durch folgende Zeilen in [.filename]#/etc/rc.conf# aktiviert werden: [.programlisting] .... nisdomainname="test-domain" <.> nis_server_enable="YES" <.> nis_yppasswdd_enable="YES" <.> .... <.> Diese Zeile setzt den NIS-Domänennamen auf `test-domain`. <.> Dadurch werden die NIS-Serverprozesse beim Systemstart automatisch ausgeführt. <.> Durch diese Zeile wird der man:rpc.yppasswdd[8]-Daemon aktiviert, der die Änderung von NIS-Passwörtern von einem Client aus ermöglicht. Wird ypserv in einer Multi-Serverdomäne verwendet, in der NIS-Server gleichzeitig als NIS-Clients arbeiten, ist es eine gute Idee, diese Server zu zwingen, sich an sich selbst zu binden. Damit wird verhindert, dass Bindeanforderungen gesendet werden und sich die Server gegenseitig binden. Sonst könnten seltsame Fehler auftreten, wenn ein Server ausfällt, auf den andere Server angewiesen sind. Letztlich werden alle Clients einen Timeout melden, und versuchen, sich an andere Server zu binden. Die dadurch entstehende Verzögerung kann beträchtlich sein. Außerdem kann der Fehler erneut auftreten, da sich die Server wiederum aneinander binden könnten. Server, die auch als Client arbeiten, können durch das Hinzufügen der folgenden Zeilen in [.filename]#/etc/rc.conf# zu gezwungen werden, sich an einen bestimmten Server zu binden: [.programlisting] .... nis_client_enable="YES" <.> nis_client_flags="-S test-domain,server" <.> .... <.> Ermöglicht die Aktivierung der Client-Komponenten. <.> Diese Zeile setzt den NIS-Domain Namen `test-domain` und bindet sich an sich selbst. Nachdem die Parameter konfiguriert wurden, muss noch `/etc/netstart` ausgeführt werden, um alles entsprechend den Vorgaben in [.filename]#/etc/rc.conf# einzurichten. Bevor die NIS-Maps einrichtet werden können, muss der man:ypserv[8]-Daemon manuell gestartet werden: [source,shell] .... # service ypserv start .... ==== Die NIS-Maps initialisieren NIS-Maps Sie werden am NIS-Masterserver aus den Konfigurationsdateien unter [.filename]#/etc# erzeugt. Einzige Ausnahme: [.filename]#/etc/master.passwd#. Dies verhindert, dass die Passwörter für `root`- oder andere Administratorkonten an alle Server in der NIS-Domäne verteilt werden. Deshalb werden die primären Passwort-Dateien konfiguriert, bevor die NIS-Maps initialisiert werden: [source,shell] .... # cp /etc/master.passwd /var/yp/master.passwd # cd /var/yp # vi master.passwd .... Es ist ratsam, alle Einträge für Systemkonten sowie Benutzerkonten, die nicht an die NIS-Clients weitergegeben werden sollen, wie beispielsweise `root` und weitere administrative Konten, zu entfernen. [NOTE] ==== Stellen Sie sicher, dass [.filename]#/var/yp/master.passwd# weder von der Gruppe noch von der Welt gelesen werden kann, indem Sie Zugriffsmodus auf `600` einstellen. ==== Nun können die NIS-Maps initialisiert werden. FreeBSD verwendet dafür das Skript man:ypinit[8]. Geben Sie `-m` und den NIS-Domänennamen an, wenn Sie NIS-Maps für den Masterserver erzeugen: [source,shell] .... ellington# ypinit -m test-domain Server Type: MASTER Domain: test-domain Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. At this point, we have to construct a list of this domains YP servers. rod.darktech.org is already known as master server. Please continue to add any slave servers, one per line. When you are done with the list, type a . master server : ellington next host to add: coltrane next host to add: ^D The current list of NIS servers looks like this: ellington coltrane Is this correct? [y/n: y] y [..output from map generation..] NIS Map update completed. ellington has been setup as an YP master server without any errors. .... Dadurch erzeugt `ypinit`[.filename]#/var/yp/Makefile# aus [.filename]#/var/yp/Makefile.dist#. Diese Datei geht in der Voreinstellung davon aus, dass in einer NIS-Umgebung mit nur einem Server gearbeitet wird und dass alle Clients unter FreeBSD laufen. Da `test-domain` aber auch über einen Slaveserver verfügt, muss [.filename]#/var/yp/Makefile# entsprechend angepasst werden, sodass es mit einem Kommentar (`#`) beginnt: [.programlisting] .... NOPUSH = "True" .... ==== Neue Benutzer hinzufügen Jedes Mal, wenn ein neuer Benutzer angelegt wird, muss er am NIS-Masterserver hinzugefügt und die NIS-Maps anschließend neu erzeugt werden. Wird dieser Punkt vergessen, kann sich der neue Benutzer _nur_ am NIS-Masterserver anmelden. Um beispielsweise den neuen Benutzer `jsmith` zur Domäne `test-domain` hinzufügen wollen, müssen folgende Kommandos auf dem Masterserver ausgeführt werden: [source,shell] .... # pw useradd jsmith # cd /var/yp # make test-domain .... Statt `pw useradd jsmith` kann auch `adduser jsmith` verwendet werden. === Einen NIS-Slaveserver einrichten Um einen NIS-Slaveserver einzurichten, melden Sie sich am Slaveserver an und bearbeiten Sie [.filename]#/etc/rc.conf# analog zum Masterserver. Erzeugen Sie aber keine NIS-Maps, da diese bereits auf dem Server vorhanden sind. Wenn `ypinit` auf dem Slaveserver ausgeführt wird, benutzen Sie `-s` (Slave) statt `-m` (Master). Diese Option benötigt den Namen des NIS-Masterservers und den Domänennamen, wie in diesem Beispiel zu sehen: [source,shell] .... coltrane# ypinit -s ellington test-domain Server Type: SLAVE Domain: test-domain Master: ellington Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. There will be no further questions. The remainder of the procedure should take a few minutes, to copy the databases from ellington. Transferring netgroup... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byuser... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byhost... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring group.bygid... ypxfr: Exiting: Map successfully transferred Transferring group.byname... ypxfr: Exiting: Map successfully transferred Transferring services.byname... ypxfr: Exiting: Map successfully transferred Transferring rpc.bynumber... ypxfr: Exiting: Map successfully transferred Transferring rpc.byname... ypxfr: Exiting: Map successfully transferred Transferring protocols.byname... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byaddr... ypxfr: Exiting: Map successfully transferred Transferring netid.byname... ypxfr: Exiting: Map successfully transferred Transferring hosts.byaddr... ypxfr: Exiting: Map successfully transferred Transferring protocols.bynumber... ypxfr: Exiting: Map successfully transferred Transferring ypservers... ypxfr: Exiting: Map successfully transferred Transferring hosts.byname... ypxfr: Exiting: Map successfully transferred coltrane has been setup as an YP slave server without any errors. Remember to update map ypservers on ellington. .... Hierbei wird auf dem Slaveserver ein Verzeichnis namens [.filename]#/var/yp/test-domain# erstellt, welches Kopien der NIS-Masterserver-Maps enthält. Durch hinzufügen der folgenden Zeilen in [.filename]#/etc/crontab# wird der Slaveserver angewiesen, seine Maps mit den Maps des Masterservers zu synchronisieren: [.programlisting] .... 20 * * * * root /usr/libexec/ypxfr passwd.byname 21 * * * * root /usr/libexec/ypxfr passwd.byuid .... Diese Einträge sind nicht zwingend notwendig, da der Masterserver automatisch versucht, alle Änderungen seiner NIS-Maps an seine Slaveserver weiterzugeben. Da Passwortinformationen aber auch für nur vom Slaveserver abhängige Systeme vital sind, ist es eine gute Idee, diese Aktualisierungen zu erzwingen. Besonders wichtig ist dies in stark ausgelasteten Netzen, in denen Map-Aktualisierungen unvollständig sein könnten. Um die Konfiguration abzuschließen, führen Sie `/etc/netstart` auf dem Slaveserver aus, um die NIS-Dienste erneut zu starten. === Einen NIS-Client einrichten Ein NIS-Client `bindet` sich unter Verwendung von `ypbind` an einen NIS-Server. Dieser Daemon sendet RPC-Anfragen auf dem lokalen Netzwerk. Diese Anfragen legen den Namen der Domäne fest, die auf dem Client konfiguriert ist. Wenn der Server der entsprechenden Domäne eine solche Anforderung erhält, schickt er eine Antwort an `ypbind`, das wiederum die Adresse des Servers speichert. Wenn mehrere Server verfügbar sind, verwendet der Client die erste erhaltene Adresse und richtet alle Anfragen an genau diesen Server. `ypbind` "pingt" den Server gelegentlich an, um sicherzustellen, dass der Server funktioniert. Antwortet der Server innerhalb eines bestimmten Zeitraums nicht (Timeout), markiert `ypbind` die Domäne als ungebunden und beginnt erneut, RPCs über das Netzwerk zu verteilen, um einen anderen Server zu finden. Einen FreeBSD-Rechner als NIS-Client einrichten: [.procedure] . Fügen Sie folgende Zeilen in [.filename]#/etc/rc.conf# ein, um den NIS-Domänennamen festzulegen, und um man:ypbind[8] bei der Initialisierung des Netzwerks zu starten: + [.programlisting] .... nisdomainname="test-domain" nis_client_enable="YES" .... . Um alle Passworteinträge des NIS-Servers zu importieren, löschen Sie alle Benutzerkonten in [.filename]#/etc/master.passwd# mit `vipw`. Denken Sie daran, zumindest ein lokales Benutzerkonto zu behalten. Dieses Konto sollte außerdem Mitglied der Gruppe `wheel` sein. Wenn es mit NIS Probleme gibt, können Sie diesen Zugang verwenden, um sich als Superuser anzumelden und das Problem zu beheben. Bevor Sie die Änderungen speichern, fügen Sie folgende Zeile am Ende der Datei hinzu: + [.programlisting] .... +::::::::: .... + Diese Zeile legt für alle gültigen Benutzerkonten der NIS-Server-Maps einen Zugang an. Es gibt verschiedene Wege, den NIS-Client durch Änderung dieser Zeile zu konfigurieren. Eine Methode wird in <> beschrieben. Weitere detaillierte Informationen finden Sie im Buch `Managing NFS and NIS` vom O'Reilly Verlag. . Um alle möglichen Gruppeneinträge vom NIS-Server zu importieren, fügen Sie folgende Zeile in [.filename]#/etc/group# ein: + [.programlisting] .... +:*:: .... Um den NIS-Client direkt zu starten, führen Sie als Superuser die folgenden Befehle aus: [source,shell] .... # /etc/netstart # service ypbind start .... Danach sollte bei der Eingabe von `ypcat passwd` auf dem Client die `passwd-Map` des NIS-Servers angezeigt werden. === Sicherheit unter NIS Da RPC ein Broadcast-basierter Dienst ist, kann jedes System innerhalb der Domäne mittels ypbind den Inhalt der NIS-Maps abrufen. Um nicht autorisierte Transaktionen zu verhindern, unterstützt man:ypserv[8] eine Funktion namens "securenets", durch die der Zugriff auf bestimmte Rechner beschränkt werden kann. In der Voreinstellung sind diese Informationen in [.filename]#/var/yp/securenets# gespeichert, es sei denn, man:ypserv[8] wurde mit der Option `-p` und einem alternativen Pfad gestartet. Diese Datei enthält Einträge, die aus einer Netzwerkadresse und einer Netzmaske bestehen. Kommentarzeilen beginnen mit "#". [.filename]##/var/yp/securnets## könnte beispielsweise so aussehen: [.programlisting] .... # allow connections from local host -- mandatory 127.0.0.1 255.255.255.255 # allow connections from any host # on the 192.168.128.0 network 192.168.128.0 255.255.255.0 # allow connections from any host # between 10.0.0.0 to 10.0.15.255 # this includes the machines in the testlab 10.0.0.0 255.255.240.0 .... Wenn man:ypserv[8] eine Anforderung von einer zu diesen Regeln passenden Adresse erhält, wird die Anforderung bearbeitet. Gibt es keine passende Regel, wird die Anforderung ignoriert und eine Warnmeldung aufgezeichnet. Wenn [.filename]#securenets# nicht existiert, erlaubt `ypserv` Verbindungen von jedem Rechner. crossref:security[tcpwrappers,"TCP Wrapper"] beschreibt eine alternative Methode zur Zugriffskontrolle. Obwohl beide Methoden einige Sicherheit gewähren, sind sie anfällig für "IP-Spoofing"-Angriffe. Der NIS-Verkehr sollte daher von einer Firewall blockiert werden. Server, die [.filename]#securenets# verwenden, können Schwierigkeiten bei der Anmeldung von NIS-Clients haben, die ein veraltetes TCP/IP-Subsystem besitzen. Einige dieser TCP/IP-Subsysteme setzen alle Rechnerbits auf Null, wenn sie einen `Broadcast` durchführen oder können die Subnetzmaske nicht auslesen, wenn sie die Broadcast-Adresse berechnen. Einige Probleme können durch Änderungen der Clientkonfiguration behoben werden. Andere hingegen lassen sich nur durch das Entfernen des betreffenden Rechners aus dem Netzwerk oder den Verzicht auf [.filename]#securenets# umgehen. Die Verwendung der TCP-Wrapper verlangsamt die Reaktion des NIS-Servers. Diese zusätzliche Reaktionszeit kann in Clientprogrammen zu Timeouts führen. Dies vor allem in Netzwerken, die stark ausgelastet sind, oder nur über langsame NIS-Server verfügen. Wenn ein oder mehrere Clients dieses Problem aufweisen, sollten Sie die betreffenden Clients in NIS-Slaveserver umwandeln, und diese an sich selbst binden. ==== Bestimmte Benutzer an der Anmeldung hindern In diesem Beispiel gibt es innerhalb der NIS-Domäne den Rechner `basie`, der nur für Mitarbeiter der Fakultät bestimmt ist. Die [.filename]#passwd# Datenbank des NIS-Masterservers enthält Benutzerkonten sowohl für Fakultätsmitarbeiter als auch für Studenten. Dieser Abschnitt beschreibt, wie Sie den Mitarbeitern der Fakultät die Anmeldung am System ermöglichen, während den Studenten die Anmeldung verweigert wird. Es gibt eine Möglichkeit, bestimmte Benutzer an der Anmeldung an einem bestimmten Rechner zu hindern, selbst wenn diese in der NIS-Datenbank vorhanden sind. Dazu kann mit `vipw` der Eintrag `-_Benutzername_` und die richtige Anzahl von Doppelpunkten an das Ende von [.filename]#/etc/master.passwd# gesetzt werden, wobei _Benutzername_ der zu blockierende Benutzername ist. Die Zeile mit dem geblockten Benutzer muss dabei vor der `+` Zeile, für zugelassene Benutzer stehen. In diesem Beispiel wird die Anmeldung für den Benutzer `bill` am Rechner `basie` blockiert: [source,shell] .... basie# cat /etc/master.passwd root:[password]:0:0::0:0:The super-user:/root:/bin/csh toor:[password]:0:0::0:0:The other super-user:/root:/bin/sh daemon:*:1:1::0:0:Owner of many system processes:/root:/usr/sbin/nologin operator:*:2:5::0:0:System &:/:/usr/sbin/nologin bin:*:3:7::0:0:Binaries Commands and Source,,,:/:/usr/sbin/nologin tty:*:4:65533::0:0:Tty Sandbox:/:/usr/sbin/nologin kmem:*:5:65533::0:0:KMem Sandbox:/:/usr/sbin/nologin games:*:7:13::0:0:Games pseudo-user:/usr/games:/usr/sbin/nologin news:*:8:8::0:0:News Subsystem:/:/usr/sbin/nologin man:*:9:9::0:0:Mister Man Pages:/usr/shared/man:/usr/sbin/nologin bind:*:53:53::0:0:Bind Sandbox:/:/usr/sbin/nologin uucp:*:66:66::0:0:UUCP pseudo-user:/var/spool/uucppublic:/usr/libexec/uucp/uucico xten:*:67:67::0:0:X-10 daemon:/usr/local/xten:/usr/sbin/nologin pop:*:68:6::0:0:Post Office Owner:/nonexistent:/usr/sbin/nologin nobody:*:65534:65534::0:0:Unprivileged user:/nonexistent:/usr/sbin/nologin -bill::::::::: +::::::::: basie# .... [[network-netgroups]] === Netzgruppen verwenden Bestimmten Benutzern die Anmeldung an einzelnen Systemen zu verweigern, kann in großen Netzwerken schnell unübersichtlich werden. Dadurch verlieren Sie den Hauptvorteil von NIS: die _zentrale_ Verwaltung. Netzgruppen wurden entwickelt, um große, komplexe Netzwerke mit Hunderten Benutzern und Rechnern zu verwalten. Ihre Aufgabe ist vergleichbar mit UNIX(R) Gruppen. Die Hauptunterschiede sind das Fehlen einer numerischen ID sowie die Möglichkeit, Netzgruppen zu definieren, die sowohl Benutzer als auch andere Netzgruppen enthalten. Um das Beispiel in diesem Kapitel fortzuführen, wird die NIS-Domäne um zusätzliche Benutzer und Rechner erweitert: .Zusätzliche Benutzer [cols="1,1", frame="none", options="header"] |=== | Benutzername(n) | Beschreibung |`alpha`, `beta` |Mitarbeiter der IT-Abteilung |`charlie`, `delta` |Lehrlinge der IT-Abteilung |`echo`, `foxtrott`, `golf`, ... |Mitarbeiter |`able`, `baker`, ... |Praktikanten |=== .Zusätzliche Rechner [cols="1,1", frame="none", options="header"] |=== | Rechnername(n) | Beschreibung |`war`, `death`, `famine`, `pollution` |Nur Mitarbeiter der IT-Abteilung dürfen sich an diesen Rechnern anmelden. |`pride`, `greed`, `envy`, `wrath`, `lust`, `sloth` |Nur Mitarbeiter und Lehrlinge der IT-Abteilung dürfen sich auf diesen Rechnern anmelden. |`one`, `two`, `three`, `four`, ... |Gewöhnliche Arbeitsrechner für Mitarbeiter. |`trashcan` |Ein sehr alter Rechner ohne kritische Daten. Sogar Praktikanten dürfen diesen Rechner verwenden. |=== Bei der Verwendung von Netzgruppen wird jeder Benutzer einer oder mehreren Netzgruppen zugewiesen und die Anmeldung wird dann für die Netzgruppe erlaubt oder verwehrt. Wenn ein neuer Rechner hinzugefügt wird, müssen die Zugangsbeschränkungen nur für die Netzgruppen festgelegt werden. Wird ein neuer Benutzer angelegt, muss er einer oder mehreren Netzgruppen zugewiesen werden. Wenn die Einrichtung von NIS sorgfältig geplant wurde, muss nur noch eine zentrale Konfigurationsdatei bearbeitet werden, um den Zugriff auf bestimmte Rechner zu erlauben oder zu verbieten. Dieses Beispiel erstellt vier Netzgruppen: IT-Mitarbeiter, IT-Lehrlinge, normale Mitarbeiter sowie Praktikanten: [.programlisting] .... IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) USERS (,echo,test-domain) (,foxtrott,test-domain) \ (,golf,test-domain) INTERNS (,able,test-domain) (,baker,test-domain) .... Jede Zeile konfiguriert eine Netzgruppe. Die erste Spalte der Zeile bezeichnet den Namen der Netzgruppe. Die Einträge in den Klammern stehen entweder für eine Gruppe von einem oder mehreren Benutzern, oder für den Namen einer weiteren Netzgruppe. Wenn ein Benutzer angegeben wird, haben die drei Felder in der Klammer folgende Bedeutung: . Der Name des Rechner(s), auf dem die weiteren Felder für den Benutzer gültig sind. Wird kein Rechnername festgelegt, ist der Eintrag auf allen Rechnern gültig. . Der Name des Benutzerkontos, der zu dieser Netzgruppe gehört. . Die NIS-Domäne für das Benutzerkonto. Benutzerkonten können von anderen NIS-Domänen in eine Netzgruppe importiert werden. Wenn eine Gruppe mehrere Benutzer enthält, müssen diese durch Leerzeichen getrennt werden. Darüber hinaus kann jedes Feld Wildcards enthalten. Weitere Einzelheiten finden Sie in man:netgroup[5]. Netzgruppennamen sollten nicht länger als 8 Zeichen sein. Es wird zwischen Groß- und Kleinschreibung unterschieden. Die Verwendung von Großbuchstaben für Netzgruppennamen ermöglicht eine leichte Unterscheidung zwischen Benutzern, Rechnern und Netzgruppen. Einige NIS-Clients (dies gilt nicht für FreeBSD) können keine Netzgruppen mit mehr als 15 Einträgen verwalten. Diese Grenze kann umgangen werden, indem mehrere Subnetzgruppen mit weniger als fünfzehn Benutzern angelegt werden und diese Subnetzgruppen wiederum in einer Netzgruppe zusammengefasst wird, wie in diesem Beispiel zu sehen: [.programlisting] .... BIGGRP1 (,joe1,domain) (,joe2,domain) (,joe3,domain) [...] BIGGRP2 (,joe16,domain) (,joe17,domain) [...] BIGGRP3 (,joe31,domain) (,joe32,domain) BIGGROUP BIGGRP1 BIGGRP2 BIGGRP3 .... Wiederholen Sie diesen Vorgang, wenn mehr als 225 (15*15) Benutzer in einer einzigen Netzgruppe existieren. Die neue NIS-Map aktivieren und verteilen: [source,shell] .... ellington# cd /var/yp ellington# make .... Dadurch werden die NIS-Maps [.filename]#netgroup#, [.filename]#netgroup.byhost# und [.filename]#netgroup.byuser# erzeugt. Prüfen Sie die Verfügbarkeit der neuen NIS-Maps mit man:ypcat[1]: [source,shell] .... ellington% ypcat -k netgroup ellington% ypcat -k netgroup.byhost ellington% ypcat -k netgroup.byuser .... Die Ausgabe des ersten Befehls gibt den Inhalt von [.filename]#/var/yp/netgroup# wieder. Der zweite Befehl erzeugt nur dann eine Ausgabe, wenn rechnerspezifische Netzgruppen erzeugt wurden. Der dritte Befehl gibt die Netzgruppen nach Benutzern sortiert aus. Wenn Sie einen Client einrichten, verwenden Sie man:vipw[8] um den Namen der Netzgruppe anzugeben. Ersetzen Sie beispielsweise auf dem Server namens `war` die folgende Zeile: [.programlisting] .... +::::::::: .... durch [.programlisting] .... +@IT_EMP::::::::: .... ersetzt werden. Diese Zeile legt fest, dass nur noch Benutzer der Netzgruppe `IT_EMP` in die Passwortdatenbank dieses Systems importiert werden. Nur diese Benutzer dürfen sich an diesem Server anmelden. Diese Konfiguration gilt auch für die `~`-Funktion der Shell und für alle Routinen, die auf Benutzernamen und numerische Benutzer-IDs zugreifen. Oder anders formuliert, `cd ~_Benutzer_` ist nicht möglich, `ls -l` zeigt die numerische Benutzer-ID statt dem Benutzernamen und `find . -user joe -print` erzeugt die Fehlermeldung `No such user`. Um dieses Problem zu beheben, müssen alle Benutzereinträge importiert werden, ohne ihnen jedoch zu erlauben, sich am Server anzumelden. Dies kann durch das Hinzufügen einer zusätzlichen Zeile erreicht werden: [.programlisting] .... +:::::::::/usr/sbin/nologin .... Diese Zeile weist den Client an, alle Einträge zu importieren, aber die Shell in diesen Einträgen durch [.filename]#/usr/sbin/nologin# zu ersetzen. Stellen Sie sicher, dass die zusätzliche Zeile _nach_ der Zeile `+@IT_EMP:::::::::` eingetragen ist. Andernfalls haben alle via NIS importierten Benutzerkonten [.filename]#/usr/sbin/nologin# als Loginshell und niemand wird sich mehr am System anmelden können. Um die weniger wichtigen Server zu konfigurieren, ersetzen Sie den alten Eintrag `+:::::::::` auf den Servern mit diesen Zeilen: [.programlisting] .... +@IT_EMP::::::::: +@IT_APP::::::::: +:::::::::/usr/sbin/nologin .... Die entsprechenden Zeilen für Arbeitsplätze lauten: [.programlisting] .... +@IT_EMP::::::::: +@USERS::::::::: +:::::::::/usr/sbin/nologin .... NIS ist in der Lage, Netzgruppen aus anderen Netzgruppen zu bilden. Dies kann nützlich sein, wenn sich die Firmenpolitik ändert. Eine Möglichkeit ist die Erzeugung rollenbasierter Netzgruppen. Sie könnten eine Netzgruppe `BIGSRV` erzeugen, um den Zugang zu den wichtigsten Servern zu beschränken, eine weitere Gruppe `SMALLSRV` für die weniger wichtigen Server und eine dritte Netzgruppe `USERBOX` für die Arbeitsplatzrechner. Jede dieser Netzgruppen enthält die Netzgruppen, die sich auf diesen Rechnern anmelden dürfen. Die Einträge der Netzgruppen in der NIS-Map sollten ähnlich den folgenden aussehen: [.programlisting] .... BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS .... Diese Methode funktioniert besonders gut, wenn Rechner in Gruppen mit identischen Beschränkungen eingeteilt werden können. Unglücklicherweise ist dies die Ausnahme und nicht die Regel. Meistens wird die Möglichkeit zur rechnerspezischen Zugangsbeschränkung benötigt. Rechnerspezifische Netzgruppen sind eine weitere Möglichkeit, um mit den oben beschriebenen Änderungen umzugehen. In diesem Szenario enthält [.filename]#/etc/master.passwd# auf jedem Rechner zwei mit "+" beginnende Zeilen. Die erste Zeile legt die Netzgruppe mit den Benutzern fest, die sich auf diesem Rechner anmelden dürfen. Die zweite Zeile weist allen anderen Benutzern [.filename]#/usr/sbin/nologin# als Shell zu. Verwenden Sie auch hier (analog zu den Netzgruppen) Großbuchstaben für die Rechnernamen: [.programlisting] .... +@BOXNAME::::::::: +:::::::::/usr/sbin/nologin .... Sobald dies für alle Rechner erledigt ist, müssen die lokalen Versionen von [.filename]#/etc/master.passwd# nie mehr verändert werden. Alle weiteren Änderungen geschehen über die NIS-Maps. Nachfolgend ein Beispiel für eine mögliche Netzgruppen-Map: [.programlisting] .... # Define groups of users first IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) DEPT1 (,echo,test-domain) (,foxtrott,test-domain) DEPT2 (,golf,test-domain) (,hotel,test-domain) DEPT3 (,india,test-domain) (,juliet,test-domain) ITINTERN (,kilo,test-domain) (,lima,test-domain) D_INTERNS (,able,test-domain) (,baker,test-domain) # # Now, define some groups based on roles USERS DEPT1 DEPT2 DEPT3 BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS # # And a groups for a special tasks # Allow echo and golf to access our anti-virus-machine SECURITY IT_EMP (,echo,test-domain) (,golf,test-domain) # # machine-based netgroups # Our main servers WAR BIGSRV FAMINE BIGSRV # User india needs access to this server POLLUTION BIGSRV (,india,test-domain) # # This one is really important and needs more access restrictions DEATH IT_EMP # # The anti-virus-machine mentioned above ONE SECURITY # # Restrict a machine to a single user TWO (,hotel,test-domain) # [...more groups to follow] .... Es ist nicht immer ratsam, rechnerbasierte Netzgruppen zu verwenden. Wenn Dutzende oder Hunderte identische Rechner eingerichtet werden müssen, sollten rollenbasierte Netzgruppen verwendet werden, um die Größe der NIS-Maps in Grenzen zu halten. === Passwortformate Alle Rechner innerhalb der NIS-Domäne müssen für die Verschlüsselung von Passwörtern das gleiche Format benutzen. Wenn Benutzer Schwierigkeiten bei der Authentifizierung auf einem NIS-Client haben, liegt dies möglicherweise an einem anderen Passwort-Format. In einem heterogenen Netzwerk muss das verwendete Format von allen Betriebssystemen unterstützt werden, wobei DES der kleinste gemeinsame Standard ist. Welches Format die Server und Clients verwenden, steht in [.filename]#/etc/login.conf#: [.programlisting] .... default:\ :passwd_format=des:\ :copyright=/etc/COPYRIGHT:\ [weitere Einträge] .... In diesem Beispiel verwendet das System das Format DES. Weitere mögliche Werte sind unter anderem `blf` und `md5` (mit Blowfish und MD5 verschlüsselte Passwörter). Wird auf einem Rechner das Format entsprechend der NIS-Domäne geändert, muss anschließend die Login-Capability Datenbank neu erstellt werden: [source,shell] .... # cap_mkdb /etc/login.conf .... [NOTE] ==== Das Format der schon bestehenden Passwörter wird erst aktualisiert, wenn ein Benutzer sein Passwort ändert, _nachdem_ die Datenbank neu erstellt wurde. ==== [[network-ldap]] == Lightweight Access Directory Protocol (LDAP) Das Lightweight Directory Access Protocol (LDAP) ist ein Protokoll der Anwendungsschicht, das verwendet wird um Objekte mithilfe eines verteilten Verzeichnisdienstes abzurufen, zu verändern und zu authentifizieren. Betrachten Sie es als ein Telefonbuch, das homogene Informationen in mehreren hierarchischen Ebenen speichert. Es wird in Active Directory und OpenLDAP-Netzwerken eingesetzt, in denen Benutzer unter Verwendung eines einzigen Kontos auf diverse interne Informationen zugreifen. Beispielsweise kann E-Mail-Authentifizierung, Abfrage von Kontaktinformationen und Website-Authentifizierung über ein einzelnes Benutzerkonto aus der Datenbank des LDAP-Servers erfolgen. Dieser Abschnitt enthält eine kompakte Anleitung, um einen LDAP-Server auf einem FreeBSD-System zu konfigurieren. Es wird vorausgesetzt, dass der Administrator bereits einen Plan erarbeitet hat, der verschiedene Punkte umfasst, unter anderem die Art der zu speichernden Informationen, für was die Informationen verwendet werden, welche Benutzer Zugriff auf die Informationen haben und wie die Informationen vor unbefugtem Zugriff geschützt werden. === LDAP Terminologie und Struktur LDAP verwendet mehrere Begriffe die Sie verstehen sollten bevor Sie die Konfiguration beginnen. Alle Verzeichniseinträge bestehen aus einer Gruppe von _Attributen_. Jede Attributgruppe enthält einen eindeutigen Bezeichner, der als distinguished name (DN) bekannt ist. Dieser setzt sich normalerweise aus mehreren anderen Attributen, wie dem Relative Distinguished Name (RDN) zusammen. Wie bei Verzeichnissen gibt es auch hier absolute und relative Pfade. Betrachten Sie DN als absoluten Pfad und RDN als relativen Pfad. Beispielsweise könnte ein LDAP-Eintrag wie folgt aussehen. Dieses Beispiel sucht nach dem Eintrag für das angegebene Benutzerkonto (`uid`), Organisationseinheit (`ou` und Organisation (`o`): [source,shell] .... % ldapsearch -xb "uid=trhodes,ou=users,o=example.com" # extended LDIF # # LDAPv3 # base with scope subtree # filter: (objectclass=*) # requesting: ALL # # trhodes, users, example.com dn: uid=trhodes,ou=users,o=example.com mail: trhodes@example.com cn: Tom Rhodes uid: trhodes telephoneNumber: (123) 456-7890 # search result search: 2 result: 0 Success # numResponses: 2 # numEntries:1 .... Die Einträge in diesem Beispiel zeigen die Werte für die Attribute `dn`, `mail`, `cn`, `uid` und `telephoneNumber`. Das Attribut `cn` ist der RDN. Weitere Informationen über LDAP und dessen Terminologie finden Sie unter http://www.openldap.org/doc/admin24/intro.html[ http://www.openldap.org/doc/admin24/intro.html]. [[ldap-config]] === Konfiguration eines LDAP-Servers FreeBSD integriert keinen LDAP-Server. Beginnen Sie die Konfiguration mit der Installation des Ports oder Pakets package:net/openldap-server[]: [source,shell] .... # pkg install openldap-server .... Im extref:{linux-users}[Paket,#software] sind eine große Anzahl an Optionen aktiviert. Mit dem Befehl `pkg info openldap-server` können diese überprüft werden. Falls die Optionen nicht ausreichend sind (weil bspw. SQL-Unterstützung benötigt wird), sollten Sie in Betracht ziehen, den Port mit dem entsprechenden Framework neu zu übersetzen. Während der Installation wird für die Daten das Verzeichnis [.filename]#/var/db/openldap-data# erstellt. Das Verzeichnis für die Ablage der Zertifikate muss manuell angelegt werden: [source,shell] .... # mkdir /usr/local/etc/openldap/private .... Im nächsten Schritt wird die Zertifizierungsstelle konfiguriert. Die folgenden Befehle müssen in [.filename]#/usr/local/etc/openldap/private# ausgeführt werden. Dies ist wichtig, da die Dateiberechtigungen restriktiv gesetzt werden und Benutzer keinen direkten Zugriff auf diese Daten haben sollten. Weitere Informationen über Zertifikate und deren Parameter finden Sie im crossref:security[openssl,"OpenSSL"]. Geben Sie folgenden Befehl ein, um die Zertifizierungsstelle zu erstellen und folgen Sie den Anweisungen: [source,shell] .... # openssl req -days 365 -nodes -new -x509 -keyout ca.key -out ../ca.crt .... Diese Einträge sind frei wählbar, _mit Ausnahme_ von _Common Name_. Hier muss etwas anderes als der Hostname des Systems eingetragen werden. Wenn ein selbstsigniertes Zertifikat verwendet wird, stellen Sie dem Hostnamen einfach das Präfix `CA` für die Zertifizierungsstelle voran. Die nächste Aufgabe besteht darin, einen Zertifikatsregistrierungsanforderung (CSR) sowie einen privaten Schlüssel zu erstellen. Geben Sie folgenden Befehl ein und folgen Sie den Anweisungen: [source,shell] .... # openssl req -days 365 -nodes -new -keyout server.key -out server.csr .... Stellen Sie hierbei sicher, dass `Common Name` richtig eingetragen wird. Die Zertifikatsregistrierungsanforderung muss mit dem Schlüssel der Zertifizierungsstelle unterschrieben werden, um als gültiges Zertifikat verwendet zu werden: [source,shell] .... # openssl x509 -req -days 365 -in server.csr -out ../server.crt -CA ../ca.crt -CAkey ca.key -CAcreateserial .... Der letzte Schritt für die Erstellung der Zertifikate besteht darin, die Client-Zertifikate zu erstellen und zu signieren: [source,shell] .... # openssl req -days 365 -nodes -new -keyout client.key -out client.csr # openssl x509 -req -days 3650 -in client.csr -out ../client.crt -CAkey ca.key .... Achten Sie wieder auf das Attribut `Common name`. Stellen Sie außerdem sicher, dass bei diesem Verfahren acht (8) neue Dateien erzeugt worden sind. Der Daemon, auf dem der OpenLDAP-Server läuft, heißt [.filename]#slapd#. Die Konfiguration erfolgt über [.filename]#slapd.ldif#. Die alte [.filename]#slapd.conf# wird von OpenLDAP nicht mehr verwendet. http://www.openldap.org/doc/admin24/slapdconf2.html[Konfigurationsbeispiele] für [.filename]#slapd.ldif# finden sich auch in [.filename]#/usr/local/etc/openldap/slapd.ldif.sample#. Optionen sind in slapd-config(5) dokumentiert. Jeder Abschnitt in [.filename]#slapd.ldif# wird, wie alle anderen LDAP-Attributgruppen, durch einen DN eindeutig identifiziert. Achten Sie darauf, dass keine Leerzeilen zwischen der Anweisung `dn:` und dem gewünschten Ende des Abschnitts verbleiben. Im folgenden Beispiel wird TLS verwendet, um einen sicheren Kanal zu implementieren. Der erste Abschnitt stellt die globale Konfiguration dar: [.programlisting] .... # # See slapd-config(5) for details on configuration options. # This file should NOT be world readable. # dn: cn=config objectClass: olcGlobal cn: config # # # Define global ACLs to disable default read access. # olcArgsFile: /var/run/openldap/slapd.args olcPidFile: /var/run/openldap/slapd.pid olcTLSCertificateFile: /usr/local/etc/openldap/server.crt olcTLSCertificateKeyFile: /usr/local/etc/openldap/private/server.key olcTLSCACertificateFile: /usr/local/etc/openldap/ca.crt #olcTLSCipherSuite: HIGH olcTLSProtocolMin: 3.1 olcTLSVerifyClient: never .... Hier müssen die Zertifizierungsstelle, das Serverzertifikat und die privaten Schlüssel des Servers angegeben werden. Es wird empfohlen, den Clients die Wahl der Sicherheits-Chiffre zu überlassen und die Option `olcTLSCipherSuite` wegzulassen (inkompatibel mit anderen TLS-Clients als [.filename]#openssl#). Mit der Option `olcTLSProtocolMin` benötigt der Server nur eine minimale Sicherheitsstufe. Diese Option wird empfohlen. Während die Verfizierung für den Server verpflichtend ist, ist sie es nicht für den Client: `olcTLSVerifyClient: never`. Der zweite Abschnitt behandelt die Backend-Module und kann wie folgt konfiguriert werden: [.programlisting] .... # # Load dynamic backend modules: # dn: cn=module,cn=config objectClass: olcModuleList cn: module olcModulepath: /usr/local/libexec/openldap olcModuleload: back_mdb.la #olcModuleload: back_bdb.la #olcModuleload: back_hdb.la #olcModuleload: back_ldap.la #olcModuleload: back_passwd.la #olcModuleload: back_shell.la .... Der dritte Abschnitt widmet sich dem Laden der benötigten ldif-Schemata, die von den Datenbanken verwendet werden sollen. Diese Dateien sind essentiell. [.programlisting] .... dn: cn=schema,cn=config objectClass: olcSchemaConfig cn: schema include: file:///usr/local/etc/openldap/schema/core.ldif include: file:///usr/local/etc/openldap/schema/cosine.ldif include: file:///usr/local/etc/openldap/schema/inetorgperson.ldif include: file:///usr/local/etc/openldap/schema/nis.ldif .... Als nächstes folgt der Abschnitt zur Frontend-Konfiguration: [.programlisting] .... # Frontend settings # dn: olcDatabase={-1}frontend,cn=config objectClass: olcDatabaseConfig objectClass: olcFrontendConfig olcDatabase: {-1}frontend olcAccess: to * by * read # # Sample global access control policy: # Root DSE: allow anyone to read it # Subschema (sub)entry DSE: allow anyone to read it # Other DSEs: # Allow self write access # Allow authenticated users read access # Allow anonymous users to authenticate # #olcAccess: to dn.base="" by * read #olcAccess: to dn.base="cn=Subschema" by * read #olcAccess: to * # by self write # by users read # by anonymous auth # # if no access controls are present, the default policy # allows anyone and everyone to read anything but restricts # updates to rootdn. (e.g., "access to * by * read") # # rootdn can always read and write EVERYTHING! # olcPasswordHash: {SSHA} # {SSHA} is already the default for olcPasswordHash .... Ein weiterer Abschnitt ist dem Konfigurations-Backend gewidmet, der einzige Weg, später auf die OpenLDAP-Serverkonfiguration zuzugreifen, ist als globaler Superuser. [.programlisting] .... dn: olcDatabase={0}config,cn=config objectClass: olcDatabaseConfig olcDatabase: {0}config olcAccess: to * by * none olcRootPW: {SSHA}iae+lrQZILpiUdf16Z9KmDmSwT77Dj4U .... Der voreingestellte Benutzername für den Administrator lautet `cn=config`. Geben Sie [.filename]#slappasswd# in eine Shell ein, wählen Sie ein Passwort und verwenden Sie seinen Hash in `olcRootPW`. Wenn diese Option jetzt nicht angegeben ist, kann vor dem Import der [.filename]#slapd.ldif# niemand später den Abschnitt _global configuration_ ändern. Der letzte Abschnitt befasst sich mit dem Datenbank-Backend: [.programlisting] .... ####################################################################### # LMDB database definitions ####################################################################### # dn: olcDatabase=mdb,cn=config objectClass: olcDatabaseConfig objectClass: olcMdbConfig olcDatabase: mdb olcDbMaxSize: 1073741824 olcSuffix: dc=domain,dc=example olcRootDN: cn=mdbadmin,dc=domain,dc=example # Cleartext passwords, especially for the rootdn, should # be avoided. See slappasswd(8) and slapd-config(5) for details. # Use of strong authentication encouraged. olcRootPW: {SSHA}X2wHvIWDk6G76CQyCMS1vDCvtICWgn0+ # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools. # Mode 700 recommended. olcDbDirectory: /var/db/openldap-data # Indices to maintain olcDbIndex: objectClass eq .... Diese Datenbank enthält den _eigentlichen Inhalt_ des LDAP-Verzeichnisses. Neben `mdb` sind weitere Versionen verfügbar. Dessen Superuser, nicht zu verwechseln mit dem globalen, wird hier konfiguriert: ein Benutzername in `olcRootDN` und der Passworthash in `olcRootPW`; [.filename]#slappasswd# kann wie zuvor benutzt werden. Dieses http://www.openldap.org/devel/gitweb.cgi?p=openldap.git;a=tree;f=tests/data/regressions/its8444;h=8a5e808e63b0de3d2bdaf2cf34fecca8577ca7fd;hb=HEAD[Repository] enthält vier Beispiele für [.filename]#slapd.ldif#. Lesen Sie diese Seite, um eine bestehende [.filename]#slapd.conf# in [.filename]#slapd.ldif# zu konvertieren. Beachten Sie, dass dies einige unbrauchbare Optionen einführen kann. Wenn die Konfiguration abgeschlossen ist, muss [.filename]#slapd.ldif# in ein leeres Verzeichnis verschoben werden. Folgendes ist die empfohlene Vorgehensweise: [source,shell] .... # mkdir /usr/local/etc/openldap/slapd.d/ .... Importieren Sie die Konfigurationsdatenbank: [source,shell] .... # /usr/local/sbin/slapadd -n0 -F /usr/local/etc/openldap/slapd.d/ -l /usr/local/etc/openldap/slapd.ldif .... Starten Sie den [.filename]#slapd#-Daemon: [source,shell] .... # /usr/local/libexec/slapd -F /usr/local/etc/openldap/slapd.d/ .... Die Option `-d` kann, wie in slapd(8) beschrieben, zur Fehlersuche benutzt werden. Stellen Sie sicher, dass der Server läuft und korrekt arbeitet: [source,shell] .... # ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts # extended LDIF # # LDAPv3 # base <> with scope baseObject # filter: (objectclass=*) # requesting: namingContexts # # dn: namingContexts: dc=domain,dc=example # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... Dem Server muss noch vertraut werden. Wenn dies noch nie zuvor geschehen ist, befolgen Sie diese Anweisungen. Installieren Sie das Paket oder den Port OpenSSL: [source,shell] .... # pkg install openssl .... Aus dem Verzeichnis, in dem [.filename]#ca.crt# gespeichert ist (in diesem Beispiel [.filename]#/usr/local/etc/openldap#), starten Sie: [source,shell] .... # c_rehash . .... Sowohl die CA als auch das Serverzertifikat werden nun in ihren jeweiligen Rollen korrekt erkannt. Um dies zu überprüfen, führen die folgenden Befehl aus dem Verzeichnis der [.filename]#server.crt# aus: [source,shell] .... # openssl verify -verbose -CApath . server.crt .... Falls [.filename]#slapd# ausgeführt wurde, muss der Daemon neu gestartet werden. Wie in [.filename]#/usr/local/etc/rc.d/slapd# angegeben, müssen die folgenden Zeilen in [.filename]#/etc/rc.conf# eingefügt werden, um [.filename]#slapd# beim Booten ordnungsgemäß auszuführen: [.programlisting] .... lapd_enable="YES" slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://0.0.0.0/"' slapd_sockets="/var/run/openldap/ldapi" slapd_cn_config="YES" .... [.filename]#slapd# bietet beim Booten keine Möglichkeit zur Fehlersuche. Überprüfen Sie dazu [.filename]#/var/log/debug.log#, `dmesg -a` und [.filename]#/var/log/messages#. Das folgende Beispiel fügt die Gruppe `team` und den Benutzer `john` zur LDAP-Datenbank `domain.example` hinzu, die bislang leer ist. Erstellen Sie zunächst die Datei [.filename]#domain.ldif#: [source,shell] .... # cat domain.ldif dn: dc=domain,dc=example objectClass: dcObject objectClass: organization o: domain.example dc: domain dn: ou=groups,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: groups dn: ou=users,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: users dn: cn=team,ou=groups,dc=domain,dc=example objectClass: top objectClass: posixGroup cn: team gidNumber: 10001 dn: uid=john,ou=users,dc=domain,dc=example objectClass: top objectClass: account objectClass: posixAccount objectClass: shadowAccount cn: John McUser uid: john uidNumber: 10001 gidNumber: 10001 homeDirectory: /home/john/ loginShell: /usr/bin/bash userPassword: secret .... Weitere Informationen finden Sie in der OpenLDAP-Dokumentation. Benutzen Sie [.filename]#slappasswd#, um das Passwort durch einen Hash in `userPassword` zu ersetzen. Der in `loginShell` angegebene Pfad muss in allen Systemen existieren, in denen `john` sich anmelden darf. Benutzen Sie schließlich den `mdb`-Administrator, um die Datenbank zu ändern: [source,shell] .... # ldapadd -W -D "cn=mdbadmin,dc=domain,dc=example" -f domain.ldif .... Änderungen im Bereich _global configuration_ können nur vom globalen Superuser vorgenommen werden. Angenommen die Option `olcTLSCipherSuite: HIGH:MEDIUM:SSLv3` wurde ursprünglich definiert und soll nun gelöscht werden. Dazu erstellen Sie zunächst eine Datei mit folgendem Inhalt: [source,shell] .... # cat global_mod dn: cn=config changetype: modify delete: olcTLSCipherSuite .... Übernehmen Sie dann die Änderungen: [source,shell] .... # ldapmodify -f global_mod -x -D "cn=config" -W .... Geben Sie bei Aufforderung das im Abschnitt _configuration backend_ gewählte Passwort ein. Der Benutzername ist nicht erforderlich: Hier repräsentiert `cn=config` den DN des zu ändernden Datenbankabschnitts. Alternativ können Sie mit `ldapmodify` eine einzelne Zeile der Datenbank löschen, mit `ldapdelete` einen ganzen Eintrag. Wenn etwas schief geht oder der globale Superuser nicht auf das Konfigurations-Backend zugreifen kann, ist es möglich, die gesamte Konfiguration zu löschen und neu zu schreiben: [source,shell] .... # rm -rf /usr/local/etc/openldap/slapd.d/ .... [.filename]#slapd.ldif# kann dann bearbeitet und erneut importiert werden. Bitte folgenden Sie dieser Vorgehensweise nur, wenn keine andere Lösung verfügbar ist. Dies ist nur die Konfiguration des Servers. Auf demselben Rechner kann auch ein LDAP-Client mit eigener, separater Konfiguration betrieben werden. [[network-dhcp]] == Dynamic Host Configuration Protocol (DHCP) Das Dynamic Host Configuration Protocol (DHCP) ermöglicht es einem System, sich mit einem Netzwerk zu verbinden und die für die Kommunikation mit diesem Netzwerk nötigen Informationen zu beziehen. FreeBSD verwendet den von OpenBSD stammenden `dhclient`, um die Adressinformationen zu beziehen. FreeBSD installiert keinen DHCP-Server, aber es stehen einige Server in der FreeBSD Ports-Sammlung zu Verfügung. Das DHCP-Protokoll wird vollständig im http://www.freesoft.org/CIE/RFC/2131/[ RFC 2131] beschrieben. Eine weitere, lehrreiche Informationsquelle existiert unter http://www.isc.org/downloads/dhcp[ isc.org/downloads/dhcp/]. In diesem Abschnitt wird beschrieben, wie der integrierte DHCP-Client verwendet wird. Anschließend wird erklärt, wie ein DHCP-Server zu installieren und konfigurieren ist. [NOTE] ==== Unter FreeBSD wird das Gerät man:bpf[4] für den DHCP-Server und den DHCP-Client benötigt. Das Gerät ist bereits im [.filename]#GENERIC#-Kernel enthalten. Benutzer, die es vorziehen einen angepassten Kernel zu erstellen, müssen dieses Gerät behalten, wenn DHCP verwendet wird. Es sei darauf hingewiesen, dass [.filename]#bpf# es priviligierten Benutzern ermöglicht einen Paket-Sniffer auf dem System auszuführen. ==== === Einen DHCP-Client konfigurieren Die Unterstützung für den DHCP-Client ist im Installationsprogramm von FreeBSD enthalten, sodass ein neu installiertes System automatisch die Adressinformationen des Netzwerks vom DHCP-Server erhält. In crossref:bsdinstall[bsdinstall-post,"Benutzerkonten, Zeitzone, Dienste und Sicherheitsoptionen"] finden Sie Beispiele für eine Netzwerkkonfiguration. `dhclient` beginnt von einem Clientrechner aus über den UDP-Port 68 Konfigurationsinformationen anzufordern. Der Server antwortet auf dem UDP-Port 67, indem er dem Client eine IP-Adresse zuweist und ihm weitere relevante Informationen über das Netzwerk, wie Netzmasken, Router und DNS-Server mitteilt. Diese Informationen werden als DHCP-Lease bezeichnet und sind nur für bestimmte Zeit, die vom Administrator des DHCP-Servers vorgegeben wird, gültig. Dadurch fallen verwaiste IP-Adressen, deren Clients nicht mehr mit dem Netzwerk verbunden sind, automatisch an den Server zurück. DHCP-Clients können sehr viele Informationen von einem DHCP-Server erhalten. Eine ausführliche Liste finden Sie in man:dhcp-options[5]. Das Gerät [.filename]#bpf# ist im [.filename]#GENERIC#-Kernel bereits enthalten. Für die Nutzung von DHCP muss also kein angepasster Kernel erzeugt werden. In einer angepassten Kernelkonfigurationsdatei muss das Gerät enthalten sein, damit DHCP ordnungsgemäß funktioniert. Standardmässig läuft die DHCP-Konfiguration bei FreeBSD im Hintergrund oder auch _asynchron_. Andere Startskripte laufen weiter, während DHCP fertig abgearbeitet wird, was den Systemstart beschleunigt. DHCP im Hintergrund funktioniert gut, wenn der DHCP-Server schnell auf Anfragen der Clients antwortet. Jedoch kann DHCP eine lange Zeit benötigen, um auf manchen Systemen fertig zu werden. Falls Netzwerkdienste gestartet werden, bevor DHCP die Informationen und Netzwerkadressen gesetzt hat, werden diese fehlschlagen. Durch die Verwendung von DHCP im _asynchronen_ Modus wird das Problem verhindert, so dass die Startskripte pausiert werden, bis die DHCP-Konfiguration abgeschlossen ist. Diese Zeile wird in [.filename]#/etc/rc.conf# verwendet, um den asynchronen Modus zu aktivieren: [.programlisting] .... ifconfig_fxp0="DHCP" .... Die Zeile kann bereits vorhanden sein, wenn bei der Installation des Systems DHCP konfiguriert wurde. Ersetzen Sie _fxp0_ durch die entsprechende Schnittstelle. Die dynamische Konfiguration von Netzwerkkarten wird in crossref:config[config-network-setup,“Einrichten von Netzwerkkarten”] beschrieben. Um stattdessen den synchronen Modus zu verwenden, der während des Systemstarts pausiert bis die DHCP-Konfiguration abgeschlossen ist, benutzen Sie "SYNCDHCP": [.programlisting] .... ifconfig_fxp0="SYNCDHCP" .... Es stehen weitere Optionen für den Client zur Verfügung. Suchen Sie in man:rc.conf[5] nach `dhclient`, wenn Sie an Einzelheiten interessiert sind. Der DHCP-Client verwendet die folgenden Dateien: * [.filename]#/etc/dhclient.conf# + Die Konfigurationsdatei von `dhclient`. Diese Datei enthält normalerweise nur Kommentare, da die Vorgabewerte zumeist ausreichend sind. Diese Konfigurationsdatei wird in man:dhclient.conf[5] beschrieben. * [.filename]#/sbin/dhclient# + Weitere Informationen über dieses Kommando finden Sie in man:dhclient[8]. * [.filename]#/sbin/dhclient-script# + Das FreeBSD-spezifische Konfigurationsskript des DHCP-Clients. Es wird in man:dhclient-script[8] beschrieben und kann meist unverändert übernommen werden. * [.filename]#/var/db/dhclient.leases.interface# + Der DHCP-Client verfügt über eine Datenbank, die alle derzeit gültigen Leases enthält und als Logdatei erzeugt wird. Diese Datei wird in man:dhclient.leases[5] beschrieben. [[network-dhcp-server]] === Einen DHCP-Server installieren und einrichten -Dieser Abschnitt beschreibt die Einrichtung eines FreeBSD-Systems als DHCP-Server. Dazu wird die DHCP-Implementation von ISC (Internet Systems Consortium) verwendet. Diese Implementation und die Dokumentation können als Port oder Paket package:net/isc-dhcp43-server[] installiert werden. +Dieser Abschnitt beschreibt die Einrichtung eines FreeBSD-Systems als DHCP-Server. Dazu wird die DHCP-Implementation von ISC (Internet Systems Consortium) verwendet. Diese Implementation und die Dokumentation können als Port oder Paket package:net/isc-dhcp44-server[] installiert werden. -Der Port package:net/isc-dhcp43-server[] installiert eine Beispiel-Konfigurationsdatei. Kopieren Sie [.filename]#/usr/local/etc/dhcpd.conf.example# nach [.filename]#/usr/local/etc/dhcpd.conf# und nehmen Sie die Änderungen an der neuen Datei vor. +Der Port package:net/isc-dhcp44-server[] installiert eine Beispiel-Konfigurationsdatei. Kopieren Sie [.filename]#/usr/local/etc/dhcpd.conf.example# nach [.filename]#/usr/local/etc/dhcpd.conf# und nehmen Sie die Änderungen an der neuen Datei vor. Diese Konfigurationsdatei umfasst Deklarationen für Subnetze und Rechner, die den DHCP-Cleints zur Verfügung gestellt wird. Die folgenden Zeilen konfigurieren Folgendes: [.programlisting] .... option domain-name "example.org";<.> option domain-name-servers ns1.example.org;<.> option subnet-mask 255.255.255.0;<.> default-lease-time 600;<.> max-lease-time 72400;<.> ddns-update-style none;<.> subnet 10.254.239.0 netmask 255.255.255.224 { range 10.254.239.10 10.254.239.20;<.> option routers rtr-239-0-1.example.org;<.> } host fantasia { hardware ethernet 08:00:07:26:c0:a5;<.> fixed-address fantasia.fugue.com;<.> } .... <.> Diese Option beschreibt die Standardsuchdomäne, die den Clients zugewiesen wird. Weitere Informationen finden Sie in man:resolv.conf[5]. <.> Diese Option legt eine, durch Kommata getrennte Liste von DNS-Servern fest, die von den Clients verwendet werden sollen. Die Server können über den Namen (FQDN) oder die IP-Adresse spezifiziert werden. <.> Die den Clients zugewiesene Subnetzmaske. <.> Die Voreinstellung für die Ablaufzeit des Lease in Sekunden. Ein Client kann diesen Wert in der Konfiguration überschreiben. <.> Die maximale Zeitdauer, für die der Server Leases vergibt. Sollte ein Client eine längere Zeitspanne anfordern, wird dennoch nur der Wert `max-lease-time` zugewiesen. <.> Die Voreinstellung `none` deaktiviert dynamische DNS-Updates. Bei der Einstellung `interim` aktualisiert der DHCP-Server den DNS-Server, wenn ein Lease vergeben oder zurückgezogen wurde. Ändern Sie die Voreinstellung nicht, wenn der Server so konfiguriert wurde, dynamische DNS-Updates zu unterstützen. <.> Diese Zeile erstellt einen Pool der verfügbaren IP-Adressen, die für die Zuweisung der DHCP-Clients reserviert sind. Der Bereich muss für das angegebene Netz oder Subnetz aus der vorherigen Zeile gültig sein. <.> Legt das Standard-Gateway für das Netz oder Subnetz fest, das nach der öffnenden Klammer `{` gültig ist. <.> Bestimmt die Hardware-MAC-Adresse eines Clients, durch die der DHCP-Server den Client erkennt, der eine Anforderung an ihn stellt. <.> Einem Rechner soll immer die gleiche IP-Adresse zugewiesen werden. Hier ist auch ein Rechnername gültig, da der DHCP-Server den Rechnernamen auflöst, bevor er das Lease zuweist. Die Konfigurationsdatei unterstützt viele weitere Optionen. Lesen Sie man:dhcpd.conf[5], die mit dem Server installiert wird, für Details und Beispiele. Nachdem [.filename]#dhcpd.conf# konfiguriert ist, aktivieren Sie den DHCP-Server in [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" dhcpd_ifaces="dc0" .... Dabei müssen Sie `dc0` durch die Gerätedatei (mehrere Gerätedateien müssen durch Leerzeichen getrennt werden) ersetzen, die der DHCP-Server auf Anfragen von DHCP-Clients hin überwachen soll. Starten Sie den Server mit folgenden Befehl: [source,shell] .... # service isc-dhcpd start .... Künftige Änderungen an der Konfiguration des Servers erfordern, dass der Dienst `dhcpd` gestoppt und anschließend mit man:service[8] gestartet wird. * [.filename]#/usr/local/sbin/dhcpd# + Weitere Informationen zu dhcpd finden Sie in man:dhcpd[8]. * [.filename]#/usr/local/etc/dhcpd.conf# + Die Konfigurationsdatei des Servers muss alle Informationen enthalten, die an die Clients weitergegeben werden soll. Außerdem sind hier Informationen zur Konfiguration des Servers enthalten. Diese Konfigurationsdatei wird in man:dhcpd.conf[5] beschrieben. * [.filename]#/var/db/dhcpd.leases# + Der DHCP-Server hat eine Datenbank, die alle vergebenen Leases enthält. Diese wird als Logdatei erzeugt. man:dhcpd.leases[5] enthält eine ausführliche Beschreibung. * [.filename]#/usr/local/sbin/dhcrelay# + -Dieser Daemon wird in komplexen Umgebungen verwendet, in denen ein DHCP-Server eine Anfrage eines Clients an einen DHCP-Server in einem separaten Netzwerk weiterleitet. Wenn Sie diese Funktion benötigen, müssen Sie package:net/isc-dhcp43-relay[] installieren. Weitere Informationen zu diesem Thema finden Sie in man:dhcrelay[8]. +Dieser Daemon wird in komplexen Umgebungen verwendet, in denen ein DHCP-Server eine Anfrage eines Clients an einen DHCP-Server in einem separaten Netzwerk weiterleitet. Wenn Sie diese Funktion benötigen, müssen Sie package:net/isc-dhcp44-relay[] installieren. Weitere Informationen zu diesem Thema finden Sie in man:dhcrelay[8]. [[network-dns]] == Domain Name System (DNS) DNS ist das für die Umwandlung von Rechnernamen in IP-Adressen zuständige Protokoll. Im Internet wird DNS durch ein komplexes System von autoritativen Root-Nameservern, Top Level Domain-Servern (TLD) sowie anderen kleineren Nameservern verwaltet, die individuelle Domaininformationen speichern und untereinander abgleichen. Für einfache DNS-Anfragen wird auf dem lokalen System kein Nameserver benötigt. Die folgende Tabelle beschreibt einige mit DNS verbundenen Begriffe: .DNS-Begriffe [cols="1,1", frame="none", options="header"] |=== | Begriff | Bedeutung |Forward-DNS |Rechnernamen in IP-Adressen umwandeln. |Origin (Ursprung) |Die in einer bestimmten Zonendatei beschriebene Domäne. |Resolver |Ein Systemprozess, durch den ein Rechner Zoneninformationen von einem Nameserver anfordert. |Reverse-DNS |die Umwandlung von IP-Adressen in Rechnernamen |Root-Zone |Der Beginn der Internet-Zonenhierarchie. Alle Zonen befinden sich innerhalb der Root-Zone. Dies ist analog zu einem Dateisystem, in dem sich alle Dateien und Verzeichnisse innerhalb des Wurzelverzeichnisses befinden. |Zone |Eine individuelle Domäne, Unterdomäne, oder ein Teil von DNS, der von der gleichen Autorität verwaltet wird. |=== Es folgen nun einige Zonenbeispiele: * Innerhalb der Dokumentation wird die Root-Zone in der Regel mit `.` bezeichnet. * `org.` ist eine Top level Domain (TLD) innerhalb der Root-Zone. * `example.org.` ist eine Zone innerhalb der `org.`-TLD. * `1.168.192.in-addr.arpa.` ist die Zone mit allen IP-Adressen des Bereichs `192.168.1.*`. Wie man an diesen Beispielen erkennen kann, befindet sich der spezifischere Teil eines Rechnernamens auf der linken Seite der Adresse. `example.org.` beschreibt einen Rechner also genauer als `org.`, während `org.` genauer als die Root-Zone ist. Jeder Teil des Rechnernamens hat Ähnlichkeiten mit einem Dateisystem, in dem etwa [.filename]#/dev# dem Wurzelverzeichnis untergeordnet ist. === Gründe für die Verwendung eines Nameservers Es gibt zwei Arten von Nameservern: Autoritative Nameserver sowie zwischenspeichernde (cachende, auch bekannt als auflösende) Nameserver. Ein autoritativer Nameserver ist notwendig, wenn * Sie anderen verbindliche DNS-Auskünfte erteilen wollen. * eine Domain, beispielsweise `example.org`, registriert wird, und den zu dieser Domain gehörenden Rechnern IP-Adressen zugewiesen werden müssen. * ein IP-Adressblock reverse-DNS-Einträge benötigt, um IP-Adressen in Rechnernamen auflösen zu können. * ein Backup-Nameserver (auch Slaveserver genannt) oder ein zweiter Nameserver auf Anfragen antworten soll. Ein cachender Nameserver ist notwendig, weil * ein lokaler DNS-Server Daten zwischenspeichern und daher schneller auf Anfragen reagieren kann als ein entfernter Server. Wird nach `www.FreeBSD.org` gesucht, leitet der Resolver diese Anfrage an den Nameserver des ISPs weiter und nimmt danach das Ergebnis der Abfrage entgegen. Existiert ein lokaler, zwischenspeichernder DNS-Server, muss dieser die Anfrage nur einmal nach außen weitergeben. Für alle weiteren Anfragen ist dies nicht mehr nötig, da diese Information nun lokal gespeichert ist. === DNS-Server Konfiguration Unbound ist im Basissystem von FreeBSD enthalten. In der Voreinstellung bietet es nur die DNS-Auflösung auf dem lokalen Rechner. Obwohl das im Basissystem enthaltene Unbound konfiguriert werden kann, um Namensauflösung über den lokalen Rechner hinweg bereitzustellen, ist es empfehlenswert für solche Anforderungen Unbound aus der FreeBSD Ports-Sammlung zu installieren. Um Unbound zu aktivieren, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... local_unbound_enable="YES" .... Alle vorhandenen Nameserver aus [.filename]#/etc/resolv.conf# werden als Forwarder in der neuen Unbound-Konfiguration benutzt. [NOTE] ==== Wenn einer der aufgeführten Nameserver kein DNSSEC unterstützt, wird die lokale DNS-Auflösung nicht funktionieren. Testen Sie jeden Server und entfernen Sie die Server, die den Test nicht bestehen. Das folgende Beispiel zeigt einen Trust Tree beziehungsweise einen Fehler für den Nameserver auf `192.168.1.1`: ==== [source,shell] .... # drill -S FreeBSD.org @192.168.1.1 .... Nachdem jeder Server für DNSSEC konfiguriert ist, starten Sie Unbound: [source,shell] .... # service local_unbound onestart .... Dieses Kommando sorgt für die Aktualisierung von [.filename]#/etc/resolv.conf#, so dass Abfragen für DNSSEC gesicherte Domains jetzt funktionieren. Führen Sie folgenden Befehl aus, um den DNSSECTrust Tree für FreeBSD.org zu überprüfen: [source,shell] .... % drill -S FreeBSD.org ;; Number of trusted keys: 1 ;; Chasing: freebsd.org. A DNSSEC Trust tree: freebsd.org. (A) |---freebsd.org. (DNSKEY keytag: 36786 alg: 8 flags: 256) |---freebsd.org. (DNSKEY keytag: 32659 alg: 8 flags: 257) |---freebsd.org. (DS keytag: 32659 digest type: 2) |---org. (DNSKEY keytag: 49587 alg: 7 flags: 256) |---org. (DNSKEY keytag: 9795 alg: 7 flags: 257) |---org. (DNSKEY keytag: 21366 alg: 7 flags: 257) |---org. (DS keytag: 21366 digest type: 1) | |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) | |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) |---org. (DS keytag: 21366 digest type: 2) |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) ;; Chase successful .... [[network-apache]] == Apache HTTP-Server Der Open Source Apache HTTP-Server ist der am weitesten verbreitete Webserver. Dieser Webserver ist nicht im Basissystem von FreeBSD enthalten, kann aber als Paket oder Port package:www/apache24[] installiert werden. Dieser Abschnitt beschreibt die Konfiguration der Version 2._x_ des Apache HTTP-Server. Weiterführende Informationen und Konfigurationsanweisungen für Apache 2.X finden Sie unter http://httpd.apache.org/[ httpd.apache.org]. === Apache konfigurieren und starten Der Apache HTTP-Server wird unter FreeBSD primär in [.filename]#/usr/local/etc/apache2x/httpd.conf# konfiguriert, wobei das _x_ die Versionsnummer darstellt. In dieser Textdatei leitet ein `#` einen Kommentar ein. Die am häufigsten verwendeten Optionen sind: `ServerRoot "/usr/local"`:: Legt das Standardwurzelverzeichnis für die Apache-Installation fest. Binärdateien werden in die Verzeichnisse [.filename]#bin# und [.filename]#sbin# unterhalb des Serverwurzelverzeichnisses installiert, während sich Konfigurationsdateien im Unterverzeichnis [.filename]#etc/apache2x# befinden. `ServerAdmin you@example.com`:: Die E-Mail-Adresse, an die Mitteilungen über Serverprobleme geschickt werden. Diese Adresse erscheint auf vom Server erzeugten Seiten, beispielsweise auf Fehlerseiten. `ServerName www.example.com:80`:: Erlaubt dem Administrator, einen Rechnernamen festzulegen, den der Server an die Clients sendet. Beispielsweise könnte `www` statt des richtigen Rechnernamens verwendet werden. Wenn das System keinen eingetragenen DNS-Namen hat, kann stattdessen die IP-Adresse eingetragen werden. Lauscht der Server auf einem anderen Port, tauschen Sie die `80` gegen eine entsprechende Portnummer. `DocumentRoot "/usr/local/www/apache2__x__/data"`:: Das Verzeichnis, in dem die Dokumente abgelegt sind. In der Voreinstellung befinden sich alle Seiten in diesem Verzeichnis, durch symbolische Links oder Aliase lassen sich aber auch andere Orte festlegen. Es ist empfehlenswert, eine Sicherungskopie der Apache-Konfigurationsdatei anzulegen, bevor Änderungen durchgeführt werden. Wenn die Konfiguration von Apache abgeschlossen ist, speichern Sie die Datei und überprüfen Sie die Konfiguration mit `apachectl`. Der Befehl `apachectl configtest` sollte `Syntax OK` zurückgeben. Um den Apache beim Systemstart zu starten, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... apache24_enable="YES" .... Wenn Sie während des Systemstarts weitere Parameter an den Apache übergeben wollen, können Sie diese durch eine zusätzliche Zeile in [.filename]#rc.conf# angeben: [.programlisting] .... apache24_flags="" .... Wenn apachectl keine Konfigurationsfehler meldet, starten Sie `httpd`: [source,shell] .... # service apache24 start .... Sie können den `httpd`-Dienst testen, indem Sie `http://_localhost_` in einen Browser eingeben, wobei Sie _localhost_ durch den vollqualifizierten Domainnamen der Maschine ersetzen, auf dem der `httpd` läuft. Die Standard Webseite, die angezeigt wird, ist [.filename]#/usr/local/www/apache24/data/index.html#. Die Konfiguration von Apache kann bei nachfolgenden Änderungen an der Konfigurationsdatei bei laufendem `httpd`, auf Fehler überprüft werden. Geben Sie dazu folgendes Kommando ein: [source,shell] .... # service apache24 configtest .... [NOTE] ==== Es ist wichitg zu beachten, dass `configtest` kein man:rc[8]-Standard ist, und somit nicht zwingend mit anderen man:rc[8]-Startskripten funktioniert. ==== === Virtual Hosting Virtual Hosting ermöglicht es, mehrere Webseiten auf einem Apache-Server laufen zu lassen. Die virtuellen Hosts können _IP-basiert_ oder _namensbasiert_ sein. IP-basiertes virtual Hosting verwendet eine IP-Adresse für jede Webseite. Beim namensbasierten virtual Hosting wird der HTTP/1.1-Header der Clients dazu verwendet, den Rechnernamen zu bestimmen. Dadurch wird es möglich, mehrere Domains unter der gleichen IP-Adresse zu betreiben. Damit der Apache namenbasierte virtuelle Domains verwalten kann, fügen Sie für jede Webseite einen separaten `VirtualHost`-Block ein. Wenn der Webserver beispielsweise `www.domain.tld` heißt und die virtuelle Domain `www.someotherdomain.tld` einrichtet werden soll, ergänzen Sie [.filename]#httpd.conf# um folgende Einträge: [.programlisting] .... ServerName www.domain.tld DocumentRoot /www/domain.tld ServerName www.someotherdomain.tld DocumentRoot /www/someotherdomain.tld .... Setzen Sie für jeden virtuellen Host die entsprechenden Werte für `ServerName` und `DocumentRoot`. Ausführliche Informationen zum Einrichten von virtuellen Hosts finden Sie in der offiziellen Apache-Dokumentation unter http://httpd.apache.org/docs/vhosts/[ http://httpd.apache.org/docs/vhosts/]. === Häufig verwendete Apache-Module Apache verwendet Module, die den Server um zusätzliche Funktionen erweitern. Eine vollständige Auflistung der zur Verfügung stehenden Module und Konfigurationsdetails finden Sie unter http://httpd.apache.org/docs/current/mod/[ http://httpd.apache.org/docs/current/mod/]. In FreeBSD können einige Module mit dem Port package:www/apache24[] kompiliert werden. Geben Sie in [.filename]#/usr/ports/www/apache24#`make config` ein, um zu sehen, welche Module zur Verfügung stehen und welche Module in der Voreinstellung aktiviert sind. Wenn ein Modul nicht zusammen mit dem Port kompiliert wird, bietet die Ports-Sammlung die Möglichkeit viele Module zu installieren. Dieser Abschnitt beschreibt drei der am häufigsten verwendeten Module. ==== SSL-Unterstützung Zu einem bestimmten Zeitpunkt erforderte die Unterstützung von SSL innerhalb von Apache ein separates Modul namens [.filename]#mod_ssl#. Dies ist nicht mehr der Fall und die Installation des Apache-Webservers wird im Standard mit SSL-Unterstützung ausgeliefert. Ein Beispiel, wie Sie SSL-Unterstützung für einen Webserver aktivieren können, finden Sie in der Datei [.filename]#httpd-ssl.conf# im Verzeichnis [.filename]#/usr/local/etc/apache24/extra#. In diesem Verzeichnis befindet sich auch eine Beispieldatei namens [.filename]#ssl.conf-sample#. Es wird empfohlen, beide Dateien zu überprüfen, um sichere Webseiten auf dem Apache-Webserver einzurichten. Nachdem die Konfiguration von SSL abgeschlossen ist, muss die folgende Zeile in [.filename]#httpd.conf# auskommentiert werden, um die Änderungen beim nächsten Neustart oder erneuten Laden der Konfiguration zu aktivieren: [.programlisting] .... #Include etc/apache24/extra/httpd-ssl.conf .... [WARNING] ==== SSL in Version 2 und 3 haben bekannte Schwachstellen. Es wird dringend empfohlen, TLS Version 1.2 und 1.3 anstelle der älteren SSL-Optionen zu aktivieren. Dies kann durch die Einstellung der folgenden Optionen in [.filename]#ssl.conf# erreicht werden: ==== [.programlisting] .... SSLProtocol all -SSLv3 -SSLv2 +TLSv1.2 +TLSv1.3 SSLProxyProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 .... Um die Konfiguration von SSL im Webserver abzuschließen, entfernen Sie den Kommentar in der folgenden Zeile, um sicherzustellen, dass die Konfiguration bei einem Neustart oder beim erneuten laden der Konfiguration von Apache übernommen wird: [.programlisting] .... # Secure (SSL/TLS) connections Include etc/apache24/extra/httpd-ssl.conf .... Diese Zeilen müssen in [.filename]#httpd.conf# ebenfalls auskommentiert bleiben, um SSL in Apache vollständig zu unterstützen: [.programlisting] .... LoadModule authn_socache_module libexec/apache24/mod_authn_socache.so LoadModule socache_shmcb_module libexec/apache24/mod_socache_shmcb.so LoadModule ssl_module libexec/apache24/mod_ssl.so .... Der nächste Schritt ist die Kooperation mit einer Zertifizierungsstelle, um die entsprechenden Zertifikate auf dem System installieren zu lassen. Dadurch wird eine Vertrauenskette für die Webseite etabliert und jegliche Warnungen vor selbstsignierten Zertifikaten verhindert. ==== [.filename]#mod_perl# Das Modul [.filename]#mod_perl# macht es möglich, vollständig in Perl geschriebene Apache-Module zu erzeugen. Da der Perl-Interpreter in den Server eingebettet wird, muss weder ein externer Interpreter noch Perl zusätzlich aufgerufen werden. [.filename]#mod_perl# wird über den Port oder das Paket package:www/mod_perl2[] installiert. Dokumentation für dieses Modul finden Sie unter http://perl.apache.org/docs/2.0/index.html[ http://perl.apache.org/docs/2.0/index.html]. ==== [.filename]#mod_php# _PHP: Hypertext Preprocessor_ (PHP) ist eine vielseitig verwendbare Skriptsprache, die besonders für die Web-Entwicklung geeignet ist. PHP kann in HTML eingebettet werden und ähnelt von der Syntax her Sprachen wie C, Java(TM) und Perl. Das Hauptanliegen von PHP ist es, Web-Entwicklern die rasche Erstellung von dynamisch erzeugten Internetseiten zu ermöglichen. PHP und weitere in PHP geschriebene Funktionen unterstützt, muss das entsprechende Paket installiert werden. Sie können mit `pkg` die Paketdatenbank nach allen unterstützten PHP-Versionen durchsuchen: [source,shell] .... # pkg search php .... Die Ausgabe ist eine Liste mit Versionen und Funktionen des jeweiligen Pakets. Die Komponenten sind vollständig modular, d.h. die Funktionen werden durch die Installation des entsprechenden Pakets aktiviert. Geben Sie folgenden Befehl ein, um PHP-Version 7.4 für Apache zu installieren: [source,shell] .... # pkg install mod_php74 .... Falls irgendwelche Pakete Abhängigkeiten besitzen, werden diese zusätzlichen Pakete ebenfalls installiert. Standardmäßig ist PHP nicht aktiviert. Die folgenden Zeilen müssen in der Apache-Konfigurationsdatei unterhalb von [.filename]#/usr/local/etc/apache24# hinzugefügt werden, um PHP zu aktivieren: [.programlisting] .... SetHandler application/x-httpd-php SetHandler application/x-httpd-php-source .... Zusätzlich muss auch der `DirectoryIndex` in der Konfigurationsdatei aktualisiert werden und Apache muss entweder neu gestartet, oder die Konfiguration neu geladen werden, damit die Änderungen wirksam werden. Mit `pkg` kann die Unterstützung für viele weitere PHP-Funktionen installiert werden. Um beispielsweise die Unterstützung für XML oder SSL zu erhalten, installieren Sie die entsprechenden Pakete: [source,shell] .... # pkg install php74-xml php74-openssl .... Wie zuvor muss die Konfiguration von Apache neu geladen werden, damit die Änderungen wirksam werden. Dies gilt auch für Fälle, in denen lediglich ein Modul installiert wurde. Geben Sie folgenden Befehl ein, um einen geordneten Neustart durchzuführen und die Konfiguration neu zu laden: [source,shell] .... # apachectl graceful .... Sobald die Installation abgeschlossen ist, gibt es zwei Möglichkeiten, um eine Liste der installierten PHP-Module und Informationen über die Umgebung der Installation zu erhalten. Die erste Möglichkeit besteht darin, die vollständige PHP-Binärdatei zu installieren und den Befehl auszuführen, um die Informationen zu erhalten: [source,shell] .... # pkg install php74 .... [source,shell] .... # php -i | less .... Da die Ausgabe des Befehls sehr umfangreich ist, ist die Weiterleitung an einen Pager, wie beispielsweise `more` oder `less`, sinnvoll. Um Änderungen an der globalen Konfiguration von PHP vorzunehmen, gibt es schließlich eine gut dokumentierte Datei, die in [.filename]#/usr/local/etc/php.ini# installiert ist. Zum Zeitpunkt der Installation wird diese Datei nicht existieren, da zwei Versionen zur Auswahl stehen. Eine [.filename]#php.ini-development# und eine [.filename]#php.ini-production#. Diese Dateien sind Ansatzpunkte, die Administratoren bei der Implementierung unterstützen sollen. === Dynamische Webseiten Neben mod_perl und mod_php stehen noch weitere Sprachen zur Erstellung von dynamischen Inhalten zur Verfügung. Dazu gehören auch Django und Ruby on Rails. ==== Django Bei Django handelt es sich um ein unter der BSD-Lizenz verfügbares Framework zur schnellen Erstellung von mächtigen Internet-Applikationen. Es beinhaltet einen objekt-relationalen Mapper (wodurch Datentypen als Phyton-Objekte entwickelt werden können) sowie eine API für den dynamischen Datenbankzugriff auf diese Objekte, ohne dass Entwickler jemals SQL-Code schreiben müssen. Zusätzlich existiert ein umfangreiches Template-System, wodurch die Programmlogik von der HTML-Präsentation getrennt werden kann. Django setzt das Modul mod_python und eine SQL-Datenbank voraus. In FreeBSD wird bei der Installation von package:www/py-django[] automatisch [.filename]#mod_python# installiert. Als Datenbanken werden PostgreSQL, MySQL und SQLite unterstützt, wobei SQLite die Voreinstellung ist. Wenn Sie die Datenbank ändern möchten, geben Sie in [.filename]#/usr/ports/www/py-django#`make config` ein und installieren Sie den Port neu. Nachdem Django installiert ist, benötigt die Anwendung ein Projektverzeichnis und die Apache-Konfiguration, um den eingebetteten Python-Interpreter zu nutzen. Dieser Interpreter wird verwendet um die Anwendung für spezifische URLs der Seite aufrufen. Damit Apache Anfragen für bestimmte URLs an die Web-Applikation übergeben kann, müssen Sie den vollständigen Pfad zum Projektverzeichnis in [.filename]#httpd.conf# festlegen: [source,shell] .... SetHandler python-program PythonPath "['/pfad/zu/den/django/paketen/'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonAutoReload On PythonDebug On .... Weitere Informationen zur Verwendung von Django finden Sie unter https://docs.djangoproject.com/en/1.6/[ https://docs.djangoproject.com/en/1.6/]. ==== Ruby on Rails Ruby on Rails ist ein weiteres, als Open Source verfügbares Webframework. Es bietet einen kompletten Entwicklungsstack und erlaubt es Webentwicklern, umfangreiche und mächtige Applikationen in kurzer Zeit zu programmieren. Unter FreeBSD kann das Framework über den Port oder das Paket package:www/rubygem-rails[] installiert werden. Weitere Informationen zur Verwendung von Ruby on Rails finden Sie unter http://rubyonrails.org/documentation[ http://rubyonrails.org/documentation]. [[network-ftp]] == File Transfer Protocol (FTP) Das File Transfer Protocol (FTP) ermöglicht auf einfache Art und Weise den Dateiaustausch mit einem FTP-Server. Der FTP-Server ftpd ist bei FreeBSD bereits im Basisystem enthalten. FreeBSD verwendet mehrere Konfigurationsdateien, um den Zugriff auf den FTP zu kontrollieren. Dieser Abschnitt fasst diese Dateien zusammen. In man:ftpd[8] finden Sie weitere Inforamtionen über den integrierten FTP-Server. === Konfiguration Der wichtigste Punkt ist hier die Entscheidung darüber, welche Benutzer auf den FTP-Server zugreifen dürfen. Ein FreeBSD-System verfügt über diverse Systembenutzerkonten, die jedoch nicht auf den FTP-Server zugreifen sollen. Die Datei [.filename]#/etc/ftpusers# enthält alle Benutzer, die vom FTP-Zugriff ausgeschlossen sind. In der Voreinstellung gilt dies auch die gerade erwähnten Systembenutzerkonten. Sie können über diese Datei weitere Benutzer vom FTP-Zugriff ausschließen. In einigen Fällen kann es wünschenswert sein, den Zugang für manche Benutzer einzuschränken, ohne dabei FTP komplett zu verbieten. Dazu passen Sie [.filename]#/etc/ftpchroot#, wie in man:ftpchroot[5] beschrieben, entsprechend an. Diese Datei enthält Benutzer und Gruppen sowie die für sie geltenden Einschränkungen für FTP. Um anonymen FTP-Zugriff auf dem Server zu aktivieren, muss ein Benutzer `ftp` auf dem FreeBSD-System angelegt werden. Danach können sich Benutzer mit dem Benutzernamen `ftp` oder `anonymous` am FTP-Server anmelden. Das Passwort ist dabei beliebig, allerdings wird dazu in der Regel eine E-Mail-Adresse verwendet. Meldet sich ein anonymer Benutzer an, aktiviert der FTP-Server man:chroot[2], um den Zugriff auf das Heimatverzeichnis des Benutzers `ftp` zu beschränken. Es gibt zwei Textdateien, deren Inhalt den FTP-Clients bei der Anmeldung angezeigt wird. Der Inhalt von [.filename]#/etc/ftpwelcome# wird angezeigt, bevor der Login-Prompt erscheint. Nach einer erfolgreichen Anmeldung wird der Inhalt von [.filename]#/etc/ftpmotd# angezeigt. Beachten Sie aber, dass es dabei um einen Pfad relativ zur Umgebung des anzumeldenden Benutzers handelt. Bei einer anonymen Anmeldung würde also der Inhalt von [.filename]#~ftp/etc/ftpmotd# angezeigt. Sobald der FTP-Server konfiguriert ist, setzen Sie die entsprechende Variable in [.filename]#/etc/rc.conf#, damit der Dienst beim Booten gestartet wird: [.programlisting] .... ftpd_enable="YES" .... Starten Sie den Dienst: [source,shell] .... # service ftpd start .... Testen Sie die Verbindung zum FTP-Server, indem Sie folgendes eingeben: [source,shell] .... % ftp localhost .... === Wartung Der ftpd-Daemon verwendet man:syslog[3], um Protokolldateien zu erstellen. In der Voreinstellung werden alle FTP betreffenden Nachrichten nach [.filename]#/var/log/xferlog# geschrieben. Dies lässt sich aber durch das Einfügen der folgenden Zeile in [.filename]#/etc/syslog.conf# ändern: [.programlisting] .... ftp.info /var/log/xferlog .... [NOTE] ==== Beachten Sie, dass mit dem Betrieb eines anonymen FTP-Servers verschiedene Sicherheitsrisiken verbunden sind. Problematisch ist hier vor allem die Erlaubnis zum anonymen Upload von Dateien. Dadurch könnte der Server zur Verbreitung von illegaler oder nicht lizensierter Software oder noch Schlimmeren missbraucht werden. Wenn anonyme FTP-Uploads dennoch erforderlich sind, sollten Sie die Zugriffsrechte so setzen, dass solche Dateien erst nach Zustimmung eines Administrators von anderen Benutzern heruntergeladen werden können. ==== [[network-samba]] == Datei- und Druckserver für Microsoft(R) Windows(R)-Clients (Samba) Samba ist ein beliebtes Open Source Softwarepaket, das Datei- und Druckdienste über das SMB/CIFS-Protokoll zur Verfügung stellt. Dieses Protokoll ist in Microsoft(R) Windows(R)-Systemen enthalten und kann über die Installation der Samba-Client-Bibliotheken in andere Betriebssysteme integriert werden. Das Protokoll ermöglicht es Clients auf freigegebene Daten und Drucker zuzugreifen, so als ob es sich um lokale Drucker und Festplatten handeln würde. Unter FreeBSD können die Samba-Client-Bibliotheken über den Port oder das Paket package:net/samba410[] installiert werden. Der Client ermöglicht es einem FreeBSD-System auf SMB/CIFS-Freigaben in einem Microsoft(R) Windows(R)-Netzwerk zuzugreifen. Ein FreeBSD-System kann auch als Samba-Server agieren, wenn Sie den Port oder das Paket package:net/samba410[] installieren. Dies erlaubt es dem Administrator SMB/CIFS-Freigaben auf dem FreeBSD-System einzurichten, auf welche dann Clients mit Microsoft(R) Windows(R) oder den Samba-Client-Bibliotheken zugreifen können. === Konfiguration des Servers Samba wird in [.filename]#/usr/local/etc/smb4.conf# konfiguriert. Diese Datei muss erstellt werden, bevor Samba benutzt werden kann. Eine einfache [.filename]#smb4.conf#, wie hier gezeigt, stellt den Zugriff auf Verzeichnisse und Drucker für Windows(R)-Clients in einer Arbeitsgruppe (engl. Workgroup) zur Verfügung. In aufwendigeren Installationen, in denen LDAP oder Active Directory zum Einsatz kommt, ist es einfacher die [.filename]#smb4.conf# mit dem Werkzeug man:samba-tool[8] zu erstellen. [.programlisting] .... [global] workgroup = WORKGROUP server string = Samba Server Version %v netbios name = ExampleMachine wins support = Yes security = user passdb backend = tdbsam # Example: share /usr/src accessible only to 'developer' user [src] path = /usr/src valid users = developer writable = yes browsable = yes read only = no guest ok = no public = no create mask = 0666 directory mask = 0755 .... ==== Globale Einstellungen Einstellungen für das Netzwerk werden in [.filename]#/usr/local/etc/smb4.conf# definiert: `workgroup`:: Der Name der Arbeitsgruppe. `netbios name`:: Der NetBIOS-Namen fest, unter dem der Samba-Server bekannt ist. In der Regel handelt es sich dabei um den ersten Teil des DNS-Namens des Servers. `server string`:: Legt die Beschreibung fest, die angezeigt wird, wenn mit `net view` oder anderen Netzwerkprogrammen Informationen über den Server angefordert werden. `wins support`:: Legt fest, ob Samba als WINS-Server fungieren soll. Aktivieren Sie die Unterstützung für WINS auf maximal einem Server im Netzwerk. ==== Samba absichern Die wichtigsten Einstellungen in [.filename]#/usr/local/etc/smb4.conf# betreffen das zu verwendende Sicherheitsmodell sowie das Backend-Passwortformat. Die folgenden Direktiven steuern diese Optionen: `security`:: Die häufigsten Optionen sind `security = share` und `security = user`. Wenn die Clients Benutzernamen verwenden, die den Benutzernamen auf dem FreeBSD-Rechner entsprechen, dann sollte die Einstellung `user level` verwendet werden. Dies ist die Standardeinstellung. Allerdings ist es dazu erforderlich, dass sich die Clients auf dem Rechner anmelden, bevor sie auf gemeinsame Ressourcen zugreifen können. + In der Einstellung `share level` müssen sich Clients nicht unter Verwendung eines gültigen Logins auf dem Rechner anmelden, bevor sie auf gemeinsame Ressourcen zugreifen können. In früheren Samba-Versionen war dies die Standardeinstellung. `passdb backend`:: Samba erlaubt verschiedene Backend-Authentifizierungsmodelle. Clients können sich durch LDAP, NIS+, eine SQL-Datenbank oder eine Passwortdatei authentifizieren. Die empfohlene Authentifizierungsmethode, `tdbsam`, ist ideal für einfache Netzwerke und wird hier vorgestellt. Für größere oder komplexere Netzwerke wird `ldapsam` empfohlen. `smbpasswd` war der frühere Standard und gilt mittlerweile als veraltet. ==== Samba Benutzer Damit Windows(R)-Clients auf die Freigaben zugreifen können, müssen die FreeBSD-Benutzerkonten in der `SambaSAMAccount`-Datenbank zugeordnet werden. Für bereits vorhandene Benutzerkonten kann dazu man:pdbedit[8] benutzt werden: [source,shell] .... # pdbedit -a username .... Dieser Abschnitt beschreibt lediglich die am häufigsten verwendeten Einstellungen. Ausführliche Informationen zur Konfiguration von Samba finden Sie im http://www.samba.org/samba/docs/man/Samba-HOWTO-Collection/[ Official Samba HOWTO]. === Samba starten Damit Samba beim Systemstart automatisch aktiviert wird, fügen Sie die folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... samba_server_enable="YES" .... Jetzt kann Samba direkt gestartet werden: [source,shell] .... # service samba_server start Performing sanity check on Samba configuration: OK Starting nmbd. Starting smbd. .... Samba verwendet drei Daemonen. Sowohl nmbd als auch smbd werden durch `samba_enable` gestartet. Wenn eine Namensauflösung über winbind benötigt wird, setzen Sie zusätzlich: [.programlisting] .... winbindd_enable="YES" .... Samba kann jederzeit durch folgenden Befehl beendet werden: [source,shell] .... # service samba_server stop .... Samba ist ein komplexes Softwarepaket mit umfassenden Funktionen, die eine weitreichende Integration von Microsoft(R) Windows(R)-Netzwerken ermöglichen. Für eine Beschreibung dieser Zusatzfunktionen sollten Sie sich auf http://www.samba.org[http://www.samba.org] umsehen. [[network-ntp]] == Die Uhrzeit mit NTP synchronisieren Die interne Uhrzeit eines Computers ist nie ganz exakt. Dies ist problematisch, da viele Dienste darauf angewiesen sind, dass die Computer im Netzwerk die exakte Uhrzeit übermitteln. Die exakte Uhrzeit ist auch erforderlich um sicherzustellen, dass die Zeitstempel der Dateien konsistent bleiben. Das Network Time Protocol (NTP) bietet die Möglichkeit, die exakte Uhrzeit in einem Netzwerk zur Verfügung zu stellen. FreeBSD enthält man:ntpd[8], das andere NTP-Server abfragen kann um die Uhrzeit auf diesem Computer zu synchronisieren, oder um selbst die Uhrzeit für andere Computer im Netzwerk bereitzustellen. Dieser Abschnitt beschreibt die Konfiguration von ntpd unter FreeBSD. Zusätzliche Dokumentation im HTML-Format finden Sie in [.filename]#/usr/shared/doc/ntp/#. === NTP konfigurieren FreeBSD enthält mit ntpd ein Werkzeug, das zur Synchronisation der Uhrzeit verwendet werden kann. Die Konfiguration von Ntpd erfolgt über Variablen in man:rc.conf[5] und [.filename]#/etc/ntp.conf#, und wird in den folgenden Abschnitten beschrieben. Ntpd kommuniziert über UDP mit mit seinen Peers. Sämtliche Firewalls zwischen Ihrem Rechner und seinen NTP-Peers müssen so konfiguriert sein, dass UDP-Pakete auf Port 123 ein- und ausgehen können. ==== [.filename]#/etc/ntp.conf# Ntpd liest [.filename]#/etc/ntp.conf# um herauszufinden, welche NTP-Server abgefragt werden sollen. Die Auswahl mehrerer NTP-Server wird empfohlen, falls einer der Server nicht erreichbar ist oder sich seine Uhr als unzuverlässig erweist. Wenn ntpd Antworten erhält, bevorzugt es zuverlässige Server gegenüber weniger zuverlässigen. Die abgefragten Server können lokal im Netzwerk, von einem ISP bereitgestellt oder aus einer http://support.ntp.org/bin/view/Servers/WebHome[Liste öffentlich zugänglicher NTP-Server] ausgewählt werden. Wenn Sie einen öffentlichen NTP-Server auswählen, wählen Sie einen geografisch nahen NTP-Server und überprüfen Sie dessen Nutzungsrichtlinien. Das Schlüsselwort `pool` wählt einen oder mehrere Server aus einem Pool von Servern aus. Eine http://support.ntp.org/bin/view/Servers/NTPPoolServers[ Liste mit öffentlich zugänglichen NTP-Pools] ist ebenfalls verfügbar, sortiert nach geografischen Gebieten. Darüber hinaus bietet FreeBSD einen vom Projekt gespendeten Pool, `0.freebsd.pool.ntp.org`. .Beispiel für [.filename]#/etc/ntp.conf# [example] ==== Dies ist ein einfaches Beispiel für eine [.filename]#ntp.conf#-Datei. Die Einträge können so übernommen werden, wie sie sind. Die Datei enthält die notwendigen Einschränkungen für den Betrieb an einer öffentlich zugänglichen Netzwerkverbindung. [.programlisting] .... # Disallow ntpq control/query access. Allow peers to be added only # based on pool and server statements in this file. restrict default limited kod nomodify notrap noquery nopeer restrict source limited kod nomodify notrap noquery # Allow unrestricted access from localhost for queries and control. restrict 127.0.0.1 restrict ::1 # Add a specific server. server ntplocal.example.com iburst # Add FreeBSD pool servers until 3-6 good servers are available. tos minclock 3 maxclock 6 pool 0.freebsd.pool.ntp.org iburst # Use a local leap-seconds file. leapfile "/var/db/ntpd.leap-seconds.list" .... ==== Das Format dieser Datei ist in man:ntp.conf[5] beschrieben. Die folgenden Erläuterungen geben einen Überblick über die Schlüsselwörter, die in dem obigen Beispiel benutzt werden. In der Voreinstellung ist ein NTP-Server für jeden Host im Netzwerk zugänglich. Das Schlüsselwort `restrict` steuert, welche Systeme auf den Server zugreifen dürfen. Es werden mehrere `restrict`-Einträge unterstützt, die jeweils die vorherigen Anweisungen verfeinern. Die im Beispiel gezeigten Werte gewährem dem lokalen System vollen Abfrage- und Kontrollzugriff, während entfernte Systemen nur die Möglichkeit gegeben wird, die Zeit abzufragen. Weitere Details finden Sie im Abschnitt `Access Control Support` von man:ntp.conf[5]. Das Schlüsselwort `server` gibt einen einzelnen Server zur Abfrage der Zeit an. Die Datei kann das Schlüsselwort `server` mehrmals enthalten, wobei pro Zeile jeweils ein Server aufgeführt ist. Das Schlüsselwort `pool` gibt einen Pool von Servern an. Ntpd fügt bei Bedarf einen oder mehrere Server aus diesem Pool hinzu, um die Anzahl der mit dem Wert `tos minclock` Peers zu erreichen. Das Schlüsselwort `iburst` weist ntpd an, einen Burst von acht schnellen Paketen mit dem Server auszutauschen, wenn der Kontakt zum ersten Mal hergestellt wird, um so die Systemzeit schneller zu synchronisieren. Das Schlüsselwort `leapfile` gibt den Pfad einer Datei an, die Informationen über Schaltsekunden enthält. Die Datei wird automatisch durch man:periodic[8] aktualisiert. Der angegebene Pfad muss mit dem in der Variable `ntp_db_leapfile` aus [.filename]#/etc/rc.conf# übereinstimmen. ==== NTP-Einträge in [.filename]#/etc/rc.conf# Um ntpd beim Booten zu starten, Sie in [.filename]#/etc/rc.conf# den Eintrag `ntpd_enable="YES"` hinzu. Danach kann ntpd direkt gestartet werden: [source,shell] .... # service ntpd start .... Lediglich `ntpd_enable` wird benötigt um ntpd benutzen zu können. Die unten aufgeführten [.filename]#rc.conf#-Variablen können bei Bedarf ebenfalls verwendet werden. Ist `ntpd_sync_on_start="YES"` konfiguriert, setzt ntpd die Uhrzeit beim Systemstart, unabhängig davon wie hoch die Abweichung ist. Normalerweise protokolliert ntpd eine Fehlermeldung und beendet sich selbst, wenn die Uhr um mehr als 1000 Sekunden abweicht. Diese Option ist besonders auf Systemem ohne batteriegepufferte Echtzeituhr nützlich. Setzen Sie `ntpd_oomprotect="YES"`, um ntpd-Daemon davor zu schützen, vom System beendet zu werden, das versucht, sich von einer Out of Memory (OOM) Situation zu retten. Mit `ntpd_config=` setzen Sie den Pfad auf eine alternative [.filename]#ntp.conf#-Datei. In `ntpd_flags=` können bei Bedarf weitere Werte enthalten sein. Vermeiden Sie jedoch die Werte, die intern von [.filename]#/etc/rc.d/ntpd# verwaltet werden: * `-p` (Pfad zur PID-Datei) * `-c` (Setzen Sie stattdessen `ntpd_config=`) ==== Ntpd und der nicht privilegierte `ntpd`-Benutzer In FreeBSD kann Ntpd als nicht privilegierter Benutzer gestartet und ausgeführt werden. Dies erfordert das Modul man:mac_ntpd[4]. Das Startskript [.filename]#/etc/rc.d/ntpd# untersucht zunächst die NTP Konfiguration. Wenn möglich, lädt es das `mac_ntpd`-Modul und startet dann ntpd als nicht privilegierten Benutzer `ntpd` (Benutzer-ID 123). Um Probleme mit dem Datei- und Verzeichniszugriff zu vermeiden, wird das Startskript ntpd nicht automatisch als Benutzer `ntpd` starten, falls die Konfiguration irgendwelche Datei-bezogenen Optionen enthält. Falls einer der folgenden Werte in `ntpd_flags` vorhanden ist, muss eine manuelle Konfiguration vorgenommen werden, damit der Daemon vom `ntpd`-Benutzer ausgeführt werden kann: * -f oder --driftfile * -i oder --jaildir * -k oder --keyfile * -l oder --logfile * -s oder --statsdir Wenn einer der folgenden Schlüsselwörter in [.filename]#ntp.conf# vorhanden ist, muss eine manuelle Konfiguration vorgenommen werden, damit der Daemon vom `ntpd`-Benutzer ausgeführt werden kann: * crypto * driftfile * key * logdir * statsdir Um ntpd so zu konfigurieren, dass der Daemon als Benutzer `ntpd` läuft, müssen folgende Voraussetzungen erfüllt sein: * Stellen Sie sicher, dass der `ntpd`-Benutzer Zugriff auf alle in der Konfiguration angegebenen Dateien und Verzeichnisse hat. * Stellen Sie sicher, dass das Modul `mac_ntpd` in den Kernel geladen oder kompiliert wird. man:mac_ntpd[4] enthält weitere Details. * Setzen Sie `ntpd_user="ntpd"` in [.filename]#/etc/rc.conf#. === NTP mit einer PPP-Verbindung verwenden ntpd benötigt keine ständige Internetverbindung. Wenn Sie sich über eine PPP-Verbindung ins Internet einwählen, sollten Sie verhindern, dass NTP-Verkehr eine Verbindung aufbauen oder aufrechterhalten kann. Dies kann in den `filter`-Direktiven von [.filename]#/etc/ppp/ppp.conf# festgelegt werden. Ein Beispiel: [.programlisting] .... set filter dial 0 deny udp src eq 123 # Prevent NTP traffic from initiating dial out set filter dial 1 permit 0 0 set filter alive 0 deny udp src eq 123 # Prevent incoming NTP traffic from keeping the connection open set filter alive 1 deny udp dst eq 123 # Prevent outgoing NTP traffic from keeping the connection open set filter alive 2 permit 0/0 0/0 .... Weitere Informationen finden Sie im Abschnitt `PACKET FILTERING` von man:ppp[8] sowie in den Beispielen unter [.filename]#/usr/shared/examples/ppp/#. [NOTE] ==== Einige Internetprovider blockieren Ports mit niedrigen Nummern. In solchen Fällen funktioniert NTP leider nicht, da Antworten eines NTP-Servers den Rechner nicht erreichen werden. ==== [[network-iscsi]] == iSCSI Initiator und Target Konfiguration iSCSI bietet die Möglichkeit, Speicherkapazitäten über ein Netzwerk zu teilen. Im Gegensatz zu NFS, das auf Dateisystemebene arbeitet, funktioniert iSCSI auf Blockgerätebene. In der iSCSI-Terminologie wird das System, das den Speicherplatz zur Verfügung stellt, als _Target_ bezeichnet. Der Speicherplatz selbst kann aus einer physischen Festplatte bestehen, oder auch aus einem Bereich, der mehrere Festplatten, oder nur Teile einer Festplatte, repräsentiert. Wenn beispielsweise die Festplatte(n) mit ZFS formatiert ist, kann ein zvol erstellt werden, welches dann als iSCSI-Speicher verwendet werden kann. Die Clients, die auf den iSCSI-Speicher zugreifen, werden _Initiator_ genannt. Ihnen steht der verfügbare Speicher als rohe, nicht formatierte Festplatte, die auch als LUN bezeichnet wird, zur Verfügung. Die Gerätedateien für die Festplatten erscheinen in [.filename]#/dev/# und müssen separat formatiert und eingehangen werden. FreeBSD enthält einen nativen, kernelbasierten iSCSI _Target_ und _Initiator_. Dieser Abschnitt beschreibt, wie ein FreeBSD-System als Target oder Initiator konfiguriert wird. [[network-iscsi-target]] === Ein iSCSI-Target konfigurieren Um ein iSCSI-Target zu konfigurieren, erstellen Sie die Konfigurationsdatei [.filename]#/etc/ctl.conf# und fügen Sie eine Zeile in [.filename]#/etc/rc.conf# hinzu, um sicherzustellen, dass man:ctld[8] automatisch beim Booten gestartet wird. Starten Sie dann den Daemon. Das folgende Beispiel zeigt eine einfache [.filename]#/etc/ctl.conf#. Eine vollständige Beschreibung dieser Datei und der verfügbaren Optionen finden Sie in man:ctl.conf[5]. [.programlisting] .... portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group no-authentication portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... Der erste Eintrag definiert die Portalgruppe `pg0`. Portalgruppen legen fest, auf welchen Netzwerk-Adressen der man:ctld[8]-Daemon Verbindungen entgegennehmen wird. Der Eintrag `discovery-auth-group no-authentication` zeigt an, dass jeder Initiator iSCSI-Targets suchen darf, ohne sich authentifizieren zu müssen. Die dritte und vierte Zeilen konfigurieren man:ctld[8] so, dass er auf allen IPv4- (`listen 0.0.0.0`) und IPv6-Adressen (`listen [::]`) auf dem Standard-Port 3260 lauscht. Es ist nicht zwingend notwendig eine Portalgruppe zu definieren, da es bereits eine integrierte Portalgruppe namens `default` gibt. In diesem Fall ist der Unterschied zwischen `default` und `pg0` der, dass bei `default` eine Authentifizierung nötig ist, während bei `pg0` die Suche nach Targets immer erlaubt ist. Der zweite Eintrag definiert ein einzelnes Target. Ein Target hat zwei mögliche Bedeutungen: eine Maschine die iSCSI bereitstellt, oder eine Gruppe von LUNs. Dieses Beispiel verwendet die letztere Bedeutung, wobei `iqn.2012-06.com.example:target0` der Name des Targets ist. Dieser Name ist nur für Testzwecke geeignet. Für den tatsächlichen Gebrauch ändern Sie `com.example` auf einen echten, rückwärts geschriebenen Domainnamen. `2012-06` steht für das Jahr und den Monat, an dem die Domain erworben wurde. `target0` darf einen beliebigen Wert haben und in der Konfigurationsdatei darf eine beliebige Anzahl von Targets definiert werden. Der Eintrag `auth-group no-authentication` erlaubt es allen Initiatoren sich mit dem angegebenen Target zu verbinden und `portal-group pg0` macht das Target über die Portalgruppe `pg0` erreichbar. Die nächste Sektion definiert die LUN. Jede LUN wird dem Initiator als separate Platte präsentiert. Für jedes Target können mehrere LUNs definiert werden. Jede LUN wird über eine Nummer identifiziert, wobei LUN 0 verpflichtend ist. Die Zeile mit dem Pfad `path /data/target0-0` definiert den absoluten Pfad zu der Datei oder des zvols für die LUN. Der Pfad muss vorhanden sein, bevor man:ctld[8] gestartet wird. Die zweite Zeile ist optional und gibt die Größe der LUN an. Als nächstes fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# ein, um man:ctld[8] automatisch beim Booten zu starten: [.programlisting] .... ctld_enable="YES" .... Um man:ctld[8] jetzt zu starten, geben Sie dieses Kommando ein: [source,shell] .... # service ctld start .... Der man:ctld[8]-Daemon liest beim Start [.filename]#/etc/ctl.conf#. Wenn diese Datei nach dem Starten des Daemons bearbeitet wird, verwenden Sie folgenden Befehl, damit die Änderungen sofort wirksam werden: [source,shell] .... # service ctld reload .... ==== Authentifizierung Die vorherigen Beispiele sind grundsätzlich unsicher, da keine Authentifizierung verwendet wird und jedermann vollen Zugriff auf alle Targets hat. Um für den Zugriff auf die Targets einen Benutzernamen und ein Passwort vorauszusetzen, ändern Sie die Konfigurationsdatei wie folgt: [.programlisting] .... auth-group ag0 { chap username1 secretsecret chap username2 anothersecret } portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group ag0 portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... Die Sektion `auth-group` definiert die Benutzernamen und Passwörter. Um sich mit `iqn.2012-06.com.example:target0` zu verbinden, muss ein Initiator zuerst einen Benutzernamen und ein Passwort angeben. Eine Suche nach Targets wird jedoch immer noch ohne Authentifizierung gestattet. Um eine Authentifizierung zu erfordern, setzen Sie `discovery-auth-group` auf eine definierte `auth-group` anstelle von `no-autentication`. In der Regel wird für jeden Initiator ein einzelnes Target exportiert. In diesem Beispiel wird der Benutzername und das Passwort direkt im Target-Eintrag festgelegt: [.programlisting] .... target iqn.2012-06.com.example:target0 { portal-group pg0 chap username1 secretsecret lun 0 { path /data/target0-0 size 4G } } .... [[network-iscsi-initiator]] === Einen iSCSI-Initiator konfigurieren [NOTE] ==== Der in dieser Sektion beschriebene iSCSI-Initiator wird seit FreeBSD 10.0-RELEASE unterstützt. Lesen Sie man:iscontrol[8], wenn Sie den iSCSI-Initiator mit älteren Versionen benutzen möchten. ==== Um den Initiator zu verwenden, muss zunächst ein iSCSI-Daemon gestartet sein. Der Daemon des Initiators benötigt keine Konfigurationsdatei. Um den Daemon automatisch beim Booten zu starten, fügen Sie folgende Zeile in [.filename]#/etc/rc.conf# ein: [.programlisting] .... iscsid_enable="YES" .... Um man:iscsid[8] jetzt zu starten, geben Sie dieses Kommando ein: [source,shell] .... # service iscsid start .... Die Verbindung mit einem Target kann mit, oder ohne eine Konfigurationsdatei [.filename]#/etc/iscsi.conf# durchgeführt werden. Dieser Abschnitt beschreibt beide Möglichkeiten. ==== Verbindung zu einem Target herstellen - ohne Konfigurationsdatei Um einen Initiator mit einem Target zu verbinden, geben Sie die IP-Adresse des Portals und den Namen des Ziels an: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 .... Um zu überprüfen, ob die Verbindung gelungen ist, rufen Sie `iscsictl` ohne Argumente auf. Die Ausgabe sollte in etwa wie folgt aussehen: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Connected: da0 .... In diesem Beispiel wurde die iSCSI-Sitzung mit der LUN [.filename]#/dev/da0# erfolgreich hergestellt. Wenn das Target `iqn.2012-06.com.example:target0` mehr als nur eine LUN exportiert, werden mehrere Gerätedateien in der Ausgabe angezeigt: [source,shell] .... Connected: da0 da1 da2. .... Alle Fehler werden auf die Ausgabe und in die Systemprotokolle geschrieben. Diese Meldung deutet beispielsweise darauf hin, dass der man:iscsid[8]-Daemon nicht ausgeführt wird: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Waiting for iscsid(8) .... Die folgende Meldung deutet auf ein Netzwerkproblem hin, zum Beispiel eine falsche IP-Adresse oder einen falschen Port: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.11 Connection refused .... Diese Meldung bedeutet, dass der Name des Targets falsch angegeben wurde: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Not found .... Diese Meldung bedeutet, dass das Target eine Authentifizierung erfordert: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Authentication failed .... Verwenden Sie diese Syntax, um einen CHAP-Benutzernamen und ein Passwort anzugeben: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 -u user -s secretsecret .... ==== Verbindung mit einem Target herstellen - mit Konfigurationsdatei Wenn Sie für die Verbindung eine Konfigurationsdatei verwenden möchten, erstellen Sie [.filename]#/etc/iscsi.conf# mit etwa folgendem Inhalt: [.programlisting] .... t0 { TargetAddress = 10.10.10.10 TargetName = iqn.2012-06.com.example:target0 AuthMethod = CHAP chapIName = user chapSecret = secretsecret } .... `t0` gibt den Namen der Sektion in der Konfigurationsdatei an. Diser Name wird vom Initiator benutzt, um zu bestimmen, welche Konfiguration verwendet werden soll. Die anderen Einträge legen die Parameter fest, die während der Verbindung verwendet werden. `TargetAddress` und `TargetName` müssen angegeben werden, die restlichen sind optional. In diesen Beispiel wird der CHAP-Benuztername und das Passwort angegeben. Um sich mit einem bestimmten Target zu verbinden, geben Sie dessen Namen an: [source,shell] .... # iscsictl -An t0 .... Um sich stattdessen mit allen definierten Targets aus der Konfigurationsdatei zu verbinden, verwenden Sie: [source,shell] .... # iscsictl -Aa .... Damit sich der Initiator automatisch mit allen Targets aus [.filename]#/etc/iscsi.conf# verbindet, fügen Sie folgendes in [.filename]#/etc/rc.conf# hinzu: [.programlisting] .... iscsictl_enable="YES" iscsictl_flags="-Aa" .... diff --git a/documentation/content/pl/books/handbook/advanced-networking/_index.adoc b/documentation/content/pl/books/handbook/advanced-networking/_index.adoc index f2e5384d9d..2dc6e02552 100644 --- a/documentation/content/pl/books/handbook/advanced-networking/_index.adoc +++ b/documentation/content/pl/books/handbook/advanced-networking/_index.adoc @@ -1,2821 +1,2821 @@ --- title: Rozdział 32. Advanced Networking part: Część IV. Komunikacja sieciowa prev: books/handbook/firewalls next: books/handbook/partv showBookMenu: true weight: 37 path: "/books/handbook/" --- [[advanced-networking]] = Advanced Networking :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 32 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/advanced-networking/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[advanced-networking-synopsis]] == Synopsis This chapter covers a number of advanced networking topics. After reading this chapter, you will know: * The basics of gateways and routes. * How to set up USB tethering. * How to set up IEEE(R) 802.11 and Bluetooth(R) devices. * How to make FreeBSD act as a bridge. * How to set up network PXE booting. * How to set up IPv6 on a FreeBSD machine. * How to enable and utilize the features of the Common Address Redundancy Protocol (CARP) in FreeBSD. * How to configure multiple VLANs on FreeBSD. * Configure bluetooth headset. Before reading this chapter, you should: * Understand the basics of the [.filename]#/etc/rc# scripts. * Be familiar with basic network terminology. * Know how to configure and install a new FreeBSD kernel (crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]). * Know how to install additional third-party software (crossref:ports[ports,Installing Applications: Packages and Ports]). [[network-routing]] == Gateways and Routes _Routing_ is the mechanism that allows a system to find the network path to another system. A _route_ is a defined pair of addresses which represent the "destination" and a "gateway". The route indicates that when trying to get to the specified destination, send the packets through the specified gateway. There are three types of destinations: individual hosts, subnets, and "default". The "default route" is used if no other routes apply. There are also three types of gateways: individual hosts, interfaces, also called links, and Ethernet hardware (MAC) addresses. Known routes are stored in a routing table. This section provides an overview of routing basics. It then demonstrates how to configure a FreeBSD system as a router and offers some troubleshooting tips. [[network-routing-default]] === Routing Basics To view the routing table of a FreeBSD system, use man:netstat[1]: [source,shell] .... % netstat -r Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default outside-gw UGS 37 418 em0 localhost localhost UH 0 181 lo0 test0 0:e0:b5:36:cf:4f UHLW 5 63288 re0 77 10.20.30.255 link#1 UHLW 1 2421 example.com link#1 UC 0 0 host1 0:e0:a8:37:8:1e UHLW 3 4601 lo0 host2 0:e0:a8:37:8:1e UHLW 0 5 lo0 => host2.example.com link#1 UC 0 0 224 link#1 UC 0 0 .... The entries in this example are as follows: default:: The first route in this table specifies the `default` route. When the local system needs to make a connection to a remote host, it checks the routing table to determine if a known path exists. If the remote host matches an entry in the table, the system checks to see if it can connect using the interface specified in that entry. + If the destination does not match an entry, or if all known paths fail, the system uses the entry for the default route. For hosts on a local area network, the `Gateway` field in the default route is set to the system which has a direct connection to the Internet. When reading this entry, verify that the `Flags` column indicates that the gateway is usable (`UG`). + The default route for a machine which itself is functioning as the gateway to the outside world will be the gateway machine at the Internet Service Provider (ISP). localhost:: The second route is the `localhost` route. The interface specified in the `Netif` column for `localhost` is [.filename]#lo0#, also known as the loopback device. This indicates that all traffic for this destination should be internal, rather than sending it out over the network. MAC address:: The addresses beginning with `0:e0:` are MAC addresses. FreeBSD will automatically identify any hosts, `test0` in the example, on the local Ethernet and add a route for that host over the Ethernet interface, [.filename]#re0#. This type of route has a timeout, seen in the `Expire` column, which is used if the host does not respond in a specific amount of time. When this happens, the route to this host will be automatically deleted. These hosts are identified using the Routing Information Protocol (RIP), which calculates routes to local hosts based upon a shortest path determination. subnet:: FreeBSD will automatically add subnet routes for the local subnet. In this example, `10.20.30.255` is the broadcast address for the subnet `10.20.30` and `example.com` is the domain name associated with that subnet. The designation `link#1` refers to the first Ethernet card in the machine. + Local network hosts and local subnets have their routes automatically configured by a daemon called man:routed[8]. If it is not running, only routes which are statically defined by the administrator will exist. host:: The `host1` line refers to the host by its Ethernet address. Since it is the sending host, FreeBSD knows to use the loopback interface ([.filename]#lo0#) rather than the Ethernet interface. + The two `host2` lines represent aliases which were created using man:ifconfig[8]. The `=>` symbol after the [.filename]#lo0# interface says that an alias has been set in addition to the loopback address. Such routes only show up on the host that supports the alias and all other hosts on the local network will have a `link#1` line for such routes. 224:: The final line (destination subnet `224`) deals with multicasting. Various attributes of each route can be seen in the `Flags` column. <> summarizes some of these flags and their meanings: [[routeflags]] .Commonly Seen Routing Table Flags [cols="1,1", frame="none", options="header"] |=== | Command | Purpose |U |The route is active (up). |H |The route destination is a single host. |G |Send anything for this destination on to this gateway, which will figure out from there where to send it. |S |This route was statically configured. |C |Clones a new route based upon this route for machines to connect to. This type of route is normally used for local networks. |W |The route was auto-configured based upon a local area network (clone) route. |L |Route involves references to Ethernet (link) hardware. |=== On a FreeBSD system, the default route can defined in [.filename]#/etc/rc.conf# by specifying the IP address of the default gateway: [.programlisting] .... defaultrouter="10.20.30.1" .... It is also possible to manually add the route using `route`: [source,shell] .... # route add default 10.20.30.1 .... Note that manually added routes will not survive a reboot. For more information on manual manipulation of network routing tables, refer to man:route[8]. [[network-static-routes]] === Configuring a Router with Static Routes A FreeBSD system can be configured as the default gateway, or router, for a network if it is a dual-homed system. A dual-homed system is a host which resides on at least two different networks. Typically, each network is connected to a separate network interface, though IP aliasing can be used to bind multiple addresses, each on a different subnet, to one physical interface. In order for the system to forward packets between interfaces, FreeBSD must be configured as a router. Internet standards and good engineering practice prevent the FreeBSD Project from enabling this feature by default, but it can be configured to start at boot by adding this line to [.filename]#/etc/rc.conf#: [.programlisting] .... gateway_enable="YES" # Set to YES if this host will be a gateway .... To enable routing now, set the man:sysctl[8] variable `net.inet.ip.forwarding` to `1`. To stop routing, reset this variable to `0`. The routing table of a router needs additional routes so it knows how to reach other networks. Routes can be either added manually using static routes or routes can be automatically learned using a routing protocol. Static routes are appropriate for small networks and this section describes how to add a static routing entry for a small network. [NOTE] ==== For large networks, static routes quickly become unscalable. FreeBSD comes with the standard BSD routing daemon man:routed[8], which provides the routing protocols RIP, versions 1 and 2, and IRDP. Support for the BGP and OSPF routing protocols can be installed using the package:net/zebra[] package or port. ==== Consider the following network: image::static-routes.png[] In this scenario, `RouterA` is a FreeBSD machine that is acting as a router to the rest of the Internet. It has a default route set to `10.0.0.1` which allows it to connect with the outside world. `RouterB` is already configured to use `192.168.1.1` as its default gateway. Before adding any static routes, the routing table on `RouterA` looks like this: [source,shell] .... % netstat -nr Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default 10.0.0.1 UGS 0 49378 xl0 127.0.0.1 127.0.0.1 UH 0 6 lo0 10.0.0.0/24 link#1 UC 0 0 xl0 192.168.1.0/24 link#2 UC 0 0 xl1 .... With the current routing table, `RouterA` does not have a route to the `192.168.2.0/24` network. The following command adds the `Internal Net 2` network to ``RouterA``'s routing table using `192.168.1.2` as the next hop: [source,shell] .... # route add -net 192.168.2.0/24 192.168.1.2 .... Now, `RouterA` can reach any host on the `192.168.2.0/24` network. However, the routing information will not persist if the FreeBSD system reboots. If a static route needs to be persistent, add it to [.filename]#/etc/rc.conf#: [.programlisting] .... # Add Internal Net 2 as a persistent static route static_routes="internalnet2" route_internalnet2="-net 192.168.2.0/24 192.168.1.2" .... The `static_routes` configuration variable is a list of strings separated by a space, where each string references a route name. The variable `route_internalnet2` contains the static route for that route name. Using more than one string in `static_routes` creates multiple static routes. The following shows an example of adding static routes for the `192.168.0.0/24` and `192.168.1.0/24` networks: [.programlisting] .... static_routes="net1 net2" route_net1="-net 192.168.0.0/24 192.168.0.1" route_net2="-net 192.168.1.0/24 192.168.1.1" .... [[network-routing-troubleshooting]] === Troubleshooting When an address space is assigned to a network, the service provider configures their routing tables so that all traffic for the network will be sent to the link for the site. But how do external sites know to send their packets to the network's ISP? There is a system that keeps track of all assigned address spaces and defines their point of connection to the Internet backbone, or the main trunk lines that carry Internet traffic across the country and around the world. Each backbone machine has a copy of a master set of tables, which direct traffic for a particular network to a specific backbone carrier, and from there down the chain of service providers until it reaches a particular network. It is the task of the service provider to advertise to the backbone sites that they are the point of connection, and thus the path inward, for a site. This is known as route propagation. Sometimes, there is a problem with route propagation and some sites are unable to connect. Perhaps the most useful command for trying to figure out where routing is breaking down is `traceroute`. It is useful when `ping` fails. When using `traceroute`, include the address of the remote host to connect to. The output will show the gateway hosts along the path of the attempt, eventually either reaching the target host, or terminating because of a lack of connection. For more information, refer to man:traceroute[8]. [[network-routing-multicast]] === Multicast Considerations FreeBSD natively supports both multicast applications and multicast routing. Multicast applications do not require any special configuration in order to run on FreeBSD. Support for multicast routing requires that the following option be compiled into a custom kernel: [.programlisting] .... options MROUTING .... The multicast routing daemon, mrouted can be installed using the package:net/mrouted[] package or port. This daemon implements the DVMRP multicast routing protocol and is configured by editing [.filename]#/usr/local/etc/mrouted.conf# in order to set up the tunnels and DVMRP. The installation of mrouted also installs map-mbone and mrinfo, as well as their associated man pages. Refer to these for configuration examples. [NOTE] ==== DVMRP has largely been replaced by the PIM protocol in many multicast installations. Refer to man:pim[4] for more information. ==== [[network-wireless]] == Wireless Networking === Wireless Networking Basics Most wireless networks are based on the IEEE(R) 802.11 standards. A basic wireless network consists of multiple stations communicating with radios that broadcast in either the 2.4GHz or 5GHz band, though this varies according to the locale and is also changing to enable communication in the 2.3GHz and 4.9GHz ranges. 802.11 networks are organized in two ways. In _infrastructure mode_, one station acts as a master with all the other stations associating to it, the network is known as a BSS, and the master station is termed an access point (AP). In a BSS, all communication passes through the AP; even when one station wants to communicate with another wireless station, messages must go through the AP. In the second form of network, there is no master and stations communicate directly. This form of network is termed an IBSS and is commonly known as an _ad-hoc network_. 802.11 networks were first deployed in the 2.4GHz band using protocols defined by the IEEE(R) 802.11 and 802.11b standard. These specifications include the operating frequencies and the MAC layer characteristics, including framing and transmission rates, as communication can occur at various rates. Later, the 802.11a standard defined operation in the 5GHz band, including different signaling mechanisms and higher transmission rates. Still later, the 802.11g standard defined the use of 802.11a signaling and transmission mechanisms in the 2.4GHz band in such a way as to be backwards compatible with 802.11b networks. Separate from the underlying transmission techniques, 802.11 networks have a variety of security mechanisms. The original 802.11 specifications defined a simple security protocol called WEP. This protocol uses a fixed pre-shared key and the RC4 cryptographic cipher to encode data transmitted on a network. Stations must all agree on the fixed key in order to communicate. This scheme was shown to be easily broken and is now rarely used except to discourage transient users from joining networks. Current security practice is given by the IEEE(R) 802.11i specification that defines new cryptographic ciphers and an additional protocol to authenticate stations to an access point and exchange keys for data communication. Cryptographic keys are periodically refreshed and there are mechanisms for detecting and countering intrusion attempts. Another security protocol specification commonly used in wireless networks is termed WPA, which was a precursor to 802.11i. WPA specifies a subset of the requirements found in 802.11i and is designed for implementation on legacy hardware. Specifically, WPA requires only the TKIP cipher that is derived from the original WEP cipher. 802.11i permits use of TKIP but also requires support for a stronger cipher, AES-CCM, for encrypting data. The AES cipher was not required in WPA because it was deemed too computationally costly to be implemented on legacy hardware. The other standard to be aware of is 802.11e. It defines protocols for deploying multimedia applications, such as streaming video and voice over IP (VoIP), in an 802.11 network. Like 802.11i, 802.11e also has a precursor specification termed WME (later renamed WMM) that has been defined by an industry group as a subset of 802.11e that can be deployed now to enable multimedia applications while waiting for the final ratification of 802.11e. The most important thing to know about 802.11e and WME/WMM is that it enables prioritized traffic over a wireless network through Quality of Service (QoS) protocols and enhanced media access protocols. Proper implementation of these protocols enables high speed bursting of data and prioritized traffic flow. FreeBSD supports networks that operate using 802.11a, 802.11b, and 802.11g. The WPA and 802.11i security protocols are likewise supported (in conjunction with any of 11a, 11b, and 11g) and QoS and traffic prioritization required by the WME/WMM protocols are supported for a limited set of wireless devices. [[network-wireless-quick-start]] === Quick Start Connecting a computer to an existing wireless network is a very common situation. This procedure shows the steps required. [.procedure] . Obtain the SSID (Service Set Identifier) and PSK (Pre-Shared Key) for the wireless network from the network administrator. . Identify the wireless adapter. The FreeBSD [.filename]#GENERIC# kernel includes drivers for many common wireless adapters. If the wireless adapter is one of those models, it will be shown in the output from man:ifconfig[8]: + [source,shell] .... % ifconfig | grep -B3 -i wireless .... + On FreeBSD 11 or higher, use this command instead: + [source,shell] .... % sysctl net.wlan.devices .... + If a wireless adapter is not listed, an additional kernel module might be required, or it might be a model not supported by FreeBSD. + This example shows the Atheros `ath0` wireless adapter. . Add an entry for this network to [.filename]#/etc/wpa_supplicant.conf#. If the file does not exist, create it. Replace _myssid_ and _mypsk_ with the SSID and PSK provided by the network administrator. + [.programlisting] .... network={ ssid="myssid" psk="mypsk" } .... . Add entries to [.filename]#/etc/rc.conf# to configure the network on startup: + [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA SYNCDHCP" .... . Restart the computer, or restart the network service to connect to the network: + [source,shell] .... # service netif restart .... [[network-wireless-basic]] === Basic Setup ==== Kernel Configuration To use wireless networking, a wireless networking card is needed and the kernel needs to be configured with the appropriate wireless networking support. The kernel is separated into multiple modules so that only the required support needs to be configured. The most commonly used wireless devices are those that use parts made by Atheros. These devices are supported by man:ath[4] and require the following line to be added to [.filename]#/boot/loader.conf#: [.programlisting] .... if_ath_load="YES" .... The Atheros driver is split up into three separate pieces: the driver (man:ath[4]), the hardware support layer that handles chip-specific functions (man:ath_hal[4]), and an algorithm for selecting the rate for transmitting frames. When this support is loaded as kernel modules, any dependencies are automatically handled. To load support for a different type of wireless device, specify the module for that device. This example is for devices based on the Intersil Prism parts (man:wi[4]) driver: [.programlisting] .... if_wi_load="YES" .... [NOTE] ==== The examples in this section use an man:ath[4] device and the device name in the examples must be changed according to the configuration. A list of available wireless drivers and supported adapters can be found in the FreeBSD Hardware Notes, available on the https://www.FreeBSD.org/releases/[Release Information] page of the FreeBSD website. If a native FreeBSD driver for the wireless device does not exist, it may be possible to use the Windows(R) driver with the help of the crossref:config[config-network-ndis,NDIS] driver wrapper. ==== In addition, the modules that implement cryptographic support for the security protocols to use must be loaded. These are intended to be dynamically loaded on demand by the man:wlan[4] module, but for now they must be manually configured. The following modules are available: man:wlan_wep[4], man:wlan_ccmp[4], and man:wlan_tkip[4]. The man:wlan_ccmp[4] and man:wlan_tkip[4] drivers are only needed when using the WPA or 802.11i security protocols. If the network does not use encryption, man:wlan_wep[4] support is not needed. To load these modules at boot time, add the following lines to [.filename]#/boot/loader.conf#: [.programlisting] .... wlan_wep_load="YES" wlan_ccmp_load="YES" wlan_tkip_load="YES" .... Once this information has been added to [.filename]#/boot/loader.conf#, reboot the FreeBSD box. Alternately, load the modules by hand using man:kldload[8]. [NOTE] ==== For users who do not want to use modules, it is possible to compile these drivers into the kernel by adding the following lines to a custom kernel configuration file: [.programlisting] .... device wlan # 802.11 support device wlan_wep # 802.11 WEP support device wlan_ccmp # 802.11 CCMP support device wlan_tkip # 802.11 TKIP support device wlan_amrr # AMRR transmit rate control algorithm device ath # Atheros pci/cardbus NIC's device ath_hal # pci/cardbus chip support options AH_SUPPORT_AR5416 # enable AR5416 tx/rx descriptors device ath_rate_sample # SampleRate tx rate control for ath .... With this information in the kernel configuration file, recompile the kernel and reboot the FreeBSD machine. ==== Information about the wireless device should appear in the boot messages, like this: [source,shell] .... ath0: mem 0x88000000-0x8800ffff irq 11 at device 0.0 on cardbus1 ath0: [ITHREAD] ath0: AR2413 mac 7.9 RF2413 phy 4.5 .... ==== Setting the Correct Region Since the regulatory situation is different in various parts of the world, it is necessary to correctly set the domains that apply to your location to have the correct information about what channels can be used. The available region definitions can be found in [.filename]#/etc/regdomain.xml#. To set the data at runtime, use `ifconfig`: [source,shell] .... # ifconfig wlan0 regdomain ETSI country AT .... To persist the settings, add it to [.filename]#/etc/rc.conf#: [source,shell] .... # sysrc create_args_wlan0="country AT regdomain ETSI" .... === Infrastructure Mode Infrastructure (BSS) mode is the mode that is typically used. In this mode, a number of wireless access points are connected to a wired network. Each wireless network has its own name, called the SSID. Wireless clients connect to the wireless access points. ==== FreeBSD Clients ===== How to Find Access Points To scan for available networks, use man:ifconfig[8]. This request may take a few moments to complete as it requires the system to switch to each available wireless frequency and probe for available access points. Only the superuser can initiate a scan: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS dlinkap 00:13:46:49:41:76 11 54M -90:96 100 EPS WPA WME freebsdap 00:11:95:c3:0d:ac 1 54M -83:96 100 EPS WPA .... [NOTE] ==== The interface must be `up` before it can scan. Subsequent scan requests do not require the interface to be marked as up again. ==== The output of a scan request lists each BSS/IBSS network found. Besides listing the name of the network, the `SSID`, the output also shows the `BSSID`, which is the MAC address of the access point. The `CAPS` field identifies the type of each network and the capabilities of the stations operating there: .Station Capability Codes [cols="1,1", frame="none", options="header"] |=== | Capability Code | Meaning |`E` |Extended Service Set (ESS). Indicates that the station is part of an infrastructure network rather than an IBSS/ad-hoc network. |`I` |IBSS/ad-hoc network. Indicates that the station is part of an ad-hoc network rather than an ESS network. |`P` |Privacy. Encryption is required for all data frames exchanged within the BSS using cryptographic means such as WEP, TKIP or AES-CCMP. |`S` |Short Preamble. Indicates that the network is using short preambles, defined in 802.11b High Rate/DSSS PHY, and utilizes a 56 bit sync field rather than the 128 bit field used in long preamble mode. |`s` |Short slot time. Indicates that the 802.11g network is using a short slot time because there are no legacy (802.11b) stations present. |=== One can also display the current list of known networks with: [source,shell] .... # ifconfig wlan0 list scan .... This information may be updated automatically by the adapter or manually with a `scan` request. Old data is automatically removed from the cache, so over time this list may shrink unless more scans are done. ===== Basic Settings This section provides a simple example of how to make the wireless network adapter work in FreeBSD without encryption. Once familiar with these concepts, it is strongly recommend to use <> to set up the wireless network. There are three basic steps to configure a wireless network: select an access point, authenticate the station, and configure an IP address. The following sections discuss each step. ====== Selecting an Access Point Most of the time, it is sufficient to let the system choose an access point using the builtin heuristics. This is the default behavior when an interface is marked as up or it is listed in [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... If there are multiple access points, a specific one can be selected by its SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here DHCP" .... In an environment where there are multiple access points with the same SSID, which is often done to simplify roaming, it may be necessary to associate to one specific device. In this case, the BSSID of the access point can be specified, with or without the SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here bssid xx:xx:xx:xx:xx:xx DHCP" .... There are other ways to constrain the choice of an access point, such as limiting the set of frequencies the system will scan on. This may be useful for a multi-band wireless card as scanning all the possible channels can be time-consuming. To limit operation to a specific band, use the `mode` parameter: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="mode 11g ssid your_ssid_here DHCP" .... This example will force the card to operate in 802.11g, which is defined only for 2.4GHz frequencies so any 5GHz channels will not be considered. This can also be achieved with the `channel` parameter, which locks operation to one specific frequency, and the `chanlist` parameter, to specify a list of channels for scanning. More information about these parameters can be found in man:ifconfig[8]. ====== Authentication Once an access point is selected, the station needs to authenticate before it can pass data. Authentication can happen in several ways. The most common scheme, open authentication, allows any station to join the network and communicate. This is the authentication to use for test purposes the first time a wireless network is setup. Other schemes require cryptographic handshakes to be completed before data traffic can flow, either using pre-shared keys or secrets, or more complex schemes that involve backend services such as RADIUS. Open authentication is the default setting. The next most common setup is WPA-PSK, also known as WPA Personal, which is described in <>. [NOTE] ==== If using an Apple(R) AirPort(R) Extreme base station for an access point, shared-key authentication together with a WEP key needs to be configured. This can be configured in [.filename]#/etc/rc.conf# or by using man:wpa_supplicant[8]. For a single AirPort(R) base station, access can be configured with: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="authmode shared wepmode on weptxkey 1 wepkey 01234567 DHCP" .... In general, shared key authentication should be avoided because it uses the WEP key material in a highly-constrained manner, making it even easier to crack the key. If WEP must be used for compatibility with legacy devices, it is better to use WEP with `open` authentication. More information regarding WEP can be found in <>. ==== ====== Getting an IP Address with DHCP Once an access point is selected and the authentication parameters are set, an IP address must be obtained in order to communicate. Most of the time, the IP address is obtained via DHCP. To achieve that, edit [.filename]#/etc/rc.conf# and add `DHCP` to the configuration for the device: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... The wireless interface is now ready to bring up: [source,shell] .... # service netif start .... Once the interface is running, use man:ifconfig[8] to see the status of the interface [.filename]#ath0#: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.1.100 netmask 0xffffff00 broadcast 192.168.1.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid dlinkap channel 11 (2462 Mhz 11g) bssid 00:13:46:49:41:76 country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... The `status: associated` line means that it is connected to the wireless network. The `bssid 00:13:46:49:41:76` is the MAC address of the access point and `authmode OPEN` indicates that the communication is not encrypted. ====== Static IP Address If an IP address cannot be obtained from a DHCP server, set a fixed IP address. Replace the `DHCP` keyword shown above with the address information. Be sure to retain any other parameters for selecting the access point: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="inet 192.168.1.100 netmask 255.255.255.0 ssid your_ssid_here" .... [[network-wireless-wpa]] ===== WPA Wi-Fi Protected Access (WPA) is a security protocol used together with 802.11 networks to address the lack of proper authentication and the weakness of WEP. WPA leverages the 802.1X authentication protocol and uses one of several ciphers instead of WEP for data integrity. The only cipher required by WPA is the Temporary Key Integrity Protocol (TKIP). TKIP is a cipher that extends the basic RC4 cipher used by WEP by adding integrity checking, tamper detection, and measures for responding to detected intrusions. TKIP is designed to work on legacy hardware with only software modification. It represents a compromise that improves security but is still not entirely immune to attack. WPA also specifies the AES-CCMP cipher as an alternative to TKIP, and that is preferred when possible. For this specification, the term WPA2 or RSN is commonly used. WPA defines authentication and encryption protocols. Authentication is most commonly done using one of two techniques: by 802.1X and a backend authentication service such as RADIUS, or by a minimal handshake between the station and the access point using a pre-shared secret. The former is commonly termed WPA Enterprise and the latter is known as WPA Personal. Since most people will not set up a RADIUS backend server for their wireless network, WPA-PSK is by far the most commonly encountered configuration for WPA. The control of the wireless connection and the key negotiation or authentication with a server is done using man:wpa_supplicant[8]. This program requires a configuration file, [.filename]#/etc/wpa_supplicant.conf#, to run. More information regarding this file can be found in man:wpa_supplicant.conf[5]. [[network-wireless-wpa-wpa-psk]] ====== WPA-PSK WPA-PSK, also known as WPA Personal, is based on a pre-shared key (PSK) which is generated from a given password and used as the master key in the wireless network. This means every wireless user will share the same key. WPA-PSK is intended for small networks where the use of an authentication server is not possible or desired. [WARNING] ==== Always use strong passwords that are sufficiently long and made from a rich alphabet so that they will not be easily guessed or attacked. ==== The first step is the configuration of [.filename]#/etc/wpa_supplicant.conf# with the SSID and the pre-shared key of the network: [.programlisting] .... network={ ssid="freebsdap" psk="freebsdmall" } .... Then, in [.filename]#/etc/rc.conf#, indicate that the wireless device configuration will be done with WPA and the IP address will be obtained with DHCP: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Then, bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 5 DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6 DHCPOFFER from 192.168.0.1 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Or, try to configure the interface manually using the information in [.filename]#/etc/wpa_supplicant.conf#: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:11:95:c3:0d:ac (SSID='freebsdap' freq=2412 MHz) Associated with 00:11:95:c3:0d:ac WPA: Key negotiation completed with 00:11:95:c3:0d:ac [PTK=CCMP GTK=CCMP] CTRL-EVENT-CONNECTED - Connection to 00:11:95:c3:0d:ac completed (auth) [id=0 id_str=] .... The next operation is to launch man:dhclient[8] to get the IP address from the DHCP server: [source,shell] .... # dhclient wlan0 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [NOTE] ==== If [.filename]#/etc/rc.conf# has an `ifconfig_wlan0="DHCP"` entry, man:dhclient[8] will be launched automatically after man:wpa_supplicant[8] associates with the access point. ==== If DHCP is not possible or desired, set a static IP address after man:wpa_supplicant[8] has authenticated the station: [source,shell] .... # ifconfig wlan0 inet 192.168.0.100 netmask 255.255.255.0 # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... When DHCP is not used, the default gateway and the nameserver also have to be manually set: [source,shell] .... # route add default your_default_router # echo "nameserver your_DNS_server" >> /etc/resolv.conf .... [[network-wireless-wpa-eap-tls]] ====== WPA with EAP-TLS The second way to use WPA is with an 802.1X backend authentication server. In this case, WPA is called WPA Enterprise to differentiate it from the less secure WPA Personal. Authentication in WPA Enterprise is based on the Extensible Authentication Protocol (EAP). EAP does not come with an encryption method. Instead, EAP is embedded inside an encrypted tunnel. There are many EAP authentication methods, but EAP-TLS, EAP-TTLS, and EAP-PEAP are the most common. EAP with Transport Layer Security (EAP-TLS) is a well-supported wireless authentication protocol since it was the first EAP method to be certified by the http://www.wi-fi.org/[Wi-Fi Alliance]. EAP-TLS requires three certificates to run: the certificate of the Certificate Authority (CA) installed on all machines, the server certificate for the authentication server, and one client certificate for each wireless client. In this EAP method, both the authentication server and wireless client authenticate each other by presenting their respective certificates, and then verify that these certificates were signed by the organization's CA. As previously, the configuration is done via [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" <.> proto=RSN <.> key_mgmt=WPA-EAP <.> eap=TLS <.> identity="loader" <.> ca_cert="/etc/certs/cacert.pem" <.> client_cert="/etc/certs/clientcert.pem" <.> private_key="/etc/certs/clientkey.pem" <.> private_key_passwd="freebsdmallclient" <.> } .... <.> This field indicates the network name (SSID). <.> This example uses the RSN IEEE(R) 802.11i protocol, also known as WPA2. <.> The `key_mgmt` line refers to the key management protocol to use. In this example, it is WPA using EAP authentication. <.> This field indicates the EAP method for the connection. <.> The `identity` field contains the identity string for EAP. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> The `client_cert` line gives the pathname to the client certificate file. This certificate is unique to each wireless client of the network. <.> The `private_key` field is the pathname to the client certificate private key file. <.> The `private_key_passwd` field contains the passphrase for the private key. Then, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... The next step is to bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... It is also possible to bring up the interface manually using man:wpa_supplicant[8] and man:ifconfig[8]. [[network-wireless-wpa-eap-ttls]] ====== WPA with EAP-TTLS With EAP-TLS, both the authentication server and the client need a certificate. With EAP-TTLS, a client certificate is optional. This method is similar to a web server which creates a secure SSL tunnel even if visitors do not have client-side certificates. EAP-TTLS uses an encrypted TLS tunnel for safe transport of the authentication data. The required configuration can be added to [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=TTLS <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase2="auth=MD5" <.> } .... <.> This field specifies the EAP method for the connection. <.> The `identity` field contains the identity string for EAP authentication inside the encrypted TLS tunnel. <.> The `password` field contains the passphrase for the EAP authentication. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> This field specifies the authentication method used in the encrypted TLS tunnel. In this example, EAP with MD5-Challenge is used. The "inner authentication" phase is often called "phase2". Next, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... The next step is to bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wpa-eap-peap]] ====== WPA with EAP-PEAP [NOTE] ==== PEAPv0/EAP-MSCHAPv2 is the most common PEAP method. In this chapter, the term PEAP is used to refer to that method. ==== Protected EAP (PEAP) is designed as an alternative to EAP-TTLS and is the most used EAP standard after EAP-TLS. In a network with mixed operating systems, PEAP should be the most supported standard after EAP-TLS. PEAP is similar to EAP-TTLS as it uses a server-side certificate to authenticate clients by creating an encrypted TLS tunnel between the client and the authentication server, which protects the ensuing exchange of authentication information. PEAP authentication differs from EAP-TTLS as it broadcasts the username in the clear and only the password is sent in the encrypted TLS tunnel. EAP-TTLS will use the TLS tunnel for both the username and password. Add the following lines to [.filename]#/etc/wpa_supplicant.conf# to configure the EAP-PEAP related settings: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=PEAP <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase1="peaplabel=0" <.> phase2="auth=MSCHAPV2" <.> } .... <.> This field specifies the EAP method for the connection. <.> The `identity` field contains the identity string for EAP authentication inside the encrypted TLS tunnel. <.> The `password` field contains the passphrase for the EAP authentication. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> This field contains the parameters for the first phase of authentication, the TLS tunnel. According to the authentication server used, specify a specific label for authentication. Most of the time, the label will be "client EAP encryption" which is set by using `peaplabel=0`. More information can be found in man:wpa_supplicant.conf[5]. <.> This field specifies the authentication protocol used in the encrypted TLS tunnel. In the case of PEAP, it is `auth=MSCHAPV2`. Add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Then, bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wep]] ===== WEP Wired Equivalent Privacy (WEP) is part of the original 802.11 standard. There is no authentication mechanism, only a weak form of access control which is easily cracked. WEP can be set up using man:ifconfig[8]: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 inet 192.168.1.100 netmask 255.255.255.0 \ ssid my_net wepmode on weptxkey 3 wepkey 3:0x3456789012 .... * The `weptxkey` specifies which WEP key will be used in the transmission. This example uses the third key. This must match the setting on the access point. When unsure which key is used by the access point, try `1` (the first key) for this value. * The `wepkey` selects one of the WEP keys. It should be in the format _index:key_. Key `1` is used by default; the index only needs to be set when using a key other than the first key. + [NOTE] ==== Replace the `0x3456789012` with the key configured for use on the access point. ==== Refer to man:ifconfig[8] for further information. The man:wpa_supplicant[8] facility can be used to configure a wireless interface with WEP. The example above can be set up by adding the following lines to [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="my_net" key_mgmt=NONE wep_key3=3456789012 wep_tx_keyidx=3 } .... Then: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:13:46:49:41:76 (SSID='dlinkap' freq=2437 MHz) Associated with 00:13:46:49:41:76 .... === Ad-hoc Mode IBSS mode, also called ad-hoc mode, is designed for point to point connections. For example, to establish an ad-hoc network between the machines `A` and `B`, choose two IP addresses and a SSID. On `A`: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... The `adhoc` parameter indicates that the interface is running in IBSS mode. `B` should now be able to detect `A`: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 02:11:95:c3:0d:ac 2 54M -64:-96 100 IS WME .... The `I` in the output confirms that `A` is in ad-hoc mode. Now, configure `B` with a different IP address: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... Both `A` and `B` are now ready to exchange information. [[network-wireless-ap]] === FreeBSD Host Access Points FreeBSD can act as an Access Point (AP) which eliminates the need to buy a hardware AP or run an ad-hoc network. This can be particularly useful when a FreeBSD machine is acting as a gateway to another network such as the Internet. [[network-wireless-ap-basic]] ==== Basic Settings Before configuring a FreeBSD machine as an AP, the kernel must be configured with the appropriate networking support for the wireless card as well as the security protocols being used. For more details, see <>. [NOTE] ==== The NDIS driver wrapper for Windows(R) drivers does not currently support AP operation. Only native FreeBSD wireless drivers support AP mode. ==== Once wireless networking support is loaded, check if the wireless device supports the host-based access point mode, also known as hostap mode: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 list caps drivercaps=6f85edc1 cryptocaps=1f .... This output displays the card's capabilities. The `HOSTAP` word confirms that this wireless card can act as an AP. Various supported ciphers are also listed: WEP, TKIP, and AES. This information indicates which security protocols can be used on the AP. The wireless device can only be put into hostap mode during the creation of the network pseudo-device, so a previously created device must be destroyed first: [source,shell] .... # ifconfig wlan0 destroy .... then regenerated with the correct option before setting the other parameters: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1 .... Use man:ifconfig[8] again to see the status of the [.filename]#wlan0# interface: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... The `hostap` parameter indicates the interface is running in the host-based access point mode. The interface configuration can be done automatically at boot time by adding the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" create_args_wlan0="wlanmode hostap" ifconfig_wlan0="inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1" .... ==== Host-based Access Point Without Authentication or Encryption Although it is not recommended to run an AP without any authentication or encryption, this is a simple way to check if the AP is working. This configuration is also important for debugging client issues. Once the AP is configured, initiate a scan from another wireless machine to find the AP: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M -66:-96 100 ES WME .... The client machine found the AP and can be associated with it: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... [[network-wireless-ap-wpa]] ==== WPA2 Host-based Access Point This section focuses on setting up a FreeBSD access point using the WPA2 security protocol. More details regarding WPA and the configuration of WPA-based wireless clients can be found in <>. The man:hostapd[8] daemon is used to deal with client authentication and key management on the WPA2-enabled AP. The following configuration operations are performed on the FreeBSD machine acting as the AP. Once the AP is correctly working, man:hostapd[8] can be automatically started at boot with this line in [.filename]#/etc/rc.conf#: [.programlisting] .... hostapd_enable="YES" .... Before trying to configure man:hostapd[8], first configure the basic settings introduced in <>. ===== WPA2-PSK WPA2-PSK is intended for small networks where the use of a backend authentication server is not possible or desired. The configuration is done in [.filename]#/etc/hostapd.conf#: [.programlisting] .... interface=wlan0 <.> debug=1 <.> ctrl_interface=/var/run/hostapd <.> ctrl_interface_group=wheel <.> ssid=freebsdap <.> wpa=2 <.> wpa_passphrase=freebsdmall <.> wpa_key_mgmt=WPA-PSK <.> wpa_pairwise=CCMP <.> .... <.> Wireless interface used for the access point. <.> Level of verbosity used during the execution of man:hostapd[8]. A value of `1` represents the minimal level. <.> Pathname of the directory used by man:hostapd[8] to store domain socket files for communication with external programs such as man:hostapd_cli[8]. The default value is used in this example. <.> The group allowed to access the control interface files. <.> The wireless network name, or SSID, that will appear in wireless scans. <.> Enable WPA and specify which WPA authentication protocol will be required. A value of `2` configures the AP for WPA2 and is recommended. Set to `1` only if the obsolete WPA is required. <.> ASCII passphrase for WPA authentication. <.> The key management protocol to use. This example sets WPA-PSK. <.> Encryption algorithms accepted by the access point. In this example, only the CCMP (AES) cipher is accepted. CCMP is an alternative to TKIP and is strongly preferred when possible. TKIP should be allowed only when there are stations incapable of using CCMP. The next step is to start man:hostapd[8]: [source,shell] .... # service hostapd forcestart .... [source,shell] .... # ifconfig wlan0 wlan0: flags=8943 metric 0 mtu 1500 ether 04:f0:21:16:8e:10 inet6 fe80::6f0:21ff:fe16:8e10%wlan0 prefixlen 64 scopeid 0x9 nd6 options=21 media: IEEE 802.11 Wireless Ethernet autoselect mode 11na status: running ssid No5ignal channel 36 (5180 MHz 11a ht/40+) bssid 04:f0:21:16:8e:10 country US ecm authmode WPA2/802.11i privacy MIXED deftxkey 2 AES-CCM 2:128-bit AES-CCM 3:128-bit txpower 17 mcastrate 6 mgmtrate 6 scanvalid 60 ampdulimit 64k ampdudensity 8 shortgi wme burst dtimperiod 1 -dfs groups: wlan .... Once the AP is running, the clients can associate with it. See <> for more details. It is possible to see the stations associated with the AP using `ifconfig _wlan0_ list sta`. ==== WEP Host-based Access Point It is not recommended to use WEP for setting up an AP since there is no authentication mechanism and the encryption is easily cracked. Some legacy wireless cards only support WEP and these cards will only support an AP without authentication or encryption. The wireless device can now be put into hostap mode and configured with the correct SSID and IP address: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 \ ssid freebsdap wepmode on weptxkey 3 wepkey 3:0x3456789012 mode 11g .... * The `weptxkey` indicates which WEP key will be used in the transmission. This example uses the third key as key numbering starts with `1`. This parameter must be specified in order to encrypt the data. * The `wepkey` sets the selected WEP key. It should be in the format _index:key_. If the index is not given, key `1` is set. The index needs to be set when using keys other than the first key. Use man:ifconfig[8] to see the status of the [.filename]#wlan0# interface: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 4 (2427 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy ON deftxkey 3 wepkey 3:40-bit txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... From another wireless machine, it is now possible to initiate a scan to find the AP: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M 22:1 100 EPS .... In this example, the client machine found the AP and can associate with it using the correct parameters. See <> for more details. === Using Both Wired and Wireless Connections A wired connection provides better performance and reliability, while a wireless connection provides flexibility and mobility. Laptop users typically want to roam seamlessly between the two types of connections. On FreeBSD, it is possible to combine two or even more network interfaces together in a "failover" fashion. This type of configuration uses the most preferred and available connection from a group of network interfaces, and the operating system switches automatically when the link state changes. Link aggregation and failover is covered in <> and an example for using both wired and wireless connections is provided at <>. === Troubleshooting This section describes a number of steps to help troubleshoot common wireless networking problems. * If the access point is not listed when scanning, check that the configuration has not limited the wireless device to a limited set of channels. * If the device cannot associate with an access point, verify that the configuration matches the settings on the access point. This includes the authentication scheme and any security protocols. Simplify the configuration as much as possible. If using a security protocol such as WPA or WEP, configure the access point for open authentication and no security to see if traffic will pass. + Debugging support is provided by man:wpa_supplicant[8]. Try running this utility manually with `-dd` and look at the system logs. * Once the system can associate with the access point, diagnose the network configuration using tools like man:ping[8]. * There are many lower-level debugging tools. Debugging messages can be enabled in the 802.11 protocol support layer using man:wlandebug[8]. For example, to enable console messages related to scanning for access points and the 802.11 protocol handshakes required to arrange communication: + [source,shell] .... # wlandebug -i wlan0 +scan+auth+debug+assoc net.wlan.0.debug: 0 => 0xc80000 .... + Many useful statistics are maintained by the 802.11 layer and `wlanstats`, found in [.filename]#/usr/src/tools/tools/net80211#, will dump this information. These statistics should display all errors identified by the 802.11 layer. However, some errors are identified in the device drivers that lie below the 802.11 layer so they may not show up. To diagnose device-specific problems, refer to the drivers' documentation. If the above information does not help to clarify the problem, submit a problem report and include output from the above tools. [[network-usb-tethering]] == USB Tethering Many cellphones provide the option to share their data connection over USB (often called "tethering"). This feature uses one of RNDIS, CDC, or a custom Apple(R) iPhone(R)/iPad(R) protocol. * Android(TM) devices generally use the man:urndis[4] driver. * Apple(R) devices use the man:ipheth[4] driver. * Older devices will often use the man:cdce[4] driver. Before attaching a device, load the appropriate driver into the kernel: [source,shell] .... # kldload if_urndis # kldload if_cdce # kldload if_ipheth .... Once the device is attached ``ue``_0_ will be available for use like a normal network device. Be sure that the "USB tethering" option is enabled on the device. To make this change permanent and load the driver as a module at boot time, place the appropriate line of the following in [.filename]#/boot/loader.conf#: [source,shell] .... if_urndis_load="YES" if_cdce_load="YES" if_ipheth_load="YES" .... [[network-bluetooth]] == Bluetooth Bluetooth is a wireless technology for creating personal networks operating in the 2.4 GHz unlicensed band, with a range of 10 meters. Networks are usually formed ad-hoc from portable devices such as cellular phones, handhelds, and laptops. Unlike Wi-Fi wireless technology, Bluetooth offers higher level service profiles, such as FTP-like file servers, file pushing, voice transport, serial line emulation, and more. This section describes the use of a USB Bluetooth dongle on a FreeBSD system. It then describes the various Bluetooth protocols and utilities. === Loading Bluetooth Support The Bluetooth stack in FreeBSD is implemented using the man:netgraph[4] framework. A broad variety of Bluetooth USB dongles is supported by man:ng_ubt[4]. Broadcom BCM2033 based Bluetooth devices are supported by the man:ubtbcmfw[4] and man:ng_ubt[4] drivers. The 3Com Bluetooth PC Card 3CRWB60-A is supported by the man:ng_bt3c[4] driver. Serial and UART based Bluetooth devices are supported by man:sio[4], man:ng_h4[4], and man:hcseriald[8]. Before attaching a device, determine which of the above drivers it uses, then load the driver. For example, if the device uses the man:ng_ubt[4] driver: [source,shell] .... # kldload ng_ubt .... If the Bluetooth device will be attached to the system during system startup, the system can be configured to load the module at boot time by adding the driver to [.filename]#/boot/loader.conf#: [.programlisting] .... ng_ubt_load="YES" .... Once the driver is loaded, plug in the USB dongle. If the driver load was successful, output similar to the following should appear on the console and in [.filename]#/var/log/messages#: [source,shell] .... ubt0: vendor 0x0a12 product 0x0001, rev 1.10/5.25, addr 2 ubt0: Interface 0 endpoints: interrupt=0x81, bulk-in=0x82, bulk-out=0x2 ubt0: Interface 1 (alt.config 5) endpoints: isoc-in=0x83, isoc-out=0x3, wMaxPacketSize=49, nframes=6, buffer size=294 .... To start and stop the Bluetooth stack, use its startup script. It is a good idea to stop the stack before unplugging the device. Starting the bluetooth stack might require man:hcsecd[8] to be started. When starting the stack, the output should be similar to the following: [source,shell] .... # service bluetooth start ubt0 BD_ADDR: 00:02:72:00:d4:1a Features: 0xff 0xff 0xf 00 00 00 00 00 <3-Slot> <5-Slot> Max. ACL packet size: 192 bytes Number of ACL packets: 8 Max. SCO packet size: 64 bytes Number of SCO packets: 8 .... === Finding Other Bluetooth Devices The Host Controller Interface (HCI) provides a uniform method for accessing Bluetooth baseband capabilities. In FreeBSD, a netgraph HCI node is created for each Bluetooth device. For more details, refer to man:ng_hci[4]. One of the most common tasks is discovery of Bluetooth devices within RF proximity. This operation is called _inquiry_. Inquiry and other HCI related operations are done using man:hccontrol[8]. The example below shows how to find out which Bluetooth devices are in range. The list of devices should be displayed in a few seconds. Note that a remote device will only answer the inquiry if it is set to _discoverable_ mode. [source,shell] .... % hccontrol -n ubt0hci inquiry Inquiry result, num_responses=1 Inquiry result #0 BD_ADDR: 00:80:37:29:19:a4 Page Scan Rep. Mode: 0x1 Page Scan Period Mode: 00 Page Scan Mode: 00 Class: 52:02:04 Clock offset: 0x78ef Inquiry complete. Status: No error [00] .... The `BD_ADDR` is the unique address of a Bluetooth device, similar to the MAC address of a network card. This address is needed for further communication with a device and it is possible to assign a human readable name to a `BD_ADDR`. Information regarding the known Bluetooth hosts is contained in [.filename]#/etc/bluetooth/hosts#. The following example shows how to obtain the human readable name that was assigned to the remote device: [source,shell] .... % hccontrol -n ubt0hci remote_name_request 00:80:37:29:19:a4 BD_ADDR: 00:80:37:29:19:a4 Name: Pav's T39 .... If an inquiry is performed on a remote Bluetooth device, it will find the computer as "your.host.name (ubt0)". The name assigned to the local device can be changed at any time. Remote devices can be assigned aliases in [.filename]#/etc/bluetooth/hosts#. More information about [.filename]#/etc/bluetooth/hosts# file might be found in man:bluetooth.hosts[5]. The Bluetooth system provides a point-to-point connection between two Bluetooth units, or a point-to-multipoint connection which is shared among several Bluetooth devices. The following example shows how to create a connection to a remote device: [source,shell] .... % hccontrol -n ubt0hci create_connection BT_ADDR .... `create_connection` accepts `BT_ADDR` as well as host aliases in [.filename]#/etc/bluetooth/hosts#. The following example shows how to obtain the list of active baseband connections for the local device: [source,shell] .... % hccontrol -n ubt0hci read_connection_list Remote BD_ADDR Handle Type Mode Role Encrypt Pending Queue State 00:80:37:29:19:a4 41 ACL 0 MAST NONE 0 0 OPEN .... A _connection handle_ is useful when termination of the baseband connection is required, though it is normally not required to do this by hand. The stack will automatically terminate inactive baseband connections. [source,shell] .... # hccontrol -n ubt0hci disconnect 41 Connection handle: 41 Reason: Connection terminated by local host [0x16] .... Type `hccontrol help` for a complete listing of available HCI commands. Most of the HCI commands do not require superuser privileges. === Device Pairing By default, Bluetooth communication is not authenticated, and any device can talk to any other device. A Bluetooth device, such as a cellular phone, may choose to require authentication to provide a particular service. Bluetooth authentication is normally done with a _PIN code_, an ASCII string up to 16 characters in length. The user is required to enter the same PIN code on both devices. Once the user has entered the PIN code, both devices will generate a _link key_. After that, the link key can be stored either in the devices or in a persistent storage. Next time, both devices will use the previously generated link key. This procedure is called _pairing_. Note that if the link key is lost by either device, the pairing must be repeated. The man:hcsecd[8] daemon is responsible for handling Bluetooth authentication requests. The default configuration file is [.filename]#/etc/bluetooth/hcsecd.conf#. An example section for a cellular phone with the PIN code set to `1234` is shown below: [.programlisting] .... device { bdaddr 00:80:37:29:19:a4; name "Pav's T39"; key nokey; pin "1234"; } .... The only limitation on PIN codes is length. Some devices, such as Bluetooth headsets, may have a fixed PIN code built in. The `-d` switch forces man:hcsecd[8] to stay in the foreground, so it is easy to see what is happening. Set the remote device to receive pairing and initiate the Bluetooth connection to the remote device. The remote device should indicate that pairing was accepted and request the PIN code. Enter the same PIN code listed in [.filename]#hcsecd.conf#. Now the computer and the remote device are paired. Alternatively, pairing can be initiated on the remote device. The following line can be added to [.filename]#/etc/rc.conf# to configure man:hcsecd[8] to start automatically on system start: [.programlisting] .... hcsecd_enable="YES" .... The following is a sample of the man:hcsecd[8] daemon output: [.programlisting] .... hcsecd[16484]: Got Link_Key_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', link key doesn't exist hcsecd[16484]: Sending Link_Key_Negative_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Got PIN_Code_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', PIN code exists hcsecd[16484]: Sending PIN_Code_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 .... === Network Access with PPP Profiles A Dial-Up Networking (DUN) profile can be used to configure a cellular phone as a wireless modem for connecting to a dial-up Internet access server. It can also be used to configure a computer to receive data calls from a cellular phone. Network access with a PPP profile can be used to provide LAN access for a single Bluetooth device or multiple Bluetooth devices. It can also provide PC to PC connection using PPP networking over serial cable emulation. In FreeBSD, these profiles are implemented with man:ppp[8] and the man:rfcomm_pppd[8] wrapper which converts a Bluetooth connection into something PPP can use. Before a profile can be used, a new PPP label must be created in [.filename]#/etc/ppp/ppp.conf#. Consult man:rfcomm_pppd[8] for examples. In this example, man:rfcomm_pppd[8] is used to open a connection to a remote device with a `BD_ADDR` of `00:80:37:29:19:a4` on a DUNRFCOMM channel: [source,shell] .... # rfcomm_pppd -a 00:80:37:29:19:a4 -c -C dun -l rfcomm-dialup .... The actual channel number will be obtained from the remote device using the SDP protocol. It is possible to specify the RFCOMM channel by hand, and in this case man:rfcomm_pppd[8] will not perform the SDP query. Use man:sdpcontrol[8] to find out the RFCOMM channel on the remote device. In order to provide network access with the PPPLAN service, man:sdpd[8] must be running and a new entry for LAN clients must be created in [.filename]#/etc/ppp/ppp.conf#. Consult man:rfcomm_pppd[8] for examples. Finally, start the RFCOMMPPP server on a valid RFCOMM channel number. The RFCOMMPPP server will automatically register the Bluetooth LAN service with the local SDP daemon. The example below shows how to start the RFCOMMPPP server. [source,shell] .... # rfcomm_pppd -s -C 7 -l rfcomm-server .... === Bluetooth Protocols This section provides an overview of the various Bluetooth protocols, their function, and associated utilities. ==== Logical Link Control and Adaptation Protocol (L2CAP) The Logical Link Control and Adaptation Protocol (L2CAP) provides connection-oriented and connectionless data services to upper layer protocols. L2CAP permits higher level protocols and applications to transmit and receive L2CAP data packets up to 64 kilobytes in length. L2CAP is based around the concept of _channels_. A channel is a logical connection on top of a baseband connection, where each channel is bound to a single protocol in a many-to-one fashion. Multiple channels can be bound to the same protocol, but a channel cannot be bound to multiple protocols. Each L2CAP packet received on a channel is directed to the appropriate higher level protocol. Multiple channels can share the same baseband connection. In FreeBSD, a netgraph L2CAP node is created for each Bluetooth device. This node is normally connected to the downstream Bluetooth HCI node and upstream Bluetooth socket nodes. The default name for the L2CAP node is "devicel2cap". For more details refer to man:ng_l2cap[4]. A useful command is man:l2ping[8], which can be used to ping other devices. Some Bluetooth implementations might not return all of the data sent to them, so `0 bytes` in the following example is normal. [source,shell] .... # l2ping -a 00:80:37:29:19:a4 0 bytes from 0:80:37:29:19:a4 seq_no=0 time=48.633 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=1 time=37.551 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=2 time=28.324 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=3 time=46.150 ms result=0 .... The man:l2control[8] utility is used to perform various operations on L2CAP nodes. This example shows how to obtain the list of logical connections (channels) and the list of baseband connections for the local device: [source,shell] .... % l2control -a 00:02:72:00:d4:1a read_channel_list L2CAP channels: Remote BD_ADDR SCID/ DCID PSM IMTU/ OMTU State 00:07:e0:00:0b:ca 66/ 64 3 132/ 672 OPEN % l2control -a 00:02:72:00:d4:1a read_connection_list L2CAP connections: Remote BD_ADDR Handle Flags Pending State 00:07:e0:00:0b:ca 41 O 0 OPEN .... Another diagnostic tool is man:btsockstat[1]. It is similar to man:netstat[1], but for Bluetooth network-related data structures. The example below shows the same logical connection as man:l2control[8] above. [source,shell] .... % btsockstat Active L2CAP sockets PCB Recv-Q Send-Q Local address/PSM Foreign address CID State c2afe900 0 0 00:02:72:00:d4:1a/3 00:07:e0:00:0b:ca 66 OPEN Active RFCOMM sessions L2PCB PCB Flag MTU Out-Q DLCs State c2afe900 c2b53380 1 127 0 Yes OPEN Active RFCOMM sockets PCB Recv-Q Send-Q Local address Foreign address Chan DLCI State c2e8bc80 0 250 00:02:72:00:d4:1a 00:07:e0:00:0b:ca 3 6 OPEN .... ==== Radio Frequency Communication (RFCOMM) The RFCOMM protocol provides emulation of serial ports over the L2CAP protocol. RFCOMM is a simple transport protocol, with additional provisions for emulating the 9 circuits of RS-232 (EIATIA-232-E) serial ports. It supports up to 60 simultaneous connections (RFCOMM channels) between two Bluetooth devices. For the purposes of RFCOMM, a complete communication path involves two applications running on the communication endpoints with a communication segment between them. RFCOMM is intended to cover applications that make use of the serial ports of the devices in which they reside. The communication segment is a direct connect Bluetooth link from one device to another. RFCOMM is only concerned with the connection between the devices in the direct connect case, or between the device and a modem in the network case. RFCOMM can support other configurations, such as modules that communicate via Bluetooth wireless technology on one side and provide a wired interface on the other side. In FreeBSD, RFCOMM is implemented at the Bluetooth sockets layer. ==== Service Discovery Protocol (SDP) The Service Discovery Protocol (SDP) provides the means for client applications to discover the existence of services provided by server applications as well as the attributes of those services. The attributes of a service include the type or class of service offered and the mechanism or protocol information needed to utilize the service. SDP involves communication between a SDP server and a SDP client. The server maintains a list of service records that describe the characteristics of services associated with the server. Each service record contains information about a single service. A client may retrieve information from a service record maintained by the SDP server by issuing a SDP request. If the client, or an application associated with the client, decides to use a service, it must open a separate connection to the service provider in order to utilize the service. SDP provides a mechanism for discovering services and their attributes, but it does not provide a mechanism for utilizing those services. Normally, a SDP client searches for services based on some desired characteristics of the services. However, there are times when it is desirable to discover which types of services are described by an SDP server's service records without any prior information about the services. This process of looking for any offered services is called _browsing_. The Bluetooth SDP server, man:sdpd[8], and command line client, man:sdpcontrol[8], are included in the standard FreeBSD installation. The following example shows how to perform a SDP browse query. [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec browse Record Handle: 00000000 Service Class ID List: Service Discovery Server (0x1000) Protocol Descriptor List: L2CAP (0x0100) Protocol specific parameter #1: u/int/uuid16 1 Protocol specific parameter #2: u/int/uuid16 1 Record Handle: 0x00000001 Service Class ID List: Browse Group Descriptor (0x1001) Record Handle: 0x00000002 Service Class ID List: LAN Access Using PPP (0x1102) Protocol Descriptor List: L2CAP (0x0100) RFCOMM (0x0003) Protocol specific parameter #1: u/int8/bool 1 Bluetooth Profile Descriptor List: LAN Access Using PPP (0x1102) ver. 1.0 .... Note that each service has a list of attributes, such as the RFCOMM channel. Depending on the service, the user might need to make note of some of the attributes. Some Bluetooth implementations do not support service browsing and may return an empty list. In this case, it is possible to search for the specific service. The example below shows how to search for the OBEX Object Push (OPUSH) service: [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec search OPUSH .... Offering services on FreeBSD to Bluetooth clients is done with the man:sdpd[8] server. The following line can be added to [.filename]#/etc/rc.conf#: [.programlisting] .... sdpd_enable="YES" .... Then the man:sdpd[8] daemon can be started with: [source,shell] .... # service sdpd start .... The local server application that wants to provide a Bluetooth service to remote clients will register the service with the local SDP daemon. An example of such an application is man:rfcomm_pppd[8]. Once started, it will register the Bluetooth LAN service with the local SDP daemon. The list of services registered with the local SDP server can be obtained by issuing a SDP browse query via the local control channel: [source,shell] .... # sdpcontrol -l browse .... ==== OBEX Object Push (OPUSH) Object Exchange (OBEX) is a widely used protocol for simple file transfers between mobile devices. Its main use is in infrared communication, where it is used for generic file transfers between notebooks or PDAs, and for sending business cards or calendar entries between cellular phones and other devices with Personal Information Manager (PIM) applications. The OBEX server and client are implemented by obexapp, which can be installed using the package:comms/obexapp[] package or port. The OBEX client is used to push and/or pull objects from the OBEX server. An example object is a business card or an appointment. The OBEX client can obtain the RFCOMM channel number from the remote device via SDP. This can be done by specifying the service name instead of the RFCOMM channel number. Supported service names are: `IrMC`, `FTRN`, and `OPUSH`. It is also possible to specify the RFCOMM channel as a number. Below is an example of an OBEX session where the device information object is pulled from the cellular phone, and a new object, the business card, is pushed into the phone's directory. [source,shell] .... % obexapp -a 00:80:37:29:19:a4 -C IrMC obex> get telecom/devinfo.txt devinfo-t39.txt Success, response: OK, Success (0x20) obex> put new.vcf Success, response: OK, Success (0x20) obex> di Success, response: OK, Success (0x20) .... In order to provide the OPUSH service, man:sdpd[8] must be running and a root folder, where all incoming objects will be stored, must be created. The default path to the root folder is [.filename]#/var/spool/obex#. Finally, start the OBEX server on a valid RFCOMM channel number. The OBEX server will automatically register the OPUSH service with the local SDP daemon. The example below shows how to start the OBEX server. [source,shell] .... # obexapp -s -C 10 .... ==== Serial Port Profile (SPP) The Serial Port Profile (SPP) allows Bluetooth devices to perform serial cable emulation. This profile allows legacy applications to use Bluetooth as a cable replacement, through a virtual serial port abstraction. In FreeBSD, man:rfcomm_sppd[1] implements SPP and a pseudo tty is used as a virtual serial port abstraction. The example below shows how to connect to a remote device's serial port service. A RFCOMM channel does not have to be specified as man:rfcomm_sppd[1] can obtain it from the remote device via SDP. To override this, specify a RFCOMM channel on the command line. [source,shell] .... # rfcomm_sppd -a 00:07:E0:00:0B:CA -t rfcomm_sppd[94692]: Starting on /dev/pts/6... /dev/pts/6 .... Once connected, the pseudo tty can be used as serial port: [source,shell] .... # cu -l /dev/pts/6 .... The pseudo tty is printed on stdout and can be read by wrapper scripts: [.programlisting] .... PTS=`rfcomm_sppd -a 00:07:E0:00:0B:CA -t` cu -l $PTS .... === Troubleshooting By default, when FreeBSD is accepting a new connection, it tries to perform a role switch and become master. Some older Bluetooth devices which do not support role switching will not be able to connect. Since role switching is performed when a new connection is being established, it is not possible to ask the remote device if it supports role switching. However, there is a HCI option to disable role switching on the local side: [source,shell] .... # hccontrol -n ubt0hci write_node_role_switch 0 .... To display Bluetooth packets, use the third-party package hcidump, which can be installed using the package:comms/hcidump[] package or port. This utility is similar to man:tcpdump[1] and can be used to display the contents of Bluetooth packets on the terminal and to dump the Bluetooth packets to a file. [[network-bridging]] == Bridging It is sometimes useful to divide a network, such as an Ethernet segment, into network segments without having to create IP subnets and use a router to connect the segments together. A device that connects two networks together in this fashion is called a "bridge". A bridge works by learning the MAC addresses of the devices on each of its network interfaces. It forwards traffic between networks only when the source and destination MAC addresses are on different networks. In many respects, a bridge is like an Ethernet switch with very few ports. A FreeBSD system with multiple network interfaces can be configured to act as a bridge. Bridging can be useful in the following situations: Connecting Networks:: The basic operation of a bridge is to join two or more network segments. There are many reasons to use a host-based bridge instead of networking equipment, such as cabling constraints or firewalling. A bridge can also connect a wireless interface running in hostap mode to a wired network and act as an access point. Filtering/Traffic Shaping Firewall:: A bridge can be used when firewall functionality is needed without routing or Network Address Translation (NAT). + An example is a small company that is connected via DSL or ISDN to an ISP. There are thirteen public IP addresses from the ISP and ten computers on the network. In this situation, using a router-based firewall is difficult because of subnetting issues. A bridge-based firewall can be configured without any IP addressing issues. Network Tap:: A bridge can join two network segments in order to inspect all Ethernet frames that pass between them using man:bpf[4] and man:tcpdump[1] on the bridge interface or by sending a copy of all frames out an additional interface known as a span port. Layer 2 VPN:: Two Ethernet networks can be joined across an IP link by bridging the networks to an EtherIP tunnel or a man:tap[4] based solution such as OpenVPN. Layer 2 Redundancy:: A network can be connected together with multiple links and use the Spanning Tree Protocol (STP) to block redundant paths. This section describes how to configure a FreeBSD system as a bridge using man:if_bridge[4]. A netgraph bridging driver is also available, and is described in man:ng_bridge[4]. [NOTE] ==== Packet filtering can be used with any firewall package that hooks into the man:pfil[9] framework. The bridge can be used as a traffic shaper with man:altq[4] or man:dummynet[4]. ==== === Enabling the Bridge In FreeBSD, man:if_bridge[4] is a kernel module which is automatically loaded by man:ifconfig[8] when creating a bridge interface. It is also possible to compile bridge support into a custom kernel by adding `device if_bridge` to the custom kernel configuration file. The bridge is created using interface cloning. To create the bridge interface: [source,shell] .... # ifconfig bridge create bridge0 # ifconfig bridge0 bridge0: flags=8802 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:00:00:00:00:00 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:00:00:00:00:00 priority 0 ifcost 0 port 0 .... When a bridge interface is created, it is automatically assigned a randomly generated Ethernet address. The `maxaddr` and `timeout` parameters control how many MAC addresses the bridge will keep in its forwarding table and how many seconds before each entry is removed after it is last seen. The other parameters control how STP operates. Next, specify which network interfaces to add as members of the bridge. For the bridge to forward packets, all member interfaces and the bridge need to be up: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 up # ifconfig fxp0 up # ifconfig fxp1 up .... The bridge can now forward Ethernet frames between [.filename]#fxp0# and [.filename]#fxp1#. Add the following lines to [.filename]#/etc/rc.conf# so the bridge is created at startup: [.programlisting] .... cloned_interfaces="bridge0" ifconfig_bridge0="addm fxp0 addm fxp1 up" ifconfig_fxp0="up" ifconfig_fxp1="up" .... If the bridge host needs an IP address, set it on the bridge interface, not on the member interfaces. The address can be set statically or via DHCP. This example sets a static IP address: [source,shell] .... # ifconfig bridge0 inet 192.168.0.1/24 .... It is also possible to assign an IPv6 address to a bridge interface. To make the changes permanent, add the addressing information to [.filename]#/etc/rc.conf#. [NOTE] ==== When packet filtering is enabled, bridged packets will pass through the filter inbound on the originating interface on the bridge interface, and outbound on the appropriate interfaces. Either stage can be disabled. When direction of the packet flow is important, it is best to firewall on the member interfaces rather than the bridge itself. The bridge has several configurable settings for passing non-IP and IP packets, and layer2 firewalling with man:ipfw[8]. See man:if_bridge[4] for more information. ==== === Enabling Spanning Tree For an Ethernet network to function properly, only one active path can exist between two devices. The STP protocol detects loops and puts redundant links into a blocked state. Should one of the active links fail, STP calculates a different tree and enables one of the blocked paths to restore connectivity to all points in the network. The Rapid Spanning Tree Protocol (RSTP or 802.1w) provides backwards compatibility with legacy STP. RSTP provides faster convergence and exchanges information with neighboring switches to quickly transition to forwarding mode without creating loops. FreeBSD supports RSTP and STP as operating modes, with RSTP being the default mode. STP can be enabled on member interfaces using man:ifconfig[8]. For a bridge with [.filename]#fxp0# and [.filename]#fxp1# as the current interfaces, enable STP with: [source,shell] .... # ifconfig bridge0 stp fxp0 stp fxp1 bridge0: flags=8843 metric 0 mtu 1500 ether d6:cf:d5:a0:94:6d id 00:01:02:4b:d4:50 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 0 port 0 member: fxp0 flags=1c7 port 3 priority 128 path cost 200000 proto rstp role designated state forwarding member: fxp1 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role designated state forwarding .... This bridge has a spanning tree ID of `00:01:02:4b:d4:50` and a priority of `32768`. As the `root id` is the same, it indicates that this is the root bridge for the tree. Another bridge on the network also has STP enabled: [source,shell] .... bridge0: flags=8843 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:13:d4:9a:06:7a priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4 member: fxp0 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role root state forwarding member: fxp1 flags=1c7 port 5 priority 128 path cost 200000 proto rstp role designated state forwarding .... The line `root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4` shows that the root bridge is `00:01:02:4b:d4:50` and has a path cost of `400000` from this bridge. The path to the root bridge is via `port 4` which is [.filename]#fxp0#. === Bridge Interface Parameters Several `ifconfig` parameters are unique to bridge interfaces. This section summarizes some common uses for these parameters. The complete list of available parameters is described in man:ifconfig[8]. private:: A private interface does not forward any traffic to any other port that is also designated as a private interface. The traffic is blocked unconditionally so no Ethernet frames will be forwarded, including ARP packets. If traffic needs to be selectively blocked, a firewall should be used instead. span:: A span port transmits a copy of every Ethernet frame received by the bridge. The number of span ports configured on a bridge is unlimited, but if an interface is designated as a span port, it cannot also be used as a regular bridge port. This is most useful for snooping a bridged network passively on another host connected to one of the span ports of the bridge. For example, to send a copy of all frames out the interface named [.filename]#fxp4#: + [source,shell] .... # ifconfig bridge0 span fxp4 .... sticky:: If a bridge member interface is marked as sticky, dynamically learned address entries are treated as static entries in the forwarding cache. Sticky entries are never aged out of the cache or replaced, even if the address is seen on a different interface. This gives the benefit of static address entries without the need to pre-populate the forwarding table. Clients learned on a particular segment of the bridge cannot roam to another segment. + An example of using sticky addresses is to combine the bridge with VLANs in order to isolate customer networks without wasting IP address space. Consider that `CustomerA` is on `vlan100`, `CustomerB` is on `vlan101`, and the bridge has the address `192.168.0.1`: + [source,shell] .... # ifconfig bridge0 addm vlan100 sticky vlan100 addm vlan101 sticky vlan101 # ifconfig bridge0 inet 192.168.0.1/24 .... + In this example, both clients see `192.168.0.1` as their default gateway. Since the bridge cache is sticky, one host cannot spoof the MAC address of the other customer in order to intercept their traffic. + Any communication between the VLANs can be blocked using a firewall or, as seen in this example, private interfaces: + [source,shell] .... # ifconfig bridge0 private vlan100 private vlan101 .... + The customers are completely isolated from each other and the full `/24` address range can be allocated without subnetting. + The number of unique source MAC addresses behind an interface can be limited. Once the limit is reached, packets with unknown source addresses are dropped until an existing host cache entry expires or is removed. + The following example sets the maximum number of Ethernet devices for `CustomerA` on `vlan100` to 10: + [source,shell] .... # ifconfig bridge0 ifmaxaddr vlan100 10 .... Bridge interfaces also support monitor mode, where the packets are discarded after man:bpf[4] processing and are not processed or forwarded further. This can be used to multiplex the input of two or more interfaces into a single man:bpf[4] stream. This is useful for reconstructing the traffic for network taps that transmit the RX/TX signals out through two separate interfaces. For example, to read the input from four network interfaces as one stream: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 addm fxp2 addm fxp3 monitor up # tcpdump -i bridge0 .... === SNMP Monitoring The bridge interface and STP parameters can be monitored via man:bsnmpd[1] which is included in the FreeBSD base system. The exported bridge MIBs conform to IETF standards so any SNMP client or monitoring package can be used to retrieve the data. To enable monitoring on the bridge, uncomment this line in [.filename]#/etc/snmpd.config# by removing the beginning `#` symbol: [.programlisting] .... begemotSnmpdModulePath."bridge" = "/usr/lib/snmp_bridge.so" .... Other configuration settings, such as community names and access lists, may need to be modified in this file. See man:bsnmpd[1] and man:snmp_bridge[3] for more information. Once these edits are saved, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... bsnmpd_enable="YES" .... Then, start man:bsnmpd[1]: [source,shell] .... # service bsnmpd start .... The following examples use the Net-SNMP software (package:net-mgmt/net-snmp[]) to query a bridge from a client system. The package:net-mgmt/bsnmptools[] port can also be used. From the SNMP client which is running Net-SNMP, add the following lines to [.filename]#$HOME/.snmp/snmp.conf# in order to import the bridge MIB definitions: [.programlisting] .... mibdirs +/usr/shared/snmp/mibs mibs +BRIDGE-MIB:RSTP-MIB:BEGEMOT-MIB:BEGEMOT-BRIDGE-MIB .... To monitor a single bridge using the IETF BRIDGE-MIB (RFC4188): [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com mib-2.dot1dBridge BRIDGE-MIB::dot1dBaseBridgeAddress.0 = STRING: 66:fb:9b:6e:5c:44 BRIDGE-MIB::dot1dBaseNumPorts.0 = INTEGER: 1 ports BRIDGE-MIB::dot1dStpTimeSinceTopologyChange.0 = Timeticks: (189959) 0:31:39.59 centi-seconds BRIDGE-MIB::dot1dStpTopChanges.0 = Counter32: 2 BRIDGE-MIB::dot1dStpDesignatedRoot.0 = Hex-STRING: 80 00 00 01 02 4B D4 50 ... BRIDGE-MIB::dot1dStpPortState.3 = INTEGER: forwarding(5) BRIDGE-MIB::dot1dStpPortEnable.3 = INTEGER: enabled(1) BRIDGE-MIB::dot1dStpPortPathCost.3 = INTEGER: 200000 BRIDGE-MIB::dot1dStpPortDesignatedRoot.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedCost.3 = INTEGER: 0 BRIDGE-MIB::dot1dStpPortDesignatedBridge.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedPort.3 = Hex-STRING: 03 80 BRIDGE-MIB::dot1dStpPortForwardTransitions.3 = Counter32: 1 RSTP-MIB::dot1dStpVersion.0 = INTEGER: rstp(2) .... The `dot1dStpTopChanges.0` value is two, indicating that the STP bridge topology has changed twice. A topology change means that one or more links in the network have changed or failed and a new tree has been calculated. The `dot1dStpTimeSinceTopologyChange.0` value will show when this happened. To monitor multiple bridge interfaces, the private BEGEMOT-BRIDGE-MIB can be used: [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com enterprises.fokus.begemot.begemotBridge BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge0" = STRING: bridge0 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge2" = STRING: bridge2 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge0" = STRING: e:ce:3b:5a:9e:13 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge2" = STRING: 12:5e:4d:74:d:fc BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge0" = INTEGER: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge2" = INTEGER: 1 ... BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge0" = Timeticks: (116927) 0:19:29.27 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge2" = Timeticks: (82773) 0:13:47.73 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge0" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge2" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge0" = Hex-STRING: 80 00 00 40 95 30 5E 31 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge2" = Hex-STRING: 80 00 00 50 8B B8 C6 A9 .... To change the bridge interface being monitored via the `mib-2.dot1dBridge` subtree: [source,shell] .... % snmpset -v 2c -c private bridge1.example.com BEGEMOT-BRIDGE-MIB::begemotBridgeDefaultBridgeIf.0 s bridge2 .... [[network-aggregation]] == Link Aggregation and Failover FreeBSD provides the man:lagg[4] interface which can be used to aggregate multiple network interfaces into one virtual interface in order to provide failover and link aggregation. Failover allows traffic to continue to flow as long as at least one aggregated network interface has an established link. Link aggregation works best on switches which support LACP, as this protocol distributes traffic bi-directionally while responding to the failure of individual links. The aggregation protocols supported by the lagg interface determine which ports are used for outgoing traffic and whether or not a specific port accepts incoming traffic. The following protocols are supported by man:lagg[4]: failover:: This mode sends and receives traffic only through the master port. If the master port becomes unavailable, the next active port is used. The first interface added to the virtual interface is the master port and all subsequently added interfaces are used as failover devices. If failover to a non-master port occurs, the original port becomes master once it becomes available again. fec / loadbalance:: Cisco(R) Fast EtherChannel(R) (FEC) is found on older Cisco(R) switches. It provides a static setup and does not negotiate aggregation with the peer or exchange frames to monitor the link. If the switch supports LACP, that should be used instead. lacp:: The IEEE(R) 802.3ad Link Aggregation Control Protocol (LACP) negotiates a set of aggregable links with the peer into one or more Link Aggregated Groups (LAGs). Each LAG is composed of ports of the same speed, set to full-duplex operation, and traffic is balanced across the ports in the LAG with the greatest total speed. Typically, there is only one LAG which contains all the ports. In the event of changes in physical connectivity, LACP will quickly converge to a new configuration. + LACP balances outgoing traffic across the active ports based on hashed protocol header information and accepts incoming traffic from any active port. The hash includes the Ethernet source and destination address and, if available, the VLAN tag, and the IPv4 or IPv6 source and destination address. roundrobin:: This mode distributes outgoing traffic using a round-robin scheduler through all active ports and accepts incoming traffic from any active port. Since this mode violates Ethernet frame ordering, it should be used with caution. === Configuration Examples This section demonstrates how to configure a Cisco(R) switch and a FreeBSD system for LACP load balancing. It then shows how to configure two Ethernet interfaces in failover mode as well as how to configure failover mode between an Ethernet and a wireless interface. [[networking-lacp-aggregation-cisco]] .LACP Aggregation with a Cisco(R) Switch [example] ==== This example connects two man:fxp[4] Ethernet interfaces on a FreeBSD machine to the first two Ethernet ports on a Cisco(R) switch as a single load balanced and fault tolerant link. More interfaces can be added to increase throughput and fault tolerance. Replace the names of the Cisco(R) ports, Ethernet devices, channel group number, and IP address shown in the example to match the local configuration. Frame ordering is mandatory on Ethernet links and any traffic between two stations always flows over the same physical link, limiting the maximum speed to that of one interface. The transmit algorithm attempts to use as much information as it can to distinguish different traffic flows and balance the flows across the available interfaces. On the Cisco(R) switch, add the _FastEthernet0/1_ and _FastEthernet0/2_ interfaces to channel group _1_: [source,shell] .... interface FastEthernet0/1 channel-group 1 mode active channel-protocol lacp ! interface FastEthernet0/2 channel-group 1 mode active channel-protocol lacp .... On the FreeBSD system, create the man:lagg[4] interface using the physical interfaces _fxp0_ and _fxp1_ and bring the interfaces up with an IP address of _10.0.0.3/24_: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24 .... Next, verify the status of the virtual interface: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.3 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto lacp laggport: fxp1 flags=1c laggport: fxp0 flags=1c .... Ports marked as `ACTIVE` are part of the LAG that has been negotiated with the remote switch. Traffic will be transmitted and received through these active ports. Add `-v` to the above command to view the LAG identifiers. To see the port status on the Cisco(R) switch: [source,shell] .... switch# show lacp neighbor Flags: S - Device is requesting Slow LACPDUs F - Device is requesting Fast LACPDUs A - Device is in Active mode P - Device is in Passive mode Channel group 1 neighbors Partner's information: LACP port Oper Port Port Port Flags Priority Dev ID Age Key Number State Fa0/1 SA 32768 0005.5d71.8db8 29s 0x146 0x3 0x3D Fa0/2 SA 32768 0005.5d71.8db8 29s 0x146 0x4 0x3D .... For more detail, type `show lacp neighbor detail`. To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf# on the FreeBSD system: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24" .... ==== [[networking-lagg-failover]] .Failover Mode [example] ==== Failover mode can be used to switch over to a secondary interface if the link is lost on the master interface. To configure failover, make sure that the underlying physical interfaces are up, then create the man:lagg[4] interface. In this example, _fxp0_ is the master interface, _fxp1_ is the secondary interface, and the virtual interface is assigned an IP address of _10.0.0.15/24_: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24 .... The virtual interface should look something like this: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.15 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto failover laggport: fxp1 flags=0<> laggport: fxp0 flags=5 .... Traffic will be transmitted and received on _fxp0_. If the link is lost on _fxp0_, _fxp1_ will become the active link. If the link is restored on the master interface, it will once again become the active link. To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24" .... ==== [[networking-lagg-wired-and-wireless]] .Failover Mode Between Ethernet and Wireless Interfaces [example] ==== For laptop users, it is usually desirable to configure the wireless device as a secondary which is only used when the Ethernet connection is not available. With man:lagg[4], it is possible to configure a failover which prefers the Ethernet connection for both performance and security reasons, while maintaining the ability to transfer data over the wireless connection. This is achieved by overriding the Ethernet interface's MAC address with that of the wireless interface. [NOTE] **** In theory, either the Ethernet or wireless MAC address can be changed to match the other. However, some popular wireless interfaces lack support for overriding the MAC address. We therefore recommend overriding the Ethernet MAC address for this purpose. **** [NOTE] **** If the driver for the wireless interface is not loaded in the `GENERIC` or custom kernel, and the computer is running FreeBSD {rel121-current}, load the corresponding [.filename]#.ko# in [.filename]#/boot/loader.conf# by adding `*driver_load="YES"*` to that file and rebooting. Another, better way is to load the driver in [.filename]#/etc/rc.conf# by adding it to `kld_list` (see man:rc.conf[5] for details) in that file and rebooting. This is needed because otherwise the driver is not loaded yet at the time the man:lagg[4] interface is set up. **** In this example, the Ethernet interface, _re0_, is the master and the wireless interface, _wlan0_, is the failover. The _wlan0_ interface was created from the _ath0_ physical wireless interface, and the Ethernet interface will be configured with the MAC address of the wireless interface. First, determine the MAC address of the wireless interface: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether b8:ee:65:5b:32:59 groups: wlan ssid Bbox-A3BD2403 channel 6 (2437 MHz 11g ht/20) bssid 00:37:b7:56:4b:60 regdomain ETSI country FR indoor ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 2:128-bit txpower 30 bmiss 7 scanvalid 60 protmode CTS ampdulimit 64k ampdudensity 8 shortgi -stbctx stbcrx -ldpc wme burst roaming MANUAL media: IEEE 802.11 Wireless Ethernet MCS mode 11ng status: associated nd6 options=29 .... Replace _wlan0_ to match the system's wireless interface name. The `ether` line will contain the MAC address of the specified interface. Now, change the MAC address of the Ethernet interface: [source,shell] .... # ifconfig re0 ether b8:ee:65:5b:32:59 .... Bring the wireless interface up (replacing _FR_ with your own 2-letter country code), but do not set an IP address: [source,shell] .... # ifconfig wlan0 create wlandev ath0 country FR ssid my_router up .... Make sure the _re0_ interface is up, then create the man:lagg[4] interface with _re0_ as master with failover to _wlan0_: [source,shell] .... # ifconfig re0 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport re0 laggport wlan0 .... The virtual interface should look something like this: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether b8:ee:65:5b:32:59 laggproto failover lagghash l2,l3,l4 laggport: re0 flags=5 laggport: wlan0 flags=0<> groups: lagg media: Ethernet autoselect status: active .... Then, start the DHCP client to obtain an IP address: [source,shell] .... # dhclient lagg0 .... To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_re0="ether b8:ee:65:5b:32:59" wlans_ath0="wlan0" ifconfig_wlan0="WPA" create_args_wlan0="country FR" cloned_interfaces="lagg0" ifconfig_lagg0="up laggproto failover laggport re0 laggport wlan0 DHCP" .... ==== [[network-diskless]] == Diskless Operation with PXE The Intel(R) Preboot eXecution Environment (PXE) allows an operating system to boot over the network. For example, a FreeBSD system can boot over the network and operate without a local disk, using file systems mounted from an NFS server. PXE support is usually available in the BIOS. To use PXE when the machine starts, select the `Boot from network` option in the BIOS setup or type a function key during system initialization. In order to provide the files needed for an operating system to boot over the network, a PXE setup also requires properly configured DHCP, TFTP, and NFS servers, where: * Initial parameters, such as an IP address, executable boot filename and location, server name, and root path are obtained from the DHCP server. * The operating system loader file is booted using TFTP. * The file systems are loaded using NFS. When a computer PXE boots, it receives information over DHCP about where to obtain the initial boot loader file. After the host computer receives this information, it downloads the boot loader via TFTP and then executes the boot loader. In FreeBSD, the boot loader file is [.filename]#/boot/pxeboot#. After [.filename]#/boot/pxeboot# executes, the FreeBSD kernel is loaded and the rest of the FreeBSD bootup sequence proceeds, as described in crossref:boot[boot,The FreeBSD Booting Process]. This section describes how to configure these services on a FreeBSD system so that other systems can PXE boot into FreeBSD. Refer to man:diskless[8] for more information. [CAUTION] ==== As described, the system providing these services is insecure. It should live in a protected area of a network and be untrusted by other hosts. ==== [[network-pxe-nfs]] === Setting Up the PXE Environment The steps shown in this section configure the built-in NFS and TFTP servers. The next section demonstrates how to install and configure the DHCP server. In this example, the directory which will contain the files used by PXE users is [.filename]#/b/tftpboot/FreeBSD/install#. It is important that this directory exists and that the same directory name is set in both [.filename]#/etc/inetd.conf# and [.filename]#/usr/local/etc/dhcpd.conf#. [.procedure] . Create the root directory which will contain a FreeBSD installation to be NFS mounted: + [source,shell] .... # export NFSROOTDIR=/b/tftpboot/FreeBSD/install # mkdir -p ${NFSROOTDIR} .... . Enable the NFS server by adding this line to [.filename]#/etc/rc.conf#: + [.programlisting] .... nfs_server_enable="YES" .... . Export the diskless root directory via NFS by adding the following to [.filename]#/etc/exports#: + [.programlisting] .... /b -ro -alldirs -maproot=root .... . Start the NFS server: + [source,shell] .... # service nfsd start .... . Enable man:inetd[8] by adding the following line to [.filename]#/etc/rc.conf#: + [.programlisting] .... inetd_enable="YES" .... . Uncomment the following line in [.filename]#/etc/inetd.conf# by making sure it does not start with a `#` symbol: + [.programlisting] .... tftp dgram udp wait root /usr/libexec/tftpd tftpd -l -s /b/tftpboot .... + [NOTE] ==== Some PXE versions require the TCP version of TFTP. In this case, uncomment the second `tftp` line which contains `stream tcp`. ==== . Start man:inetd[8]: + [source,shell] .... # service inetd start .... . Install the base system into [.filename]#${NFSROOTDIR}#, either by decompressing the official archives or by rebuilding the FreeBSD kernel and userland (refer to crossref:cutting-edge[makeworld,“Updating FreeBSD from Source”] for more detailed instructions, but do not forget to add `DESTDIR=_${NFSROOTDIR}_` when running the `make installkernel` and `make installworld` commands. . Test that the TFTP server works and can download the boot loader which will be obtained via PXE: + [source,shell] .... # tftp localhost tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... . Edit [.filename]#${NFSROOTDIR}/etc/fstab# and create an entry to mount the root file system over NFS: + [.programlisting] .... # Device Mountpoint FSType Options Dump Pass myhost.example.com:/b/tftpboot/FreeBSD/install / nfs ro 0 0 .... + Replace _myhost.example.com_ with the hostname or IP address of the NFS server. In this example, the root file system is mounted read-only in order to prevent NFS clients from potentially deleting the contents of the root file system. . Set the root password in the PXE environment for client machines which are PXE booting : + [source,shell] .... # chroot ${NFSROOTDIR} # passwd .... . If needed, enable man:ssh[1] root logins for client machines which are PXE booting by editing [.filename]#${NFSROOTDIR}/etc/ssh/sshd_config# and enabling `PermitRootLogin`. This option is documented in man:sshd_config[5]. . Perform any other needed customizations of the PXE environment in [.filename]#${NFSROOTDIR}#. These customizations could include things like installing packages or editing the password file with man:vipw[8]. When booting from an NFS root volume, [.filename]#/etc/rc# detects the NFS boot and runs [.filename]#/etc/rc.initdiskless#. In this case, [.filename]#/etc# and [.filename]#/var# need to be memory backed file systems so that these directories are writable but the NFS root directory is read-only: [source,shell] .... # chroot ${NFSROOTDIR} # mkdir -p conf/base # tar -c -v -f conf/base/etc.cpio.gz --format cpio --gzip etc # tar -c -v -f conf/base/var.cpio.gz --format cpio --gzip var .... When the system boots, memory file systems for [.filename]#/etc# and [.filename]#/var# will be created and mounted and the contents of the [.filename]#cpio.gz# files will be copied into them. By default, these file systems have a maximum capacity of 5 megabytes. If your archives do not fit, which is usually the case for [.filename]#/var# when binary packages have been installed, request a larger size by putting the number of 512 byte sectors needed (e.g., 5 megabytes is 10240 sectors) in [.filename]#${NFSROOTDIR}/conf/base/etc/md_size# and [.filename]#${NFSROOTDIR}/conf/base/var/md_size# files for [.filename]#/etc# and [.filename]#/var# file systems respectively. [[network-pxe-setting-up-dhcp]] === Configuring the DHCP Server The DHCP server does not need to be the same machine as the TFTP and NFS server, but it needs to be accessible in the network. -DHCP is not part of the FreeBSD base system but can be installed using the package:net/isc-dhcp43-server[] port or package. +DHCP is not part of the FreeBSD base system but can be installed using the package:net/isc-dhcp44-server[] port or package. Once installed, edit the configuration file, [.filename]#/usr/local/etc/dhcpd.conf#. Configure the `next-server`, `filename`, and `root-path` settings as seen in this example: [.programlisting] .... subnet 192.168.0.0 netmask 255.255.255.0 { range 192.168.0.2 192.168.0.3 ; option subnet-mask 255.255.255.0 ; option routers 192.168.0.1 ; option broadcast-address 192.168.0.255 ; option domain-name-servers 192.168.35.35, 192.168.35.36 ; option domain-name "example.com"; # IP address of TFTP server next-server 192.168.0.1 ; # path of boot loader obtained via tftp filename "FreeBSD/install/boot/pxeboot" ; # pxeboot boot loader will try to NFS mount this directory for root FS option root-path "192.168.0.1:/b/tftpboot/FreeBSD/install/" ; } .... The `next-server` directive is used to specify the IP address of the TFTP server. The `filename` directive defines the path to [.filename]#/boot/pxeboot#. A relative filename is used, meaning that [.filename]#/b/tftpboot# is not included in the path. The `root-path` option defines the path to the NFS root file system. Once the edits are saved, enable DHCP at boot time by adding the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" .... Then start the DHCP service: [source,shell] .... # service isc-dhcpd start .... === Debugging PXE Problems Once all of the services are configured and started, PXE clients should be able to automatically load FreeBSD over the network. If a particular client is unable to connect, when that client machine boots up, enter the BIOS configuration menu and confirm that it is set to boot from the network. This section describes some troubleshooting tips for isolating the source of the configuration problem should no clients be able to PXE boot. [.procedure] **** . Use the package:net/wireshark[] package or port to debug the network traffic involved during the PXE booting process, which is illustrated in the diagram below. + .PXE Booting Process with NFS Root Mount image::pxe-nfs.png[] + 1. Client broadcasts a DHCPDISCOVER message. + 2. The DHCP server responds with the IP address, next-server, filename, and root-path values. + 3. The client sends a TFTP request to next-server, asking to retrieve filename. + 4. The TFTP server responds and sends filename to client. + 5. The client executes filename, which is pxeboot(8), which then loads the kernel. When the kernel executes, the root file system specified by root-path is mounted over NFS. + . On the TFTP server, read [.filename]#/var/log/xferlog# to ensure that [.filename]#pxeboot# is being retrieved from the correct location. To test this example configuration: + [source,shell] .... # tftp 192.168.0.1 tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... + The `BUGS` sections in man:tftpd[8] and man:tftp[1] document some limitations with TFTP. . Make sure that the root file system can be mounted via NFS. To test this example configuration: + [source,shell] .... # mount -t nfs 192.168.0.1:/b/tftpboot/FreeBSD/install /mnt .... **** [[network-ipv6]] == IPv6 IPv6 is the new version of the well known IP protocol, also known as IPv4. IPv6 provides several advantages over IPv4 as well as many new features: * Its 128-bit address space allows for 340,282,366,920,938,463,463,374,607,431,768,211,456 addresses. This addresses the IPv4 address shortage and eventual IPv4 address exhaustion. * Routers only store network aggregation addresses in their routing tables, thus reducing the average space of a routing table to 8192 entries. This addresses the scalability issues associated with IPv4, which required every allocated block of IPv4 addresses to be exchanged between Internet routers, causing their routing tables to become too large to allow efficient routing. * Address autoconfiguration (http://www.ietf.org/rfc/rfc2462.txt[RFC2462]). * Mandatory multicast addresses. * Built-in IPsec (IP security). * Simplified header structure. * Support for mobile IP. * IPv6-to-IPv4 transition mechanisms. FreeBSD includes the http://www.kame.net/[http://www.kame.net/] IPv6 reference implementation and comes with everything needed to use IPv6. This section focuses on getting IPv6 configured and running. === Background on IPv6 Addresses There are three different types of IPv6 addresses: Unicast:: A packet sent to a unicast address arrives at the interface belonging to the address. Anycast:: These addresses are syntactically indistinguishable from unicast addresses but they address a group of interfaces. The packet destined for an anycast address will arrive at the nearest router interface. Anycast addresses are only used by routers. Multicast:: These addresses identify a group of interfaces. A packet destined for a multicast address will arrive at all interfaces belonging to the multicast group. The IPv4 broadcast address, usually `xxx.xxx.xxx.255`, is expressed by multicast addresses in IPv6. When reading an IPv6 address, the canonical form is represented as `x:x:x:x:x:x:x:x`, where each `x` represents a 16 bit hex value. An example is `FEBC:A574:382B:23C1:AA49:4592:4EFE:9982`. Often, an address will have long substrings of all zeros. A `::` (double colon) can be used to replace one substring per address. Also, up to three leading ``0``s per hex value can be omitted. For example, `fe80::1` corresponds to the canonical form `fe80:0000:0000:0000:0000:0000:0000:0001`. A third form is to write the last 32 bits using the well known IPv4 notation. For example, `2002::10.0.0.1` corresponds to the hexadecimal canonical representation `2002:0000:0000:0000:0000:0000:0a00:0001`, which in turn is equivalent to `2002::a00:1`. To view a FreeBSD system's IPv6 address, use man:ifconfig[8]: [source,shell] .... # ifconfig .... [.programlisting] .... rl0: flags=8943 mtu 1500 inet 10.0.0.10 netmask 0xffffff00 broadcast 10.0.0.255 inet6 fe80::200:21ff:fe03:8e1%rl0 prefixlen 64 scopeid 0x1 ether 00:00:21:03:08:e1 media: Ethernet autoselect (100baseTX ) status: active .... In this example, the [.filename]#rl0# interface is using `fe80::200:21ff:fe03:8e1%rl0`, an auto-configured link-local address which was automatically generated from the MAC address. Some IPv6 addresses are reserved. A summary of these reserved addresses is seen in <>: [[reservedip6]] .Reserved IPv6 Addresses [cols="1,1,1,1", frame="none", options="header"] |=== | IPv6 address | Prefixlength (Bits) | Description | Notes |`::` |128 bits |unspecified |Equivalent to `0.0.0.0` in IPv4. |`::1` |128 bits |loopback address |Equivalent to `127.0.0.1` in IPv4. |`::00:xx:xx:xx:xx` |96 bits |embedded IPv4 |The lower 32 bits are the compatible IPv4 address. |`::ff:xx:xx:xx:xx` |96 bits |IPv4 mapped IPv6 address |The lower 32 bits are the IPv4 address for hosts which do not support IPv6. |`fe80::/10` |10 bits |link-local |Equivalent to 169.254.0.0/16 in IPv4. |`fc00::/7` |7 bits |unique-local |Unique local addresses are intended for local communication and are only routable within a set of cooperating sites. |`ff00::` |8 bits |multicast | |``2000::-3fff::`` |3 bits |global unicast |All global unicast addresses are assigned from this pool. The first 3 bits are `001`. |=== For further information on the structure of IPv6 addresses, refer to http://www.ietf.org/rfc/rfc3513.txt[RFC3513]. === Configuring IPv6 To configure a FreeBSD system as an IPv6 client, add these two lines to [.filename]#rc.conf#: [.programlisting] .... ifconfig_rl0_ipv6="inet6 accept_rtadv" rtsold_enable="YES" .... The first line enables the specified interface to receive router advertisement messages. The second line enables the router solicitation daemon, man:rtsol[8]. If the interface needs a statically assigned IPv6 address, add an entry to specify the static address and associated prefix length: [.programlisting] .... ifconfig_rl0_ipv6="inet6 2001:db8:4672:6565:2026:5043:2d42:5344 prefixlen 64" .... To assign a default router, specify its address: [.programlisting] .... ipv6_defaultrouter="2001:db8:4672:6565::1" .... === Connecting to a Provider In order to connect to other IPv6 networks, one must have a provider or a tunnel that supports IPv6: * Contact an Internet Service Provider to see if they offer IPv6. * http://www.tunnelbroker.net[Hurricane Electric] offers tunnels with end-points all around the globe. [NOTE] ==== Install the package:net/freenet6[] package or port for a dial-up connection. ==== This section demonstrates how to take the directions from a tunnel provider and convert them into [.filename]#/etc/rc.conf# settings that will persist through reboots. The first [.filename]#/etc/rc.conf# entry creates the generic tunneling interface [.filename]#gif0#: [.programlisting] .... cloned_interfaces="gif0" .... Next, configure that interface with the IPv4 addresses of the local and remote endpoints. Replace `_MY_IPv4_ADDR_` and `_REMOTE_IPv4_ADDR_` with the actual IPv4 addresses: [.programlisting] .... create_args_gif0="tunnel MY_IPv4_ADDR REMOTE_IPv4_ADDR" .... To apply the IPv6 address that has been assigned for use as the IPv6 tunnel endpoint, add this line, replacing `_MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR_` with the assigned address: [.programlisting] .... ifconfig_gif0_ipv6="inet6 MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR" .... Then, set the default route for the other side of the IPv6 tunnel. Replace `_MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR_` with the default gateway address assigned by the provider: [.programlisting] .... ipv6_defaultrouter="MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR" .... If the FreeBSD system will route IPv6 packets between the rest of the network and the world, enable the gateway using this line: [.programlisting] .... ipv6_gateway_enable="YES" .... === Router Advertisement and Host Auto Configuration This section demonstrates how to setup man:rtadvd[8] to advertise the IPv6 default route. To enable man:rtadvd[8], add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... rtadvd_enable="YES" .... It is important to specify the interface on which to do IPv6 router advertisement. For example, to tell man:rtadvd[8] to use [.filename]#rl0#: [.programlisting] .... rtadvd_interfaces="rl0" .... Next, create the configuration file, [.filename]#/etc/rtadvd.conf# as seen in this example: [.programlisting] .... rl0:\ :addrs#1:addr="2001:db8:1f11:246::":prefixlen#64:tc=ether: .... Replace [.filename]#rl0# with the interface to be used and `2001:db8:1f11:246::` with the prefix of the allocation. For a dedicated `/64` subnet, nothing else needs to be changed. Otherwise, change the `prefixlen#` to the correct value. === IPv6 and IPv6 Address Mapping When IPv6 is enabled on a server, there may be a need to enable IPv4 mapped IPv6 address communication. This compatibility option allows for IPv4 addresses to be represented as IPv6 addresses. Permitting IPv6 applications to communicate with IPv4 and vice versa may be a security issue. This option may not be required in most cases and is available only for compatibility. This option will allow IPv6-only applications to work with IPv4 in a dual stack environment. This is most useful for third party applications which may not support an IPv6-only environment. To enable this feature, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... ipv6_ipv4mapping="YES" .... Reviewing the information in RFC 3493, section 3.6 and 3.7 as well as RFC 4038 section 4.2 may be useful to some administrators. [[carp]] == Common Address Redundancy Protocol (CARP) The Common Address Redundancy Protocol (CARP) allows multiple hosts to share the same IP address and Virtual Host ID (VHID) in order to provide _high availability_ for one or more services. This means that one or more hosts can fail, and the other hosts will transparently take over so that users do not see a service failure. In addition to the shared IP address, each host has its own IP address for management and configuration. All of the machines that share an IP address have the same VHID. The VHID for each virtual IP address must be unique across the broadcast domain of the network interface. High availability using CARP is built into FreeBSD, though the steps to configure it vary slightly depending upon the FreeBSD version. This section provides the same example configuration for versions before and equal to or after FreeBSD 10. This example configures failover support with three hosts, all with unique IP addresses, but providing the same web content. It has two different masters named `hosta.example.org` and `hostb.example.org`, with a shared backup named `hostc.example.org`. These machines are load balanced with a Round Robin DNS configuration. The master and backup machines are configured identically except for their hostnames and management IP addresses. These servers must have the same configuration and run the same services. When the failover occurs, requests to the service on the shared IP address can only be answered correctly if the backup server has access to the same content. The backup machine has two additional CARP interfaces, one for each of the master content server's IP addresses. When a failure occurs, the backup server will pick up the failed master machine's IP address. [[carp-10x]] === Using CARP on FreeBSD 10 and Later Enable boot-time support for CARP by adding an entry for the [.filename]#carp.ko# kernel module in [.filename]#/boot/loader.conf#: [.programlisting] .... carp_load="YES" .... To load the module now without rebooting: [source,shell] .... # kldload carp .... For users who prefer to use a custom kernel, include the following line in the custom kernel configuration file and compile the kernel as described in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [.programlisting] .... device carp .... The hostname, management IP address and subnet mask, shared IP address, and VHID are all set by adding entries to [.filename]#/etc/rc.conf#. This example is for `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_em0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 pass testpass alias 192.168.1.50/32" .... The next set of entries are for `hostb.example.org`. Since it represents a second master, it uses a different shared IP address and VHID. However, the passwords specified with `pass` must be identical as CARP will only listen to and accept advertisements from machines with the correct password. [.programlisting] .... hostname="hostb.example.org" ifconfig_em0="inet 192.168.1.4 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 2 pass testpass alias 192.168.1.51/32" .... The third machine, `hostc.example.org`, is configured to handle failover from either master. This machine is configured with two CARPVHIDs, one to handle the virtual IP address for each of the master hosts. The CARP advertising skew, `advskew`, is set to ensure that the backup host advertises later than the master, since `advskew` controls the order of precedence when there are multiple backup servers. [.programlisting] .... hostname="hostc.example.org" ifconfig_em0="inet 192.168.1.5 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 advskew 100 pass testpass alias 192.168.1.50/32" ifconfig_em0_alias1="inet vhid 2 advskew 100 pass testpass alias 192.168.1.51/32" .... Having two CARPVHIDs configured means that `hostc.example.org` will notice if either of the master servers becomes unavailable. If a master fails to advertise before the backup server, the backup server will pick up the shared IP address until the master becomes available again. [NOTE] ==== If the original master server becomes available again, `hostc.example.org` will not release the virtual IP address back to it automatically. For this to happen, preemption has to be enabled. The feature is disabled by default, it is controlled via the man:sysctl[8] variable `net.inet.carp.preempt`. The administrator can force the backup server to return the IP address to the master: [source,shell] .... # ifconfig em0 vhid 1 state backup .... ==== Once the configuration is complete, either restart networking or reboot each system. High availability is now enabled. CARP functionality can be controlled via several man:sysctl[8] variables documented in the man:carp[4] manual pages. Other actions can be triggered from CARP events by using man:devd[8]. [[carp-9x]] === Using CARP on FreeBSD 9 and Earlier The configuration for these versions of FreeBSD is similar to the one described in the previous section, except that a CARP device must first be created and referred to in the configuration. Enable boot-time support for CARP by loading the [.filename]#if_carp.ko# kernel module in [.filename]#/boot/loader.conf#: [.programlisting] .... if_carp_load="YES" .... To load the module now without rebooting: [source,shell] .... # kldload carp .... For users who prefer to use a custom kernel, include the following line in the custom kernel configuration file and compile the kernel as described in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [.programlisting] .... device carp .... Next, on each host, create a CARP device: [source,shell] .... # ifconfig carp0 create .... Set the hostname, management IP address, the shared IP address, and VHID by adding the required lines to [.filename]#/etc/rc.conf#. Since a virtual CARP device is used instead of an alias, the actual subnet mask of `/24` is used instead of `/32`. Here are the entries for `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_fxp0="inet 192.168.1.3 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 1 pass testpass 192.168.1.50/24" .... On `hostb.example.org`: [.programlisting] .... hostname="hostb.example.org" ifconfig_fxp0="inet 192.168.1.4 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 2 pass testpass 192.168.1.51/24" .... The third machine, `hostc.example.org`, is configured to handle failover from either of the master hosts: [.programlisting] .... hostname="hostc.example.org" ifconfig_fxp0="inet 192.168.1.5 netmask 255.255.255.0" cloned_interfaces="carp0 carp1" ifconfig_carp0="vhid 1 advskew 100 pass testpass 192.168.1.50/24" ifconfig_carp1="vhid 2 advskew 100 pass testpass 192.168.1.51/24" .... [NOTE] ==== Preemption is disabled in the [.filename]#GENERIC# FreeBSD kernel. If preemption has been enabled with a custom kernel, `hostc.example.org` may not release the IP address back to the original content server. The administrator can force the backup server to return the IP address to the master with the command: [source,shell] .... # ifconfig carp0 down && ifconfig carp0 up .... This should be done on the [.filename]#carp# interface which corresponds to the correct host. ==== Once the configuration is complete, either restart networking or reboot each system. High availability is now enabled. [[network-vlan]] == VLANs VLANs are a way of virtually dividing up a network into many different subnetworks, also referred to as segmenting. Each segment will have its own broadcast domain and be isolated from other VLANs. On FreeBSD, VLANs must be supported by the network card driver. To see which drivers support vlans, refer to the man:vlan[4] manual page. When configuring a VLAN, a couple pieces of information must be known. First, which network interface? Second, what is the VLAN tag? To configure VLANs at run time, with a NIC of `em0` and a VLAN tag of `5` the command would look like this: [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 inet 192.168.20.20/24 .... [NOTE] ==== See how the interface name includes the NIC driver name and the VLAN tag, separated by a period? This is a best practice to make maintaining the VLAN configuration easy when many VLANs are present on a machine. ==== To configure VLANs at boot time, [.filename]#/etc/rc.conf# must be updated. To duplicate the configuration above, the following will need to be added: [.programlisting] .... vlans_em0="5" ifconfig_em0_5="inet 192.168.20.20/24" .... Additional VLANs may be added, by simply adding the tag to the `vlans_em0` field and adding an additional line configuring the network on that VLAN tag's interface. It is useful to assign a symbolic name to an interface so that when the associated hardware is changed, only a few configuration variables need to be updated. For example, security cameras need to be run over VLAN 1 on `em0`. Later, if the `em0` card is replaced with a card that uses the man:ixgb[4] driver, all references to `em0.1` will not have to change to `ixgb0.1`. To configure VLAN `5`, on the NIC `em0`, assign the interface name `cameras`, and assign the interface an IP address of `_192.168.20.20_` with a `24`-bit prefix, use this command: [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 name cameras inet 192.168.20.20/24 .... For an interface named `video`, use the following: [source,shell] .... # ifconfig video.5 create vlan 5 vlandev video name cameras inet 192.168.20.20/24 .... To apply the changes at boot time, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... vlans_video="cameras" create_args_cameras="vlan 5" ifconfig_cameras="inet 192.168.20.20/24" .... diff --git a/documentation/content/pl/books/handbook/network-servers/_index.adoc b/documentation/content/pl/books/handbook/network-servers/_index.adoc index b7b0a3ed9a..d2fcce6201 100644 --- a/documentation/content/pl/books/handbook/network-servers/_index.adoc +++ b/documentation/content/pl/books/handbook/network-servers/_index.adoc @@ -1,2402 +1,2402 @@ --- title: Rozdział 30. Network Servers part: Część IV. Komunikacja sieciowa prev: books/handbook/mail next: books/handbook/firewalls showBookMenu: true weight: 35 path: "/books/handbook/" --- [[network-servers]] = Network Servers :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 30 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/network-servers/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[network-servers-synopsis]] == Synopsis This chapter covers some of the more frequently used network services on UNIX(R) systems. This includes installing, configuring, testing, and maintaining many different types of network services. Example configuration files are included throughout this chapter for reference. By the end of this chapter, readers will know: * How to manage the inetd daemon. * How to set up the Network File System (NFS). * How to set up the Network Information Server (NIS) for centralizing and sharing user accounts. * How to set FreeBSD up to act as an LDAP server or client * How to set up automatic network settings using DHCP. * How to set up a Domain Name Server (DNS). * How to set up the ApacheHTTP Server. * How to set up a File Transfer Protocol (FTP) server. * How to set up a file and print server for Windows(R) clients using Samba. * How to synchronize the time and date, and set up a time server using the Network Time Protocol (NTP). * How to set up iSCSI. This chapter assumes a basic knowledge of: * [.filename]#/etc/rc# scripts. * Network terminology. * Installation of additional third-party software (crossref:ports[ports,Installing Applications: Packages and Ports]). [[network-inetd]] == The inetd Super-Server The man:inetd[8] daemon is sometimes referred to as a Super-Server because it manages connections for many services. Instead of starting multiple applications, only the inetd service needs to be started. When a connection is received for a service that is managed by inetd, it determines which program the connection is destined for, spawns a process for that program, and delegates the program a socket. Using inetd for services that are not heavily used can reduce system load, when compared to running each daemon individually in stand-alone mode. Primarily, inetd is used to spawn other daemons, but several trivial protocols are handled internally, such as chargen, auth, time, echo, discard, and daytime. This section covers the basics of configuring inetd. [[network-inetd-conf]] === Configuration File Configuration of inetd is done by editing [.filename]#/etc/inetd.conf#. Each line of this configuration file represents an application which can be started by inetd. By default, every line starts with a comment (`#`), meaning that inetd is not listening for any applications. To configure inetd to listen for an application's connections, remove the `#` at the beginning of the line for that application. After saving your edits, configure inetd to start at system boot by editing [.filename]#/etc/rc.conf#: [.programlisting] .... inetd_enable="YES" .... To start inetd now, so that it listens for the service you configured, type: [source,shell] .... # service inetd start .... Once inetd is started, it needs to be notified whenever a modification is made to [.filename]#/etc/inetd.conf#: [[network-inetd-reread]] .Reloading the inetd Configuration File [example] ==== [source,shell] .... # service inetd reload .... ==== Typically, the default entry for an application does not need to be edited beyond removing the `#`. In some situations, it may be appropriate to edit the default entry. As an example, this is the default entry for man:ftpd[8] over IPv4: [.programlisting] .... ftp stream tcp nowait root /usr/libexec/ftpd ftpd -l .... The seven columns in an entry are as follows: [.programlisting] .... service-name socket-type protocol {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]] user[:group][/login-class] server-program server-program-arguments .... where: service-name:: The service name of the daemon to start. It must correspond to a service listed in [.filename]#/etc/services#. This determines which port inetd listens on for incoming connections to that service. When using a custom service, it must first be added to [.filename]#/etc/services#. socket-type:: Either `stream`, `dgram`, `raw`, or `seqpacket`. Use `stream` for TCP connections and `dgram` for UDP services. protocol:: Use one of the following protocol names: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Protocol Name | Explanation |tcp or tcp4 |TCP IPv4 |udp or udp4 |UDP IPv4 |tcp6 |TCP IPv6 |udp6 |UDP IPv6 |tcp46 |Both TCP IPv4 and IPv6 |udp46 |Both UDP IPv4 and IPv6 |=== {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]]:: In this field, `wait` or `nowait` must be specified. `max-child`, `max-connections-per-ip-per-minute` and `max-child-per-ip` are optional. + `wait|nowait` indicates whether or not the service is able to handle its own socket. `dgram` socket types must use `wait` while `stream` daemons, which are usually multi-threaded, should use `nowait`. `wait` usually hands off multiple sockets to a single daemon, while `nowait` spawns a child daemon for each new socket. + The maximum number of child daemons inetd may spawn is set by `max-child`. For example, to limit ten instances of the daemon, place a `/10` after `nowait`. Specifying `/0` allows an unlimited number of children. + `max-connections-per-ip-per-minute` limits the number of connections from any particular IP address per minute. Once the limit is reached, further connections from this IP address will be dropped until the end of the minute. For example, a value of `/10` would limit any particular IP address to ten connection attempts per minute. `max-child-per-ip` limits the number of child processes that can be started on behalf on any single IP address at any moment. These options can limit excessive resource consumption and help to prevent Denial of Service attacks. + An example can be seen in the default settings for man:fingerd[8]: + [.programlisting] .... finger stream tcp nowait/3/10 nobody /usr/libexec/fingerd fingerd -k -s .... user:: The username the daemon will run as. Daemons typically run as `root`, `daemon`, or `nobody`. server-program:: The full path to the daemon. If the daemon is a service provided by inetd internally, use `internal`. server-program-arguments:: Used to specify any command arguments to be passed to the daemon on invocation. If the daemon is an internal service, use `internal`. [[network-inetd-cmdline]] === Command-Line Options Like most server daemons, inetd has a number of options that can be used to modify its behavior. By default, inetd is started with `-wW -C 60`. These options enable TCP wrappers for all services, including internal services, and prevent any IP address from requesting any service more than 60 times per minute. To change the default options which are passed to inetd, add an entry for `inetd_flags` in [.filename]#/etc/rc.conf#. If inetd is already running, restart it with `service inetd restart`. The available rate limiting options are: -c maximum:: Specify the default maximum number of simultaneous invocations of each service, where the default is unlimited. May be overridden on a per-service basis by using `max-child` in [.filename]#/etc/inetd.conf#. -C rate:: Specify the default maximum number of times a service can be invoked from a single IP address per minute. May be overridden on a per-service basis by using `max-connections-per-ip-per-minute` in [.filename]#/etc/inetd.conf#. -R rate:: Specify the maximum number of times a service can be invoked in one minute, where the default is `256`. A rate of `0` allows an unlimited number. -s maximum:: Specify the maximum number of times a service can be invoked from a single IP address at any one time, where the default is unlimited. May be overridden on a per-service basis by using `max-child-per-ip` in [.filename]#/etc/inetd.conf#. Additional options are available. Refer to man:inetd[8] for the full list of options. [[network-inetd-security]] === Security Considerations Many of the daemons which can be managed by inetd are not security-conscious. Some daemons, such as fingerd, can provide information that may be useful to an attacker. Only enable the services which are needed and monitor the system for excessive connection attempts. `max-connections-per-ip-per-minute`, `max-child` and `max-child-per-ip` can be used to limit such attacks. By default, TCP wrappers is enabled. Consult man:hosts_access[5] for more information on placing TCP restrictions on various inetd invoked daemons. [[network-nfs]] == Network File System (NFS) FreeBSD supports the Network File System (NFS), which allows a server to share directories and files with clients over a network. With NFS, users and programs can access files on remote systems as if they were stored locally. NFS has many practical uses. Some of the more common uses include: * Data that would otherwise be duplicated on each client can be kept in a single location and accessed by clients on the network. * Several clients may need access to the [.filename]#/usr/ports/distfiles# directory. Sharing that directory allows for quick access to the source files without having to download them to each client. * On large networks, it is often more convenient to configure a central NFS server on which all user home directories are stored. Users can log into a client anywhere on the network and have access to their home directories. * Administration of NFS exports is simplified. For example, there is only one file system where security or backup policies must be set. * Removable media storage devices can be used by other machines on the network. This reduces the number of devices throughout the network and provides a centralized location to manage their security. It is often more convenient to install software on multiple machines from a centralized installation media. NFS consists of a server and one or more clients. The client remotely accesses the data that is stored on the server machine. In order for this to function properly, a few processes have to be configured and running. These daemons must be running on the server: [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Daemon | Description |nfsd |The NFS daemon which services requests from NFS clients. |mountd |The NFS mount daemon which carries out requests received from nfsd. |rpcbind | This daemon allows NFS clients to discover which port the NFS server is using. |=== Running man:nfsiod[8] on the client can improve performance, but is not required. [[network-configuring-nfs]] === Configuring the Server The file systems which the NFS server will share are specified in [.filename]#/etc/exports#. Each line in this file specifies a file system to be exported, which clients have access to that file system, and any access options. When adding entries to this file, each exported file system, its properties, and allowed hosts must occur on a single line. If no clients are listed in the entry, then any client on the network can mount that file system. The following [.filename]#/etc/exports# entries demonstrate how to export file systems. The examples can be modified to match the file systems and client names on the reader's network. There are many options that can be used in this file, but only a few will be mentioned here. See man:exports[5] for the full list of options. This example shows how to export [.filename]#/cdrom# to three hosts named _alpha_, _bravo_, and _charlie_: [.programlisting] .... /cdrom -ro alpha bravo charlie .... The `-ro` flag makes the file system read-only, preventing clients from making any changes to the exported file system. This example assumes that the host names are either in DNS or in [.filename]#/etc/hosts#. Refer to man:hosts[5] if the network does not have a DNS server. The next example exports [.filename]#/home# to three clients by IP address. This can be useful for networks without DNS or [.filename]#/etc/hosts# entries. The `-alldirs` flag allows subdirectories to be mount points. In other words, it will not automatically mount the subdirectories, but will permit the client to mount the directories that are required as needed. [.programlisting] .... /usr/home -alldirs 10.0.0.2 10.0.0.3 10.0.0.4 .... This next example exports [.filename]#/a# so that two clients from different domains may access that file system. The `-maproot=root` allows `root` on the remote system to write data on the exported file system as `root`. If `-maproot=root` is not specified, the client's `root` user will be mapped to the server's `nobody` account and will be subject to the access limitations defined for `nobody`. [.programlisting] .... /a -maproot=root host.example.com box.example.org .... A client can only be specified once per file system. For example, if [.filename]#/usr# is a single file system, these entries would be invalid as both entries specify the same host: [.programlisting] .... # Invalid when /usr is one file system /usr/src client /usr/ports client .... The correct format for this situation is to use one entry: [.programlisting] .... /usr/src /usr/ports client .... The following is an example of a valid export list, where [.filename]#/usr# and [.filename]#/exports# are local file systems: [.programlisting] .... # Export src and ports to client01 and client02, but only # client01 has root privileges on it /usr/src /usr/ports -maproot=root client01 /usr/src /usr/ports client02 # The client machines have root and can mount anywhere # on /exports. Anyone in the world can mount /exports/obj read-only /exports -alldirs -maproot=root client01 client02 /exports/obj -ro .... To enable the processes required by the NFS server at boot time, add these options to [.filename]#/etc/rc.conf#: [.programlisting] .... rpcbind_enable="YES" nfs_server_enable="YES" mountd_enable="YES" .... The server can be started now by running this command: [source,shell] .... # service nfsd start .... Whenever the NFS server is started, mountd also starts automatically. However, mountd only reads [.filename]#/etc/exports# when it is started. To make subsequent [.filename]#/etc/exports# edits take effect immediately, force mountd to reread it: [source,shell] .... # service mountd reload .... === Configuring the Client To enable NFS clients, set this option in each client's [.filename]#/etc/rc.conf#: [.programlisting] .... nfs_client_enable="YES" .... Then, run this command on each NFS client: [source,shell] .... # service nfsclient start .... The client now has everything it needs to mount a remote file system. In these examples, the server's name is `server` and the client's name is `client`. To mount [.filename]#/home# on `server` to the [.filename]#/mnt# mount point on `client`: [source,shell] .... # mount server:/home /mnt .... The files and directories in [.filename]#/home# will now be available on `client`, in the [.filename]#/mnt# directory. To mount a remote file system each time the client boots, add it to [.filename]#/etc/fstab#: [.programlisting] .... server:/home /mnt nfs rw 0 0 .... Refer to man:fstab[5] for a description of all available options. === Locking Some applications require file locking to operate correctly. To enable locking, add these lines to [.filename]#/etc/rc.conf# on both the client and server: [.programlisting] .... rpc_lockd_enable="YES" rpc_statd_enable="YES" .... Then start the applications: [source,shell] .... # service lockd start # service statd start .... If locking is not required on the server, the NFS client can be configured to lock locally by including `-L` when running mount. Refer to man:mount_nfs[8] for further details. [[network-autofs]] === Automating Mounts with man:autofs[5] [NOTE] ==== The man:autofs[5] automount facility is supported starting with FreeBSD 10.1-RELEASE. To use the automounter functionality in older versions of FreeBSD, use man:amd[8] instead. This chapter only describes the man:autofs[5] automounter. ==== The man:autofs[5] facility is a common name for several components that, together, allow for automatic mounting of remote and local filesystems whenever a file or directory within that file system is accessed. It consists of the kernel component, man:autofs[5], and several userspace applications: man:automount[8], man:automountd[8] and man:autounmountd[8]. It serves as an alternative for man:amd[8] from previous FreeBSD releases. Amd is still provided for backward compatibility purposes, as the two use different map format; the one used by autofs is the same as with other SVR4 automounters, such as the ones in Solaris, MacOS X, and Linux. The man:autofs[5] virtual filesystem is mounted on specified mountpoints by man:automount[8], usually invoked during boot. Whenever a process attempts to access file within the man:autofs[5] mountpoint, the kernel will notify man:automountd[8] daemon and pause the triggering process. The man:automountd[8] daemon will handle kernel requests by finding the proper map and mounting the filesystem according to it, then signal the kernel to release blocked process. The man:autounmountd[8] daemon automatically unmounts automounted filesystems after some time, unless they are still being used. The primary autofs configuration file is [.filename]#/etc/auto_master#. It assigns individual maps to top-level mounts. For an explanation of [.filename]#auto_master# and the map syntax, refer to man:auto_master[5]. There is a special automounter map mounted on [.filename]#/net#. When a file is accessed within this directory, man:autofs[5] looks up the corresponding remote mount and automatically mounts it. For instance, an attempt to access a file within [.filename]#/net/foobar/usr# would tell man:automountd[8] to mount the [.filename]#/usr# export from the host `foobar`. .Mounting an Export with man:autofs[5] [example] ==== In this example, `showmount -e` shows the exported file systems that can be mounted from the NFS server, `foobar`: [source,shell] .... % showmount -e foobar Exports list on foobar: /usr 10.10.10.0 /a 10.10.10.0 % cd /net/foobar/usr .... ==== The output from `showmount` shows [.filename]#/usr# as an export. When changing directories to [.filename]#/host/foobar/usr#, man:automountd[8] intercepts the request and attempts to resolve the hostname `foobar`. If successful, man:automountd[8] automatically mounts the source export. To enable man:autofs[5] at boot time, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... autofs_enable="YES" .... Then man:autofs[5] can be started by running: [source,shell] .... # service automount start # service automountd start # service autounmountd start .... The man:autofs[5] map format is the same as in other operating systems. Information about this format from other sources can be useful, like the http://web.archive.org/web/20160813071113/http://images.apple.com/business/docs/Autofs.pdf[Mac OS X document]. Consult the man:automount[8], man:automountd[8], man:autounmountd[8], and man:auto_master[5] manual pages for more information. [[network-nis]] == Network Information System (NIS) Network Information System (NIS) is designed to centralize administration of UNIX(R)-like systems such as Solaris(TM), HP-UX, AIX(R), Linux, NetBSD, OpenBSD, and FreeBSD. NIS was originally known as Yellow Pages but the name was changed due to trademark issues. This is the reason why NIS commands begin with `yp`. NIS is a Remote Procedure Call (RPC)-based client/server system that allows a group of machines within an NIS domain to share a common set of configuration files. This permits a system administrator to set up NIS client systems with only minimal configuration data and to add, remove, or modify configuration data from a single location. FreeBSD uses version 2 of the NIS protocol. === NIS Terms and Processes Table 28.1 summarizes the terms and important processes used by NIS: .NIS Terminology [cols="1,1", frame="none", options="header"] |=== | Term | Description |NIS domain name |NIS servers and clients share an NIS domain name. Typically, this name does not have anything to do with DNS. |man:rpcbind[8] |This service enables RPC and must be running in order to run an NIS server or act as an NIS client. |man:ypbind[8] |This service binds an NIS client to its NIS server. It will take the NIS domain name and use RPC to connect to the server. It is the core of client/server communication in an NIS environment. If this service is not running on a client machine, it will not be able to access the NIS server. |man:ypserv[8] |This is the process for the NIS server. If this service stops running, the server will no longer be able to respond to NIS requests so hopefully, there is a slave server to take over. Some non-FreeBSD clients will not try to reconnect using a slave server and the ypbind process may need to be restarted on these clients. |man:rpc.yppasswdd[8] |This process only runs on NIS master servers. This daemon allows NIS clients to change their NIS passwords. If this daemon is not running, users will have to login to the NIS master server and change their passwords there. |=== === Machine Types There are three types of hosts in an NIS environment: * NIS master server + This server acts as a central repository for host configuration information and maintains the authoritative copy of the files used by all of the NIS clients. The [.filename]#passwd#, [.filename]#group#, and other various files used by NIS clients are stored on the master server. While it is possible for one machine to be an NIS master server for more than one NIS domain, this type of configuration will not be covered in this chapter as it assumes a relatively small-scale NIS environment. * NIS slave servers + NIS slave servers maintain copies of the NIS master's data files in order to provide redundancy. Slave servers also help to balance the load of the master server as NIS clients always attach to the NIS server which responds first. * NIS clients + NIS clients authenticate against the NIS server during log on. Information in many files can be shared using NIS. The [.filename]#master.passwd#, [.filename]#group#, and [.filename]#hosts# files are commonly shared via NIS. Whenever a process on a client needs information that would normally be found in these files locally, it makes a query to the NIS server that it is bound to instead. === Planning Considerations This section describes a sample NIS environment which consists of 15 FreeBSD machines with no centralized point of administration. Each machine has its own [.filename]#/etc/passwd# and [.filename]#/etc/master.passwd#. These files are kept in sync with each other only through manual intervention. Currently, when a user is added to the lab, the process must be repeated on all 15 machines. The configuration of the lab will be as follows: [.informaltable] [cols="1,1,1", frame="none", options="header"] |=== | Machine name | IP address | Machine role |`ellington` |`10.0.0.2` |NIS master |`coltrane` |`10.0.0.3` |NIS slave |`basie` |`10.0.0.4` |Faculty workstation |`bird` |`10.0.0.5` |Client machine |`cli[1-11]` |`10.0.0.[6-17]` |Other client machines |=== If this is the first time an NIS scheme is being developed, it should be thoroughly planned ahead of time. Regardless of network size, several decisions need to be made as part of the planning process. ==== Choosing a NIS Domain Name When a client broadcasts its requests for info, it includes the name of the NIS domain that it is part of. This is how multiple servers on one network can tell which server should answer which request. Think of the NIS domain name as the name for a group of hosts. Some organizations choose to use their Internet domain name for their NIS domain name. This is not recommended as it can cause confusion when trying to debug network problems. The NIS domain name should be unique within the network and it is helpful if it describes the group of machines it represents. For example, the Art department at Acme Inc. might be in the "acme-art"NIS domain. This example will use the domain name `test-domain`. However, some non-FreeBSD operating systems require the NIS domain name to be the same as the Internet domain name. If one or more machines on the network have this restriction, the Internet domain name _must_ be used as the NIS domain name. ==== Physical Server Requirements There are several things to keep in mind when choosing a machine to use as a NIS server. Since NIS clients depend upon the availability of the server, choose a machine that is not rebooted frequently. The NIS server should ideally be a stand alone machine whose sole purpose is to be an NIS server. If the network is not heavily used, it is acceptable to put the NIS server on a machine running other services. However, if the NIS server becomes unavailable, it will adversely affect all NIS clients. === Configuring the NIS Master Server The canonical copies of all NIS files are stored on the master server. The databases used to store the information are called NIS maps. In FreeBSD, these maps are stored in [.filename]#/var/yp/[domainname]# where [.filename]#[domainname]# is the name of the NIS domain. Since multiple domains are supported, it is possible to have several directories, one for each domain. Each domain will have its own independent set of maps. NIS master and slave servers handle all NIS requests through man:ypserv[8]. This daemon is responsible for receiving incoming requests from NIS clients, translating the requested domain and map name to a path to the corresponding database file, and transmitting data from the database back to the client. Setting up a master NIS server can be relatively straight forward, depending on environmental needs. Since FreeBSD provides built-in NIS support, it only needs to be enabled by adding the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... nisdomainname="test-domain" <.> nis_server_enable="YES" <.> nis_yppasswdd_enable="YES" <.> .... <.> This line sets the NIS domain name to `test-domain`. <.> This automates the start up of the NIS server processes when the system boots. <.> This enables the man:rpc.yppasswdd[8] daemon so that users can change their NIS password from a client machine. Care must be taken in a multi-server domain where the server machines are also NIS clients. It is generally a good idea to force the servers to bind to themselves rather than allowing them to broadcast bind requests and possibly become bound to each other. Strange failure modes can result if one server goes down and others are dependent upon it. Eventually, all the clients will time out and attempt to bind to other servers, but the delay involved can be considerable and the failure mode is still present since the servers might bind to each other all over again. A server that is also a client can be forced to bind to a particular server by adding these additional lines to [.filename]#/etc/rc.conf#: [.programlisting] .... nis_client_enable="YES" <.> nis_client_flags="-S test-domain,server" <.> .... <.> This enables running client stuff as well. <.> This line sets the NIS domain name to `test-domain` and bind to itself. After saving the edits, type `/etc/netstart` to restart the network and apply the values defined in [.filename]#/etc/rc.conf#. Before initializing the NIS maps, start man:ypserv[8]: [source,shell] .... # service ypserv start .... ==== Initializing the NIS Maps NIS maps are generated from the configuration files in [.filename]#/etc# on the NIS master, with one exception: [.filename]#/etc/master.passwd#. This is to prevent the propagation of passwords to all the servers in the NIS domain. Therefore, before the NIS maps are initialized, configure the primary password files: [source,shell] .... # cp /etc/master.passwd /var/yp/master.passwd # cd /var/yp # vi master.passwd .... It is advisable to remove all entries for system accounts as well as any user accounts that do not need to be propagated to the NIS clients, such as the `root` and any other administrative accounts. [NOTE] ==== Ensure that the [.filename]#/var/yp/master.passwd# is neither group or world readable by setting its permissions to `600`. ==== After completing this task, initialize the NIS maps. FreeBSD includes the man:ypinit[8] script to do this. When generating maps for the master server, include `-m` and specify the NIS domain name: [source,shell] .... ellington# ypinit -m test-domain Server Type: MASTER Domain: test-domain Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. At this point, we have to construct a list of this domains YP servers. rod.darktech.org is already known as master server. Please continue to add any slave servers, one per line. When you are done with the list, type a . master server : ellington next host to add: coltrane next host to add: ^D The current list of NIS servers looks like this: ellington coltrane Is this correct? [y/n: y] y [..output from map generation..] NIS Map update completed. ellington has been setup as an YP master server without any errors. .... This will create [.filename]#/var/yp/Makefile# from [.filename]#/var/yp/Makefile.dist#. By default, this file assumes that the environment has a single NIS server with only FreeBSD clients. Since `test-domain` has a slave server, edit this line in [.filename]#/var/yp/Makefile# so that it begins with a comment (`#`): [.programlisting] .... NOPUSH = "True" .... ==== Adding New Users Every time a new user is created, the user account must be added to the master NIS server and the NIS maps rebuilt. Until this occurs, the new user will not be able to login anywhere except on the NIS master. For example, to add the new user `jsmith` to the `test-domain` domain, run these commands on the master server: [source,shell] .... # pw useradd jsmith # cd /var/yp # make test-domain .... The user could also be added using `adduser jsmith` instead of `pw useradd smith`. === Setting up a NIS Slave Server To set up an NIS slave server, log on to the slave server and edit [.filename]#/etc/rc.conf# as for the master server. Do not generate any NIS maps, as these already exist on the master server. When running `ypinit` on the slave server, use `-s` (for slave) instead of `-m` (for master). This option requires the name of the NIS master in addition to the domain name, as seen in this example: [source,shell] .... coltrane# ypinit -s ellington test-domain Server Type: SLAVE Domain: test-domain Master: ellington Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. There will be no further questions. The remainder of the procedure should take a few minutes, to copy the databases from ellington. Transferring netgroup... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byuser... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byhost... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring group.bygid... ypxfr: Exiting: Map successfully transferred Transferring group.byname... ypxfr: Exiting: Map successfully transferred Transferring services.byname... ypxfr: Exiting: Map successfully transferred Transferring rpc.bynumber... ypxfr: Exiting: Map successfully transferred Transferring rpc.byname... ypxfr: Exiting: Map successfully transferred Transferring protocols.byname... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byaddr... ypxfr: Exiting: Map successfully transferred Transferring netid.byname... ypxfr: Exiting: Map successfully transferred Transferring hosts.byaddr... ypxfr: Exiting: Map successfully transferred Transferring protocols.bynumber... ypxfr: Exiting: Map successfully transferred Transferring ypservers... ypxfr: Exiting: Map successfully transferred Transferring hosts.byname... ypxfr: Exiting: Map successfully transferred coltrane has been setup as an YP slave server without any errors. Remember to update map ypservers on ellington. .... This will generate a directory on the slave server called [.filename]#/var/yp/test-domain# which contains copies of the NIS master server's maps. Adding these [.filename]#/etc/crontab# entries on each slave server will force the slaves to sync their maps with the maps on the master server: [.programlisting] .... 20 * * * * root /usr/libexec/ypxfr passwd.byname 21 * * * * root /usr/libexec/ypxfr passwd.byuid .... These entries are not mandatory because the master server automatically attempts to push any map changes to its slaves. However, since clients may depend upon the slave server to provide correct password information, it is recommended to force frequent password map updates. This is especially important on busy networks where map updates might not always complete. To finish the configuration, run `/etc/netstart` on the slave server in order to start the NIS services. === Setting Up an NIS Client An NIS client binds to an NIS server using man:ypbind[8]. This daemon broadcasts RPC requests on the local network. These requests specify the domain name configured on the client. If an NIS server in the same domain receives one of the broadcasts, it will respond to ypbind, which will record the server's address. If there are several servers available, the client will use the address of the first server to respond and will direct all of its NIS requests to that server. The client will automatically ping the server on a regular basis to make sure it is still available. If it fails to receive a reply within a reasonable amount of time, ypbind will mark the domain as unbound and begin broadcasting again in the hopes of locating another server. To configure a FreeBSD machine to be an NIS client: [.procedure] . Edit [.filename]#/etc/rc.conf# and add the following lines in order to set the NIS domain name and start man:ypbind[8] during network startup: + [.programlisting] .... nisdomainname="test-domain" nis_client_enable="YES" .... . To import all possible password entries from the NIS server, use `vipw` to remove all user accounts except one from [.filename]#/etc/master.passwd#. When removing the accounts, keep in mind that at least one local account should remain and this account should be a member of `wheel`. If there is a problem with NIS, this local account can be used to log in remotely, become the superuser, and fix the problem. Before saving the edits, add the following line to the end of the file: + [.programlisting] .... +::::::::: .... + This line configures the client to provide anyone with a valid account in the NIS server's password maps an account on the client. There are many ways to configure the NIS client by modifying this line. One method is described in <>. For more detailed reading, refer to the book `Managing NFS and NIS`, published by O'Reilly Media. . To import all possible group entries from the NIS server, add this line to [.filename]#/etc/group#: + [.programlisting] .... +:*:: .... To start the NIS client immediately, execute the following commands as the superuser: [source,shell] .... # /etc/netstart # service ypbind start .... After completing these steps, running `ypcat passwd` on the client should show the server's [.filename]#passwd# map. === NIS Security Since RPC is a broadcast-based service, any system running ypbind within the same domain can retrieve the contents of the NIS maps. To prevent unauthorized transactions, man:ypserv[8] supports a feature called "securenets" which can be used to restrict access to a given set of hosts. By default, this information is stored in [.filename]#/var/yp/securenets#, unless man:ypserv[8] is started with `-p` and an alternate path. This file contains entries that consist of a network specification and a network mask separated by white space. Lines starting with `#` are considered to be comments. A sample [.filename]+securenets+ might look like this: [.programlisting] .... # allow connections from local host -- mandatory 127.0.0.1 255.255.255.255 # allow connections from any host # on the 192.168.128.0 network 192.168.128.0 255.255.255.0 # allow connections from any host # between 10.0.0.0 to 10.0.15.255 # this includes the machines in the testlab 10.0.0.0 255.255.240.0 .... If man:ypserv[8] receives a request from an address that matches one of these rules, it will process the request normally. If the address fails to match a rule, the request will be ignored and a warning message will be logged. If the [.filename]#securenets# does not exist, `ypserv` will allow connections from any host. crossref:security[tcpwrappers,"TCP Wrapper"] is an alternate mechanism for providing access control instead of [.filename]#securenets#. While either access control mechanism adds some security, they are both vulnerable to "IP spoofing" attacks. All NIS-related traffic should be blocked at the firewall. Servers using [.filename]#securenets# may fail to serve legitimate NIS clients with archaic TCP/IP implementations. Some of these implementations set all host bits to zero when doing broadcasts or fail to observe the subnet mask when calculating the broadcast address. While some of these problems can be fixed by changing the client configuration, other problems may force the retirement of these client systems or the abandonment of [.filename]#securenets#. The use of TCP Wrapper increases the latency of the NIS server. The additional delay may be long enough to cause timeouts in client programs, especially in busy networks with slow NIS servers. If one or more clients suffer from latency, convert those clients into NIS slave servers and force them to bind to themselves. ==== Barring Some Users In this example, the `basie` system is a faculty workstation within the NIS domain. The [.filename]#passwd# map on the master NIS server contains accounts for both faculty and students. This section demonstrates how to allow faculty logins on this system while refusing student logins. To prevent specified users from logging on to a system, even if they are present in the NIS database, use `vipw` to add `-_username_` with the correct number of colons towards the end of [.filename]#/etc/master.passwd# on the client, where _username_ is the username of a user to bar from logging in. The line with the blocked user must be before the `+` line that allows NIS users. In this example, `bill` is barred from logging on to `basie`: [source,shell] .... basie# cat /etc/master.passwd root:[password]:0:0::0:0:The super-user:/root:/bin/csh toor:[password]:0:0::0:0:The other super-user:/root:/bin/sh daemon:*:1:1::0:0:Owner of many system processes:/root:/usr/sbin/nologin operator:*:2:5::0:0:System &:/:/usr/sbin/nologin bin:*:3:7::0:0:Binaries Commands and Source,,,:/:/usr/sbin/nologin tty:*:4:65533::0:0:Tty Sandbox:/:/usr/sbin/nologin kmem:*:5:65533::0:0:KMem Sandbox:/:/usr/sbin/nologin games:*:7:13::0:0:Games pseudo-user:/usr/games:/usr/sbin/nologin news:*:8:8::0:0:News Subsystem:/:/usr/sbin/nologin man:*:9:9::0:0:Mister Man Pages:/usr/shared/man:/usr/sbin/nologin bind:*:53:53::0:0:Bind Sandbox:/:/usr/sbin/nologin uucp:*:66:66::0:0:UUCP pseudo-user:/var/spool/uucppublic:/usr/libexec/uucp/uucico xten:*:67:67::0:0:X-10 daemon:/usr/local/xten:/usr/sbin/nologin pop:*:68:6::0:0:Post Office Owner:/nonexistent:/usr/sbin/nologin nobody:*:65534:65534::0:0:Unprivileged user:/nonexistent:/usr/sbin/nologin -bill::::::::: +::::::::: basie# .... [[network-netgroups]] === Using Netgroups Barring specified users from logging on to individual systems becomes unscaleable on larger networks and quickly loses the main benefit of NIS: _centralized_ administration. Netgroups were developed to handle large, complex networks with hundreds of users and machines. Their use is comparable to UNIX(R) groups, where the main difference is the lack of a numeric ID and the ability to define a netgroup by including both user accounts and other netgroups. To expand on the example used in this chapter, the NIS domain will be extended to add the users and systems shown in Tables 28.2 and 28.3: .Additional Users [cols="1,1", frame="none", options="header"] |=== | User Name(s) | Description |`alpha`, `beta` |IT department employees |`charlie`, `delta` |IT department apprentices |`echo`, `foxtrott`, `golf`, ... |employees |`able`, `baker`, ... |interns |=== .Additional Systems [cols="1,1", frame="none", options="header"] |=== | Machine Name(s) | Description |`war`, `death`, `famine`, `pollution` |Only IT employees are allowed to log onto these servers. |`pride`, `greed`, `envy`, `wrath`, `lust`, `sloth` |All members of the IT department are allowed to login onto these servers. |`one`, `two`, `three`, `four`, ... |Ordinary workstations used by employees. |`trashcan` |A very old machine without any critical data. Even interns are allowed to use this system. |=== When using netgroups to configure this scenario, each user is assigned to one or more netgroups and logins are then allowed or forbidden for all members of the netgroup. When adding a new machine, login restrictions must be defined for all netgroups. When a new user is added, the account must be added to one or more netgroups. If the NIS setup is planned carefully, only one central configuration file needs modification to grant or deny access to machines. The first step is the initialization of the NIS `netgroup` map. In FreeBSD, this map is not created by default. On the NIS master server, use an editor to create a map named [.filename]#/var/yp/netgroup#. This example creates four netgroups to represent IT employees, IT apprentices, employees, and interns: [.programlisting] .... IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) USERS (,echo,test-domain) (,foxtrott,test-domain) \ (,golf,test-domain) INTERNS (,able,test-domain) (,baker,test-domain) .... Each entry configures a netgroup. The first column in an entry is the name of the netgroup. Each set of brackets represents either a group of one or more users or the name of another netgroup. When specifying a user, the three comma-delimited fields inside each group represent: . The name of the host(s) where the other fields representing the user are valid. If a hostname is not specified, the entry is valid on all hosts. . The name of the account that belongs to this netgroup. . The NIS domain for the account. Accounts may be imported from other NIS domains into a netgroup. If a group contains multiple users, separate each user with whitespace. Additionally, each field may contain wildcards. See man:netgroup[5] for details. Netgroup names longer than 8 characters should not be used. The names are case sensitive and using capital letters for netgroup names is an easy way to distinguish between user, machine and netgroup names. Some non-FreeBSD NIS clients cannot handle netgroups containing more than 15 entries. This limit may be circumvented by creating several sub-netgroups with 15 users or fewer and a real netgroup consisting of the sub-netgroups, as seen in this example: [.programlisting] .... BIGGRP1 (,joe1,domain) (,joe2,domain) (,joe3,domain) [...] BIGGRP2 (,joe16,domain) (,joe17,domain) [...] BIGGRP3 (,joe31,domain) (,joe32,domain) BIGGROUP BIGGRP1 BIGGRP2 BIGGRP3 .... Repeat this process if more than 225 (15 times 15) users exist within a single netgroup. To activate and distribute the new NIS map: [source,shell] ellington# cd /var/yp ellington# make .... This will generate the three NIS maps [.filename]#netgroup#, [.filename]#netgroup.byhost# and [.filename]#netgroup.byuser#. Use the map key option of man:ypcat[1] to check if the new NIS maps are available: [source,shell] .... ellington% ypcat -k netgroup ellington% ypcat -k netgroup.byhost ellington% ypcat -k netgroup.byuser .... The output of the first command should resemble the contents of [.filename]#/var/yp/netgroup#. The second command only produces output if host-specific netgroups were created. The third command is used to get the list of netgroups for a user. To configure a client, use man:vipw[8] to specify the name of the netgroup. For example, on the server named `war`, replace this line: [.programlisting] .... +::::::::: .... with [.programlisting] .... +@IT_EMP::::::::: .... This specifies that only the users defined in the netgroup `IT_EMP` will be imported into this system's password database and only those users are allowed to login to this system. This configuration also applies to the `~` function of the shell and all routines which convert between user names and numerical user IDs. In other words, `cd ~_user_` will not work, `ls -l` will show the numerical ID instead of the username, and `find . -user joe -print` will fail with the message `No such user`. To fix this, import all user entries without allowing them to login into the servers. This can be achieved by adding an extra line: [.programlisting] .... +:::::::::/usr/sbin/nologin .... This line configures the client to import all entries but to replace the shell in those entries with [.filename]#/usr/sbin/nologin#. Make sure that extra line is placed _after_ `+@IT_EMP:::::::::`. Otherwise, all user accounts imported from NIS will have [.filename]#/usr/sbin/nologin# as their login shell and no one will be able to login to the system. To configure the less important servers, replace the old `+:::::::::` on the servers with these lines: [.programlisting] .... +@IT_EMP::::::::: +@IT_APP::::::::: +:::::::::/usr/sbin/nologin .... The corresponding lines for the workstations would be: [.programlisting] .... +@IT_EMP::::::::: +@USERS::::::::: +:::::::::/usr/sbin/nologin .... NIS supports the creation of netgroups from other netgroups which can be useful if the policy regarding user access changes. One possibility is the creation of role-based netgroups. For example, one might create a netgroup called `BIGSRV` to define the login restrictions for the important servers, another netgroup called `SMALLSRV` for the less important servers, and a third netgroup called `USERBOX` for the workstations. Each of these netgroups contains the netgroups that are allowed to login onto these machines. The new entries for the NIS `netgroup` map would look like this: [.programlisting] .... BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS .... This method of defining login restrictions works reasonably well when it is possible to define groups of machines with identical restrictions. Unfortunately, this is the exception and not the rule. Most of the time, the ability to define login restrictions on a per-machine basis is required. Machine-specific netgroup definitions are another possibility to deal with the policy changes. In this scenario, the [.filename]#/etc/master.passwd# of each system contains two lines starting with "+". The first line adds a netgroup with the accounts allowed to login onto this machine and the second line adds all other accounts with [.filename]#/usr/sbin/nologin# as shell. It is recommended to use the "ALL-CAPS" version of the hostname as the name of the netgroup: [.programlisting] .... +@BOXNAME::::::::: +:::::::::/usr/sbin/nologin .... Once this task is completed on all the machines, there is no longer a need to modify the local versions of [.filename]#/etc/master.passwd# ever again. All further changes can be handled by modifying the NIS map. Here is an example of a possible `netgroup` map for this scenario: [.programlisting] .... # Define groups of users first IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) DEPT1 (,echo,test-domain) (,foxtrott,test-domain) DEPT2 (,golf,test-domain) (,hotel,test-domain) DEPT3 (,india,test-domain) (,juliet,test-domain) ITINTERN (,kilo,test-domain) (,lima,test-domain) D_INTERNS (,able,test-domain) (,baker,test-domain) # # Now, define some groups based on roles USERS DEPT1 DEPT2 DEPT3 BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS # # And a groups for a special tasks # Allow echo and golf to access our anti-virus-machine SECURITY IT_EMP (,echo,test-domain) (,golf,test-domain) # # machine-based netgroups # Our main servers WAR BIGSRV FAMINE BIGSRV # User india needs access to this server POLLUTION BIGSRV (,india,test-domain) # # This one is really important and needs more access restrictions DEATH IT_EMP # # The anti-virus-machine mentioned above ONE SECURITY # # Restrict a machine to a single user TWO (,hotel,test-domain) # [...more groups to follow] .... It may not always be advisable to use machine-based netgroups. When deploying a couple of dozen or hundreds of systems, role-based netgroups instead of machine-based netgroups may be used to keep the size of the NIS map within reasonable limits. === Password Formats NIS requires that all hosts within an NIS domain use the same format for encrypting passwords. If users have trouble authenticating on an NIS client, it may be due to a differing password format. In a heterogeneous network, the format must be supported by all operating systems, where DES is the lowest common standard. To check which format a server or client is using, look at this section of [.filename]#/etc/login.conf#: [.programlisting] .... default:\ :passwd_format=des:\ :copyright=/etc/COPYRIGHT:\ [Further entries elided] .... In this example, the system is using the DES format. Other possible values are `blf` for Blowfish and `md5` for MD5 encrypted passwords. If the format on a host needs to be edited to match the one being used in the NIS domain, the login capability database must be rebuilt after saving the change: [source,shell] .... # cap_mkdb /etc/login.conf .... [NOTE] ==== The format of passwords for existing user accounts will not be updated until each user changes their password _after_ the login capability database is rebuilt. ==== [[network-ldap]] == Lightweight Directory Access Protocol (LDAP) The Lightweight Directory Access Protocol (LDAP) is an application layer protocol used to access, modify, and authenticate objects using a distributed directory information service. Think of it as a phone or record book which stores several levels of hierarchical, homogeneous information. It is used in Active Directory and OpenLDAP networks and allows users to access to several levels of internal information utilizing a single account. For example, email authentication, pulling employee contact information, and internal website authentication might all make use of a single user account in the LDAP server's record base. This section provides a quick start guide for configuring an LDAP server on a FreeBSD system. It assumes that the administrator already has a design plan which includes the type of information to store, what that information will be used for, which users should have access to that information, and how to secure this information from unauthorized access. === LDAP Terminology and Structure LDAP uses several terms which should be understood before starting the configuration. All directory entries consist of a group of _attributes_. Each of these attribute sets contains a unique identifier known as a _Distinguished Name_ (DN) which is normally built from several other attributes such as the common or _Relative Distinguished Name_ (RDN). Similar to how directories have absolute and relative paths, consider a DN as an absolute path and the RDN as the relative path. An example LDAP entry looks like the following. This example searches for the entry for the specified user account (`uid`), organizational unit (`ou`), and organization (`o`): [source,shell] .... % ldapsearch -xb "uid=trhodes,ou=users,o=example.com" # extended LDIF # # LDAPv3 # base with scope subtree # filter: (objectclass=*) # requesting: ALL # # trhodes, users, example.com dn: uid=trhodes,ou=users,o=example.com mail: trhodes@example.com cn: Tom Rhodes uid: trhodes telephoneNumber: (123) 456-7890 # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... This example entry shows the values for the `dn`, `mail`, `cn`, `uid`, and `telephoneNumber` attributes. The cn attribute is the RDN. More information about LDAP and its terminology can be found at http://www.openldap.org/doc/admin24/intro.html[http://www.openldap.org/doc/admin24/intro.html]. [[ldap-config]] === Configuring an LDAP Server FreeBSD does not provide a built-in LDAP server. Begin the configuration by installing package:net/openldap-server[] package or port: [source,shell] .... # pkg install openldap-server .... There is a large set of default options enabled in the extref:{linux-users}[package, software]. Review them by running `pkg info openldap-server`. If they are not sufficient (for example if SQL support is needed), please consider recompiling the port using the appropriate crossref:ports[ports-using,framework]. The installation creates the directory [.filename]#/var/db/openldap-data# to hold the data. The directory to store the certificates must be created: [source,shell] .... # mkdir /usr/local/etc/openldap/private .... The next phase is to configure the Certificate Authority. The following commands must be executed from [.filename]#/usr/local/etc/openldap/private#. This is important as the file permissions need to be restrictive and users should not have access to these files. More detailed information about certificates and their parameters can be found in crossref:security[openssl,"OpenSSL"]. To create the Certificate Authority, start with this command and follow the prompts: [source,shell] .... # openssl req -days 365 -nodes -new -x509 -keyout ca.key -out ../ca.crt .... The entries for the prompts may be generic _except_ for the `Common Name`. This entry must be _different_ than the system hostname. If this will be a self signed certificate, prefix the hostname with `CA` for Certificate Authority. The next task is to create a certificate signing request and a private key. Input this command and follow the prompts: [source,shell] .... # openssl req -days 365 -nodes -new -keyout server.key -out server.csr .... During the certificate generation process, be sure to correctly set the `Common Name` attribute. The Certificate Signing Request must be signed with the Certificate Authority in order to be used as a valid certificate: [source,shell] .... # openssl x509 -req -days 365 -in server.csr -out ../server.crt -CA ../ca.crt -CAkey ca.key -CAcreateserial .... The final part of the certificate generation process is to generate and sign the client certificates: [source,shell] .... # openssl req -days 365 -nodes -new -keyout client.key -out client.csr # openssl x509 -req -days 3650 -in client.csr -out ../client.crt -CA ../ca.crt -CAkey ca.key .... Remember to use the same `Common Name` attribute when prompted. When finished, ensure that a total of eight (8) new files have been generated through the proceeding commands. The daemon running the OpenLDAP server is [.filename]#slapd#. Its configuration is performed through [.filename]#slapd.ldif#: the old [.filename]#slapd.conf# has been deprecated by OpenLDAP. http://www.openldap.org/doc/admin24/slapdconf2.html[Configuration examples] for [.filename]#slapd.ldif# are available and can also be found in [.filename]#/usr/local/etc/openldap/slapd.ldif.sample#. Options are documented in slapd-config(5). Each section of [.filename]#slapd.ldif#, like all the other LDAP attribute sets, is uniquely identified through a DN. Be sure that no blank lines are left between the `dn:` statement and the desired end of the section. In the following example, TLS will be used to implement a secure channel. The first section represents the global configuration: [.programlisting] .... # # See slapd-config(5) for details on configuration options. # This file should NOT be world readable. # dn: cn=config objectClass: olcGlobal cn: config # # # Define global ACLs to disable default read access. # olcArgsFile: /var/run/openldap/slapd.args olcPidFile: /var/run/openldap/slapd.pid olcTLSCertificateFile: /usr/local/etc/openldap/server.crt olcTLSCertificateKeyFile: /usr/local/etc/openldap/private/server.key olcTLSCACertificateFile: /usr/local/etc/openldap/ca.crt #olcTLSCipherSuite: HIGH olcTLSProtocolMin: 3.1 olcTLSVerifyClient: never .... The Certificate Authority, server certificate and server private key files must be specified here. It is recommended to let the clients choose the security cipher and omit option `olcTLSCipherSuite` (incompatible with TLS clients other than [.filename]#openssl#). Option `olcTLSProtocolMin` lets the server require a minimum security level: it is recommended. While verification is mandatory for the server, it is not for the client: `olcTLSVerifyClient: never`. The second section is about the backend modules and can be configured as follows: [.programlisting] .... # # Load dynamic backend modules: # dn: cn=module,cn=config objectClass: olcModuleList cn: module olcModulepath: /usr/local/libexec/openldap olcModuleload: back_mdb.la #olcModuleload: back_bdb.la #olcModuleload: back_hdb.la #olcModuleload: back_ldap.la #olcModuleload: back_passwd.la #olcModuleload: back_shell.la .... The third section is devoted to load the needed `ldif` schemas to be used by the databases: they are essential. [.programlisting] .... dn: cn=schema,cn=config objectClass: olcSchemaConfig cn: schema include: file:///usr/local/etc/openldap/schema/core.ldif include: file:///usr/local/etc/openldap/schema/cosine.ldif include: file:///usr/local/etc/openldap/schema/inetorgperson.ldif include: file:///usr/local/etc/openldap/schema/nis.ldif .... Next, the frontend configuration section: [.programlisting] .... # Frontend settings # dn: olcDatabase={-1}frontend,cn=config objectClass: olcDatabaseConfig objectClass: olcFrontendConfig olcDatabase: {-1}frontend olcAccess: to * by * read # # Sample global access control policy: # Root DSE: allow anyone to read it # Subschema (sub)entry DSE: allow anyone to read it # Other DSEs: # Allow self write access # Allow authenticated users read access # Allow anonymous users to authenticate # #olcAccess: to dn.base="" by * read #olcAccess: to dn.base="cn=Subschema" by * read #olcAccess: to * # by self write # by users read # by anonymous auth # # if no access controls are present, the default policy # allows anyone and everyone to read anything but restricts # updates to rootdn. (e.g., "access to * by * read") # # rootdn can always read and write EVERYTHING! # olcPasswordHash: {SSHA} # {SSHA} is already the default for olcPasswordHash .... Another section is devoted to the _configuration backend_, the only way to later access the OpenLDAP server configuration is as a global super-user. [.programlisting] .... dn: olcDatabase={0}config,cn=config objectClass: olcDatabaseConfig olcDatabase: {0}config olcAccess: to * by * none olcRootPW: {SSHA}iae+lrQZILpiUdf16Z9KmDmSwT77Dj4U .... The default administrator username is `cn=config`. Type [.filename]#slappasswd# in a shell, choose a password and use its hash in `olcRootPW`. If this option is not specified now, before [.filename]#slapd.ldif# is imported, no one will be later able to modify the _global configuration_ section. The last section is about the database backend: [.programlisting] .... ####################################################################### # LMDB database definitions ####################################################################### # dn: olcDatabase=mdb,cn=config objectClass: olcDatabaseConfig objectClass: olcMdbConfig olcDatabase: mdb olcDbMaxSize: 1073741824 olcSuffix: dc=domain,dc=example olcRootDN: cn=mdbadmin,dc=domain,dc=example # Cleartext passwords, especially for the rootdn, should # be avoided. See slappasswd(8) and slapd-config(5) for details. # Use of strong authentication encouraged. olcRootPW: {SSHA}X2wHvIWDk6G76CQyCMS1vDCvtICWgn0+ # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools. # Mode 700 recommended. olcDbDirectory: /var/db/openldap-data # Indices to maintain olcDbIndex: objectClass eq .... This database hosts the _actual contents_ of the LDAP directory. Types other than `mdb` are available. Its super-user, not to be confused with the global one, is configured here: a (possibly custom) username in `olcRootDN` and the password hash in `olcRootPW`; [.filename]#slappasswd# can be used as before. This http://www.openldap.org/devel/gitweb.cgi?p=openldap.git;a=tree;f=tests/data/regressions/its8444;h=8a5e808e63b0de3d2bdaf2cf34fecca8577ca7fd;hb=HEAD[repository] contains four examples of [.filename]#slapd.ldif#. To convert an existing [.filename]#slapd.conf# into [.filename]#slapd.ldif#, refer to http://www.openldap.org/doc/admin24/slapdconf2.html[this page] (please note that this may introduce some unuseful options). When the configuration is completed, [.filename]#slapd.ldif# must be placed in an empty directory. It is recommended to create it as: [source,shell] .... # mkdir /usr/local/etc/openldap/slapd.d/ .... Import the configuration database: [source,shell] .... # /usr/local/sbin/slapadd -n0 -F /usr/local/etc/openldap/slapd.d/ -l /usr/local/etc/openldap/slapd.ldif .... Start the [.filename]#slapd# daemon: [source,shell] .... # /usr/local/libexec/slapd -F /usr/local/etc/openldap/slapd.d/ .... Option `-d` can be used for debugging, as specified in slapd(8). To verify that the server is running and working: [source,shell] .... # ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts # extended LDIF # # LDAPv3 # base <> with scope baseObject # filter: (objectclass=*) # requesting: namingContexts # # dn: namingContexts: dc=domain,dc=example # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... The server must still be trusted. If that has never been done before, follow these instructions. Install the OpenSSL package or port: [source,shell] .... # pkg install openssl .... From the directory where [.filename]#ca.crt# is stored (in this example, [.filename]#/usr/local/etc/openldap#), run: [source,shell] .... # c_rehash . .... Both the CA and the server certificate are now correctly recognized in their respective roles. To verify this, run this command from the [.filename]#server.crt# directory: [source,shell] .... # openssl verify -verbose -CApath . server.crt .... If [.filename]#slapd# was running, restart it. As stated in [.filename]#/usr/local/etc/rc.d/slapd#, to properly run [.filename]#slapd# at boot the following lines must be added to [.filename]#/etc/rc.conf#: [.programlisting] .... lapd_enable="YES" slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://0.0.0.0/"' slapd_sockets="/var/run/openldap/ldapi" slapd_cn_config="YES" .... [.filename]#slapd# does not provide debugging at boot. Check [.filename]#/var/log/debug.log#, [.filename]#dmesg -a# and [.filename]#/var/log/messages# for this purpose. The following example adds the group `team` and the user `john` to the `domain.example` LDAP database, which is still empty. First, create the file [.filename]#domain.ldif#: [source,shell] .... # cat domain.ldif dn: dc=domain,dc=example objectClass: dcObject objectClass: organization o: domain.example dc: domain dn: ou=groups,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: groups dn: ou=users,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: users dn: cn=team,ou=groups,dc=domain,dc=example objectClass: top objectClass: posixGroup cn: team gidNumber: 10001 dn: uid=john,ou=users,dc=domain,dc=example objectClass: top objectClass: account objectClass: posixAccount objectClass: shadowAccount cn: John McUser uid: john uidNumber: 10001 gidNumber: 10001 homeDirectory: /home/john/ loginShell: /usr/bin/bash userPassword: secret .... See the OpenLDAP documentation for more details. Use [.filename]#slappasswd# to replace the plain text password `secret` with a hash in `userPassword`. The path specified as `loginShell` must exist in all the systems where `john` is allowed to login. Finally, use the `mdb` administrator to modify the database: [source,shell] .... # ldapadd -W -D "cn=mdbadmin,dc=domain,dc=example" -f domain.ldif .... Modifications to the _global configuration_ section can only be performed by the global super-user. For example, assume that the option `olcTLSCipherSuite: HIGH:MEDIUM:SSLv3` was initially specified and must now be deleted. First, create a file that contains the following: [source,shell] .... # cat global_mod dn: cn=config changetype: modify delete: olcTLSCipherSuite .... Then, apply the modifications: [source,shell] .... # ldapmodify -f global_mod -x -D "cn=config" -W .... When asked, provide the password chosen in the _configuration backend_ section. The username is not required: here, `cn=config` represents the DN of the database section to be modified. Alternatively, use `ldapmodify` to delete a single line of the database, `ldapdelete` to delete a whole entry. If something goes wrong, or if the global super-user cannot access the configuration backend, it is possible to delete and re-write the whole configuration: [source,shell] .... # rm -rf /usr/local/etc/openldap/slapd.d/ .... [.filename]#slapd.ldif# can then be edited and imported again. Please, follow this procedure only when no other solution is available. This is the configuration of the server only. The same machine can also host an LDAP client, with its own separate configuration. [[network-dhcp]] == Dynamic Host Configuration Protocol (DHCP) The Dynamic Host Configuration Protocol (DHCP) allows a system to connect to a network in order to be assigned the necessary addressing information for communication on that network. FreeBSD includes the OpenBSD version of `dhclient` which is used by the client to obtain the addressing information. FreeBSD does not install a DHCP server, but several servers are available in the FreeBSD Ports Collection. The DHCP protocol is fully described in http://www.freesoft.org/CIE/RFC/2131/[RFC 2131]. Informational resources are also available at http://www.isc.org/downloads/dhcp/[isc.org/downloads/dhcp/]. This section describes how to use the built-in DHCP client. It then describes how to install and configure a DHCP server. [NOTE] ==== In FreeBSD, the man:bpf[4] device is needed by both the DHCP server and DHCP client. This device is included in the [.filename]#GENERIC# kernel that is installed with FreeBSD. Users who prefer to create a custom kernel need to keep this device if DHCP is used. It should be noted that [.filename]#bpf# also allows privileged users to run network packet sniffers on that system. ==== === Configuring a DHCP Client DHCP client support is included in the FreeBSD installer, making it easy to configure a newly installed system to automatically receive its networking addressing information from an existing DHCP server. Refer to crossref:bsdinstall[bsdinstall-post,"Accounts, Time Zone, Services and Hardening"] for examples of network configuration. When `dhclient` is executed on the client machine, it begins broadcasting requests for configuration information. By default, these requests use UDP port 68. The server replies on UDP port 67, giving the client an IP address and other relevant network information such as a subnet mask, default gateway, and DNS server addresses. This information is in the form of a DHCP"lease" and is valid for a configurable time. This allows stale IP addresses for clients no longer connected to the network to automatically be reused. DHCP clients can obtain a great deal of information from the server. An exhaustive list may be found in man:dhcp-options[5]. By default, when a FreeBSD system boots, its DHCP client runs in the background, or _asynchronously_. Other startup scripts continue to run while the DHCP process completes, which speeds up system startup. Background DHCP works well when the DHCP server responds quickly to the client's requests. However, DHCP may take a long time to complete on some systems. If network services attempt to run before DHCP has assigned the network addressing information, they will fail. Using DHCP in _synchronous_ mode prevents this problem as it pauses startup until the DHCP configuration has completed. This line in [.filename]#/etc/rc.conf# is used to configure background or asynchronous mode: [.programlisting] .... ifconfig_fxp0="DHCP" .... This line may already exist if the system was configured to use DHCP during installation. Replace the _fxp0_ shown in these examples with the name of the interface to be dynamically configured, as described in crossref:config[config-network-setup,“Setting Up Network Interface Cards”]. To instead configure the system to use synchronous mode, and to pause during startup while DHCP completes, use "`SYNCDHCP`": [.programlisting] .... ifconfig_fxp0="SYNCDHCP" .... Additional client options are available. Search for `dhclient` in man:rc.conf[5] for details. The DHCP client uses the following files: * [.filename]#/etc/dhclient.conf# + The configuration file used by `dhclient`. Typically, this file contains only comments as the defaults are suitable for most clients. This configuration file is described in man:dhclient.conf[5]. * [.filename]#/sbin/dhclient# + More information about the command itself can be found in man:dhclient[8]. * [.filename]#/sbin/dhclient-script# + The FreeBSD-specific DHCP client configuration script. It is described in man:dhclient-script[8], but should not need any user modification to function properly. * [.filename]#/var/db/dhclient.leases.interface# + The DHCP client keeps a database of valid leases in this file, which is written as a log and is described in man:dhclient.leases[5]. [[network-dhcp-server]] === Installing and Configuring a DHCP Server -This section demonstrates how to configure a FreeBSD system to act as a DHCP server using the Internet Systems Consortium (ISC) implementation of the DHCP server. This implementation and its documentation can be installed using the package:net/isc-dhcp43-server[] package or port. +This section demonstrates how to configure a FreeBSD system to act as a DHCP server using the Internet Systems Consortium (ISC) implementation of the DHCP server. This implementation and its documentation can be installed using the package:net/isc-dhcp44-server[] package or port. -The installation of package:net/isc-dhcp43-server[] installs a sample configuration file. Copy [.filename]#/usr/local/etc/dhcpd.conf.example# to [.filename]#/usr/local/etc/dhcpd.conf# and make any edits to this new file. +The installation of package:net/isc-dhcp44-server[] installs a sample configuration file. Copy [.filename]#/usr/local/etc/dhcpd.conf.example# to [.filename]#/usr/local/etc/dhcpd.conf# and make any edits to this new file. The configuration file is comprised of declarations for subnets and hosts which define the information that is provided to DHCP clients. For example, these lines configure the following: [.programlisting] .... option domain-name "example.org";<.> option domain-name-servers ns1.example.org;<.> option subnet-mask 255.255.255.0;<.> default-lease-time 600;<.> max-lease-time 72400;<.> ddns-update-style none;<.> subnet 10.254.239.0 netmask 255.255.255.224 { range 10.254.239.10 10.254.239.20;<.> option routers rtr-239-0-1.example.org, rtr-239-0-2.example.org;<.> } host fantasia { hardware ethernet 08:00:07:26:c0:a5;<.> fixed-address fantasia.fugue.com;<.> } .... <.> This option specifies the default search domain that will be provided to clients. Refer to man:resolv.conf[5] for more information. <.> This option specifies a comma separated list of DNS servers that the client should use. They can be listed by their Fully Qualified Domain Names (FQDN), as seen in the example, or by their IP addresses. <.> The subnet mask that will be provided to clients. <.> The default lease expiry time in seconds. A client can be configured to override this value. <.> The maximum allowed length of time, in seconds, for a lease. Should a client request a longer lease, a lease will still be issued, but it will only be valid for `max-lease-time`. <.> The default of `none` disables dynamic DNS updates. Changing this to `interim` configures the DHCP server to update a DNS server whenever it hands out a lease so that the DNS server knows which IP addresses are associated with which computers in the network. Do not change the default setting unless the DNS server has been configured to support dynamic DNS. <.> This line creates a pool of available IP addresses which are reserved for allocation to DHCP clients. The range of addresses must be valid for the network or subnet specified in the previous line. <.> Declares the default gateway that is valid for the network or subnet specified before the opening `{` bracket. <.> Specifies the hardware MAC address of a client so that the DHCP server can recognize the client when it makes a request. <.> Specifies that this host should always be given the same IP address. Using the hostname is correct, since the DHCP server will resolve the hostname before returning the lease information. This configuration file supports many more options. Refer to dhcpd.conf(5), installed with the server, for details and examples. Once the configuration of [.filename]#dhcpd.conf# is complete, enable the DHCP server in [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" dhcpd_ifaces="dc0" .... Replace the `dc0` with the interface (or interfaces, separated by whitespace) that the DHCP server should listen on for DHCP client requests. Start the server by issuing the following command: [source,shell] .... # service isc-dhcpd start .... Any future changes to the configuration of the server will require the dhcpd service to be stopped and then started using man:service[8]. The DHCP server uses the following files. Note that the manual pages are installed with the server software. * [.filename]#/usr/local/sbin/dhcpd# + More information about the dhcpd server can be found in dhcpd(8). * [.filename]#/usr/local/etc/dhcpd.conf# + The server configuration file needs to contain all the information that should be provided to clients, along with information regarding the operation of the server. This configuration file is described in dhcpd.conf(5). * [.filename]#/var/db/dhcpd.leases# + The DHCP server keeps a database of leases it has issued in this file, which is written as a log. Refer to dhcpd.leases(5), which gives a slightly longer description. * [.filename]#/usr/local/sbin/dhcrelay# + -This daemon is used in advanced environments where one DHCP server forwards a request from a client to another DHCP server on a separate network. If this functionality is required, install the package:net/isc-dhcp43-relay[] package or port. The installation includes dhcrelay(8) which provides more detail. +This daemon is used in advanced environments where one DHCP server forwards a request from a client to another DHCP server on a separate network. If this functionality is required, install the package:net/isc-dhcp44-relay[] package or port. The installation includes dhcrelay(8) which provides more detail. [[network-dns]] == Domain Name System (DNS) Domain Name System (DNS) is the protocol through which domain names are mapped to IP addresses, and vice versa. DNS is coordinated across the Internet through a somewhat complex system of authoritative root, Top Level Domain (TLD), and other smaller-scale name servers, which host and cache individual domain information. It is not necessary to run a name server to perform DNS lookups on a system. The following table describes some of the terms associated with DNS: .DNS Terminology [cols="1,1", frame="none", options="header"] |=== | Term | Definition |Forward DNS |Mapping of hostnames to IP addresses. |Origin |Refers to the domain covered in a particular zone file. |Resolver |A system process through which a machine queries a name server for zone information. |Reverse DNS |Mapping of IP addresses to hostnames. |Root zone |The beginning of the Internet zone hierarchy. All zones fall under the root zone, similar to how all files in a file system fall under the root directory. |Zone |An individual domain, subdomain, or portion of the DNS administered by the same authority. |=== Examples of zones: * `.` is how the root zone is usually referred to in documentation. * `org.` is a Top Level Domain (TLD) under the root zone. * `example.org.` is a zone under the `org.` TLD. * `1.168.192.in-addr.arpa` is a zone referencing all IP addresses which fall under the `192.168.1.*` IP address space. As one can see, the more specific part of a hostname appears to its left. For example, `example.org.` is more specific than `org.`, as `org.` is more specific than the root zone. The layout of each part of a hostname is much like a file system: the [.filename]#/dev# directory falls within the root, and so on. === Reasons to Run a Name Server Name servers generally come in two forms: authoritative name servers, and caching (also known as resolving) name servers. An authoritative name server is needed when: * One wants to serve DNS information to the world, replying authoritatively to queries. * A domain, such as `example.org`, is registered and IP addresses need to be assigned to hostnames under it. * An IP address block requires reverse DNS entries (IP to hostname). * A backup or second name server, called a slave, will reply to queries. A caching name server is needed when: * A local DNS server may cache and respond more quickly than querying an outside name server. When one queries for `www.FreeBSD.org`, the resolver usually queries the uplink ISP's name server, and retrieves the reply. With a local, caching DNS server, the query only has to be made once to the outside world by the caching DNS server. Additional queries will not have to go outside the local network, since the information is cached locally. === DNS Server Configuration Unbound is provided in the FreeBSD base system. By default, it will provide DNS resolution to the local machine only. While the base system package can be configured to provide resolution services beyond the local machine, it is recommended that such requirements be addressed by installing Unbound from the FreeBSD Ports Collection. To enable Unbound, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... local_unbound_enable="YES" .... Any existing nameservers in [.filename]#/etc/resolv.conf# will be configured as forwarders in the new Unbound configuration. [NOTE] ==== If any of the listed nameservers do not support DNSSEC, local DNS resolution will fail. Be sure to test each nameserver and remove any that fail the test. The following command will show the trust tree or a failure for a nameserver running on `192.168.1.1`: ==== [source,shell] .... % drill -S FreeBSD.org @192.168.1.1 .... Once each nameserver is confirmed to support DNSSEC, start Unbound: [source,shell] .... # service local_unbound onestart .... This will take care of updating [.filename]#/etc/resolv.conf# so that queries for DNSSEC secured domains will now work. For example, run the following to validate the FreeBSD.org DNSSEC trust tree: [source,shell] .... % drill -S FreeBSD.org ;; Number of trusted keys: 1 ;; Chasing: freebsd.org. A DNSSEC Trust tree: freebsd.org. (A) |---freebsd.org. (DNSKEY keytag: 36786 alg: 8 flags: 256) |---freebsd.org. (DNSKEY keytag: 32659 alg: 8 flags: 257) |---freebsd.org. (DS keytag: 32659 digest type: 2) |---org. (DNSKEY keytag: 49587 alg: 7 flags: 256) |---org. (DNSKEY keytag: 9795 alg: 7 flags: 257) |---org. (DNSKEY keytag: 21366 alg: 7 flags: 257) |---org. (DS keytag: 21366 digest type: 1) | |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) | |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) |---org. (DS keytag: 21366 digest type: 2) |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) ;; Chase successful .... [[network-apache]] == Apache HTTP Server The open source Apache HTTP Server is the most widely used web server. FreeBSD does not install this web server by default, but it can be installed from the package:www/apache24[] package or port. This section summarizes how to configure and start version 2._x_ of the Apache HTTP Server on FreeBSD. For more detailed information about Apache 2.X and its configuration directives, refer to http://httpd.apache.org/[httpd.apache.org]. === Configuring and Starting Apache In FreeBSD, the main Apache HTTP Server configuration file is installed as [.filename]#/usr/local/etc/apache2x/httpd.conf#, where _x_ represents the version number. This ASCII text file begins comment lines with a `#`. The most frequently modified directives are: `ServerRoot "/usr/local"`:: Specifies the default directory hierarchy for the Apache installation. Binaries are stored in the [.filename]#bin# and [.filename]#sbin# subdirectories of the server root and configuration files are stored in the [.filename]#etc/apache2x# subdirectory. `ServerAdmin you@example.com`:: Change this to the email address to receive problems with the server. This address also appears on some server-generated pages, such as error documents. `ServerName www.example.com:80`:: Allows an administrator to set a hostname which is sent back to clients for the server. For example, `www` can be used instead of the actual hostname. If the system does not have a registered DNS name, enter its IP address instead. If the server will listen on an alternate report, change `80` to the alternate port number. `DocumentRoot "/usr/local/www/apache2__x__/data"`:: The directory where documents will be served from. By default, all requests are taken from this directory, but symbolic links and aliases may be used to point to other locations. It is always a good idea to make a backup copy of the default Apache configuration file before making changes. When the configuration of Apache is complete, save the file and verify the configuration using `apachectl`. Running `apachectl configtest` should return `Syntax OK`. To launch Apache at system startup, add the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... apache24_enable="YES" .... If Apache should be started with non-default options, the following line may be added to [.filename]#/etc/rc.conf# to specify the needed flags: [.programlisting] .... apache24_flags="" .... If apachectl does not report configuration errors, start `httpd` now: [source,shell] .... # service apache24 start .... The `httpd` service can be tested by entering `http://_localhost_` in a web browser, replacing _localhost_ with the fully-qualified domain name of the machine running `httpd`. The default web page that is displayed is [.filename]#/usr/local/www/apache24/data/index.html#. The Apache configuration can be tested for errors after making subsequent configuration changes while `httpd` is running using the following command: [source,shell] .... # service apache24 configtest .... [NOTE] ==== It is important to note that `configtest` is not an man:rc[8] standard, and should not be expected to work for all startup scripts. ==== === Virtual Hosting Virtual hosting allows multiple websites to run on one Apache server. The virtual hosts can be _IP-based_ or _name-based_. IP-based virtual hosting uses a different IP address for each website. Name-based virtual hosting uses the clients HTTP/1.1 headers to figure out the hostname, which allows the websites to share the same IP address. To setup Apache to use name-based virtual hosting, add a `VirtualHost` block for each website. For example, for the webserver named `www.domain.tld` with a virtual domain of `www.someotherdomain.tld`, add the following entries to [.filename]#httpd.conf#: [.programlisting] .... ServerName www.domain.tld DocumentRoot /www/domain.tld ServerName www.someotherdomain.tld DocumentRoot /www/someotherdomain.tld .... For each virtual host, replace the values for `ServerName` and `DocumentRoot` with the values to be used. For more information about setting up virtual hosts, consult the official Apache documentation at: http://httpd.apache.org/docs/vhosts/[http://httpd.apache.org/docs/vhosts/]. === Apache Modules Apache uses modules to augment the functionality provided by the basic server. Refer to http://httpd.apache.org/docs/current/mod/[http://httpd.apache.org/docs/current/mod/] for a complete listing of and the configuration details for the available modules. In FreeBSD, some modules can be compiled with the package:www/apache24[] port. Type `make config` within [.filename]#/usr/ports/www/apache24# to see which modules are available and which are enabled by default. If the module is not compiled with the port, the FreeBSD Ports Collection provides an easy way to install many modules. This section describes three of the most commonly used modules. ==== [.filename]#mod_ssl# The [.filename]#mod_ssl# module uses the OpenSSL library to provide strong cryptography via the Secure Sockets Layer (SSLv3) and Transport Layer Security (TLSv1) protocols. This module provides everything necessary to request a signed certificate from a trusted certificate signing authority to run a secure web server on FreeBSD. In FreeBSD, [.filename]#mod_ssl# module is enabled by default in both the package and the port. The available configuration directives are explained at http://httpd.apache.org/docs/current/mod/mod_ssl.html[http://httpd.apache.org/docs/current/mod/mod_ssl.html]. ==== [.filename]#mod_perl# The [.filename]#mod_perl# module makes it possible to write Apache modules in Perl. In addition, the persistent interpreter embedded in the server avoids the overhead of starting an external interpreter and the penalty of Perl start-up time. The [.filename]#mod_perl# can be installed using the package:www/mod_perl2[] package or port. Documentation for using this module can be found at http://perl.apache.org/docs/2.0/index.html[http://perl.apache.org/docs/2.0/index.html]. ==== [.filename]#mod_php# _PHP: Hypertext Preprocessor_ (PHP) is a general-purpose scripting language that is especially suited for web development. Capable of being embedded into HTML, its syntax draws upon C, Java(TM), and Perl with the intention of allowing web developers to write dynamically generated webpages quickly. To gain support for PHP5 for the Apache web server, install the package:www/mod_php56[] package or port. This will install and configure the modules required to support dynamic PHP applications. The installation will automatically add this line to [.filename]#/usr/local/etc/apache24/httpd.conf#: [.programlisting] .... LoadModule php5_module libexec/apache24/libphp5.so .... Then, perform a graceful restart to load the PHP module: [source,shell] .... # apachectl graceful .... The PHP support provided by package:www/mod_php56[] is limited. Additional support can be installed using the package:lang/php56-extensions[] port which provides a menu driven interface to the available PHP extensions. Alternatively, individual extensions can be installed using the appropriate port. For instance, to add PHP support for the MySQL database server, install package:databases/php56-mysql[]. After installing an extension, the Apache server must be reloaded to pick up the new configuration changes: [source,shell] .... # apachectl graceful .... === Dynamic Websites In addition to mod_perl and mod_php, other languages are available for creating dynamic web content. These include Django and Ruby on Rails. ==== Django Django is a BSD-licensed framework designed to allow developers to write high performance, elegant web applications quickly. It provides an object-relational mapper so that data types are developed as Python objects. A rich dynamic database-access API is provided for those objects without the developer ever having to write SQL. It also provides an extensible template system so that the logic of the application is separated from the HTML presentation. Django depends on [.filename]#mod_python#, and an SQL database engine. In FreeBSD, the package:www/py-django[] port automatically installs [.filename]#mod_python# and supports the PostgreSQL, MySQL, or SQLite databases, with the default being SQLite. To change the database engine, type `make config` within [.filename]#/usr/ports/www/py-django#, then install the port. Once Django is installed, the application will need a project directory along with the Apache configuration in order to use the embedded Python interpreter. This interpreter is used to call the application for specific URLs on the site. To configure Apache to pass requests for certain URLs to the web application, add the following to [.filename]#httpd.conf#, specifying the full path to the project directory: [.programlisting] .... SetHandler python-program PythonPath "['/dir/to/the/django/packages/'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonAutoReload On PythonDebug On .... Refer to https://docs.djangoproject.com[https://docs.djangoproject.com] for more information on how to use Django. ==== Ruby on Rails Ruby on Rails is another open source web framework that provides a full development stack. It is optimized to make web developers more productive and capable of writing powerful applications quickly. On FreeBSD, it can be installed using the package:www/rubygem-rails[] package or port. Refer to http://guides.rubyonrails.org[http://guides.rubyonrails.org] for more information on how to use Ruby on Rails. [[network-ftp]] == File Transfer Protocol (FTP) The File Transfer Protocol (FTP) provides users with a simple way to transfer files to and from an FTP server. FreeBSD includes FTP server software, ftpd, in the base system. FreeBSD provides several configuration files for controlling access to the FTP server. This section summarizes these files. Refer to man:ftpd[8] for more details about the built-in FTP server. === Configuration The most important configuration step is deciding which accounts will be allowed access to the FTP server. A FreeBSD system has a number of system accounts which should not be allowed FTP access. The list of users disallowed any FTP access can be found in [.filename]#/etc/ftpusers#. By default, it includes system accounts. Additional users that should not be allowed access to FTP can be added. In some cases it may be desirable to restrict the access of some users without preventing them completely from using FTP. This can be accomplished be creating [.filename]#/etc/ftpchroot# as described in man:ftpchroot[5]. This file lists users and groups subject to FTP access restrictions. To enable anonymous FTP access to the server, create a user named `ftp` on the FreeBSD system. Users will then be able to log on to the FTP server with a username of `ftp` or `anonymous`. When prompted for the password, any input will be accepted, but by convention, an email address should be used as the password. The FTP server will call man:chroot[2] when an anonymous user logs in, to restrict access to only the home directory of the `ftp` user. There are two text files that can be created to specify welcome messages to be displayed to FTP clients. The contents of [.filename]#/etc/ftpwelcome# will be displayed to users before they reach the login prompt. After a successful login, the contents of [.filename]#/etc/ftpmotd# will be displayed. Note that the path to this file is relative to the login environment, so the contents of [.filename]#~ftp/etc/ftpmotd# would be displayed for anonymous users. Once the FTP server has been configured, set the appropriate variable in [.filename]#/etc/rc.conf# to start the service during boot: [.programlisting] .... ftpd_enable="YES" .... To start the service now: [source,shell] .... # service ftpd start .... Test the connection to the FTP server by typing: [source,shell] .... % ftp localhost .... The ftpd daemon uses man:syslog[3] to log messages. By default, the system log daemon will write messages related to FTP in [.filename]#/var/log/xferlog#. The location of the FTP log can be modified by changing the following line in [.filename]#/etc/syslog.conf#: [.programlisting] .... ftp.info /var/log/xferlog .... [NOTE] ==== Be aware of the potential problems involved with running an anonymous FTP server. In particular, think twice about allowing anonymous users to upload files. It may turn out that the FTP site becomes a forum for the trade of unlicensed commercial software or worse. If anonymous FTP uploads are required, then verify the permissions so that these files cannot be read by other anonymous users until they have been reviewed by an administrator. ==== [[network-samba]] == File and Print Services for Microsoft(R) Windows(R) Clients (Samba) Samba is a popular open source software package that provides file and print services using the SMB/CIFS protocol. This protocol is built into Microsoft(R) Windows(R) systems. It can be added to non-Microsoft(R) Windows(R) systems by installing the Samba client libraries. The protocol allows clients to access shared data and printers. These shares can be mapped as a local disk drive and shared printers can be used as if they were local printers. On FreeBSD, the Samba client libraries can be installed using the package:net/samba410[] port or package. The client provides the ability for a FreeBSD system to access SMB/CIFS shares in a Microsoft(R) Windows(R) network. A FreeBSD system can also be configured to act as a Samba server by installing the same package:net/samba410[] port or package. This allows the administrator to create SMB/CIFS shares on the FreeBSD system which can be accessed by clients running Microsoft(R) Windows(R) or the Samba client libraries. === Server Configuration Samba is configured in [.filename]#/usr/local/etc/smb4.conf#. This file must be created before Samba can be used. A simple [.filename]#smb4.conf# to share directories and printers with Windows(R) clients in a workgroup is shown here. For more complex setups involving LDAP or Active Directory, it is easier to use man:samba-tool[8] to create the initial [.filename]#smb4.conf#. [.programlisting] .... [global] workgroup = WORKGROUP server string = Samba Server Version %v netbios name = ExampleMachine wins support = Yes security = user passdb backend = tdbsam # Example: share /usr/src accessible only to 'developer' user [src] path = /usr/src valid users = developer writable = yes browsable = yes read only = no guest ok = no public = no create mask = 0666 directory mask = 0755 .... ==== Global Settings Settings that describe the network are added in [.filename]#/usr/local/etc/smb4.conf#: `workgroup`:: The name of the workgroup to be served. `netbios name`:: The NetBIOS name by which a Samba server is known. By default, it is the same as the first component of the host's DNS name. `server string`:: The string that will be displayed in the output of `net view` and some other networking tools that seek to display descriptive text about the server. `wins support`:: Whether Samba will act as a WINS server. Do not enable support for WINS on more than one server on the network. ==== Security Settings The most important settings in [.filename]#/usr/local/etc/smb4.conf# are the security model and the backend password format. These directives control the options: `security`:: The most common settings are `security = share` and `security = user`. If the clients use usernames that are the same as their usernames on the FreeBSD machine, user level security should be used. This is the default security policy and it requires clients to first log on before they can access shared resources. + In share level security, clients do not need to log onto the server with a valid username and password before attempting to connect to a shared resource. This was the default security model for older versions of Samba. `passdb backend`:: Samba has several different backend authentication models. Clients may be authenticated with LDAP, NIS+, an SQL database, or a modified password file. The recommended authentication method, `tdbsam`, is ideal for simple networks and is covered here. For larger or more complex networks, `ldapsam` is recommended. `smbpasswd` was the former default and is now obsolete. ==== Samba Users FreeBSD user accounts must be mapped to the `SambaSAMAccount` database for Windows(R) clients to access the share. Map existing FreeBSD user accounts using man:pdbedit[8]: [source,shell] .... # pdbedit -a username .... This section has only mentioned the most commonly used settings. Refer to the https://wiki.samba.org[Official Samba Wiki] for additional information about the available configuration options. === Starting Samba To enable Samba at boot time, add the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... samba_server_enable="YES" .... To start Samba now: [source,shell] .... # service samba_server start Performing sanity check on Samba configuration: OK Starting nmbd. Starting smbd. .... Samba consists of three separate daemons. Both the nmbd and smbd daemons are started by `samba_enable`. If winbind name resolution is also required, set: [.programlisting] .... winbindd_enable="YES" .... Samba can be stopped at any time by typing: [source,shell] .... # service samba_server stop .... Samba is a complex software suite with functionality that allows broad integration with Microsoft(R) Windows(R) networks. For more information about functionality beyond the basic configuration described here, refer to https://www.samba.org[https://www.samba.org]. [[network-ntp]] == Clock Synchronization with NTP Over time, a computer's clock is prone to drift. This is problematic as many network services require the computers on a network to share the same accurate time. Accurate time is also needed to ensure that file timestamps stay consistent. The Network Time Protocol (NTP) is one way to provide clock accuracy in a network. FreeBSD includes man:ntpd[8] which can be configured to query other NTP servers to synchronize the clock on that machine or to provide time services to other computers in the network. This section describes how to configure ntpd on FreeBSD. Further documentation can be found in [.filename]#/usr/shared/doc/ntp/# in HTML format. === NTP Configuration On FreeBSD, the built-in ntpd can be used to synchronize a system's clock. Ntpd is configured using man:rc.conf[5] variables and [.filename]#/etc/ntp.conf#, as detailed in the following sections. Ntpd communicates with its network peers using UDP packets. Any firewalls between your machine and its NTP peers must be configured to allow UDP packets in and out on port 123. ==== The [.filename]#/etc/ntp.conf# file Ntpd reads [.filename]#/etc/ntp.conf# to determine which NTP servers to query. Choosing several NTP servers is recommended in case one of the servers becomes unreachable or its clock proves unreliable. As ntpd receives responses, it favors reliable servers over the less reliable ones. The servers which are queried can be local to the network, provided by an ISP, or selected from an http://support.ntp.org/bin/view/Servers/WebHome[online list of publicly accessible NTP servers]. When choosing a public NTP server, select one that is geographically close and review its usage policy. The `pool` configuration keyword selects one or more servers from a pool of servers. An http://support.ntp.org/bin/view/Servers/NTPPoolServers[online list of publicly accessible NTP pools] is available, organized by geographic area. In addition, FreeBSD provides a project-sponsored pool, `0.freebsd.pool.ntp.org`. .Sample [.filename]#/etc/ntp.conf# [example] ==== This is a simple example of an [.filename]#ntp.conf# file. It can safely be used as-is; it contains the recommended `restrict` options for operation on a publicly-accessible network connection. [.programlisting] .... # Disallow ntpq control/query access. Allow peers to be added only # based on pool and server statements in this file. restrict default limited kod nomodify notrap noquery nopeer restrict source limited kod nomodify notrap noquery # Allow unrestricted access from localhost for queries and control. restrict 127.0.0.1 restrict ::1 # Add a specific server. server ntplocal.example.com iburst # Add FreeBSD pool servers until 3-6 good servers are available. tos minclock 3 maxclock 6 pool 0.freebsd.pool.ntp.org iburst # Use a local leap-seconds file. leapfile "/var/db/ntpd.leap-seconds.list" .... ==== The format of this file is described in man:ntp.conf[5]. The descriptions below provide a quick overview of just the keywords used in the sample file above. By default, an NTP server is accessible to any network host. The `restrict` keyword controls which systems can access the server. Multiple `restrict` entries are supported, each one refining the restrictions given in previous statements. The values shown in the example grant the local system full query and control access, while allowing remote systems only the ability to query the time. For more details, refer to the `Access Control Support` subsection of man:ntp.conf[5]. The `server` keyword specifies a single server to query. The file can contain multiple server keywords, with one server listed on each line. The `pool` keyword specifies a pool of servers. Ntpd will add one or more servers from this pool as needed to reach the number of peers specified using the `tos minclock` value. The `iburst` keyword directs ntpd to perform a burst of eight quick packet exchanges with a server when contact is first established, to help quickly synchronize system time. The `leapfile` keyword specifies the location of a file containing information about leap seconds. The file is updated automatically by man:periodic[8]. The file location specified by this keyword must match the location set in the `ntp_db_leapfile` variable in [.filename]#/etc/rc.conf#. ==== NTP entries in [.filename]#/etc/rc.conf# Set `ntpd_enable=YES` to start ntpd at boot time. Once `ntpd_enable=YES` has been added to [.filename]#/etc/rc.conf#, ntpd can be started immediately without rebooting the system by typing: [source,shell] .... # service ntpd start .... Only `ntpd_enable` must be set to use ntpd. The [.filename]#rc.conf# variables listed below may also be set as needed. Set `ntpd_sync_on_start=YES` to allow ntpd to step the clock any amount, one time at startup. Normally ntpd will log an error message and exit if the clock is off by more than 1000 seconds. This option is especially useful on systems without a battery-backed realtime clock. Set `ntpd_oomprotect=YES` to protect the ntpd daemon from being killed by the system attempting to recover from an Out Of Memory (OOM) condition. Set `ntpd_config=` to the location of an alternate [.filename]#ntp.conf# file. Set `ntpd_flags=` to contain any other ntpd flags as needed, but avoid using these flags which are managed internally by [.filename]#/etc/rc.d/ntpd#: * `-p` (pid file location) * `-c` (set `ntpd_config=` instead) ==== Ntpd and the unpriveleged `ntpd` user Ntpd on FreeBSD can start and run as an unpriveleged user. Doing so requires the man:mac_none[4] policy module. The [.filename]#/etc/rc.d/ntpd# startup script first examines the NTP configuration. If possible, it loads the `mac_ntpd` module, then starts ntpd as unpriveleged user `ntpd` (user id 123). To avoid problems with file and directory access, the startup script will not automatically start ntpd as `ntpd` when the configuration contains any file-related options. The presence of any of the following in `ntpd_flags` requires manual configuration as described below to run as the `ntpd` user: * -f or --driftfile * -i or --jaildir * -k or --keyfile * -l or --logfile * -s or --statsdir The presence of any of the following keywords in [.filename]#ntp.conf# requires manual configuration as described below to run as the `ntpd` user: * crypto * driftfile * key * logdir * statsdir To manually configure ntpd to run as user `ntpd` you must: * Ensure that the `ntpd` user has access to all the files and directories specified in the configuration. * Arrange for the `mac_ntpd` module to be loaded or compiled into the kernel. See man:mac_none[4] for details. * Set `ntpd_user="ntpd"` in [.filename]#/etc/rc.conf# === Using NTP with a PPP Connection ntpd does not need a permanent connection to the Internet to function properly. However, if a PPP connection is configured to dial out on demand, NTP traffic should be prevented from triggering a dial out or keeping the connection alive. This can be configured with `filter` directives in [.filename]#/etc/ppp/ppp.conf#. For example: [.programlisting] .... set filter dial 0 deny udp src eq 123 # Prevent NTP traffic from initiating dial out set filter dial 1 permit 0 0 set filter alive 0 deny udp src eq 123 # Prevent incoming NTP traffic from keeping the connection open set filter alive 1 deny udp dst eq 123 # Prevent outgoing NTP traffic from keeping the connection open set filter alive 2 permit 0/0 0/0 .... For more details, refer to the `PACKET FILTERING` section in man:ppp[8] and the examples in [.filename]#/usr/shared/examples/ppp/#. [NOTE] ==== Some Internet access providers block low-numbered ports, preventing NTP from functioning since replies never reach the machine. ==== [[network-iscsi]] == iSCSI Initiator and Target Configuration iSCSI is a way to share storage over a network. Unlike NFS, which works at the file system level, iSCSI works at the block device level. In iSCSI terminology, the system that shares the storage is known as the _target_. The storage can be a physical disk, or an area representing multiple disks or a portion of a physical disk. For example, if the disk(s) are formatted with ZFS, a zvol can be created to use as the iSCSI storage. The clients which access the iSCSI storage are called _initiators_. To initiators, the storage available through iSCSI appears as a raw, unformatted disk known as a LUN. Device nodes for the disk appear in [.filename]#/dev/# and the device must be separately formatted and mounted. FreeBSD provides a native, kernel-based iSCSI target and initiator. This section describes how to configure a FreeBSD system as a target or an initiator. [[network-iscsi-target]] === Configuring an iSCSI Target To configure an iSCSI target, create the [.filename]#/etc/ctl.conf# configuration file, add a line to [.filename]#/etc/rc.conf# to make sure the man:ctld[8] daemon is automatically started at boot, and then start the daemon. The following is an example of a simple [.filename]#/etc/ctl.conf# configuration file. Refer to man:ctl.conf[5] for a more complete description of this file's available options. [.programlisting] .... portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group no-authentication portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... The first entry defines the `pg0` portal group. Portal groups define which network addresses the man:ctld[8] daemon will listen on. The `discovery-auth-group no-authentication` entry indicates that any initiator is allowed to perform iSCSI target discovery without authentication. Lines three and four configure man:ctld[8] to listen on all IPv4 (`listen 0.0.0.0`) and IPv6 (`listen [::]`) addresses on the default port of 3260. It is not necessary to define a portal group as there is a built-in portal group called `default`. In this case, the difference between `default` and `pg0` is that with `default`, target discovery is always denied, while with `pg0`, it is always allowed. The second entry defines a single target. Target has two possible meanings: a machine serving iSCSI or a named group of LUNs. This example uses the latter meaning, where `iqn.2012-06.com.example:target0` is the target name. This target name is suitable for testing purposes. For actual use, change `com.example` to the real domain name, reversed. The `2012-06` represents the year and month of acquiring control of that domain name, and `target0` can be any value. Any number of targets can be defined in this configuration file. The `auth-group no-authentication` line allows all initiators to connect to the specified target and `portal-group pg0` makes the target reachable through the `pg0` portal group. The next section defines the LUN. To the initiator, each LUN will be visible as a separate disk device. Multiple LUNs can be defined for each target. Each LUN is identified by a number, where LUN 0 is mandatory. The `path /data/target0-0` line defines the full path to a file or zvol backing the LUN. That path must exist before starting man:ctld[8]. The second line is optional and specifies the size of the LUN. Next, to make sure the man:ctld[8] daemon is started at boot, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... ctld_enable="YES" .... To start man:ctld[8] now, run this command: [source,shell] .... # service ctld start .... As the man:ctld[8] daemon is started, it reads [.filename]#/etc/ctl.conf#. If this file is edited after the daemon starts, use this command so that the changes take effect immediately: [source,shell] .... # service ctld reload .... ==== Authentication The previous example is inherently insecure as it uses no authentication, granting anyone full access to all targets. To require a username and password to access targets, modify the configuration as follows: [.programlisting] .... auth-group ag0 { chap username1 secretsecret chap username2 anothersecret } portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group ag0 portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... The `auth-group` section defines username and password pairs. An initiator trying to connect to `iqn.2012-06.com.example:target0` must first specify a defined username and secret. However, target discovery is still permitted without authentication. To require target discovery authentication, set `discovery-auth-group` to a defined `auth-group` name instead of `no-authentication`. It is common to define a single exported target for every initiator. As a shorthand for the syntax above, the username and password can be specified directly in the target entry: [.programlisting] .... target iqn.2012-06.com.example:target0 { portal-group pg0 chap username1 secretsecret lun 0 { path /data/target0-0 size 4G } } .... [[network-iscsi-initiator]] === Configuring an iSCSI Initiator [NOTE] ==== The iSCSI initiator described in this section is supported starting with FreeBSD 10.0-RELEASE. To use the iSCSI initiator available in older versions, refer to man:iscontrol[8]. ==== The iSCSI initiator requires that the man:iscsid[8] daemon is running. This daemon does not use a configuration file. To start it automatically at boot, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... iscsid_enable="YES" .... To start man:iscsid[8] now, run this command: [source,shell] .... # service iscsid start .... Connecting to a target can be done with or without an [.filename]#/etc/iscsi.conf# configuration file. This section demonstrates both types of connections. ==== Connecting to a Target Without a Configuration File To connect an initiator to a single target, specify the IP address of the portal and the name of the target: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 .... To verify if the connection succeeded, run `iscsictl` without any arguments. The output should look similar to this: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Connected: da0 .... In this example, the iSCSI session was successfully established, with [.filename]#/dev/da0# representing the attached LUN. If the `iqn.2012-06.com.example:target0` target exports more than one LUN, multiple device nodes will be shown in that section of the output: [source,shell] .... Connected: da0 da1 da2. .... Any errors will be reported in the output, as well as the system logs. For example, this message usually means that the man:iscsid[8] daemon is not running: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Waiting for iscsid(8) .... The following message suggests a networking problem, such as a wrong IP address or port: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.11 Connection refused .... This message means that the specified target name is wrong: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Not found .... This message means that the target requires authentication: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Authentication failed .... To specify a CHAP username and secret, use this syntax: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 -u user -s secretsecret .... ==== Connecting to a Target with a Configuration File To connect using a configuration file, create [.filename]#/etc/iscsi.conf# with contents like this: [.programlisting] .... t0 { TargetAddress = 10.10.10.10 TargetName = iqn.2012-06.com.example:target0 AuthMethod = CHAP chapIName = user chapSecret = secretsecret } .... The `t0` specifies a nickname for the configuration file section. It will be used by the initiator to specify which configuration to use. The other lines specify the parameters to use during connection. The `TargetAddress` and `TargetName` are mandatory, whereas the other options are optional. In this example, the CHAP username and secret are shown. To connect to the defined target, specify the nickname: [source,shell] .... # iscsictl -An t0 .... Alternately, to connect to all targets defined in the configuration file, use: [source,shell] .... # iscsictl -Aa .... To make the initiator automatically connect to all targets in [.filename]#/etc/iscsi.conf#, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... iscsictl_enable="YES" iscsictl_flags="-Aa" .... diff --git a/documentation/content/pt-br/books/handbook/advanced-networking/_index.adoc b/documentation/content/pt-br/books/handbook/advanced-networking/_index.adoc index 7cd34020e8..d2d10b5c06 100644 --- a/documentation/content/pt-br/books/handbook/advanced-networking/_index.adoc +++ b/documentation/content/pt-br/books/handbook/advanced-networking/_index.adoc @@ -1,2840 +1,2840 @@ --- title: Capítulo 31. Rede Avançada part: Parte IV. Comunicação de rede prev: books/handbook/firewalls next: books/handbook/partv showBookMenu: true weight: 36 path: "/books/handbook/" --- [[advanced-networking]] = Rede Avançada :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 31 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/advanced-networking/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[advanced-networking-synopsis]] == Sinopse Este capítulo aborda vários tópicos avançados de rede. Depois de ler este capítulo, você saberá: * O básico de gateways e rotas. * Como configurar o USB tethering. * Como configurar os dispositivos IEEE(TM) 802.11 e Bluetooth(TM). * Como fazer o FreeBSD atuar como uma Bridge. * Como configurar a inicialização via PXE na rede. * Como configurar o IPv6 em uma máquina FreeBSD. * Como habilitar e utilizar os recursos do Protocolo CARP (Common Address Redundancy Protocol) no FreeBSD. * Como configurar múltiplas VLANs no FreeBSD. * Como configurar um fone de ouvido bluetooth. Antes de ler este capítulo, você deve: * Entender os fundamentos dos scripts [.filename]#/etc/rc#. * Estar familiarizado com a terminologia básica de rede. * Saber como configurar e instalar um novo kernel do FreeBSD (crossref:kernelconfig[kernelconfig, Configurando o kernel do FreeBSD]). * Saber como instalar software adicional de terceiros (crossref:ports[ports, Instalando Aplicativos. Pacotes e Ports]). [[network-routing]] == Gateways e Rotas O _roteamento_ é o mecanismo que permite que um sistema encontre o caminho da rede para outro sistema. Uma _rota_ é um par definido de endereços que representam o "destino" e um "gateway". A rota indica que, ao tentar chegar ao destino especificado, você deverá enviar os pacotes pelo gateway especificado. Existem três tipos de destinos: hosts individuais, sub-redes e "padrão". A "rota padrão" é usada se nenhuma outra rota for aplicada. Existem também três tipos de gateways: hosts individuais, interfaces, também chamados de links, e endereços de hardware Ethernet (MAC). Rotas conhecidas são armazenadas em uma tabela de roteamento. Esta seção fornece uma visão geral dos fundamentos de roteamento. Em seguida, ele demonstra como configurar um sistema FreeBSD como um roteador e oferece algumas dicas de solução de problemas. [[network-routing-default]] === Fundamentos de roteamento Para ver a tabela de roteamento de um sistema FreeBSD, use man:netstat[1]: [source,shell] .... % netstat -r Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default outside-gw UGS 37 418 em0 localhost localhost UH 0 181 lo0 test0 0:e0:b5:36:cf:4f UHLW 5 63288 re0 77 10.20.30.255 link#1 UHLW 1 2421 example.com link#1 UC 0 0 host1 0:e0:a8:37:8:1e UHLW 3 4601 lo0 host2 0:e0:a8:37:8:1e UHLW 0 5 lo0 => host2.example.com link#1 UC 0 0 224 link#1 UC 0 0 .... As entradas neste exemplo são as seguintes: padrão:: A primeira rota nesta tabela especifica a rota `padrão`. Quando o sistema local precisa estabelecer uma conexão com um host remoto, ele verifica a tabela de roteamento para determinar se existe um caminho conhecido. Se o host remoto corresponder a uma entrada na tabela, o sistema verificará se pode se conectar usando a interface especificada nessa entrada. + Se o destino não corresponder a uma entrada ou se todos os caminhos conhecidos falharem, o sistema usará a entrada para a rota padrão. Para hosts em uma rede local, o campo `Gateway` na rota padrão é definido para o sistema que possui uma conexão direta com a internet. Ao ler esta entrada, verifique se a coluna `Flags` indica que o gateway é utilizável (`UG`). + A rota padrão para uma máquina que está funcionando como gateway para o mundo externo será a máquina de gateway no provedor de serviços de Internet (ISP). localhost:: A segunda rota é a `localhost`. A interface especificada na coluna `Netif` para `localhost` é [.filename]#lo0#, também conhecido como o dispositivo de loopback. Isso indica que todo o tráfego para esse destino deve ser interno, em vez de enviá-lo pela rede. Endereço MAC:: Os endereços que começam com `0:e0:` são endereços de MAC. O FreeBSD irá identificar automaticamente quaisquer hosts, `test0` no exemplo, na Ethernet local e adicionará uma rota para aquele host através da interface Ethernet, [.filename]#re0#. Esse tipo de rota tem um tempo limite, visto na coluna `Expire`, que é usada se o host não responder em um período de tempo específico. Quando isso acontecer, a rota para esse host será automaticamente excluída. Esses hosts são identificados usando o protocolo de informações de roteamento (RIP), que calcula rotas para hosts locais com base em uma determinação de caminho mais curto. sub-rede:: O FreeBSD irá adicionar automaticamente rotas de sub-rede para a sub-rede local. Neste exemplo, `10.20.30.255` é o endereço de broadcast da sub-rede `10.20.30` e `example.com` é o nome de domínio associado a essa sub-rede. A designação `link#1` refere-se à primeira placa Ethernet na máquina. + Hosts de rede local e sub-redes locais têm suas rotas configuradas automaticamente por um daemon chamado man:routed[8]. Se ele não estiver em execução, somente as rotas definidas estaticamente pelo administrador existirão. host:: A linha `host1` refere-se ao host pelo seu endereço Ethernet. Como é o host de envio, o FreeBSD sabe usar a interface de loopback ([.filename]#lo0#) em vez da interface Ethernet. + As duas linhas `host2` representam os aliases que foram criados usando man:ifconfig[8]. O símbolo `=>` após a interface [.filename]#lo0# diz que um alias foi definido além do endereço de loopback. Tais rotas só aparecem no host que suporta o alias e todos os outros hosts na rede local terão uma linha `link#1` para tais rotas. 224:: A linha final (destino subnet `224`) lida com multicasting. Vários atributos de cada rota podem ser vistos na coluna `Flags`. A <> resume algumas destas flags e seus significados: [[routeflags]] .Flags da Tabela de Roteamento Frequentemente Observados [cols="1,1", frame="none", options="header"] |=== | Comando | Propósito |U |A rota está ativa (up). |H |O destino da rota é um único host. |G |Envie qualquer coisa para este destino por este gateway, que ele irá descobrir a partir daí para onde enviá-lo. |S |Esta rota foi configurada estaticamente. |C |Clona uma nova rota baseada nessa rota para as máquinas se conectarem. Esse tipo de rota é normalmente usado para redes locais. |W |A rota foi configurada automaticamente com base em uma rota de rede local (clone). |L |A rota envolve referências a um hardware Ethernet (link). |=== Em um sistema FreeBSD, a rota padrão pode ser definida no [.filename]#/etc/rc.conf# especificando o endereço IP do gateway padrão: [.programlisting] .... defaultrouter="10.20.30.1" .... Também é possível adicionar manualmente a rota usando o comando `route`: [source,shell] .... # route add default 10.20.30.1 .... Observe que as rotas adicionadas manualmente não sobreviverão a uma reinicialização. Para obter mais informações sobre a manipulação manual das tabelas de roteamento de rede, consulte man:route[8]. [[network-static-routes]] === Configurando um roteador com rotas estáticas Um sistema FreeBSD pode ser configurado como o gateway padrão, ou roteador, para uma rede se for um sistema dual-homed. Um sistema dual-homed é um host que reside em pelo menos duas redes diferentes. Normalmente, cada rede é conectada a uma interface de rede separada, embora o aliasing IP possa ser usado para vincular vários endereços, cada um em uma sub-rede diferente, a uma interface física. Para que o sistema encaminhe os pacotes entre as interfaces, o FreeBSD deve ser configurado como um roteador. Padrões da Internet e boas práticas de engenharia impedem o Projeto FreeBSD de habilitar esse recurso por padrão, mas ele pode ser configurado para iniciar na inicialização adicionando esta linha ao [.filename]#/etc/rc.conf#: [.programlisting] .... gateway_enable="YES" # Set to YES if this host will be a gateway .... Para habilitar o roteamento agora, defina a variável man:sysctl[8]`net.inet.ip.forwarding` para `1`. Para parar o roteamento, redefina essa variável para `0`. A tabela de roteamento de um roteador precisa de rotas adicionais para saber como acessar outras redes. Rotas podem ser adicionadas manualmente usando rotas estáticas ou rotas podem ser aprendidas automaticamente usando um protocolo de roteamento. As rotas estáticas são apropriadas para redes pequenas e esta seção descreve como adicionar uma entrada de roteamento estático para uma rede pequena. [NOTE] ==== Para grandes redes, as rotas estáticas se tornam não escaláveis rapidamente. O FreeBSD vem com o daemon de roteamento BSD padrão man:routed[8], que fornece os protocolos de roteamento RIP, versões 1 e 2 e IRDP. O suporte para os protocolos de roteamento BGP e OSPF pode ser instalado usando o pacote ou port package:net/zebra[]. ==== Considere a seguinte rede: image::static-routes.png[] Neste cenário, o `RouterA` é uma máquina FreeBSD que está agindo como um roteador para o resto da Internet. Ele tem uma rota padrão definida como `10.0.0.1`, que permite a conexão com o mundo externo. O `RouterB` já está configurado para usar `192.168.1.1` como seu gateway padrão. Antes de adicionar rotas estáticas, a tabela de roteamento no `RouterA` se parece com: [source,shell] .... % netstat -nr Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default 10.0.0.1 UGS 0 49378 xl0 127.0.0.1 127.0.0.1 UH 0 6 lo0 10.0.0.0/24 link#1 UC 0 0 xl0 192.168.1.0/24 link#2 UC 0 0 xl1 .... Com a tabela de roteamento atual, o `RouterA` não tem uma rota para a rede `192.168.2.0/24`. O comando a seguir adiciona a rede `Internal Net 2` à tabela de roteamento do `RouterA` usando `192.168.1.2` como o próximo salto: [source,shell] .... # route add -net 192.168.2.0/24 192.168.1.2 .... Agora, o `RouterA` pode alcançar qualquer host na rede `192.168.2.0/24`. No entanto, as informações de roteamento não persistirão se o sistema FreeBSD for reinicializado. Se uma rota estática precisar ser persistente, adicione-a ao [.filename]#/etc/rc.conf#: [.programlisting] .... # Add Internal Net 2 as a persistent static route static_routes="internalnet2" route_internalnet2="-net 192.168.2.0/24 192.168.1.2" .... A variável de configuração `static_routes` é uma lista de strings separadas por um espaço, onde cada string faz referência a um nome de rota. A variável `route_internalnet2` contém a rota estática para esse nome de rota. Usar mais de uma string em `static_routes` cria várias rotas estáticas. A seguir, é mostrado um exemplo de adição de rotas estáticas para as redes `192.168.0.0/24` e `192.168.1.0/24`: [.programlisting] .... static_routes="net1 net2" route_net1="-net 192.168.0.0/24 192.168.0.1" route_net2="-net 192.168.1.0/24 192.168.1.1" .... [[network-routing-troubleshooting]] === Solução de problemas Quando um espaço de endereçamento é atribuído a uma rede, o provedor de serviços configura suas tabelas de roteamento para que todo o tráfego da rede seja enviado para o link do site. Mas como os sites externos sabem enviar seus pacotes para a rede do ISP? Existe um sistema que rastreia todos os espaços de endereçamento e define seu ponto de conexão com o backbone da Internet, ou as principais linhas que transportam o tráfego da Internet pelo país e pelo mundo. Cada máquina de backbone possui uma cópia de um conjunto mestre de tabelas, que direciona o tráfego de uma rede específica para uma portadora de backbone específica e, a partir daí, desce a cadeia de provedores de serviços até alcançar uma determinada rede. É tarefa do provedor de serviços anunciar aos sites de backbone que eles são o ponto de conexão e, assim, o caminho para dentro de um site. Isso é conhecido como propagação de rota. Às vezes, há um problema com a propagação de rotas e alguns sites não conseguem se conectar. Talvez o comando mais útil para tentar descobrir onde o roteamento está quebrando seja o `traceroute`. Ele é útil quando o `ping` falha. Ao usar o `traceroute`, inclua o endereço do host remoto para se conectar. A saída mostrará os gateway ao longo do caminho da tentativa, eventualmente atingindo o host de destino ou encerrando devido à falta de conexão. Para mais informações, consulte man:traceroute[8]. [[network-routing-multicast]] === Considerações sobre Multicast O FreeBSD suporta nativamente tanto aplicativos multicast e quanto roteamento multicast. Os aplicativos multicast não exigem nenhuma configuração especial para serem executados no FreeBSD. O suporte ao roteamento multicast requer que a seguinte opção seja compilada em um kernel personalizado: [.programlisting] .... options MROUTING .... O daemon de roteamento multicast, mrouted, pode ser instalado usando o pacote ou port package:net/mrouted[]. Este daemon implementa o protocolo de roteamento multicast DVMRP e é configurado editando o [.filename]#/usr/local/etc/mrouted.conf# para configurar os túneis e o DVMRP. A instalação do mrouted também instala o map-mbone e o mrinfo, bem como suas páginas de manual associadas. Consulte estes documentos para exemplos de configuração. [NOTE] ==== O DVMRP foi amplamente substituído pelo protocolo PIM em muitas instalações multicast. Consulte man:pim[4] para obter maiores informações. ==== [[network-wireless]] == Rede sem fio === Noções básicas sobre redes sem fio A maioria das redes sem fio é baseada nos padrões IEEE(TM)802.11. Uma rede sem fio básica consiste em várias estações que se comunicam com rádios que transmitem na banda de 2,4 GHz ou 5 GHz, embora isso varie de acordo com a localidade e também esteja mudando para permitir a comunicação nas faixas de 2,3 GHz e 4,9 GHz. As redes 802.11 são organizadas de duas maneiras. No _modo de infra-estrutura_, uma estação atua como mestre para todas as outras estações que se associam a ela, a rede é conhecida como BSS e a estação mestre é denominada ponto de acesso. (AP). Em um BSS, toda a comunicação passa pelo AP; mesmo quando uma estação deseja se comunicar com outra estação sem fio, as mensagens devem passar pelo AP. Na segunda forma de rede, não há mestre e as estações se comunicam diretamente. Esta forma de rede é denominada IBSS e é comumente conhecida como uma _rede ad-hoc_. As redes 802.11 foram implantadas pela primeira vez na banda de 2,4 GHz usando protocolos definidos pelo padrão 802.11 e 802.11b da IEEE(TM). Essas especificações incluem as frequências operacionais e as características da camada MAC, incluindo as taxas de enquadramento e transmissão, pois a comunicação pode ocorrer em várias taxas. Posteriormente, o padrão 802.11a definiu a operação na faixa de 5GHz, incluindo diferentes mecanismos de sinalização e taxas de transmissão mais altas. Mais tarde, o padrão 802.11g definiu o uso de mecanismos de sinalização e transmissão 802.11a na banda de 2,4 GHz de modo a ser compatível com redes 802.11b. Separadas das técnicas de transmissão básicas, as redes 802.11 possuem uma variedade de mecanismos de segurança. As especificações originais do 802.11 definiam um protocolo de segurança simples chamado WEP. Este protocolo usa uma chave pré-compartilhada fixa e a criptografia criptográfica RC4 para codificar dados transmitidos em uma rede. Todas as estações devem concordar com a chave fixa para se comunicar. Esse esquema mostrou-se de fácil quebra e agora raramente é usado, exceto para desencorajar usuários transitórios a se juntarem a uma rede. A prática atual de segurança é dada pela especificação 802.11i do IEEE(TM) que define novas cifras criptográficas e um protocolo adicional para autenticar estações para um ponto de acesso e para trocar chaves para comunicação de dados. As chaves criptográficas são atualizadas periodicamente e existem mecanismos para detectar e combater tentativas de invasão. Outra especificação de protocolo de segurança comumente usada em redes sem fio é denominada WPA, que foi um precursor do 802.11i. O WPA especifica um subconjunto dos requisitos encontrados no 802.11i e foi projetado para implementação em hardware legado. Especificamente, o WPA requer apenas a codificação TKIP derivada da codificação original WEP. O 802.11i permite o uso do TKIP, mas também requer suporte para uma criptografia mais forte, o AES-CCM, para criptografar os dados. A codificação AES não era exigida no WPA porque foi considerada demasiadamente cara computacionalmente para ser executada em hardware legado. Um outro padrão a se ter em conta é o 802.11e. Ele define protocolos para a implantação de aplicativos multimídia, como streaming de vídeo e voz sobre IP (VoIP), em uma rede 802.11. Como o 802.11i, o 802.11e também tem uma especificação de precursor denominada WME (posteriormente renomeada como WMM) que foi definida por um grupo industrial como um subconjunto do 802.11e que pode ser implantado agora para habilitar aplicativos multimídia enquanto aguarda a ratificação final do 802.11e. O mais importante a saber sobre o 802.11e e o WME/WMM é que ele permite o tráfego prioritário através de uma rede sem fio através de protocolos de Qualidade de Serviço (QoS) e protocolos de acesso de mídia aprimorados. A implementação adequada desses protocolos permite o aumento rápido de dados e o fluxo de tráfego priorizado. O FreeBSD suporta redes que operam usando 802.11a, 802.11b e 802.11g. Os protocolos de segurança WPA e 802.11i também são suportados (em conjunto com qualquer um dos 11a, 11b e 11g) e o QoS e priorização de tráfego exigidos pelo protocolo WME/WMM são suportados por um conjunto limitado de dispositivos sem fio. [[network-wireless-quick-start]] === Inicio Rápido Conectar um computador a uma rede sem fio existente é uma situação muito comum. Este procedimento mostra as etapas necessárias. [.procedure] ==== . Obtenha o SSID (identificador de conjunto de serviços) e PSK (chave pré-compartilhada) para a rede sem fio do administrador da rede. . Identifique o adaptador sem fio. O kernel [.filename]#GENERIC# do FreeBSD inclui drivers para muitos adaptadores sem fio comuns. Se o adaptador sem fio for um desses modelos, ele será mostrado na saída do man:ifconfig[8]: + [source,shell] .... % ifconfig | grep -B3 -i wireless .... + No FreeBSD 11 ou superior, use este comando: + [source,shell] .... % sysctl net.wlan.devices .... + Se um adaptador sem fio não estiver listado, um módulo adicional do kernel pode ser necessário, ou pode ser um modelo não suportado pelo FreeBSD. + Este exemplo mostra o adaptador wireless Atheros `ath0`. . Adicione uma entrada para esta rede ao [.filename]#/etc/wpa_supplicant.conf#. Se o arquivo não existir, crie-o. Substitua _myssid_ e _mypsk_ pelo SSID e PSK fornecidos pelo administrador da rede. + [.programlisting] .... network={ ssid="myssid" psk="mypsk" } .... + . Adicione entradas ao [.filename]#/etc/rc.conf# para configurar a rede na inicialização: + [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA SYNCDHCP" .... + . Reinicie o computador ou reinicie o serviço de rede para conectar-se à rede: + [source,shell] .... # service netif restart .... ==== [[network-wireless-basic]] === Configuração básica ==== Configuração do Kernel Para usar a rede sem fio, uma placa de rede sem fio é necessária e o kernel precisa ser configurado com o suporte de rede sem fio apropriado. O kernel é separado em vários módulos para que apenas o suporte necessário precise ser configurado. Os dispositivos sem fio mais comumente usados são aqueles que usam peças fabricadas pela Atheros. Estes dispositivos são suportados pelo man:ath[4] e requerem que a seguinte linha seja adicionada ao [.filename]#/boot/loader.conf# : [.programlisting] .... if_ath_load="YES" .... O driver Atheros é dividido em três partes separadas: o driver (man:ath[4]), a camada de suporte de hardware que lida com funções específicas do chip (man:ath_hal[4]) e um algoritmo para selecionar a taxa de transmissão de quadros. Quando este suporte é carregado como módulo do kernel, quaisquer dependências são tratadas automaticamente. Para carregar o suporte para um tipo diferente de dispositivo sem fio, especifique o módulo para esse dispositivo. Este exemplo é para dispositivos baseados no driver Intersil Prism parts (man:wi[4]): [.programlisting] .... if_wi_load="YES" .... [NOTE] ==== Os exemplos nesta seção usam um dispositivoman:ath[4] e o nome do dispositivo nos exemplos deve ser alterado de acordo com a configuração. Uma lista de drivers sem fio disponíveis e adaptadores suportados pode ser encontrada nas Notas de Hardware do FreeBSD, disponíveis nas https://www.FreeBSD.org/releases/[Informações de Release] da página do site do FreeBSD. Se um driver nativo do FreeBSD para o dispositivo sem fio não existir, pode ser possível usar o driver Windows(TM) com a ajuda do wrapper de driver crossref:config[config-network-ndis,NDIS]. ==== Além disso, os módulos que implementam o suporte criptográfico para os protocolos de segurança devem ser carregados. Estes destinam-se a ser dinamicamente carregados sob demanda pelo módulo man:wlan[4], mas por enquanto eles devem ser configurados manualmente. Os seguintes módulos estão disponíveis: man:wlan_wep[4], man:wlan_ccmp[4], e man:wlan_tkip[4]. Os drivers man:wlan_ccmp[4] e man:wlan_tkip[4] são necessário apenas ao usar os protocolos de segurança WPA ou 802.11i. Se a rede não usar criptografia, o suporte a man:wlan_wep[4] não será necessário. Para carregar estes módulos no momento da inicialização, adicione as seguintes linhas ao [.filename]#/boot/loader.conf#: [.programlisting] .... wlan_wep_load="YES" wlan_ccmp_load="YES" wlan_tkip_load="YES" .... Uma vez que esta informação tenha sido adicionada ao [.filename]#/boot/loader.conf#, reinicie a caixa FreeBSD. Como alternativa, carregue os módulos manualmente usando man:kldload[8]. [NOTE] ==== Para usuários que não querem usar módulos, é possível compilar esses drivers no kernel adicionando as seguintes linhas a um arquivo de configuração de kernel personalizado: [.programlisting] .... device wlan # 802.11 support device wlan_wep # 802.11 WEP support device wlan_ccmp # 802.11 CCMP support device wlan_tkip # 802.11 TKIP support device wlan_amrr # AMRR transmit rate control algorithm device ath # Atheros pci/cardbus NIC's device ath_hal # pci/cardbus chip support options AH_SUPPORT_AR5416 # enable AR5416 tx/rx descriptors device ath_rate_sample # SampleRate tx rate control for ath .... Com esta informação no arquivo de configuração do kernel, recompile o kernel e reinicie a máquina do FreeBSD. ==== Informações sobre o dispositivo sem fio devem aparecer nas mensagens de inicialização, assim: [source,shell] .... ath0: mem 0x88000000-0x8800ffff irq 11 at device 0.0 on cardbus1 ath0: [ITHREAD] ath0: AR2413 mac 7.9 RF2413 phy 4.5 .... ==== Definindo a Região Correta Como a situação regulatória é diferente em várias partes do mundo, é necessário definir corretamente os domínios que se aplicam à sua localização para obter as informações corretas sobre quais canais podem ser usados. As definições de região disponíveis podem ser encontradas em [.filename]#/etc/regdomain.xml#. Para definir os dados em tempo de execução, use o `ifconfig`: [source,shell] .... # ifconfig wlan0 regdomain ETSI country AT .... Para persistir as configurações, adicione-o ao [.filename]#/etc/rc.conf#: [source,shell] .... # sysrc create_args_wlan0="country AT regdomain ETSI" .... === Modo de Infraestrutura O modo de infra-estrutura (BSS) é o modo normalmente usado. Neste modo, vários pontos de acesso sem fio são conectados a uma rede com fio. Cada rede sem fio tem seu próprio nome, chamado de SSID. Os clientes sem fio se conectam aos pontos de acesso sem fio. ==== Clientes do FreeBSD ===== Como encontrar pontos de acesso Para procurar redes disponíveis, use man:ifconfig[8]. Essa solicitação pode demorar alguns instantes para ser concluída, pois exige que o sistema alterne para cada frequência sem fio disponível e sonde os pontos de acesso disponíveis. Apenas o superusuário pode iniciar uma varredura: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS dlinkap 00:13:46:49:41:76 11 54M -90:96 100 EPS WPA WME freebsdap 00:11:95:c3:0d:ac 1 54M -83:96 100 EPS WPA .... [NOTE] ==== A interface deve estar `up` antes de poder efetuar a busca. Pedidos de varredura subsequentes não exigem que a interface seja marcada como up novamente. ==== A saída de uma solicitação de varredura lista cada rede BSS/IBSS encontrada. Além de listar o nome da rede, o `SSID`, a saída também mostra o `BSSID`, que é o endereço MAC do ponto de acesso. O campo `CAPS` identifica o tipo de cada rede e os recursos das estações que operam lá: .Códigos de capacidade da estação [cols="1,1", frame="none", options="header"] |=== | Código de capacidade | Significado |`E` |Conjunto de serviços estendidos (ESS). Indica que a estação faz parte de uma rede de infraestrutura em vez de uma rede IBSS/ad-hoc. |`I` |Rede IBSS/ad-hoc. Indica que a estação faz parte de uma rede ad-hoc em vez de uma rede ESS. |`P` |Privacidade. A criptografia é necessária para todos os quadros de dados trocados dentro do BSS usando meios criptográficos como o WEP, o TKIP ou o AES-CCMP. |`S` |Preâmbulo Curto. Indica que a rede está usando preâmbulos curtos, definidos em 802.11b de Alta Taxa/DSSS PHYS, e utiliza um campo de sincronização de 56 bits em vez do campo de 128 bits usado no modo de preâmbulo longo. |`s` |Tempo de slot curto. Indica que a rede 802.11g está usando um tempo de slot curto porque não há estações legadas (802.11b) presentes. |=== Pode-se também exibir a lista atual de redes conhecidas com: [source,shell] .... # ifconfig wlan0 list scan .... Essas informações podem ser atualizadas automaticamente pelo adaptador ou manualmente com uma solicitação de `scan`. Dados antigos são automaticamente removidos do cache, então com o tempo essa lista pode diminuir a menos que mais varreduras sejam feitas. ===== Configurações básicas Esta seção fornece um exemplo simples de como fazer com que o adaptador de rede sem fio funcione no FreeBSD sem criptografia. Uma vez familiarizado com esses conceitos, é altamente recomendável usar o <> para configurar a rede sem fio. Existem três etapas básicas para configurar uma rede sem fio: selecionar um ponto de acesso, autenticar a estação e configurar um endereço IP. As seções a seguir discutem cada etapa. ====== Selecionando um ponto de acesso Na maioria das vezes, é suficiente deixar o sistema escolher um ponto de acesso usando a heurística integrada. Este é o comportamento padrão quando uma interface é marcada como up ou está listada em [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... Se houver vários pontos de acesso, um específico pode ser selecionado pelo seu SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here DHCP" .... Em um ambiente em que há vários pontos de acesso com o mesmo SSID, o que geralmente é feito para simplificar o roaming, talvez seja necessário associá-lo a um dispositivo específico. Neste caso, o BSSID do ponto de acesso pode ser especificado, com ou sem o SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here bssid xx:xx:xx:xx:xx:xx DHCP" .... Existem outras maneiras de restringir a escolha de um ponto de acesso, como limitar o conjunto de freqüências que o sistema fará a varredura. Isso pode ser útil para uma placa sem fio de banda múltipla, pois a varredura de todos os canais possíveis pode consumir muito tempo. Para limitar a operação a uma banda específica, use o parâmetro `mode`: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="mode 11g ssid your_ssid_here DHCP" .... Este exemplo forçará a placa a operar em 802.11g, que é definido apenas para freqüências de 2.4GHz, portanto, qualquer canal de 5GHz não será considerado. Isso também pode ser obtido com o parâmetro `channel`, que bloqueia a operação para uma frequência específica, e o parâmetro `chanlist`, para especificar uma lista de canais para varredura. Maiores informações sobre esses parâmetros podem ser encontradas em man:ifconfig[8]. ====== Autenticação Quando um ponto de acesso é selecionado, a estação precisa se autenticar antes de poder transmitir dados. A autenticação pode acontecer de várias maneiras. O esquema mais comum, autenticação aberta, permite que qualquer estação entre na rede e se comunique. Essa é a autenticação a ser usada para fins de teste na primeira vez em que uma rede sem fio é configurada. Outros esquemas exigem que os handshakes criptográficos sejam concluídos antes que o tráfego de dados possa fluir, usando chaves ou segredos pré-compartilhados ou esquemas mais complexos que envolvam serviços de back-end, como o RADIUS. Autenticação aberta é a configuração padrão. A próxima configuração mais comum é o WPA-PSK, também conhecido como WPA Pessoal, que é descrito em <>. [NOTE] ==== Se estiver usando uma estação base Extreme AirPort(TM) da Apple(TM) para um ponto de acesso, a autenticação de chave compartilhada juntamente com um WEP chave precisa ser configurada. Isto pode ser configurado em [.filename]#/etc/rc.conf# ou usando man:wpa_supplicant[8]. Para uma única estação base AirPort(TM), o acesso pode ser configurado com: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="authmode shared wepmode on weptxkey 1 wepkey 01234567 DHCP" .... Em geral, a autenticação de chave compartilhada deve ser evitada porque ela usa o material de chave WEP de uma maneira altamente restrita, facilitando ainda mais a quebra da chave. Se o WEP deve ser usado para compatibilidade com dispositivos legados, é melhor usar o WEP com a autenticação `open`. Mais informações sobre o WEP podem ser encontradas em <>. ==== ====== Obtendo um endereço IP com DHCP Quando um ponto de acesso é selecionado e os parâmetros de autenticação são definidos, um endereço IP deve ser obtido para se comunicar. Na maioria das vezes, o endereço IP é obtido através do DHCP. Para isso, edite o [.filename]#/etc/rc.conf# e adicione o `DHCP` à configuração do dispositivo: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... A interface sem fio está agora pronta para subir: [source,shell] .... # service netif start .... Quando a interface estiver rodando, use o man:ifconfig[8] para ver o status da interface [.filename]#ath0#: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.1.100 netmask 0xffffff00 broadcast 192.168.1.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid dlinkap channel 11 (2462 Mhz 11g) bssid 00:13:46:49:41:76 country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... A linha `status: associated` significa que está conectada à rede sem fio. O `bssid 00:13:46:49:41:76` é o endereço MAC do ponto de acesso e o `authmode OPEN` indica que a comunicação é não criptografada. ====== Endereço IP estático Se um endereço IP não puder ser obtido de um servidor DHCP, defina um endereço de IP fixo. Substitua a palavra-chave `DHCP` mostrada acima pelas informações do endereço. Certifique-se de reter quaisquer outros parâmetros para selecionar o ponto de acesso: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="inet 192.168.1.100 netmask 255.255.255.0 ssid your_ssid_here" .... [[network-wireless-wpa]] ===== WPA O Wi-Fi Protected Access (WPA) é um protocolo de segurança usado em conjunto com redes 802.11 para resolver a falta de autenticação adequada e a fraqueza do WEP. O WPA utiliza o protocolo de autenticação 802.1X e usa uma das várias codificações disponíveis em vez do WEP para integridade de dados. A única codificação exigida pelo WPA é o protocolo de integridade de chave temporária (TKIP). O TKIP é uma codificação que estende a codificação básica RC4 usada pelo WEP, adicionando verificação de integridade, detecção de adulteração e medidas para responder a intrusões detectadas. O TKIP foi projetado para funcionar em hardware legado apenas com uma modificação de software. Ele representa um compromisso que melhora a segurança, mas ainda não é totalmente imune a ataques. O WPA também especifica a codificação AES-CCMP como uma alternativa para o TKIP, e é preferível quando possível. Para esta especificação, o termo WPA2 ou RSN é comumente usado. O WPA define protocolos de autenticação e criptografia. A autenticação é mais comumente feita usando uma de duas técnicas: por 802.1X e um serviço de autenticação backend, como o RADIUS, ou por um handshake mínimo entre a estação e o ponto de acesso usando um segredo pré-compartilhado. O primeiro é comumente chamado de WPA Enterprise e o último é conhecido como WPA Pessoal. Como a maioria das pessoas não configurará um servidor backend RADIUS para sua rede sem fio, o WPA-PSK é de longe a configuração mais comumente encontrada para o WPA . O controle da conexão sem fio e a negociação ou autenticação de chave com um servidor é feito usando o man:wpa_supplicant[8]. Este programa requer um arquivo de configuração, o [.filename]#/etc/wpa_supplicant.conf#, para ser executado. Maiores informações sobre este arquivo podem ser encontradas em man:wpa_supplicant.conf[5]. [[network-wireless-wpa-wpa-psk]] ====== WPA-PSK O WPA-PSK, também conhecido como WPA Pessoal, é baseado em uma chave pré-compartilhada (PSK) que é gerada a partir de uma determinada senha e usado como chave mestra na rede sem fio. Isso significa que todos os usuários sem fio compartilharão a mesma chave. O WPA-PSK destina-se a redes pequenas em que o uso de um servidor de autenticação não é possível ou desejado. [WARNING] ==== Sempre use senhas fortes que sejam suficientemente longas e feitas de um alfabeto rico para que elas não sejam facilmente adivinhadas ou atacadas. ==== O primeiro passo é a configuração do [.filename]#/etc/wpa_supplicant.conf# com o SSID e a chave pré-compartilhada da rede: [.programlisting] .... network={ ssid="freebsdap" psk="freebsdmall" } .... Então, em [.filename]#/etc/rc.conf#, indique que a configuração do dispositivo sem fio será feita com o WPA e o endereço IP será obtido com o DHCP: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Então, suba a interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 5 DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6 DHCPOFFER from 192.168.0.1 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Ou, tente configurar a interface manualmente usando as informações em [.filename]#/etc/wpa_supplicant.conf#: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:11:95:c3:0d:ac (SSID='freebsdap' freq=2412 MHz) Associated with 00:11:95:c3:0d:ac WPA: Key negotiation completed with 00:11:95:c3:0d:ac [PTK=CCMP GTK=CCMP] CTRL-EVENT-CONNECTED - Connection to 00:11:95:c3:0d:ac completed (auth) [id=0 id_str=] .... A próxima operação é iniciar o man:dhclient[8] para obter o endereço IP do servidor DHCP: [source,shell] .... # dhclient wlan0 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [NOTE] ==== Se o [.filename]#/etc/rc.conf# tiver uma entrada `ifconfig_wlan0="DHCP"`, man:dhclient[8] será iniciado automaticamente após o man:wpa_supplicant[8] associar-se ao ponto de acesso. ==== Se o DHCP não for possível ou desejado, defina um endereço IP estático após o man:wpa_supplicant[8] autenticar a estação: [source,shell] .... # ifconfig wlan0 inet 192.168.0.100 netmask 255.255.255.0 # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Quando o DHCP não é usado, o gateway padrão e o servidor de nomes também precisam ser definidos manualmente: [source,shell] .... # route add default your_default_router # echo "nameserver your_DNS_server" >> /etc/resolv.conf .... [[network-wireless-wpa-eap-tls]] ====== WPA com EAP-TLS A segunda maneira de usar o WPA é com um servidor de autenticação de backend 802.1X. Neste caso, o WPA é chamado de WPA Enterprise para diferenciá-lo do WPA Pessoal menos seguro. A autenticação no WPA Enterprise é baseada no protocolo de autenticação extensível (EAP). O EAP não vem com um método de criptografia. Em vez disso, o EAP é incorporado dentro de um túnel criptografado. Existem muitos métodos de autenticação EAP, mas o EAP-TLS, o EAP-TTLS e o EAP-PEAP são os mais comum. O EAP com Segurança da Camada de Transporte (EAP-TLS) é um protocolo de autenticação sem fio bem suportado, já que foi o primeiro método EAP a ser certificado pela http://www.wi-fi.org/[WiFi Alliance]. O EAP-TLS requer três certificados para executar: o certificado da Autoridade de Certificação (CA) instalado em todas as máquinas, o certificado do servidor para o servidor de autenticação e um certificado de cliente para cada cliente sem fio. Nesse método EAP, o servidor de autenticação e o cliente sem fio autenticam um ao outro apresentando seus respectivos certificados e, em seguida, verificam se esses certificados foram assinados pela CA da organização. Como anteriormente, a configuração é feita através do [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" <.> proto=RSN <.> key_mgmt=WPA-EAP <.> eap=TLS <.> identity="loader" <.> ca_cert="/etc/certs/cacert.pem" <.> client_cert="/etc/certs/clientcert.pem" <.> private_key="/etc/certs/clientkey.pem" <.> private_key_passwd="freebsdmallclient" <.> } .... <.> Este campo indica o nome da rede (SSID). <.> Este exemplo usa o protocolo 802.11i RSN IEEE(TM), também conhecido como WPA2. <.> A linha `key_mgmt` refere-se ao protocolo de gerenciamento de chaves a ser usado. Neste exemplo, é o WPA usando a autenticação EAP. <.> Este campo indica o método EAP para a conexão. <.> O campo `identity` contém a sequência de identidade para EAP. <.> O campo `ca_cert` indica o nome do caminho do arquivo de certificado CA. Este arquivo é necessário para verificar o certificado do servidor. <.> A linha `client_cert` fornece o nome do caminho para o arquivo de certificado do cliente. Este certificado é exclusivo para cada cliente sem fio da rede. <.> O campo `private_key` é o nome do caminho para o arquivo de chave privada do certificado do cliente. <.> O campo `private_key_passwd` contém a frase secreta para a chave privada. Em seguida, adicione as seguintes linhas ao [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... O próximo passo é subir a interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Também é possível subir a interface manualmente usando man:wpa_supplicant[8] e man:ifconfig[8]. [[network-wireless-wpa-eap-ttls]] ====== WPA com EAP-TTLS Com o EAP-TLS, o servidor de autenticação e o cliente precisam de um certificado. Com o EAP-TTLS, um certificado de cliente é opcional. Esse método é semelhante a um servidor da Web que cria um túnel seguro SSL, mesmo se os visitantes não tiverem certificados do lado do cliente. O EAP-TTLS usa um túnel TLS criptografado para o transporte seguro dos dados de autenticação. A configuração necessária pode ser adicionada ao [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=TTLS <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase2="auth=MD5" <.> } .... <.> Este campo especifica o método EAP para a conexão. <.> O campo `identity` contém a sequência de identidade para a autenticação EAP dentro do túnel TLS criptografado. <.> O campo `password` contém a senha para a autenticação EAP. <.> O campo `ca_cert` indica o nome do caminho do arquivo de certificado CA. Este arquivo é necessário para verificar o certificado do servidor. <.> Este campo especifica o método de autenticação usado no túnel TLS criptografado. Neste exemplo, o EAP com desafio MD5 é usado. A fase de "inner authentication" é freqüentemente chamada de "phase2". Em seguida, adicione as seguintes linhas ao [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... O próximo passo é subir a interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wpa-eap-peap]] ====== WPA com EAP-PEAP [NOTE] ==== O PEAPv0/EAP-MSCHAPv2 é o método PEAP mais comum. Neste capítulo, o termo PEAP é usado para se referir a esse método. ==== O EAP protegido (PEAP) foi criado como uma alternativa ao EAP-TTLS e é o padrão mais usado do EAP após o EAP-TLS. Em uma rede com sistemas operacionais mistos, o PEAP deve ser o padrão mais suportado após o EAP-TLS. O PEAP é semelhante ao EAP-TTLS, pois usa um certificado do lado do servidor para autenticar clientes criando um túnel TLS criptografado entre o cliente e o servidor de autenticação, que protege a troca subsequente das informações de autenticação. A autenticação PEAP difere do EAP-TTLS, pois transmite o nome de usuário em texto aberto e somente a senha é enviada no túnel TLS criptografado. O EAP-TTLS usará o túnel TLS para o nome de usuário e para a senha. Adicione as seguintes linhas ao [.filename]#/etc/wpa_supplicant.conf# para ajustar as configurações relacionadas ao EAP-PEAP: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=PEAP <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase1="peaplabel=0" <.> phase2="auth=MSCHAPV2" <.> } .... <.> Este campo especifica o método EAP para a conexão. <.> O campo `identity` contém a sequência de identidade para a autenticação EAP dentro do túnel TLS criptografado. <.> O campo `password` contém a senha para a autenticação EAP. <.> O campo `ca_cert` indica o nome do caminho do arquivo de certificado CA. Este arquivo é necessário para verificar o certificado do servidor. <.> Este campo contém os parâmetros para a primeira fase de autenticação, o túnel TLS. De acordo com o servidor de autenticação usado, especifique um label específico para autenticação. Na maioria das vezes, o label será "client EAP encryption" que é definido usando `peaplabel=0`. Maiores informações podem ser encontradas em man:wpa_supplicant.conf[5]. <.> Este campo especifica o protocolo de autenticação usado no túnel TLS criptografado. No caso do PEAP, é `auth=MSCHAPV2`. Adicione o seguinte ao [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Então, suba a interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wep]] ===== WEP A privacidade equivalente com fio (WEP) faz parte do padrão 802.11 original. Não há mecanismo de autenticação, apenas uma forma fraca de controle de acesso que é facilmente quebrada. O WEP pode ser configurado usando o man:ifconfig[8]: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 inet 192.168.1.100 netmask 255.255.255.0 \ ssid my_net wepmode on weptxkey 3 wepkey 3:0x3456789012 .... * O `weptxkey` especifica qual chave WEP será usada na transmissão. Este exemplo usa a terceira chave. Isso deve corresponder à configuração no ponto de acesso. Quando não tiver certeza de qual chave é usada pelo ponto de acesso, tente `1` (a primeira chave) para esse valor. * O `wepkey` seleciona uma das chaves WEP. Deve estar no formato _index:key_. A chave `1` é usada por padrão; o índice só precisa ser definido ao usar uma chave diferente da primeira. + [NOTE] ==== Substitua o `0x3456789012` com a chave configurada para uso no ponto de acesso. ==== Consulte o man:ifconfig[8] para obter maiores informações. O recurso man:wpa_supplicant[8] pode ser usado para configurar uma interface sem fio com o WEP. O exemplo acima pode ser configurado adicionando as seguintes linhas ao [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="my_net" key_mgmt=NONE wep_key3=3456789012 wep_tx_keyidx=3 } .... Então: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:13:46:49:41:76 (SSID='dlinkap' freq=2437 MHz) Associated with 00:13:46:49:41:76 .... === Modo Ad-hoc O modo IBSS, também chamado de modo ad-hoc, é projetado para conexões ponto a ponto. Por exemplo, para estabelecer uma rede ad-hoc entre as máquinas `A` e `B`, escolha dois endereços IP e um SSID. Em `A`: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... O parâmetro `adhoc` indica que a interface está sendo executada no modo IBSS. `B` deve ser capaz de detectar `A`: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 02:11:95:c3:0d:ac 2 54M -64:-96 100 IS WME .... O `I` na saída confirma que `A` está no modo ad-hoc. Agora, configure `B` com um endereço IP diferente: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... Ambos `A` e `B` agora estão prontos para trocar informações. [[network-wireless-ap]] === Pontos de Acesso com um host FreeBSD O FreeBSD pode atuar como um Access Point (AP), o que elimina a necessidade de comprar um hardware AP ou executar uma rede ad-hoc. Isso pode ser particularmente útil quando uma máquina FreeBSD está atuando como um gateway para outra rede, como a Internet. [[network-wireless-ap-basic]] ==== Configurações básicas Antes de configurar uma máquina FreeBSD como um AP, o kernel deve ser configurado com o suporte de rede apropriado para a placa wireless assim como os protocolos de segurança que estão sendo usados. Para maiores detalhes, veja <>. [NOTE] ==== O wrapper do driver NDIS para os drivers Windows(TM) não suporta atualmente a operação AP. Somente os drivers nativos de rede sem fio do FreeBSD suportam o modo AP. ==== Quando o suporte à rede sem fio estiver carregado, verifique se o dispositivo sem fio oferece suporte ao modo de ponto de acesso baseado em host, também conhecido como modo hostap: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 list caps drivercaps=6f85edc1 cryptocaps=1f .... Esta saída exibe os recursos da placa. A palavra `HOSTAP` confirma que esta placa sem fio pode atuar como um AP. Diversas cifras suportadas também são listadas: WEP, TKIP e AES. Esta informação indica quais protocolos de segurança podem ser usados no AP. O dispositivo sem fio só pode ser colocado no modo hostap durante a criação do pseudo-dispositivo de rede, portanto, um dispositivo criado anteriormente deve ser destruído primeiro: [source,shell] .... # ifconfig wlan0 destroy .... e então regenerado com a opção correta antes de configurar os outros parâmetros: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1 .... Use o man:ifconfig[8] novamente para ver o status da interface [.filename]#wlan0#: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... O parâmetro `hostap` indica que a interface está sendo executada no modo de ponto de acesso baseado em host. A configuração da interface pode ser feita automaticamente no momento da inicialização, adicionando as seguintes linhas ao [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" create_args_wlan0="wlanmode hostap" ifconfig_wlan0="inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1" .... ==== Ponto de acesso baseado em host sem autenticação ou criptografia Embora não seja recomendado executar um AP sem nenhuma autenticação ou criptografia, esta é uma maneira simples de verificar se o AP está funcionando. Essa configuração também é importante para depurar problemas do cliente. Quando o AP estiver configurado, inicie uma verificação de outra máquina sem fio para encontrar o AP: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M -66:-96 100 ES WME .... A máquina cliente encontrou o AP e pode ser associado a ele: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... [[network-wireless-ap-wpa]] ==== Ponto de acesso baseado em host com WPA2 Esta seção se concentra na configuração de um ponto de acesso do FreeBSD usando o protocolo de segurança WPA2. Maiores detalhes sobre WPA e a configuração de clientes sem fio baseados em WPA podem ser encontrados em <>. O daemon man:hostapd[8] é usado para lidar com a autenticação de clientes e o gerenciamento de chaves no AP com WPA2 habilitado. As seguintes operações de configuração são executadas na máquina FreeBSD atuando como o AP. Uma vez que o AP esteja funcionando corretamente, o man:hostapd[8] pode ser iniciado automaticamente na inicialização com essa linha em [.filename]#/etc/rc.conf#: [.programlisting] .... hostapd_enable="YES" .... Antes de tentar configurar o man:hostapd[8], primeiro defina as configurações básicas introduzidas em <> . ===== WPA2-PSK O WPA2-PSK destina-se a redes pequenas em que o uso de um servidor de autenticação backend não é possível ou desejado. A configuração é feita em [.filename]#/etc/hostapd.conf#: [.programlisting] .... interface=wlan0 <.> debug=1 <.> ctrl_interface=/var/run/hostapd <.> ctrl_interface_group=wheel <.> ssid=freebsdap <.> wpa=2 <.> wpa_passphrase=freebsdmall <.> wpa_key_mgmt=WPA-PSK <.> wpa_pairwise=CCMP <.> .... <.> Interface sem fio usada para o ponto de acesso. <.> Nível de detalhamento usado durante a execução de man:hostapd[8]. Um valor de `1` representa o nível mínimo. <.> Nome do caminho de diretório usado pelo man:hostapd[8] para armazenar arquivos de soquete de domínio para comunicação com programas externos, como man:hostapd_cli[8]. O valor padrão é usado neste exemplo. <.> O grupo permitiu acessar os arquivos da interface de controle. <.> O nome da rede sem fio, ou SSID, que aparecerá nas varreduras sem fio. <.> Ative o WPA e especifique qual protocolo de autenticação WPA será necessário. Um valor de `2` configura o AP para WPA2 e é recomendado. Defina como `1` apenas se o WPA obsoleto for necessário. <.> Senha ASCII para autenticação WPA. <.> O protocolo de gerenciamento de chaves a ser usado. Este exemplo define o WPA-PSK. Algoritmos de criptografia aceitos pelo ponto de acesso. Neste exemplo, apenas a codificação CCMP (AES) é aceita. O CCMP é uma alternativa ao TKIP e é fortemente preferido quando possível. O TKIP só deve ser permitido quando houver estações incapazes de usar o CCMP. O próximo passo é iniciar man:hostapd[8]: [source,shell] .... # service hostapd forcestart .... [source,shell] .... # ifconfig wlan0 wlan0: flags=8943 metric 0 mtu 1500 ether 04:f0:21:16:8e:10 inet6 fe80::6f0:21ff:fe16:8e10%wlan0 prefixlen 64 scopeid 0x9 nd6 options=21 media: IEEE 802.11 Wireless Ethernet autoselect mode 11na status: running ssid No5ignal channel 36 (5180 MHz 11a ht/40+) bssid 04:f0:21:16:8e:10 country US ecm authmode WPA2/802.11i privacy MIXED deftxkey 2 AES-CCM 2:128-bit AES-CCM 3:128-bit txpower 17 mcastrate 6 mgmtrate 6 scanvalid 60 ampdulimit 64k ampdudensity 8 shortgi wme burst dtimperiod 1 -dfs groups: wlan .... Quando o AP está em execução, os clientes podem associar-se a ele. Veja <> para maiores detalhes. É possível ver as estações associadas ao AP usando o `ifconfig _wlan0_ list sta`. ==== Ponto de acesso baseado em host WEP Não é recomendado o uso do WEP para configurar um AP, já que não há mecanismo de autenticação e a criptografia é facilmente quebrada. Algumas placas sem fio legadas suportam apenas o WEP e essas placas suportarão apenas um AP sem autenticação ou criptografia. O dispositivo sem fio agora pode ser colocado no modo hostap e configurado com o endereço SSID e IP corretos: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 \ ssid freebsdap wepmode on weptxkey 3 wepkey 3:0x3456789012 mode 11g .... * O `weptxkey` indica qual a chave WEP será usada na transmissão. Este exemplo usa a terceira chave, pois a numeração de chaves começa com `1`. Esse parâmetro deve ser especificado para criptografar os dados. * O `wepkey` define a chave WEP selecionada. Ela deve estar no formato _index:key_. Se o índice não for fornecido, a chave `1` será configurada. O índice precisa ser definido ao usar chaves diferentes da primeira chave. Use o man:ifconfig[8] para ver o status da interface [.filename]#wlan0#: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 4 (2427 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy ON deftxkey 3 wepkey 3:40-bit txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... De uma outra máquina sem fio, agora é possível iniciar uma varredura para encontrar o AP: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M 22:1 100 EPS .... Neste exemplo, a máquina cliente encontrou o AP e pode associá-lo usando os parâmetros corretos. Veja <> para maiores detalhes. === Usando conexões com fio e sem fio Uma conexão com fio oferece melhor desempenho e confiabilidade, enquanto uma conexão sem fio fornece flexibilidade e mobilidade. Os usuários de laptop normalmente querem se movimentar perfeitamente entre os dois tipos de conexão. No FreeBSD, é possível combinar duas ou mais interfaces de rede em um "failover". Esse tipo de configuração usa a conexão mais prioritária e disponível de um grupo de interfaces de rede, e o sistema operacional alterna automaticamente quando o estado do link é alterado. A agregação de links e o failover são cobertos em <> e um exemplo para usar conexões com e sem fio é fornecido em <>. === Solução de problemas Esta seção descreve várias etapas para ajudar a solucionar problemas comuns de rede sem fio. * Se o ponto de acesso não estiver listado durante a verificação, verifique se a configuração não limitou o dispositivo sem fio a um conjunto limitado de canais. * Se o dispositivo não puder se associar a um ponto de acesso, verifique se a configuração corresponde às configurações no ponto de acesso. Isso inclui o esquema de autenticação e qualquer protocolo de segurança. Simplifique a configuração tanto quanto possível. Se estiver usando um protocolo de segurança, como o WPA ou o WEP, configure o ponto de acesso para autenticação aberta e nenhuma segurança para ver se o tráfego irá passar. + O suporte a depuração é fornecido pelo man:wpa_supplicant[8]. Tente executar este utilitário manualmente com a opção `-dd` e examine os logs do sistema. * Uma vez que o sistema possa se associar com o ponto de acesso, diagnostique a configuração da rede usando ferramentas como o man:ping[8]. * Existem muitas ferramentas de depuração de nível inferior. As mensagens de depuração podem ser ativadas na camada de suporte do protocolo 802.11 usando o man:wlandebug[8]. Por exemplo, para habilitar mensagens do console relacionadas à varredura de pontos de acesso e aos handshakes do protocolo 802.11 necessários para organizar a comunicação: + [source,shell] .... # wlandebug -i wlan0 +scan+auth+debug+assoc net.wlan.0.debug: 0 => 0xc80000 .... + Muitas estatísticas úteis são mantidas pela camada 802.11 e o `wlanstats`, encontrado em [.filename]#/usr/src/tools/tools/net80211#, vai despejar esta informação. Essas estatísticas devem exibir todos os erros identificados pela camada 802.11. No entanto, alguns erros são identificados nos drivers de dispositivo que estão abaixo da camada 802.11, portanto eles podem não aparecer. Para diagnosticar problemas específicos do dispositivo, consulte a documentação do driver. Se as informações acima não ajudarem a esclarecer o problema, envie um relatório de problemas e inclua a saída das ferramentas acima. [[network-usb-tethering]] == USB Tethering Muitos telefones celulares oferecem a opção de compartilhar sua conexão de dados sobre o USB (muitas vezes chamado de "tethering"). Este recurso usa o RNDIS, CDC ou um protocolo personalizado Apple(TM)iPhone(TM)/iPad(TM). * Os dispositivos Android(TM) geralmente utilizam o driver man:urndis[4]. * Os dispositivos Apple(TM) utilizam o driver man:ipheth[4]. * Dispositivos mais antigos geralmente utilizam o driver man:cdce[4]. Antes de conectar um dispositivo, carregue o driver apropriado no kernel: [source,shell] .... # kldload if_urndis # kldload if_cdce # kldload if_ipheth .... Uma vez que o dispositivo esteja conectado, ``ue``__0__ estará disponível para uso como um dispositivo de rede normal. Certifique-se de que a opção "USB Tethering" esteja ativada no dispositivo. Para tornar essa alteração permanente e carregar o driver como um módulo no momento da inicialização, coloque a linha apropriada abaixo em [.filename]#/boot/loader.conf#: [source,shell] .... if_urndis_load="YES" if_cdce_load="YES" if_ipheth_load="YES" .... [[network-bluetooth]] == Bluetooth O bluetooth é uma tecnologia sem fio para a criação de redes pessoais que operam na faixa não licenciada de 2,4 GHz, com um alcance de 10 metros. As redes geralmente são formadas em modo ad-hoc a partir de dispositivos portáteis, como telefones celulares, computadores de mão e laptops. Ao contrário da tecnologia sem fio Wi-Fi, o Bluetooth oferece perfis de serviços de nível superior, como servidores de arquivos semelhantes ao FTP, envio de arquivos, transporte de voz, emulação de linha serial e muito mais. Esta seção descreve o uso de um dongle Bluetooth USB em um sistema FreeBSD. Em seguida, descreve os vários protocolos e utilitários Bluetooth. === Carregando o Suporte Bluetooth A pilha Bluetooth no FreeBSD é implementada usando o framework man:netgraph[4]. Uma ampla variedade de dongles Bluetooth USB é suportada pelo man:ng_ubt[4]. Os dispositivos Bluetooth baseados no Broadcom BCM2033 são suportados pelos drivers man:ubtbcmfw[4] e man:ng_ubt[4]. A placa 3Com Bluetooth PC Card 3CRWB60-A é suportada pelo driver man:ng_bt3c[4]. Dispositivos Bluetooth baseados em Portas Seriais e UART são suportados por man:sio[4], man:ng_h4[4], e man:hcseriald[8]. Antes de conectar um dispositivo, determine qual dos drivers acima ele usa e, em seguida, carregue o driver. Por exemplo, se o dispositivo usar o driver man:ng_ubt[4]: [source,shell] .... # kldload ng_ubt .... Se o dispositivo Bluetooth for conectado ao sistema durante a inicialização do sistema, o sistema pode ser configurado para carregar o módulo no momento da inicialização, adicionando o driver ao [.filename]#/boot/loader.conf#: [.programlisting] .... ng_ubt_load="YES" .... Quando o driver estiver carregado, conecte o dongle USB. Se a carga do driver tiver sido bem-sucedida, uma saída semelhante à seguinte deve aparecer no console e em [.filename]#/var/log/messages#: [source,shell] .... ubt0: vendor 0x0a12 product 0x0001, rev 1.10/5.25, addr 2 ubt0: Interface 0 endpoints: interrupt=0x81, bulk-in=0x82, bulk-out=0x2 ubt0: Interface 1 (alt.config 5) endpoints: isoc-in=0x83, isoc-out=0x3, wMaxPacketSize=49, nframes=6, buffer size=294 .... Para iniciar e parar a stack Bluetooth, use seu script de inicialização. É uma boa ideia parar a stack antes de desconectar o dispositivo. Iniciar a stack bluetooth pode exigir que o man:hcsecd[8] seja iniciado. Ao iniciar a stack, a saída deve ser semelhante à seguinte: [source,shell] .... # service bluetooth start ubt0 BD_ADDR: 00:02:72:00:d4:1a Features: 0xff 0xff 0xf 00 00 00 00 00 <3-Slot> <5-Slot> Max. ACL packet size: 192 bytes Number of ACL packets: 8 Max. SCO packet size: 64 bytes Number of SCO packets: 8 .... === Encontrando outros dispositivos Bluetooth A Interface do Controlador do Host (HCI) fornece um método uniforme para acessar os recursos de banda básica do Bluetooth. No FreeBSD, um nó netgraph HCI é criado para cada dispositivo Bluetooth. Para mais detalhes, consulte man:ng_hci[4]. Uma das tarefas mais comuns é a descoberta de dispositivos Bluetooth dentro da proximidade RF. Esta operação é chamada _inquiry_. Investigação e outras operações relacionadas a HCI são feitas usando man:hccontrol[8]. O exemplo abaixo mostra como descobrir quais dispositivos Bluetooth estão ao alcance. A lista de dispositivos deve ser exibida em alguns segundos. Note que um dispositivo remoto só irá responder a pergunta se estiver configurado para o modo _detectável_. [source,shell] .... % hccontrol -n ubt0hci inquiry Inquiry result, num_responses=1 Inquiry result #0 BD_ADDR: 00:80:37:29:19:a4 Page Scan Rep. Mode: 0x1 Page Scan Period Mode: 00 Page Scan Mode: 00 Class: 52:02:04 Clock offset: 0x78ef Inquiry complete. Status: No error [00] .... O `BD_ADDR` é o endereço exclusivo de um dispositivo Bluetooth, semelhante ao endereço MAC de uma placa de rede. Este endereço é necessário para uma comunicação posterior com um dispositivo e é possível atribuir um nome legível a um `BD_ADDR`. Informações sobre os hosts Bluetooth conhecidos estão contidas em [.filename]#/etc/bluetooth/hosts#. O exemplo a seguir mostra como obter o nome legível que foi atribuído ao dispositivo remoto: [source,shell] .... % hccontrol -n ubt0hci remote_name_request 00:80:37:29:19:a4 BD_ADDR: 00:80:37:29:19:a4 Name: Pav's T39 .... Se uma consulta for realizada em um dispositivo Bluetooth remoto, ele encontrará o computador como "your.host.name (ubt0)". O nome atribuído ao dispositivo local pode ser alterado a qualquer momento. Dispositivos remotos podem receber aliases em [.filename]#/etc/bluetooth/hosts#. Maiores informações sobre o arquivo [.filename]#/etc/bluetooth/hosts# podem ser encontradas em man:bluetooth.hosts[5]. O sistema Bluetooth fornece uma conexão ponta-a-ponto entre duas unidades Bluetooth ou uma conexão ponto-a-multiponto que é compartilhada entre vários dispositivos Bluetooth. O exemplo a seguir mostra como criar uma conexão a um dispositivo remoto: [source,shell] .... % hccontrol -n ubt0hci create_connection BT_ADDR .... O `create_connection` aceita `BT_ADDR`, bem como aliases de host em [.filename]#/etc/bluetooth/hosts#. O exemplo a seguir mostra como obter a lista de conexões de banda base ativas para o dispositivo local: [source,shell] .... % hccontrol -n ubt0hci read_connection_list Remote BD_ADDR Handle Type Mode Role Encrypt Pending Queue State 00:80:37:29:19:a4 41 ACL 0 MAST NONE 0 0 OPEN .... Um _identificador de conexão_ é útil quando a finalização da conexão de banda base é necessária, embora normalmente não seja necessário fazer isso manualmente. A stack terminará automaticamente as conexões de banda básica inativas. [source,shell] .... # hccontrol -n ubt0hci disconnect 41 Connection handle: 41 Reason: Connection terminated by local host [0x16] .... Digite `hccontrol help` para obter uma lista completa dos comandos HCI disponíveis. A maioria dos comandos HCI não requer privilégios de superusuário. === Emparelhamento de dispositivos Por padrão, a comunicação Bluetooth não é autenticada e qualquer dispositivo pode conversar com qualquer outro dispositivo. Um dispositivo Bluetooth, como um telefone celular, pode optar por exigir autenticação para fornecer um serviço específico. A autenticação Bluetooth é normalmente feita com um _PIN code_, uma string ASCII com até 16 caracteres de comprimento. O usuário é obrigado a digitar o mesmo código de PIN em ambos os dispositivos. Depois que o usuário inserir o código de PIN, ambos os dispositivos gerarão uma _chave de link_. Depois disso, a chave de link pode ser armazenada nos dispositivos ou em um armazenamento persistente. Na próxima vez, os dois dispositivos usarão a chave de link gerada anteriormente. Este procedimento é chamado de _emparelhamento_. Observe que, se a chave de link for perdida por um dos dispositivos, o emparelhamento deverá ser repetido. O daemon man:hcsecd[8] é responsável por tratar os pedidos de autenticação Bluetooth. O arquivo de configuração padrão é o [.filename]#/etc/bluetooth/hcsecd.conf#. Uma seção de exemplo para um telefone celular com o código PIN definido como `1234` é mostrada abaixo: [.programlisting] .... device { bdaddr 00:80:37:29:19:a4; name "Pav's T39"; key nokey; pin "1234"; } .... A única limitação nos códigos de PIN é o comprimento. Alguns dispositivos, como fones de ouvido Bluetooth, podem ter um código PIN integrado fixo. A opção `-d` força o man:hcsecd[8] a ficar em primeiro plano, então é fácil ver o que está acontecendo. Configure o dispositivo remoto para receber o emparelhamento e inicie a conexão Bluetooth ao dispositivo remoto. O dispositivo remoto deve indicar que o pareamento foi aceito e solicitar o código de PIN. Digite o mesmo código de PIN listado em [.filename]#hcsecd.conf#. Agora o computador e o dispositivo remoto estão emparelhados. Alternativamente, o emparelhamento pode ser iniciado no dispositivo remoto. A seguinte linha pode ser adicionada ao [.filename]#/etc/rc.conf# para configurar o man:hcsecd[8] para iniciar automaticamente quando o sistema inicializar: [.programlisting] .... hcsecd_enable="YES" .... A seguir, um exemplo da saída do daemon man:hcsecd[8]: [.programlisting] .... hcsecd[16484]: Got Link_Key_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', link key doesn't exist hcsecd[16484]: Sending Link_Key_Negative_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Got PIN_Code_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', PIN code exists hcsecd[16484]: Sending PIN_Code_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 .... === Acesso à rede com perfis PPP Um perfil de rede dial-up (DUN) pode ser usado para configurar um telefone celular como um modem sem fio para a conexão a um servidor de acesso à Internet dial-up. Também pode ser usado para configurar um computador para receber chamadas de dados de um telefone celular. O acesso à rede com um perfil PPP pode ser usado para fornecer acesso LAN a um único dispositivo Bluetooth ou a vários dispositivos Bluetooth. Ele também pode fornecer uma conexão PC para PC usando uma rede PPP sobre uma emulação de cabo serial. No FreeBSD, esses perfis são implementados com o man:ppp[8] e o wrapper man:rfcomm_pppd[8] que converte uma conexão Bluetooth em algo que o PPP pode usar. Antes que um perfil possa ser usado, um novo label PPP deve ser criado em [.filename]#/etc/ppp/ppp.conf#. Consulte man:rfcomm_pppd[8] para exemplos. Neste exemplo, o man:rfcomm_pppd[8] é usado para abrir uma conexão com um dispositivo remoto com um `BD_ADDR` de `00:80:37:29:19:a4` em um canal DUNRFCOMM: [source,shell] .... # rfcomm_pppd -a 00:80:37:29:19:a4 -c -C dun -l rfcomm-dialup .... O número real do canal será obtido a partir do dispositivo remoto usando o protocolo SDP. É possível especificar manualmente o canal RFCOMM e, nesse caso, o man:rfcomm_pppd[8] não executará a consulta SDP. Use o man:sdpcontrol[8] para descobrir o canal RFCOMM no dispositivo remoto. Para fornecer acesso à rede com o serviço PPPLAN, o man:sdpd[8] precisa estar sendo executado e uma nova entrada para clientes LAN deve ser criada em [.filename]#/etc/ppp/ppp.conf#. Consulte man:rfcomm_pppd[8] para exemplos. Por fim, inicie o servidor RFCOMMPPP em um número de canal RFCOMM válido. O servidor RFCOMMPPP registrará automaticamente o serviço Bluetooth LAN com o daemon local SDP. O exemplo abaixo mostra como iniciar o servidor RFCOMMPPP. [source,shell] .... # rfcomm_pppd -s -C 7 -l rfcomm-server .... === Protocolos Bluetooth Esta seção fornece uma visão geral dos vários protocolos Bluetooth, suas funções e utilitários associados. ==== Controle de Link Lógico e Protocolo de Adaptação (L2CAP) O Protocolo de Adaptação e Controle de Link Lógico (L2CAP) fornece serviços de dados orientados a conexão e sem conexão para protocolos de camada superior. O L2CAP permite que protocolos e aplicativos de alto nível transmitam e recebam pacotes de dados L2CAP de até 64 kilobytes de comprimento. O L2CAP é baseado no conceito de _canais_. Um canal é uma conexão lógica em cima de uma conexão de banda base, na qual cada canal é vinculado a um único protocolo de maneira many-to-one. Vários canais podem ser vinculados ao mesmo protocolo, mas um canal não pode ser vinculado a vários protocolos. Cada pacote L2CAP recebido em um canal é direcionado para o protocolo apropriado de nível superior. Vários canais podem compartilhar a mesma conexão de banda base. No FreeBSD, um nó netgraph L2CAP é criado para cada dispositivo Bluetooth. Esse nó é normalmente conectado ao nó Bluetooth HCI downstream e aos nós de soquete Bluetooth upstream. O nome padrão para o nó L2CAP é "devicel2cap". Para mais detalhes, consulte man:ng_l2cap[4]. Um comando útil é o man:l2ping[8], que pode ser usado para executar ping em outros dispositivos. Algumas implementações Bluetooth podem não retornar todos os dados enviados para elas, portanto, a saída `0 bytes` no exemplo a seguir é normal. [source,shell] .... # l2ping -a 00:80:37:29:19:a4 0 bytes from 0:80:37:29:19:a4 seq_no=0 time=48.633 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=1 time=37.551 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=2 time=28.324 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=3 time=46.150 ms result=0 .... O utilitário man:l2control[8] é usado para executar várias operações em nós L2CAP. Este exemplo mostra como obter a lista de conexões lógicas (canais) e a lista de conexões de banda base para o dispositivo local: [source,shell] .... % l2control -a 00:02:72:00:d4:1a read_channel_list L2CAP channels: Remote BD_ADDR SCID/ DCID PSM IMTU/ OMTU State 00:07:e0:00:0b:ca 66/ 64 3 132/ 672 OPEN % l2control -a 00:02:72:00:d4:1a read_connection_list L2CAP connections: Remote BD_ADDR Handle Flags Pending State 00:07:e0:00:0b:ca 41 O 0 OPEN .... Outra ferramenta de diagnóstico é o man:btsockstat[1]. Ele é semelhante ao man:netstat[1], mas para estruturas de dados relacionadas à rede Bluetooth. O exemplo abaixo mostra a mesma conexão lógica que man:l2control[8] acima. [source,shell] .... % btsockstat Active L2CAP sockets PCB Recv-Q Send-Q Local address/PSM Foreign address CID State c2afe900 0 0 00:02:72:00:d4:1a/3 00:07:e0:00:0b:ca 66 OPEN Active RFCOMM sessions L2PCB PCB Flag MTU Out-Q DLCs State c2afe900 c2b53380 1 127 0 Yes OPEN Active RFCOMM sockets PCB Recv-Q Send-Q Local address Foreign address Chan DLCI State c2e8bc80 0 250 00:02:72:00:d4:1a 00:07:e0:00:0b:ca 3 6 OPEN .... ==== Comunicação por radiofrequência (RFCOMM) O protocolo RFCOMM fornece emulação de portas seriais sobre o protocolo L2CAP. O RFCOMM é um protocolo de transporte simples, com disposições adicionais para emular os 9 circuitos das portas seriais RS-232 (EIATIA-232-E). Suporta até 60 conexões simultâneas (canais RFCOMM) entre dois dispositivos Bluetooth. Para fins do RFCOMM, um caminho de comunicação completo envolve dois aplicativos em execução nos terminais de comunicação com um segmento de comunicação entre eles. O RFCOMM destina-se a abranger aplicativos que fazem uso das portas seriais dos dispositivos em que residem. O segmento de comunicação é um link Bluetooth de conexão direta de um dispositivo para outro. O RFCOMM está relacionado apenas com a conexão entre os dispositivos no caso de conexão direta ou entre o dispositivo e um modem no caso de rede. O RFCOMM pode suportar outras configurações, como módulos que se comunicam via tecnologia sem fio Bluetooth de um lado e fornecem uma interface com fio no outro lado. No FreeBSD, o RFCOMM é implementado na camada de sockets do Bluetooth. ==== Protocolo de Descoberta de Serviços (SDP) O Protocolo de Descoberta de Serviços (SDP) fornece os meios para os aplicativos clientes descobrirem a existência de serviços fornecidos por aplicativos de servidor, bem como os atributos desses serviços. Os atributos de um serviço incluem o tipo ou classe de serviço oferecido e as informações de mecanismo ou protocolo necessárias para utilizar o serviço. O SDP envolve a comunicação entre um servidor SDP e um cliente SDP. O servidor mantém uma lista de registros de serviço que descrevem as características dos serviços associados ao servidor. Cada registro de serviço contém informações sobre um único serviço. Um cliente pode recuperar informações de um registro de serviço mantido pelo servidor SDP emitindo uma solicitação SDP. Se o cliente, ou um aplicativo associado ao cliente, decidir usar um serviço, ele deverá abrir uma conexão separada com o provedor de serviços para utilizar o serviço. O SDP fornece um mecanismo para descobrir serviços e seus atributos, mas não fornece um mecanismo para utilizar esses serviços. Normalmente, um cliente SDP procura serviços baseados em algumas características desejadas dos serviços. No entanto, há momentos em que é desejável descobrir quais tipos de serviços são descritos pelos registros de serviço de um servidor SDP, sem qualquer informação prévia sobre os serviços. Este processo de procurar por qualquer serviço oferecido é chamado de _navegação_. O servidor Bluetooth SDP, man:sdpd[8] e o cliente de linha de comandos, man:sdpcontrol[8], estão incluídos na instalação padrão do FreeBSD. O exemplo a seguir mostra como executar uma consulta de navegação SDP. [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec browse Record Handle: 00000000 Service Class ID List: Service Discovery Server (0x1000) Protocol Descriptor List: L2CAP (0x0100) Protocol specific parameter #1: u/int/uuid16 1 Protocol specific parameter #2: u/int/uuid16 1 Record Handle: 0x00000001 Service Class ID List: Browse Group Descriptor (0x1001) Record Handle: 0x00000002 Service Class ID List: LAN Access Using PPP (0x1102) Protocol Descriptor List: L2CAP (0x0100) RFCOMM (0x0003) Protocol specific parameter #1: u/int8/bool 1 Bluetooth Profile Descriptor List: LAN Access Using PPP (0x1102) ver. 1.0 .... Observe que cada serviço tem uma lista de atributos, como o canal RFCOMM. Dependendo do serviço, o usuário pode precisar anotar alguns dos atributos. Algumas implementações Bluetooth não suportam a navegação de serviço e podem retornar uma lista vazia. Nesse caso, é possível procurar pelo serviço específico. O exemplo abaixo mostra como pesquisar o serviço OBEX Object Push (OPUSH) : [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec search OPUSH .... A oferta de serviços no FreeBSD para clientes Bluetooth é feita com o servidor man:sdpd[8]. A seguinte linha pode ser adicionada ao [.filename]#/etc/rc.conf#: [.programlisting] .... sdpd_enable="YES" .... Então o daemon man:sdpd[8] pode ser iniciado com: [source,shell] .... # service sdpd start .... O aplicativo de servidor local que deseja fornecer um serviço Bluetooth a clientes remotos registrará o serviço com o daemon SDP local . Um exemplo de tal aplicativo é o man:rfcomm_pppd[8]. Uma vez iniciado, ele registrará o serviço LAN Bluetooth com o daemon local SDP. A lista de serviços registrados no servidor SDPlocal pode ser obtida através da emissão de uma consulta de navegação SDP através do canal de controle local: [source,shell] .... # sdpcontrol -l browse .... ==== OBEX Object Push (OPUSH) Object Exchange (OBEX) é um protocolo amplamente utilizado para transferências de arquivos simples entre dispositivos móveis. Seu principal uso é na comunicação por infravermelho, onde é usado para transferências de arquivos genéricos entre notebooks ou PDAs, e para enviar cartões de visita ou entradas de calendário entre telefones celulares e outros dispositivos com Personal Information Manager (PIM). O servidor e o cliente OBEX são implementados pelo obexapp, que pode ser instalado usando o pacote ou port package:comms/obexapp[]. O cliente OBEX é usado para empurrar e/ou puxar objetos do servidor OBEX. Um exemplo de objeto é um cartão de visita ou um compromisso. O cliente OBEX pode obter o número do canal RFCOMM do dispositivo remoto via SDP. Isso pode ser feito especificando o nome do serviço em vez do número do canal RFCOMM. Os nomes de serviços suportados são: `IrMC`, `FTRN` e `OPUSH`. Também é possível especificar o canal RFCOMM como um número. Abaixo está um exemplo de uma sessão OBEX em que o objeto de informações do dispositivo é extraído do telefone celular e um novo objeto, o cartão de visita, é inserido no diretório do telefone. [source,shell] .... % obexapp -a 00:80:37:29:19:a4 -C IrMC obex> get telecom/devinfo.txt devinfo-t39.txt Success, response: OK, Success (0x20) obex> put new.vcf Success, response: OK, Success (0x20) obex> di Success, response: OK, Success (0x20) .... Para fornecer o serviço OPUSH, o man:sdpd[8] deve estar em execução e uma pasta raiz, onde todos os objetos recebidos serão armazenados, deve ser criado. O caminho padrão para a pasta raiz é [.filename]#/var/spool/obex#. Por fim, inicie o servidor OBEX em um número de canal RFCOMM válido. O servidor OBEX registrará automaticamente o serviço OPUSH com o daemon SDP local. O exemplo abaixo mostra como iniciar o servidor OBEX. [source,shell] .... # obexapp -s -C 10 .... ==== Perfil de porta serial (SPP) O perfil de porta serial (SPP) permite que dispositivos Bluetooth executem emulação de cabo serial. Este perfil permite que aplicativos legados usem o Bluetooth como um substituto de cabos, através de uma abstração de porta serial virtual. No FreeBSD, o man:rfcomm_sppd[1] implementa o SPP e uma pseudo tty é usada como uma abstração de porta serial virtual. O exemplo abaixo mostra como se conectar ao serviço de porta serial de um dispositivo remoto. Um canal RFCOMM não precisa ser especificado uma vez que o man:rfcomm_sppd[1] pode obtê-lo a partir do dispositivo remoto via SDP. Para sobrescrever isso, especifique um canal RFCOMM na linha de comando. [source,shell] .... # rfcomm_sppd -a 00:07:E0:00:0B:CA -t rfcomm_sppd[94692]: Starting on /dev/pts/6... /dev/pts/6 .... Uma vez conectado, o pseudo-tty pode ser usado como porta serial: [source,shell] .... # cu -l /dev/pts/6 .... A pseudo-tty é impressa no stdout e pode ser lida por scripts de wrapper: [.programlisting] .... PTS=`rfcomm_sppd -a 00:07:E0:00:0B:CA -t` cu -l $PTS .... === Solução de problemas Por padrão, quando o FreeBSD está aceitando uma nova conexão, ele tenta executar uma troca de função e se tornar o mestre. Alguns dispositivos Bluetooth mais antigos que não suportam a troca de função não poderão se conectar. Como a troca de função é executada quando uma nova conexão está sendo estabelecida, não é possível perguntar ao dispositivo remoto se ele suporta a troca de função. No entanto, há uma opção HCI para desativar a alternância de funções no lado local: [source,shell] .... # hccontrol -n ubt0hci write_node_role_switch 0 .... Para exibir pacotes Bluetooth, use o pacote de terceiros hcidump, que pode ser instalado usando o pacote ou port package:comms/hcidump[]. Este utilitário é semelhante ao man:tcpdump[1] e pode ser usado para exibir o conteúdo dos pacotes Bluetooth no terminal e para descarregar os pacotes Bluetooth para um arquivo. [[network-bridging]] == Bridging Às vezes, é útil dividir uma rede, como um segmento Ethernet, em segmentos de rede sem precisar criar subnets IP e usar um roteador para conectar os segmentos. Um dispositivo que conecta duas redes dessa maneira é chamado de "bridge". Uma bridge funciona aprendendo os endereços MAC dos dispositivos em cada uma das suas interfaces de rede. Ele encaminha o tráfego entre as redes somente quando os endereços de origem e destino MAC estão em redes diferentes. Em muitos aspectos, uma brifge é como um switch Ethernet com poucas portas. Um sistema FreeBSD com múltiplas interfaces de rede pode ser configurado para atuar como uma bridge. Construir uma bridge pode ser útil nas seguintes situações: Conectar Redes:: A operação básica de uma bridge é unir dois ou mais segmentos de rede. Existem muitas razões para usar uma bridge baseada em host em vez de equipamentos de rede, tais como restrições de cabeamento ou firewall. Uma bridge também pode conectar uma interface sem fio em execução no modo hostap a uma rede com fio e atuar como um ponto de acesso. Firewall de Filtragem / Limitação de Trafego:: Uma bridge pode ser usada quando a funcionalidade de firewall é necessária sem a realização de roteamento ou conversão de endereços de rede (NAT). + Um exemplo é uma pequena empresa conectada via DSL ou ISDN a um ISP. Existem treze endereços IP públicos do ISP e dez computadores na rede. Nessa situação, é difícil usar um firewall baseado em roteador devido a problemas de sub-rede. Um firewall baseado em bridge pode ser configurado sem qualquer problema de endereçamento IP. Inspeção de Rede:: Uma bridge pode unir dois segmentos de rede para inspecionar todos os pacotes Ethernet que passam entre elas usando man:bpf[4] e man:tcpdump[1] na interface de bridge ou enviando uma cópia de todos os frames para uma interface adicional conhecida como span port. VPN de Camada 2:: Duas redes Ethernet podem ser unidas através de um link IP ligando as redes a um túnel EtherIP ou a uma solução baseada no man:tap[4] tal como o OpenVPN. Redundância de Camada 2:: Uma rede pode ser conectada com vários links e usar o protocolo Spanning Tree (STP) para bloquear caminhos redundantes. Esta seção descreve como configurar um sistema FreeBSD como uma bridge usando o man:if_bridge[4]. Um driver de bridge netgraph também está disponível e é descrito em man:ng_bridge[4]. [NOTE] ==== A filtragem de pacotes pode ser usada com qualquer pacote de firewall que se conecte ao framework man:pfil[9]. A bridge pode ser usada como um modelador de tráfego com o man:altq[4] ou man:dummynet[4]. ==== === Habilitando a Bridge No FreeBSD, o man:if_bridge[4] é um módulo do kernel que é carregado automaticamente pelo man:ifconfig[8] ao criar uma interface de bridge. Também é possível compilar o suporte de bridge em um kernel customizado adicionando `device if_bridge` ao arquivo de configuração do kernel personalizado. A bridge é criada usando clonagem de interface. Para criar a interface da bridge: [source,shell] .... # ifconfig bridge create bridge0 # ifconfig bridge0 bridge0: flags=8802 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:00:00:00:00:00 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:00:00:00:00:00 priority 0 ifcost 0 port 0 .... Quando uma interface de bridge é criada, ela recebe automaticamente um endereço Ethernet gerado aleatoriamente. Os parâmetros `maxaddr` e `timeout` controlam quantos endereços MAC a bridge manterá em sua tabela de encaminhamento e quantos segundos o sistema irá esperar antes de cada entrada ser removida após um endereço MAC ser visto pela última vez. Os outros parâmetros controlam como o STP opera. Em seguida, especifique quais interfaces de rede adicionar como membros da bridge. Para a bridge encaminhar pacotes, todas as interfaces de membros e a bridge precisam estar ativas: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 up # ifconfig fxp0 up # ifconfig fxp1 up .... A bridge agora pode encaminhar quadros Ethernet entre [.filename]#fxp0# e [.filename]#fxp1#. Adicione as seguintes linhas ao [.filename]#/etc/rc.conf# para que a bridge seja criada na inicialização: [.programlisting] .... cloned_interfaces="bridge0" ifconfig_bridge0="addm fxp0 addm fxp1 up" ifconfig_fxp0="up" ifconfig_fxp1="up" .... Se o host de ponte precisar de um endereço IP, defina-o na interface de bridge, não nas interfaces de membro. O endereço pode ser definido estaticamente ou via DHCP. Este exemplo define um endereço IP estático: [source,shell] .... # ifconfig bridge0 inet 192.168.0.1/24 .... Também é possível atribuir um endereço IPv6 a uma interface de bridge. Para tornar as mudanças permanentes, adicione as informações de endereçamento ao [.filename]#/etc/rc.conf#. [NOTE] ==== Quando a filtragem de pacotes está habilitada, os pacotes passarão pela entrada do filtro na interface de origem na interface da bridge e na saída nas interfaces apropriadas. Qualquer estágio pode ser desativado. Quando a direção do fluxo de pacotes é importante, é melhor usar o firewall nas interfaces de membros, em vez da própria bridge. A bridge tem várias opções configuráveis para o trafego de pacotes IP e não-IP, e a filtragem de pacotes layer2 com o man:ipfw[8]. Veja man:if_bridge[4] para maiores informações. ==== === Ativando o Spanning Tree Para que uma rede Ethernet funcione corretamente, somente um caminho ativo pode existir entre dois dispositivos. O protocolo STP detecta loops e coloca links redundantes em um estado bloqueado. Se um dos links ativos falhar, o STP calcula uma árvore diferente e habilita um dos caminhos bloqueados para restaurar a conectividade a todos os pontos da rede. O protocolo Rapid Spanning Tree (RSTP ou 802.1w) fornece compatibilidade retroativa com o STP legado. O RSTP fornece uma convergência mais rápida e troca informações com os switches vizinhos para fazer a transição rápida para o modo de encaminhamento sem criar loops. O FreeBSD suporta o RSTP e o STP como modos de operação, com o RSTP sendo o modo padrão. O STP pode ser ativado nas interfaces de membro usando o man:ifconfig[8]. Para uma bridge com [.filename]#fxp0# e [.filename]#fxp1# como as interfaces atuais, ative o STP com: [source,shell] .... # ifconfig bridge0 stp fxp0 stp fxp1 bridge0: flags=8843 metric 0 mtu 1500 ether d6:cf:d5:a0:94:6d id 00:01:02:4b:d4:50 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 0 port 0 member: fxp0 flags=1c7 port 3 priority 128 path cost 200000 proto rstp role designated state forwarding member: fxp1 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role designated state forwarding .... Essa ponte possui um spanning tree ID de `00:01:02:4b:d4:50` e uma prioridade de `32768`. Como o `root id` é o mesmo, indica que esta é a bridge raiz para a árvore. Outra bridge na rede também tem o STP ativado: [source,shell] .... bridge0: flags=8843 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:13:d4:9a:06:7a priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4 member: fxp0 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role root state forwarding member: fxp1 flags=1c7 port 5 priority 128 path cost 200000 proto rstp role designated state forwarding .... A linha `root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4` mostra que a bridge raiz é `00:01:02:4b:d4:50` e tem um custo de caminho de `400000` desta bridge. O caminho para a bridge raiz é via `port 4`, que é [.filename]#fxp0#. === Parâmetros da Interface de Bridge Vários parâmetros do `ifconfig` são exclusivos para interligar interfaces. Esta seção resume alguns usos comuns para esses parâmetros. A lista completa de parâmetros disponíveis é descrita em man:ifconfig[8]. privado:: Uma interface privada não encaminha qualquer tráfego para qualquer outra porta que também seja designada como uma interface privada. O tráfego é bloqueado incondicionalmente para que nenhum quadro Ethernet seja encaminhado, incluindo pacotes ARP. Se o tráfego precisar ser bloqueado seletivamente, um firewall deve ser usado no lugar. span:: Uma porta span transmite uma cópia de cada quadro Ethernet recebido pela bridge. O número de portas de span configuradas em uma bridge é ilimitado, mas se uma interface for designada como uma porta de span, ela também não poderá ser usada como uma porta de bridge comum. Isso é mais útil para espionar passivamente uma rede em bridge a partir de outro host conectado a uma das portas da bridge. Por exemplo, para enviar uma cópia de todos os quadros para fora da interface denominada [.filename]#fxp4#: + [source,shell] .... # ifconfig bridge0 span fxp4 .... sticky:: Se uma interface de membro de uma bridge estiver marcada como fixa, as entradas de endereço aprendidas dinamicamente serão tratadas como entradas estáticas no cache de encaminhamento. Entradas fixas nunca são eliminadas do cache ou substituídas, mesmo que o endereço seja visto em uma interface diferente. Isso oferece o benefício de entradas de endereço estático sem a necessidade de preencher previamente a tabela de encaminhamento. Os clientes aprendidos em um segmento específico da bridge não podem se deslocar para outro segmento. + Um exemplo do uso de endereços fixos é combinar a bridge com VLANs para isolar redes de clientes sem desperdiçar espaço de endereço IP. Considere que `CustomerA` está em `vlan100`, `CustomerB` está em `vlan101`, e a bridge tem o endereço `192.168.0.1`: + [source,shell] .... # ifconfig bridge0 addm vlan100 sticky vlan100 addm vlan101 sticky vlan101 # ifconfig bridge0 inet 192.168.0.1/24 .... + Neste exemplo, os dois clientes vêem `192.168.0.1` como seu gateway padrão. Como o cache da bridge é fixo, um host não pode falsificar o endereço MAC do outro cliente para interceptar o tráfego. + Qualquer comunicação entre as VLANs pode ser bloqueada usando um firewall ou, como visto neste exemplo, interfaces privadas: + [source,shell] .... # ifconfig bridge0 private vlan100 private vlan101 .... + Os clientes são completamente isolados uns dos outros e o intervalo completo de endereços `/24` pode ser alocado sem criação de sub-redes. + O número de endereços MAC de origem exclusivos por trás de uma interface pode ser limitado. Quando o limite é atingido, os pacotes com endereços de origem desconhecidos são descartados até que uma entrada de cache do host existente expire ou seja removida. + O exemplo a seguir define o número máximo de dispositivos Ethernet para `CustomerA` em `vlan100` para 10: + [source,shell] .... # ifconfig bridge0 ifmaxaddr vlan100 10 .... As interfaces de bridge também suportam o modo monitor, onde os pacotes são descartados após processamento do man:bpf[4] e não são processados ou encaminhados. Isso pode ser usado para multiplexar a entrada de duas ou mais interfaces em um único fluxo man:bpf[4]. Isso é útil para reconstruir o tráfego de taps de rede que transmitem os sinais RX/TX através de duas interfaces separadas. Por exemplo, para ler a entrada de quatro interfaces de rede como um fluxo: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 addm fxp2 addm fxp3 monitor up # tcpdump -i bridge0 .... === Monitoramento SNMP A interface de bridge e os parâmetros de STP podem ser monitorados via o man:bsnmpd[1] o qual está incluído no sistema básico do FreeBSD. A MIB exportada da bridge está em conformidade com os padrões IETF, portanto, qualquer cliente ou pacote de monitoramento SNMP pode ser usado para recuperar os dados. Para ativar o monitoramento na bridge, descomente esta linha em [.filename]#/etc/snmpd.config# removendo o símbolo inicial `#`: [.programlisting] .... begemotSnmpdModulePath."bridge" = "/usr/lib/snmp_bridge.so" .... Outras configurações, como nomes de comunidades e listas de acesso, podem precisar ser modificadas nesse arquivo. Consulte man:bsnmpd[1] e man:snmp_bridge[3] para maiores informações. Depois que essas edições forem salvas, adicione esta linha ao [.filename]#/etc/rc.conf#: [.programlisting] .... bsnmpd_enable="YES" .... Em seguida, inicie o man:bsnmpd[1]: [source,shell] .... # service bsnmpd start .... Os exemplos a seguir usam o software Net-SNMP (package:net-mgmt/net-snmp[]) para consultar uma bridge a partir de um sistema cliente. O port package:net-mgmt/bsnmptools[] também pode ser usado. Do cliente SNMP que está executando o Net-SNMP, adicione as seguintes linhas ao [.filename]#$HOME/.snmp/snmp.conf# para importar as definições da bridge MIB: [.programlisting] .... mibdirs +/usr/shared/snmp/mibs mibs +BRIDGE-MIB:RSTP-MIB:BEGEMOT-MIB:BEGEMOT-BRIDGE-MIB .... Para monitorar uma única bridge usando o IETF BRIDGE-MIB (RFC4188): [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com mib-2.dot1dBridge BRIDGE-MIB::dot1dBaseBridgeAddress.0 = STRING: 66:fb:9b:6e:5c:44 BRIDGE-MIB::dot1dBaseNumPorts.0 = INTEGER: 1 ports BRIDGE-MIB::dot1dStpTimeSinceTopologyChange.0 = Timeticks: (189959) 0:31:39.59 centi-seconds BRIDGE-MIB::dot1dStpTopChanges.0 = Counter32: 2 BRIDGE-MIB::dot1dStpDesignatedRoot.0 = Hex-STRING: 80 00 00 01 02 4B D4 50 ... BRIDGE-MIB::dot1dStpPortState.3 = INTEGER: forwarding(5) BRIDGE-MIB::dot1dStpPortEnable.3 = INTEGER: enabled(1) BRIDGE-MIB::dot1dStpPortPathCost.3 = INTEGER: 200000 BRIDGE-MIB::dot1dStpPortDesignatedRoot.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedCost.3 = INTEGER: 0 BRIDGE-MIB::dot1dStpPortDesignatedBridge.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedPort.3 = Hex-STRING: 03 80 BRIDGE-MIB::dot1dStpPortForwardTransitions.3 = Counter32: 1 RSTP-MIB::dot1dStpVersion.0 = INTEGER: rstp(2) .... O valor `dot1dStpTopChanges.0` é dois, indicando que a topologia da bridge STP foi alterada duas vezes. Uma alteração de topologia significa que um ou mais links na rede foram alterados ou falharam e uma nova árvore foi calculada. O valor de `dot1dStpTimeSinceTopologyChange.0` será exibido quando isso acontecer. Para monitorar várias interfaces de bridge, o BEGEMOT-BRIDGE-MIB privado pode ser usado: [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com enterprises.fokus.begemot.begemotBridge BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge0" = STRING: bridge0 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge2" = STRING: bridge2 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge0" = STRING: e:ce:3b:5a:9e:13 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge2" = STRING: 12:5e:4d:74:d:fc BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge0" = INTEGER: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge2" = INTEGER: 1 ... BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge0" = Timeticks: (116927) 0:19:29.27 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge2" = Timeticks: (82773) 0:13:47.73 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge0" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge2" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge0" = Hex-STRING: 80 00 00 40 95 30 5E 31 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge2" = Hex-STRING: 80 00 00 50 8B B8 C6 A9 .... Para alterar a interface da bridge que está sendo monitorada através da subárvore `mib-2.dot1dBridge`: [source,shell] .... % snmpset -v 2c -c private bridge1.example.com BEGEMOT-BRIDGE-MIB::begemotBridgeDefaultBridgeIf.0 s bridge2 .... [[network-aggregation]] == Agregação de links e failover O FreeBSD fornece a interface man:lagg[4] que pode ser usada para agregar várias interfaces de rede em uma interface virtual para fornecer failover e agregação de links. O failover permite que o tráfego continue a fluir, desde que pelo menos uma interface de rede agregada tenha um link estabelecido. A agregação de links funciona melhor em switches compatíveis com LACP, pois esse protocolo distribui o tráfego bidirecionalmente ao responder à falha de links individuais. Os protocolos de agregação suportados pela interface lagg determinam quais portas são usadas para o tráfego de saída e se uma porta específica aceita tráfego de entrada. Os seguintes protocolos são suportados pelo man:lagg[4]: failover:: Este modo envia e recebe tráfego somente através da porta principal. Se a porta principal ficar indisponível, a próxima porta ativa será usada. A primeira interface adicionada à interface virtual é a porta principal e todas as interfaces adicionadas posteriormente são usadas como dispositivos de failover. Se ocorrer um failover em uma porta não mestre, a porta original se tornará a principal quando estiver disponível novamente. fec / loadbalance:: Cisco(TM) Fast EtherChannel(TM) (FEC) é encontrado em versões anteriores de switches Cisco (TM). Ele fornece uma configuração estática e não negocia a agregação com o par ou troca quadros para monitorar o link. Se o switch suportar LACP, isso deve ser usado em seu lugar. lacp:: O protocolo de controle de agregação de links IEEE(TM) 802.3ad (LACP) negocia um conjunto de links agregáveis com o peer em um ou mais grupos agregados de links (LAGs). Cada LAG é composto de portas da mesma velocidade, configuradas para operação full-duplex e o tráfego é balanceado entre as portas no LAG com a maior velocidade total. Normalmente, há apenas um LAG que contém todas as portas. No caso de alterações na conectividade física, o LACP convergirá rapidamente para uma nova configuração. + O LACP equilibra o tráfego de saída nas portas ativas com base nas informações de hash do cabeçalho do protocolo e aceita tráfego de entrada de qualquer porta ativa. O hash inclui o endereço Ethernet de origem e destino e, se disponível, a tag VLAN e o endereço de origem e destino IPv4 ou IPv6. roundrobin:: Esse modo distribui o tráfego de saída usando um agendador round-robin por meio de todas as portas ativas e aceita tráfego de entrada de qualquer porta ativa. Como esse modo viola a ordenação de quadros Ethernet, ele deve ser usado com cautela. === Exemplos de configuração Esta seção demonstra como configurar um switch Cisco(TM) e um sistema FreeBSD para balanceamento de carga LACP. Em seguida, ele mostra como configurar duas interfaces Ethernet no modo de failover, além de como configurar o modo de failover entre uma Ethernet e uma interface sem fio. [[networking-lacp-aggregation-cisco]] .Agregação LACP com um switch Cisco(TM) [example] ==== Este exemplo conecta duas interfaces Ethernet man:fxp[4] em uma máquina FreeBSD às duas primeiras portas Ethernet em um switch Cisco(TM) como um link de carga única balanceada e tolerante a falhas. Mais interfaces podem ser adicionadas para aumentar o rendimento e a tolerância a falhas. Substitua os nomes das portas Cisco(TM), dos dispositivos Ethernet, do número do grupo de canais e do endereço IP mostrado no exemplo para corresponder à configuração local. A ordenação de quadros é obrigatória em links Ethernet e qualquer tráfego entre duas estações sempre flui pelo mesmo link físico, limitando a velocidade máxima àquela de uma interface. O algoritmo de transmissão tenta usar o máximo de informações possível para distinguir diferentes fluxos de tráfego e equilibrar os fluxos entre as interfaces disponíveis. No switch Cisco(TM), adicione as interfaces _FastEthernet0/1_ e _FastEthernet0/2_ ao grupo de canais _1_: [source,shell] .... interface FastEthernet0/1 channel-group 1 mode active channel-protocol lacp ! interface FastEthernet0/2 channel-group 1 mode active channel-protocol lacp .... No sistema FreeBSD, crie a interface man:lagg[4] usando as interfaces físicas _fxp0_ e _fxp1_ e suba as interfaces com o endereço IP de _10.0.0.3/24_: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24 .... Em seguida, verifique o status da interface virtual: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.3 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto lacp laggport: fxp1 flags=1c laggport: fxp0 flags=1c .... Portas marcadas como `ACTIVE` fazem parte do LAG que foi negociado com o switch remoto. O tráfego será transmitido e recebido através dessas portas ativas. Adicione `-v` ao comando acima para ver os identificadores LAG. Para ver o status da porta no switch Cisco(TM): [source,shell] .... switch# show lacp neighbor Flags: S - Device is requesting Slow LACPDUs F - Device is requesting Fast LACPDUs A - Device is in Active mode P - Device is in Passive mode Channel group 1 neighbors Partner's information: LACP port Oper Port Port Port Flags Priority Dev ID Age Key Number State Fa0/1 SA 32768 0005.5d71.8db8 29s 0x146 0x3 0x3D Fa0/2 SA 32768 0005.5d71.8db8 29s 0x146 0x4 0x3D .... Para mais detalhes, digite `show lacp neighbor detail`. Para manter esta configuração através de reinicializações, adicione as seguintes entradas ao [.filename]#/etc/rc.conf# no sistema FreeBSD: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24" .... ==== [[networking-lagg-failover]] .Modo de Failover [example] ==== O modo de failover pode ser usado para alternar para uma interface secundária se o link for perdido na interface principal. Para configurar o failover, certifique-se de que as interfaces físicas subjacentes estejam ativadas e crie a interface man:lagg[4]. Neste exemplo, _fxp0_ é a interface principal, _fxp1_ é a interface secundária e a interface virtual recebeu um endereço IP de _10.0.0.15/24_: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24 .... A interface virtual deve ser algo como isto: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.15 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto failover laggport: fxp1 flags=0<> laggport: fxp0 flags=5 .... O tráfego será transmitido e recebido em _fxp0_. Se o link for perdido em _fxp0_, _fxp1_ se tornará o link ativo. Se o link for restaurado na interface principal, ele se tornará novamente o link ativo. Para manter essa configuração através de reinicializações, adicione as seguintes entradas ao [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24" .... ==== [[networking-lagg-wired-and-wireless]] .Modo de failover entre interfaces Ethernet e sem fio [example] ==== Para usuários de laptop, geralmente é desejável configurar o dispositivo sem fio como secundário, que é usado somente quando a conexão Ethernet não está disponível. Com man:lagg[4], é possível configurar um failover que preferia a conexão Ethernet por motivos de desempenho e de segurança, mantendo a capacidade de transferência dados através da conexão sem fio. Isso é obtido substituindo o endereço MAC da interface Ethernet com o da interface wireless. [NOTE] ====== Em teoria, o endereço MAC da Ethernet ou da wireless pode ser alterado para corresponder ao outro. No entanto, algumas interfaces wireless populares não têm suporte para substituir o endereço MAC. Portanto, recomendamos substituir o endereço MAC da Ethernet para esse fim. ====== [NOTE] ====== Se o driver para a interface wireless não estiver carregado no kernel `GENERIC` ou customizado, e o computador estiver rodando o FreeBSD 12.1, carregue o [.filename]#.ko# correspondente no arquivo [.filename]#/boot/loader.conf# adicionando `_driver__load="YES"` e reiniciando a maquina. Outra forma melhor, é carregar o driver no arquivo [.filename]#/etc/rc.conf# adicionando a variável `kld_list` (veja man:rc.conf[5] para maiores detalhes) nesse arquivo e reiniciar. Isso é necessário porque de outra forma o driver não estará carregado no tempo em que a interface man:lagg[4] for configurada. ====== Neste exemplo, a interface Ethernet, _re0_, é a interface principal e a interface sem fio, _wlan0_, é o failover. A interface _wlan0_ foi criada a partir da interface wireless _ath0_, e a interface Ethernet será configurada com o endereço MAC da interface wireless. Primeiro, determine o endereço MAC da interface wireless: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether b8:ee:65:5b:32:59 groups: wlan ssid Bbox-A3BD2403 channel 6 (2437 MHz 11g ht/20) bssid 00:37:b7:56:4b:60 regdomain ETSI country FR indoor ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 2:128-bit txpower 30 bmiss 7 scanvalid 60 protmode CTS ampdulimit 64k ampdudensity 8 shortgi -stbctx stbcrx -ldpc wme burst roaming MANUAL media: IEEE 802.11 Wireless Ethernet MCS mode 11ng status: associated nd6 options=29 .... Substitua _wlan0_ para corresponder ao nome da interface wireless do sistema. A linha `ether` conterá o endereço MAC da interface especificada. Agora, altere o endereço MAC da interface Ethernet subjacente: [source,shell] .... # ifconfig re0 ether b8:ee:65:5b:32:59 .... Suba a interface sem fio (substituindo _FR_ pelo seu próprio código de país com duas letras), mas não defina um endereço IP: [source,shell] .... # ifconfig wlan0 create wlandev ath0 country FR ssid my_router up .... Certifique-se de que a interface _re0_ esteja ativa, então crie a interface man:lagg[4] com a _re0_ como master com failover para a_wlan0_: [source,shell] .... # ifconfig re0 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport re0 laggport wlan0 .... A interface virtual deve ser algo como isto: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether b8:ee:65:5b:32:59 laggproto failover lagghash l2,l3,l4 laggport: re0 flags=5 laggport: wlan0 flags=0<> groups: lagg media: Ethernet autoselect status: active .... Em seguida, inicie o cliente DHCP para obter um endereço IP: [source,shell] .... # dhclient lagg0 .... Para manter essa configuração através de reinicializações, adicione as seguintes entradas ao [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_re0="ether b8:ee:65:5b:32:59" wlans_ath0="wlan0" ifconfig_wlan0="WPA" create_args_wlan0="country FR" cloned_interfaces="lagg0" ifconfig_lagg0="up laggproto failover laggport re0 laggport wlan0 DHCP" .... ==== [[network-diskless]] == Operação Diskless com PXE O Ambiente de execução de pré-inicialização da Intel(TM) (PXE) permite que um sistema operacional inicialize pela rede. Por exemplo, um sistema FreeBSD pode inicializar através da rede e operar sem um disco local, usando sistemas de arquivos montados a partir de um servidor NFS. O suporte para PXE geralmente está disponível no BIOS. Para usar o PXE quando a máquina iniciar, selecione a opção `Inicialização da rede` na configuração do BIOS ou digite uma tecla de função durante a inicialização do sistema. Para fornecer os arquivos necessários para um sistema operacional inicializar pela rede, uma configuração do PXE também requer o DHCP, TFTP configurado corretamente e Servidores NFS, onde: * Parâmetros iniciais, como endereço de IP, nome e localização do arquivo de inicialização executável, nome do servidor e caminho do root são obtidos do servidor DHCP. * O arquivo do carregador do sistema operacional é inicializado usando TFTP. * Os sistemas de arquivos são carregados usando o NFS. Quando um computador PXE inicializa, ele recebe informações por meio do DHCP sobre onde obter o arquivo inicial do carregador de boot. Depois que o computador host recebe essa informação, ele faz o download do carregador de boot via TFTP e, em seguida, executa o carregador de boot. No FreeBSD, o arquivo do gerenciador de boot é o [.filename]#/boot/pxeboot#. Depois que o [.filename]#/boot/pxeboot# é executado, o kernel do FreeBSD é carregado e o resto da seqüência de inicialização do FreeBSD continua, como descrito em crossref:boot[boot, O processo de inicialização do FreeBSD]. Esta seção descreve como configurar estes serviços em um sistema FreeBSD para que outros sistemas possam inicializar o PXE a partir do FreeBSD. Consulte man:diskless[8] para obter maiores informações. [CAUTION] ==== Conforme descrito, o sistema que fornece esses serviços é inseguro. Ele deve ficar em uma área protegida de uma rede e não deve ser considerado confiável por outros hosts. ==== [[network-pxe-nfs]] === Configurando o ambiente PXE As etapas mostradas nesta seção configuram os servidores internos de NFS e TFTP. A próxima seção demonstra como instalar e configurar o servidor DHCP. Neste exemplo, o diretório que conterá os arquivos usados pelos usuários do PXE é o [.filename]#/b/tftpboot/FreeBSD/install#. É importante que este diretório exista e que o mesmo nome de diretório seja configurado no [.filename]#/etc/inetd.conf# e no [.filename]#/usr/local/etc/dhcpd.conf#. [.procedure] ==== . Crie o diretório raiz que irá conter uma instalação do FreeBSD para ser montado por NFS: + [source,shell] .... # export NFSROOTDIR=/b/tftpboot/FreeBSD/install # mkdir -p ${NFSROOTDIR} .... + . Ative o servidor NFS adicionando esta linha ao [.filename]#/etc/rc.conf#: + [.programlisting] .... nfs_server_enable="YES" .... + . Exporte o diretório raiz sem disco via NFS adicionando o seguinte ao [.filename]#/etc/exports#: + [.programlisting] .... /b -ro -alldirs -maproot=root .... + . Inicie o servidor NFS: + [source,shell] .... # service nfsd start .... + . Ative o man:inetd[8] adicionando a seguinte linha ao [.filename]#/etc/rc.conf#: + [.programlisting] .... inetd_enable="YES" .... + . Descomente a seguinte linha no [.filename]#/etc/inetd.conf# certificando-se de que ela não comece com um símbolo `#`: + [.programlisting] .... tftp dgram udp wait root /usr/libexec/tftpd tftpd -l -s /b/tftpboot .... + [NOTE] ====== Algumas versões do PXE exigem a versão TCP do TFTP. Neste caso, remova o comentário da segunda linha `tftp` que contém `stream tcp`. ====== + . Inicie o man:inetd[8]: + [source,shell] .... # service inetd start .... + . Instale o sistema básico em [.filename]#${NFSROOTDIR}#, seja descompactando os arquivos oficiais ou recompilando o kernel do FreeBSD e o userland (consulte crossref:cutting-edge[makeworld,Atualizando o FreeBSD a partir do código fonte] para instruções mais detalhadas, mas não esqueça de adicionar `DESTDIR=_${NFSROOTDIR}_` ao executar os comandos `make installkernel` e `make installworld`. . Teste que o servidor TFTP funciona e que pode baixar o gerenciador de boot que será obtido via PXE: + [source,shell] .... # tftp localhost tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... + . Edite o [.filename]#${NFSROOTDIR}/etc/fstab# e crie uma entrada para montar o sistema de arquivos raiz por meio do NFS: + [.programlisting] .... # Device Mountpoint FSType Options Dump Pass myhost.example.com:/b/tftpboot/FreeBSD/install / nfs ro 0 0 .... + Substitua _myhost.example.com_ pelo nome do host ou pelo endereço IP do servidor NFS. Neste exemplo, o sistema de arquivos raiz é montado como somente leitura para evitar que os clientes do NFS excluam potencialmente o conteúdo do sistema de arquivos raiz. . Defina a senha de root no ambiente PXE para as máquinas clientes que serão inicializadas por PXE: + [source,shell] .... # chroot ${NFSROOTDIR} # passwd .... + . Se necessário, ative o login do root via man:ssh[1] para as máquinas clientes que estão inicializando por PXE editando o [.filename]#${NFSROOTDIR}/etc/ssh/sshd_config# e habilitando o `PermitRootLogin`. Esta opção está documentada em man:sshd_config[5]. . Execute qualquer outra customização necessária do ambiente PXE no [.filename]#${NFSROOTDIR}#. Estas customizações podem incluir coisas como instalar pacotes ou editar o arquivo de senha com o man:vipw[8]. ==== Ao inicializar de um volume raiz NFS, o [.filename]#/etc/rc# detecta a inicialização do NFS e executa o [.filename]#/etc/rc.initdiskless#. Neste caso, o [.filename]#/etc# e [.filename]#/var# precisam ser sistemas de arquivos montados em memória para que estes diretórios sejam graváveis mas o diretório raiz NFS seja apenas de leitura: [source,shell] .... # chroot ${NFSROOTDIR} # mkdir -p conf/base # tar -c -v -f conf/base/etc.cpio.gz --format cpio --gzip etc # tar -c -v -f conf/base/var.cpio.gz --format cpio --gzip var .... Quando o sistema inicializar, os sistemas de arquivos em memória para o [.filename]#/etc# e o [.filename]#/var# serão criados e montados e o conteúdo dos arquivos [.filename]#cpio.gz# será copiado para eles. Por padrão, esses sistemas de arquivos têm uma capacidade máxima de 5 megabytes. Se seus arquivos não couberem, o que geralmente é o caso do [.filename]#/var# quando pacotes binários foram instalados, solicite um tamanho maior colocando o número de setores de 512 bytes necessários (por exemplo, 5 megabytes é 10240 setores) nos arquivos [.filename]#${NFSROOTDIR}/conf/base/etc/md_size# e [.filename]#${NFSROOTDIR}/conf/base/var/md_size# para os sistemas de arquivos [.filename]#/etc# e o [.filename]#/var# respectivamente. [[network-pxe-setting-up-dhcp]] === Configurando o servidor DHCP O servidor DHCP não precisa ser a mesma máquina que o servidor TFTP e NFS, mas ele precisa estar acessível na rede. -O DHCP não faz parte do sistema básico do FreeBSD, mas pode ser instalado usando o port ou pacote package:net/isc-dhcp43-server[]. +O DHCP não faz parte do sistema básico do FreeBSD, mas pode ser instalado usando o port ou pacote package:net/isc-dhcp44-server[]. Uma vez instalado, edite o arquivo de configuração, [.filename]#/usr/local/etc/dhcpd.conf#. Configure as diretivas `next-server`, `filename` e `root-path` conforme mostrado neste exemplo: [.programlisting] .... subnet 192.168.0.0 netmask 255.255.255.0 { range 192.168.0.2 192.168.0.3 ; option subnet-mask 255.255.255.0 ; option routers 192.168.0.1 ; option broadcast-address 192.168.0.255 ; option domain-name-servers 192.168.35.35, 192.168.35.36 ; option domain-name "example.com"; # IP address of TFTP server next-server 192.168.0.1 ; # path of boot loader obtained via tftp filename "FreeBSD/install/boot/pxeboot" ; # pxeboot boot loader will try to NFS mount this directory for root FS option root-path "192.168.0.1:/b/tftpboot/FreeBSD/install/" ; } .... A diretiva `next-server` é usada para especificar o endereço IP do servidor TFTP. A diretiva `filename` define o caminho para o [.filename]#/boot/pxeboot#. Um nome de arquivo relativo é usado, significando que [.filename]#/b/tftpboot# não está incluído no caminho. A diretiva `root-path` define o caminho para o sistema de arquivos raiz a ser montado por NFS. Depois que as edições forem salvas, ative o DHCP no momento da inicialização adicionando a seguinte linha ao [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" .... Então inicie o serviço DHCP: [source,shell] .... # service isc-dhcpd start .... === Depurando problemas de PXE Uma vez que todos os serviços estejam configurados e iniciados, os clientes de PXE devem poder carregar automaticamente o FreeBSD pela rede. Se um determinado cliente não conseguir se conectar, quando a máquina cliente inicializar, entre no menu de configuração da BIOS e confirme se ela está configurada para inicializar a partir da rede. Esta seção descreve algumas dicas de solução de problemas para isolar a origem do problema de configuração, caso nenhum cliente seja capaz de inicializar o PXE. [.procedure] ==== . Use o pacote ou port package:net/wireshark[] para depurar o tráfego de rede envolvido durante o processo de inicialização do PXE, que está ilustrado no diagrama abaixo. + .Processo de inicialização PXE com o sistema de arquivos raiz montado por NFS image::pxe-nfs.png[] + . No servidor TFTP, leia o [.filename]#/var/log/xferlog# para garantir que o [.filename]#pxeboot# esteja sendo recuperado do local correto. Para testar esta configuração de exemplo: + [source,shell] .... # tftp 192.168.0.1 tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... + As seções de `BUGS` do man:tftpd[8] e man:tftp[1] documenta algumas limitações com o TFTP. . Certifique-se de que o sistema de arquivos raiz possa ser montado via NFS. Para testar esta configuração de exemplo: + [source,shell] .... # mount -t nfs 192.168.0.1:/b/tftpboot/FreeBSD/install /mnt .... ==== [[network-ipv6]] == IPv6 O IPv6 é a nova versão do conhecido protocolo IP, também conhecido como IPv4. O IPv6 oferece várias vantagens sobre o IPv4, além de muitos recursos novos: * Seu espaço de endereços de 128 bits permite 340.282.366.920.938.463.463.374.607.431.768.211.456 endereços. Isso corrige a falta de endereços do IPv4 e o eventual esgotamento do endereço de IPv4. * Os roteadores armazenam apenas endereços de agregação de rede em suas tabelas de roteamento, reduzindo assim o espaço médio de uma tabela de roteamento para 8192 entradas. Isso resolve os problemas de escalabilidade associados ao IPv4, que exigia que cada bloco alocado de endereços IPv4 fossem trocados entre roteadores da Internet, fazendo com que suas tabelas de roteamento ficassem muito grandes para permitir um roteamento eficiente . * Autoconfiguração de endereço (http://www.ietf.org/rfc/rfc2462.txt[RFC2462]). * Endereços multicast obrigatórios. * IPsec Embutido (Segurança IP). * Estrutura simplificada do cabeçalho. * Suporte para mobile IP. * Mecanismos de transição IPv6-to-IPv4. O FreeBSD inclui a implementação de referência do http://www.kame.net/[http://www.kame.net/]IPv6 e vem com tudo necessário usar o IPv6. Esta seção se concentra em configurar e executar o IPv6. === Informações sobre endereços de IPv6 Existem três tipos diferentes de endereços de IPv6: Unicast:: Um pacote enviado para um endereço unicast chega à interface pertencente ao endereço. Anycast:: Esses endereços são sintaticamente indistinguíveis dos endereços unicast, mas eles tratam de um grupo de interfaces. O pacote destinado a um endereço anycast chegará à interface do roteador mais próxima. Endereços anycast são usados apenas por roteadores. Multicast:: Esses endereços identificam um grupo de interfaces. Um pacote destinado a um endereço multicast chegará a todas as interfaces pertencentes ao grupo multicast. O endereço de broadcast IPv4 , geralmente `xxx.xxx.xxx.255`, é expresso por endereços multicast em IPv6. Ao ler um endereço IPv6, a forma canônica é representada como `x:x:x:x:x:x:x:x`, onde cada `x` representa um valor hexadecimal de 16 bits. Um exemplo é `FEBC:A574:382B:23C1:AA49:4592:4EFE:9982`. Muitas vezes, um endereço terá substrings longas apenas com zeros. Um `::` (dois-pontos duplos) pode ser usado para substituir uma subcadeia por endereço. Além disso, até três valores ``0``s iniciais por valor hexadecimal podem ser omitidos. Por exemplo, `fe80::1` corresponde à forma canônica `fe80:0000:0000:0000:0000:0000:0000:0001`. Uma terceira forma é escrever os últimos 32 bits usando a conhecida notação IPv4. Por exemplo, `2002::10.0.0.1` corresponde à representação canônica hexadecimal `2002:0000:0000:0000:0000:0000:0a00:0001`, que por sua vez é equivalente a `2002::a00:1`. Para visualizar o endereço IPv6 do sistema FreeBSD, use man:ifconfig[8]: [source,shell] .... # ifconfig .... [.programlisting] .... rl0: flags=8943 mtu 1500 inet 10.0.0.10 netmask 0xffffff00 broadcast 10.0.0.255 inet6 fe80::200:21ff:fe03:8e1%rl0 prefixlen 64 scopeid 0x1 ether 00:00:21:03:08:e1 media: Ethernet autoselect (100baseTX ) status: active .... Neste exemplo, a interface [.filename]#rl0# está usando `fe80::200:21ff:fe03:8e1%rl0`, um endereço local de link auto-configurado que foi gerado automaticamente a partir do endereço MAC. Alguns endereços do IPv6 são reservados. Um resumo destes endereços reservados é visto em <>: [[reservedip6]] .Endereços IPv6 reservados [cols="1,1,1,1", frame="none", options="header"] |=== | endereço IPv6 | Prefixlength (Bits) | Descrição | Notas |`::` |128 bits |não especificado |Equivalente a `0.0.0.0` em IPv4. |`::1` |128 bits |endereço de loopback |Equivalente ao `127.0.0.1` no IPv4. |`::00:xx:xx:xx:xx` |96 bits |IPv4 Embarcado |Os 32 bits inferiores são o endereço IPv4 compatível. |`::ff:xx:xx:xx:xx` |96 bits |O endereço IPv4 mapeado do endereço IPv6 |Os 32 bits mais baixos são o endereço IPv4 para hosts que não suportam o IPv6. |`fe80::/10` |10 bits |link-local |Equivalente a 169.254.0.0/16 em IPv4. |`fc00::/7` |7 bits |unique-local |Endereços locais exclusivos são destinados à comunicação local e só podem ser roteados dentro de um conjunto de sites cooperantes. |`ff00::` |8 bits |multicast | |`2000::-3fff::` |3 bits |unicast global |Todos os endereços unicast globais são atribuídos a partir desse pool. Os primeiros 3 bits são `001`. |=== Para maiores informações sobre a estrutura dos endereços do IPv6, consulte a http://www.ietf.org/rfc/rfc3513.txt[RFC3513]. === Configurando o IPv6 Para configurar um sistema FreeBSD como um cliente IPv6, adicione estas duas linhas ao [.filename]#rc.conf#: [.programlisting] .... ifconfig_rl0_ipv6="inet6 accept_rtadv" rtsold_enable="YES" .... A primeira linha permite que a interface especificada receba mensagens de solicitação do roteador. A segunda linha ativa o daemon de solicitação do roteador, man:rtsol[8]. Se a interface precisar de um endereço IPv6 atribuído estaticamente, adicione uma entrada para especificar o endereço estático e o comprimento do prefixo associado: [.programlisting] .... ifconfig_rl0_ipv6="inet6 2001:db8:4672:6565:2026:5043:2d42:5344 prefixlen 64" .... Para atribuir um roteador padrão, especifique seu endereço: [.programlisting] .... ipv6_defaultrouter="2001:db8:4672:6565::1" .... === Conectando-se a um provedor Para se conectar a outras redes IPv6, é necessário ter um provedor ou um túnel que suporte IPv6: * Entre em contato com um provedor de serviços de Internet para saber se eles oferecem IPv6. * O http://www.tunnelbroker.net[Hurricane Electric] oferece túneis com endpoints em todo o mundo. [NOTE] ==== Instale o pacote ou port package:net/freenet6[] para uma conexão dial-up. ==== Esta seção demonstra como obter as direções de um provedor de túneis e convertê-las em configurações do [.filename]#/etc/rc.conf# que persistirão durante as reinicializações. A primeira entrada [.filename]#/etc/rc.conf# cria a interface de encapsulamento genérica [.filename]#gif0#: [.programlisting] .... cloned_interfaces="gif0" .... Em seguida, configure essa interface com os endereços IPv4 dos pontos de extremidade locais e remotos. Substitua _MY_IPv4_ADDR_ e _REMOTE_IPv4_ADDR_ pelos endereços atuais de IPv4: [.programlisting] .... create_args_gif0="tunnel MY_IPv4_ADDR REMOTE_IPv4_ADDR" .... Para aplicar o endereço IPv6 que foi atribuído para uso como o ponto final do túnel IPv6, adicione esta linha, substituindo _MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR_ pelo endereço atribuído: [.programlisting] .... ifconfig_gif0_ipv6="inet6 MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR" .... Em seguida, defina a rota padrão para o outro lado do túnel IPv6. Substitua _MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR_ pelo endereço do gateway padrão atribuído pelo provedor: [.programlisting] .... ipv6_defaultrouter="MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR" .... Se o sistema FreeBSD irá rotear pacotes IPv6 entre o resto da rede e o mundo, habilite o gateway usando esta linha: [.programlisting] .... ipv6_gateway_enable="YES" .... === Anúncio do roteador e configuração automática do host Esta seção demonstra como configurar o man:rtadvd[8] para anunciar a rota padrão de IPv6. Para ativar man:rtadvd[8], inclua o seguinte no [.filename]#/etc/rc.conf#: [.programlisting] .... rtadvd_enable="YES" .... É importante especificar a interface na qual fazer a solicitação do roteador IPv6. Por exemplo, para informar o man:rtadvd[8] para usar [.filename]#rl0#: [.programlisting] .... rtadvd_interfaces="rl0" .... Em seguida, crie o arquivo de configuração, [.filename]#/etc/rtadvd.conf# como visto neste exemplo: [.programlisting] .... rl0:\ :addrs#1:addr="2001:db8:1f11:246::":prefixlen#64:tc=ether: .... Substitua [.filename]#rl0# com a interface a ser usada e `2001:db8:1f11:246::` com o prefixo da alocação. Para uma sub-rede `/64` dedicada, nada mais precisa ser alterado. Caso contrário, altere o `prefixlen#` para o valor correto. === IPv6 e o mapeamento de endereços IPv6 Quando o IPv6 está habilitado em um servidor, pode ser necessário ativar a comunicação de endereços IPv4 mapeados para IPv6. Esta opção de compatibilidade permite que endereços IPv4 sejam representados como endereços de IPv6. Permitir que aplicativos IPv6 se comuniquem com IPv4 e vice-versa pode ser um problema de segurança. Essa opção pode não ser necessária na maioria dos casos e está disponível apenas para compatibilidade. Esta opção permitirá que os aplicativos que suportam apenas o IPv6 funcionem com IPv4 em um ambiente de pilha dupla. Isso é mais útil para aplicativos de terceiros que podem não suportar um ambiente somente de IPv6. Para habilitar esse recurso, adicione o seguinte ao [.filename]#/etc/rc.conf#: [.programlisting] .... ipv6_ipv4mapping="YES" .... Revisar as informações da RFC 3493, seção 3.6 e 3.7, bem como da RFC 4038 seção 4.2, pode ser útil para alguns administradores. [[carp]] == Protocolo Comum de Redundância de Endereços (CARP) O Protocolo Comum de Redundância de Endereços (CARP) permite que vários hosts compartilhem o mesmo endereço IP e ID de Host Virtual (VHID) para fornecer _alta disponibilidade_ para um ou mais serviços. Isso significa que um ou mais hosts podem falhar e os outros hosts assumem o controle de modo transparente, de modo que os usuários não percebam uma falha de serviço. Além do endereço IP compartilhado, cada host tem seu próprio endereço IP para gerenciamento e configuração. Todas as máquinas que compartilham um endereço IP têm o mesmo VHID. O VHID para cada endereço virtual de IP deve ser exclusivo no domínio de broadcast da interface de rede. A alta disponibilidade usando o CARP é nativa no FreeBSD, embora os passos para configurá-lo variem um pouco dependendo da versão do FreeBSD. Esta seção fornece a mesma configuração de exemplo para versões anteriores, iguais ou posteriores ao FreeBSD 10. Este exemplo configura o suporte a failover com três hosts, todos com endereços exclusivos de IP, mas que fornecem o mesmo conteúdo da web. Ele tem dois mestres diferentes chamados `hosta.example.org` e `hostb.example.org`, com um backup compartilhado chamado `hostc.example.org`. O balanceamento de carga destas máquinas é feito por meio de uma configuração de DNS Round Robin. As máquinas principais e de backup são configuradas de forma idêntica, exceto por seus nomes de host e endereços de gerenciamento IP. Esses servidores devem ter a mesma configuração e executar os mesmos serviços. Quando o failover ocorre, as solicitações para o serviço no endereço IP compartilhado só podem ser respondidas corretamente se o servidor de backup tiver acesso ao mesmo conteúdo. A máquina de backup tem duas interfaces CARP adicionais, uma para cada endereço IP do servidor de conteúdo mestre. Quando ocorre uma falha, o servidor de backup selecionará o endereço IP da máquina mestre com falha. [[carp-10x]] === Usando CARP no FreeBSD 10 e Posteriores Ative o suporte para CARP na inicialização do sistema, adicionando uma entrada para o módulo do kernel [.filename]#carp.ko# em [.filename]#/boot/loader.conf#: [.programlisting] .... carp_load="YES" .... Para carregar o módulo agora sem reiniciar: [source,shell] .... # kldload carp .... Para usuários que preferem usar um kernel personalizado, inclua a seguinte linha no arquivo de configuração do kernel personalizado e compile o kernel como descrito em crossref:kernelconfig[kernelconfig, Configurando o kernel do FreeBSD]: [.programlisting] .... device carp .... O nome do host, o endereço IP de gerenciamento e a máscara de sub-rede, o endereço IP compartilhado e o VHID são definidos adicionando entradas ao [.filename]#/etc/rc.conf#. Este exemplo é para o `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_em0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 pass testpass alias 192.168.1.50/32" .... O próximo conjunto de entradas é para o `hostb.example.org`. Como ele representa um segundo mestre, ele usa um endereço IP compartilhado diferente e VHID. No entanto, as senhas especificadas com `pass` devem ser idênticas, pois o CARP somente ouvirá e aceitará anúncios de máquinas com a senha correta. [.programlisting] .... hostname="hostb.example.org" ifconfig_em0="inet 192.168.1.4 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 2 pass testpass alias 192.168.1.51/32" .... A terceira máquina, `hostc.example.org`, é configurada para lidar com o failover de um dos mestres. Esta máquina é configurada com dois CARPVHIDs, um para manipular o endereço IP virtual para cada um dos hosts principais. O desvio de publicidade CARP, `advskew`, é definida para garantir que o host de backup seja anunciado depois do mestre, pois `advskew` controla a ordem de precedência quando existem vários servidores de backup. [.programlisting] .... hostname="hostc.example.org" ifconfig_em0="inet 192.168.1.5 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 advskew 100 pass testpass alias 192.168.1.50/32" ifconfig_em0_alias1="inet vhid 2 advskew 100 pass testpass alias 192.168.1.51/32" .... Ter dois CARPVHIDs configurados significa que o `hostc.example.org` notará se um dos servidores principais ficar indisponível. Se um mestre falhar em anunciar antes do servidor de backup, o servidor de backup selecionará o endereço IP compartilhado até que o mestre se torne disponível novamente. [NOTE] ==== Se o servidor mestre original se tornar disponível novamente, o `hostc.example.org` não liberará o endereço virtual IP de volta a ele automaticamente. Para que isso aconteça, a preempção deve ser ativada. O recurso está desabilitado por padrão, ele é controlado por meio da variável man:sysctl[8]`net.inet.carp.preempt`. O administrador pode forçar o servidor de backup a retornar o endereço IP para o mestre: [source,shell] .... # ifconfig em0 vhid 1 state backup .... ==== Quando a configuração estiver concluída, reinicie a rede ou reinicie cada um dos sistemas. A alta disponibilidade está agora ativada. A funcionalidade CARP pode ser controlada através de diversas variáveis man:sysctl[8] documentadas nas páginas de manual do man:carp[4]. Outras ações podem ser acionadas a partir de eventos CARP usando man:devd[8]. [[carp-9x]] === Usando CARP no FreeBSD 9 e Anteriores A configuração para estas versões do FreeBSD é similar àquela descrita na seção anterior, exceto que o dispositivo CARP deve ser criado primeiro e referenciado na configuração. Ative o suporte de tempo de inicialização para o CARP carregando o módulo do kernel [.filename]#if_carp.ko# no [.filename]#/boot/loader.conf#: [.programlisting] .... if_carp_load="YES" .... Para carregar o módulo agora sem reiniciar: [source,shell] .... # kldload carp .... Para usuários que preferem usar um kernel personalizado, inclua a seguinte linha no arquivo de configuração do kernel personalizado e compile o kernel como descrito em crossref:kernelconfig[kernelconfig, Configurando o kernel do FreeBSD]: [.programlisting] .... device carp .... Em seguida, em cada host, crie um dispositivo CARP: [source,shell] .... # ifconfig carp0 create .... Defina o nome do host, o endereço IP de gerenciamento, o endereço IP compartilhado e o VHID adicionando as linhas necessárias ao [.filename]#/etc/rc.conf#. Como um dispositivo virtual CARP é usado em vez de um alias, uma máscara de subrede real `/24` é usada em vez de uma `/32`. Aqui estão as entradas para o `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_fxp0="inet 192.168.1.3 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 1 pass testpass 192.168.1.50/24" .... Em `hostb.example.org`: [.programlisting] .... hostname="hostb.example.org" ifconfig_fxp0="inet 192.168.1.4 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 2 pass testpass 192.168.1.51/24" .... A terceira máquina, `hostc.example.org`, está configurada para lidar com o failover de qualquer um dos hosts principais: [.programlisting] .... hostname="hostc.example.org" ifconfig_fxp0="inet 192.168.1.5 netmask 255.255.255.0" cloned_interfaces="carp0 carp1" ifconfig_carp0="vhid 1 advskew 100 pass testpass 192.168.1.50/24" ifconfig_carp1="vhid 2 advskew 100 pass testpass 192.168.1.51/24" .... [NOTE] ==== A preempção está desabilitada no kernel [.filename]#GENERIC# do FreeBSD. Se a preempção tiver sido ativada com um kernel personalizado, o `hostc.example.org` poderá não liberar o endereço IP de volta ao servidor de conteúdo original. O administrador pode forçar o servidor de backup a retornar o endereço IP para o mestre com o comando: [source,shell] .... # ifconfig carp0 down && ifconfig carp0 up .... Isso deve ser feito na interface [.filename]#carp#, que corresponde ao host correto. ==== Quando a configuração estiver concluída, reinicie a rede ou reinicie cada um dos sistemas. A alta disponibilidade está agora ativada. [[network-vlan]] == VLANs As VLANs são uma forma de dividir virtualmente uma rede em várias sub-redes diferentes, também conhecida como segmentação. Cada segmento terá seu próprio domínio de broadcast e será isolado de outras VLANs. No FreeBSD, as VLANs devem ser suportadas pelo driver da placa de rede. Para ver quais drivers suportam vlans, consulte a página de manual man:vlan[4]. Ao configurar uma VLAN, algumas informações devem ser conhecidas. Primeiro, qual a interface de rede? Segundo, qual é a tag da VLAN? Para configurar uma VLANs em tempo de execução, com uma NIC `em0` e uma tag VLAN de `5` o comando ficaria assim: [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 inet 192.168.20.20/24 .... [NOTE] ==== Viu como o nome da interface inclui o nome do driver da NIC e a tag VLAN, separados por um ponto final? Essa é uma prática recomendada para facilitar a manutenção da configuração de VLAN quando muitas VLANs estiverem presentes em uma máquina. ==== Para configurar uma VLANs no momento da inicialização, o [.filename]#/etc/rc.conf# deve ser atualizado. Para duplicar a configuração acima, será necessário adicionar o seguinte: [.programlisting] .... vlans_em0="5" ifconfig_em0_5="inet 192.168.20.20/24" .... VLANs adicionais podem ser inseridas, simplesmente adicionando a tag ao campo `vlans_em0` e incrementando uma linha de configuração da rede nessa interface da tag VLAN. É útil atribuir um nome simbólico a uma interface para que, quando o hardware associado for alterado, apenas algumas variáveis de configuração precisem ser atualizadas. Por exemplo, câmeras de segurança precisam ser executadas pela VLAN 1 em `em0`. Posteriormente, se a placa `em0` for substituída por uma placa que use o driver man:ixgb[4], todas as referências a `em0.1` não precisarão ser alterado para `ixgb0.1`. Para configurar a VLAN `5`, na NIC `em0`, atribua o nome de interface `cameras`, e atribua à interface um endereço IP de `_192.168.20.20_` com um prefixo `24`-bit, use este comando: [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 name cameras inet 192.168.20.20/24 .... Para uma interface denominada `video`, use o seguinte: [source,shell] .... # ifconfig video.5 create vlan 5 vlandev video name cameras inet 192.168.20.20/24 .... Para aplicar as mudanças no momento da inicialização, adicione as seguintes linhas ao [.filename]#/etc/rc.conf#: [.programlisting] .... vlans_video="cameras" create_args_cameras="vlan 5" ifconfig_cameras="inet 192.168.20.20/24" .... diff --git a/documentation/content/pt-br/books/handbook/network-servers/_index.adoc b/documentation/content/pt-br/books/handbook/network-servers/_index.adoc index 74b2f143f9..80a6b6f137 100644 --- a/documentation/content/pt-br/books/handbook/network-servers/_index.adoc +++ b/documentation/content/pt-br/books/handbook/network-servers/_index.adoc @@ -1,2548 +1,2548 @@ --- title: Capítulo 29. Servidores de Rede part: Parte IV. Comunicação de rede prev: books/handbook/mail next: books/handbook/firewalls showBookMenu: true weight: 34 path: "/books/handbook/" --- [[network-servers]] = Servidores de Rede :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 29 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/network-servers/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[network-servers-synopsis]] == Sinopse Este capítulo aborda alguns dos serviços de rede usados com mais frequência em sistemas UNIX(TM). Isso inclui instalar, configurar, testar e manter muitos tipos diferentes de serviços de rede. Exemplos de arquivos de configuração estão incluídos neste capítulo para referência. No final deste capítulo, os leitores saberão: * Como gerenciar o daemon inetd. * Como configurar o Network File System (NFS). * Como configurar o Network Information Server (NIS) para centralizar e compartilhar contas de usuários. * Como configurar o FreeBSD para funcionar como um servidor ou cliente LDAP * Como configurar configurações de rede automáticas usando o DHCP. * Como configurar um Domain Name Server (DNS). * Como configurar o servidor ApacheHTTP. * Como Configurar um Servidor de File Transfer Protocol (FTP). * Como configurar um servidor de arquivo e de impressão para clientes Windows(TM) usando o Samba. * Como sincronizar a hora e a data e configurar um servidor de horário usando o Network Time Protocol (NTP). * Como configurar o iSCSI. Este capítulo pressupõe um conhecimento básico de: * scripts [.filename]#/etc/rc#. * Terminologia de rede. * Instalação de software adicional de terceiros (crossref:ports[ports, Instalando Aplicativos. Pacotes e Ports]). [[network-inetd]] == O super-servidor inetd O daemon man:inetd[8] é algumas vezes chamado de Super-Servidor porque gerencia conexões para muitos serviços. Em vez de iniciar vários aplicativos, apenas o serviço inetd precisa ser iniciado. Quando uma conexão é recebida para um serviço gerenciado pelo inetd, ele determina para qual programa a conexão está destinada, gera um processo para esse programa e delega ao programa um socket. O uso de inetd para serviços que não são muito usados pode reduzir a carga do sistema, quando comparado à execução de cada daemon individualmente no modo independente. Primeiramente, inetd é usado para gerar outros daemons, mas vários protocolos triviais são tratados internamente, como chargen, auth, time, echo, discard e daytime. Esta seção aborda os conceitos básicos da configuração do inetd. [[network-inetd-conf]] === Arquivo de Configuração A configuração do inetd é feita editando o [.filename]#/etc/inetd.conf#. Cada linha deste arquivo de configuração representa um aplicativo que pode ser iniciado pelo inetd. Por padrão, cada linha começa com um comentário (`#`), o que significa que inetd não está atendendo a nenhum aplicativo. Para configurar o inetd para escutar as conexões de um aplicativo, remova o `#` no início da linha desse aplicativo. Depois de salvar suas edições, configure o inetd para iniciar na inicialização do sistema editando o arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... inetd_enable="YES" .... Para iniciar o inetd agora, para que ele ouça o serviço que você configurou, digite: [source,shell] .... # service inetd start .... Uma vez iniciado o inetd, ele precisa ser notificado sempre que uma modificação for feita no arquivo [.filename]#/etc/inetd.conf#: [[network-inetd-reread]] .Recarregando o Arquivo de Configuração do inetd [example] ==== [source,shell] .... # service inetd reload .... ==== Normalmente, a entrada padrão de um aplicativo não precisa ser editada além da remoção do `#`. Em algumas situações, pode ser apropriado editar a entrada padrão. Como exemplo, esta é a entrada padrão para man:ftpd[8] sobre o IPv4: [.programlisting] .... ftp stream tcp nowait root /usr/libexec/ftpd ftpd -l .... As sete colunas em uma entrada são as seguintes: [.programlisting] .... service-name socket-type protocol {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]] user[:group][/login-class] server-program server-program-arguments .... Onde: service-name:: O nome do serviço do daemon para iniciar. Deve corresponder a um serviço listado no arquivo [.filename]#/etc/services#. Isso determina qual porta inetd atende para conexões de entrada para esse serviço. Ao usar um serviço personalizado, ele deve primeiro ser adicionado ao arquivo [.filename]#/etc/services#. socket-type:: Ou `stream`, `dgram`, `raw`, ou `seqpacket`. Use `stream` para conexões TCP e `dgram` para serviços UDP. protocol:: Use um dos seguintes nomes de protocolo: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Protocol Name | Explicação |tcp ou tcp4 |TCP IPv4 |udp ou udp4 |UDP IPv4 |tcp6 |TCP IPv6 |udp6 |UDP IPv6 |tcp46 |Ambos TCP IPv4 e IPv6 |udp46 |Ambos UDP IPv4 e IPv6 |=== {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]]:: Neste campo, `wait` ou `nowait` deve ser especificado. `max-child`, `max-connections-per-ip-por-minute` e `max-child-per-ip` são opcionais. + `wait|nowait` indica se o serviço pode ou não manipular seu próprio socket. Os tipos de socket `dgram` devem usar `wait` enquanto os daemons `stream`, que geralmente são multi-threaded, devem usar `nowait`. `wait` geralmente passa vários sockets para um único daemon, enquanto `nowait` gera um daemon filho para cada novo socket. + O número máximo de daemons inetd que podem aparecer é definido por `max-child`. Por exemplo, para limitar dez instâncias do daemon, coloque um `/10` após o `nowait`. Especificar `/0` permite um número ilimitado de filhos. + `max-connections-per-ip-per-minute` limita o número de conexões de qualquer endereço específico de IP por minuto. Quando o limite for atingido, outras conexões desse endereço IP serão descartadas até o final do minuto. Por exemplo, um valor de `/10` limitaria qualquer endereço IP específico a dez tentativas de conexão por minuto. `max-child-per-ip` limita o número de processos-filhos que podem ser iniciados em nome de um único endereço IP a qualquer momento. Essas opções podem limitar o consumo excessivo de recursos e ajudar a impedir ataques de negação de serviço (DoS (Denial Of Service)). + Um exemplo pode ser visto nas configurações padrão para man:fingerd[8]: + [.programlisting] .... finger stream tcp nowait/3/10 nobody /usr/libexec/fingerd fingerd -k -s .... usuário:: O nome de usuário que o daemon será executado como. Daemons geralmente são executados como `root`, `daemon`, ou `nobody`. programa servidor:: O caminho completo para o daemon. Se o daemon for um serviço fornecido pelo inetd internamente, use `internal`. argumentos do programa servidor:: Usado para especificar qualquer argumento de comando a ser transmitido ao daemon na chamada. Se o daemon for um serviço interno, use `internal`. [[network-inetd-cmdline]] === Opções de linha de comando Como a maioria dos daemons de servidor, o inetd tem várias opções que podem ser usadas para modificar seu comportamento. Por padrão, inetd é iniciado com `-wW -C 60`. Essas opções ativam TCP wrappers para todos os serviços, incluindo serviços internos, e impedem que qualquer endereço de IP solicite qualquer serviço mais de 60 vezes por minuto. Para alterar as opções padrão que são passadas para inetd, adicione uma entrada para `inetd_flags` no arquivo [.filename]#/etc/rc.conf#. Se o inetd já estiver em execução, reinicie-o com `service inetd restart`. As opções disponíveis de limitação de taxa são: -c máximo:: Especifique o número máximo padrão de chamadas simultâneas de cada serviço, em que o padrão é ilimitado. Pode ser sobrescrito com base no serviço usando `max-child` em [.filename]#/etc/inetd.conf#. -C taxa:: Especifique o número máximo padrão de vezes por minuto que um serviço pode ser chamado a partir de um único endereço de IP. Pode ser substituído com base no serviço usando `max-connections-per-ip-por-minute` em [.filename]#/etc/inetd.conf#. -R taxa:: Especifique o número máximo de vezes que um serviço pode ser chamado em um minuto, em que o padrão é `256`. Uma taxa de `0` permite um número ilimitado. -s máximo:: Especifique o número máximo de vezes que um serviço pode ser chamado a partir de um único endereço IP a qualquer momento, em que o padrão é ilimitado. Pode ser sobrescrito com base no serviço usando `max-child-per-ip` no arquivo [.filename]#/etc/inetd.conf#. Opções adicionais estão disponíveis. Consulte man:inetd[8] para a lista completa de opções. [[network-inetd-security]] === Considerações de segurança Muitos dos daemons que podem ser gerenciados pelo inetd não são conscientes da segurança. Alguns daemons, como fingerd, podem fornecer informações que podem ser úteis para um invasor. Ative apenas os serviços necessários e monitore o sistema para tentativas excessivas de conexão. `max-connections-per-ip-por-minute`, `max-child` e `max-child-per-ip` podem ser usados para limitar tais ataques. Por padrão, TCP wrappers estão ativados. Consulte man:hosts_access[5] para obter mais informações sobre como colocar restrições TCP em vários daemons chamados pelo inetd. [[network-nfs]] == Network File System (NFS) O FreeBSD suporta o Network File System (NFS), que permite que um servidor compartilhe diretórios e arquivos com clientes através de uma rede. Com o NFS, os usuários e programas podem acessar arquivos em sistemas remotos como se estivessem armazenados localmente. NFS tem muitos usos práticos. Alguns dos usos mais comuns incluem: * Os dados que seriam duplicados em cada cliente podem ser mantidos em um único local e acessados por clientes na rede. * Vários clientes podem precisar de acesso ao diretório [.filename]#/usr/ports/distfiles#. Compartilhar esse diretório permite acesso rápido aos arquivos fonte sem precisar baixá-los para cada cliente. * Em grandes redes, geralmente é mais conveniente configurar um servidor central NFS no qual todos os diretórios home dos usuários são armazenados. Os usuários podem logar em um cliente em qualquer lugar da rede e ter acesso aos seus diretórios home. * A administração de exports do NFS é simplificada. Por exemplo, há apenas um sistema de arquivos no qual as políticas de segurança ou de backup devem ser definidas. * Dispositivos removíveis de armazenamento de mídia podem ser usados por outras máquinas na rede. Isso reduz o número de dispositivos em toda a rede e fornece um local centralizado para gerenciar sua segurança. Geralmente, é mais conveniente instalar software em várias máquinas a partir de uma mídia de instalação centralizada. O NFS consiste em um servidor e um ou mais clientes. O cliente acessa remotamente os dados armazenados na máquina do servidor. Para que isso funcione corretamente, alguns processos precisam ser configurados e executados. Esses daemons devem estar em execução no servidor: [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Daemon | Descrição |nfsd |O daemon NFS que atende a solicitações de clientes NFS. |mountd |O daemon de montagem do NFS que realiza solicitações recebidas do nfsd. |rpcbind |Este daemon permite que clientes NF descubram qual porta o servidor NFS está usando. |=== A execução de man:nfsiod[8] no cliente pode melhorar o desempenho, mas não é necessária. [[network-configuring-nfs]] === Configurando o Servidor Os sistemas de arquivos que o servidor NFS irá compartilhar são especificados no arquivo [.filename]#/etc/exports#. Cada linha neste arquivo especifica um sistema de arquivos a ser exportado, quais clientes têm acesso a esse sistema de arquivos e quaisquer opções de acesso. Ao adicionar entradas a este arquivo, cada sistema de arquivos exportado, suas propriedades e hosts permitidos devem ocorrer em uma única linha. Se nenhum cliente estiver listado na entrada, qualquer cliente na rede poderá montar esse sistema de arquivos. As seguintes entradas no arquivo [.filename]#/etc/exports# demonstram como exportar sistemas de arquivos. Os exemplos podem ser modificados para corresponder aos sistemas de arquivos e nomes de clientes na rede do leitor. Existem muitas opções que podem ser usadas neste arquivo, mas apenas algumas serão mencionadas aqui. Veja man:exports[5] para a lista completa de opções. Este exemplo mostra como exportar [.filename]#/cdrom# para três hosts chamados _alpha_, _bravo_ e _charlie_: [.programlisting] .... /cdrom -ro alpha bravo charlie .... A flag `-ro` torna o sistema de arquivos somente leitura, impedindo que os clientes façam alterações no sistema de arquivos exportado. Este exemplo assume que os nomes de host estão no DNS ou no arquivo [.filename]#/etc/hosts#. Consulte man:hosts[5] se a rede não tiver um servidor de DNS. O próximo exemplo exporta [.filename]#/home# para três clientes pelo endereço IP. Isso pode ser útil para redes sem DNS ou [.filename]#/etc/hosts#. A flag `-alldirs` permite que os subdiretórios sejam pontos de montagem. Em outras palavras, ele não montará automaticamente os subdiretórios, mas permitirá que o cliente monte os diretórios necessários conforme necessário. [.programlisting] .... /usr/home -alldirs 10.0.0.2 10.0.0.3 10.0.0.4 .... Este próximo exemplo exporta [.filename]#/a# para que dois clientes de domínios diferentes possam acessar esse sistema de arquivos. `-maproot=root` permite que o usuário `root` no sistema remoto grave os dados no sistema de arquivos exportado como `root`. Se `-maproot=root` não for especificado, o usuário `root` do cliente será mapeado para a conta `nobody` do servidor e estará sujeito às limitações de acesso definidas para `nobody`. [.programlisting] .... /a -maproot=root host.example.com box.example.org .... Um cliente só pode ser especificado uma vez por sistema de arquivos. Por exemplo, se [.filename]#/usr# for um único sistema de arquivos, essas entradas serão inválidas, já que ambas as entradas especificam o mesmo host: [.programlisting] .... # Invalid when /usr is one file system /usr/src client /usr/ports client .... O formato correto para essa situação é usar uma entrada: [.programlisting] .... /usr/src /usr/ports client .... A seguir, um exemplo de uma lista de exportação válida, em que [.filename]#/usr# e [.filename]#/exports# são sistemas de arquivos locais: [.programlisting] .... # Export src and ports to client01 and client02, but only # client01 has root privileges on it /usr/src /usr/ports -maproot=root client01 /usr/src /usr/ports client02 # The client machines have root and can mount anywhere # on /exports. Anyone in the world can mount /exports/obj read-only /exports -alldirs -maproot=root client01 client02 /exports/obj -ro .... Para habilitar os processos requeridos pelo servidor NFS no momento da inicialização, adicione estas opções ao arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... rpcbind_enable="YES" nfs_server_enable="YES" mountd_enable="YES .... O servidor pode ser iniciado agora executando este comando: [source,shell] .... # service nfsd start .... Sempre que o servidor NFS for iniciado, o mountd também é iniciado automaticamente. No entanto, mountd lê apenas [.filename]#/etc/exports# quando é iniciado. Para fazer as edições subsequentes de [.filename]#/etc/exports# entrarem em vigor imediatamente, force mountd para ler novamente: [source,shell] .... # service mountd reload .... === Configurando o Cliente Para ativar clientes NFS, defina essa opção no arquivo [.filename]#/etc/rc.conf# de cada cliente: [.programlisting] .... nfs_client_enable="YES" .... Em seguida, execute este comando em cada cliente NFS: [source,shell] .... # service nfsclient start .... O cliente agora tem tudo de que precisa para montar um sistema de arquivos remoto. Nestes exemplos, o nome do servidor é `server` e o nome do cliente é `client`. Para montar [.filename]#/home# no `server` para o ponto de montagem [.filename]#/mnt# no `client`: [source,shell] .... # mount server:/home /mnt .... Os arquivos e diretórios em [.filename]#/home# agora estarão disponíveis no `client`, no diretório [.filename]#/mnt#. Para montar um sistema de arquivos remoto toda vez que o cliente for inicializado, adicione-o ao arquivo [.filename]#/etc/fstab#: [.programlisting] .... server:/home /mnt nfs rw 0 0 .... Consulte man:fstab[5] para obter uma descrição de todas as opções disponíveis. === Bloqueando Alguns aplicativos exigem o bloqueio de arquivos para funcionar corretamente. Para ativar o bloqueio, adicione estas linhas ao arquivo [.filename]#/etc/rc.conf# no cliente e no servidor: [.programlisting] .... rpc_lockd_enable="YES" rpc_statd_enable="YES" .... Então inicie as aplicações: [source,shell] .... # service lockd start # service statd start .... Se o bloqueio não for necessário no servidor, o cliente NFS pode ser configurado para bloquear localmente incluindo `-L` ao executar o mount. Consulte man:mount_nfs[8] para mais detalhes. [[network-autofs]] === Automatizando Montagens com man:autofs[5] [NOTE] ==== O recurso de montagem automática man:autofs[5] é suportado a partir do FreeBSD 10.1-RELEASE. Para usar a funcionalidade automounter em versões mais antigas do FreeBSD, use man:amd[8]. Este capítulo descreve apenas o montador automático man:autofs[5]. ==== O recurso man:autofs[5] é um nome comum para vários componentes que, juntos, permitem a montagem automática de sistemas de arquivos locais e remotos sempre que um arquivo ou diretório dentro desse sistema de arquivos é acessado. Ele consiste no componente do kernel, man:autofs[5] e vários aplicativos no espaço do usuário: man:automount[8], man:automountd[8] e man:autounmountd[8]. Ele serve como uma alternativa para man:amd[8] de versões anteriores do FreeBSD. Amd ainda é fornecido para fins de compatibilidade com versões anteriores, já que os dois usam formato de mapeamento diferentes; o usado pelo autofs é o mesmo que com outros automontadores do SVR4, como os do Solaris, MacOS X e Linux. O sistema de arquivos virtual man:autofs[5] é montado em pontos de montagem especificados por man:automount[8], geralmente chamado durante a inicialização. Sempre que um processo tentar acessar o arquivo dentro do ponto de montagem man:autofs[], o kernel notificará o daemon man:automountd[8] e irá pausar o processo de disparo. O daemon man:automountd[8] processará as solicitações do kernel localizando o mapeamento apropriado e irá montar o sistema de arquivos de acordo com ele, então sinaliza ao kernel para liberar o processo bloqueado . O daemon man:autounmountd[8] desmonta automaticamente os sistemas de arquivos montados automaticamente após algum tempo, a menos que eles ainda estejam sendo usados. O arquivo de configuração principal do autofs é o [.filename]#/etc/auto_master#. Atribui mapeamentos individuais a montagens de nível superior. Para uma explicação do [.filename]#auto_master# e da sintaxe do mapeamento, consulte man:auto_master[5]. Existe um mapeamento especial montado automaticamente em [.filename]#/net#. Quando um arquivo é acessado dentro desse diretório, o man:autofs[5] procura a montagem remota correspondente e monta-a automaticamente. Por exemplo, uma tentativa de acessar um arquivo dentro de [.filename]#/net/foobar/usr# informaria man:automountd[8] para montar a exportação [.filename]#/usr# do host `foobar`. .Montando uma Exportação com man:autofs[5] [example] ==== Neste exemplo, `showmount -e` mostra os sistemas de arquivos exportados que podem ser montados a partir do servidor NFS, `foobar`: [source,shell] .... % showmount -e foobar Exports list on foobar: /usr 10.10.10.0 /a 10.10.10.0 % cd /net/foobar/usr .... ==== A saída de `showmount` mostra [.filename]#/usr# como uma exportação. Ao alterar os diretórios para [.filename]#/host/foobar/usr#, o man:automountd[8] intercepta o pedido e tenta resolver o nome do host `foobar`. Se for bem-sucedido, man:automountd[8] montará automaticamente a exportação de origem. Para habilitar man:autofs[5] no momento da inicialização, adicione esta linha ao arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... autofs_enable="YES" .... Em seguida, man:autofs[5] pode ser iniciado executando: [source,shell] .... # service automount start # service automountd start # service autounmountd start .... O formato de mapeamento de man:autofs[5] é o mesmo que em outros sistemas operacionais. Informações sobre este formato de outras fontes podem ser úteis, como o http://web.archive.org/web/20160813071113/http://images.apple.com/business/docs/Autofs.pdf[documento do Mac OS X]. Consulte as páginas de manuais man:automount[8], man:automountd[8], man:autounmountd[8] e man:auto_master[5] para maiores informações. [[network-nis]] == Sistema de Informação de Rede (NIS) O Network Information System (NIS) foi projetado para centralizar a administração de sistemas UNIX(TM) como Solaris(TM), HP-UX, AIX(TM), Linux, NetBSD, OpenBSD e FreeBSD. O NIS era originalmente conhecido como Yellow Pages, mas o nome foi alterado devido a problemas de marca registrada. Esta é a razão pela qual os comandos do NIS começam com `yp`. O NIS é um sistema cliente/servidor baseado em Remote Procedure Call (RPC) que permite que um grupo de máquinas dentro de um domínio NIS compartilhe um conjunto de arquivos de configuração. Isso permite que um administrador do sistema configure sistemas clientes NIS com apenas dados mínimos de configuração e adicione, remova ou modifique dados de configuração de um único local. O FreeBSD usa a versão 2 do protocolo NIS. === Termos do NIS e Processos A Tabela 28.1 resume os termos e processos importantes usados pelo NIS: .Terminologia do NIS [cols="1,1", frame="none", options="header"] |=== | Termo | Descrição |nome de domínio NIS |Os servidores e clientes do NIS compartilham um nome de domínio NIS. Normalmente, esse nome não tem nada a ver com DNS. |man:rpcbind[8] |Este serviço habilita o RPC e deve estar rodando para rodar um servidor NIS ou atuar como um cliente NIS. |man:ypbind[8] |Este serviço liga um cliente NIS ao seu servidor NIS. Ele levará o nome de domínio NIS e usará RPC para se conectar ao servidor. É o núcleo da comunicação cliente/servidor em um ambiente NIS. Se este serviço não estiver sendo executado em uma máquina cliente, ele não poderá acessar o servidor NIS. |man:ypserv[8] |Este é o processo para o servidor NIS. Se este serviço parar de funcionar, o servidor não poderá mais responder aos pedidos do NIS, portanto, esperamos que exista um servidor slave para assumir o controle. Alguns clientes não-FreeBSD não tentarão se reconectar usando um servidor slave e o processo ypbind pode precisar ser reiniciado nesses clientes. |man:rpc.yppasswdd[8] |Este processo só é executado em servidores principais de NIS. Este daemon permite que clientes NIS alterem suas senhas do NIS. Se este daemon não estiver rodando, os usuários terão que acessar o servidor principal do NIS e alterar suas senhas lá. |=== === Tipos de Máquinas Existem três tipos de hosts em um ambiente NIS: * Servidor NIS master + Esse servidor atua como um repositório central para as informações de configuração do host e mantém a cópia autoritativa dos arquivos usados por todos os clientes do NIS. O [.filename]#passwd#, o [.filename]#group# e outros arquivos usados pelos clientes do NIS são armazenados no servidor master. Embora seja possível que uma máquina seja um servidor NIS master para mais de um domínio NIS, esse tipo de configuração não será abordado neste capítulo, pois pressupõe ambiente NIS de pequena escala. * Servidores NIS slave + Os servidores slaves do NIS mantêm cópias dos arquivos de dados do master do NIS para fornecer redundância. Os servidores slaves também ajudam a balancear a carga do servidor master, pois os clientes do NIS sempre se conectam ao servidor do NIS que responde primeiro. * Clientes NIS + Os clientes do NIS autenticam-se contra o servidor NIS durante o logon. Informações em muitos arquivos podem ser compartilhadas usando o NIS . Os arquivos [.filename]#master.passwd#, [.filename]#group# e [.filename]#hosts# são comumente compartilhados via NIS. Sempre que um processo em um cliente precisa de informações que normalmente seriam encontradas nesses arquivos localmente, ele faz uma consulta ao servidor NIS ao qual está vinculado. === Considerações de Planejamento Esta seção descreve um ambiente NIS de exemplo que consiste em 15 máquinas FreeBSD sem ponto de administração centralizado. Cada máquina tem seu próprio [.filename]#/etc/passwd# e [.filename]#/etc/master.passwd#. Esses arquivos são mantidos em sincronia entre si somente por meio de intervenção manual. Atualmente, quando um usuário é adicionado ao laboratório, o processo deve ser repetido em todas as 15 máquinas. A configuração do laboratório será a seguinte: [.informaltable] [cols="1,1,1", frame="none", options="header"] |=== | Nome da maquina | Endereço IP | Role da máquina |`ellington` |`10.0.0.2` |NIS master |`coltrane` |`10.0.0.3` |NIS slave |`basie` |`10.0.0.4` |Estação de Trabalho da Facultativa |`bird` |`10.0.0.5` |Máquina Cliente |`cli[1-11]` |`10.0.0.[6-17]` |Outras Máquinas Clientes |=== Se esta é a primeira vez que um esquema de NIS está sendo desenvolvido, ele deve ser cuidadosamente planejado através do tempo. Independentemente do tamanho da rede, várias decisões precisam ser tomadas como parte do processo de planejamento. ==== Escolhendo um Nome de Domínio NIS Quando um cliente transmite suas solicitações de informações, ele inclui o nome do domínio NIS do qual faz parte. É assim que vários servidores em uma rede podem informar qual servidor deve responder a qual solicitação. Pense no nome de domínio NIS como o nome de um grupo de hosts. Algumas organizações optam por usar o nome de domínio da Internet para o nome de domínio NIS. Isso não é recomendado, pois pode causar confusão ao tentar depurar problemas de rede. O nome de domínio NIS deve ser único dentro da rede e é útil se ele descrever o grupo de máquinas que representa. Por exemplo, o departamento de Arte da Acme Inc. pode estar no domínio NIS"acme-art". Este exemplo usará o nome de domínio `test-domain`. No entanto, alguns sistemas operacionais não-FreeBSD exigem que o nome de domínio NIS seja o mesmo que o nome de domínio da Internet. Se uma ou mais máquinas na rede tiverem essa restrição, o nome de domínio da Internet _deve_ ser usado como o nome de domínio NIS. ==== Requisitos Físicos do Servidor Há várias coisas que você deve ter em mente ao escolher uma máquina para usar como um servidor NIS. Como os clientes do NIS dependem da disponibilidade do servidor, escolha uma máquina que não seja reinicializada com freqüência. O servidor do NIS deve idealmente ser uma máquina autônoma cujo único propósito seja ser um servidor NIS. Se a rede não for muito usada, é aceitável colocar o servidor NIS em uma máquina que executa outros serviços. No entanto, se o servidor NIS ficar indisponível, isso afetará negativamente todos os clientes NIS. === Configurando o Servidor NIS Master As cópias canônicas de todos os arquivos NIS são armazenadas no servidor master. Os bancos de dados usados para armazenar as informações são chamados de mapas de NIS. No FreeBSD, estes mapas são armazenados em [.filename]#/var/yp/[nome_do_domínio]# onde [.filename]#[nome_do_dominio]# é o nome do domínio NIS. Como vários domínios são suportados, é possível ter vários diretórios, um para cada domínio. Cada domínio terá seu próprio conjunto independente de mapas. Os servidores master e slave do NIS lidam com todas as requisições NIS através do man:ypserv[8]. Esse daemon é responsável por receber solicitações de entrada de clientes NIS, traduzindo o domínio e o nome do mapa solicitados para um caminho para o arquivo de banco de dados correspondente e transmitindo dados do banco de dados de volta ao cliente. Configurar um servidor NIS master pode ser relativamente simples, dependendo das necessidades ambientais. Como o FreeBSD oferece suporte a NIS embutido, ele só precisa ser ativado adicionando as seguintes linhas ao arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... nisdomainname="test-domain" <.> nis_server_enable="YES" <.> nis_yppasswdd_enable="YES" <.> .... <.> Esta linha define o nome de domínio NIS para `test-domain`. <.> Isto automatiza o início dos processos do servidor NIS quando o sistema é inicializado. <.> Isso habilita o daemon man:rpc.yppasswdd[8] para que os usuários possam alterar sua senha NIS de uma máquina cliente. É preciso ter cuidado em um domínio com vários servidores, no qual as máquinas do servidor também são clientes NIS. Geralmente, é uma boa ideia forçar os servidores a fazerem bind em si mesmos, em vez de permitir que eles transmitam solicitações de bind e, possivelmente, fiquem vinculados um ao outro. Modos de falha estranhos podem ocorrer se um servidor cair e outros dependerem dele. Eventualmente, todos os clientes terão tempo limite e tentarão fazer bind em outros servidores, mas o atraso envolvido poderá ser considerável e o modo de falha ainda estará presente, uma vez que os servidores podem ligar-se entre si novamente. Um servidor que também é um cliente pode ser forçado fazer bind em um servidor em particular adicionando estas linhas adicionais ao arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... nis_client_enable="YES" <.> nis_client_flags="-S test-domain,server" <.> .... <.> Isso permite rodar coisas do cliente também. <.> Esta linha define o nome de domínio NIS para test-domain e vincula para si mesmo. Depois de salvar as edições, digite `/etc/netstart` para reiniciar a rede e aplicar os valores definidos no arquivo [.filename]#/etc/rc.conf#. Antes de inicializar os mapas de NIS, inicie man:ypserv[8]: [source,shell] .... # service ypserv start .... ==== Inicializando os mapas do NIS Os mapeamentos NIS são gerados a partir dos arquivos de configuração no diretório [.filename]#/etc# no NIS master, com uma exceção: [.filename]#/etc/master.passwd#. Isso evita a propagação de senhas para todos os servidores no domínio NIS. Portanto, antes de inicializar os mapas do NIS, configure os arquivos de senha primários: [source,shell] .... # cp /etc/master.passwd /var/yp/master.passwd # cd /var/yp # vi master.passwd .... É aconselhável remover todas as entradas de contas do sistema, bem como quaisquer contas de usuário que não precisem ser propagadas para os clientes do NIS, como o `root` e quaisquer outras contas administrativas. [NOTE] ==== Assegure-se de que o arquivo [.filename]#/var/yp/master.passwd# não seja de grupo nem de mundo legível, definindo suas permissões para `600`. ==== Depois de concluir esta tarefa, inicialize os mapas do NIS. O FreeBSD inclui o script man:ypinit[8] para fazer isso. Ao gerar mapas para o servidor master, inclua `-m` e especifique o nome de domínio NIS: [source,shell] .... ellington# ypinit -m test-domain Server Type: MASTER Domain: test-domain Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. At this point, we have to construct a list of this domains YP servers. rod.darktech.org is already known as master server. Please continue to add any slave servers, one per line. When you are done with the list, type a . master server : ellington next host to add: coltrane next host to add: ^D The current list of NIS servers looks like this: ellington coltrane Is this correct? [y/n: y] y [..output from map generation..] NIS Map update completed. ellington has been setup as an YP master server without any errors. .... Isto irá criar [.filename]#/var/yp/Makefile# a partir de [.filename]#/var/yp/Makefile.dist#. Por padrão, este arquivo assume que o ambiente tem um único servidor NIS com apenas clientes FreeBSD. Como `test-domain` tem um servidor slave, edite esta linha no arquivo [.filename]#/var/yp/Makefile# para que comece com um comentário (`#`) : [.programlisting] .... NOPUSH = "True" .... ==== Adicionando novos usuários Toda vez que um novo usuário é criado, a conta de usuário deve ser adicionada ao servidor mestre NIS e aos mapeamentos do NIS reconstruídos. Até que isso ocorra, o novo usuário não poderá efetuar login em nenhum lugar, exceto no NIS master. Por exemplo, para adicionar o novo usuário `jsmith` ao domínio `test-domain`, execute estes comandos no servidor master: [source,shell] .... # pw useradd jsmith # cd /var/yp # make test-domain .... O usuário também pode ser adicionado usando `adduser jsmith` em vez de `pw useradd smith`. === Configurando um Servidor NIS Slave Para configurar um servidor NIS slave, faça o logon no servidor slave e edite o arquivo [.filename]#/etc/rc.conf# assim como para o servidor master. Não gere nenhum mapa de NIS, pois estes já existem no servidor master. Ao executar `ypinit` no servidor slave, use `-s` (para slave) ao invés de `-m` (para master). Esta opção requer o nome do NIS master, além do nome do domínio, como visto neste exemplo: [source,shell] .... coltrane# ypinit -s ellington test-domain Server Type: SLAVE Domain: test-domain Master: ellington Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. There will be no further questions. The remainder of the procedure should take a few minutes, to copy the databases from ellington. Transferring netgroup... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byuser... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byhost... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring group.bygid... ypxfr: Exiting: Map successfully transferred Transferring group.byname... ypxfr: Exiting: Map successfully transferred Transferring services.byname... ypxfr: Exiting: Map successfully transferred Transferring rpc.bynumber... ypxfr: Exiting: Map successfully transferred Transferring rpc.byname... ypxfr: Exiting: Map successfully transferred Transferring protocols.byname... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byaddr... ypxfr: Exiting: Map successfully transferred Transferring netid.byname... ypxfr: Exiting: Map successfully transferred Transferring hosts.byaddr... ypxfr: Exiting: Map successfully transferred Transferring protocols.bynumber... ypxfr: Exiting: Map successfully transferred Transferring ypservers... ypxfr: Exiting: Map successfully transferred Transferring hosts.byname... ypxfr: Exiting: Map successfully transferred coltrane has been setup as an YP slave server without any errors. Remember to update map ypservers on ellington. .... Isto irá gerar um diretório no servidor slave chamado [.filename]#/var/yp/test-domain# que contém cópias dos mapas do servidor principal do NIS. Adicionar estas entradas ao arquivo [.filename]#/etc/crontab# em cada servidor slave forçará os slaves a sincronizar seus mapas com os mapas no servidor master: [.programlisting] .... 20 * * * * root /usr/libexec/ypxfr passwd.byname 21 * * * * root /usr/libexec/ypxfr passwd.byuid .... Essas entradas não são obrigatórias porque o servidor master tenta enviar automaticamente quaisquer alterações no mapa para seus escravos. No entanto, como os clientes podem depender do servidor escravo para fornecer informações corretas de senha, recomenda-se forçar atualizações frequentes de mapas de senha. Isso é especialmente importante em redes ocupadas nas quais as atualizações de mapas nem sempre são concluídas. Para finalizar a configuração, execute `/etc/netstart` no servidor slave para iniciar os serviços do NIS. === Configurando um cliente NIS Um cliente NIS é vinculado a um servidor NIS usando man:ypbind[8]. Esse daemon transmite solicitações de RPC na rede local. Essas solicitações especificam o nome do domínio configurado no cliente. Se um servidor NIS no mesmo domínio receber uma das transmissões, ele responderá a ypbind, que registrará o endereço do servidor. Se houver vários servidores disponíveis, o cliente usará o endereço do primeiro servidor para responder e direcionará todas as suas solicitações de NIS para esse servidor. O cliente irá automaticamente pingar o servidor regularmente para garantir que ainda esteja disponível. Se ele não receber uma resposta dentro de um período de tempo razoável, o ypbind marcará o domínio como não acoplado e começará a transmitir novamente na esperança de localizar outro servidor. Para configurar uma máquina FreeBSD para ser um cliente NIS: [.procedure] ==== . Edite o [.filename]#/etc/rc.conf# e adicione as seguintes linhas para definir o nome de domínio NIS e inicie man:ypbind[8] durante a inicialização da rede: + [.programlisting] .... nisdomainname="test-domain" nis_client_enable="YES" .... + . Para importar todas as possíveis entradas de senha do servidor NIS, use `vipw` para remover todas as contas de usuário, exceto uma do arquivo [.filename]#/etc/master.passwd#. Ao remover as contas, lembre-se de que pelo menos uma conta local deve permanecer e essa conta deve ser membro do grupo `wheel`. Se houver um problema com o NIS, essa conta local poderá ser usada para efetuar login remotamente, tornar-se o superusuário e corrigir o problema. Antes de salvar as edições, adicione a seguinte linha ao final do arquivo: + [.programlisting] .... +::::::::: .... + Esta linha configura o cliente para fornecer qualquer pessoa com uma conta válida na senha do servidor do NIS mapeia uma conta no cliente. Existem várias maneiras de configurar o cliente NIS modificando essa linha. Um método é descrito em <>. Para uma leitura mais detalhada, consulte o livro `Managing NFS and NIS`, publicado pela O'Reilly Media. + . Para importar todas as entradas de grupo possíveis do servidor NIS, adicione esta linha ao [.filename]#/etc/group#: + [.programlisting] .... +:*:: .... ==== Para iniciar imediatamente o cliente NIS, execute os seguintes comandos como superusuário: [source,shell] .... # /etc/netstart # service ypbind start .... Depois de concluir estas etapas, a execução do `ypcat passwd` no cliente deve mostrar o mapa [.filename]#passwd# do servidor. === Segurança NIS Como o RPC é um serviço baseado em broadcast, qualquer sistema executando o ypbind dentro do mesmo domínio pode recuperar o conteúdo dos mapas do NIS. Para evitar transações não autorizadas, man:ypserv[8] suporta um recurso chamado "securenets" que pode ser usado para restringir o acesso a um dado conjunto de hosts. Por padrão, essas informações são armazenadas no arquivo [.filename]#/var/yp/securenets#, a menos que man:ypserv[8] seja iniciado com `-p` e um caminho alternativo. Este arquivo contém entradas que consistem em uma especificação de rede e uma máscara de rede separadas por espaço em branco. Linhas iniciando com `#` são consideradas comentários. Um exemplo de [.filename]##securenets## pode ser assim: [.programlisting] .... # allow connections from local host -- mandatory 127.0.0.1 255.255.255.255 # allow connections from any host # on the 192.168.128.0 network 192.168.128.0 255.255.255.0 # allow connections from any host # between 10.0.0.0 to 10.0.15.255 # this includes the machines in the testlab 10.0.0.0 255.255.240.0 .... Se man:ypserv[8] receber uma solicitação de um endereço que corresponda a uma dessas regras, ela processará a solicitação normalmente. Se o endereço não corresponder a uma regra, a solicitação será ignorada e uma mensagem de aviso será registrada. Se o [.filename]#securenets# não existir, o `ypserv` permitirá conexões de qualquer host. crossref:security[tcpwrappers,TCP Wrapper] é um mecanismo alternativo para fornecer controle de acesso em vez de [.filename]#securenets#. Embora o mecanismo de controle de acesso acrescente alguma segurança, ambos são vulneráveis a ataques como "IP spoofing". Todo o tráfego relacionado a NIS deve ser bloqueado no firewall. Servidores que usam [.filename]#securenets# podem não servir clientes legítimos de NIS com implementações arcaicas de TCP/IP. Algumas dessas implementações definem todos os bits do host como zero ao fazer transmissões ou não observam a máscara de sub-rede ao calcular o endereço de transmissão. Embora alguns desses problemas possam ser corrigidos alterando a configuração do cliente, outros problemas podem forçar a desativação desses sistemas clientes ou o abandono do [.filename]#securenets#. O uso de TCP Wrapper aumenta a latência do servidor NIS. O atraso adicional pode ser longo o suficiente para causar timeouts em programas clientes, especialmente em redes ocupadas com servidores NIS lentos. Se um ou mais clientes sofrerem de latência, converta esses clientes em servidores de NIS slaves e force-os a se ligarem a eles mesmos. ==== Barrando alguns usuários Neste exemplo, o sistema `basie` é uma estação de trabalho da dentro do domínio NIS facultativo. O mapa [.filename]#passwd# no servidor NIS master contém contas para professores e alunos. Esta seção demonstra como permitir o login do corpo docente neste sistema e, ao mesmo tempo, recusar logins de alunos. Para previnir usuários específicos de logar em um sistema, desde que eles estejam presentes no banco de dados do NIS, use `vipw` para adicionar `-_username_` com o numero correto de virgulas em direção ao fim do arquivo [.filename]#/etc/master.passwd# no cliente, onde _username_ é o nome de usuário a impedir de logar. A linha com o usuário bloqueado deve estar antes da linha `+` que permite usuários do NIS. Neste exemplo, `bill` está impedido de logar no `basie`: [source,shell] .... basie# cat /etc/master.passwd root:[password]:0:0::0:0:The super-user:/root:/bin/csh toor:[password]:0:0::0:0:The other super-user:/root:/bin/sh daemon:*:1:1::0:0:Owner of many system processes:/root:/usr/sbin/nologin operator:*:2:5::0:0:System &:/:/usr/sbin/nologin bin:*:3:7::0:0:Binaries Commands and Source,,,:/:/usr/sbin/nologin tty:*:4:65533::0:0:Tty Sandbox:/:/usr/sbin/nologin kmem:*:5:65533::0:0:KMem Sandbox:/:/usr/sbin/nologin games:*:7:13::0:0:Games pseudo-user:/usr/games:/usr/sbin/nologin news:*:8:8::0:0:News Subsystem:/:/usr/sbin/nologin man:*:9:9::0:0:Mister Man Pages:/usr/shared/man:/usr/sbin/nologin bind:*:53:53::0:0:Bind Sandbox:/:/usr/sbin/nologin uucp:*:66:66::0:0:UUCP pseudo-user:/var/spool/uucppublic:/usr/libexec/uucp/uucico xten:*:67:67::0:0:X-10 daemon:/usr/local/xten:/usr/sbin/nologin pop:*:68:6::0:0:Post Office Owner:/nonexistent:/usr/sbin/nologin nobody:*:65534:65534::0:0:Unprivileged user:/nonexistent:/usr/sbin/nologin -bill::::::::: +::::::::: basie# .... [[network-netgroups]] === Usando Netgroups A exclusão de usuários especificados do logon em sistemas individuais torna-se imprestável em redes maiores e perde rapidamente o principal benefício do NIS: administração _centralizada_. Os netgroups foram desenvolvidos para lidar com redes grandes e complexas com centenas de usuários e máquinas. Seu uso é comparável aos grupos UNIX(TM), onde a principal diferença é a falta de um ID numérico e a capacidade de definir um netgroup incluindo contas de usuário e outros netgroups. Para expandir o exemplo usado neste capítulo, o domínio NIS será estendido para adicionar os usuários e sistemas mostrados nas Tabelas 28.2 e 28.3: .Usuários Adicionais [cols="1,1", frame="none", options="header"] |=== | Nome(s) de usuário | Descrição |`alpha`, `beta` |Funcionários do departamento de TI |`charlie`, `delta` |Aprendizes do departamento de TI |`echo`, `foxtrott`, `golf`, ... |funcionários |`able`, `baker`, ... |estagiários |=== .Sistemas Adicionais [cols="1,1", frame="none", options="header"] |=== | Nome(s) de máquina | Descrição |`war`, `death`, `famine`, `pollution` |Somente funcionários de TI podem fazer logon nesses servidores. |`pride`, `greed`, `envy`, `wrath`, `lust`, `sloth` |Todos os membros do departamento de TI podem fazer login nesses servidores. |`one`, `two`, `three`, `four`, ... |Estações de trabalho comuns usadas pelos funcionários. |`trashcan` |Uma máquina muito antiga sem dados críticos. Até os estagiários podem usar este sistema. |=== Ao usar netgroups para configurar esse cenário, cada usuário é atribuído a um ou mais netgroups e os logins são permitidos ou proibidos para todos os membros do netgroup. Ao adicionar uma nova máquina, as restrições de login devem ser definidas para todos os netgroups. Quando um novo usuário é adicionado, a conta deve ser adicionada a um ou mais netgroups. Se a configuração do NIS for planejada com cuidado, somente um arquivo de configuração central precisará ser modificado para conceder ou negar acesso a máquinas. O primeiro passo é a inicialização do mapa do NIS `netgroup`. No FreeBSD, este mapa não é criado por padrão. No servidor NIS master, use um editor para criar um mapa chamado [.filename]#/var/yp/netgroup#. Este exemplo cria quatro grupos de rede para representar funcionários de TI, aprendizes de TI, funcionários e estagiários: [.programlisting] .... IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) USERS (,echo,test-domain) (,foxtrott,test-domain) \ (,golf,test-domain) INTERNS (,able,test-domain) (,baker,test-domain) .... Cada entrada configura um netgroup. A primeira coluna em uma entrada é o nome do netgroup. Cada conjunto de colchetes representa um grupo de um ou mais usuários ou o nome de outro grupo de rede. Ao especificar um usuário, os três campos delimitados por vírgula dentro de cada grupo representam: . O nome do(s) host(s) onde os outros campos que representam o usuário são válidos. Se um nome de host não for especificado, a entrada será válida em todos os hosts. . O nome da conta que pertence a este netgroup. . O domínio NIS da conta. As contas podem ser importadas de outros domínios do NIS para um netgroup. Se um grupo contiver vários usuários, separe cada usuário com espaço em branco. Além disso, cada campo pode conter curingas. Veja man:netgroup[5] para detalhes. Nomes de grupos maiores que 8 caracteres não devem ser usados. Os nomes diferenciam maiúsculas de minúsculas e usar letras maiúsculas para nomes de grupos de rede é uma maneira fácil de distinguir entre nomes de usuários, máquinas e grupos de rede. Alguns clientes não-FreeBSD NIS não podem lidar com netgroups contendo mais de 15 entradas. Esse limite pode ser contornado criando vários grupos de sub-redes com 15 usuários ou menos e um grupo de rede real consistindo dos grupos de sub-redes, como visto neste exemplo: [.programlisting] .... BIGGRP1 (,joe1,domain) (,joe2,domain) (,joe3,domain) [...] BIGGRP2 (,joe16,domain) (,joe17,domain) [...] BIGGRP3 (,joe31,domain) (,joe32,domain) BIGGROUP BIGGRP1 BIGGRP2 BIGGRP3 .... Repita este processo se mais de 225 (15 vezes 15) usuários existirem dentro de um único netgroup. Para ativar e distribuir o novo mapa do NIS: [source,shell] .... ellington# cd /var/yp ellington# make .... Isso gerará os três mapas NIS, [.filename]#netgroup#, [.filename]#netgroup.byhost# e [.filename]#netgroup.byuser#. Use a opção de chave de mapa man:ypcat[1] para verificar se os novos mapas de NIS estão disponíveis: [source,shell] .... ellington% ypcat -k netgroup ellington% ypcat -k netgroup.byhost ellington% ypcat -k netgroup.byuser .... A saída do primeiro comando deve lembrar o conteúdo de [.filename]#/var/yp/netgroup#. O segundo comando só produz saída se os netgroups específicos do host foram criados. O terceiro comando é usado para obter a lista de netgroups de um usuário. Para configurar um cliente, use man:vipw[8] para especificar o nome do netgroup. Por exemplo, no servidor chamado `war`, substitua esta linha: [.programlisting] .... +::::::::: .... com [.programlisting] .... +@IT_EMP::::::::: .... Isso especifica que apenas os usuários definidos no netgroup `IT_EMP` serão importados para o banco de dados de senhas deste sistema e somente esses usuários terão permissão para efetuar login nesse sistema. Essa configuração também se aplica à função `~` do shell e a todas as rotinas que convertem entre nomes de usuário e IDs de usuário numérico. Em outras palavras, `cd ~_user_` não funcionará, `ls -l` mostrará o ID numérico em vez do nome de usuário e `find . -user joe -print` falhará com a mensagem `No such user`. Para corrigir isso, importe todas as entradas do usuário sem permitir que elas efetuem login nos servidores. Isto pode ser conseguido adicionando uma linha extra: [.programlisting] .... +:::::::::/usr/sbin/nologin .... Esta linha configura o cliente para importar todas as entradas, mas para substituir o shell nessas entradas com [.filename]#/usr/sbin/nologin#. Certifique-se que a linha extra é colocada _após_ `+@IT_EMP:::::::::`. Caso contrário, todas as contas de usuário importadas do NIS terão [.filename]#/usr/sbin/nologin# como seu shell de login e ninguém poderá efetuar o login no sistema. Para configurar os servidores menos importantes, substitua o antigo `+:::::::::` nos servidores com estas linhas: [.programlisting] .... +@IT_EMP::::::::: +@IT_APP::::::::: +:::::::::/usr/sbin/nologin .... As linhas correspondentes para as estações de trabalho seriam: [.programlisting] .... +@IT_EMP::::::::: +@USERS::::::::: +:::::::::/usr/sbin/nologin .... O NIS suporta a criação de grupos de rede de outros grupos de rede, o que pode ser útil se a política relacionada ao acesso do usuário for alterada. Uma possibilidade é a criação de netgroups baseados em funções. Por exemplo, pode-se criar um netgroup chamado `BIGSRV` para definir as restrições de login para os servidores importantes, outro grupo de rede chamado `SMALLSRV` para os servidores menos importantes e um terceiro netgroup chamado `USERBOX` para as estações de trabalho. Cada um desses netgroups contém os netgroups com permissão para efetuar login nessas máquinas. As novas entradas para o mapa do NIS `netgroup` seriam assim: [.programlisting] .... BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS .... Esse método de definir restrições de login funciona razoavelmente bem quando é possível definir grupos de máquinas com restrições idênticas. Infelizmente, esta é a exceção e não a regra. Na maioria das vezes, é necessária a capacidade de definir restrições de login por máquina. As definições de netgroup específicas da máquina são outra possibilidade para lidar com as mudanças na política. Neste cenário, o [.filename]#/etc/master.passwd# de cada sistema contém duas linhas que começam com "+". A primeira linha adiciona um netgroup com as contas permitidas para entrar nesta máquina e a segunda linha adiciona todas as outras contas com [.filename]#/usr/sbin/nologin# como shell. Recomenda-se usar a versão "ALL-CAPS" do nome do host como o nome do netgroup: [.programlisting] .... +@BOXNAME::::::::: +:::::::::/usr/sbin/nologin .... Quando esta tarefa estiver completa em todas as máquinas, não haverá mais a necessidade de modificar as versões locais de [.filename]#/etc/master.passwd# novamente. Todas as alterações posteriores podem ser manipuladas, modificando o mapa do NIS. Aqui está um exemplo de um possível mapa `netgroup` para este cenário: [.programlisting] .... # Define groups of users first IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) DEPT1 (,echo,test-domain) (,foxtrott,test-domain) DEPT2 (,golf,test-domain) (,hotel,test-domain) DEPT3 (,india,test-domain) (,juliet,test-domain) ITINTERN (,kilo,test-domain) (,lima,test-domain) D_INTERNS (,able,test-domain) (,baker,test-domain) # # Now, define some groups based on roles USERS DEPT1 DEPT2 DEPT3 BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS # # And a groups for a special tasks # Allow echo and golf to access our anti-virus-machine SECURITY IT_EMP (,echo,test-domain) (,golf,test-domain) # # machine-based netgroups # Our main servers WAR BIGSRV FAMINE BIGSRV # User india needs access to this server POLLUTION BIGSRV (,india,test-domain) # # This one is really important and needs more access restrictions DEATH IT_EMP # # The anti-virus-machine mentioned above ONE SECURITY # # Restrict a machine to a single user TWO (,hotel,test-domain) # [...more groups to follow] .... Pode não ser sempre aconselhável usar netgroups baseados em máquina. Ao implantar algumas dúzias ou centenas de sistemas, grupos de rede baseados em funções em vez de grupos de rede baseados em máquina podem ser usados para manter o tamanho do mapa do NIS dentro de limites razoáveis. === Formatos de Senha O NIS requer que todos os hosts em um domínio NIS usem o mesmo formato para criptografar senhas. Se os usuários tiverem problemas para autenticar em um cliente NIS, pode ser devido a um formato de senha diferente. Em uma rede heterogênea, o formato deve ser suportado por todos os sistemas operacionais, onde DES é o padrão comum mais baixo. Para verificar qual formato um servidor ou cliente está usando, veja esta seção do [.filename]#/etc/login.conf#: [.programlisting] .... default:\ :passwd_format=des:\ :copyright=/etc/COPYRIGHT:\ [Further entries elided] .... Neste exemplo, o sistema está usando o formato DES. Outros valores possíveis são `blf` para Blowfish e `md5` para senhas criptografadas com MD5. Se o formato em um host precisar ser editado para corresponder ao que está sendo usado no domínio NIS, o banco de dados de recursos de login deve ser reconstruído após salvar a alteração: [source,shell] .... # cap_mkdb /etc/login.conf .... [NOTE] ==== O formato das senhas das contas de usuários existentes não será atualizado até que cada usuário mude sua senha _após_ o banco de dados de recursos de login ser reconstruído. ==== [[network-ldap]] == Protocolo leve de acesso de diretório ( LDAP ) O protocolo LDAP (LDAP) é um protocolo da camada de aplicação usado para acessar, modificar e autenticar objetos usando um serviço de informações de diretório distribuído. Pense nisso como um telefone ou livro de registro que armazena vários níveis de informações hierárquicas e homogêneas. Ele é usado nas redes do Active Directory e do OpenLDAP e permite que os usuários acessem vários níveis de informações internas utilizando uma única conta. Por exemplo, a autenticação de email, a obtenção de informações de contato dos funcionários e a autenticação interna de sites podem usar uma única conta de usuário na base de registros do servidor LDAP. Esta seção fornece um guia de início rápido para configurar um servidor LDAP em um sistema FreeBSD. Ele pressupõe que o administrador já tenha um plano de design que inclua o tipo de informação a ser armazenada, para que essas informações sejam usadas, quais usuários devem ter acesso a essas informações e como proteger essas informações contra acesso não autorizado. === Terminologia e Estrutura do LDAP O LDAP usa vários termos que devem ser entendidos antes de iniciar a configuração. Todas as entradas de diretório consistem em um grupo de _attributes_. Cada um desses conjuntos de atributos contém um identificador exclusivo conhecido como _Distinguished Name_ (DN) que é normalmente criado a partir de vários outros atributos, como Common ou _Relative Distinguished Name_ (RDN). Semelhante a como os diretórios têm caminhos absolutos e relativos, considere um DN como um caminho absoluto e o RDN como o caminho relativo. Um exemplo de entrada LDAP é semelhante ao seguinte. Este exemplo procura a entrada para a conta de usuário especificada (`uid`), unidade organizacional (`ou`) e organização (`o`): [source,shell] .... % ldapsearch -xb "uid=trhodes,ou=users,o=example.com" # extended LDIF # # LDAPv3 # base with scope subtree # filter: (objectclass=*) # requesting: ALL # # trhodes, users, example.com dn: uid=trhodes,ou=users,o=example.com mail: trhodes@example.com cn: Tom Rhodes uid: trhodes telephoneNumber: (123) 456-7890 # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... Esta entrada de exemplo mostra os valores para os atributos `dn`, `mail`, `cn`, `uid` e `telephoneNumber`. O atributo do cn é o RDN. Maiores informações sobre o LDAP e sua terminologia podem ser encontradas em http://www.openldap.org/doc/admin24/intro.html[http://www.openldap.org/doc/admin24/intro.html]. [[ldap-config]] === Configurando um servidor LDAP O FreeBSD não provê um servidor LDAP embutido. Comece a configuração instalando o pacote ou port package:net/openldap-server[]: [source,shell] .... # pkg install openldap-server .... Aqui está um largo conjunto de opções habilitadas no extref:{linux-users}[pacote, software]. Reveja-os rodando o comando `pkg info openldap-server`. Se não for suficiente (por exemplo se o suporte a SQL for necessário), por favor considere recompilar o port usando o framework crossref:ports[ports-using,apropriado]. A instalação cria o diretório [.filename]#/var/db/openldap-data# para conter os dados. O diretório para armazenar os certificados deve ser criado: [source,shell] .... # mkdir /usr/local/etc/openldap/private .... A próxima fase é configurar a autoridade de certificação. Os seguintes comandos devem ser executados em [.filename]#/usr/local/etc/openldap/private#. Isso é importante, pois as permissões de arquivo precisam ser restritivas e os usuários não devem ter acesso a esses arquivos. Informações mais detalhadas sobre certificados e seus parâmetros podem ser encontradas em crossref:security[openssl,OpenSSL]. Para criar a Autoridade de Certificação, comece com este comando e siga os prompts: [source,shell] .... # openssl req -days 365 -nodes -new -x509 -keyout ca.key -out ../ca.crt .... As entradas para os prompts podem ser genéricas _exceto_ para o `Common Name`. Esta entrada deve ser _diferente_ do nome do host do sistema. Se este será um certificado auto-assinado, prefixe o nome do host com `CA` para a Autoridade de Certificação. A próxima tarefa é criar uma solicitação de assinatura de certificado e uma chave privada. Insira este comando e siga os prompts: [source,shell] .... # openssl req -days 365 -nodes -new -keyout server.key -out server.csr .... Durante o processo de geração de certificados, certifique-se de configurar corretamente o atributo `Common Name`. A Solicitação de Assinatura de Certificado deve ser assinada com a Autoridade de Certificação para ser usada como um certificado válido: [source,shell] .... # openssl x509 -req -days 365 -in server.csr -out ../server.crt -CA ../ca.crt -CAkey ca.key -CAcreateserial .... A parte final do processo de geração de certificados é gerar e assinar os certificados do cliente: [source,shell] .... # openssl req -days 365 -nodes -new -keyout client.key -out client.csr # openssl x509 -req -days 3650 -in client.csr -out ../client.crt -CA ../ca.crt -CAkey ca.key .... Lembre-se de usar o mesmo atributo `Common Name` quando solicitado. Quando terminar, assegure-se de que um total de oito (8) novos arquivos tenham sido gerado através dos comandos procedentes. O daemon que executa o servidor OpenLDAP é o [.filename]#slapd#. Sua configuração é executada através do [.filename]#slapd.ldif#: o antigo [.filename]#slapd.conf# foi descontinuado pelo OpenLDAP. http://www.openldap.org/doc/admin24/slapdconf2.html[Exemplos de configuração] para o [.filename]#slapd.ldif# estão disponíveis e também podem ser encontrados em [.filename]#/usr/local/etc/openldap/slapd.ldif.sample#. As opções estão documentadas em slapd-config(5). Cada seção do [.filename]#slapd.ldif#, como todos os outros conjuntos de atributos LDAP, é identificada exclusivamente por meio de um DN. Certifique-se de que nenhuma linha em branco seja deixada entre a instrução `dn:` e o final desejado da seção. No exemplo a seguir, o TLS será usado para implementar um canal seguro. A primeira seção representa a configuração global: [.programlisting] .... # # See slapd-config(5) for details on configuration options. # This file should NOT be world readable. # dn: cn=config objectClass: olcGlobal cn: config # # # Define global ACLs to disable default read access. # olcArgsFile: /var/run/openldap/slapd.args olcPidFile: /var/run/openldap/slapd.pid olcTLSCertificateFile: /usr/local/etc/openldap/server.crt olcTLSCertificateKeyFile: /usr/local/etc/openldap/private/server.key olcTLSCACertificateFile: /usr/local/etc/openldap/ca.crt #olcTLSCipherSuite: HIGH olcTLSProtocolMin: 3.1 olcTLSVerifyClient: never .... A Autoridade de Certificação, o certificado do servidor e os arquivos de chave privada do servidor devem ser especificados aqui. Recomenda-se que os clientes escolham a opção de criptografia de segurança e omitam `olcTLSCipherSuite` (incompatível com clientes TLS diferentes de [.filename]#openssl#). A opção `olcTLSProtocolMin` permite que o servidor exija um nível mínimo de segurança: é recomendado. Enquanto a verificação é obrigatória para o servidor, não é para o cliente: `olcTLSVerifyClient: never`. A segunda seção é sobre os módulos de backend e pode ser configurada da seguinte maneira: [.programlisting] .... # # Load dynamic backend modules: # dn: cn=module,cn=config objectClass: olcModuleList cn: module olcModulepath: /usr/local/libexec/openldap olcModuleload: back_mdb.la #olcModuleload: back_bdb.la #olcModuleload: back_hdb.la #olcModuleload: back_ldap.la #olcModuleload: back_passwd.la #olcModuleload: back_shell.la .... A terceira seção é dedicada a carregar os esquemas `ldif` necessários para serem usados pelos bancos de dados: eles são essenciais. [.programlisting] .... dn: cn=schema,cn=config objectClass: olcSchemaConfig cn: schema include: file:///usr/local/etc/openldap/schema/core.ldif include: file:///usr/local/etc/openldap/schema/cosine.ldif include: file:///usr/local/etc/openldap/schema/inetorgperson.ldif include: file:///usr/local/etc/openldap/schema/nis.ldif .... Em seguida, a seção de configuração do frontend: [.programlisting] .... # Frontend settings # dn: olcDatabase={-1}frontend,cn=config objectClass: olcDatabaseConfig objectClass: olcFrontendConfig olcDatabase: {-1}frontend olcAccess: to * by * read # # Sample global access control policy: # Root DSE: allow anyone to read it # Subschema (sub)entry DSE: allow anyone to read it # Other DSEs: # Allow self write access # Allow authenticated users read access # Allow anonymous users to authenticate # #olcAccess: to dn.base="" by * read #olcAccess: to dn.base="cn=Subschema" by * read #olcAccess: to * # by self write # by users read # by anonymous auth # # if no access controls are present, the default policy # allows anyone and everyone to read anything but restricts # updates to rootdn. (e.g., "access to * by * read") # # rootdn can always read and write EVERYTHING! # olcPasswordHash: {SSHA} # {SSHA} is already the default for olcPasswordHash .... Outra seção é dedicada ao _backend de configuração_, a única maneira de acessar posteriormente a configuração do servidor OpenLDAP é como um superusuário global. [.programlisting] .... dn: olcDatabase={0}config,cn=config objectClass: olcDatabaseConfig olcDatabase: {0}config olcAccess: to * by * none olcRootPW: {SSHA}iae+lrQZILpiUdf16Z9KmDmSwT77Dj4U .... O nome de usuário administrador padrão é `cn=config`. Digite [.filename]#slappasswd# em um shell, escolha a senha e use sua hash `olcRootPW`. Se essa opção não for especificada agora, antes do arquivo [.filename]#slapd.ldif# ser importado, ninguém poderá modificar a seção de _configuração global_. A última seção é sobre o back-end do banco de dados: [.programlisting] .... ####################################################################### # LMDB database definitions ####################################################################### # dn: olcDatabase=mdb,cn=config objectClass: olcDatabaseConfig objectClass: olcMdbConfig olcDatabase: mdb olcDbMaxSize: 1073741824 olcSuffix: dc=domain,dc=example olcRootDN: cn=mdbadmin,dc=domain,dc=example # Cleartext passwords, especially for the rootdn, should # be avoided. See slappasswd(8) and slapd-config(5) for details. # Use of strong authentication encouraged. olcRootPW: {SSHA}X2wHvIWDk6G76CQyCMS1vDCvtICWgn0+ # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools. # Mode 700 recommended. olcDbDirectory: /var/db/openldap-data # Indices to maintain olcDbIndex: objectClass eq .... Esse banco de dados hospeda os _conteudos atuais_ do diretório LDAP. Outros tipos diferentes de `mdb` estão disponiveis. Esse é super-usuário, não confundir com um global, é configurado aqui: um usuário (possivelmente customizado) em `olcRootDN` e a hash da senha em `olcRootPW`; [.filename]#slappasswd# pode ser usado como antes. Esse http://www.openldap.org/devel/gitweb.cgi?p=openldap.git;a=tree;f=tests/data/regressions/its8444;h=8a5e808e63b0de3d2bdaf2cf34fecca8577ca7fd;hb=HEAD[repositorio] contém quatro exemplos do arquivo [.filename]#slapd.ldif#. Para converter um arquivo [.filename]#slapd.conf# existente dentro de [.filename]#slapd.ldif#, referencie a http://www.openldap.org/doc/admin24/slapdconf2.html[essa página] (por favor, note que isso pode introduzir algumas opções inuteis). Quando a configuração estiver concluída, o [.filename]#slapd.ldif# deve ser colocado em um diretório vazio. Recomenda-se criá-lo como: [source,shell] .... # mkdir /usr/local/etc/openldap/slapd.d/ .... Importe o banco de dados de configuração: [source,shell] .... # /usr/local/sbin/slapadd -n0 -F /usr/local/etc/openldap/slapd.d/ -l /usr/local/etc/openldap/slapd.ldif .... Inicie o daemon [.filename]#slapd#: [source,shell] .... # /usr/local/libexec/slapd -F /usr/local/etc/openldap/slapd.d/ .... A opção `-d` pode ser usada para depuração, conforme especificado em slapd(8). Para verificar se o servidor está em execução e funcionando: [source,shell] .... # ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts # extended LDIF # # LDAPv3 # base <> with scope baseObject # filter: (objectclass=*) # requesting: namingContexts # # dn: namingContexts: dc=domain,dc=example # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... O servidor ainda deve ser confiável. Se isso nunca foi feito antes, siga estas instruções. Instale o pacote ou o port OpenSSL: [source,shell] .... # pkg install openssl .... No diretório onde o [.filename]#ca.crt# está armazenado (neste exemplo, [.filename]#/usr/local/etc/openldap#), execute: [source,shell] .... # c_rehash . .... Tanto a CA quanto o certificado do servidor agora são reconhecidos corretamente em suas respectivas funções. Para verificar isso, execute este comando no diretório [.filename]#server.crt#: [source,shell] .... # openssl verify -verbose -CApath . server.crt .... Se o [.filename]#slapd# estiver em execução, reinicie-o. Como declarado em [.filename]#/usr/local/etc/rc.d/slapd#, para executar corretamente o [.filename]#slapd# na inicialização, as seguintes linhas devem ser adicionadas ao [.filename]#/etc/rc.conf#: [.programlisting] .... lapd_enable="YES" slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://0.0.0.0/"' slapd_sockets="/var/run/openldap/ldapi" slapd_cn_config="YES" .... O [.filename]#slapd# não fornece depuração na inicialização. Verifique o [.filename]#/var/log/debug.log#, o [.filename]#dmesg -a# e o [.filename]#/var/log/messages# para este propósito. O exemplo a seguir adiciona o grupo `team` e o usuário `john` ao banco de dados LDAP de `domain.example`, que ainda está vazio. Primeiro, crie o arquivo [.filename]#domain.ldif#: [source,shell] .... # cat domain.ldif dn: dc=domain,dc=example objectClass: dcObject objectClass: organization o: domain.example dc: domain dn: ou=groups,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: groups dn: ou=users,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: users dn: cn=team,ou=groups,dc=domain,dc=example objectClass: top objectClass: posixGroup cn: team gidNumber: 10001 dn: uid=john,ou=users,dc=domain,dc=example objectClass: top objectClass: account objectClass: posixAccount objectClass: shadowAccount cn: John McUser uid: john uidNumber: 10001 gidNumber: 10001 homeDirectory: /home/john/ loginShell: /usr/bin/bash userPassword: secret .... Veja a documentação do OpenLDAP para mais detalhes. Use [.filename]#slappasswd# para substituir a senha `secret` em texto puro com um hash no `userPassword`. O caminho especificado como `loginShell` deve existir em todos sistemas onde `john` pode se logar. Finalmente, use o administrador `mdb` para modificar o banco de dados: [source,shell] .... # ldapadd -W -D "cn=mdbadmin,dc=domain,dc=example" -f domain.ldif .... Modificações para a seção _configurações globais_ podem ser feitas apenas pelo super-usuário global. Por exemplo, assume que a opção `olcTLSCipherSuite: HIGH:MEDIUM:SSLv3` foi inicialmente especificada e deve agora ser deletada. Primeiro, crie um arquivo que contenha o seguinte: [source,shell] .... # cat global_mod dn: cn=config changetype: modify delete: olcTLSCipherSuite .... Em seguida, aplique as modificações: [source,shell] .... # ldapmodify -f global_mod -x -D "cn=config" -W .... Quando solicitado, forneça a senha escolhida na seção _configuração backend_. O nome de usuário não é necessário: aqui, `cn=config` representa o DN da seção do banco de dados a ser modificada. Como alternativa, use `ldapmodify` para excluir uma única linha do banco de dados, `ldapdelete` para excluir uma entrada inteira. Se algo der errado ou se o superusuário global não puder acessar o backend de configuração, é possível excluir e reescrever toda a configuração: [source,shell] .... # rm -rf /usr/local/etc/openldap/slapd.d/ .... O [.filename]#slapd.ldif# pode então ser editado e importado novamente. Por favor, siga este procedimento somente quando nenhuma outra solução estiver disponível. Esta é a configuração do servidor apenas. A mesma máquina também pode hospedar um cliente LDAP, com sua própria configuração separada. [[network-dhcp]] == Protocolo de configuração dinâmica de hosts (DHCP) O protocolo de configuração dinâmica de hosts (DHCP) permite que um sistema se conecte a uma rede para receber as informações de endereçamento necessárias para a comunicação nessa rede. O FreeBSD inclui a versão do `dhclient` do OpenBSD que é usada pelo cliente para obter as informações de endereçamento. O FreeBSD não instala um servidor DHCP, mas vários servidores estão disponíveis na coleção de Ports do FreeBSD. O protocolo DHCP é totalmente descrito em http://www.freesoft.org/CIE/RFC/2131/[RFC 2131]. Recursos informativos também estão disponíveis em http://www.isc.org/downloads/dhcp/[isc.org/downloads/dhcp/]. Esta seção descreve como usar o cliente DHCP integrado. Em seguida, descreve como instalar e configurar um servidor DHCP. [NOTE] ==== No FreeBSD, o dispositivo man:bpf[4] é necessário tanto pelo servidor DHCP como pelo DHCP > cliente. Este dispositivo está incluído no kernel [.filename]#GENERIC# que é instalado com o FreeBSD. Usuários que preferem criar um kernel personalizado precisam manter este dispositivo se o DHCP for usado. Deve-se notar que o [.filename]#bpf# também permite que usuários privilegiados executem sniffers de pacotes de rede naquele sistema. ==== === Configurando um cliente DHCP O suporte ao cliente DHCP está incluído no instalador do FreeBSD, facilitando a configuração de um sistema recém-instalado para receber automaticamente as informações de endereçamento de rede de um servidor DHCP existente. Consulte crossref:bsdinstall[bsdinstall-post,Pós-instalação] para exemplos de configuração de rede. Quando o `dhclient` é executado na máquina cliente, ele inicia as solicitações de transmissão das informações de configuração. Por padrão, esses pedidos usam a porta UDP 68. O servidor responde na porta UDP 67 , fornecendo ao cliente um endereço IP e outras informações de rede relevantes como uma máscara de sub-rede, gateway padrão e endereços de servidor DNS. Esta informação está na forma de uma "concessão" de DHCP e é válida por um tempo configurável. Isso permite que endereços IP obsoletos para clientes que não estejam mais conectados à rede sejam reutilizados automaticamente. Clientes DHCP podem obter uma grande quantidade de informações do servidor. Uma lista exaustiva pode ser encontrada em man:dhcp-options[5]. Por padrão, quando um sistema FreeBSD inicializa, seu cliente DHCP é executado em segundo plano, ou _asynchronously_. Outros scripts de inicialização continuam sendo executados enquanto o processo DHCP é concluído, o que acelera a inicialização do sistema. O DHCP em segundo plano funciona bem quando o servidor DHCP responde rapidamente às solicitações do cliente. No entanto, o DHCP pode levar muito tempo para ser concluído em alguns sistemas. Se os serviços de rede tentarem executar antes que o DHCP tenha atribuído as informações de endereçamento de rede, eles falharão. O uso do DHCP no modo _synchronous_ impede esse problema, pois ele pausa a inicialização até que a configuração DHCP seja concluída. Esta linha no [.filename]#/etc/rc.conf# é usada para configurar o modo background ou assíncrono: [.programlisting] .... ifconfig_fxp0="DHCP" .... Esta linha pode já existir se o sistema foi configurado para usar o DHCP durante a instalação. Substitua o _fxp0_ mostrado nesses exemplos pelo nome da interface a ser configurada dinamicamente, conforme descrito em crossref:config[config-network-setup,Configurando Placas de Interface de Rede]. Para configurar o sistema para usar o modo síncrono e pausar durante a inicialização enquanto o DHCP é concluído, use "`SYNCDHCP`": [.programlisting] .... ifconfig_fxp0="SYNCDHCP" .... Opções adicionais do cliente estão disponíveis. Procure por `dhclient` in man:rc.conf[5] para detalhes. O cliente DHCP usa os seguintes arquivos: * [.filename]#/etc/dhclient.conf# + O arquivo de configuração usado pelo `dhclient`. Normalmente, esse arquivo contém apenas comentários, pois os padrões são adequados para a maioria dos clientes. Este arquivo de configuração é descrito em man:dhclient.conf[5]. * [.filename]#/sbin/dhclient# + Maiores informações sobre o comando em si podem ser encontradas em man:dhclient[8]. * [.filename]#/sbin/dhclient-script# + O script de configuração do cliente DHCP específico do FreeBSD. Ele é descrito em man:dhclient-script[8], mas não deve precisar de nenhuma modificação do usuário para funcionar corretamente. * [.filename]#/var/db/dhclient.leases.interface# + O cliente DHCP mantém um banco de dados de concessões válidas neste arquivo, que é escrito como um log e é descrito em man:dhclient.leases[5]. [[network-dhcp-server]] === Instalando e configurando um servidor DHCP -Esta seção demonstra como configurar um sistema FreeBSD para atuar como um servidor DHCP usando a implementação do servidor DHCP do Internet Systems Consortium (ISC). Esta implementação e a sua documentação podem ser instaladas usando o pacote ou port package:net/isc-dhcp43-server[]. +Esta seção demonstra como configurar um sistema FreeBSD para atuar como um servidor DHCP usando a implementação do servidor DHCP do Internet Systems Consortium (ISC). Esta implementação e a sua documentação podem ser instaladas usando o pacote ou port package:net/isc-dhcp44-server[]. -A instalação do package:net/isc-dhcp43-server[] instala um arquivo de configuração de exemplo. Copie o [.filename]#/usr/local/etc/dhcpd.conf.example# para [.filename]#/usr/local/etc/dhcpd.conf# e faça as alterações neste novo arquivo. +A instalação do package:net/isc-dhcp44-server[] instala um arquivo de configuração de exemplo. Copie o [.filename]#/usr/local/etc/dhcpd.conf.example# para [.filename]#/usr/local/etc/dhcpd.conf# e faça as alterações neste novo arquivo. O arquivo de configuração é composto de declarações para sub-redes e hosts que definem as informações que são fornecidas aos clientes DHCP. Por exemplo, essas linhas configuram o seguinte: [.programlisting] .... option domain-name "example.org";<.> option domain-name-servers ns1.example.org;<.> option subnet-mask 255.255.255.0;<.> default-lease-time 600;<.> max-lease-time 72400;<.> ddns-update-style none;<.> subnet 10.254.239.0 netmask 255.255.255.224 { range 10.254.239.10 10.254.239.20;<.> option routers rtr-239-0-1.example.org, rtr-239-0-2.example.org;<.> } host fantasia { hardware ethernet 08:00:07:26:c0:a5;<.> fixed-address fantasia.fugue.com;<.> } .... <.> Esta opção especifica o domínio de pesquisa padrão que será fornecido aos clientes. Consulte man:resolv.conf[5] para obter maiores informações. <.> Esta opção especifica uma lista separada por vírgula de servidores DNS que o cliente deve usar. Eles podem ser listados por seus nomes de domínio totalmente qualificados (FQDN), como visto no exemplo, ou por seus endereços de IP. <.> A máscara de sub-rede que será fornecida aos clientes. <.> O tempo de expiração da concessão padrão em segundos. Um cliente pode ser configurado para substituir esse valor. <.> O período máximo permitido de tempo, em segundos, para uma concessão. Se um cliente solicitar uma concessão mais longa, uma concessão ainda será emitida, mas será válida apenas para o tempo especificado em `max-lease-time`. <.> O padrão `none` desabilita as atualizações de DNS dinâmicas. Alterar isso para `interim` configura o servidor DHCP para atualizar um servidor DNS sempre que for concedido um contrato para que o servidor de DNS saiba quais endereços de IP estão associados a quais computadores na rede. Não altere a configuração padrão, a menos que o servidor de DNS tenha sido configurado para suportar DNS dinâmico. <.> Esta linha cria um conjunto de endereços IP disponíveis que são reservados para alocação a clientes DHCP. O intervalo de endereços deve ser válido para a rede ou sub-rede especificada na linha anterior. <.> Declara o gateway padrão que é válido para a rede ou sub-rede especificada antes do colchete de abertura `{`. <.> Especifica o endereço de hardware MAC de um cliente para que o servidor DHCP possa reconhecer o cliente quando ele fizer uma solicitação. <.> Especifica que este host deve sempre receber o mesmo endereço IP. A utilização do nome do host está correta, pois o servidor DHCP resolverá o nome do host antes de retornar as informações de concessão. Este arquivo de configuração suporta muito mais opções. Consulte o man:dhcpd.conf[5], instalado com o servidor, para obter detalhes e exemplos. Uma vez que a configuração do [.filename]#dhcpd.conf# estiver completa, habilite o servidor DHCP em [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" dhcpd_ifaces="dc0" .... Substitua o `dc0` pela interface (ou interfaces, separadas por espaço em branco) que o servidor DHCP deverá escutar por solicitações de clientes DHCP. Inicie o servidor executando o seguinte comando: [source,shell] .... # service isc-dhcpd start .... Quaisquer mudanças futuras na configuração do servidor exigirão que o serviço dhcpd seja interrompido e, em seguida, iniciado usando man:service[8]. O servidor DHCP usa os seguintes arquivos. Observe que as páginas de manual são instaladas com o software do servidor. * [.filename]#/usr/local/sbin/dhcpd# + Maiores informações sobre o servidor dhcpd podem ser encontradas em man:dhcpd[8]. * [.filename]#/usr/local/etc/dhcpd.conf# + O arquivo de configuração do servidor precisa conter todas as informações que devem ser fornecidas aos clientes, juntamente com informações sobre a operação do servidor. Este arquivo de configuração é descrito no man:dhcpd.conf[5]. * [.filename]#/var/db/dhcpd.leases# + O servidor DHCP mantém um banco de dados das concessões que ele emitiu neste arquivo, que é gravado como um log. Consulte man:dhcpd.leases[5], o qual fornece uma descrição um pouco mais longa. * [.filename]#/usr/local/sbin/dhcrelay# + -Esse daemon é usado em ambientes avançados, onde um servidor DHCP encaminha uma solicitação de um cliente para outro servidor DHCP em uma rede separada. Se esta funcionalidade for necessária, instale o pacote ou port package:net/isc-dhcp43-relay[]. A instalação inclui o man:dhcrelay[8], que fornece maiores detalhes. +Esse daemon é usado em ambientes avançados, onde um servidor DHCP encaminha uma solicitação de um cliente para outro servidor DHCP em uma rede separada. Se esta funcionalidade for necessária, instale o pacote ou port package:net/isc-dhcp44-relay[]. A instalação inclui o man:dhcrelay[8], que fornece maiores detalhes. [[network-dns]] == Sistema de Nomes de Domínio (DNS) O Sistema de Nomes de Domínio (DNS) é o protocolo através do qual os nomes de domínio são mapeados para endereços de IP e vice-versa. O DNS é coordenado pela Internet através de um sistema complexo de raiz de autoridade, Top Level Domain (TLD) e outros servidores de nomes de menor escala, que hospedam e armazenam em cache domínios individuais. Não é necessário executar um servidor de nomes para executar pesquisas de DNS em um sistema. A tabela a seguir descreve alguns dos termos associados ao DNS: .Terminologia DNS [cols="1,1", frame="none", options="header"] |=== | Termo | Definição |Encaminhamento de DNS |Mapeamento de nomes de hosts para endereços de IP. |Origem |Refere-se ao domínio coberto em um arquivo de zona específico. |Resolver |Um processo do sistema através do qual uma máquina consulta um servidor de nomes para informações de zona. |DNS Reverso |Mapeamento de endereços IP para hostnames. |Root zone |O início da hierarquia da zona da Internet. Todas as zonas se enquadram na zona de raiz, semelhante a como todos os arquivos em um sistema de arquivos se enquadram no diretório raiz. |Zona |Um domínio individual, subdomínio ou parte do DNS administrado pela mesma autoridade. |=== Exemplos de zonas: * `.` é como a zona root é geralmente referida na documentação. * `org.` é um domínio de nível superior (TLD) sob a zona raiz. * `example.org.` é uma zona sob o TLD `org.`. * `1.168.192.in-addr.arpa` é uma zona que faz referência a todos os endereços IP que se enquadram no espaço de endereçamento IP `192.168.1.*` . Como se pode ver, a parte mais específica de um nome de host aparece à esquerda. Por exemplo, `example.org.` é mais específico que `org.`, como `org.` é mais específico que a zona raiz . O layout de cada parte de um nome de host é muito parecido com um sistema de arquivos: o diretório [.filename]#/dev# está dentro da raiz e assim por diante. === Razões para executar um servidor de nomes Os servidores de nomes geralmente vêm em duas formas: servidores de nomes autoritativos e servidores de nomes de armazenamento em cache (também conhecidos como servidores de resolução). Um servidor de nomes autoritativo é necessário quando: * Alguém quer servir ao mundo informações de DNS, respondendo autoritariamente a consultas. * Um domínio, como `example.org`, está registrado e os endereços IP precisam ser atribuídos a nomes de host sob ele. * Um bloco de endereços IP requer entradas reversas de DNS (IP para hostname). * Um servidor de nomes de backup ou secundário, chamado de escravo, responderá às consultas. Um servidor de nomes em cache é necessário quando: * Um servidor DNS local pode armazenar em cache e responder mais rapidamente do que consultar um servidor de nomes externo. Quando alguém pergunta por `www.FreeBSD.org`, o resolvedor geralmente consulta o servidor de nomes do ISP e recupera a resposta. Com um servidor local, de cache DNS, a consulta só precisa ser feita uma vez para o mundo externo pelo servidor de Cache DNS. Consultas adicionais não precisarão sair da rede local, pois as informações estão armazenadas em um cache local. === Configuração do servidor de DNS O Unbound é fornecido no sistema básico do FreeBSD. Por padrão, ele fornecerá a resolução de DNS apenas para a máquina local. Embora o pacote básico do sistema possa ser configurado para fornecer serviços de resolução além da máquina local, é recomendável que esses requisitos sejam resolvidos instalando o Unbound da coleção de ports do FreeBSD. Para ativar o Unbound, adicione o seguinte ao [.filename]#/etc/rc.conf#: [.programlisting] .... local_unbound_enable="YES" .... Quaisquer servidores de nomes existentes em [.filename]#/etc/resolv.conf# serão configurados como forwarders na nova configuração do Unbound. [NOTE] ==== Se algum dos servidores de nomes listados não suportar o DNSSEC, a resolução local DNS falhará. Certifique-se de testar cada servidor de nomes e remover qualquer um que falhe no teste. O seguinte comando mostrará a árvore de confiança ou uma falha para um servidor de nomes em execução em `192.168.1.1`: ==== [source,shell] .... % drill -S FreeBSD.org @192.168.1.1 .... Quando cada servidor de nomes for confirmado para suportar DNSSEC, inicie o Unbound: [source,shell] .... # service local_unbound onestart .... Isso cuidará da atualização do arquivo [.filename]#/etc/resolv.conf# para que as consultas para domínios seguros DNSSEC funcionem agora. Por exemplo, execute o seguinte DNSSEC para validar a árvore confiável do FreeBSD.org : [source,shell] .... % drill -S FreeBSD.org ;; Number of trusted keys: 1 ;; Chasing: freebsd.org. A DNSSEC Trust tree: freebsd.org. (A) |---freebsd.org. (DNSKEY keytag: 36786 alg: 8 flags: 256) |---freebsd.org. (DNSKEY keytag: 32659 alg: 8 flags: 257) |---freebsd.org. (DS keytag: 32659 digest type: 2) |---org. (DNSKEY keytag: 49587 alg: 7 flags: 256) |---org. (DNSKEY keytag: 9795 alg: 7 flags: 257) |---org. (DNSKEY keytag: 21366 alg: 7 flags: 257) |---org. (DS keytag: 21366 digest type: 1) | |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) | |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) |---org. (DS keytag: 21366 digest type: 2) |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) ;; Chase successful .... [[network-apache]] == Servidor HTTP Apache O open source Apache HTTP Server é o servidor Web mais utilizado. O FreeBSD não instala este servidor web por padrão, mas ele pode ser instalado a partir do pacote ou Port package:www/apache24[]. Esta seção resume como configurar e iniciar a versão 2._x_ do Servidor HTTP Apache no FreeBSD. Para informações mais detalhadas sobre o Apache2.X e suas diretivas de configuração, consulte http://httpd.apache.org/[httpd.apache.org]. === Configurando e Iniciando o Apache No FreeBSD, o arquivo de configuração principal do Apache HTTP Server é instalado como [.filename]#/usr/local/etc/apache2x/httpd.conf#, onde _x_ representa o número da versão. Este arquivo ASCII de texto inicia as linhas de comentário com um `#`. As diretivas modificadas com mais freqüência são: `ServerRoot "/usr/local"`:: Especifica a hierarquia de diretório padrão para a instalação do Apache. Os binários são armazenados nos subdiretórios [.filename]#bin# e [.filename]#sbin# da raiz do servidor e os arquivos de configuração são armazenados no subdiretório [.filename]#etc/apache2x#. `ServerAdmin you@example.com`:: Altere isso para seu endereço de e-mail para receber problemas com o servidor. Esse endereço também aparece em algumas páginas geradas pelo servidor, como documentos de erro. `ServerName www.example.com:80`:: Permite que um administrador defina um nome de host que é enviado de volta aos clientes pelo servidor. Por exemplo, `www` pode ser usado em vez do nome do host real. Se o sistema não tiver um nome registrado no DNS, insira seu endereço IP. Se o servidor irá escutar em um relatório alternativo, altere a porta `80` para o número de porta alternativa. `DocumentRoot "/usr/local/www/apache2__x__/data"`:: O diretório no qual os documentos serão exibidos. Por padrão, todas as solicitações são obtidas desse diretório, mas os links e aliases simbólicos podem ser usados para apontar para outros locais. É sempre uma boa ideia fazer uma cópia de backup do arquivo de configuração do Apache padrão antes de fazer alterações. Quando a configuração do Apache estiver concluída, salve o arquivo e verifique a configuração usando o `apachectl`. A execução do `apachectl configtest` deve retornar `Syntax OK`. Para iniciar o Apache na inicialização do sistema, adicione a seguinte linha ao [.filename]#/etc/rc.conf#: [.programlisting] .... apache24_enable="YES" .... Se o Apache deve ser iniciado com opções não-padrão, a seguinte linha pode ser adicionada ao [.filename]#/etc/rc.conf# para especificar os flags necessários: [.programlisting] .... apache24_flags="" .... Se o apachectl não relatar erros de configuração, inicie o `httpd` agora: [source,shell] .... # service apache24 start .... O serviço `httpd` pode ser testado inserindo `http://_localhost_` em um navegador da Web, substituindo _localhost_ pelo nome de domínio totalmente qualificado da máquina que está executando o `httpd`. A página padrão da Web exibida é [.filename]#/usr/local/www/apache24/data/index.html#. A configuração do Apache pode ser testada quanto a erros depois de fazer alterações subsequentes de configuração enquanto o `httpd` está em execução usando o seguinte comando: [source,shell] .... # service apache24 configtest .... [NOTE] ==== É importante notar que o `configtest` não é um padrão man:rc[8] e não se espera que funcione para todos os scripts de inicialização. ==== === Hospedagem Virtual A hospedagem virtual permite que vários sites sejam executados em um servidor Apache. Os hosts virtuais podem ser _baseados em IP_ ou _baseados em nome_. A hospedagem virtual baseada em IP usa um endereço IP diferente para cada site. A hospedagem virtual baseada em nome usa os cabeçalhos HTTP/1.1 do cliente para descobrir o nome do host, o que permite que os sites compartilhem o mesmo endereço de IP. Para configurar o Apache para usar hospedagem virtual baseada em nome, adicione um bloco `VirtualHost` para cada site. Por exemplo, para o servidor Web denominado `www.domain.tld` com um domínio virtual de `www.someotherdomain.tld`, adicione as seguintes entradas ao arquivo [.filename]#httpd.conf#: [.programlisting] .... ServerName www.domain.tld DocumentRoot /www/domain.tld ServerName www.someotherdomain.tld DocumentRoot /www/someotherdomain.tld .... Para cada host virtual, substitua os valores de `ServerName` e `DocumentRoot` pelos valores a serem usados. Para obter mais informações sobre como configurar hosts virtuais, consulte a documentação oficial do Apache em: http://httpd.apache.org/docs/vhosts/[http://httpd.apache.org/docs/vhosts/]. === Módulos Apache O Apache usa módulos para aumentar a funcionalidade fornecida pelo servidor básico. Consulte o http://httpd.apache.org/docs/current/mod/[http://httpd.apache.org/docs/current/mod/] para uma lista completa e detalhes de configuração para os módulos disponíveis. No FreeBSD, alguns módulos podem ser compilados com o port package:www/apache24[]. Digite `make config` dentro do diretório [.filename]#/usr/ports/www/apache24# para ver quais módulos estão disponíveis e quais estão ativados por padrão. Se o módulo não é compilado com o port, a Coleção de Ports do FreeBSD fornece uma maneira fácil de instalar vários módulos. Esta seção descreve três dos módulos mais usados. ==== Suporte SSL Em algum momento, o suporte para o SSL dentro do Apache requer um modulo secundário chamado [.filename]#mod_ssl#. Esse não é mais o casoe a instalação padrão do Apache vem com SSL embutido no servidor web. Um exemplo de como habilitar o suporte para paginas com SSL está disponível no arquivo [.filename]#http-ssl.conf# instalado dentro do diretório [.filename]#/usr/local/etc/apache24/extra#. Dentro desse diretório também esta um exemplo do arquivo chamado [.filename]#ssl.conf-sample#. É recomendado que ambos arquivos sejam avaliados para configurar apropriadamente páginas seguras no servidor web Apache. Depois da configuração do SSL estiver completa, deve ser removido o comentário da linha seguinte no arquivo [.filename]#http.conf# principal para ativar as mudanças no próximo restart ou reload do Apache: [.programlisting] .... #Include etc/apache24/extra/httpd-ssl.conf .... [WARNING] ==== Versão dois do SSL e a versão três tem problemas de vulnerabilidades conhecidas. É altamente recomendado a versão 1.2 do TLS e 1.3 deve ser habilitada no lugar das velhas opções do SSL. Isso pode ser realizado configurando as seguintes opções no arquivo [.filename]#ssl.conf#: ==== [.programlisting] .... SSLProtocol all -SSLv3 -SSLv2 +TLSv1.2 +TLSv1.3 SSLProxyProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 .... Para completar a configuração do SSL no servidor web, remova os comentários da seguinte linha para garantir que a configuração irá ser enviada para dentro do Apache durante o restart ou reload: [.programlisting] .... # Secure (SSL/TLS) connections Include etc/apache24/extra/httpd-ssl.conf .... As linhas a seguir também devem ser descomentadas no [.filename]#httpd.conf# para suportar totalmente o SSL no Apache: [.programlisting] .... LoadModule authn_socache_module libexec/apache24/mod_authn_socache.so LoadModule socache_shmcb_module libexec/apache24/mod_socache_shmcb.so LoadModule ssl_module libexec/apache24/mod_ssl.so .... O próximo passo é trabalhar com uma autoridade certificadora para ter certificados apropriados instalados no sistema. Isso vai configurar um cadeia de confiança para a pagina e prever alguns avisos de certificados auto assinados. ==== [.filename]#mod_perl# O módulo [.filename]#mod_perl# torna possível escrever módulos Apache em Perl. Além disso, o intérprete persistente embutido no servidor evita a sobrecarga de iniciar um intérprete externo e a penalidade do tempo de inicialização do Perl. O [.filename]#mod_perl# pode ser instalado usando o pacote ou port package:www/mod_perl2[]. A documentação para usar este módulo pode ser encontrada em http://perl.apache.org/docs/2.0/index.html[http://perl.apache.org/docs/2.0/index .html]. ==== [.filename]#mod_php# _PHP: Pré-processador de hipertexto_ ( PHP ) é uma linguagem de script de propósito geral que é especialmente adequada para desenvolvimento web. Capaz de ser incorporada em HTML, sua sintaxe se baseia em C, Java(TM) e Perl com a intenção de permitir desenvolvedores web para escrever rapidamente páginas da web geradas dinamicamente. Suporte para PHP para o Apache e alguma outra parte escrita na linguagem, pode ser adicionada instalando o port apropriado. Para todas versões suportadas, procure os dados do pacote usando o comando `pkg`: [source,shell] .... # pkg search php .... Uma lista vai ser disponibilizada incluindo as versões e partes adicionais que elas proverem. Os componentes são completamente modulares, significando que as partes especificas são habilitadas instalando o port apropriado. Para instalar o PHP na versão 7.4 para o Apache, use o seguinte comando: [source,shell] .... # pkg install mod_php74 .... Se algum pacote dependente precisar ser instalado, ele irá ser instalado também. Por padrão, o PHP não estará habilitado. As seguintes linhas precisam ser adicionadas no arquivo de configuração do Apache localizado em [.filename]#/usr/local/etc/apache24# para ativa-lo: [.programlisting] .... SetHandler application/x-httpd-php SetHandler application/x-httpd-php-source .... Em adição, a opção `DirectoryIndex` no arquivo de configuração irá precisar ser atualizada também e o Apache irá precisar ser reiniciado ou feito um relaoad também para as mudanças surtirem efeito. Suporte para muitas partes do PHP podem ser instalado também usando o comando `pkg`. Por exemplo, para instalar suporte para o XML ou para SSL, instale os seguintes ports: [source,shell] .... # pkg install php74-xml php74-openssl .... Como antes, a configuração do Apache irá precisar ser recarregada para as mudanças surtirem efeito, mesmo em casos onde foi feita apenas a instalação de um modulo. Para realizar uma reinicialização normal para recarregar a configuração, digite o seguinte comando: [source,shell] .... # apachectl graceful .... Uma vez que a instalação esteja completa, há dois métodos para obter o suporte para os modulos do PHP e a informação do ambiente dessa instalação. A primeira é instalar o binário completo do PHP e rodar o seguinte comando para obter a informação: [source,shell] .... # pkg install php74 .... [source,shell] .... # php -i |less .... Isso é necessário para passar a saída paga um paginador, como o comando `more` ou `less` para visualizar melhor a saída. Finalmente, para fazer alguma mudança na configuração global do PHP há um arquivo bem documentado instalado dentro de [.filename]#/usr/local/etc/php.ini#. No momento da instalação, esse arquivo não irá existir porque há duas versões para escolher, uma é o arquivo [.filename]#php.ini-development# e outra o [.filename]#php.ini-production#. Esses são pontos iniciais para ajudar os administradores na implementação. ==== Suporte a HTTP2 Suporte do Apache para o protocolo HTTP está incluido por padrão quando instala o port com o comando `pkg`. A nova versão do HTTP inclui muitas melhorias em relação a versão anterior, incluindo utilizar uma conexão singular para uma página, reduzindo as idas e vindas de conexões TCP. Também, os dados no cabeçalho do pacote é comprimido e o HTTP2 requer encriptação por padrão. Quando o Apache estiver configurado para usar HTTP2 apenas, os navegadores web irão requisitar conexões seguras, encriptadas com HTTPS. Quando o Apache estiver configurado para usar ambas versões, o HTTP1.1 irá ser considerado uma opção substituta se algum problema surgir durante a conexão. Embora essa mudança exija que os administradores façam alterações, elas são positivas e equivalem a uma Internet mais segura para todos. As mudanças são requeridas apenas para paginas não implementada corretamente com SSL e TLS. [NOTE] ==== Essa configuração depende das seções anteriores, incluindo suporte a TLS. É recomendado que essas instruções seja seguidas antes de continuar com essa configuração. ==== Comece o processo habilitando o modulo http2 removendo o comentário da linha no arquivo [.filename]#/usr/local/etc/apache24/httpd.conf# e trocando o modulo mpm_prefork pelo mpm_event pois o anterior não suporta o http2. [.programlisting] .... LoadModule http2_module libexec/apache24/mod_http2.so LoadModule mpm_event_module libexec/apache24/mod_mpm_event.so .... [NOTE] ==== Aqui há um port [.filename]#mod_http1# distinto que está disponível. Ele existe pra entregar segurança e correção de bugs mais rápido que o modulo instalado por padrão com o port [.filename]#apache24#. Ele não é requisitado para o suporte do HTTP2 mas está disponível. Quando instalado, o [.filename]#mod_h2.so# deve ser usado no lugar do [.filename]#mod_http2.so# na configuração do Apache. ==== Aqui há dois métodos para implementar o HTTP2 no Apache; um caminho é de forma global para todos os sites e cada VirtualHost rodando no sistema. Para habilitar o HTTP2 globalmente, adicione a seguinte linha abaixo da diretiva ServerName: [.programlisting] .... Protocolos h2 http/1.1 .... [NOTE] ==== Para habilitar HTTP2 sobre texto simples, use h2h2chttp/1.1 no arquivo [.filename]#httpd.conf#. ==== Tendo o h2c aqui irá permitir que o dado em texto simples do HTTP2 passar pelo sistema mas isso não é recomendado. Em adição a isso, usando o http/1.1 aqui irá permitir retornar para a versão do protocolo HTTP1.1 caso sejá necessário pelo sistema. Para habilitar HTTP2 para VirtualHosts individuais, adicione a mesma linha com a diretiva VirtualHost no arquivo [.filename]#httpd.conf# ou [.filename]#httpd-ssl.conf#. Recarregue a configuração usando o comando `apachectl` reload e teste a configuração seguindo um dos métodos após visitar uma das paginas hosteadas: [source,shell] .... # grep "HTTP/2.0" /var/log/httpd-access.log .... A saída deve ser semelhante à seguinte: [.programlisting] .... 192.168.1.205 - - [18/Oct/2020:18:34:36 -0400] "GET / HTTP/2.0" 304 - 192.0.2.205 - - [18/Oct/2020:19:19:57 -0400] "GET / HTTP/2.0" 304 - 192.0.0.205 - - [18/Oct/2020:19:20:52 -0400] "GET / HTTP/2.0" 304 - 192.0.2.205 - - [18/Oct/2020:19:23:10 -0400] "GET / HTTP/2.0" 304 - .... O outro metodo é usar o navegador web padrão no debugger do site ou o comando `tcpdump`; contanto, o uso de qualquer método está além do escopo desse documento. Suporte para conexões do proxy reverso HTTP2 usando o modulo [.filename]#mod_proxy_http2.so#. Quando declarado na configuração o ProxyPass ou RewriteRules [P], eles devem usar h2:// para a conexão. === Websites Dinâmicos Além do mod_perl e do mod_php, outras linguagens estão disponíveis para a criação de conteúdo dinâmico da web. Estes incluem o Django e o Ruby on Rails. ==== Django O Django é um framework de licença BSD projetado para permitir que desenvolvedores escrevam aplicações web elegantes e de alto desempenho rapidamente. Ele fornece um mapeador relacional de objeto para que os tipos de dados sejam desenvolvidos como objetos Python. Uma API rica e dinâmica de acesso ao banco de dados é fornecida para os objetos sem que o desenvolvedor tenha que escrever SQL. Ele também fornece um sistema de template extensível para que a lógica do aplicativo seja separada da apresentação HTML. Django depende de [.filename]#mod_python#, e um mecanismo de banco de dados SQL. No FreeBSD, o port package:www/py-django[] instala automaticamente o [.filename]#mod_python# e suporta os banco de dados PostgreSQL, MySQL, ou SQLite, com o padrão sendo o SQLite. Para trocar o mecanismo de banco de dados, digite `make config` dentro do diretório [.filename]#/usr/ports/www/py-django#, então instale o port. Uma vez instalado o Django, a aplicação precisará de um diretório de projeto junto com a configuração Apache para usar o interpretador Python incorporado. Este intérprete é usado para chamar o aplicativo para URLs específicas no site. Para configurar o Apache para que passe a fazer solicitações para determinadas URLs para a aplicação Web, adicione o seguinte ao [.filename]#httpd.conf#, especificando o caminho completo para o diretório do projeto: [.programlisting] .... SetHandler python-program PythonPath "['/dir/to/the/django/packages/'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonAutoReload On PythonDebug On .... Consulte https://docs.djangoproject.com[https://docs.djangoproject.com] para maiores informações sobre como usar o Django. ==== Ruby on Rails O Ruby on Rails é outro framework de software livre da Web que fornece uma stack de desenvolvimento completa. Ele é otimizado para tornar os desenvolvedores da Web mais produtivos e capazes de criar rapidamente aplicativos poderosos. No FreeBSD, ele pode ser instalado usando o pacote ou port package:www/rubygem-rails[]. Consulte http://guides.rubyonrails.org[http://guides.rubyonrails.org] para maiores informações sobre como usar o Ruby on Rails . [[network-ftp]] == Protocolo de Transferência de Arquivos (FTP) O Protocolo de Transferência de Arquivos (FTP) fornece aos usuários uma maneira simples de transferir arquivos para um servidor FTP. O FreeBSD inclui o software do servidor FTP, ftpd, no sistema base. O FreeBSD fornece vários arquivos de configuração para controlar o acesso ao servidor FTP. Esta seção resume esses arquivos. Consulte man:ftpd[8] para obter mais detalhes sobre o servidor FTP incorporado. === Configuração A etapa de configuração mais importante é decidir quais contas terão permissão para acessar o servidor FTP. Um sistema FreeBSD possui várias contas do sistema que não devem ter acesso ao FTP. A lista de usuários que não permitem acesso FTP pode ser encontrada em [.filename]#/etc/ftpusers#. Por padrão, inclui contas do sistema. Usuários adicionais que não devem ter acesso a FTP podem ser adicionados. Em alguns casos, pode ser desejável restringir o acesso de alguns usuários sem impedi-los completamente de usar o FTP. Isso pode ser feito criando [.filename]#/etc/ftpchroot# como descrito em man:ftpchroot[5]. Este arquivo lista usuários e grupos sujeitos a restrições de acesso a FTP. Para permitir acesso anônimo ao servidor FTP, crie um usuário chamado `ftp` no sistema FreeBSD. Os usuários poderão então fazer logon no servidor FTP com um nome de usuário `ftp` ou `anonymous` . Quando for solicitada a senha, qualquer entrada será aceita, mas por convenção, um endereço de e-mail deverá ser usado como a senha. O servidor FTP chamará man:chroot[2] quando um usuário anônimo efetuar login para restringir o acesso somente ao diretório home do usuário `ftp`. Existem dois arquivos de texto que podem ser criados para especificar mensagens de boas-vindas a serem exibidas para clientes FTP. O conteúdo de [.filename]#/etc/ftpwelcome# será exibido aos usuários antes que eles atinjam o prompt de login. Após um login bem sucedido, o conteúdo de [.filename]#/etc/ftpmotd# será exibido. Observe que o caminho para esse arquivo é relativo ao ambiente de login, portanto, o conteúdo de [.filename]#~ftp/etc/ftpmotd# seria exibido para usuários anônimos. Uma vez configurado o servidor FTP, defina a variável apropriada em [.filename]#/etc/rc.conf# para iniciar o serviço durante a inicialização: [.programlisting] .... ftpd_enable="YES" .... Para iniciar o serviço agora: [source,shell] .... # service ftpd start .... Teste a conexão com o servidor FTP digitando: [source,shell] .... % ftp localhost .... O daemon ftpd usa o man:syslog[3] para registrar mensagens. Por padrão, o daemon de log do sistema gravará mensagens relacionadas a FTP em [.filename]#/var/log/xferlog#. A localização do log do FTP pode ser modificada alterando a seguinte linha no [.filename]#/etc/syslog.conf#: [.programlisting] .... ftp.info /var/log/xferlog .... [NOTE] ==== Esteja ciente dos possíveis problemas envolvidos na execução de um servidor FTP anônimo. Em particular, pense duas vezes antes de permitir que usuários anônimos façam upload de arquivos. Pode acontecer que o site FTP se torne um fórum para o comércio de software comercial não licenciado ou pior. Se uploads anônimos de FTP forem necessários, verifique as permissões para que esses arquivos não possam ser lidos por outros usuários anônimos até que sejam revisados por um administrador. ==== [[network-samba]] == Serviços de arquivos e impressão para clientes Microsoft(TM)Windows(TM) Clients (Samba) Samba é um popular pacote de software de código aberto que fornece serviços de arquivo e impressão usando o protocolo SMB/CIFS. Este protocolo está incorporado nos sistemas Microsoft(TM)Windows(TM). Ele pode ser adicionado a sistemas não Microsoft(TM)Windows(TM) instalando as bibliotecas-cliente Samba. O protocolo permite que os clientes acessem dados e impressoras compartilhadas. Esses compartilhamentos podem ser mapeados como uma unidade de disco local e as impressoras compartilhadas podem ser usadas como se fossem impressoras locais. No FreeBSD, as bibliotecas cliente do Samba podem ser instaladas usando o port ou pacote package:net/samba410[]. O cliente fornece a capacidade de um sistema FreeBSD acessar compartilhamentos de SMB/CIFS em uma rede Microsoft(TM)Windows(TM). Um sistema FreeBSD também pode ser configurado para atuar como um servidor Samba instalando o port ou pacote package:net/samba410[]. Isso permite que o administrador crie compartilhamentos de SMB/CIFS no sistema FreeBSD que podem ser acessados por clientes executando Microsoft(TM)Windows(TM) ou as bibliotecas do cliente Samba. === Configuração do Servidor O Samba é configurado em [.filename]#/usr/local/etc/smb4.conf#. Este arquivo deve ser criado antes que o Samba possa ser usado. Um simples [.filename]#smb4.conf# para compartilhar diretórios e impressoras com clientes Windows(TM) em um grupo de trabalho é mostrado aqui. Para configurações mais complexas envolvendo LDAP ou Active Directory, é mais fácil usar o man:samba-tool[8] para criar o [.filename]#smb4.conf#. [.programlisting] .... [global] workgroup = WORKGROUP server string = Samba Server Version %v netbios name = ExampleMachine wins support = Yes security = user passdb backend = tdbsam # Example: share /usr/src accessible only to 'developer' user [src] path = /usr/src valid users = developer writable = yes browsable = yes read only = no guest ok = no public = no create mask = 0666 directory mask = 0755 .... ==== Configurações Globais As configurações que descrevem a rede são adicionadas em [.filename]#/usr/local/etc/smb4.conf#: `workgroup`:: O nome do grupo de trabalho a ser servido. `netbios name`:: O nome NetBIOS pelo qual um servidor Samba é conhecido. Por padrão, é o mesmo que o primeiro componente do nome do DNS do host. `server string`:: A string que será exibida na saída de `net view` e algumas outras ferramentas de rede que buscam exibir texto descritivo sobre o servidor. `wins support`:: Se o Samba funcionará como um servidor WINS. Não habilite o suporte para WINS em mais de um servidor na rede. ==== Configurações de Segurança As configurações mais importantes em [.filename]#/usr/local/etc/smb4.conf# são o modelo de segurança e o formato de senha de backend. Essas diretivas controlam as opções: `security`:: As configurações mais comuns são `security=share` e `security=user`. Se os clientes usarem nomes de usuários que sejam os mesmos nomes de usuários na máquina do FreeBSD, a segurança no nível do usuário deve ser usada. Essa é a política de segurança padrão e exige que os clientes façam logon pela primeira vez antes de poderem acessar recursos compartilhados. + Na segurança em nível de compartilhamento, os clientes não precisam efetuar logon no servidor com um nome de usuário e senha válidos antes de tentar se conectar a um recurso compartilhado. Este era o modelo de segurança padrão para versões mais antigas do Samba. `passdb backend`:: O Samba possui vários modelos de autenticação de backend diferentes. Os clientes podem ser autenticados com LDAP, NIS+, um banco de dados SQL ou um arquivo de senha modificado. O método de autenticação recomendado, `tdbsam`, é ideal para redes simples e é abordado aqui. Para redes maiores ou mais complexas, o `ldapsam` é recomendado. `smbpasswd` foi o padrão anterior e agora está obsoleto. ==== Usuários do Samba As contas de usuário do FreeBSD devem ser mapeadas para o banco de dados `SambaSAMAccount` para que os clientes Windows(TM) acessem o compartilhamento. Mapear contas de usuários existentes do FreeBSD usando man:pdbedit[8]: [source,shell] .... # pdbedit -a username .... Esta seção mencionou apenas as configurações mais usadas. Consulte a https://wiki.samba.org[Wiki Oficial do Samba] para obter informações adicionais sobre as opções de configuração disponíveis. === Iniciando o Samba Para habilitar o Samba no momento da inicialização, adicione a seguinte linha ao [.filename]#/etc/rc.conf#: [.programlisting] .... samba_server_enable="YES" .... Para iniciar o Samba agora: [source,shell] .... # service samba_server start Performing sanity check on Samba configuration: OK Starting nmbd. Starting smbd. .... O Samba consiste em três daemons separados. Os daemons nmbd e smbd são iniciados por `samba_enable`. Se resolução de nomes winbind também é necessária, defina: [.programlisting] .... winbindd_enable="YES" .... O Samba pode ser interrompido a qualquer momento digitando: [source,shell] .... # service samba_server stop .... O Samba é um conjunto de software complexo com funcionalidade que permite ampla integração com as redes Microsoft(TM)Windows(TM). Para mais informações sobre a funcionalidade além da configuração básica descrita aqui, consulte https://www.samba.org[https://www.samba.org]. [[network-ntp]] == Sincronização de Relógio com NTP Com o tempo, o relógio de um computador está propenso a se desviar. Isso é problemático, pois muitos serviços de rede exigem que os computadores em uma rede compartilhem o mesmo tempo exato. Tempo preciso também é necessário para garantir que os registros de data e hora dos arquivos permaneçam consistentes. O protocolo de horário da rede (NTP) é uma maneira de fornecer precisão de relógio em uma rede. O FreeBSD inclui o man:ntpd[8] o qual pode ser configurado para consultar outros servidores NTP para sincronizar o relógio nessa máquina ou para fornecer serviços de horário para outros computadores na rede. Esta seção descreve como configurar o ntpd no FreeBSD. Mais documentação pode ser encontrada em [.filename]#/usr/shared/doc/ntp/# no formato HTML. === Configuração de NTP No FreeBSD, o ntpd nativo pode ser usado para sincronizar o relógio do sistema. O Ntpd é configurado usando variáveis no man:rc.conf[5] e no [.filename]#/etc/ntp.conf#, conforme detalhado nas seções a seguir. O Ntpd se comunica com seus network peers usando pacotes UDP. Quaisquer firewalls entre sua máquina e seus NTP peers devem ser configurados para permitir a entrada e saída de pacotes UDP na porta 123. ==== O arquivo [.filename]#/etc/ntp.conf# O Ntpd faz a leitura do [.filename]#/etc/ntp.conf# para determinar quais servidores NTP que ele deve consultar. É recomendável escolher vários servidores NTP, caso um dos servidores se torne inacessível ou seu relógio torne-se não confiável. Como o ntpd recebe respostas, ele favorece servidores confiáveis em vez dos menos confiáveis. Os servidores consultados podem ser locais na rede, fornecidos por um ISP ou selecionados a partir de uma http://support.ntp.org/bin/view/Servers/WebHome[ lista online de servidores NTP publicamente acessíveis]. Ao escolher um servidor NTP público, selecione um servidor geograficamente próximo e revise sua política de uso. A palavra-chave `pool` de configuração seleciona um ou mais servidores de um pool de servidores. Está disponível uma http://support.ntp.org/bin/view/Servers/NTPPoolServers[ lista online de pools NTP publicamente acessíveis], organizada por área geográfica. Além disso, o FreeBSD fornece um pool patrocinado pelo projeto, `0.freebsd.pool.ntp.org`. .Exemplo de [.filename]#/etc/ntp.conf# [example] ==== Este é um exemplo simples de um arquivo [.filename]#ntp.conf#. Ele pode ser usado com segurança como está; ele contém as opções `restrict` recomendadas para operação em uma conexão de rede pública. [.programlisting] .... # Disallow ntpq control/query access. Allow peers to be added only # based on pool and server statements in this file. restrict default limited kod nomodify notrap noquery nopeer restrict source limited kod nomodify notrap noquery # Allow unrestricted access from localhost for queries and control. restrict 127.0.0.1 restrict ::1 # Add a specific server. server ntplocal.example.com iburst # Add FreeBSD pool servers until 3-6 good servers are available. tos minclock 3 maxclock 6 pool 0.freebsd.pool.ntp.org iburst # Use a local leap-seconds file. leapfile "/var/db/ntpd.leap-seconds.list" .... ==== O formato deste arquivo é descrito em man:ntp.conf[5]. As descrições abaixo fornecem uma visão geral rápida apenas das palavras-chave usadas no arquivo de exemplo acima. Por padrão, um servidor NTP pode ser acessado de qualquer host da rede. A palavra-chave `restrict` controla quais sistemas podem acessar o servidor. Múltiplas entradas `restrict` são suportadas, cada uma refinando as restrições fornecidas nas instruções anteriores. Os valores mostrados no exemplo concedem ao sistema local o acesso completo à consulta e controle, enquanto permitem aos sistemas remotos apenas a capacidade de consultar o horário. Para obter mais detalhes, consulte a subseção `Access Control Support` de man:ntp.conf[5]. A palavra-chave `server` especifica um único servidor para consulta. O arquivo pode conter várias palavras-chave server, com um servidor listado em cada linha. A palavra-chave `pool` especifica um pool de servidores. O Ntpd adicionará um ou mais servidores desse pool, conforme necessário, para atingir o número de peers especificado usando o valor `tos minclock`. A palavra-chave `iburst` direciona o ntpd para executar um burst de oito trocas rápidas de pacotes com um servidor quando o contato é estabelecido pela primeira vez, para ajudar a sincronizar rapidamente a hora do sistema. A palavra-chave `leapfile` especifica o local de um arquivo que contém informações sobre segundos bissextos. O arquivo é atualizado automaticamente pelo man:periodic[8]. O local do arquivo especificado por esta palavra-chave deve corresponder ao local definido na variável `ntp_db_leapfile` em [.filename]#/etc/rc.conf#. ==== Entradas NTP no [.filename]#/etc/rc.conf# Defina `ntpd_enable=YES` para iniciar o ntpd no momento do boot do sistema. Depois que o `ntpd_enable=YES` for adicionado ao [.filename]#/etc/rc.conf#, o ntpd poderá ser iniciado imediatamente sem reiniciar o sistema, digitando: [source,shell] .... # service ntpd start .... Somente `ntpd_enable` deve ser configurado para usar o ntpd. As variáveis [.filename]#rc.conf# listadas abaixo também podem ser definidas conforme necessário. Defina `ntpd_sync_on_start=YES` para permitir que o ntpd adiante o relógio, uma vez na inicialização. Normalmente, o ntpd registra uma mensagem de erro e se finaliza se o relógio estiver dessincronizado por mais de 1000 segundos. Essa opção é especialmente útil em sistemas sem um relógio em tempo real com bateria. Defina `ntpd_oomprotect=YES` para proteger o serviço ntpd de ser finalizado pelo sistema quando ele tentar se recuperar de uma condição de Falta de Nemória (OOM). Defina `ntpd_config=` para o local de um arquivo [.filename]#ntp.conf# alternativo. Defina `ntpd_flags=` para conter outras flags ntpd conforme necessário, mas evite usar as flags gerenciadas internamente pelo [.filename]#/etc/rc.d/ntpd#: * `-p` (local do arquivo pid) * `-c` (configure `ntpd_config=` como alternativa) ==== O Ntpd e o usuário não privilegiado `ntpd` O Ntpd no FreeBSD pode ser iniciado e executado como um usuário não privilegiado. Para isso, é necessário o módulo de política man:mac_ntpd[4]. O script de inicialização [.filename]#/etc/rc.d/ntpd# examina primeiro a configuração do NTP. Se possível, ele carrega o módulo `mac_ntpd` e inicia o ntpd como um usuário não vinculado `ntpd` (user id 123). Para evitar problemas com o acesso a arquivos e diretórios, o script de inicialização não iniciará automaticamente o ntpd como `ntpd` quando a configuração contiver quaisquer opções relacionadas a arquivos. A presença de qualquer um dos itens a seguir em `ntpd_flags` requer configuração manual, conforme descrito abaixo, para ser executada como o usuário `ntpd` user: * -f or --driftfile * -i or --jaildir * -k or --keyfile * -l or --logfile * -s or --statsdir A presença de qualquer uma das seguintes palavras-chave no [.filename]#ntp.conf# requer configuração manual, conforme descrito abaixo, para ser executado como usuário `ntpd`: * crypto * driftfile * key * logdir * statsdir Para configurar manualmente o ntpd para ser executado como usuário `ntpd`, você deve: * Certifique-se de que o usuário `ntpd` tenha acesso a todos os arquivos e diretórios especificados na configuração. * Se certifique para que o módulo `mac_ntpd` seja carregado ou compilado no kernel. Consulte man:mac_ntpd[4] para obter detalhes. * Defina `ntpd_user="ntpd"` no [.filename]#/etc/rc.conf# === Usando NTP com uma Conexão PPP O ntpd não precisa de uma conexão permanente com a Internet para funcionar corretamente. No entanto, se uma conexão PPP estiver configurada para discar sob demanda, o tráfego de NTP deverá ser impedido de disparar uma discagem ou manter a conexão ativa. Isso pode ser configurado com as diretivas `filter` em [.filename]#/etc/ppp/ppp.conf#. Por exemplo: [.programlisting] .... set filter dial 0 deny udp src eq 123 # Prevent NTP traffic from initiating dial out set filter dial 1 permit 0 0 set filter alive 0 deny udp src eq 123 # Prevent incoming NTP traffic from keeping the connection open set filter alive 1 deny udp dst eq 123 # Prevent outgoing NTP traffic from keeping the connection open set filter alive 2 permit 0/0 0/0 .... Para mais detalhes, consulte a seção `PACKET FILTERING` em man:ppp[8] e os exemplos em [.filename]#/usr/shared/examples/ppp/#. [NOTE] ==== Alguns provedores de acesso à Internet bloqueiam portas de números baixos, impedindo o funcionamento do NTP, pois as respostas nunca chegam à máquina. ==== [[network-iscsi]] == Inicializador iSCSI e Configuração Alvo iSCSI é uma maneira de compartilhar o armazenamento em uma rede. Ao contrário do NFS, que funciona no nível do sistema de arquivos, o iSCSI funciona no nível do dispositivo de bloco. Na terminologia iSCSI, o sistema que compartilha o armazenamento é conhecido como _alvo_. O armazenamento pode ser um disco físico ou uma área representando vários discos ou uma parte de um disco físico. Por exemplo, se os discos estiverem formatados com ZFS, um zvol poderá ser criado para ser usado como armazenamento iSCSI. Os clientes que acessam o armazenamento do iSCSI são chamados de _iniciadores_. Para os iniciadores, o armazenamento disponível por meio do iSCSI aparece como um disco bruto, não formatado, conhecido como LUN. Nós de dispositivo para o disco aparecem em [.filename]#/dev/# e o dispositivo deve ser formatado e montado separadamente. O FreeBSD fornece um alvo e iniciador nativo, baseado em kernel iSCSI. Esta seção descreve como configurar um sistema FreeBSD como um alvo ou um iniciador. [[network-iscsi-target]] === Configurando um Alvo iSCSI Para configurar um alvo iSCSI, crie o arquivo de configuração [.filename]#/etc/ctl.conf#, adicione uma linha ao arquivo [.filename]#/etc/rc.conf# para certificar-se de que o daemon man:ctld[8] seja iniciado automaticamente na inicialização e, em seguida, inicie-o. A seguir, um exemplo de um arquivo de configuração simples [.filename]#/etc/ctl.conf#. Consulte man:ctl.conf[5] para obter uma descrição mais completa das opções disponíveis deste arquivo. [.programlisting] .... portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group no-authentication portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... A primeira entrada define o grupo de portais `pg0`. Grupos de portal definem quais endereços de rede o daemon man:ctld[8] irá escutar. A entrada `discovery-auth-group no-authentication` indica que qualquer iniciador tem permissão para executar descoberta de alvo iSCSI sem autenticação. As linhas três e quatro configuram man:ctld[8] para escutar em todos os endereços IPv4 (`listen 0.0.0.0`) e IPv6 (`listen [::]`) na porta padrão 3260. Não é necessário definir um grupo de portais, pois há um grupo de portais interno chamado `default`. Nesse caso, a diferença entre `default` e `pg0` é que com `default`, a descoberta de alvo é sempre negada, enquanto com `pg0`, é sempre permitido. A segunda entrada define um único alvo. O alvo tem dois significados possíveis: uma máquina que atende iSCSI ou um grupo nomeado de LUNs. Este exemplo usa o último significado, onde `iqn.2012-06.com.example:target0` é o nome do alvo. Este nome de alvo é adequado para fins de teste. Para uso real, altere `com.example` para o nome de domínio real, invertido. O `2012-06` representa o ano e o mês de aquisição do controle desse nome de domínio, e `target0` pode ser qualquer valor. Qualquer número de alvos pode ser definido neste arquivo de configuração. A linha `auth-group no-authentication` permite que todos os iniciadores se conectem ao alvo especificado e `portal-group pg0` torna o alvo acessível através do grupo do portal `pg0`. A próxima seção define o LUN. Para o iniciador, cada LUN será visível como um dispositivo de disco separado. Múltiplos LUNs podem ser definidos para cada destino. Cada LUN é identificado por um número, onde LUN 0 é obrigatório. A linha `path/data/target0-0` define o caminho completo para um arquivo ou zvol que suporta o LUN. Esse caminho deve existir antes de iniciar man:ctld[8]. A segunda linha é opcional e especifica o tamanho do LUN. Em seguida, para ter certeza que o daemon man:ctld[8] foi iniciado no boot, adicione esta linha ao arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... ctld_enable="YES" .... Para iniciar o man:ctld[8] agora, execute este comando: [source,shell] .... # service ctld start .... Quando o daemon man:ctld[8] é iniciado, ele lê o arquivo [.filename]#/etc/ctl.conf#. Se este arquivo for editado depois que o daemon iniciar, use este comando para que as mudanças entrem em vigor imediatamente: [source,shell] .... # service ctld reload .... ==== Autenticação O exemplo anterior é inerentemente inseguro, pois não usa autenticação, concedendo a qualquer um acesso total a todos os alvos. Para exigir um nome de usuário e senha para acessar os alvos, modifique a configuração da seguinte maneira: [.programlisting] .... auth-group ag0 { chap username1 secretsecret chap username2 anothersecret } portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group ag0 portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... A seção `auth-group` define os pares de nome de usuário e senha. Um inicializador tentando se conectar a `iqn.2012-06.com.example:target0` deve primeiro especificar um nome de usuário e senha definidos. No entanto, a descoberta do alvo ainda é permitida sem autenticação. Para exigir autenticação de descoberta de alvo, defina `discovery-auth-group` como um nome `auth-group` definido em vez de `no-authentication`. É comum definir um único alvo exportado para cada inicializador. Como um atalho para a sintaxe acima, o nome de usuário e a senha podem ser especificados diretamente na entrada do alvo: [.programlisting] .... target iqn.2012-06.com.example:target0 { portal-group pg0 chap username1 secretsecret lun 0 { path /data/target0-0 size 4G } } .... [[network-iscsi-initiator]] === Configurando um Inicializador iSCSI [NOTE] ==== O inicializador iSCSI descrito nesta seção é suportado a partir do FreeBSD 10.0-RELEASE. Para usar o inicializador iSCSI disponível em versões mais antigas, consulte man:iscontrol[8]. ==== O inicializador iSCSI requer que o daemon man:iscsid[8] esteja em execução. Este daemon não usa um arquivo de configuração. Para iniciá-lo automaticamente na inicialização, adicione esta linha ao arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... iscsid_enable="YES" .... Para iniciar man:iscsid[8] agora, execute este comando: [source,shell] .... # service iscsid start .... Conectar-se a um alvo pode ser feito com ou sem um arquivo [.filename]#/etc/iscsi.conf# de configuração. Esta seção demonstra os dois tipos de conexões. ==== Conectando-se a um Alvo sem um Arquivo de Configuração Para conectar um inicializador a um único alvo, especifique o endereço IP do portal e o nome do alvo: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 .... Para verificar se a conexão foi bem sucedida, execute `iscsictl` sem nenhum argumento. A saída deve ser semelhante a esta: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Connected: da0 .... Neste exemplo, a sessão iSCSI foi estabelecida com sucesso, com [.filename]#/dev/da0# representando o LUN anexado. Se o destino `iqn.2012-06.com.example:target0` exportar mais de um LUN, vários nós de dispositivos serão mostrados nessa seção da saída: [source,shell] .... Connected: da0 da1 da2. .... Quaisquer erros serão relatados na saída, assim como os logs do sistema. Por exemplo, esta mensagem normalmente significa que o daemon man:iscsid[8] não está em execução: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Waiting for iscsid(8) .... A mensagem a seguir sugere um problema de rede, como uma porta ou endereço IP incorreto: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.11 Connection refused .... Esta mensagem significa que o nome do alvo especificado está errado: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Not found .... Esta mensagem significa que o alvo requer autenticação: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Authentication failed .... Para especificar um nome de usuário e uma senha de CHAP, use esta sintaxe: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 -u user -s secretsecret .... ==== Conectando-se a um Alvo com um Arquivo de Configuração Para se conectar usando um arquivo de configuração, crie o [.filename]#/etc/iscsi.conf# com o seguinte conteúdo: [.programlisting] .... t0 { TargetAddress = 10.10.10.10 TargetName = iqn.2012-06.com.example:target0 AuthMethod = CHAP chapIName = user chapSecret = secretsecret } .... O `t0` especifica um nickname para a seção do arquivo de configuração. Ele será usado pelo iniciador para especificar qual configuração usar. As outras linhas especificam os parâmetros a serem usados durante a conexão. O `TargetAddress` e `TargetName` são obrigatórios, enquanto as outras opções são opcionais. Neste exemplo, o nome de usuário e a senha do CHAP são mostrados. Para se conectar ao alvo definido, especifique o apelido: [source,shell] .... # iscsictl -An t0 .... Como alternativa, para conectar-se a todos os alvos definidos no arquivo de configuração, use: [source,shell] .... # iscsictl -Aa .... Para fazer com que o inicializador se conecte automaticamente a todos os alvos no arquivo [.filename]#/etc/iscsi.conf#, adicione o seguinte ao arquivo [.filename]#/etc/rc.conf#: [.programlisting] .... iscsictl_enable="YES" iscsictl_flags="-Aa" .... diff --git a/documentation/content/zh-tw/books/handbook/advanced-networking/_index.adoc b/documentation/content/zh-tw/books/handbook/advanced-networking/_index.adoc index e303dcdd2c..cef31954c7 100644 --- a/documentation/content/zh-tw/books/handbook/advanced-networking/_index.adoc +++ b/documentation/content/zh-tw/books/handbook/advanced-networking/_index.adoc @@ -1,2817 +1,2817 @@ --- title: 章 31. 進階網路設定 part: 部 IV. 網路通訊 prev: books/handbook/firewalls next: books/handbook/partv showBookMenu: true weight: 36 path: "/books/handbook/" --- [[advanced-networking]] = 進階網路設定 :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 31 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/advanced-networking/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[advanced-networking-synopsis]] == 概述 This chapter covers a number of advanced networking topics. 讀完這章,您將了解: * The basics of gateways and routes. * How to set up USB tethering. * How to set up IEEE(TM) 802.11 and Bluetooth(TM) devices. * How to make FreeBSD act as a bridge. * How to set up network PXE booting. * How to set up IPv6 on a FreeBSD machine. * How to enable and utilize the features of the Common Address Redundancy Protocol (CARP) in FreeBSD. * 如何在 FreeBSD 上設定多個 VLAN。 * Configure bluetooth headset. 在開始閱讀這章之前,您需要: * Understand the basics of the [.filename]#/etc/rc# scripts. * 熟悉基本網路術語。 * Know how to configure and install a new FreeBSD kernel (crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心]). * 了解如何安裝其他第三方軟體 (crossref:ports[ports,安裝應用程式:套件與 Port])。 [[network-routing]] == 通訊閘與路由 _Routing_ is the mechanism that allows a system to find the network path to another system. A _route_ is a defined pair of addresses which represent the "destination" and a "gateway". The route indicates that when trying to get to the specified destination, send the packets through the specified gateway. There are three types of destinations: individual hosts, subnets, and "default". The "default route" is used if no other routes apply. There are also three types of gateways: individual hosts, interfaces, also called links, and Ethernet hardware (MAC) addresses. Known routes are stored in a routing table. This section provides an overview of routing basics. It then demonstrates how to configure a FreeBSD system as a router and offers some troubleshooting tips. [[network-routing-default]] === 路由基礎概念 To view the routing table of a FreeBSD system, use man:netstat[1]: [source,shell] .... % netstat -r Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default outside-gw UGS 37 418 em0 localhost localhost UH 0 181 lo0 test0 0:e0:b5:36:cf:4f UHLW 5 63288 re0 77 10.20.30.255 link#1 UHLW 1 2421 example.com link#1 UC 0 0 host1 0:e0:a8:37:8:1e UHLW 3 4601 lo0 host2 0:e0:a8:37:8:1e UHLW 0 5 lo0 => host2.example.com link#1 UC 0 0 224 link#1 UC 0 0 .... The entries in this example are as follows: default:: The first route in this table specifies the `default` route. When the local system needs to make a connection to a remote host, it checks the routing table to determine if a known path exists. If the remote host matches an entry in the table, the system checks to see if it can connect using the interface specified in that entry. + If the destination does not match an entry, or if all known paths fail, the system uses the entry for the default route. For hosts on a local area network, the `Gateway` field in the default route is set to the system which has a direct connection to the Internet. When reading this entry, verify that the `Flags` column indicates that the gateway is usable (`UG`). + The default route for a machine which itself is functioning as the gateway to the outside world will be the gateway machine at the Internet Service Provider (ISP). localhost:: The second route is the `localhost` route. The interface specified in the `Netif` column for `localhost` is [.filename]#lo0#, also known as the loopback device. This indicates that all traffic for this destination should be internal, rather than sending it out over the network. MAC address:: The addresses beginning with `0:e0:` are MAC addresses. FreeBSD will automatically identify any hosts, `test0` in the example, on the local Ethernet and add a route for that host over the Ethernet interface, [.filename]#re0#. This type of route has a timeout, seen in the `Expire` column, which is used if the host does not respond in a specific amount of time. When this happens, the route to this host will be automatically deleted. These hosts are identified using the Routing Information Protocol (RIP), which calculates routes to local hosts based upon a shortest path determination. subnet:: FreeBSD will automatically add subnet routes for the local subnet. In this example, `10.20.30.255` is the broadcast address for the subnet `10.20.30` and `example.com` is the domain name associated with that subnet. The designation `link#1` refers to the first Ethernet card in the machine. + Local network hosts and local subnets have their routes automatically configured by a daemon called man:routed[8]. If it is not running, only routes which are statically defined by the administrator will exist. host:: The `host1` line refers to the host by its Ethernet address. Since it is the sending host, FreeBSD knows to use the loopback interface ([.filename]#lo0#) rather than the Ethernet interface. + The two `host2` lines represent aliases which were created using man:ifconfig[8]. The `=>` symbol after the [.filename]#lo0# interface says that an alias has been set in addition to the loopback address. Such routes only show up on the host that supports the alias and all other hosts on the local network will have a `link#1` line for such routes. 224:: The final line (destination subnet `224`) deals with multicasting. Various attributes of each route can be seen in the `Flags` column. <> summarizes some of these flags and their meanings: [[routeflags]] .常見路由表標記 [cols="1,1", frame="none", options="header"] |=== | 指令 | 用途 |U |The route is active (up). |H |The route destination is a single host. |G |Send anything for this destination on to this gateway, which will figure out from there where to send it. |S |This route was statically configured. |C |Clones a new route based upon this route for machines to connect to. This type of route is normally used for local networks. |W |The route was auto-configured based upon a local area network (clone) route. |L |Route involves references to Ethernet (link) hardware. |=== On a FreeBSD system, the default route can defined in [.filename]#/etc/rc.conf# by specifying the IP address of the default gateway: [.programlisting] .... defaultrouter="10.20.30.1" .... It is also possible to manually add the route using `route`: [source,shell] .... # route add default 10.20.30.1 .... Note that manually added routes will not survive a reboot. For more information on manual manipulation of network routing tables, refer to man:route[8]. [[network-static-routes]] === 設定路由器使用靜態路由 A FreeBSD system can be configured as the default gateway, or router, for a network if it is a dual-homed system. A dual-homed system is a host which resides on at least two different networks. Typically, each network is connected to a separate network interface, though IP aliasing can be used to bind multiple addresses, each on a different subnet, to one physical interface. In order for the system to forward packets between interfaces, FreeBSD must be configured as a router. Internet standards and good engineering practice prevent the FreeBSD Project from enabling this feature by default, but it can be configured to start at boot by adding this line to [.filename]#/etc/rc.conf#: [.programlisting] .... gateway_enable="YES" # Set to YES if this host will be a gateway .... To enable routing now, set the man:sysctl[8] variable `net.inet.ip.forwarding` to `1`. To stop routing, reset this variable to `0`. The routing table of a router needs additional routes so it knows how to reach other networks. Routes can be either added manually using static routes or routes can be automatically learned using a routing protocol. Static routes are appropriate for small networks and this section describes how to add a static routing entry for a small network. [NOTE] ==== For large networks, static routes quickly become unscalable. FreeBSD comes with the standard BSD routing daemon man:routed[8], which provides the routing protocols RIP, versions 1 and 2, and IRDP. Support for the BGP and OSPF routing protocols can be installed using the package:net/zebra[] package or port. ==== Consider the following network: image::static-routes.png[] In this scenario, `RouterA` is a FreeBSD machine that is acting as a router to the rest of the Internet. It has a default route set to `10.0.0.1` which allows it to connect with the outside world. `RouterB` is already configured to use `192.168.1.1` as its default gateway. Before adding any static routes, the routing table on `RouterA` looks like this: [source,shell] .... % netstat -nr Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default 10.0.0.1 UGS 0 49378 xl0 127.0.0.1 127.0.0.1 UH 0 6 lo0 10.0.0.0/24 link1 UC 0 0 xl0 192.168.1.0/24 link2 UC 0 0 xl1 .... With the current routing table, `RouterA` does not have a route to the `192.168.2.0/24` network. The following command adds the `Internal Net 2` network to ``RouterA``'s routing table using `192.168.1.2` as the next hop: [source,shell] .... # route add -net 192.168.2.0/24 192.168.1.2 .... Now, `RouterA` can reach any host on the `192.168.2.0/24` network. However, the routing information will not persist if the FreeBSD system reboots. If a static route needs to be persistent, add it to [.filename]#/etc/rc.conf#: [.programlisting] .... # Add Internal Net 2 as a persistent static route static_routes="internalnet2" route_internalnet2="-net 192.168.2.0/24 192.168.1.2" .... The `static_routes` configuration variable is a list of strings separated by a space, where each string references a route name. The variable `__route_internalnet2__` contains the static route for that route name. Using more than one string in `static_routes` creates multiple static routes. The following shows an example of adding static routes for the `192.168.0.0/24` and `192.168.1.0/24` networks: [.programlisting] .... static_routes="net1 net2" route_net1="-net 192.168.0.0/24 192.168.0.1" route_net2="-net 192.168.1.0/24 192.168.1.1" .... [[network-routing-troubleshooting]] === 疑難排解 When an address space is assigned to a network, the service provider configures their routing tables so that all traffic for the network will be sent to the link for the site. But how do external sites know to send their packets to the network's ISP? There is a system that keeps track of all assigned address spaces and defines their point of connection to the Internet backbone, or the main trunk lines that carry Internet traffic across the country and around the world. Each backbone machine has a copy of a master set of tables, which direct traffic for a particular network to a specific backbone carrier, and from there down the chain of service providers until it reaches a particular network. It is the task of the service provider to advertise to the backbone sites that they are the point of connection, and thus the path inward, for a site. This is known as route propagation. Sometimes, there is a problem with route propagation and some sites are unable to connect. Perhaps the most useful command for trying to figure out where routing is breaking down is `traceroute`. It is useful when `ping` fails. When using `traceroute`, include the address of the remote host to connect to. The output will show the gateway hosts along the path of the attempt, eventually either reaching the target host, or terminating because of a lack of connection. For more information, refer to man:traceroute[8]. [[network-routing-multicast]] === 群播 (Multicast) 注意事項 FreeBSD natively supports both multicast applications and multicast routing. Multicast applications do not require any special configuration in order to run on FreeBSD. Support for multicast routing requires that the following option be compiled into a custom kernel: [.programlisting] .... options MROUTING .... The multicast routing daemon, mrouted can be installed using the package:net/mrouted[] package or port. This daemon implements the DVMRP multicast routing protocol and is configured by editing [.filename]#/usr/local/etc/mrouted.conf# in order to set up the tunnels and DVMRP. The installation of mrouted also installs map-mbone and mrinfo, as well as their associated man pages. Refer to these for configuration examples. [NOTE] ==== DVMRP has largely been replaced by the PIM protocol in many multicast installations. Refer to man:pim[4] for more information. ==== [[network-wireless]] == 無線網路 === 無線網路基礎 Most wireless networks are based on the IEEE(TM) 802.11 standards. A basic wireless network consists of multiple stations communicating with radios that broadcast in either the 2.4GHz or 5GHz band, though this varies according to the locale and is also changing to enable communication in the 2.3GHz and 4.9GHz ranges. 802.11 networks are organized in two ways. In _infrastructure mode_, one station acts as a master with all the other stations associating to it, the network is known as a BSS, and the master station is termed an access point (AP). In a BSS, all communication passes through the AP; even when one station wants to communicate with another wireless station, messages must go through the AP. In the second form of network, there is no master and stations communicate directly. This form of network is termed an IBSS and is commonly known as an _ad-hoc network_. 802.11 networks were first deployed in the 2.4GHz band using protocols defined by the IEEE(TM) 802.11 and 802.11b standard. These specifications include the operating frequencies and the MAC layer characteristics, including framing and transmission rates, as communication can occur at various rates. Later, the 802.11a standard defined operation in the 5GHz band, including different signaling mechanisms and higher transmission rates. Still later, the 802.11g standard defined the use of 802.11a signaling and transmission mechanisms in the 2.4GHz band in such a way as to be backwards compatible with 802.11b networks. Separate from the underlying transmission techniques, 802.11 networks have a variety of security mechanisms. The original 802.11 specifications defined a simple security protocol called WEP. This protocol uses a fixed pre-shared key and the RC4 cryptographic cipher to encode data transmitted on a network. Stations must all agree on the fixed key in order to communicate. This scheme was shown to be easily broken and is now rarely used except to discourage transient users from joining networks. Current security practice is given by the IEEE(TM) 802.11i specification that defines new cryptographic ciphers and an additional protocol to authenticate stations to an access point and exchange keys for data communication. Cryptographic keys are periodically refreshed and there are mechanisms for detecting and countering intrusion attempts. Another security protocol specification commonly used in wireless networks is termed WPA, which was a precursor to 802.11i. WPA specifies a subset of the requirements found in 802.11i and is designed for implementation on legacy hardware. Specifically, WPA requires only the TKIP cipher that is derived from the original WEP cipher. 802.11i permits use of TKIP but also requires support for a stronger cipher, AES-CCM, for encrypting data. The AES cipher was not required in WPA because it was deemed too computationally costly to be implemented on legacy hardware. The other standard to be aware of is 802.11e. It defines protocols for deploying multimedia applications, such as streaming video and voice over IP (VoIP), in an 802.11 network. Like 802.11i, 802.11e also has a precursor specification termed WME (later renamed WMM) that has been defined by an industry group as a subset of 802.11e that can be deployed now to enable multimedia applications while waiting for the final ratification of 802.11e. The most important thing to know about 802.11e and WME/WMM is that it enables prioritized traffic over a wireless network through Quality of Service (QoS) protocols and enhanced media access protocols. Proper implementation of these protocols enables high speed bursting of data and prioritized traffic flow. FreeBSD supports networks that operate using 802.11a, 802.11b, and 802.11g. The WPA and 802.11i security protocols are likewise supported (in conjunction with any of 11a, 11b, and 11g) and QoS and traffic prioritization required by the WME/WMM protocols are supported for a limited set of wireless devices. [[network-wireless-quick-start]] === 快速開始 Connecting a computer to an existing wireless network is a very common situation. This procedure shows the steps required. [.procedure] ==== . Obtain the SSID (Service Set Identifier) and PSK (Pre-Shared Key) for the wireless network from the network administrator. . Identify the wireless adapter. The FreeBSD [.filename]#GENERIC# kernel includes drivers for many common wireless adapters. If the wireless adapter is one of those models, it will be shown in the output from man:ifconfig[8]: + [source,shell] .... % ifconfig | grep -B3 -i wireless .... + On FreeBSD 11 or higher, use this command instead: + [source,shell] .... % sysctl net.wlan.devices .... + If a wireless adapter is not listed, an additional kernel module might be required, or it might be a model not supported by FreeBSD. + This example shows the Atheros `ath0` wireless adapter. . Add an entry for this network to [.filename]#/etc/wpa_supplicant.conf#. If the file does not exist, create it. Replace _myssid_ and _mypsk_ with the SSID and PSK provided by the network administrator. + [.programlisting] .... network={ ssid="myssid" psk="mypsk" } .... + . Add entries to [.filename]#/etc/rc.conf# to configure the network on startup: + [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA SYNCDHCP" .... + . Restart the computer, or restart the network service to connect to the network: + [source,shell] .... # service netif restart .... ==== [[network-wireless-basic]] === 基礎設定 ==== 核心設定 To use wireless networking, a wireless networking card is needed and the kernel needs to be configured with the appropriate wireless networking support. The kernel is separated into multiple modules so that only the required support needs to be configured. The most commonly used wireless devices are those that use parts made by Atheros. These devices are supported by man:ath[4] and require the following line to be added to [.filename]#/boot/loader.conf#: [.programlisting] .... if_ath_load="YES" .... The Atheros driver is split up into three separate pieces: the driver (man:ath[4]), the hardware support layer that handles chip-specific functions (man:ath_hal[4]), and an algorithm for selecting the rate for transmitting frames. When this support is loaded as kernel modules, any dependencies are automatically handled. To load support for a different type of wireless device, specify the module for that device. This example is for devices based on the Intersil Prism parts (man:wi[4]) driver: [.programlisting] .... if_wi_load="YES" .... [NOTE] ==== The examples in this section use an man:ath[4] device and the device name in the examples must be changed according to the configuration. A list of available wireless drivers and supported adapters can be found in the FreeBSD Hardware Notes, available on the https://www.FreeBSD.org/releases/[Release Information] page of the FreeBSD website. If a native FreeBSD driver for the wireless device does not exist, it may be possible to use the Windows(TM) driver with the help of the crossref:config[config-network-ndis,NDIS] driver wrapper. ==== In addition, the modules that implement cryptographic support for the security protocols to use must be loaded. These are intended to be dynamically loaded on demand by the man:wlan[4] module, but for now they must be manually configured. The following modules are available: man:wlan_wep[4], man:wlan_ccmp[4], and man:wlan_tkip[4]. The man:wlan_ccmp[4] and man:wlan_tkip[4] drivers are only needed when using the WPA or 802.11i security protocols. If the network does not use encryption, man:wlan_wep[4] support is not needed. To load these modules at boot time, add the following lines to [.filename]#/boot/loader.conf#: [.programlisting] .... wlan_wep_load="YES" wlan_ccmp_load="YES" wlan_tkip_load="YES" .... Once this information has been added to [.filename]#/boot/loader.conf#, reboot the FreeBSD box. Alternately, load the modules by hand using man:kldload[8]. [NOTE] ==== For users who do not want to use modules, it is possible to compile these drivers into the kernel by adding the following lines to a custom kernel configuration file: [.programlisting] .... device wlan # 802.11 support device wlan_wep # 802.11 WEP support device wlan_ccmp # 802.11 CCMP support device wlan_tkip # 802.11 TKIP support device wlan_amrr # AMRR transmit rate control algorithm device ath # Atheros pci/cardbus NIC's device ath_hal # pci/cardbus chip support options AH_SUPPORT_AR5416 # enable AR5416 tx/rx descriptors device ath_rate_sample # SampleRate tx rate control for ath .... With this information in the kernel configuration file, recompile the kernel and reboot the FreeBSD machine. ==== Information about the wireless device should appear in the boot messages, like this: [source,shell] .... ath0: mem 0x88000000-0x8800ffff irq 11 at device 0.0 on cardbus1 ath0: [ITHREAD] ath0: AR2413 mac 7.9 RF2413 phy 4.5 .... ==== 設定正確的區域 Since the regulatory situation is different in various parts of the world, it is necessary to correctly set the domains that apply to your location to have the correct information about what channels can be used. The available region definitions can be found in [.filename]#/etc/regdomain.xml#. To set the data at runtime, use `ifconfig`: [source,shell] .... # ifconfig wlan0 regdomain ETSI country AT .... To persist the settings, add it to [.filename]#/etc/rc.conf#: [source,shell] .... # sysrc create_args_wlan0="country AT regdomain ETSI" .... === 主從式 (Infrastructure) Infrastructure (BSS) mode is the mode that is typically used. In this mode, a number of wireless access points are connected to a wired network. Each wireless network has its own name, called the SSID. Wireless clients connect to the wireless access points. ==== FreeBSD 客戶端 ===== 如何尋找存取點 To scan for available networks, use man:ifconfig[8]. This request may take a few moments to complete as it requires the system to switch to each available wireless frequency and probe for available access points. Only the superuser can initiate a scan: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS dlinkap 00:13:46:49:41:76 11 54M -90:96 100 EPS WPA WME freebsdap 00:11:95:c3:0d:ac 1 54M -83:96 100 EPS WPA .... [NOTE] ==== The interface must be `up` before it can scan. Subsequent scan requests do not require the interface to be marked as up again. ==== The output of a scan request lists each BSS/IBSS network found. Besides listing the name of the network, the `SSID`, the output also shows the `BSSID`, which is the MAC address of the access point. The `CAPS` field identifies the type of each network and the capabilities of the stations operating there: .站台功能代號 [cols="1,1", frame="none", options="header"] |=== | 功能代號 | 意義 |`E` |Extended Service Set (ESS). Indicates that the station is part of an infrastructure network rather than an IBSS/ad-hoc network. |`I` |IBSS/ad-hoc network. Indicates that the station is part of an ad-hoc network rather than an ESS network. |`P` |Privacy. Encryption is required for all data frames exchanged within the BSS using cryptographic means such as WEP, TKIP or AES-CCMP. |`S` |Short Preamble. Indicates that the network is using short preambles, defined in 802.11b High Rate/DSSS PHY, and utilizes a 56 bit sync field rather than the 128 bit field used in long preamble mode. |`s` |Short slot time. Indicates that the 802.11g network is using a short slot time because there are no legacy (802.11b) stations present. |=== One can also display the current list of known networks with: [source,shell] .... # ifconfig wlan0 list scan .... This information may be updated automatically by the adapter or manually with a `scan` request. Old data is automatically removed from the cache, so over time this list may shrink unless more scans are done. ===== 基礎設定 This section provides a simple example of how to make the wireless network adapter work in FreeBSD without encryption. Once familiar with these concepts, it is strongly recommend to use <> to set up the wireless network. There are three basic steps to configure a wireless network: select an access point, authenticate the station, and configure an IP address. The following sections discuss each step. ====== 選擇存取點 Most of the time, it is sufficient to let the system choose an access point using the builtin heuristics. This is the default behavior when an interface is marked as up or it is listed in [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... If there are multiple access points, a specific one can be selected by its SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here DHCP" .... In an environment where there are multiple access points with the same SSID, which is often done to simplify roaming, it may be necessary to associate to one specific device. In this case, the BSSID of the access point can be specified, with or without the SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here bssid xx:xx:xx:xx:xx:xx DHCP" .... There are other ways to constrain the choice of an access point, such as limiting the set of frequencies the system will scan on. This may be useful for a multi-band wireless card as scanning all the possible channels can be time-consuming. To limit operation to a specific band, use the `mode` parameter: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="mode 11g ssid your_ssid_here DHCP" .... This example will force the card to operate in 802.11g, which is defined only for 2.4GHz frequencies so any 5GHz channels will not be considered. This can also be achieved with the `channel` parameter, which locks operation to one specific frequency, and the `chanlist` parameter, to specify a list of channels for scanning. More information about these parameters can be found in man:ifconfig[8]. ====== 認證 Once an access point is selected, the station needs to authenticate before it can pass data. Authentication can happen in several ways. The most common scheme, open authentication, allows any station to join the network and communicate. This is the authentication to use for test purposes the first time a wireless network is setup. Other schemes require cryptographic handshakes to be completed before data traffic can flow, either using pre-shared keys or secrets, or more complex schemes that involve backend services such as RADIUS. Open authentication is the default setting. The next most common setup is WPA-PSK, also known as WPA Personal, which is described in <>. [NOTE] ==== If using an Apple(TM)AirPort(TM) Extreme base station for an access point, shared-key authentication together with a WEP key needs to be configured. This can be configured in [.filename]#/etc/rc.conf# or by using man:wpa_supplicant[8]. For a single AirPort(TM) base station, access can be configured with: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="authmode shared wepmode on weptxkey 1 wepkey 01234567 DHCP" .... In general, shared key authentication should be avoided because it uses the WEP key material in a highly-constrained manner, making it even easier to crack the key. If WEP must be used for compatibility with legacy devices, it is better to use WEP with `open` authentication. More information regarding WEP can be found in <>. ==== ====== 使用 DHCP 取得 IP 位址 Once an access point is selected and the authentication parameters are set, an IP address must be obtained in order to communicate. Most of the time, the IP address is obtained via DHCP. To achieve that, edit [.filename]#/etc/rc.conf# and add `DHCP` to the configuration for the device: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... The wireless interface is now ready to bring up: [source,shell] .... # service netif start .... Once the interface is running, use man:ifconfig[8] to see the status of the interface [.filename]#ath0#: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.1.100 netmask 0xffffff00 broadcast 192.168.1.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid dlinkap channel 11 (2462 Mhz 11g) bssid 00:13:46:49:41:76 country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... The `status: associated` line means that it is connected to the wireless network. The `bssid 00:13:46:49:41:76` is the MAC address of the access point and `authmode OPEN` indicates that the communication is not encrypted. ====== 靜態 IP 位址 If an IP address cannot be obtained from a DHCP server, set a fixed IP address. Replace the `DHCP` keyword shown above with the address information. Be sure to retain any other parameters for selecting the access point: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="inet 192.168.1.100 netmask 255.255.255.0 ssid your_ssid_here" .... [[network-wireless-wpa]] ===== WPA Wi-Fi Protected Access (WPA) is a security protocol used together with 802.11 networks to address the lack of proper authentication and the weakness of WEP. WPA leverages the 802.1X authentication protocol and uses one of several ciphers instead of WEP for data integrity. The only cipher required by WPA is the Temporary Key Integrity Protocol (TKIP). TKIP is a cipher that extends the basic RC4 cipher used by WEP by adding integrity checking, tamper detection, and measures for responding to detected intrusions. TKIP is designed to work on legacy hardware with only software modification. It represents a compromise that improves security but is still not entirely immune to attack. WPA also specifies the AES-CCMP cipher as an alternative to TKIP, and that is preferred when possible. For this specification, the term WPA2 or RSN is commonly used. WPA defines authentication and encryption protocols. Authentication is most commonly done using one of two techniques: by 802.1X and a backend authentication service such as RADIUS, or by a minimal handshake between the station and the access point using a pre-shared secret. The former is commonly termed WPA Enterprise and the latter is known as WPA Personal. Since most people will not set up a RADIUS backend server for their wireless network, WPA-PSK is by far the most commonly encountered configuration for WPA. The control of the wireless connection and the key negotiation or authentication with a server is done using man:wpa_supplicant[8]. This program requires a configuration file, [.filename]#/etc/wpa_supplicant.conf#, to run. More information regarding this file can be found in man:wpa_supplicant.conf[5]. [[network-wireless-wpa-wpa-psk]] ====== WPA-PSK WPA-PSK, also known as WPA Personal, is based on a pre-shared key (PSK) which is generated from a given password and used as the master key in the wireless network. This means every wireless user will share the same key. WPA-PSK is intended for small networks where the use of an authentication server is not possible or desired. [WARNING] ==== Always use strong passwords that are sufficiently long and made from a rich alphabet so that they will not be easily guessed or attacked. ==== The first step is the configuration of [.filename]#/etc/wpa_supplicant.conf# with the SSID and the pre-shared key of the network: [.programlisting] .... network={ ssid="freebsdap" psk="freebsdmall" } .... Then, in [.filename]#/etc/rc.conf#, indicate that the wireless device configuration will be done with WPA and the IP address will be obtained with DHCP: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Then, bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 5 DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6 DHCPOFFER from 192.168.0.1 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Or, try to configure the interface manually using the information in [.filename]#/etc/wpa_supplicant.conf#: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:11:95:c3:0d:ac (SSID='freebsdap' freq=2412 MHz) Associated with 00:11:95:c3:0d:ac WPA: Key negotiation completed with 00:11:95:c3:0d:ac [PTK=CCMP GTK=CCMP] CTRL-EVENT-CONNECTED - Connection to 00:11:95:c3:0d:ac completed (auth) [id=0 id_str=] .... The next operation is to launch man:dhclient[8] to get the IP address from the DHCP server: [source,shell] .... # dhclient wlan0 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [NOTE] ==== If [.filename]#/etc/rc.conf# has an `ifconfig_wlan0="DHCP"` entry, man:dhclient[8] will be launched automatically after man:wpa_supplicant[8] associates with the access point. ==== If DHCP is not possible or desired, set a static IP address after man:wpa_supplicant[8] has authenticated the station: [source,shell] .... # ifconfig wlan0 inet 192.168.0.100 netmask 255.255.255.0 # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... When DHCP is not used, the default gateway and the nameserver also have to be manually set: [source,shell] .... # route add default your_default_router # echo "nameserver your_DNS_server" >> /etc/resolv.conf .... [[network-wireless-wpa-eap-tls]] ====== WPA 加上 EAP-TLS The second way to use WPA is with an 802.1X backend authentication server. In this case, WPA is called WPA Enterprise to differentiate it from the less secure WPA Personal. Authentication in WPA Enterprise is based on the Extensible Authentication Protocol (EAP). EAP does not come with an encryption method. Instead, EAP is embedded inside an encrypted tunnel. There are many EAP authentication methods, but EAP-TLS, EAP-TTLS, and EAP-PEAP are the most common. EAP with Transport Layer Security (EAP-TLS) is a well-supported wireless authentication protocol since it was the first EAP method to be certified by the http://www.wi-fi.org/[Wi-Fi Alliance]. EAP-TLS requires three certificates to run: the certificate of the Certificate Authority (CA) installed on all machines, the server certificate for the authentication server, and one client certificate for each wireless client. In this EAP method, both the authentication server and wireless client authenticate each other by presenting their respective certificates, and then verify that these certificates were signed by the organization's CA. As previously, the configuration is done via [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" <.> proto=RSN <.> key_mgmt=WPA-EAP <.> eap=TLS <.> identity="loader" <.> ca_cert="/etc/certs/cacert.pem" <.> client_cert="/etc/certs/clientcert.pem" <.> private_key="/etc/certs/clientkey.pem" <.> private_key_passwd="freebsdmallclient" <.> } .... <.> This field indicates the network name (SSID). <.> This example uses the RSN IEEE(TM) 802.11i protocol, also known as WPA2. <.> The `key_mgmt` line refers to the key management protocol to use. In this example, it is WPA using EAP authentication. <.> This field indicates the EAP method for the connection. <.> The `identity` field contains the identity string for EAP. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> The `client_cert` line gives the pathname to the client certificate file. This certificate is unique to each wireless client of the network. <.> The `private_key` field is the pathname to the client certificate private key file. <.> The `private_key_passwd` field contains the passphrase for the private key. Then, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... The next step is to bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... It is also possible to bring up the interface manually using man:wpa_supplicant[8] and man:ifconfig[8]. [[network-wireless-wpa-eap-ttls]] ====== WPA 加上 EAP-TTLS With EAP-TLS, both the authentication server and the client need a certificate. With EAP-TTLS, a client certificate is optional. This method is similar to a web server which creates a secure SSL tunnel even if visitors do not have client-side certificates. EAP-TTLS uses an encrypted TLS tunnel for safe transport of the authentication data. The required configuration can be added to [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=TTLS <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase2="auth=MD5" <.> } .... <.> This field specifies the EAP method for the connection. <.> The `identity` field contains the identity string for EAP authentication inside the encrypted TLS tunnel. <.> The `password` field contains the passphrase for the EAP authentication. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> This field specifies the authentication method used in the encrypted TLS tunnel. In this example, EAP with MD5-Challenge is used. The "inner authentication" phase is often called "phase2". Next, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... The next step is to bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wpa-eap-peap]] ====== WPA 加上 EAP-PEAP [NOTE] ==== PEAPv0/EAP-MSCHAPv2 is the most common PEAP method. In this chapter, the term PEAP is used to refer to that method. ==== Protected EAP (PEAP) is designed as an alternative to EAP-TTLS and is the most used EAP standard after EAP-TLS. In a network with mixed operating systems, PEAP should be the most supported standard after EAP-TLS. PEAP is similar to EAP-TTLS as it uses a server-side certificate to authenticate clients by creating an encrypted TLS tunnel between the client and the authentication server, which protects the ensuing exchange of authentication information. PEAP authentication differs from EAP-TTLS as it broadcasts the username in the clear and only the password is sent in the encrypted TLS tunnel. EAP-TTLS will use the TLS tunnel for both the username and password. Add the following lines to [.filename]#/etc/wpa_supplicant.conf# to configure the EAP-PEAP related settings: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=PEAP <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase1="peaplabel=0" <.> phase2="auth=MSCHAPV2" <.> } .... <.> This field specifies the EAP method for the connection. <.> The `identity` field contains the identity string for EAP authentication inside the encrypted TLS tunnel. <.> The `password` field contains the passphrase for the EAP authentication. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> This field contains the parameters for the first phase of authentication, the TLS tunnel. According to the authentication server used, specify a specific label for authentication. Most of the time, the label will be "client EAP encryption" which is set by using `peaplabel=0`. More information can be found in man:wpa_supplicant.conf[5]. <.> This field specifies the authentication protocol used in the encrypted TLS tunnel. In the case of PEAP, it is `auth=MSCHAPV2`. 將以下參數加到 [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Then, bring up the interface: [source,shell] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wep]] ===== WEP Wired Equivalent Privacy (WEP) is part of the original 802.11 standard. There is no authentication mechanism, only a weak form of access control which is easily cracked. WEP can be set up using man:ifconfig[8]: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 inet 192.168.1.100 netmask 255.255.255.0 \ ssid my_net wepmode on weptxkey 3 wepkey 3:0x3456789012 .... * The `weptxkey` specifies which WEP key will be used in the transmission. This example uses the third key. This must match the setting on the access point. When unsure which key is used by the access point, try `1` (the first key) for this value. * The `wepkey` selects one of the WEP keys. It should be in the format _index:key_. Key `1` is used by default; the index only needs to be set when using a key other than the first key. + [NOTE] ==== Replace the `0x3456789012` with the key configured for use on the access point. ==== Refer to man:ifconfig[8] for further information. The man:wpa_supplicant[8] facility can be used to configure a wireless interface with WEP. The example above can be set up by adding the following lines to [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="my_net" key_mgmt=NONE wep_key3=3456789012 wep_tx_keyidx=3 } .... Then: [source,shell] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:13:46:49:41:76 (SSID='dlinkap' freq=2437 MHz) Associated with 00:13:46:49:41:76 .... === 對等式 (Ad-hoc) IBSS mode, also called ad-hoc mode, is designed for point to point connections. For example, to establish an ad-hoc network between the machines `A` and `B`, choose two IP addresses and a SSID. On `A`: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... The `adhoc` parameter indicates that the interface is running in IBSS mode. `B` should now be able to detect `A`: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 02:11:95:c3:0d:ac 2 54M -64:-96 100 IS WME .... The `I` in the output confirms that `A` is in ad-hoc mode. Now, configure `B` with a different IP address: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... Both `A` and `B` are now ready to exchange information. [[network-wireless-ap]] === FreeBSD 主機存取點 FreeBSD can act as an Access Point (AP) which eliminates the need to buy a hardware AP or run an ad-hoc network. This can be particularly useful when a FreeBSD machine is acting as a gateway to another network such as the Internet. [[network-wireless-ap-basic]] ==== 基礎設定 Before configuring a FreeBSD machine as an AP, the kernel must be configured with the appropriate networking support for the wireless card as well as the security protocols being used. For more details, see <>. [NOTE] ==== The NDIS driver wrapper for Windows(TM) drivers does not currently support AP operation. Only native FreeBSD wireless drivers support AP mode. ==== Once wireless networking support is loaded, check if the wireless device supports the host-based access point mode, also known as hostap mode: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 list caps drivercaps=6f85edc1 cryptocaps=1f .... This output displays the card's capabilities. The `HOSTAP` word confirms that this wireless card can act as an AP. Various supported ciphers are also listed: WEP, TKIP, and AES. This information indicates which security protocols can be used on the AP. The wireless device can only be put into hostap mode during the creation of the network pseudo-device, so a previously created device must be destroyed first: [source,shell] .... # ifconfig wlan0 destroy .... then regenerated with the correct option before setting the other parameters: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1 .... Use man:ifconfig[8] again to see the status of the [.filename]#wlan0# interface: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... The `hostap` parameter indicates the interface is running in the host-based access point mode. The interface configuration can be done automatically at boot time by adding the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" create_args_wlan0="wlanmode hostap" ifconfig_wlan0="inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1" .... ==== 無認證或加密的 Host-based 存取點 Although it is not recommended to run an AP without any authentication or encryption, this is a simple way to check if the AP is working. This configuration is also important for debugging client issues. Once the AP is configured, initiate a scan from another wireless machine to find the AP: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M -66:-96 100 ES WME .... The client machine found the AP and can be associated with it: [source,shell] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... [[network-wireless-ap-wpa]] ==== WPA2 Host-based 存取點 This section focuses on setting up a FreeBSD access point using the WPA2 security protocol. More details regarding WPA and the configuration of WPA-based wireless clients can be found in <>. The man:hostapd[8] daemon is used to deal with client authentication and key management on the WPA2-enabled AP. The following configuration operations are performed on the FreeBSD machine acting as the AP. Once the AP is correctly working, man:hostapd[8] can be automatically started at boot with this line in [.filename]#/etc/rc.conf#: [.programlisting] .... hostapd_enable="YES" .... Before trying to configure man:hostapd[8], first configure the basic settings introduced in <>. ===== WPA2-PSK WPA2-PSK is intended for small networks where the use of a backend authentication server is not possible or desired. The configuration is done in [.filename]#/etc/hostapd.conf#: [.programlisting] .... interface=wlan0 <.> debug=1 <.> ctrl_interface=/var/run/hostapd <.> ctrl_interface_group=wheel <.> ssid=freebsdap <.> wpa=2 <.> wpa_passphrase=freebsdmall <.> wpa_key_mgmt=WPA-PSK <.> wpa_pairwise=CCMP <.> .... <.> Wireless interface used for the access point. <.> Level of verbosity used during the execution of man:hostapd[8]. A value of `1` represents the minimal level. <.> Pathname of the directory used by man:hostapd[8] to store domain socket files for communication with external programs such as man:hostapd_cli[8]. The default value is used in this example. <.> The group allowed to access the control interface files. <.> The wireless network name, or SSID, that will appear in wireless scans. <.> Enable WPA and specify which WPA authentication protocol will be required. A value of `2` configures the AP for WPA2 and is recommended. Set to `1` only if the obsolete WPA is required. <.> ASCII passphrase for WPA authentication. <.> The key management protocol to use. This example sets WPA-PSK. <.> Encryption algorithms accepted by the access point. In this example, only the CCMP (AES) cipher is accepted. CCMP is an alternative to TKIP and is strongly preferred when possible. TKIP should be allowed only when there are stations incapable of using CCMP. The next step is to start man:hostapd[8]: [source,shell] .... # service hostapd forcestart .... [source,shell] .... # ifconfig wlan0 wlan0: flags=8943 metric 0 mtu 1500 ether 04:f0:21:16:8e:10 inet6 fe80::6f0:21ff:fe16:8e10%wlan0 prefixlen 64 scopeid 0x9 nd6 options=21 media: IEEE 802.11 Wireless Ethernet autoselect mode 11na status: running ssid No5ignal channel 36 (5180 MHz 11a ht/40+) bssid 04:f0:21:16:8e:10 country US ecm authmode WPA2/802.11i privacy MIXED deftxkey 2 AES-CCM 2:128-bit AES-CCM 3:128-bit txpower 17 mcastrate 6 mgmtrate 6 scanvalid 60 ampdulimit 64k ampdudensity 8 shortgi wme burst dtimperiod 1 -dfs groups: wlan .... Once the AP is running, the clients can associate with it. See <> for more details. It is possible to see the stations associated with the AP using `ifconfig _wlan0_ list sta`. ==== WEP Host-based 存取點 It is not recommended to use WEP for setting up an AP since there is no authentication mechanism and the encryption is easily cracked. Some legacy wireless cards only support WEP and these cards will only support an AP without authentication or encryption. The wireless device can now be put into hostap mode and configured with the correct SSID and IP address: [source,shell] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 \ ssid freebsdap wepmode on weptxkey 3 wepkey 3:0x3456789012 mode 11g .... * The `weptxkey` indicates which WEP key will be used in the transmission. This example uses the third key as key numbering starts with `1`. This parameter must be specified in order to encrypt the data. * The `wepkey` sets the selected WEP key. It should be in the format _index:key_. If the index is not given, key `1` is set. The index needs to be set when using keys other than the first key. Use man:ifconfig[8] to see the status of the [.filename]#wlan0# interface: [source,shell] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 4 (2427 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy ON deftxkey 3 wepkey 3:40-bit txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... From another wireless machine, it is now possible to initiate a scan to find the AP: [source,shell] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M 22:1 100 EPS .... In this example, the client machine found the AP and can associate with it using the correct parameters. See <> for more details. === 同時使用有線及無線連線 A wired connection provides better performance and reliability, while a wireless connection provides flexibility and mobility. Laptop users typically want to roam seamlessly between the two types of connections. On FreeBSD, it is possible to combine two or even more network interfaces together in a "failover" fashion. This type of configuration uses the most preferred and available connection from a group of network interfaces, and the operating system switches automatically when the link state changes. Link aggregation and failover is covered in <> and an example for using both wired and wireless connections is provided at <>. === 疑難排解 This section describes a number of steps to help troubleshoot common wireless networking problems. * If the access point is not listed when scanning, check that the configuration has not limited the wireless device to a limited set of channels. * If the device cannot associate with an access point, verify that the configuration matches the settings on the access point. This includes the authentication scheme and any security protocols. Simplify the configuration as much as possible. If using a security protocol such as WPA or WEP, configure the access point for open authentication and no security to see if traffic will pass. + Debugging support is provided by man:wpa_supplicant[8]. Try running this utility manually with `-dd` and look at the system logs. * Once the system can associate with the access point, diagnose the network configuration using tools like man:ping[8]. * There are many lower-level debugging tools. Debugging messages can be enabled in the 802.11 protocol support layer using man:wlandebug[8]. For example, to enable console messages related to scanning for access points and the 802.11 protocol handshakes required to arrange communication: + [source,shell] .... # wlandebug -i wlan0 +scan+auth+debug+assoc net.wlan.0.debug: 0 => 0xc80000 .... + Many useful statistics are maintained by the 802.11 layer and `wlanstats`, found in [.filename]#/usr/src/tools/tools/net80211#, will dump this information. These statistics should display all errors identified by the 802.11 layer. However, some errors are identified in the device drivers that lie below the 802.11 layer so they may not show up. To diagnose device-specific problems, refer to the drivers' documentation. If the above information does not help to clarify the problem, submit a problem report and include output from the above tools. [[network-usb-tethering]] == USB 網路共享 Many cellphones provide the option to share their data connection over USB (often called "tethering"). This feature uses either the RNDIS, CDC or a custom Apple(TM)iPhone(TM)/iPad(TM) protocol. * Android(TM) devices generally use the man:urndis[4] driver. * Apple(TM) devices use the man:ipheth[4] driver. * Older devices will often use the man:cdce[4] driver. Before attaching a device, load the appropriate driver into the kernel: [source,shell] .... # kldload if_urndis # kldload if_cdce # kldload if_ipheth .... Once the device is attached `ue__0__` will be available for use like a normal network device. Be sure that the "USB tethering" option is enabled on the device. [[network-bluetooth]] == 藍牙 Bluetooth is a wireless technology for creating personal networks operating in the 2.4 GHz unlicensed band, with a range of 10 meters. Networks are usually formed ad-hoc from portable devices such as cellular phones, handhelds, and laptops. Unlike Wi-Fi wireless technology, Bluetooth offers higher level service profiles, such as FTP-like file servers, file pushing, voice transport, serial line emulation, and more. This section describes the use of a USB Bluetooth dongle on a FreeBSD system. It then describes the various Bluetooth protocols and utilities. === 載入藍牙支援 The Bluetooth stack in FreeBSD is implemented using the man:netgraph[4] framework. A broad variety of Bluetooth USB dongles is supported by man:ng_ubt[4]. Broadcom BCM2033 based Bluetooth devices are supported by the man:ubtbcmfw[4] and man:ng_ubt[4] drivers. The 3Com Bluetooth PC Card 3CRWB60-A is supported by the man:ng_bt3c[4] driver. Serial and UART based Bluetooth devices are supported by man:sio[4], man:ng_h4[4], and man:hcseriald[8]. Before attaching a device, determine which of the above drivers it uses, then load the driver. For example, if the device uses the man:ng_ubt[4] driver: [source,shell] .... # kldload ng_ubt .... If the Bluetooth device will be attached to the system during system startup, the system can be configured to load the module at boot time by adding the driver to [.filename]#/boot/loader.conf#: [.programlisting] .... ng_ubt_load="YES" .... Once the driver is loaded, plug in the USB dongle. If the driver load was successful, output similar to the following should appear on the console and in [.filename]#/var/log/messages#: [source,shell] .... ubt0: vendor 0x0a12 product 0x0001, rev 1.10/5.25, addr 2 ubt0: Interface 0 endpoints: interrupt=0x81, bulk-in=0x82, bulk-out=0x2 ubt0: Interface 1 (alt.config 5) endpoints: isoc-in=0x83, isoc-out=0x3, wMaxPacketSize=49, nframes=6, buffer size=294 .... To start and stop the Bluetooth stack, use its startup script. It is a good idea to stop the stack before unplugging the device. Starting the bluetooth stack might require man:hcsecd[8] to be started. When starting the stack, the output should be similar to the following: [source,shell] .... # service bluetooth start ubt0 BD_ADDR: 00:02:72:00:d4:1a Features: 0xff 0xff 0xf 00 00 00 00 00 <3-Slot> <5-Slot> Max. ACL packet size: 192 bytes Number of ACL packets: 8 Max. SCO packet size: 64 bytes Number of SCO packets: 8 .... === 尋找其他藍牙裝置 The Host Controller Interface (HCI) provides a uniform method for accessing Bluetooth baseband capabilities. In FreeBSD, a netgraph HCI node is created for each Bluetooth device. For more details, refer to man:ng_hci[4]. One of the most common tasks is discovery of Bluetooth devices within RF proximity. This operation is called _inquiry_. Inquiry and other HCI related operations are done using man:hccontrol[8]. The example below shows how to find out which Bluetooth devices are in range. The list of devices should be displayed in a few seconds. Note that a remote device will only answer the inquiry if it is set to _discoverable_ mode. [source,shell] .... % hccontrol -n ubt0hci inquiry Inquiry result, num_responses=1 Inquiry result #0 BD_ADDR: 00:80:37:29:19:a4 Page Scan Rep. Mode: 0x1 Page Scan Period Mode: 00 Page Scan Mode: 00 Class: 52:02:04 Clock offset: 0x78ef Inquiry complete. Status: No error [00] .... The `BD_ADDR` is the unique address of a Bluetooth device, similar to the MAC address of a network card. This address is needed for further communication with a device and it is possible to assign a human readable name to a `BD_ADDR`. Information regarding the known Bluetooth hosts is contained in [.filename]#/etc/bluetooth/hosts#. The following example shows how to obtain the human readable name that was assigned to the remote device: [source,shell] .... % hccontrol -n ubt0hci remote_name_request 00:80:37:29:19:a4 BD_ADDR: 00:80:37:29:19:a4 Name: Pav's T39 .... If an inquiry is performed on a remote Bluetooth device, it will find the computer as "your.host.name (ubt0)". The name assigned to the local device can be changed at any time. Remote devices can be assigned aliases in [.filename]#/etc/bluetooth/hosts#. More information about [.filename]#/etc/bluetooth/hosts# file might be found in man:bluetooth.hosts[5]. The Bluetooth system provides a point-to-point connection between two Bluetooth units, or a point-to-multipoint connection which is shared among several Bluetooth devices. The following example shows how to create a connection to a remote device: [source,shell] .... % hccontrol -n ubt0hci create_connection BT_ADDR .... `create_connection` accepts `BT_ADDR` as well as host aliases in [.filename]#/etc/bluetooth/hosts#. The following example shows how to obtain the list of active baseband connections for the local device: [source,shell] .... % hccontrol -n ubt0hci read_connection_list Remote BD_ADDR Handle Type Mode Role Encrypt Pending Queue State 00:80:37:29:19:a4 41 ACL 0 MAST NONE 0 0 OPEN .... A _connection handle_ is useful when termination of the baseband connection is required, though it is normally not required to do this by hand. The stack will automatically terminate inactive baseband connections. [source,shell] .... # hccontrol -n ubt0hci disconnect 41 Connection handle: 41 Reason: Connection terminated by local host [0x16] .... Type `hccontrol help` for a complete listing of available HCI commands. Most of the HCI commands do not require superuser privileges. === 裝置配對 By default, Bluetooth communication is not authenticated, and any device can talk to any other device. A Bluetooth device, such as a cellular phone, may choose to require authentication to provide a particular service. Bluetooth authentication is normally done with a _PIN code_, an ASCII string up to 16 characters in length. The user is required to enter the same PIN code on both devices. Once the user has entered the PIN code, both devices will generate a _link key_. After that, the link key can be stored either in the devices or in a persistent storage. Next time, both devices will use the previously generated link key. This procedure is called _pairing_. Note that if the link key is lost by either device, the pairing must be repeated. The man:hcsecd[8] daemon is responsible for handling Bluetooth authentication requests. The default configuration file is [.filename]#/etc/bluetooth/hcsecd.conf#. An example section for a cellular phone with the PIN code set to `1234` is shown below: [.programlisting] .... device { bdaddr 00:80:37:29:19:a4; name "Pav's T39"; key nokey; pin "1234"; } .... The only limitation on PIN codes is length. Some devices, such as Bluetooth headsets, may have a fixed PIN code built in. The `-d` switch forces man:hcsecd[8] to stay in the foreground, so it is easy to see what is happening. Set the remote device to receive pairing and initiate the Bluetooth connection to the remote device. The remote device should indicate that pairing was accepted and request the PIN code. Enter the same PIN code listed in [.filename]#hcsecd.conf#. Now the computer and the remote device are paired. Alternatively, pairing can be initiated on the remote device. The following line can be added to [.filename]#/etc/rc.conf# to configure man:hcsecd[8] to start automatically on system start: [.programlisting] .... hcsecd_enable="YES" .... The following is a sample of the man:hcsecd[8] daemon output: [.programlisting] .... hcsecd[16484]: Got Link_Key_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', link key doesn't exist hcsecd[16484]: Sending Link_Key_Negative_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Got PIN_Code_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', PIN code exists hcsecd[16484]: Sending PIN_Code_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 .... === 使用 PPP Profile 存取網路 A Dial-Up Networking (DUN) profile can be used to configure a cellular phone as a wireless modem for connecting to a dial-up Internet access server. It can also be used to configure a computer to receive data calls from a cellular phone. Network access with a PPP profile can be used to provide LAN access for a single Bluetooth device or multiple Bluetooth devices. It can also provide PC to PC connection using PPP networking over serial cable emulation. In FreeBSD, these profiles are implemented with man:ppp[8] and the man:rfcomm_pppd[8] wrapper which converts a Bluetooth connection into something PPP can use. Before a profile can be used, a new PPP label must be created in [.filename]#/etc/ppp/ppp.conf#. Consult man:rfcomm_pppd[8] for examples. In this example, man:rfcomm_pppd[8] is used to open a connection to a remote device with a `BD_ADDR` of `00:80:37:29:19:a4` on a DUNRFCOMM channel: [source,shell] .... # rfcomm_pppd -a 00:80:37:29:19:a4 -c -C dun -l rfcomm-dialup .... The actual channel number will be obtained from the remote device using the SDP protocol. It is possible to specify the RFCOMM channel by hand, and in this case man:rfcomm_pppd[8] will not perform the SDP query. Use man:sdpcontrol[8] to find out the RFCOMM channel on the remote device. In order to provide network access with the PPPLAN service, man:sdpd[8] must be running and a new entry for LAN clients must be created in [.filename]#/etc/ppp/ppp.conf#. Consult man:rfcomm_pppd[8] for examples. Finally, start the RFCOMMPPP server on a valid RFCOMM channel number. The RFCOMMPPP server will automatically register the Bluetooth LAN service with the local SDP daemon. The example below shows how to start the RFCOMMPPP server. [source,shell] .... # rfcomm_pppd -s -C 7 -l rfcomm-server .... === 藍牙通訊協定 This section provides an overview of the various Bluetooth protocols, their function, and associated utilities. ==== Logical Link Control and Adaptation Protocol (L2CAP) The Logical Link Control and Adaptation Protocol (L2CAP) provides connection-oriented and connectionless data services to upper layer protocols. L2CAP permits higher level protocols and applications to transmit and receive L2CAP data packets up to 64 kilobytes in length. L2CAP is based around the concept of _channels_. A channel is a logical connection on top of a baseband connection, where each channel is bound to a single protocol in a many-to-one fashion. Multiple channels can be bound to the same protocol, but a channel cannot be bound to multiple protocols. Each L2CAP packet received on a channel is directed to the appropriate higher level protocol. Multiple channels can share the same baseband connection. In FreeBSD, a netgraph L2CAP node is created for each Bluetooth device. This node is normally connected to the downstream Bluetooth HCI node and upstream Bluetooth socket nodes. The default name for the L2CAP node is "devicel2cap". For more details refer to man:ng_l2cap[4]. A useful command is man:l2ping[8], which can be used to ping other devices. Some Bluetooth implementations might not return all of the data sent to them, so `0 bytes` in the following example is normal. [source,shell] .... # l2ping -a 00:80:37:29:19:a4 0 bytes from 0:80:37:29:19:a4 seq_no=0 time=48.633 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=1 time=37.551 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=2 time=28.324 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=3 time=46.150 ms result=0 .... The man:l2control[8] utility is used to perform various operations on L2CAP nodes. This example shows how to obtain the list of logical connections (channels) and the list of baseband connections for the local device: [source,shell] .... % l2control -a 00:02:72:00:d4:1a read_channel_list L2CAP channels: Remote BD_ADDR SCID/ DCID PSM IMTU/ OMTU State 00:07:e0:00:0b:ca 66/ 64 3 132/ 672 OPEN % l2control -a 00:02:72:00:d4:1a read_connection_list L2CAP connections: Remote BD_ADDR Handle Flags Pending State 00:07:e0:00:0b:ca 41 O 0 OPEN .... Another diagnostic tool is man:btsockstat[1]. It is similar to man:netstat[1], but for Bluetooth network-related data structures. The example below shows the same logical connection as man:l2control[8] above. [source,shell] .... % btsockstat Active L2CAP sockets PCB Recv-Q Send-Q Local address/PSM Foreign address CID State c2afe900 0 0 00:02:72:00:d4:1a/3 00:07:e0:00:0b:ca 66 OPEN Active RFCOMM sessions L2PCB PCB Flag MTU Out-Q DLCs State c2afe900 c2b53380 1 127 0 Yes OPEN Active RFCOMM sockets PCB Recv-Q Send-Q Local address Foreign address Chan DLCI State c2e8bc80 0 250 00:02:72:00:d4:1a 00:07:e0:00:0b:ca 3 6 OPEN .... ==== Radio Frequency Communication (RFCOMM) The RFCOMM protocol provides emulation of serial ports over the L2CAP protocol. RFCOMM is a simple transport protocol, with additional provisions for emulating the 9 circuits of RS-232 (EIATIA-232-E) serial ports. It supports up to 60 simultaneous connections (RFCOMM channels) between two Bluetooth devices. For the purposes of RFCOMM, a complete communication path involves two applications running on the communication endpoints with a communication segment between them. RFCOMM is intended to cover applications that make use of the serial ports of the devices in which they reside. The communication segment is a direct connect Bluetooth link from one device to another. RFCOMM is only concerned with the connection between the devices in the direct connect case, or between the device and a modem in the network case. RFCOMM can support other configurations, such as modules that communicate via Bluetooth wireless technology on one side and provide a wired interface on the other side. In FreeBSD, RFCOMM is implemented at the Bluetooth sockets layer. ==== Service Discovery Protocol (SDP) The Service Discovery Protocol (SDP) provides the means for client applications to discover the existence of services provided by server applications as well as the attributes of those services. The attributes of a service include the type or class of service offered and the mechanism or protocol information needed to utilize the service. SDP involves communication between a SDP server and a SDP client. The server maintains a list of service records that describe the characteristics of services associated with the server. Each service record contains information about a single service. A client may retrieve information from a service record maintained by the SDP server by issuing a SDP request. If the client, or an application associated with the client, decides to use a service, it must open a separate connection to the service provider in order to utilize the service. SDP provides a mechanism for discovering services and their attributes, but it does not provide a mechanism for utilizing those services. Normally, a SDP client searches for services based on some desired characteristics of the services. However, there are times when it is desirable to discover which types of services are described by an SDP server's service records without any prior information about the services. This process of looking for any offered services is called _browsing_. The Bluetooth SDP server, man:sdpd[8], and command line client, man:sdpcontrol[8], are included in the standard FreeBSD installation. The following example shows how to perform a SDP browse query. [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec browse Record Handle: 00000000 Service Class ID List: Service Discovery Server (0x1000) Protocol Descriptor List: L2CAP (0x0100) Protocol specific parameter #1: u/int/uuid16 1 Protocol specific parameter #2: u/int/uuid16 1 Record Handle: 0x00000001 Service Class ID List: Browse Group Descriptor (0x1001) Record Handle: 0x00000002 Service Class ID List: LAN Access Using PPP (0x1102) Protocol Descriptor List: L2CAP (0x0100) RFCOMM (0x0003) Protocol specific parameter #1: u/int8/bool 1 Bluetooth Profile Descriptor List: LAN Access Using PPP (0x1102) ver. 1.0 .... Note that each service has a list of attributes, such as the RFCOMM channel. Depending on the service, the user might need to make note of some of the attributes. Some Bluetooth implementations do not support service browsing and may return an empty list. In this case, it is possible to search for the specific service. The example below shows how to search for the OBEX Object Push (OPUSH) service: [source,shell] .... % sdpcontrol -a 00:01:03:fc:6e:ec search OPUSH .... Offering services on FreeBSD to Bluetooth clients is done with the man:sdpd[8] server. The following line can be added to [.filename]#/etc/rc.conf#: [.programlisting] .... sdpd_enable="YES" .... Then the man:sdpd[8] daemon can be started with: [source,shell] .... # service sdpd start .... The local server application that wants to provide a Bluetooth service to remote clients will register the service with the local SDP daemon. An example of such an application is man:rfcomm_pppd[8]. Once started, it will register the Bluetooth LAN service with the local SDP daemon. The list of services registered with the local SDP server can be obtained by issuing a SDP browse query via the local control channel: [source,shell] .... # sdpcontrol -l browse .... ==== OBEX Object Push (OPUSH) Object Exchange (OBEX) is a widely used protocol for simple file transfers between mobile devices. Its main use is in infrared communication, where it is used for generic file transfers between notebooks or PDAs, and for sending business cards or calendar entries between cellular phones and other devices with Personal Information Manager (PIM) applications. The OBEX server and client are implemented by obexapp, which can be installed using the package:comms/obexapp[] package or port. The OBEX client is used to push and/or pull objects from the OBEX server. An example object is a business card or an appointment. The OBEX client can obtain the RFCOMM channel number from the remote device via SDP. This can be done by specifying the service name instead of the RFCOMM channel number. Supported service names are: `IrMC`, `FTRN`, and `OPUSH`. It is also possible to specify the RFCOMM channel as a number. Below is an example of an OBEX session where the device information object is pulled from the cellular phone, and a new object, the business card, is pushed into the phone's directory. [source,shell] .... % obexapp -a 00:80:37:29:19:a4 -C IrMC obex> get telecom/devinfo.txt devinfo-t39.txt Success, response: OK, Success (0x20) obex> put new.vcf Success, response: OK, Success (0x20) obex> di Success, response: OK, Success (0x20) .... In order to provide the OPUSH service, man:sdpd[8] must be running and a root folder, where all incoming objects will be stored, must be created. The default path to the root folder is [.filename]#/var/spool/obex#. Finally, start the OBEX server on a valid RFCOMM channel number. The OBEX server will automatically register the OPUSH service with the local SDP daemon. The example below shows how to start the OBEX server. [source,shell] .... # obexapp -s -C 10 .... ==== Serial Port Profile (SPP) The Serial Port Profile (SPP) allows Bluetooth devices to perform serial cable emulation. This profile allows legacy applications to use Bluetooth as a cable replacement, through a virtual serial port abstraction. In FreeBSD, man:rfcomm_sppd[1] implements SPP and a pseudo tty is used as a virtual serial port abstraction. The example below shows how to connect to a remote device's serial port service. A RFCOMM channel does not have to be specified as man:rfcomm_sppd[1] can obtain it from the remote device via SDP. To override this, specify a RFCOMM channel on the command line. [source,shell] .... # rfcomm_sppd -a 00:07:E0:00:0B:CA -t rfcomm_sppd[94692]: Starting on /dev/pts/6... /dev/pts/6 .... Once connected, the pseudo tty can be used as serial port: [source,shell] .... # cu -l /dev/pts/6 .... The pseudo tty is printed on stdout and can be read by wrapper scripts: [.programlisting] .... PTS=`rfcomm_sppd -a 00:07:E0:00:0B:CA -t` cu -l $PTS .... === 疑難排解 By default, when FreeBSD is accepting a new connection, it tries to perform a role switch and become master. Some older Bluetooth devices which do not support role switching will not be able to connect. Since role switching is performed when a new connection is being established, it is not possible to ask the remote device if it supports role switching. However, there is a HCI option to disable role switching on the local side: [source,shell] .... # hccontrol -n ubt0hci write_node_role_switch 0 .... To display Bluetooth packets, use the third-party package hcidump, which can be installed using the package:comms/hcidump[] package or port. This utility is similar to man:tcpdump[1] and can be used to display the contents of Bluetooth packets on the terminal and to dump the Bluetooth packets to a file. [[network-bridging]] == 橋接 It is sometimes useful to divide a network, such as an Ethernet segment, into network segments without having to create IP subnets and use a router to connect the segments together. A device that connects two networks together in this fashion is called a "bridge". A bridge works by learning the MAC addresses of the devices on each of its network interfaces. It forwards traffic between networks only when the source and destination MAC addresses are on different networks. In many respects, a bridge is like an Ethernet switch with very few ports. A FreeBSD system with multiple network interfaces can be configured to act as a bridge. Bridging can be useful in the following situations: Connecting Networks:: The basic operation of a bridge is to join two or more network segments. There are many reasons to use a host-based bridge instead of networking equipment, such as cabling constraints or firewalling. A bridge can also connect a wireless interface running in hostap mode to a wired network and act as an access point. Filtering/Traffic Shaping Firewall:: A bridge can be used when firewall functionality is needed without routing or Network Address Translation (NAT). + An example is a small company that is connected via DSL or ISDN to an ISP. There are thirteen public IP addresses from the ISP and ten computers on the network. In this situation, using a router-based firewall is difficult because of subnetting issues. A bridge-based firewall can be configured without any IP addressing issues. Network Tap:: A bridge can join two network segments in order to inspect all Ethernet frames that pass between them using man:bpf[4] and man:tcpdump[1] on the bridge interface or by sending a copy of all frames out an additional interface known as a span port. Layer 2 VPN:: Two Ethernet networks can be joined across an IP link by bridging the networks to an EtherIP tunnel or a man:tap[4] based solution such as OpenVPN. Layer 2 Redundancy:: A network can be connected together with multiple links and use the Spanning Tree Protocol (STP) to block redundant paths. This section describes how to configure a FreeBSD system as a bridge using man:if_bridge[4]. A netgraph bridging driver is also available, and is described in man:ng_bridge[4]. [NOTE] ==== Packet filtering can be used with any firewall package that hooks into the man:pfil[9] framework. The bridge can be used as a traffic shaper with man:altq[4] or man:dummynet[4]. ==== === 開啟橋接 In FreeBSD, man:if_bridge[4] is a kernel module which is automatically loaded by man:ifconfig[8] when creating a bridge interface. It is also possible to compile bridge support into a custom kernel by adding `device if_bridge` to the custom kernel configuration file. The bridge is created using interface cloning. To create the bridge interface: [source,shell] .... # ifconfig bridge create bridge0 # ifconfig bridge0 bridge0: flags=8802 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:00:00:00:00:00 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:00:00:00:00:00 priority 0 ifcost 0 port 0 .... When a bridge interface is created, it is automatically assigned a randomly generated Ethernet address. The `maxaddr` and `timeout` parameters control how many MAC addresses the bridge will keep in its forwarding table and how many seconds before each entry is removed after it is last seen. The other parameters control how STP operates. Next, specify which network interfaces to add as members of the bridge. For the bridge to forward packets, all member interfaces and the bridge need to be up: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 up # ifconfig fxp0 up # ifconfig fxp1 up .... The bridge can now forward Ethernet frames between [.filename]#fxp0# and [.filename]#fxp1#. Add the following lines to [.filename]#/etc/rc.conf# so the bridge is created at startup: [.programlisting] .... cloned_interfaces="bridge0" ifconfig_bridge0="addm fxp0 addm fxp1 up" ifconfig_fxp0="up" ifconfig_fxp1="up" .... If the bridge host needs an IP address, set it on the bridge interface, not on the member interfaces. The address can be set statically or via DHCP. This example sets a static IP address: [source,shell] .... # ifconfig bridge0 inet 192.168.0.1/24 .... It is also possible to assign an IPv6 address to a bridge interface. To make the changes permanent, add the addressing information to [.filename]#/etc/rc.conf#. [NOTE] ==== When packet filtering is enabled, bridged packets will pass through the filter inbound on the originating interface on the bridge interface, and outbound on the appropriate interfaces. Either stage can be disabled. When direction of the packet flow is important, it is best to firewall on the member interfaces rather than the bridge itself. The bridge has several configurable settings for passing non-IP and IP packets, and layer2 firewalling with man:ipfw[8]. See man:if_bridge[4] for more information. ==== === 開啟 Spanning Tree For an Ethernet network to function properly, only one active path can exist between two devices. The STP protocol detects loops and puts redundant links into a blocked state. Should one of the active links fail, STP calculates a different tree and enables one of the blocked paths to restore connectivity to all points in the network. The Rapid Spanning Tree Protocol (RSTP or 802.1w) provides backwards compatibility with legacy STP. RSTP provides faster convergence and exchanges information with neighboring switches to quickly transition to forwarding mode without creating loops. FreeBSD supports RSTP and STP as operating modes, with RSTP being the default mode. STP can be enabled on member interfaces using man:ifconfig[8]. For a bridge with [.filename]#fxp0# and [.filename]#fxp1# as the current interfaces, enable STP with: [source,shell] .... # ifconfig bridge0 stp fxp0 stp fxp1 bridge0: flags=8843 metric 0 mtu 1500 ether d6:cf:d5:a0:94:6d id 00:01:02:4b:d4:50 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 0 port 0 member: fxp0 flags=1c7 port 3 priority 128 path cost 200000 proto rstp role designated state forwarding member: fxp1 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role designated state forwarding .... This bridge has a spanning tree ID of `00:01:02:4b:d4:50` and a priority of `32768`. As the `root id` is the same, it indicates that this is the root bridge for the tree. Another bridge on the network also has STP enabled: [source,shell] .... bridge0: flags=8843 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:13:d4:9a:06:7a priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4 member: fxp0 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role root state forwarding member: fxp1 flags=1c7 port 5 priority 128 path cost 200000 proto rstp role designated state forwarding .... The line `root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4` shows that the root bridge is `00:01:02:4b:d4:50` and has a path cost of `400000` from this bridge. The path to the root bridge is via `port 4` which is [.filename]#fxp0#. === 橋接介面參數 Several `ifconfig` parameters are unique to bridge interfaces. This section summarizes some common uses for these parameters. The complete list of available parameters is described in man:ifconfig[8]. private:: A private interface does not forward any traffic to any other port that is also designated as a private interface. The traffic is blocked unconditionally so no Ethernet frames will be forwarded, including ARP packets. If traffic needs to be selectively blocked, a firewall should be used instead. span:: A span port transmits a copy of every Ethernet frame received by the bridge. The number of span ports configured on a bridge is unlimited, but if an interface is designated as a span port, it cannot also be used as a regular bridge port. This is most useful for snooping a bridged network passively on another host connected to one of the span ports of the bridge. For example, to send a copy of all frames out the interface named [.filename]#fxp4#: + [source,shell] .... # ifconfig bridge0 span fxp4 .... sticky:: If a bridge member interface is marked as sticky, dynamically learned address entries are treated as static entries in the forwarding cache. Sticky entries are never aged out of the cache or replaced, even if the address is seen on a different interface. This gives the benefit of static address entries without the need to pre-populate the forwarding table. Clients learned on a particular segment of the bridge cannot roam to another segment. + An example of using sticky addresses is to combine the bridge with VLANs in order to isolate customer networks without wasting IP address space. Consider that `CustomerA` is on `vlan100`, `CustomerB` is on `vlan101`, and the bridge has the address `192.168.0.1`: + [source,shell] .... # ifconfig bridge0 addm vlan100 sticky vlan100 addm vlan101 sticky vlan101 # ifconfig bridge0 inet 192.168.0.1/24 .... + In this example, both clients see `192.168.0.1` as their default gateway. Since the bridge cache is sticky, one host cannot spoof the MAC address of the other customer in order to intercept their traffic. + Any communication between the VLANs can be blocked using a firewall or, as seen in this example, private interfaces: + [source,shell] .... # ifconfig bridge0 private vlan100 private vlan101 .... + The customers are completely isolated from each other and the full `/24` address range can be allocated without subnetting. + The number of unique source MAC addresses behind an interface can be limited. Once the limit is reached, packets with unknown source addresses are dropped until an existing host cache entry expires or is removed. + The following example sets the maximum number of Ethernet devices for `CustomerA` on `vlan100` to 10: + [source,shell] .... # ifconfig bridge0 ifmaxaddr vlan100 10 .... Bridge interfaces also support monitor mode, where the packets are discarded after man:bpf[4] processing and are not processed or forwarded further. This can be used to multiplex the input of two or more interfaces into a single man:bpf[4] stream. This is useful for reconstructing the traffic for network taps that transmit the RX/TX signals out through two separate interfaces. For example, to read the input from four network interfaces as one stream: [source,shell] .... # ifconfig bridge0 addm fxp0 addm fxp1 addm fxp2 addm fxp3 monitor up # tcpdump -i bridge0 .... === SNMP 監視 The bridge interface and STP parameters can be monitored via man:bsnmpd[1] which is included in the FreeBSD base system. The exported bridge MIBs conform to IETF standards so any SNMP client or monitoring package can be used to retrieve the data. To enable monitoring on the bridge, uncomment this line in [.filename]#/etc/snmpd.config# by removing the beginning `#` symbol: [.programlisting] .... begemotSnmpdModulePath."bridge" = "/usr/lib/snmp_bridge.so" .... Other configuration settings, such as community names and access lists, may need to be modified in this file. See man:bsnmpd[1] and man:snmp_bridge[3] for more information. Once these edits are saved, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... bsnmpd_enable="YES" .... Then, start man:bsnmpd[1]: [source,shell] .... # service bsnmpd start .... The following examples use the Net-SNMP software (package:net-mgmt/net-snmp[]) to query a bridge from a client system. The package:net-mgmt/bsnmptools[] port can also be used. From the SNMP client which is running Net-SNMP, add the following lines to [.filename]#$HOME/.snmp/snmp.conf# in order to import the bridge MIB definitions: [.programlisting] .... mibdirs +/usr/shared/snmp/mibs mibs +BRIDGE-MIB:RSTP-MIB:BEGEMOT-MIB:BEGEMOT-BRIDGE-MIB .... To monitor a single bridge using the IETF BRIDGE-MIB (RFC4188): [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com mib-2.dot1dBridge BRIDGE-MIB::dot1dBaseBridgeAddress.0 = STRING: 66:fb:9b:6e:5c:44 BRIDGE-MIB::dot1dBaseNumPorts.0 = INTEGER: 1 ports BRIDGE-MIB::dot1dStpTimeSinceTopologyChange.0 = Timeticks: (189959) 0:31:39.59 centi-seconds BRIDGE-MIB::dot1dStpTopChanges.0 = Counter32: 2 BRIDGE-MIB::dot1dStpDesignatedRoot.0 = Hex-STRING: 80 00 00 01 02 4B D4 50 ... BRIDGE-MIB::dot1dStpPortState.3 = INTEGER: forwarding(5) BRIDGE-MIB::dot1dStpPortEnable.3 = INTEGER: enabled(1) BRIDGE-MIB::dot1dStpPortPathCost.3 = INTEGER: 200000 BRIDGE-MIB::dot1dStpPortDesignatedRoot.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedCost.3 = INTEGER: 0 BRIDGE-MIB::dot1dStpPortDesignatedBridge.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedPort.3 = Hex-STRING: 03 80 BRIDGE-MIB::dot1dStpPortForwardTransitions.3 = Counter32: 1 RSTP-MIB::dot1dStpVersion.0 = INTEGER: rstp(2) .... The `dot1dStpTopChanges.0` value is two, indicating that the STP bridge topology has changed twice. A topology change means that one or more links in the network have changed or failed and a new tree has been calculated. The `dot1dStpTimeSinceTopologyChange.0` value will show when this happened. To monitor multiple bridge interfaces, the private BEGEMOT-BRIDGE-MIB can be used: [source,shell] .... % snmpwalk -v 2c -c public bridge1.example.com enterprises.fokus.begemot.begemotBridge BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge0" = STRING: bridge0 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge2" = STRING: bridge2 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge0" = STRING: e:ce:3b:5a:9e:13 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge2" = STRING: 12:5e:4d:74:d:fc BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge0" = INTEGER: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge2" = INTEGER: 1 ... BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge0" = Timeticks: (116927) 0:19:29.27 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge2" = Timeticks: (82773) 0:13:47.73 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge0" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge2" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge0" = Hex-STRING: 80 00 00 40 95 30 5E 31 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge2" = Hex-STRING: 80 00 00 50 8B B8 C6 A9 .... To change the bridge interface being monitored via the `mib-2.dot1dBridge` subtree: [source,shell] .... % snmpset -v 2c -c private bridge1.example.com BEGEMOT-BRIDGE-MIB::begemotBridgeDefaultBridgeIf.0 s bridge2 .... [[network-aggregation]] == Link Aggregation 與容錯移轉 FreeBSD provides the man:lagg[4] interface which can be used to aggregate multiple network interfaces into one virtual interface in order to provide failover and link aggregation. Failover allows traffic to continue to flow as long as at least one aggregated network interface has an established link. Link aggregation works best on switches which support LACP, as this protocol distributes traffic bi-directionally while responding to the failure of individual links. The aggregation protocols supported by the lagg interface determine which ports are used for outgoing traffic and whether or not a specific port accepts incoming traffic. The following protocols are supported by man:lagg[4]: failover:: This mode sends and receives traffic only through the master port. If the master port becomes unavailable, the next active port is used. The first interface added to the virtual interface is the master port and all subsequently added interfaces are used as failover devices. If failover to a non-master port occurs, the original port becomes master once it becomes available again. fec / loadbalance:: Cisco(TM) Fast EtherChannel(TM) (FEC) is found on older Cisco(TM) switches. It provides a static setup and does not negotiate aggregation with the peer or exchange frames to monitor the link. If the switch supports LACP, that should be used instead. lacp:: The IEEE(TM) 802.3ad Link Aggregation Control Protocol (LACP) negotiates a set of aggregable links with the peer into one or more Link Aggregated Groups (LAGs). Each LAG is composed of ports of the same speed, set to full-duplex operation, and traffic is balanced across the ports in the LAG with the greatest total speed. Typically, there is only one LAG which contains all the ports. In the event of changes in physical connectivity, LACP will quickly converge to a new configuration. + LACP balances outgoing traffic across the active ports based on hashed protocol header information and accepts incoming traffic from any active port. The hash includes the Ethernet source and destination address and, if available, the VLAN tag, and the IPv4 or IPv6 source and destination address. roundrobin:: This mode distributes outgoing traffic using a round-robin scheduler through all active ports and accepts incoming traffic from any active port. Since this mode violates Ethernet frame ordering, it should be used with caution. === 設定範例 This section demonstrates how to configure a Cisco(TM) switch and a FreeBSD system for LACP load balancing. It then shows how to configure two Ethernet interfaces in failover mode as well as how to configure failover mode between an Ethernet and a wireless interface. [[networking-lacp-aggregation-cisco]] .Cisco(TM) 交換器上設定 LACP Aggregation [example] ==== This example connects two man:fxp[4] Ethernet interfaces on a FreeBSD machine to the first two Ethernet ports on a Cisco(TM) switch as a single load balanced and fault tolerant link. More interfaces can be added to increase throughput and fault tolerance. Replace the names of the Cisco(TM) ports, Ethernet devices, channel group number, and IP address shown in the example to match the local configuration. Frame ordering is mandatory on Ethernet links and any traffic between two stations always flows over the same physical link, limiting the maximum speed to that of one interface. The transmit algorithm attempts to use as much information as it can to distinguish different traffic flows and balance the flows across the available interfaces. On the Cisco(TM) switch, add the _FastEthernet0/1_ and _FastEthernet0/2_ interfaces to channel group _1_: [source,shell] .... interface FastEthernet0/1 channel-group 1 mode active channel-protocol lacp ! interface FastEthernet0/2 channel-group 1 mode active channel-protocol lacp .... On the FreeBSD system, create the man:lagg[4] interface using the physical interfaces _fxp0_ and _fxp1_ and bring the interfaces up with an IP address of _10.0.0.3/24_: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24 .... Next, verify the status of the virtual interface: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.3 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto lacp laggport: fxp1 flags=1c laggport: fxp0 flags=1c .... Ports marked as `ACTIVE` are part of the LAG that has been negotiated with the remote switch. Traffic will be transmitted and received through these active ports. Add `-v` to the above command to view the LAG identifiers. To see the port status on the Cisco(TM) switch: [source,shell] .... switch# show lacp neighbor Flags: S - Device is requesting Slow LACPDUs F - Device is requesting Fast LACPDUs A - Device is in Active mode P - Device is in Passive mode Channel group 1 neighbors Partner's information: LACP port Oper Port Port Port Flags Priority Dev ID Age Key Number State Fa0/1 SA 32768 0005.5d71.8db8 29s 0x146 0x3 0x3D Fa0/2 SA 32768 0005.5d71.8db8 29s 0x146 0x4 0x3D .... For more detail, type `show lacp neighbor detail`. To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf# on the FreeBSD system: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24" .... ==== [[networking-lagg-failover]] .容錯移轉模式 [example] ==== Failover mode can be used to switch over to a secondary interface if the link is lost on the master interface. To configure failover, make sure that the underlying physical interfaces are up, then create the man:lagg[4] interface. In this example, _fxp0_ is the master interface, _fxp1_ is the secondary interface, and the virtual interface is assigned an IP address of _10.0.0.15/24_: [source,shell] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24 .... The virtual interface should look something like this: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.15 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto failover laggport: fxp1 flags=0<> laggport: fxp0 flags=5 .... Traffic will be transmitted and received on _fxp0_. If the link is lost on _fxp0_, _fxp1_ will become the active link. If the link is restored on the master interface, it will once again become the active link. To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24" .... ==== [[networking-lagg-wired-and-wireless]] .乙太網路與無線介面間的容錯移轉模式 [example] ==== For laptop users, it is usually desirable to configure the wireless device as a secondary which is only used when the Ethernet connection is not available. With man:lagg[4], it is possible to configure a failover which prefers the Ethernet connection for both performance and security reasons, while maintaining the ability to transfer data over the wireless connection. This is achieved by overriding the physical wireless interface's MAC address with that of the Ethernet interface. In this example, the Ethernet interface, _bge0_, is the master and the wireless interface, _wlan0_, is the failover. The _wlan0_ device was created from _iwn0_ wireless interface, which will be configured with the MAC address of the Ethernet interface. First, determine the MAC address of the Ethernet interface: [source,shell] .... # ifconfig bge0 bge0: flags=8843 metric 0 mtu 1500 options=19b ether 00:21:70:da:ae:37 inet6 fe80::221:70ff:feda:ae37%bge0 prefixlen 64 scopeid 0x2 nd6 options=29 media: Ethernet autoselect (1000baseT ) status: active .... Replace _bge0_ to match the system's Ethernet interface name. The `ether` line will contain the MAC address of the specified interface. Now, change the MAC address of the underlying wireless interface: [source,shell] .... # ifconfig iwn0 ether 00:21:70:da:ae:37 .... Bring the wireless interface up, but do not set an IP address: [source,shell] .... # ifconfig wlan0 create wlandev iwn0 ssid my_router up .... Make sure the _bge0_ interface is up, then create the man:lagg[4] interface with _bge0_ as master with failover to _wlan0_: [source,shell] .... # ifconfig bge0 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport bge0 laggport wlan0 .... The virtual interface should look something like this: [source,shell] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:21:70:da:ae:37 media: Ethernet autoselect status: active laggproto failover laggport: wlan0 flags=0<> laggport: bge0 flags=5 .... Then, start the DHCP client to obtain an IP address: [source,shell] .... # dhclient lagg0 .... To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_bge0="up" wlans_iwn0="wlan0" ifconfig_wlan0="WPA" create_args_wlan0="wlanaddr 00:21:70:da:ae:37" cloned_interfaces="lagg0" ifconfig_lagg0="up laggproto failover laggport bge0 laggport wlan0 DHCP" .... ==== [[network-diskless]] == PXE 無磁碟作業 The Intel(TM) Preboot eXecution Environment (PXE) allows an operating system to boot over the network. For example, a FreeBSD system can boot over the network and operate without a local disk, using file systems mounted from an NFS server. PXE support is usually available in the BIOS. To use PXE when the machine starts, select the `Boot from network` option in the BIOS setup or type a function key during system initialization. In order to provide the files needed for an operating system to boot over the network, a PXE setup also requires properly configured DHCP, TFTP, and NFS servers, where: * Initial parameters, such as an IP address, executable boot filename and location, server name, and root path are obtained from the DHCP server. * The operating system loader file is booted using TFTP. * The file systems are loaded using NFS. When a computer PXE boots, it receives information over DHCP about where to obtain the initial boot loader file. After the host computer receives this information, it downloads the boot loader via TFTP and then executes the boot loader. In FreeBSD, the boot loader file is [.filename]#/boot/pxeboot#. After [.filename]#/boot/pxeboot# executes, the FreeBSD kernel is loaded and the rest of the FreeBSD bootup sequence proceeds, as described in crossref:boot[boot,FreeBSD 開機程序]. This section describes how to configure these services on a FreeBSD system so that other systems can PXE boot into FreeBSD. Refer to man:diskless[8] for more information. [CAUTION] ==== As described, the system providing these services is insecure. It should live in a protected area of a network and be untrusted by other hosts. ==== [[network-pxe-nfs]] === 設定 PXE 環境 The steps shown in this section configure the built-in NFS and TFTP servers. The next section demonstrates how to install and configure the DHCP server. In this example, the directory which will contain the files used by PXE users is [.filename]#/b/tftpboot/FreeBSD/install#. It is important that this directory exists and that the same directory name is set in both [.filename]#/etc/inetd.conf# and [.filename]#/usr/local/etc/dhcpd.conf#. [.procedure] ==== . Create the root directory which will contain a FreeBSD installation to be NFS mounted: + [source,shell] .... # export NFSROOTDIR=/b/tftpboot/FreeBSD/install # mkdir -p ${NFSROOTDIR} .... + . Enable the NFS server by adding this line to [.filename]#/etc/rc.conf#: + [.programlisting] .... nfs_server_enable="YES" .... + . Export the diskless root directory via NFS by adding the following to [.filename]#/etc/exports#: + [.programlisting] .... /b -ro -alldirs -maproot=root .... + . Start the NFS server: + [source,shell] .... # service nfsd start .... + . Enable man:inetd[8] by adding the following line to [.filename]#/etc/rc.conf#: + [.programlisting] .... inetd_enable="YES" .... . Uncomment the following line in [.filename]#/etc/inetd.conf# by making sure it does not start with a `#` symbol: + [.programlisting] .... tftp dgram udp wait root /usr/libexec/tftpd tftpd -l -s /b/tftpboot .... + [NOTE] ====== Some PXE versions require the TCP version of TFTP. In this case, uncomment the second `tftp` line which contains `stream tcp`. ====== + . Start man:inetd[8]: + [source,shell] .... # service inetd start .... + . Install the base system into [.filename]#${NFSROOTDIR}#, either by decompressing the official archives or by rebuilding the FreeBSD kernel and userland (refer to crossref:cutting-edge[makeworld,從原始碼更新 FreeBSD] for more detailed instructions, but do not forget to add `DESTDIR=_${NFSROOTDIR}_` when running the `make installkernel` and `make installworld` commands. . Test that the TFTP server works and can download the boot loader which will be obtained via PXE: + [source,shell] .... # tftp localhost tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... + . Edit [.filename]#${NFSROOTDIR}/etc/fstab# and create an entry to mount the root file system over NFS: + [.programlisting] .... # Device Mountpoint FSType Options Dump Pass myhost.example.com:/b/tftpboot/FreeBSD/install / nfs ro 0 0 .... + Replace _myhost.example.com_ with the hostname or IP address of the NFS server. In this example, the root file system is mounted read-only in order to prevent NFS clients from potentially deleting the contents of the root file system. . Set the root password in the PXE environment for client machines which are PXE booting : + [source,shell] .... # chroot ${NFSROOTDIR} # passwd .... + . If needed, enable man:ssh[1] root logins for client machines which are PXE booting by editing [.filename]#${NFSROOTDIR}/etc/ssh/sshd_config# and enabling `PermitRootLogin`. This option is documented in man:sshd_config[5]. . Perform any other needed customizations of the PXE environment in [.filename]#${NFSROOTDIR}#. These customizations could include things like installing packages or editing the password file with man:vipw[8]. ==== When booting from an NFS root volume, [.filename]#/etc/rc# detects the NFS boot and runs [.filename]#/etc/rc.initdiskless#. In this case, [.filename]#/etc# and [.filename]#/var# need to be memory backed file systems so that these directories are writable but the NFS root directory is read-only: [source,shell] .... # chroot ${NFSROOTDIR} # mkdir -p conf/base # tar -c -v -f conf/base/etc.cpio.gz --format cpio --gzip etc # tar -c -v -f conf/base/var.cpio.gz --format cpio --gzip var .... When the system boots, memory file systems for [.filename]#/etc# and [.filename]#/var# will be created and mounted and the contents of the [.filename]#cpio.gz# files will be copied into them. By default, these file systems have a maximum capacity of 5 megabytes. If your archives do not fit, which is usually the case for [.filename]#/var# when binary packages have been installed, request a larger size by putting the number of 512 byte sectors needed (e.g., 5 megabytes is 10240 sectors) in [.filename]#${NFSROOTDIR}/conf/base/etc/md_size# and [.filename]#${NFSROOTDIR}/conf/base/var/md_size# files for [.filename]#/etc# and [.filename]#/var# file systems respectively. [[network-pxe-setting-up-dhcp]] === 設定 DHCP 伺服器 The DHCP server does not need to be the same machine as the TFTP and NFS server, but it needs to be accessible in the network. -DHCP is not part of the FreeBSD base system but can be installed using the package:net/isc-dhcp43-server[] port or package. +DHCP is not part of the FreeBSD base system but can be installed using the package:net/isc-dhcp44-server[] port or package. Once installed, edit the configuration file, [.filename]#/usr/local/etc/dhcpd.conf#. Configure the `next-server`, `filename`, and `root-path` settings as seen in this example: [.programlisting] .... subnet 192.168.0.0 netmask 255.255.255.0 { range 192.168.0.2 192.168.0.3 ; option subnet-mask 255.255.255.0 ; option routers 192.168.0.1 ; option broadcast-address 192.168.0.255 ; option domain-name-servers 192.168.35.35, 192.168.35.36 ; option domain-name "example.com"; # IP address of TFTP server next-server 192.168.0.1 ; # path of boot loader obtained via tftp filename "FreeBSD/install/boot/pxeboot" ; # pxeboot boot loader will try to NFS mount this directory for root FS option root-path "192.168.0.1:/b/tftpboot/FreeBSD/install/" ; } .... The `next-server` directive is used to specify the IP address of the TFTP server. The `filename` directive defines the path to [.filename]#/boot/pxeboot#. A relative filename is used, meaning that [.filename]#/b/tftpboot# is not included in the path. The `root-path` option defines the path to the NFS root file system. Once the edits are saved, enable DHCP at boot time by adding the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" .... Then start the DHCP service: [source,shell] .... # service isc-dhcpd start .... === PXE 問題除錯 Once all of the services are configured and started, PXE clients should be able to automatically load FreeBSD over the network. If a particular client is unable to connect, when that client machine boots up, enter the BIOS configuration menu and confirm that it is set to boot from the network. This section describes some troubleshooting tips for isolating the source of the configuration problem should no clients be able to PXE boot. [.procedure] ==== . Use the package:net/wireshark[] package or port to debug the network traffic involved during the PXE booting process, which is illustrated in the diagram below. + .使用 NFS Root Mount 進行 PXE 開機程序 image::pxe-nfs.png[] + . On the TFTP server, read [.filename]#/var/log/xferlog# to ensure that [.filename]#pxeboot# is being retrieved from the correct location. To test this example configuration: + [source,shell] .... # tftp 192.168.0.1 tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... + The `BUGS` sections in man:tftpd[8] and man:tftp[1] document some limitations with TFTP. . Make sure that the root file system can be mounted via NFS. To test this example configuration: + [source,shell] .... # mount -t nfs 192.168.0.1:/b/tftpboot/FreeBSD/install /mnt .... ==== [[network-ipv6]] == IPv6 IPv6 is the new version of the well known IP protocol, also known as IPv4. IPv6 provides several advantages over IPv4 as well as many new features: * Its 128-bit address space allows for 340,282,366,920,938,463,463,374,607,431,768,211,456 addresses. This addresses the IPv4 address shortage and eventual IPv4 address exhaustion. * Routers only store network aggregation addresses in their routing tables, thus reducing the average space of a routing table to 8192 entries. This addresses the scalability issues associated with IPv4, which required every allocated block of IPv4 addresses to be exchanged between Internet routers, causing their routing tables to become too large to allow efficient routing. * Address autoconfiguration (http://www.ietf.org/rfc/rfc2462.txt[RFC2462]). * Mandatory multicast addresses. * Built-in IPsec (IP security). * Simplified header structure. * Support for mobile IP. * IPv6-to-IPv4 transition mechanisms. FreeBSD includes the http://www.kame.net/[http://www.kame.net/]IPv6 reference implementation and comes with everything needed to use IPv6. This section focuses on getting IPv6 configured and running. === IPv6 位址的背景知識 There are three different types of IPv6 addresses: Unicast:: A packet sent to a unicast address arrives at the interface belonging to the address. Anycast:: These addresses are syntactically indistinguishable from unicast addresses but they address a group of interfaces. The packet destined for an anycast address will arrive at the nearest router interface. Anycast addresses are only used by routers. Multicast:: These addresses identify a group of interfaces. A packet destined for a multicast address will arrive at all interfaces belonging to the multicast group. The IPv4 broadcast address, usually `xxx.xxx.xxx.255`, is expressed by multicast addresses in IPv6. When reading an IPv6 address, the canonical form is represented as `x:x:x:x:x:x:x:x`, where each `x` represents a 16 bit hex value. An example is `FEBC:A574:382B:23C1:AA49:4592:4EFE:9982`. Often, an address will have long substrings of all zeros. A `::` (double colon) can be used to replace one substring per address. Also, up to three leading ``0``s per hex value can be omitted. For example, `fe80::1` corresponds to the canonical form `fe80:0000:0000:0000:0000:0000:0000:0001`. A third form is to write the last 32 bits using the well known IPv4 notation. For example, `2002::10.0.0.1` corresponds to the hexadecimal canonical representation `2002:0000:0000:0000:0000:0000:0a00:0001`, which in turn is equivalent to `2002::a00:1`. To view a FreeBSD system's IPv6 address, use man:ifconfig[8]: [source,shell] .... # ifconfig .... [.programlisting] .... rl0: flags=8943 mtu 1500 inet 10.0.0.10 netmask 0xffffff00 broadcast 10.0.0.255 inet6 fe80::200:21ff:fe03:8e1%rl0 prefixlen 64 scopeid 0x1 ether 00:00:21:03:08:e1 media: Ethernet autoselect (100baseTX ) status: active .... In this example, the [.filename]#rl0# interface is using `fe80::200:21ff:fe03:8e1%rl0`, an auto-configured link-local address which was automatically generated from the MAC address. Some IPv6 addresses are reserved. A summary of these reserved addresses is seen in <>: [[reservedip6]] .已保留的 IPv6 位址 [cols="1,1,1,1", frame="none", options="header"] |=== | IPv6 address | Prefixlength (Bits) | 說明 | 說明 |`::` |128 bits |unspecified |Equivalent to `0.0.0.0` in IPv4. |`::1` |128 bits |loopback address |Equivalent to `127.0.0.1` in IPv4. |`::00:xx:xx:xx:xx` |96 bits |embedded IPv4 |The lower 32 bits are the compatible IPv4 address. |`::ff:xx:xx:xx:xx` |96 bits |IPv4 mapped IPv6 address |The lower 32 bits are the IPv4 address for hosts which do not support IPv6. |`fe80::/10` |10 bits |link-local |Equivalent to 169.254.0.0/16 in IPv4. |`fc00::/7` |7 bits |unique-local |Unique local addresses are intended for local communication and are only routable within a set of cooperating sites. |`ff00::` |8 bits |multicast | |`2000::-3fff:` |3 bits |global unicast |All global unicast addresses are assigned from this pool. The first 3 bits are `001`. |=== For further information on the structure of IPv6 addresses, refer to http://www.ietf.org/rfc/rfc3513.txt[RFC3513]. === 設定 IPv6 To configure a FreeBSD system as an IPv6 client, add these two lines to [.filename]#rc.conf#: [.programlisting] .... ifconfig_rl0_ipv6="inet6 accept_rtadv" rtsold_enable="YES" .... The first line enables the specified interface to receive router advertisement messages. The second line enables the router solicitation daemon, man:rtsol[8]. If the interface needs a statically assigned IPv6 address, add an entry to specify the static address and associated prefix length: [.programlisting] .... ifconfig_rl0_ipv6="inet6 2001:db8:4672:6565:2026:5043:2d42:5344 prefixlen 64" .... To assign a default router, specify its address: [.programlisting] .... ipv6_defaultrouter="2001:db8:4672:6565::1" .... === 連線到 Provider In order to connect to other IPv6 networks, one must have a provider or a tunnel that supports IPv6: * Contact an Internet Service Provider to see if they offer IPv6. * http://www.tunnelbroker.net[Hurricane Electric] offers tunnels with end-points all around the globe. [NOTE] ==== Install the package:net/freenet6[] package or port for a dial-up connection. ==== This section demonstrates how to take the directions from a tunnel provider and convert them into [.filename]#/etc/rc.conf# settings that will persist through reboots. The first [.filename]#/etc/rc.conf# entry creates the generic tunneling interface [.filename]#gif0#: [.programlisting] .... cloned_interfaces="gif0" .... Next, configure that interface with the IPv4 addresses of the local and remote endpoints. Replace _MY_IPv4_ADDR_ and _REMOTE_IPv4_ADDR_ with the actual IPv4 addresses: [.programlisting] .... create_args_gif0="tunnel MY_IPv4_ADDR REMOTE_IPv4_ADDR" .... To apply the IPv6 address that has been assigned for use as the IPv6 tunnel endpoint, add this line, replacing _MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR_ with the assigned address: [.programlisting] .... ifconfig_gif0_ipv6="inet6 MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR" .... Then, set the default route for the other side of the IPv6 tunnel. Replace _MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR_ with the default gateway address assigned by the provider: [.programlisting] .... ipv6_defaultrouter="MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR" .... If the FreeBSD system will route IPv6 packets between the rest of the network and the world, enable the gateway using this line: [.programlisting] .... ipv6_gateway_enable="YES" .... === Router Advertisement 與 Host Auto Configuration This section demonstrates how to setup man:rtadvd[8] to advertise the IPv6 default route. To enable man:rtadvd[8], add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... rtadvd_enable="YES" .... It is important to specify the interface on which to do IPv6 router advertisement. For example, to tell man:rtadvd[8] to use [.filename]#rl0#: [.programlisting] .... rtadvd_interfaces="rl0" .... Next, create the configuration file, [.filename]#/etc/rtadvd.conf# as seen in this example: [.programlisting] .... rl0:\ :addrs#1:addr="2001:db8:1f11:246::":prefixlen#64:tc=ether: .... Replace [.filename]#rl0# with the interface to be used and `2001:db8:1f11:246::` with the prefix of the allocation. For a dedicated `/64` subnet, nothing else needs to be changed. Otherwise, change the `prefixlen#` to the correct value. === IPv6 與 IPv6 位址對應表 When IPv6 is enabled on a server, there may be a need to enable IPv4 mapped IPv6 address communication. This compatibility option allows for IPv4 addresses to be represented as IPv6 addresses. Permitting IPv6 applications to communicate with IPv4 and vice versa may be a security issue. This option may not be required in most cases and is available only for compatibility. This option will allow IPv6-only applications to work with IPv4 in a dual stack environment. This is most useful for third party applications which may not support an IPv6-only environment. To enable this feature, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... ipv6_ipv4mapping="YES" .... Reviewing the information in RFC 3493, section 3.6 and 3.7 as well as RFC 4038 section 4.2 may be useful to some administrators. [[carp]] == 共用位址備援協定 (CARP) The Common Address Redundancy Protocol (CARP) allows multiple hosts to share the same IP address and Virtual Host ID (VHID) in order to provide _high availability_ for one or more services. This means that one or more hosts can fail, and the other hosts will transparently take over so that users do not see a service failure. In addition to the shared IP address, each host has its own IP address for management and configuration. All of the machines that share an IP address have the same VHID. The VHID for each virtual IP address must be unique across the broadcast domain of the network interface. High availability using CARP is built into FreeBSD, though the steps to configure it vary slightly depending upon the FreeBSD version. This section provides the same example configuration for versions before and equal to or after FreeBSD 10. This example configures failover support with three hosts, all with unique IP addresses, but providing the same web content. It has two different masters named `hosta.example.org` and `hostb.example.org`, with a shared backup named `hostc.example.org`. These machines are load balanced with a Round Robin DNS configuration. The master and backup machines are configured identically except for their hostnames and management IP addresses. These servers must have the same configuration and run the same services. When the failover occurs, requests to the service on the shared IP address can only be answered correctly if the backup server has access to the same content. The backup machine has two additional CARP interfaces, one for each of the master content server's IP addresses. When a failure occurs, the backup server will pick up the failed master machine's IP address. [[carp-10x]] === 使用 CARP 於 FreeBSD 10 及之後版本 Enable boot-time support for CARP by adding an entry for the [.filename]#carp.ko# kernel module in [.filename]#/boot/loader.conf#: [.programlisting] .... carp_load="YES" .... To load the module now without rebooting: [source,shell] .... # kldload carp .... For users who prefer to use a custom kernel, include the following line in the custom kernel configuration file and compile the kernel as described in crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心]: [.programlisting] .... device carp .... The hostname, management IP address and subnet mask, shared IP address, and VHID are all set by adding entries to [.filename]#/etc/rc.conf#. This example is for `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_em0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 pass testpass alias 192.168.1.50/32" .... The next set of entries are for `hostb.example.org`. Since it represents a second master, it uses a different shared IP address and VHID. However, the passwords specified with `pass` must be identical as CARP will only listen to and accept advertisements from machines with the correct password. [.programlisting] .... hostname="hostb.example.org" ifconfig_em0="inet 192.168.1.4 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 2 pass testpass alias 192.168.1.51/32" .... The third machine, `hostc.example.org`, is configured to handle failover from either master. This machine is configured with two CARPVHIDs, one to handle the virtual IP address for each of the master hosts. The CARP advertising skew, `advskew`, is set to ensure that the backup host advertises later than the master, since `advskew` controls the order of precedence when there are multiple backup servers. [.programlisting] .... hostname="hostc.example.org" ifconfig_em0="inet 192.168.1.5 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 advskew 100 pass testpass alias 192.168.1.50/32" ifconfig_em0_alias1="inet vhid 2 advskew 100 pass testpass alias 192.168.1.51/32" .... Having two CARPVHIDs configured means that `hostc.example.org` will notice if either of the master servers becomes unavailable. If a master fails to advertise before the backup server, the backup server will pick up the shared IP address until the master becomes available again. [NOTE] ==== If the original master server becomes available again, `hostc.example.org` will not release the virtual IP address back to it automatically. For this to happen, preemption has to be enabled. The feature is disabled by default, it is controlled via the man:sysctl[8] variable `net.inet.carp.preempt`. The administrator can force the backup server to return the IP address to the master: [source,shell] .... # ifconfig em0 vhid 1 state backup .... ==== Once the configuration is complete, either restart networking or reboot each system. High availability is now enabled. CARP functionality can be controlled via several man:sysctl[8] variables documented in the man:carp[4] manual pages. Other actions can be triggered from CARP events by using man:devd[8]. [[carp-9x]] === 使用 CARP 於 FreeBSD 9 及先前版本 The configuration for these versions of FreeBSD is similar to the one described in the previous section, except that a CARP device must first be created and referred to in the configuration. Enable boot-time support for CARP by loading the [.filename]#if_carp.ko# kernel module in [.filename]#/boot/loader.conf#: [.programlisting] .... if_carp_load="YES" .... To load the module now without rebooting: [source,shell] .... # kldload carp .... For users who prefer to use a custom kernel, include the following line in the custom kernel configuration file and compile the kernel as described in crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心]: [.programlisting] .... device carp .... Next, on each host, create a CARP device: [source,shell] .... # ifconfig carp0 create .... Set the hostname, management IP address, the shared IP address, and VHID by adding the required lines to [.filename]#/etc/rc.conf#. Since a virtual CARP device is used instead of an alias, the actual subnet mask of `/24` is used instead of `/32`. Here are the entries for `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_fxp0="inet 192.168.1.3 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 1 pass testpass 192.168.1.50/24" .... On `hostb.example.org`: [.programlisting] .... hostname="hostb.example.org" ifconfig_fxp0="inet 192.168.1.4 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 2 pass testpass 192.168.1.51/24" .... The third machine, `hostc.example.org`, is configured to handle failover from either of the master hosts: [.programlisting] .... hostname="hostc.example.org" ifconfig_fxp0="inet 192.168.1.5 netmask 255.255.255.0" cloned_interfaces="carp0 carp1" ifconfig_carp0="vhid 1 advskew 100 pass testpass 192.168.1.50/24" ifconfig_carp1="vhid 2 advskew 100 pass testpass 192.168.1.51/24" .... [NOTE] ==== Preemption is disabled in the [.filename]#GENERIC# FreeBSD kernel. If preemption has been enabled with a custom kernel, `hostc.example.org` may not release the IP address back to the original content server. The administrator can force the backup server to return the IP address to the master with the command: [source,shell] .... # ifconfig carp0 down && ifconfig carp0 up .... This should be done on the [.filename]#carp# interface which corresponds to the correct host. ==== Once the configuration is complete, either restart networking or reboot each system. High availability is now enabled. [[network-vlan]] == VLANs VLANs are a way of virtually dividing up a network into many different subnetworks, also referred to as segmenting. Each segment will have its own broadcast domain and be isolated from other VLANs. 在 FreeBSD 上,要使用 VLANs 必須有網路卡驅動程式的支援,要查看那些驅動程式支援 vlan,請參考 man:vlan[4] 操作手冊。 When configuring a VLAN, a couple pieces of information must be known. First, which network interface? Second, what is the VLAN tag? To configure VLANs at run time, with a NIC of `em0` and a VLAN tag of `5` the command would look like this: [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 inet 192.168.20.20/24 .... [NOTE] ==== See how the interface name includes the NIC driver name and the VLAN tag, separated by a period? This is a best practice to make maintaining the VLAN configuration easy when many VLANs are present on a machine. ==== To configure VLANs at boot time, [.filename]#/etc/rc.conf# must be updated. To duplicate the configuration above, the following will need to be added: [.programlisting] .... vlans_em0="5" ifconfig_em0_5="inet 192.168.20.20/24" .... Additional VLANs may be added, by simply adding the tag to the `vlans__em0__` field and adding an additional line configuring the network on that VLAN tag's interface. It is useful to assign a symbolic name to an interface so that when the associated hardware is changed, only a few configuration variables need to be updated. For example, security cameras need to be run over VLAN 1 on `em0`. Later, if the `em0` card is replaced with a card that uses the man:ixgb[4] driver, all references to `em0.1` will not have to change to `ixgb0.1`. To configure VLAN `5`, on the NIC `em0`, assign the interface name `cameras`, and assign the interface an IP address of `_192.168.20.20_` with a `24`-bit prefix, use this command: [source,shell] .... # ifconfig em0.5 create vlan 5 vlandev em0 name cameras inet 192.168.20.20/24 .... For an interface named `video`, use the following: [source,shell] .... # ifconfig video.5 create vlan 5 vlandev video name cameras inet 192.168.20.20/24 .... To apply the changes at boot time, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... vlans_video="camera" create_args_camera="vlan 5" ifconfig_camera="inet 192.168.20.20/24" .... diff --git a/documentation/content/zh-tw/books/handbook/network-servers/_index.adoc b/documentation/content/zh-tw/books/handbook/network-servers/_index.adoc index 8affaefef2..a92d7276b5 100644 --- a/documentation/content/zh-tw/books/handbook/network-servers/_index.adoc +++ b/documentation/content/zh-tw/books/handbook/network-servers/_index.adoc @@ -1,2466 +1,2466 @@ --- title: 章 29. 網路伺服器 part: 部 IV. 網路通訊 prev: books/handbook/mail next: books/handbook/firewalls showBookMenu: true weight: 34 path: "/books/handbook/" --- [[network-servers]] = 網路伺服器 :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 29 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/network-servers/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[network-servers-synopsis]] == 概述 本章節涵蓋一些在 UNIX(TM) 系統常用的網路服務,包含安裝、設定、測試及維護各種不同類型的網路服務。本章會提供範例設定檔以供參考。 讀完本章,您將了解: * 如何管理 inetd Daemon。 * 如何設定網路檔案系統 (Network File System, NFS)。 * 如何設定網路資訊伺服器 (Network Information Server, NIS) 來集中管理及共用使用者帳號。 * 如何設定 FreeBSD 成為 LDAP 伺服器或客戶端 * 如何設定使用 DHCP 自動網路設定。 * 如何設定網域名稱伺服器 (Domain Name Server, DNS)。 * 如何設定 ApacheHTTP 伺服器。 * 如何設定檔案傳輸協定 (File Transfer Protocol, FTP) 伺服器。 * 如何設定 Samba 檔案與列印伺服器供 Windows(TM) 客戶端使用。 * 如何同步時間與日期,並使用網路時間協定 (Network Time Protocol, NTP) 設定時間伺服器。 * 如何設定 iSCSI。 本章假設您有以下基礎知識: * [.filename]#/etc/rc# Script。 * 網路術語。 * 安裝其他第三方軟體 (crossref:ports[ports,安裝應用程式:套件與 Port])。 [[network-inetd]] == inetd 超級伺服器 The man:inetd[8] daemon is sometimes referred to as a Super-Server because it manages connections for many services. Instead of starting multiple applications, only the inetd service needs to be started. When a connection is received for a service that is managed by inetd, it determines which program the connection is destined for, spawns a process for that program, and delegates the program a socket. Using inetd for services that are not heavily used can reduce system load, when compared to running each daemon individually in stand-alone mode. Primarily, inetd is used to spawn other daemons, but several trivial protocols are handled internally, such as chargen, auth, time, echo, discard, and daytime. This section covers the basics of configuring inetd. [[network-inetd-conf]] === 設定檔 Configuration of inetd is done by editing [.filename]#/etc/inetd.conf#. Each line of this configuration file represents an application which can be started by inetd. By default, every line starts with a comment (`#`), meaning that inetd is not listening for any applications. To configure inetd to listen for an application's connections, remove the `#` at the beginning of the line for that application. After saving your edits, configure inetd to start at system boot by editing [.filename]#/etc/rc.conf#: [.programlisting] .... inetd_enable="YES" .... To start inetd now, so that it listens for the service you configured, type: [source,shell] .... # service inetd start .... Once inetd is started, it needs to be notified whenever a modification is made to [.filename]#/etc/inetd.conf#: [[network-inetd-reread]] .重新庫入 inetd 設定檔 [example] ==== [source,shell] .... # service inetd reload .... ==== Typically, the default entry for an application does not need to be edited beyond removing the `#`. In some situations, it may be appropriate to edit the default entry. As an example, this is the default entry for man:ftpd[8] over IPv4: [.programlisting] .... ftp stream tcp nowait root /usr/libexec/ftpd ftpd -l .... The seven columns in an entry are as follows: [.programlisting] .... service-name socket-type protocol {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]] user[:group][/login-class] server-program server-program-arguments .... where: service-name:: The service name of the daemon to start. It must correspond to a service listed in [.filename]#/etc/services#. This determines which port inetd listens on for incoming connections to that service. When using a custom service, it must first be added to [.filename]#/etc/services#. socket-type:: Either `stream`, `dgram`, `raw`, or `seqpacket`. Use `stream` for TCP connections and `dgram` for UDP services. protocol:: Use one of the following protocol names: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Protocol Name | Explanation |tcp or tcp4 |TCP IPv4 |udp or udp4 |UDP IPv4 |tcp6 |TCP IPv6 |udp6 |UDP IPv6 |tcp46 |Both TCP IPv4 and IPv6 |udp46 |Both UDP IPv4 and IPv6 |=== {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]]:: In this field, `wait` or `nowait` must be specified. `max-child`, `max-connections-per-ip-per-minute` and `max-child-per-ip` are optional. + `wait|nowait` indicates whether or not the service is able to handle its own socket. `dgram` socket types must use `wait` while `stream` daemons, which are usually multi-threaded, should use `nowait`. `wait` usually hands off multiple sockets to a single daemon, while `nowait` spawns a child daemon for each new socket. + The maximum number of child daemons inetd may spawn is set by `max-child`. For example, to limit ten instances of the daemon, place a `/10` after `nowait`. Specifying `/0` allows an unlimited number of children. + `max-connections-per-ip-per-minute` limits the number of connections from any particular IP address per minute. Once the limit is reached, further connections from this IP address will be dropped until the end of the minute. For example, a value of `/10` would limit any particular IP address to ten connection attempts per minute. `max-child-per-ip` limits the number of child processes that can be started on behalf on any single IP address at any moment. These options can limit excessive resource consumption and help to prevent Denial of Service attacks. + An example can be seen in the default settings for man:fingerd[8]: + [.programlisting] .... finger stream tcp nowait/3/10 nobody /usr/libexec/fingerd fingerd -k -s .... user:: The username the daemon will run as. Daemons typically run as `root`, `daemon`, or `nobody`. server-program:: The full path to the daemon. If the daemon is a service provided by inetd internally, use `internal`. server-program-arguments:: Used to specify any command arguments to be passed to the daemon on invocation. If the daemon is an internal service, use `internal`. [[network-inetd-cmdline]] === 指令列選項 Like most server daemons, inetd has a number of options that can be used to modify its behavior. By default, inetd is started with `-wW -C 60`. These options enable TCP wrappers for all services, including internal services, and prevent any IP address from requesting any service more than 60 times per minute. To change the default options which are passed to inetd, add an entry for `inetd_flags` in [.filename]#/etc/rc.conf#. If inetd is already running, restart it with `service inetd restart`. The available rate limiting options are: -c maximum:: Specify the default maximum number of simultaneous invocations of each service, where the default is unlimited. May be overridden on a per-service basis by using `max-child` in [.filename]#/etc/inetd.conf#. -C rate:: Specify the default maximum number of times a service can be invoked from a single IP address per minute. May be overridden on a per-service basis by using `max-connections-per-ip-per-minute` in [.filename]#/etc/inetd.conf#. -R rate:: Specify the maximum number of times a service can be invoked in one minute, where the default is `256`. A rate of `0` allows an unlimited number. -s maximum:: Specify the maximum number of times a service can be invoked from a single IP address at any one time, where the default is unlimited. May be overridden on a per-service basis by using `max-child-per-ip` in [.filename]#/etc/inetd.conf#. Additional options are available. Refer to man:inetd[8] for the full list of options. [[network-inetd-security]] === 安全注意事項 Many of the daemons which can be managed by inetd are not security-conscious. Some daemons, such as fingerd, can provide information that may be useful to an attacker. Only enable the services which are needed and monitor the system for excessive connection attempts. `max-connections-per-ip-per-minute`, `max-child` and `max-child-per-ip` can be used to limit such attacks. By default, TCP wrappers is enabled. Consult man:hosts_access[5] for more information on placing TCP restrictions on various inetd invoked daemons. [[network-nfs]] == 網路檔案系統 (NFS) FreeBSD supports the Network File System (NFS), which allows a server to share directories and files with clients over a network. With NFS, users and programs can access files on remote systems as if they were stored locally. NFS has many practical uses. Some of the more common uses include: * Data that would otherwise be duplicated on each client can be kept in a single location and accessed by clients on the network. * Several clients may need access to the [.filename]#/usr/ports/distfiles# directory. Sharing that directory allows for quick access to the source files without having to download them to each client. * On large networks, it is often more convenient to configure a central NFS server on which all user home directories are stored. Users can log into a client anywhere on the network and have access to their home directories. * Administration of NFS exports is simplified. For example, there is only one file system where security or backup policies must be set. * Removable media storage devices can be used by other machines on the network. This reduces the number of devices throughout the network and provides a centralized location to manage their security. It is often more convenient to install software on multiple machines from a centralized installation media. NFS consists of a server and one or more clients. The client remotely accesses the data that is stored on the server machine. In order for this to function properly, a few processes have to be configured and running. These daemons must be running on the server: [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Daemon | 說明 |nfsd |The NFS daemon which services requests from NFS clients. |mountd |The NFS mount daemon which carries out requests received from nfsd. |rpcbind | This daemon allows NFS clients to discover which port the NFS server is using. |=== Running man:nfsiod[8] on the client can improve performance, but is not required. [[network-configuring-nfs]] === 設定伺服器 The file systems which the NFS server will share are specified in [.filename]#/etc/exports#. Each line in this file specifies a file system to be exported, which clients have access to that file system, and any access options. When adding entries to this file, each exported file system, its properties, and allowed hosts must occur on a single line. If no clients are listed in the entry, then any client on the network can mount that file system. The following [.filename]#/etc/exports# entries demonstrate how to export file systems. The examples can be modified to match the file systems and client names on the reader's network. There are many options that can be used in this file, but only a few will be mentioned here. See man:exports[5] for the full list of options. This example shows how to export [.filename]#/cdrom# to three hosts named _alpha_, _bravo_, and _charlie_: [.programlisting] .... /cdrom -ro alpha bravo charlie .... The `-ro` flag makes the file system read-only, preventing clients from making any changes to the exported file system. This example assumes that the host names are either in DNS or in [.filename]#/etc/hosts#. Refer to man:hosts[5] if the network does not have a DNS server. The next example exports [.filename]#/home# to three clients by IP address. This can be useful for networks without DNS or [.filename]#/etc/hosts# entries. The `-alldirs` flag allows subdirectories to be mount points. In other words, it will not automatically mount the subdirectories, but will permit the client to mount the directories that are required as needed. [.programlisting] .... /usr/home -alldirs 10.0.0.2 10.0.0.3 10.0.0.4 .... This next example exports [.filename]#/a# so that two clients from different domains may access that file system. The `-maproot=root` allows `root` on the remote system to write data on the exported file system as `root`. If `-maproot=root` is not specified, the client's `root` user will be mapped to the server's `nobody` account and will be subject to the access limitations defined for `nobody`. [.programlisting] .... /a -maproot=root host.example.com box.example.org .... A client can only be specified once per file system. For example, if [.filename]#/usr# is a single file system, these entries would be invalid as both entries specify the same host: [.programlisting] .... # Invalid when /usr is one file system /usr/src client /usr/ports client .... The correct format for this situation is to use one entry: [.programlisting] .... /usr/src /usr/ports client .... The following is an example of a valid export list, where [.filename]#/usr# and [.filename]#/exports# are local file systems: [.programlisting] .... # Export src and ports to client01 and client02, but only # client01 has root privileges on it /usr/src /usr/ports -maproot=root client01 /usr/src /usr/ports client02 # The client machines have root and can mount anywhere # on /exports. Anyone in the world can mount /exports/obj read-only /exports -alldirs -maproot=root client01 client02 /exports/obj -ro .... To enable the processes required by the NFS server at boot time, add these options to [.filename]#/etc/rc.conf#: [.programlisting] .... rpcbind_enable="YES" nfs_server_enable="YES" mountd_flags="-r" .... The server can be started now by running this command: [source,shell] .... # service nfsd start .... Whenever the NFS server is started, mountd also starts automatically. However, mountd only reads [.filename]#/etc/exports# when it is started. To make subsequent [.filename]#/etc/exports# edits take effect immediately, force mountd to reread it: [source,shell] .... # service mountd reload .... === 設定客戶端 To enable NFS clients, set this option in each client's [.filename]#/etc/rc.conf#: [.programlisting] .... nfs_client_enable="YES" .... Then, run this command on each NFS client: [source,shell] .... # service nfsclient start .... The client now has everything it needs to mount a remote file system. In these examples, the server's name is `server` and the client's name is `client`. To mount [.filename]#/home# on `server` to the [.filename]#/mnt# mount point on `client`: [source,shell] .... # mount server:/home /mnt .... The files and directories in [.filename]#/home# will now be available on `client`, in the [.filename]#/mnt# directory. To mount a remote file system each time the client boots, add it to [.filename]#/etc/fstab#: [.programlisting] .... server:/home /mnt nfs rw 0 0 .... Refer to man:fstab[5] for a description of all available options. === 鎖定 Some applications require file locking to operate correctly. To enable locking, add these lines to [.filename]#/etc/rc.conf# on both the client and server: [.programlisting] .... rpc_lockd_enable="YES" rpc_statd_enable="YES" .... Then start the applications: [source,shell] .... # service lockd start # service statd start .... If locking is not required on the server, the NFS client can be configured to lock locally by including `-L` when running mount. Refer to man:mount_nfs[8] for further details. [[network-amd]] === 使用 man:amd[8] 自動掛載 The automatic mounter daemon, amd, automatically mounts a remote file system whenever a file or directory within that file system is accessed. File systems that are inactive for a period of time will be automatically unmounted by amd. This daemon provides an alternative to modifying [.filename]#/etc/fstab# to list every client. It operates by attaching itself as an NFS server to the [.filename]#/host# and [.filename]#/net# directories. When a file is accessed within one of these directories, amd looks up the corresponding remote mount and automatically mounts it. [.filename]#/net# is used to mount an exported file system from an IP address while [.filename]#/host# is used to mount an export from a remote hostname. For instance, an attempt to access a file within [.filename]#/host/foobar/usr# would tell amd to mount the [.filename]#/usr# export on the host `foobar`. .使用 amd 掛載 Export [example] ==== In this example, `showmount -e` shows the exported file systems that can be mounted from the NFS server, `foobar`: [source,shell] .... % showmount -e foobar Exports list on foobar: /usr 10.10.10.0 /a 10.10.10.0 % cd /host/foobar/usr .... ==== The output from `showmount` shows [.filename]#/usr# as an export. When changing directories to [.filename]#/host/foobar/usr#, amd intercepts the request and attempts to resolve the hostname `foobar`. If successful, amd automatically mounts the desired export. To enable amd at boot time, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... amd_enable="YES" .... To start amd now: [source,shell] .... # service amd start .... Custom flags can be passed to amd from the `amd_flags` environment variable. By default, `amd_flags` is set to: [.programlisting] .... amd_flags="-a /.amd_mnt -l syslog /host /etc/amd.map /net /etc/amd.map" .... The default options with which exports are mounted are defined in [.filename]#/etc/amd.map#. Some of the more advanced features of amd are defined in [.filename]#/etc/amd.conf#. Consult man:amd[8] and man:amd.conf[5] for more information. [[network-autofs]] === 使用 man:autofs[5] 自動掛載 [NOTE] ==== The man:autofs[5] automount facility is supported starting with FreeBSD 10.1-RELEASE. To use the automounter functionality in older versions of FreeBSD, use man:amd[8] instead. This chapter only describes the man:autofs[5] automounter. ==== The man:autofs[5] facility is a common name for several components that, together, allow for automatic mounting of remote and local filesystems whenever a file or directory within that file system is accessed. It consists of the kernel component, man:autofs[5], and several userspace applications: man:automount[8], man:automountd[8] and man:autounmountd[8]. It serves as an alternative for man:amd[8] from previous FreeBSD releases. Amd is still provided for backward compatibility purposes, as the two use different map format; the one used by autofs is the same as with other SVR4 automounters, such as the ones in Solaris, MacOS X, and Linux. The man:autofs[5] virtual filesystem is mounted on specified mountpoints by man:automount[8], usually invoked during boot. Whenever a process attempts to access file within the man:autofs[5] mountpoint, the kernel will notify man:automountd[8] daemon and pause the triggering process. The man:automountd[8] daemon will handle kernel requests by finding the proper map and mounting the filesystem according to it, then signal the kernel to release blocked process. The man:autounmountd[8] daemon automatically unmounts automounted filesystems after some time, unless they are still being used. The primary autofs configuration file is [.filename]#/etc/auto_master#. It assigns individual maps to top-level mounts. For an explanation of [.filename]#auto_master# and the map syntax, refer to man:auto_master[5]. There is a special automounter map mounted on [.filename]#/net#. When a file is accessed within this directory, man:autofs[5] looks up the corresponding remote mount and automatically mounts it. For instance, an attempt to access a file within [.filename]#/net/foobar/usr# would tell man:automountd[8] to mount the [.filename]#/usr# export from the host `foobar`. .使用 man:autofs[5] 掛載 Export [example] ==== In this example, `showmount -e` shows the exported file systems that can be mounted from the NFS server, `foobar`: [source,shell] .... % showmount -e foobar Exports list on foobar: /usr 10.10.10.0 /a 10.10.10.0 % cd /net/foobar/usr .... ==== The output from `showmount` shows [.filename]#/usr# as an export. When changing directories to [.filename]#/host/foobar/usr#, man:automountd[8] intercepts the request and attempts to resolve the hostname `foobar`. If successful, man:automountd[8] automatically mounts the source export. To enable man:autofs[5] at boot time, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... autofs_enable="YES" .... Then man:autofs[5] can be started by running: [source,shell] .... # service automount start # service automountd start # service autounmountd start .... The man:autofs[5] map format is the same as in other operating systems. Information about this format from other sources can be useful, like the http://web.archive.org/web/20160813071113/http://images.apple.com/business/docs/Autofs.pdf[Mac OS X document]. Consult the man:automount[8], man:automountd[8], man:autounmountd[8], and man:auto_master[5] manual pages for more information. [[network-nis]] == 網路資訊系統 (NIS) Network Information System (NIS) is designed to centralize administration of UNIX(TM)-like systems such as Solaris(TM), HP-UX, AIX(TM), Linux, NetBSD, OpenBSD, and FreeBSD. NIS was originally known as Yellow Pages but the name was changed due to trademark issues. This is the reason why NIS commands begin with `yp`. NIS is a Remote Procedure Call (RPC)-based client/server system that allows a group of machines within an NIS domain to share a common set of configuration files. This permits a system administrator to set up NIS client systems with only minimal configuration data and to add, remove, or modify configuration data from a single location. FreeBSD uses version 2 of the NIS protocol. === NIS 術語與程序 Table 28.1 summarizes the terms and important processes used by NIS: .NIS 術語 [cols="1,1", frame="none", options="header"] |=== | 術語 | 說明 |NIS domain name |NIS servers and clients share an NIS domain name. Typically, this name does not have anything to do with DNS. |man:rpcbind[8] |This service enables RPC and must be running in order to run an NIS server or act as an NIS client. |man:ypbind[8] |This service binds an NIS client to its NIS server. It will take the NIS domain name and use RPC to connect to the server. It is the core of client/server communication in an NIS environment. If this service is not running on a client machine, it will not be able to access the NIS server. |man:ypserv[8] |This is the process for the NIS server. If this service stops running, the server will no longer be able to respond to NIS requests so hopefully, there is a slave server to take over. Some non-FreeBSD clients will not try to reconnect using a slave server and the ypbind process may need to be restarted on these clients. |man:rpc.yppasswdd[8] |This process only runs on NIS master servers. This daemon allows NIS clients to change their NIS passwords. If this daemon is not running, users will have to login to the NIS master server and change their passwords there. |=== === 主機類型 There are three types of hosts in an NIS environment: * NIS master server + This server acts as a central repository for host configuration information and maintains the authoritative copy of the files used by all of the NIS clients. The [.filename]#passwd#, [.filename]#group#, and other various files used by NIS clients are stored on the master server. While it is possible for one machine to be an NIS master server for more than one NIS domain, this type of configuration will not be covered in this chapter as it assumes a relatively small-scale NIS environment. * NIS slave servers + NIS slave servers maintain copies of the NIS master's data files in order to provide redundancy. Slave servers also help to balance the load of the master server as NIS clients always attach to the NIS server which responds first. * NIS clients + NIS clients authenticate against the NIS server during log on. Information in many files can be shared using NIS. The [.filename]#master.passwd#, [.filename]#group#, and [.filename]#hosts# files are commonly shared via NIS. Whenever a process on a client needs information that would normally be found in these files locally, it makes a query to the NIS server that it is bound to instead. === 規劃注意事項 This section describes a sample NIS environment which consists of 15 FreeBSD machines with no centralized point of administration. Each machine has its own [.filename]#/etc/passwd# and [.filename]#/etc/master.passwd#. These files are kept in sync with each other only through manual intervention. Currently, when a user is added to the lab, the process must be repeated on all 15 machines. The configuration of the lab will be as follows: [.informaltable] [cols="1,1,1", frame="none", options="header"] |=== | Machine name | IP 位址 | Machine role |`ellington` |`10.0.0.2` |NIS master |`coltrane` |`10.0.0.3` |NIS slave |`basie` |`10.0.0.4` |Faculty workstation |`bird` |`10.0.0.5` |Client machine |`cli[1-11]` |`10.0.0.[6-17]` |Other client machines |=== If this is the first time an NIS scheme is being developed, it should be thoroughly planned ahead of time. Regardless of network size, several decisions need to be made as part of the planning process. ==== 選擇 NIS 網域名稱 When a client broadcasts its requests for info, it includes the name of the NIS domain that it is part of. This is how multiple servers on one network can tell which server should answer which request. Think of the NIS domain name as the name for a group of hosts. Some organizations choose to use their Internet domain name for their NIS domain name. This is not recommended as it can cause confusion when trying to debug network problems. The NIS domain name should be unique within the network and it is helpful if it describes the group of machines it represents. For example, the Art department at Acme Inc. might be in the "acme-art"NIS domain. This example will use the domain name `test-domain`. However, some non-FreeBSD operating systems require the NIS domain name to be the same as the Internet domain name. If one or more machines on the network have this restriction, the Internet domain name _must_ be used as the NIS domain name. ==== 實體伺服器需求 There are several things to keep in mind when choosing a machine to use as a NIS server. Since NIS clients depend upon the availability of the server, choose a machine that is not rebooted frequently. The NIS server should ideally be a stand alone machine whose sole purpose is to be an NIS server. If the network is not heavily used, it is acceptable to put the NIS server on a machine running other services. However, if the NIS server becomes unavailable, it will adversely affect all NIS clients. === 設定 NIS Master 伺服器 The canonical copies of all NIS files are stored on the master server. The databases used to store the information are called NIS maps. In FreeBSD, these maps are stored in [.filename]#/var/yp/[domainname]# where [.filename]#[domainname]# is the name of the NIS domain. Since multiple domains are supported, it is possible to have several directories, one for each domain. Each domain will have its own independent set of maps. NIS master and slave servers handle all NIS requests through man:ypserv[8]. This daemon is responsible for receiving incoming requests from NIS clients, translating the requested domain and map name to a path to the corresponding database file, and transmitting data from the database back to the client. Setting up a master NIS server can be relatively straight forward, depending on environmental needs. Since FreeBSD provides built-in NIS support, it only needs to be enabled by adding the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... nisdomainname="test-domain" <.> nis_server_enable="YES" <.> nis_yppasswdd_enable="YES" <.> .... <.> This line sets the NIS domain name to `test-domain`. <.> This automates the start up of the NIS server processes when the system boots. <.> This enables the man:rpc.yppasswdd[8] daemon so that users can change their NIS password from a client machine. Care must be taken in a multi-server domain where the server machines are also NIS clients. It is generally a good idea to force the servers to bind to themselves rather than allowing them to broadcast bind requests and possibly become bound to each other. Strange failure modes can result if one server goes down and others are dependent upon it. Eventually, all the clients will time out and attempt to bind to other servers, but the delay involved can be considerable and the failure mode is still present since the servers might bind to each other all over again. A server that is also a client can be forced to bind to a particular server by adding these additional lines to [.filename]#/etc/rc.conf#: [.programlisting] .... nis_client_enable="YES" # run client stuff as well nis_client_flags="-S NIS domain,server" .... After saving the edits, type `/etc/netstart` to restart the network and apply the values defined in [.filename]#/etc/rc.conf#. Before initializing the NIS maps, start man:ypserv[8]: [source,shell] .... # service ypserv start .... ==== 初始化 NIS 對應表 NIS maps are generated from the configuration files in [.filename]#/etc# on the NIS master, with one exception: [.filename]#/etc/master.passwd#. This is to prevent the propagation of passwords to all the servers in the NIS domain. Therefore, before the NIS maps are initialized, configure the primary password files: [source,shell] .... # cp /etc/master.passwd /var/yp/master.passwd # cd /var/yp # vi master.passwd .... It is advisable to remove all entries for system accounts as well as any user accounts that do not need to be propagated to the NIS clients, such as the `root` and any other administrative accounts. [NOTE] ==== Ensure that the [.filename]#/var/yp/master.passwd# is neither group or world readable by setting its permissions to `600`. ==== After completing this task, initialize the NIS maps. FreeBSD includes the man:ypinit[8] script to do this. When generating maps for the master server, include `-m` and specify the NIS domain name: [source,shell] .... ellington# ypinit -m test-domain Server Type: MASTER Domain: test-domain Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. At this point, we have to construct a list of this domains YP servers. rod.darktech.org is already known as master server. Please continue to add any slave servers, one per line. When you are done with the list, type a . master server : ellington next host to add: coltrane next host to add: ^D The current list of NIS servers looks like this: ellington coltrane Is this correct? [y/n: y] y [..output from map generation..] NIS Map update completed. ellington has been setup as an YP master server without any errors. .... This will create [.filename]#/var/yp/Makefile# from [.filename]#/var/yp/Makefile.dist#. By default, this file assumes that the environment has a single NIS server with only FreeBSD clients. Since `test-domain` has a slave server, edit this line in [.filename]#/var/yp/Makefile# so that it begins with a comment (`#`): [.programlisting] .... NOPUSH = "True" .... ==== 新增使用者 Every time a new user is created, the user account must be added to the master NIS server and the NIS maps rebuilt. Until this occurs, the new user will not be able to login anywhere except on the NIS master. For example, to add the new user `jsmith` to the `test-domain` domain, run these commands on the master server: [source,shell] .... # pw useradd jsmith # cd /var/yp # make test-domain .... The user could also be added using `adduser jsmith` instead of `pw useradd smith`. === 設定 NIS Slave 伺服器 To set up an NIS slave server, log on to the slave server and edit [.filename]#/etc/rc.conf# as for the master server. Do not generate any NIS maps, as these already exist on the master server. When running `ypinit` on the slave server, use `-s` (for slave) instead of `-m` (for master). This option requires the name of the NIS master in addition to the domain name, as seen in this example: [source,shell] .... coltrane# ypinit -s ellington test-domain Server Type: SLAVE Domain: test-domain Master: ellington Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. There will be no further questions. The remainder of the procedure should take a few minutes, to copy the databases from ellington. Transferring netgroup... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byuser... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byhost... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring group.bygid... ypxfr: Exiting: Map successfully transferred Transferring group.byname... ypxfr: Exiting: Map successfully transferred Transferring services.byname... ypxfr: Exiting: Map successfully transferred Transferring rpc.bynumber... ypxfr: Exiting: Map successfully transferred Transferring rpc.byname... ypxfr: Exiting: Map successfully transferred Transferring protocols.byname... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byaddr... ypxfr: Exiting: Map successfully transferred Transferring netid.byname... ypxfr: Exiting: Map successfully transferred Transferring hosts.byaddr... ypxfr: Exiting: Map successfully transferred Transferring protocols.bynumber... ypxfr: Exiting: Map successfully transferred Transferring ypservers... ypxfr: Exiting: Map successfully transferred Transferring hosts.byname... ypxfr: Exiting: Map successfully transferred coltrane has been setup as an YP slave server without any errors. Remember to update map ypservers on ellington. .... This will generate a directory on the slave server called [.filename]#/var/yp/test-domain# which contains copies of the NIS master server's maps. Adding these [.filename]#/etc/crontab# entries on each slave server will force the slaves to sync their maps with the maps on the master server: [.programlisting] .... 20 * * * * root /usr/libexec/ypxfr passwd.byname 21 * * * * root /usr/libexec/ypxfr passwd.byuid .... These entries are not mandatory because the master server automatically attempts to push any map changes to its slaves. However, since clients may depend upon the slave server to provide correct password information, it is recommended to force frequent password map updates. This is especially important on busy networks where map updates might not always complete. To finish the configuration, run `/etc/netstart` on the slave server in order to start the NIS services. === 設定 NIS 客戶端 An NIS client binds to an NIS server using man:ypbind[8]. This daemon broadcasts RPC requests on the local network. These requests specify the domain name configured on the client. If an NIS server in the same domain receives one of the broadcasts, it will respond to ypbind, which will record the server's address. If there are several servers available, the client will use the address of the first server to respond and will direct all of its NIS requests to that server. The client will automatically ping the server on a regular basis to make sure it is still available. If it fails to receive a reply within a reasonable amount of time, ypbind will mark the domain as unbound and begin broadcasting again in the hopes of locating another server. To configure a FreeBSD machine to be an NIS client: [.procedure] ==== . Edit [.filename]#/etc/rc.conf# and add the following lines in order to set the NIS domain name and start man:ypbind[8] during network startup: + [.programlisting] .... nisdomainname="test-domain" nis_client_enable="YES" .... + . To import all possible password entries from the NIS server, use `vipw` to remove all user accounts except one from [.filename]#/etc/master.passwd#. When removing the accounts, keep in mind that at least one local account should remain and this account should be a member of `wheel`. If there is a problem with NIS, this local account can be used to log in remotely, become the superuser, and fix the problem. Before saving the edits, add the following line to the end of the file: + [.programlisting] .... +::::::::: .... + This line configures the client to provide anyone with a valid account in the NIS server's password maps an account on the client. There are many ways to configure the NIS client by modifying this line. One method is described in <>. For more detailed reading, refer to the book `Managing NFS and NIS`, published by O'Reilly Media. + . To import all possible group entries from the NIS server, add this line to [.filename]#/etc/group#: + [.programlisting] .... +:*:: .... ==== To start the NIS client immediately, execute the following commands as the superuser: [source,shell] .... # /etc/netstart # service ypbind start .... After completing these steps, running `ypcat passwd` on the client should show the server's [.filename]#passwd# map. === NIS 安全性 Since RPC is a broadcast-based service, any system running ypbind within the same domain can retrieve the contents of the NIS maps. To prevent unauthorized transactions, man:ypserv[8] supports a feature called "securenets" which can be used to restrict access to a given set of hosts. By default, this information is stored in [.filename]#/var/yp/securenets#, unless man:ypserv[8] is started with `-p` and an alternate path. This file contains entries that consist of a network specification and a network mask separated by white space. Lines starting with `#` are considered to be comments. A sample [.filename]##securenets## might look like this: [.programlisting] .... # allow connections from local host -- mandatory 127.0.0.1 255.255.255.255 # allow connections from any host # on the 192.168.128.0 network 192.168.128.0 255.255.255.0 # allow connections from any host # between 10.0.0.0 to 10.0.15.255 # this includes the machines in the testlab 10.0.0.0 255.255.240.0 .... If man:ypserv[8] receives a request from an address that matches one of these rules, it will process the request normally. If the address fails to match a rule, the request will be ignored and a warning message will be logged. If the [.filename]#securenets# does not exist, `ypserv` will allow connections from any host. crossref:security[tcpwrappers,TCP Wrapper] is an alternate mechanism for providing access control instead of [.filename]#securenets#. While either access control mechanism adds some security, they are both vulnerable to "IP spoofing" attacks. All NIS-related traffic should be blocked at the firewall. Servers using [.filename]#securenets# may fail to serve legitimate NIS clients with archaic TCP/IP implementations. Some of these implementations set all host bits to zero when doing broadcasts or fail to observe the subnet mask when calculating the broadcast address. While some of these problems can be fixed by changing the client configuration, other problems may force the retirement of these client systems or the abandonment of [.filename]#securenets#. The use of TCP Wrapper increases the latency of the NIS server. The additional delay may be long enough to cause timeouts in client programs, especially in busy networks with slow NIS servers. If one or more clients suffer from latency, convert those clients into NIS slave servers and force them to bind to themselves. ==== 阻擋部份使用者 In this example, the `basie` system is a faculty workstation within the NIS domain. The [.filename]#passwd# map on the master NIS server contains accounts for both faculty and students. This section demonstrates how to allow faculty logins on this system while refusing student logins. To prevent specified users from logging on to a system, even if they are present in the NIS database, use `vipw` to add `-_username_` with the correct number of colons towards the end of [.filename]#/etc/master.passwd# on the client, where _username_ is the username of a user to bar from logging in. The line with the blocked user must be before the `+` line that allows NIS users. In this example, `bill` is barred from logging on to `basie`: [source,shell] .... basie# cat /etc/master.passwd root:[password]:0:0::0:0:The super-user:/root:/bin/csh toor:[password]:0:0::0:0:The other super-user:/root:/bin/sh daemon:*:1:1::0:0:Owner of many system processes:/root:/usr/sbin/nologin operator:*:2:5::0:0:System &:/:/usr/sbin/nologin bin:*:3:7::0:0:Binaries Commands and Source,,,:/:/usr/sbin/nologin tty:*:4:65533::0:0:Tty Sandbox:/:/usr/sbin/nologin kmem:*:5:65533::0:0:KMem Sandbox:/:/usr/sbin/nologin games:*:7:13::0:0:Games pseudo-user:/usr/games:/usr/sbin/nologin news:*:8:8::0:0:News Subsystem:/:/usr/sbin/nologin man:*:9:9::0:0:Mister Man Pages:/usr/shared/man:/usr/sbin/nologin bind:*:53:53::0:0:Bind Sandbox:/:/usr/sbin/nologin uucp:*:66:66::0:0:UUCP pseudo-user:/var/spool/uucppublic:/usr/libexec/uucp/uucico xten:*:67:67::0:0:X-10 daemon:/usr/local/xten:/usr/sbin/nologin pop:*:68:6::0:0:Post Office Owner:/nonexistent:/usr/sbin/nologin nobody:*:65534:65534::0:0:Unprivileged user:/nonexistent:/usr/sbin/nologin -bill::::::::: +::::::::: basie# .... [[network-netgroups]] === 使用 Netgroups Barring specified users from logging on to individual systems becomes unscaleable on larger networks and quickly loses the main benefit of NIS: _centralized_ administration. Netgroups were developed to handle large, complex networks with hundreds of users and machines. Their use is comparable to UNIX(TM) groups, where the main difference is the lack of a numeric ID and the ability to define a netgroup by including both user accounts and other netgroups. To expand on the example used in this chapter, the NIS domain will be extended to add the users and systems shown in Tables 28.2 and 28.3: .其他使用者 [cols="1,1", frame="none", options="header"] |=== | 使用者名稱 | 說明 |`alpha`, `beta` |IT department employees |`charlie`, `delta` |IT department apprentices |`echo`, `foxtrott`, `golf`, ... |employees |`able`, `baker`, ... |interns |=== .其他系統 [cols="1,1", frame="none", options="header"] |=== | 機器名稱 | 說明 |`war`, `death`, `famine`, `pollution` |Only IT employees are allowed to log onto these servers. |`pride`, `greed`, `envy`, `wrath`, `lust`, `sloth` |All members of the IT department are allowed to login onto these servers. |`one`, `two`, `three`, `four`, ... |Ordinary workstations used by employees. |`trashcan` |A very old machine without any critical data. Even interns are allowed to use this system. |=== When using netgroups to configure this scenario, each user is assigned to one or more netgroups and logins are then allowed or forbidden for all members of the netgroup. When adding a new machine, login restrictions must be defined for all netgroups. When a new user is added, the account must be added to one or more netgroups. If the NIS setup is planned carefully, only one central configuration file needs modification to grant or deny access to machines. The first step is the initialization of the NIS `netgroup` map. In FreeBSD, this map is not created by default. On the NIS master server, use an editor to create a map named [.filename]#/var/yp/netgroup#. This example creates four netgroups to represent IT employees, IT apprentices, employees, and interns: [.programlisting] .... IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) USERS (,echo,test-domain) (,foxtrott,test-domain) \ (,golf,test-domain) INTERNS (,able,test-domain) (,baker,test-domain) .... Each entry configures a netgroup. The first column in an entry is the name of the netgroup. Each set of brackets represents either a group of one or more users or the name of another netgroup. When specifying a user, the three comma-delimited fields inside each group represent: . The name of the host(s) where the other fields representing the user are valid. If a hostname is not specified, the entry is valid on all hosts. . The name of the account that belongs to this netgroup. . The NIS domain for the account. Accounts may be imported from other NIS domains into a netgroup. If a group contains multiple users, separate each user with whitespace. Additionally, each field may contain wildcards. See man:netgroup[5] for details. Netgroup names longer than 8 characters should not be used. The names are case sensitive and using capital letters for netgroup names is an easy way to distinguish between user, machine and netgroup names. Some non-FreeBSD NIS clients cannot handle netgroups containing more than 15 entries. This limit may be circumvented by creating several sub-netgroups with 15 users or fewer and a real netgroup consisting of the sub-netgroups, as seen in this example: [.programlisting] .... BIGGRP1 (,joe1,domain) (,joe2,domain) (,joe3,domain) [...] BIGGRP2 (,joe16,domain) (,joe17,domain) [...] BIGGRP3 (,joe31,domain) (,joe32,domain) BIGGROUP BIGGRP1 BIGGRP2 BIGGRP3 .... Repeat this process if more than 225 (15 times 15) users exist within a single netgroup. To activate and distribute the new NIS map: [source,shell] .... ellington# cd /var/yp ellington# make .... This will generate the three NIS maps [.filename]#netgroup#, [.filename]#netgroup.byhost# and [.filename]#netgroup.byuser#. Use the map key option of man:ypcat[1] to check if the new NIS maps are available: [source,shell] .... ellington% ypcat -k netgroup ellington% ypcat -k netgroup.byhost ellington% ypcat -k netgroup.byuser .... The output of the first command should resemble the contents of [.filename]#/var/yp/netgroup#. The second command only produces output if host-specific netgroups were created. The third command is used to get the list of netgroups for a user. To configure a client, use man:vipw[8] to specify the name of the netgroup. For example, on the server named `war`, replace this line: [.programlisting] .... +::::::::: .... with [.programlisting] .... +@IT_EMP::::::::: .... This specifies that only the users defined in the netgroup `IT_EMP` will be imported into this system's password database and only those users are allowed to login to this system. This configuration also applies to the `~` function of the shell and all routines which convert between user names and numerical user IDs. In other words, `cd ~_user_` will not work, `ls -l` will show the numerical ID instead of the username, and `find . -user joe -print` will fail with the message `No such user`. To fix this, import all user entries without allowing them to login into the servers. This can be achieved by adding an extra line: [.programlisting] .... +:::::::::/usr/sbin/nologin .... This line configures the client to import all entries but to replace the shell in those entries with [.filename]#/usr/sbin/nologin#. Make sure that extra line is placed _after_ `+@IT_EMP:::::::::`. Otherwise, all user accounts imported from NIS will have [.filename]#/usr/sbin/nologin# as their login shell and no one will be able to login to the system. To configure the less important servers, replace the old `+:::::::::` on the servers with these lines: [.programlisting] .... +@IT_EMP::::::::: +@IT_APP::::::::: +:::::::::/usr/sbin/nologin .... The corresponding lines for the workstations would be: [.programlisting] .... +@IT_EMP::::::::: +@USERS::::::::: +:::::::::/usr/sbin/nologin .... NIS supports the creation of netgroups from other netgroups which can be useful if the policy regarding user access changes. One possibility is the creation of role-based netgroups. For example, one might create a netgroup called `BIGSRV` to define the login restrictions for the important servers, another netgroup called `SMALLSRV` for the less important servers, and a third netgroup called `USERBOX` for the workstations. Each of these netgroups contains the netgroups that are allowed to login onto these machines. The new entries for the NIS `netgroup` map would look like this: [.programlisting] .... BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS .... This method of defining login restrictions works reasonably well when it is possible to define groups of machines with identical restrictions. Unfortunately, this is the exception and not the rule. Most of the time, the ability to define login restrictions on a per-machine basis is required. Machine-specific netgroup definitions are another possibility to deal with the policy changes. In this scenario, the [.filename]#/etc/master.passwd# of each system contains two lines starting with "+". The first line adds a netgroup with the accounts allowed to login onto this machine and the second line adds all other accounts with [.filename]#/usr/sbin/nologin# as shell. It is recommended to use the "ALL-CAPS" version of the hostname as the name of the netgroup: [.programlisting] .... +@BOXNAME::::::::: +:::::::::/usr/sbin/nologin .... Once this task is completed on all the machines, there is no longer a need to modify the local versions of [.filename]#/etc/master.passwd# ever again. All further changes can be handled by modifying the NIS map. Here is an example of a possible `netgroup` map for this scenario: [.programlisting] .... # Define groups of users first IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) DEPT1 (,echo,test-domain) (,foxtrott,test-domain) DEPT2 (,golf,test-domain) (,hotel,test-domain) DEPT3 (,india,test-domain) (,juliet,test-domain) ITINTERN (,kilo,test-domain) (,lima,test-domain) D_INTERNS (,able,test-domain) (,baker,test-domain) # # Now, define some groups based on roles USERS DEPT1 DEPT2 DEPT3 BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS # # And a groups for a special tasks # Allow echo and golf to access our anti-virus-machine SECURITY IT_EMP (,echo,test-domain) (,golf,test-domain) # # machine-based netgroups # Our main servers WAR BIGSRV FAMINE BIGSRV # User india needs access to this server POLLUTION BIGSRV (,india,test-domain) # # This one is really important and needs more access restrictions DEATH IT_EMP # # The anti-virus-machine mentioned above ONE SECURITY # # Restrict a machine to a single user TWO (,hotel,test-domain) # [...more groups to follow] .... It may not always be advisable to use machine-based netgroups. When deploying a couple of dozen or hundreds of systems, role-based netgroups instead of machine-based netgroups may be used to keep the size of the NIS map within reasonable limits. === 密碼格式 NIS requires that all hosts within an NIS domain use the same format for encrypting passwords. If users have trouble authenticating on an NIS client, it may be due to a differing password format. In a heterogeneous network, the format must be supported by all operating systems, where DES is the lowest common standard. To check which format a server or client is using, look at this section of [.filename]#/etc/login.conf#: [.programlisting] .... default:\ :passwd_format=des:\ :copyright=/etc/COPYRIGHT:\ [Further entries elided] .... In this example, the system is using the DES format. Other possible values are `blf` for Blowfish and `md5` for MD5 encrypted passwords. If the format on a host needs to be edited to match the one being used in the NIS domain, the login capability database must be rebuilt after saving the change: [source,shell] .... # cap_mkdb /etc/login.conf .... [NOTE] ==== The format of passwords for existing user accounts will not be updated until each user changes their password _after_ the login capability database is rebuilt. ==== [[network-ldap]] == 輕量級目錄存取協定 (LDAP) 輕量級目錄存取協定 (Lightweight Directory Access Protocol, LDAP) 是一個利用分散式目錄資訊服務來做到存取、修改與認証物件的應用層通訊協定,可以想像成是一本可以儲存數個階層、同質資訊的電話簿或記錄簿。它用在 Active Directory 及 OpenLDAP 網路,允許使用者利用一個帳號來存取數個階層的內部資訊,例如:電子郵件認証、取得員工聯絡資訊及內部網站的認証皆可使用 LDAP 伺服器資料庫中的單一使用者帳號來存取。 本章節將介紹在 FreeBSD 系統上如何快速的設定一個 LDAP 伺服器。本章節假設管理者已做好規劃,這包含:要儲存何種類型的資訊、這些資訊要來做什麼、那些使用者擁有存取這些資訊的權限以及如何確保這些資訊不會被未經授權存取。 === LDAP 術語與結構 LDAP 使用了數個術語在開始設置之前必須先了解。所有的目錄項目由一群屬性 (_attributes_) 所組成,每個屬性集皆有一個獨特的辨識碼稱為辨識名稱 (_Distinguished Name_, DN),這個辨識碼會由數個其他的屬性,如:常用或相對辨識名稱 (_Relative Distinguished Name_, RDN) 所組成,這就像目錄有絕對路徑與相對路徑,可以把 DN 當做絕對路徑,RDN 當做相對路徑。 LDAP 項目的例子如下。這個例子會搜尋指定使用者帳號 (`uid`)、組織單位 (`ou`) 及組織的項目 (`o`): [source,shell] .... % ldapsearch -xb "uid=trhodes,ou=users,o=example.com" # extended LDIF # # LDAPv3 # base with scope subtree # filter: (objectclass=*) # requesting: ALL # # trhodes, users, example.com dn: uid=trhodes,ou=users,o=example.com mail: trhodes@example.com cn: Tom Rhodes uid: trhodes telephoneNumber: (123) 456-7890 # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... 這個範例項目會顯示 `dn`, `mail`, `cn`, `uid` 以及 `telephoneNumber` 屬性的數值。而 cn 屬性則是 RDN。 更多有關 LDAP 以及其術語的資訊可在 http://www.openldap.org/doc/admin24/intro.html[http://www.openldap.org/doc/admin24/intro.html] 找到。 [[ldap-config]] === 設定 LDAP 伺服器 FreeBSD 並未提供內建的 LDAP 伺服器,要開始設定前請先安裝 package:net/openldap-server[] 套件或 Port: [source,shell] .... # pkg install openldap-server .... 在extref:{linux-users}[套件, software]中已開啟了許多的預設選項,可以透過執行 `pkg info openldap-server` 來查看已開啟的選項,若有不足的地方 (例如需要開啟 SQL 的支援),請考慮使用適當的crossref:ports[ports-using,方式]重新編譯該 Port。 安裝程序會建立目錄 [.filename]#/var/db/openldap-data# 來儲存資料,同時需要建立儲存憑證的目錄: [source,shell] .... # mkdir /usr/local/etc/openldap/private .... 接下來是設定憑証機構 (Certificate authority)。以下指令必須在 [.filename]#/usr/local/etc/openldap/private# 下執行,這很重要是由於檔案權限須要被限制且其他使用者不應有這些檔案的存取權限,更多有關憑証的詳細資訊以及相關的參數可在 crossref:security[openssl,OpenSSL] 中找到。要建立憑証授權,需先輸人這個指令並依提示操作: [source,shell] .... # openssl req -days 365 -nodes -new -x509 -keyout ca.key -out ../ca.crt .... 提示輸入的項目__除了__通用名稱 (`Common Name`) 外其他是可以一樣的,這個項目必須使用跟系統主機名稱 _不同_ 的名稱。若這是一個自行簽署的憑証 (Self signed certificate),則在憑証機構 `CA` 的前面加上主機名稱。 接下來的工作是建立一個伺服器的憑証簽署請求與一個私鑰。請輸入以下指令然後依提示操作: [source,shell] .... # openssl req -days 365 -nodes -new -keyout server.key -out server.csr .... 在憑証產生程序的過程中請確認 `Common Name` 屬性設定正確。憑証簽署請求 (Certificate Signing Request) 必須經過憑証機構簽署後才會成為有效的憑証: [source,shell] .... # openssl x509 -req -days 365 -in server.csr -out ../server.crt -CA ../ca.crt -CAkey ca.key -CAcreateserial .... 在憑証產生程序的最後一步是產生並簽署客戶端憑証: [source,shell] .... # openssl req -days 365 -nodes -new -keyout client.key -out client.csr # openssl x509 -req -days 3650 -in client.csr -out ../client.crt -CA ../ca.crt -CAkey ca.key .... 記得當提示時要使用同樣的 `Common Name` 屬性。完成之後,請確認執行的指令產生了 8 個新檔案。 OpenLDAP 伺服器所執行的 Daemon 為 [.filename]#slapd#,OpenLDAP 是透過 [.filename]#slapd.ldif# 來做設定, OpenLDAP 官方已停止採用舊的 [.filename]#slapd.conf# 格式。 這裡有些 [.filename]#slapd.ldif# 的 http://www.openldap.org/doc/admin24/slapdconf2.html[設定檔範例] 可以使用,同時您也可以在 [.filename]#/usr/local/etc/openldap/slapd.ldif.sample# 找到範例資訊。相關可用的選項在 slapd-config(5) 文件會有說明。[.filename]#slapd.ldif# 的每個段落,如同其他 LDAP 屬性設定一樣會透過獨一無二 DN 來辨識,並請確保 `dn:` 描述與其相關屬性之間沒有空行。以下的範例中會實作一個使用 TLS 的安全通道,首先是全域的設定: [.programlisting] .... # # See slapd-config(5) for details on configuration options. # This file should NOT be world readable. # dn: cn=config objectClass: olcGlobal cn: config # # # Define global ACLs to disable default read access. # olcArgsFile: /var/run/openldap/slapd.args olcPidFile: /var/run/openldap/slapd.pid olcTLSCertificateFile: /usr/local/etc/openldap/server.crt olcTLSCertificateKeyFile: /usr/local/etc/openldap/private/server.key olcTLSCACertificateFile: /usr/local/etc/openldap/ca.crt #olcTLSCipherSuite: HIGH olcTLSProtocolMin: 3.1 olcTLSVerifyClient: never .... 這個檔案中必須指定憑証機構 (Certificate Authority)、伺服器憑証 (Server Certificate) 與伺服器私鑰 (Server Private Key),建議可讓客戶端決定使用的安全密碼 (Security Cipher),略過 `olcTLSCipherSuite` 選項 (此選項不相容 [.filename]#openssl# 以外的 TLS 客戶端)。選項 `olcTLSProtocolMin` 讓伺服器可要求一個安全等級的最低限度,建議使用。伺服器有進行驗証的必要,但客戶端並不需要,因此可設定 `olcTLSVerifyClient: never`。 第二個部份是設定後端要採用的模組有那些,可使用以下方式設定: [.programlisting] .... # # Load dynamic backend modules: # dn: cn=module,cn=config objectClass: olcModuleList cn: module olcModulepath: /usr/local/libexec/openldap olcModuleload: back_mdb.la #olcModuleload: back_bdb.la #olcModuleload: back_hdb.la #olcModuleload: back_ldap.la #olcModuleload: back_passwd.la #olcModuleload: back_shell.la .... 第三個部份要載入資料庫所需的 `ldif` 綱要 (Schema),這個動作是必要的。 [.programlisting] .... dn: cn=schema,cn=config objectClass: olcSchemaConfig cn: schema include: file:///usr/local/etc/openldap/schema/core.ldif include: file:///usr/local/etc/openldap/schema/cosine.ldif include: file:///usr/local/etc/openldap/schema/inetorgperson.ldif include: file:///usr/local/etc/openldap/schema/nis.ldif .... 接下來是前端設定的部份: [.programlisting] .... # Frontend settings # dn: olcDatabase={-1}frontend,cn=config objectClass: olcDatabaseConfig objectClass: olcFrontendConfig olcDatabase: {-1}frontend olcAccess: to * by * read # # Sample global access control policy: # Root DSE: allow anyone to read it # Subschema (sub)entry DSE: allow anyone to read it # Other DSEs: # Allow self write access # Allow authenticated users read access # Allow anonymous users to authenticate # #olcAccess: to dn.base="" by * read #olcAccess: to dn.base="cn=Subschema" by * read #olcAccess: to * # by self write # by users read # by anonymous auth # # if no access controls are present, the default policy # allows anyone and everyone to read anything but restricts # updates to rootdn. (e.g., "access to * by * read") # # rootdn can always read and write EVERYTHING! # olcPasswordHash: {SSHA} # {SSHA} is already the default for olcPasswordHash .... 再來是__設定後端__的部份,之後唯一能夠存取 OpenLDAP 伺服器設定的方式是使用全域超級使用者。 [.programlisting] .... dn: olcDatabase={0}config,cn=config objectClass: olcDatabaseConfig olcDatabase: {0}config olcAccess: to * by * none olcRootPW: {SSHA}iae+lrQZILpiUdf16Z9KmDmSwT77Dj4U .... 預設的管理者使用者名稱是 `cn=config`,可在 Shell 中輸入 [.filename]#slappasswd#,決定要使用的密碼並將其產生的編碼放到 `olcRootPW` 欄位中。若這個選項在這時沒有設定好,在匯入 [.filename]#slapd.ldif# 之後將沒有任何人有辦法修改__全域的設定__。 最後一個部份是有關資料庫後端的設定: [.programlisting] .... ####################################################################### # LMDB database definitions ####################################################################### # dn: olcDatabase=mdb,cn=config objectClass: olcDatabaseConfig objectClass: olcMdbConfig olcDatabase: mdb olcDbMaxSize: 1073741824 olcSuffix: dc=domain,dc=example olcRootDN: cn=mdbadmin,dc=domain,dc=example # Cleartext passwords, especially for the rootdn, should # be avoided. See slappasswd(8) and slapd-config(5) for details. # Use of strong authentication encouraged. olcRootPW: {SSHA}X2wHvIWDk6G76CQyCMS1vDCvtICWgn0+ # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools. # Mode 700 recommended. olcDbDirectory: /var/db/openldap-data # Indices to maintain olcDbIndex: objectClass eq .... 這裡指定的資料庫即__實際用來保存__LDAP 目錄的資料,也可以使用 `mdb` 以外的項目,資料庫的超級使用者可在這裡設定 (與全域的超級使用者是不同的東西):`olcRootDN` 需填寫使用者名稱 (可自訂),`olcRootPW` 需填寫該使用者編碼後的密碼,將密碼編碼可使用 [.filename]#slappasswd# 如同前面所述。 這裡有個link:http://www.openldap.org/devel/gitweb.cgi?p=openldap.git;a=tree;f=tests/data/regressions/its8444;h=8a5e808e63b0de3d2bdaf2cf34fecca8577ca7fd;hb=HEAD[檔案庫]內有四個 [.filename]#slapd.ldif# 的範例,要將現有的 [.filename]#slapd.conf# 轉換成 [.filename]#slapd.ldif# 格式,可參考link:http://www.openldap.org/doc/admin24/slapdconf2.html[此頁] (注意,這裡面的說明也會介紹一些不常用的選項)。 當設定完成之後,需將 [.filename]#slapd.ldif# 放在一個空的目錄當中,建議如以下方式建立: [source,shell] .... # mkdir /usr/local/etc/openldap/slapd.d/ .... 匯入設定資料庫: [source,shell] .... # /usr/local/sbin/slapadd -n0 -F /usr/local/etc/openldap/slapd.d/ -l /usr/local/etc/openldap/slapd.ldif .... 啟動 [.filename]#slapd# Daemon: [source,shell] .... # /usr/local/libexec/slapd -F /usr/local/etc/openldap/slapd.d/ .... 選項 `-d` 可以用來除錯使用,如同 slapd(8) 中所說明的,若要檢驗伺服器是否正常執行與運作可以: [source,shell] .... # ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts # extended LDIF # # LDAPv3 # base <> with scope baseObject # filter: (objectclass=*) # requesting: namingContexts # # dn: namingContexts: dc=domain,dc=example # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... 伺服器端仍必須受到信任,若在此之前未做過這個動作,請依照以下指示操作。安裝 OpenSSL 套件或 Port: [source,shell] .... # pkg install openssl .... 進入 [.filename]#ca.crt# 所在的目錄 (以這邊使用的例子來說則是 [.filename]#/usr/local/etc/openldap#),執行: [source,shell] .... # c_rehash . .... 現在 CA 與伺服器憑証可以依其用途被辨識,可進入 [.filename]#server.crt# 所在的目錄執行以下指令來檢查: [source,shell] .... # openssl verify -verbose -CApath . server.crt .... 若 [.filename]#slapd# 已正在執行,就重新啟動它。如同 [.filename]#/usr/local/etc/rc.d/slapd# 所述,要讓 [.filename]#slapd# 開機時可正常執行,須要加入以下行到 [.filename]#/etc/rc.conf#: [.programlisting] .... lapd_enable="YES" slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://0.0.0.0/"' slapd_sockets="/var/run/openldap/ldapi" slapd_cn_config="YES" .... 開機啟動 [.filename]#slapd# 並不會提供除錯的功能,您可以檢查 [.filename]#/var/log/debug.log#, [.filename]#dmesg -a# 及 [.filename]#/var/log/messages# 檢確認是否有正常運作。 以下範例會新增群組 `team` 及使用者 `john` 到 `domain.example` LDAP 資料庫,而該資料庫目前是空的。首先要先建立 [.filename]#domain.ldif# 檔: [source,shell] .... # cat domain.ldif dn: dc=domain,dc=example objectClass: dcObject objectClass: organization o: domain.example dc: domain dn: ou=groups,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: groups dn: ou=users,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: users dn: cn=team,ou=groups,dc=domain,dc=example objectClass: top objectClass: posixGroup cn: team gidNumber: 10001 dn: uid=john,ou=users,dc=domain,dc=example objectClass: top objectClass: account objectClass: posixAccount objectClass: shadowAccount cn: John McUser uid: john uidNumber: 10001 gidNumber: 10001 homeDirectory: /home/john/ loginShell: /usr/bin/bash userPassword: secret .... 請查看 OpenLDAP 說明文件取得更詳細的資訊,使用 [.filename]#slappasswd# 來將純文字的密碼 `secret` 更改為已編碼的型式來填寫 `userPassword` 欄位。在 `loginShell` 所指定的路徑,必須在所有可讓 `john` 登入的系統中存在。最後是使用 `mdb` 管理者修改資料庫: [source,shell] .... # ldapadd -W -D "cn=mdbadmin,dc=domain,dc=example" -f domain.ldif .... 要修改__全域設定__只能使用全域的超及使用者。例如,假設一開始採用了 `olcTLSCipherSuite: HIGH:MEDIUM:SSLv3` 選項,但最後想要把它移除,可以建立一個有以下內容的檔案: [source,shell] .... # cat global_mod dn: cn=config changetype: modify delete: olcTLSCipherSuite .... 然後套用修改內容: [source,shell] .... # ldapmodify -f global_mod -x -D "cn=config" -W .... 當提示輸入密碼時,提供當時在__設定後端__一節所設定的密碼,在這裡無須填寫使用者名稱,`cn=config` 代表要修改資料庫資料的位置。也可以使用 `ldapmodify` 刪除其中一行屬性,或是 `ldapdelete` 刪除整筆資料。 若有問題無法正常執行,或是全域的超級使用者無法存取後端的設定,可以刪除並重建整個後端設定: [source,shell] .... # rm -rf /usr/local/etc/openldap/slapd.d/ .... 可以修改 [.filename]#slapd.ldif# 後再重新匯入一次。請注意,這個步驟只在沒有其他方式可用時才使用。 本章節的設定說明只針對伺服器端的部份,在同一台主機中也可以同時有安裝 LDAP 客戶端但需要額外做設定。 [[network-dhcp]] == 動態主機設置協定 (DHCP) 動態主機設置協定 (Dynamic Host Configuration Protocol, DHCP) 可分配必要的位置資訊給一個連線到網路的系統以在該網路通訊。FreeBSD 內含 OpenBSD 版本的 `dhclient`,可用來做為客戶端來取得位置資訊。FreeBSD 預設並不會安裝 DHCP 伺服器,但在 FreeBSD Port 套件集中有許多可用的伺服器。有關 DHCP 通訊協定的完整說明位於 http://www.freesoft.org/CIE/RFC/2131/[RFC 2131],相關資源也可至 http://www.isc.org/downloads/dhcp/[isc.org/downloads/dhcp/] 取得。 本節將介紹如何使用內建的 DHCP 客戶端,接著會介紹如何安裝並設定一個 DHCP 伺服器。 [NOTE] ==== 在 FreeBSD 中,man:bpf[4] 裝置同時會被 DHCP 伺服器與 DHCP 客戶端所使用。這個裝置會在 [.filename]#GENERIC# 核心中被引用並隨著 FreeBSD 安裝。想要建立自訂核心的使用者若要使用 DHCP 則須保留這個裝置。 另外要注意 [.filename]#bpf# 也會讓有權限的使用者在該系統上可執行網路封包監聽程式。 ==== === 設定 DHCP 客戶端 DHCP 客戶端內含在 FreeBSD 安裝程式當中,這讓在新安裝的系統上設定自動從 DHCP 伺服器接收網路位置資訊變的更簡單。請參考 crossref:bsdinstall[bsdinstall-post,安裝後注意事項] 取得網路設置的範例。 當 `dhclient` 在客戶端機器上執行時,它便會開始廣播請求取得設置資訊。預設這些請求會使用 UDP 埠號 68。而伺服器則會在 UDP 埠號 67 來回覆,將 IP 位址與其他相關的網路資訊,如:子網路遮罩、預設閘道及 DNS 伺服器位址告訴客戶端,詳細的清單可在 man:dhcp-options[5] 找到。 預設當 FreeBSD 系統開機時,其 DHCP 客戶端會在背景執行或稱非同步 (_Asynchronously_) 執行,在完成 DHCP 程序的同時其他啟動 Script 會繼續執行,來加速系統啟動。 背景 DHCP 在 DHCP 伺服器可以快速的回應客戶端請求時可運作的很好。然而 DHCP 在某些系統可能需要較長的時間才能完成,若網路服務嘗試在 DHCP 尚未分配網路位置資訊前執行則會失敗。使用同步 (_Synchronous_) 模式執行 DHCP 可避免這個問題,因為同步模式會暫停啟動直到 DHCP 已設置完成。 在 [.filename]#/etc/rc.conf# 中的這行用來設定採用背景 (非同步模式): [.programlisting] .... ifconfig_fxp0="DHCP" .... 若系統已經在安裝時設定使用 DHCP,這行可能會已存在。替換在例子中的 _fxp0_ 為實際要動態設置的網路介面名稱,如 crossref:config[config-network-setup,設定網路介面卡] 中的說明。 要改設定系統採用同步模式,在啟動時暫停等候 DHCP 完成,使用 "`SYNCDHCP`": [.programlisting] .... ifconfig_fxp0="SYNCDHCP" .... 尚有其他可用的客戶端選項,請在 man:rc.conf[5] 搜尋 `dhclient` 來取得詳細資訊。 DHCP 客戶端會使用到以下檔案: * [.filename]#/etc/dhclient.conf# + `dhclient` 用到的設定檔。通常這個檔案只會有註解,因為預設便適用大多數客戶端。這個設定檔在 man:dhclient.conf[5] 中有說明。 * [.filename]#/sbin/dhclient# + 有關指令本身的更多資訊可於 man:dhclient[8] 找到。 * [.filename]#/sbin/dhclient-script# + FreeBSD 特定的 DHCP 客戶端設定 Script。在 man:dhclient-script[8] 中有說明,但應不須做任何修改便可正常運作。 * [.filename]#/var/db/dhclient.leases.interface# + DHCP 客戶端會在這個檔案中儲存有效租約的資料,寫入的格式類似日誌,在 man:dhclient.leases[5] 有說明。 [[network-dhcp-server]] === 安裝並設定 DHCP 伺服器 -本節將示範如何設定 FreeBSD 系統成為 DHCP 伺服器,使用 Internet Systems Consortium (ISC) 所實作的 DHCP 伺服器,這個伺服器及其文件可使用 package:net/isc-dhcp43-server[] 套件或 Port 安裝。 +本節將示範如何設定 FreeBSD 系統成為 DHCP 伺服器,使用 Internet Systems Consortium (ISC) 所實作的 DHCP 伺服器,這個伺服器及其文件可使用 package:net/isc-dhcp44-server[] 套件或 Port 安裝。 -package:net/isc-dhcp43-server[] 的安裝程式會安裝一份範例設定檔,複製 [.filename]#/usr/local/etc/dhcpd.conf.example# 到 [.filename]#/usr/local/etc/dhcpd.conf# 並在這個新檔案做編輯。 +package:net/isc-dhcp44-server[] 的安裝程式會安裝一份範例設定檔,複製 [.filename]#/usr/local/etc/dhcpd.conf.example# 到 [.filename]#/usr/local/etc/dhcpd.conf# 並在這個新檔案做編輯。 這個設定檔內容包括了子網路及主機的宣告,用來定義要提供給 DHCP 客戶端的資訊。如以下行設定: [.programlisting] .... option domain-name "example.org";<.> option domain-name-servers ns1.example.org;<.> option subnet-mask 255.255.255.0;<.> default-lease-time 600;<.> max-lease-time 72400;<.> ddns-update-style none;<.> subnet 10.254.239.0 netmask 255.255.255.224 { range 10.254.239.10 10.254.239.20;<.> option routers rtr-239-0-1.example.org, rtr-239-0-2.example.org;<.> } host fantasia { hardware ethernet 08:00:07:26:c0:a5;<.> fixed-address fantasia.fugue.com;<.> } .... <.> 這個選項指定了要提供給客戶端的預設搜尋網域。請參考 man:resolv.conf[5] 取得更多資訊。 <.> 這個選項指定了客戶端應使用的 DNS 伺服器清單 (以逗號分隔)。如範例中所示,可使用伺服器的完整網域名稱 (Fully Qualified Domain Names, FQDN) 或伺服器的 IP 位址。 <.> 要提供給客戶端的子網路遮罩。 <.> 預設租約到期時間 (秒)。客戶端可以自行設定覆蓋這個數值。 <.> 一個租約最多允許的時間長度 (秒)。若客戶端請求更長的租約,仍會發出租約,但最多只會在 `max-lease-time` 內有效。 <.> 預設的 `none` 會關閉動態 DNS 更新。更改此值為 `interim` 可讓 DHCP 伺服器每當發出一個租約便通知 DNS 伺服器更新,如此一來 DNS 伺服器便知道網路中該電腦的 IP 位址。不要更改此預設值,除非 DNS 伺服器已設定為支援動態 DNS。 <.> 此行會建立一個可用 IP 位址的儲存池來保留這些要分配給 DHCP 客戶端的位址。位址範圍必須在前一行所指定的網路或子網路中有效。 <.> 宣告在開始的 `{` 括號之前所指定的網路或子網路中有效的預設通訊閘。 <.> 指定客戶端的硬體 MAC 位址,好讓 DHCP 伺服器在客戶端發出請求時可以辨識客戶端。 <.> 指定這個主機應分配相同的 IP 位址。在此處用主機名稱是正確的,由於 DHCP 伺服器會在回傳租約資訊前先解析主機名稱。 此設定檔還支援其他選項,請參考隨伺服器一併安裝的 dhcpd.conf(5) 來取得詳細資訊與範例。 完成 [.filename]#dhcpd.conf# 的設定之後,在 [.filename]#/etc/rc.conf# 啟動 DHCP 伺服器: [.programlisting] .... dhcpd_enable="YES" dhcpd_ifaces="dc0" .... 替換 `dc0` 為 DHCP 伺服器要傾聽 DHCP 客戶端請求的網路介面 (多個介面可以空白分隔)。 執行以下指令來啟動伺服器: [source,shell] .... # service isc-dhcpd start .... 往後任何對伺服器設定的變更會需要使用 man:service[8] 中止 dhcpd 服務然後啟動。 DHCP 伺服器會使用到以下檔案。注意,操作手冊會與伺服器軟體一同安裝。 * [.filename]#/usr/local/sbin/dhcpd# + 更多有關 dhcpd 伺服器的資訊可在 dhcpd(8) 找到。 * [.filename]#/usr/local/etc/dhcpd.conf# + 伺服器設定檔需要含有所有要提供給客戶端的資訊以及有關伺服器運作的資訊。在 dhcpd.conf(5) 有此設定檔的說明。 * [.filename]#/var/db/dhcpd.leases# + DHCP 伺服器會儲存一份已發出租約的資料於這個檔案,寫入的格式類似日誌。參考 dhcpd.leases(5) 會有更完整的說明。 * [.filename]#/usr/local/sbin/dhcrelay# + -這個 Daemon 會用在更進階的環境中,在一個 DHCP 伺服器要轉發來自客戶端的請求到另一個網路的另一個 DHCP 伺服器的環境。若需要使用此功能,請安裝 package:net/isc-dhcp43-relay[] 套件或 Port,安裝會包含 dhcrelay(8),裡面有提供更詳細的資訊。 +這個 Daemon 會用在更進階的環境中,在一個 DHCP 伺服器要轉發來自客戶端的請求到另一個網路的另一個 DHCP 伺服器的環境。若需要使用此功能,請安裝 package:net/isc-dhcp44-relay[] 套件或 Port,安裝會包含 dhcrelay(8),裡面有提供更詳細的資訊。 [[network-dns]] == 網域名稱系統 (DNS) 網域名稱系統 (Domain Name System, DNS) 是一種協定用來轉換網域名稱為 IP 位址,反之亦然。DNS 會協調網際網路上有權的根節點 (Authoritative root)、最上層網域 (Top Level Domain, TLD) 及其他小規模名稱伺服器來取得結果,而這些伺服器可管理與快取個自的網域資訊。要在系統上做 DNS 查詢並不需要架設一個名稱伺服器。 以下表格會說明一些與 DNS 有關的術語: .DNS 術語 [cols="1,1", frame="none", options="header"] |=== | 術語 | 定義 |正向 DNS (Forward DNS) |將主機名稱對應 IP 位址的動作。 |源頭 (Origin) |代表某個轄區檔案中所涵蓋的網域。 |解析器 (Resolver) |主機向名稱伺服器查詢轄區資訊的系統程序。 |反向 DNS (Reverse DNS) |將 IP 對應主機名稱的動作。 |根轄區 (Root zone) |網際網路轄區階層的最開始,所有的轄區會在根轄區之下,類似在檔案系統中所有的檔案會在根目錄底下。 |轄區 (Zone) |獨立的網域、子網域或或由相同授權 (Authority) 管理的部分 DNS。 |=== 轄區範例: * `.` 是一般在文件中表達根轄區的方式。 * `org.` 是一個在根轄區底下的最上層網域 (Top Level Domain , TLD)。 * `example.org.` 是一個在 `org.` TLD 底下的轄區。 * `1.168.192.in-addr.arpa` 是一個轄區用來代表所有在 `192.168.1.*` IP 位址空間底下的 IP 位址。 如您所見,更詳細的主機名稱會加在左方,例如 `example.org.` 比 `org.` 更具體,如同 `org.` 比根轄區更具體,主機名稱每一部份的架構很像檔案系統:[.filename]#/dev# 目錄在根目錄底下,以此類推。 === 要架設名稱伺服器的原因 名稱伺服器通常有兩種形式:有權的 (Authoritative) 名稱伺服器與快取 (或稱解析) 名稱伺服器。 以下情況會需要一台有權的名稱伺服器: * 想要提供 DNS 資訊給全世界,做為官方回覆查詢。 * 已經註冊了一個網域,例如 `example.org`,且要將 IP 位址分配到主機名稱下。 * 一段 IP 位址範圍需要反向 DNS 項目 (IP 轉主機名稱)。 * 要有一台備援或次要名稱伺服器用來回覆查詢。 以下情況會需要一台快取名稱伺服器: * 比起查詢外部的名稱伺服器本地 DNS 伺服器可以快取並更快的回應。 當查詢 `www.FreeBSD.org` 時,解析程式通常會查詢上游 ISP 的名稱伺服器然後接收其回覆,使用本地、快取 DNS 伺服器,只需要由快取 DNS 伺服器對外部做一次查詢,其他的查詢則不需要再向區域網路之外查詢,因為這些資訊已經在本地被快取了。 === DNS 伺服器設定 Unbound 由 FreeBSD 基礎系統提供,預設只會提供本機的 DNS 解析,雖然基礎系統的套件可被設定提供本機以外的解析服務,但要解決這樣的需求仍建議安裝 FreeBSD Port 套件集中的 Unbound。 要開啟 Unbound 可加入下行到 [.filename]#/etc/rc.conf#: [.programlisting] .... local_unbound_enable="YES" .... 任何已存在於 [.filename]#/etc/resolv.conf# 中的名稱伺服器會在新的 Unbound 設定中被設為追隨者 (Forwarder)。 [NOTE] ==== 若任一個列在清單中的名稱伺服器不支援 DNSSEC,則本地的 DNS 解析便會失敗,請確認有測試每一台名稱伺服器並移除所有測試失敗的項目。以下指令會顯示出信認樹或在 `192.168.1.1` 上執行失敗的名稱伺服器: ==== [source,shell] .... % drill -S FreeBSD.org @192.168.1.1 .... 確認完每一台名稱伺服器都支援 DNSSEC 後啟動 Unbound: [source,shell] .... # service local_unbound onestart .... 這將會更新 [.filename]#/etc/resolv.conf# 來讓查詢已用 DNSSEC 確保安全的網域現在可以運作,例如,執行以下指令來檢驗 FreeBSD.org DNSSEC 信任樹: [source,shell] .... % drill -S FreeBSD.org ;; Number of trusted keys: 1 ;; Chasing: freebsd.org. A DNSSEC Trust tree: freebsd.org. (A) |---freebsd.org. (DNSKEY keytag: 36786 alg: 8 flags: 256) |---freebsd.org. (DNSKEY keytag: 32659 alg: 8 flags: 257) |---freebsd.org. (DS keytag: 32659 digest type: 2) |---org. (DNSKEY keytag: 49587 alg: 7 flags: 256) |---org. (DNSKEY keytag: 9795 alg: 7 flags: 257) |---org. (DNSKEY keytag: 21366 alg: 7 flags: 257) |---org. (DS keytag: 21366 digest type: 1) | |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) | |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) |---org. (DS keytag: 21366 digest type: 2) |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) ;; Chase successful .... [[network-apache]] == Apache HTTP 伺服器 開放源碼的 Apache HTTP Server 是目前最廣泛被使用的網頁伺服器,FreeBSD 預設並不會安裝這個網頁伺服器,但可從 package:www/apache24[] 套件或 Port 安裝。 本節將會摘要如何設定並啟動在 FreeBSD 上 2._x_ 版的 Apache HTTP Server,要取得有關 Apache 更詳細的資訊及其設定項目請參考 http://httpd.apache.org/[httpd.apache.org]。 === 設定並啟動 Apache 在 FreeBSD 中,主 Apache HTTP Server 設定檔會安裝於 [.filename]#/usr/local/etc/apache2x/httpd.conf#,其中 _x_ 代表版號,這份 ASCII 文字檔中以 `#` 做為行首的是註解,而最常需修改的項目有: `ServerRoot "/usr/local"`:: 指定該 Apache 的預設安裝路徑,Binary 檔會儲存在伺服器根目錄 (Server root) 下的 [.filename]#bin# 與 [.filename]#sbin# 子目錄,而設定檔會儲存在 [.filename]#etc/apache2x# 子目錄。 `ServerAdmin you@example.com`:: 更改此項目為您要接收問題回報的電子郵件位址,這個位址也會顯示在一些伺服器產生的頁面上,如:錯誤頁面。 `ServerName www.example.com:80`:: 讓管理者可以設定伺服器要回傳給客戶端的主機名稱 (Hostname),例如,`www` 可以更改為實際的主機名稱,若系統並未有註冊的 DNS 名稱,則可改輸入其 IP 位址,若伺服器需要傾聽其他埠號,可更改 `80` 為其他埠號。 `DocumentRoot "/usr/local/www/apache2__x__/data"`:: 提供文件的目錄,預設所有的請求均會到此目錄,但可以使用符號連結與別名來指向其他地方。 在對 Apache 設定檔做變更之前,建議先做備份,在 Apache 設定完成之後,儲存讓檔案並使用 `apachectl` 檢驗設定,執行 `apachectl configtest` 的結果應回傳 `Syntax OK`。 要在系統啟動時執行 Apache,可加入下行到 [.filename]#/etc/rc.conf#: [.programlisting] .... apache24_enable="YES" .... 若 Apache 要使用非預設的選項啟動,可加入下行到 [.filename]#/etc/rc.conf# 來指定所需的旗標參數: [.programlisting] .... apache24_flags="" .... 若 apachectl 未回報設定錯,則可啟動 `httpd`: [source,shell] .... # service apache24 start .... `httpd` 服務可以透過在網頁瀏覽器中輸入 `http://_localhost_` 來測試,將 _localhost_ 更改為執行 `httpd` 那台主機的完整網域名稱 (Fully-qualified domain name)。預設會顯示的網頁為 [.filename]#/usr/local/www/apache24/data/index.html#。 後續若有在 `httpd` 執行中時修改 Apache 設定檔可使用以下指令來測試是否有誤: [source,shell] .... # service apache24 configtest .... [NOTE] ==== 注意,`configtest` 並非採用 man:rc[8] 標準,不應預期其可在所有的啟動 Script 中正常運作。 ==== === 虛擬主機 虛擬主機允許在一個 Apache 伺服器執行多個網站,虛擬主機可以是以 IP 為主 (_IP-based_) 或以名稱為主 (_name-based_)。以 IP 為主的虛擬主機中的每一個網站要使用不同的 IP 位址。以名稱為主的虛擬主機會使用客戶端的 HTTP/1.1 標頭來判斷主機名稱,這可讓不同的網站共用相同的 IP 位址。 要設定 Apache 使用以名稱為主的虛擬主機可在每一個網站加入 `VirtualHost` 區塊,例如,有一個名稱為 `www.domain.tld` 的主機擁有一個 `www.someotherdomain.tld` 的虛擬網域,可加入以下項目到 [.filename]#httpd.conf#: [.programlisting] .... ServerName www.domain.tld DocumentRoot /www/domain.tld ServerName www.someotherdomain.tld DocumentRoot /www/someotherdomain.tld .... 每一個虛擬主機均需更改其 `ServerName` 與 `DocumentRoot` 的值為實際要使用的值。 更多有關設定虛擬主機的資訊,可參考 Apache 官方說明文件於:link:http://httpd.apache.org/docs/vhosts/[http://httpd.apache.org/docs/vhosts/]。 === Apache 模組 Apache 使用模組 (Module) 來擴充伺服器所提供的功能。請參考 http://httpd.apache.org/docs/current/mod/[http://httpd.apache.org/docs/current/mod/] 來取得可用模組的完整清單與設定詳細資訊。 在 FreeBSD 中有些模組可以隨著 package:www/apache24[] Port 編譯,只要在 [.filename]#/usr/ports/www/apache24# 輸入 `make config` 便可查看有那一些模組是預設開啟的,若模組未與 Port 一併編譯,FreeBSD Port 套件集也提供了一個簡單的方式可安裝各種模組,本節將介紹最常使用的三個模組。 ==== [.filename]#mod_ssl# [.filename]#mod_ssl# 模組利用了 OpenSSL 透過 Secure Sockets Layer (SSLv3) 與 Transport Layer Security (TLSv1) 通訊協定來提供強大的加密,這個模組提供了向受信認的憑証簽署機構申請簽章憑証所需的任何東西,讓 FreeBSD 上能夠執行安全的網頁伺服器。 在 FreeBSD 中 [.filename]#mod_ssl# 模組預設在套件與 Port 均是開啟的,可用的設定項目在 http://httpd.apache.org/docs/current/mod/mod_ssl.html[http://httpd.apache.org/docs/current/mod/mod_ssl.html] 會說明。 ==== [.filename]#mod_perl# [.filename]#mod_perl# 模組讓您可以使用 Perl 撰寫 Apache 模組,除此之外,嵌入到伺服器的直譯器可避免啟動外部直譯器的額外開銷與 Perl 耗費的啟動時間。 [.filename]#mod_perl# 可以使用 package:www/mod_perl2[] 套件或 Port 安裝,有關使用此模組的說明文件可在 http://perl.apache.org/docs/2.0/index.html[http://perl.apache.org/docs/2.0/index.html] 中找到。 ==== [.filename]#mod_php# _PHP: Hypertext Preprocessor_ (PHP) 是一般用途的腳本 (Script) 語言,特別適用於網站開發,能夠嵌入在 HTML 當中,它的語法參考自 C, Java(TM) 及 Perl,目的在讓網頁開發人員能快速的寫出動態網頁。 要在 Apache 網頁伺服器上加入對 PHP5 的支援,可安裝 package:www/mod_php56[] 套件或 Port,這會安裝並設定支援動態 PHP 應用程式所需的模組。安裝過程會自動加入下行到 [.filename]#/usr/local/etc/apache24/httpd.conf#: [.programlisting] .... LoadModule php5_module libexec/apache24/libphp5.so .... 接著,執行 graceful 重新啟動來載入 PHP 模組: [source,shell] .... # apachectl graceful .... 由 package:www/mod_php56[] 所提供的 PHP 支援是有限的,若需要額外的支援可以使用 package:lang/php56-extensions[] Port 來安裝,該 Port 提供了選單介面來選擇可用的 PHP 擴充套件。 或者,可以找到適當的 Port 來安裝各別的擴充套件,例如,要增加 PHP 對 MySQL 資料庫伺服器的支援可安裝 package:databases/php56-mysql[]。 在安裝完擴充套件之後,必須重新載入 Apache 伺服器來使用新的設定值: [source,shell] .... # apachectl graceful .... === 動態網站 除了 mod_perl 與 mod_php 外,也有其他語言可用來建立動態網頁內容,這包含了 Django 與 Ruby on Rails。 ==== Django Django 是以 BSD 授權的框架 (Framework),指在讓開發人員能快速的寫出高效、優雅的網頁應用程式。它提供了物件關聯對應器 (Object-relational mapper),所以各種資料型態可當做 Python 的物件來開發,且提供了豐富的動態資料庫存取 API 給這些物件,讓開發人員不再需要寫 SQL。它也同時提供了可擴充的樣板系統,來讓應用程式的邏輯與 HTML 呈現能夠被拆開。 Django 需要 [.filename]#mod_python#,以及一個 SQL 資料庫引擎才能運作。在 FreeBSD 中的 package:www/py-django[] Port 會自動安裝 [.filename]#mod_python# 以及對 PostgreSQL, MySQL 或 SQLite 資料庫的支援,預設為 SQLite,要更改資料庫引擎可在 [.filename]#/usr/ports/www/py-django# 輸入 `make config` 然後再安裝該 Port。 Django 安裝完成之後,應用程式會需要一個專案目錄並搭配 Apache 設定才能使用內嵌的 Python 直譯器,此直譯器會用來呼叫網站上指定 URL 的應用程式。 要設定 Apache 傳遞某個 URL 請求到網站應用程式,可加入下行到 [.filename]#httpd.conf# 來指定專案目錄的完整路徑: [.programlisting] .... SetHandler python-program PythonPath "['/dir/to/the/django/packages/'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonAutoReload On PythonDebug On .... 請參考 https://docs.djangoproject.com[https://docs.djangoproject.com] 來取得如何使用 Django 的更多資訊。 ==== Ruby on Rails Ruby on Rails 是另外一套開放源碼的網站框架 (Framework),提供了完整的開發堆疊,這使得網頁開發人員可以更有生產力且能夠快速的寫出強大的應用程式,在 FreeBSD 它可以使用 package:www/rubygem-rails[] 套件或 Port 安裝。 請參考 http://guides.rubyonrails.org[http://guides.rubyonrails.org] 來取得更多有關如何使用 Ruby on Rails 的資訊。 [[network-ftp]] == 檔案傳輸協定 (FTP) 檔案傳輸協定 (File Transfer Protocol, FTP) 提供了使用一個簡單的方式能夠將檔案傳輸到與接收自 FTP 伺服器,FreeBSD 內建了 FTP 伺服器軟體 ftpd 在基礎系統 (Base system) 中。 FreeBSD 提供了多個設定檔來控制對 FTP 伺服器的存取,本節將摘要這些檔案的設定方式,請參考 man:ftpd[8] 來取得更多有關內建 FTP 伺服器的詳細資訊。 === 設定 最重要的一個設定步驟便是決定那些帳號能夠存取 FTP 伺服器,FreeBSD 系統有數個系統帳號,這些帳號不應該能夠擁有 FTP 存取權,不允許存取 FTP 的使用者清單可在 [.filename]#/etc/ftpusers# 找到,預設該檔案內會有所有的系統帳號,其他不應允許存取 FTP 的使用者也可在此加入。 在某些情況可能會布望限制某些使用者的存取,而不是完全避免這些使用者使用 FTP,這可以透過建立 [.filename]#/etc/ftpchroot# 來完成,詳如 man:ftpchroot[5] 所述,這個檔案會列出受到 FTP 存取限制的使用者與群組。 要在伺服器上開啟匿名 FTP 存取權,可在 FreeBSD 系統上建立一個名稱為 `ftp` 使用者,使用者將能夠使用 `ftp` 或 `anonymous` 使用者名稱來登入 FTP 伺服器,當提示輸入密碼時,輸入任何值都會被接受,但是慣例上應使用電子郵件位址來當做密碼。當匿名使用者登入時 FTP 伺服器會呼叫 man:chroot[2] 來限制使用者只能存取 `ftp` 使用者的家目錄。 要設定顯示給 FTP 客戶端的歡迎訊息有兩個文字檔可以建立,[.filename]#/etc/ftpwelcome# 的內容會在收到登入提示前顯示給使用者看,登入成功能後,則會顯示 [.filename]#/etc/ftpmotd# 的內容。注意,這個檔案的路徑是相對於登入環境的,所以 [.filename]#~ftp/etc/ftpmotd# 的內容只會對匿名使用者顯示。 設定完 FTP 伺服器之後,在 [.filename]#/etc/rc.conf# 設定適當的變數來在開機時啟動該服務: [.programlisting] .... ftpd_enable="YES" .... 要立即啟動服務可: [source,shell] .... # service ftpd start .... 要測試到 FTP 伺服器的連線可輸入: [source,shell] .... % ftp localhost .... ftpd daemon 會使用 man:syslog[3] 來記錄訊息,預設,系統記錄 Daemon 會寫入有關 FTP 的訊息到 [.filename]#/var/log/xferlog#,FTP 記錄的位置可以透過更改 [.filename]#/etc/syslog.conf# 中下行來做修改: [.programlisting] .... ftp.info /var/log/xferlog .... [NOTE] ==== 要注意啟動匿名 FTP 伺服器可能的潛藏問題,尤其是要讓匿名使用者上傳檔案時要再次確認,因為這可能讓該 FTP 站變成用來交換未授權商業軟體的交流平台或者更糟的狀況。若真的需要匿名 FTP 上傳,那麼請檢查權限設定,讓這些檔案在尚未被管理者審查前不能夠被其他匿名使用者讀取。 ==== [[network-samba]] == Microsoft(TM)Windows(TM) 用戶端檔案與列印服務 (Samba) Samba 是熱門的開放源碼軟體套件,使用 SMB/CIFS 通訊協定提供檔案與列印服務,此通訊協定內建於 Microsoft(TM) Windows(TM) 系統,在非 Microsoft(TM) Windows(TM) 的系統可透過安裝 Samba 客戶端程式庫來支援此協定。此通訊協定讓客戶端可以存取共享的資料與印表機,這些共享的資源可掛載到一個本機的磁碟機,而共享的印表機則可以當做本機的印表機使用。 在 FreeBSD 上,可以使用 package:net/samba48[] Port 或套件來安裝 Samba 客戶端程式庫,這個客戶端提供了讓 FreeBSD 系統能存取 SMB/CIFS 在 Microsoft(TM) Windows(TM) 網路中共享的資源。 FreeBSD 系統也可以透過安裝 package:net/samba48[] Port 或套件來設定成 Samba 伺服器,這讓管理者可以在 FreeBSD 系統上建立 SMB/CIFS 的共享資源,讓執行 Microsoft(TM) Windows(TM) 或 Samba 客戶端程式庫的客戶端能夠存取。 === 伺服器設定 Samba 的設定位於 [.filename]#/usr/local/etc/smb4.conf#,必須先設定這個檔案才可使用 Samba。 要共享目錄與印表機給在工作群組中的 Windows(TM) 客戶端的簡易 [.filename]#smb4.conf# 範例如下。對於涉及 LDAP 或 Active Directory 的複雜安裝,可使用 man:samba-tool[8] 來建立初始的 [.filename]#smb4.conf#。 [.programlisting] .... [global] workgroup = WORKGROUP server string = Samba Server Version %v netbios name = ExampleMachine wins support = Yes security = user passdb backend = tdbsam # Example: share /usr/src accessible only to 'developer' user [src] path = /usr/src valid users = developer writable = yes browsable = yes read only = no guest ok = no public = no create mask = 0666 directory mask = 0755 .... ==== 全域設定 在 [.filename]#/usr/local/etc/smb4.conf# 中加入用來描述網路環境的設定有: `workgroup`:: 要提供的工作群組名稱。 `netbios name`:: Samba 伺服器已知的 NetBIOS 名稱,預設為主機的 DNS 名稱第一節。 `server string`:: 會顯示於 `net view` 輸出結果以及其他會尋找伺服器描述文字並顯示的網路工具的文字。 `wins support`:: 不論 Samba 是否要作為 WINS 伺服器,請不要在網路上開啟超過一台伺服器的 WINS 功能。 ==== 安全性設定 在 [.filename]#/usr/local/etc/smb4.conf# 中最重要的設定便是安全性模式以及後端密碼格式,以下項目管控的選項有: `security`:: 最常見的設定為 `security = share` 以及 `security = user`,若客戶端使用的使用者名稱與在 FreeBSD 主機上使用的使用者名稱相同,則應該使用使用者 (user) 層級的安全性,這是預設的安全性原則且它會要求客戶端在存取共享資源前先登入。 + 安全性為共享 (share) 層級時,客戶端存取共享資源不需要先使用有效的使用者名稱與密碼登入伺服器,在是在舊版 Samba 所採用的預設安全性模式。 `passdb backend`:: Samba 支援數種不同的後端認証模式,客戶端可以使用 LDAP, NIS+, SQL 資料庫或修改過的密碼檔來認証,建議的認証方式是 `tdbsam`,適用於簡易的網路環境且在此處說明,對於較大或更複雜的網路則較建議使用 `ldapsam`,而 `smbpasswd` 是舊版的預設值,現在已廢棄不使用。 ==== Samba 使用者 FreeBSD 使用者帳號必須對應 `SambaSAMAccount` 資料庫, 才能讓 Windows(TM) 客戶端存取共享資源,要對應既有的 FreeBSD 使用者帳號可使用 man:pdbedit[8]: [source,shell] .... # pdbedit -a username .... 本節只會提到一些最常用的設定,請參考 http://www.samba.org/samba/docs/man/Samba-HOWTO-Collection/[官方 Samba HOWTO] 來取得有關可用設定選項的額外資訊。 === 啟動 Samba 要在開機時啟動 Samba,可加入下行到 [.filename]#/etc/rc.conf#: [.programlisting] .... samba_server_enable="YES" .... 要立即啟動 Samba: [source,shell] .... # service samba_server start Performing sanity check on Samba configuration: OK Starting nmbd. Starting smbd. .... Samba 由三個獨立的 Daemon 所組成,nmbd 與 smbd daemon 可透過 `samba_enable` 來啟動,若同時也需要 winbind 名稱解析服務則需額外設定: [.programlisting] .... winbindd_enable="YES" .... Samba 可以隨時停止,要停止可輸入: [source,shell] .... # service samba_server stop .... Samba 是一套擁有能整合 Microsoft(TM) Windows(TM) 網路功能的複雜軟體套件,除了在此處說明的基礎設定,要取得更多的功能資訊,請參考 http://www.samba.org[http://www.samba.org]。 [[network-ntp]] == NTP 時間校對 隨著使用時間,電腦的時鐘會逐漸偏移,這對需要網路上電腦有相同準確度時間的許多網路服務來說是一個大問題。準確的時間同樣能確保檔案時間戳記的一致性。網路時間協定 (Network Time Protocol, NTP) 是一種在網路上可以確保時間準確的方式。 FreeBSD 內含 man:ntpd[8] 可設定來查詢其他 NTP 伺服器來同步電腦的時間或提供時間服務給其他在網路上的電腦。 本節將會介紹如何設定 FreeBSD 上的 ntpd,更進一步的說明文件可於 [.filename]#/usr/shared/doc/ntp/# 找到 HTML 格式的版本。 === NTP 設定 在 FreeBSD,內建的 ntpd 可用來同步系統的時間,Ntpd 要使用 man:rc.conf[5] 中的變數以及下一節會詳細說明的 [.filename]#/etc/ntp.conf# 來設定。 Ntpd 與網路中各節點的通訊採用 UDP 封包,在伺服器與 NTP 各節點間的防火牆必須設定成可允許進/出埠 123 的 UDP 封包。 ==== [.filename]#/etc/ntp.conf# 檔 Ntpd 會讀取 [.filename]#/etc/ntp.conf# 來得知要從那些 NTP 伺服器查詢時間,建議可設定多個 NTP 伺服器,來避免萬一其中一個伺服器無法連線或是時間不可靠的問題,當 ntpd 收到回應,它會偏好先採用較可信賴的伺服器。查詢的伺服器可以是來自本地網路的 ISP 所提供,也可從link:http://support.ntp.org/bin/view/Servers/WebHome[線上可公開存取的NTP 伺服器清單]中挑選,您可以選擇一個離您地理位置較近的伺服器並閱讀它的使用規則。也有 http://support.ntp.org/bin/view/Servers/NTPPoolServers[可公開存取的 NTP 池線上清單]可用,由一個地理區域所組織,除此之外 FreeBSD 提供了計劃贊助的伺服器池,`0.freebsd.pool.ntp.org`。 .[.filename]#/etc/ntp.conf# 範例 [example] ==== 這份簡單的 [.filename]#ntp.conf# 範例檔可以放心的使用,其中包含了建議的 `restrict` 選項可避免伺服器被公開存取。 [.programlisting] .... # Disallow ntpq control/query access. Allow peers to be added only # based on pool and server statements in this file. restrict default limited kod nomodify notrap noquery nopeer restrict source limited kod nomodify notrap noquery # Allow unrestricted access from localhost for queries and control. restrict 127.0.0.1 restrict ::1 # Add a specific server. server ntplocal.example.com iburst # Add FreeBSD pool servers until 3-6 good servers are available. tos minclock 3 maxclock 6 pool 0.freebsd.pool.ntp.org iburst # Use a local leap-seconds file. leapfile "/var/db/ntpd.leap-seconds.list" .... ==== 這個檔案的格式在 man:ntp.conf[5] 有詳細說明,以下的說明僅快速的帶過以上範例檔有用到的一些關鍵字。 預設 NTP 伺服器是可以被任何網路主機所存取,`restrict` 關鍵字可以控制有那些系統可以存取伺服器。`restrict` 支援設定多項,每一項可再更進一步調整前面所做的設定。範例中的設定授權本地系統有完整的查詢及控制權限,而遠端系統只有查詢時間的權限。要了解更詳細的資訊請參考 man:ntp.conf[5] 中的 `Access Control Support` 一節。 `server` 關鍵字可指定要查詢的伺服器,設定檔中可以使用多個 server 關鍵字,一個伺服器列一行。`pool` 關鍵字可指定伺服器池,Ntpd 會加入該伺服器池中的一或多台伺服器,直到數量滿足 `tos minclock` 的設定。`iburst` 關鍵字會指示 ntpd 在建立連線時執行 8 連發快速封包交換,可以更快的同步系統時間。 `leapfile` 關鍵字用來指定含有閏秒 (Leap second) 資訊的檔案位置,該檔案是由 man:periodic[8] 自動更新。這個關鍵字指定的檔案位置必須與 [.filename]#/etc/rc.conf# 中設定的 `ntp_db_leapfile` 相同。 ==== 在 [.filename]#/etc/rc.conf# 中的 NTP 設定項目 設定 `ntpd_enable="YES"` 可讓開機時會啟動 ntpd。將 `ntpd_enable=YES` 加到 [.filename]#/etc/rc.conf# 之後,可輸入以下指令讓 ntpd 不需重新開機立即啟動: [source,shell] .... # service ntpd start .... 要使用 ntpd 必須設定 `ntpd_enable`,以下所列的 [.filename]#rc.conf# 變數可視所需請況設定。 設定 `ntpd_sync_on_start=YES` 可讓 ntpd 可以在系統啟動時一次同步任何差距的時間,正常情況若時鐘的差距超過 1000 秒便會記錄錯誤並且中止。這個設定項目在沒有電池備援的時鐘上特別有用。 設定 `ntpd_oomprotect=YES` 可保護 ntpd daemon 被系統中止並嘗試從記憶體不足 (Out Of Memory, OOM) 的情況恢復運作。 設定 `ntpd_config=` 可更改 [.filename]#ntp.conf# 檔案的位置。 設定 `ntpd_flags=` 可設定使用任何其他所需 ntpd 參數,但要避免使用由 [.filename]#/etc/rc.d/ntpd# 內部控管的參數如下: * `-p` (pid 檔案位置) * `-c` (改用 `ntpd_config=` 設定) ==== 使用無特權的 `ntpd` 使用者執行 Ntpd 在 FreeBSD 上的 Ntpd 現在可以使用無特權的使用者啟動並執行,要達到這個功能需要 man:mac_ntpd[4] 規則模組。[.filename]#/etc/rc.d/ntpd# 啟動 Script 會先檢查 NTP 的設定,若可以的話它會載入 `mac_ntpd` 模組,然後以無特權的使用者 `ntpd` (user id 123) 來啟動 ntpd。為了避免檔案與目錄存取權限的問題,當設定中有任何檔案相關的選項時,啟動 Script 不會自動以 `ntpd` 身份啟動 ntpd。 在 `ntpd_flags` 若出現以下任何參數則需要以最下面的方式手動設定才能以 `ntpd` 使用者的身份執行: * -f 或 --driftfile * -i 或 --jaildir * -k 或 --keyfile * -l 或 --logfile * -s 或 --statsdir 在 [.filename]#ntp.conf# 若出現以下任何關鍵字則需要以最下面的方式手動設定才能以 `ntpd` 使用者的身份執行: * crypto * driftfile * key * logdir * statsdir 要手動設定以使用者 `ntpd` 身份執行 ntpd 你必須: * 確保 `ntpd` 使用者有權限存取所有在設定檔中指定的檔案與目錄。 * 讓 `mac_ntpd` 模組載入或編譯至核心,請參考 man:mac_ntpd[4] 取得詳細資訊。 * 在 [.filename]#/etc/rc.conf# 中設定 `ntpd_user="ntpd"` === 在 PPP 連線使用 NTP ntpd 並不需要永久的網際網路連線才能正常運作,若有一個 PPP 連線是設定成需要時撥號,那麼便需要避免 NTP 的流量觸發撥號或是保持連線不中斷,這可在 [.filename]#/etc/ppp/ppp.conf# 使用 `filter` 項目設定,例如: [.programlisting] .... set filter dial 0 deny udp src eq 123 # Prevent NTP traffic from initiating dial out set filter dial 1 permit 0 0 set filter alive 0 deny udp src eq 123 # Prevent incoming NTP traffic from keeping the connection open set filter alive 1 deny udp dst eq 123 # Prevent outgoing NTP traffic from keeping the connection open set filter alive 2 permit 0/0 0/0 .... 要取得更詳細的資訊,請參考於 man:ppp[8] 的 `PACKET FILTERING` 小節以及在 [.filename]#/usr/shared/examples/ppp/# 中的範例。 [NOTE] ==== 部份網際網路存取提供商會封鎖較小編號的埠,這會讓 NTP 無法運作,因為回應永遠無到傳送到該主機。 ==== [[network-iscsi]] == iSCSI Initiator 與 Target 設定 iSCSI is a way to share storage over a network. Unlike NFS, which works at the file system level, iSCSI works at the block device level. In iSCSI terminology, the system that shares the storage is known as the _target_. The storage can be a physical disk, or an area representing multiple disks or a portion of a physical disk. For example, if the disk(s) are formatted with ZFS, a zvol can be created to use as the iSCSI storage. The clients which access the iSCSI storage are called _initiators_. To initiators, the storage available through iSCSI appears as a raw, unformatted disk known as a LUN. Device nodes for the disk appear in [.filename]#/dev/# and the device must be separately formatted and mounted. FreeBSD provides a native, kernel-based iSCSI target and initiator. This section describes how to configure a FreeBSD system as a target or an initiator. [[network-iscsi-target]] === 設定 iSCSI Target To configure an iSCSI target, create the [.filename]#/etc/ctl.conf# configuration file, add a line to [.filename]#/etc/rc.conf# to make sure the man:ctld[8] daemon is automatically started at boot, and then start the daemon. The following is an example of a simple [.filename]#/etc/ctl.conf# configuration file. Refer to man:ctl.conf[5] for a more complete description of this file's available options. [.programlisting] .... portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group no-authentication portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... The first entry defines the `pg0` portal group. Portal groups define which network addresses the man:ctld[8] daemon will listen on. The `discovery-auth-group no-authentication` entry indicates that any initiator is allowed to perform iSCSI target discovery without authentication. Lines three and four configure man:ctld[8] to listen on all IPv4 (`listen 0.0.0.0`) and IPv6 (`listen [::]`) addresses on the default port of 3260. It is not necessary to define a portal group as there is a built-in portal group called `default`. In this case, the difference between `default` and `pg0` is that with `default`, target discovery is always denied, while with `pg0`, it is always allowed. The second entry defines a single target. Target has two possible meanings: a machine serving iSCSI or a named group of LUNs. This example uses the latter meaning, where `iqn.2012-06.com.example:target0` is the target name. This target name is suitable for testing purposes. For actual use, change `com.example` to the real domain name, reversed. The `2012-06` represents the year and month of acquiring control of that domain name, and `target0` can be any value. Any number of targets can be defined in this configuration file. The `auth-group no-authentication` line allows all initiators to connect to the specified target and `portal-group pg0` makes the target reachable through the `pg0` portal group. The next section defines the LUN. To the initiator, each LUN will be visible as a separate disk device. Multiple LUNs can be defined for each target. Each LUN is identified by a number, where LUN 0 is mandatory. The `path /data/target0-0` line defines the full path to a file or zvol backing the LUN. That path must exist before starting man:ctld[8]. The second line is optional and specifies the size of the LUN. Next, to make sure the man:ctld[8] daemon is started at boot, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... ctld_enable="YES" .... To start man:ctld[8] now, run this command: [source,shell] .... # service ctld start .... As the man:ctld[8] daemon is started, it reads [.filename]#/etc/ctl.conf#. If this file is edited after the daemon starts, use this command so that the changes take effect immediately: [source,shell] .... # service ctld reload .... ==== 認證 The previous example is inherently insecure as it uses no authentication, granting anyone full access to all targets. To require a username and password to access targets, modify the configuration as follows: [.programlisting] .... auth-group ag0 { chap username1 secretsecret chap username2 anothersecret } portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group ag0 portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... The `auth-group` section defines username and password pairs. An initiator trying to connect to `iqn.2012-06.com.example:target0` must first specify a defined username and secret. However, target discovery is still permitted without authentication. To require target discovery authentication, set `discovery-auth-group` to a defined `auth-group` name instead of `no-authentication`. It is common to define a single exported target for every initiator. As a shorthand for the syntax above, the username and password can be specified directly in the target entry: [.programlisting] .... target iqn.2012-06.com.example:target0 { portal-group pg0 chap username1 secretsecret lun 0 { path /data/target0-0 size 4G } } .... [[network-iscsi-initiator]] === 設定 iSCSI Initiator [NOTE] ==== The iSCSI initiator described in this section is supported starting with FreeBSD 10.0-RELEASE. To use the iSCSI initiator available in older versions, refer to man:iscontrol[8]. ==== The iSCSI initiator requires that the man:iscsid[8] daemon is running. This daemon does not use a configuration file. To start it automatically at boot, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... iscsid_enable="YES" .... To start man:iscsid[8] now, run this command: [source,shell] .... # service iscsid start .... Connecting to a target can be done with or without an [.filename]#/etc/iscsi.conf# configuration file. This section demonstrates both types of connections. ==== 不使用設定檔連線到 Target To connect an initiator to a single target, specify the IP address of the portal and the name of the target: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 .... To verify if the connection succeeded, run `iscsictl` without any arguments. The output should look similar to this: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Connected: da0 .... In this example, the iSCSI session was successfully established, with [.filename]#/dev/da0# representing the attached LUN. If the `iqn.2012-06.com.example:target0` target exports more than one LUN, multiple device nodes will be shown in that section of the output: [source,shell] .... Connected: da0 da1 da2. .... Any errors will be reported in the output, as well as the system logs. For example, this message usually means that the man:iscsid[8] daemon is not running: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Waiting for iscsid(8) .... The following message suggests a networking problem, such as a wrong IP address or port: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.11 Connection refused .... This message means that the specified target name is wrong: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Not found .... This message means that the target requires authentication: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Authentication failed .... To specify a CHAP username and secret, use this syntax: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 -u user -s secretsecret .... ==== 使用設定檔連線到 Target To connect using a configuration file, create [.filename]#/etc/iscsi.conf# with contents like this: [.programlisting] .... t0 { TargetAddress = 10.10.10.10 TargetName = iqn.2012-06.com.example:target0 AuthMethod = CHAP chapIName = user chapSecret = secretsecret } .... The `t0` specifies a nickname for the configuration file section. It will be used by the initiator to specify which configuration to use. The other lines specify the parameters to use during connection. The `TargetAddress` and `TargetName` are mandatory, whereas the other options are optional. In this example, the CHAP username and secret are shown. To connect to the defined target, specify the nickname: [source,shell] .... # iscsictl -An t0 .... Alternately, to connect to all targets defined in the configuration file, use: [source,shell] .... # iscsictl -Aa .... To make the initiator automatically connect to all targets in [.filename]#/etc/iscsi.conf#, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... iscsictl_enable="YES" iscsictl_flags="-Aa" ....