NOTA: Si busqueu el protocol de xarxa IP consulteu IP
ip és l'eina de nova generació pensada per substituir eines ("obsoletes") com ifconfig o route. Es proporcionada per LARTC (Linux Advanced Routing and Traffic Control)
Recursos:
http://linux-ip.net/html/tools-ip-address.html http://www.policyrouting.org/iproute2.doc.html#ss9.0 http://en.wikipedia.org/wiki/Iproute2
http://en.wikipedia.org/wiki/Iproute2
Ordres que substitueix i millora:
purpose | legacy "net-tools" | iproute2 |
---|---|---|
Address and link configuration | ifconfig | ip addr, ip link |
Routing tables | route | ip route |
Neighbors | arp | ip neigh |
VLAN | vconfig | ip link |
Tunnels | iptunnel | ip tunnel |
Multicast | ipmaddr | ip maddr |
Statistics | netstat | ss |
Normalment no caldrà instal·lar aquesta paquet perquè ja el trobareu instal·lat:
$ sudo apt-get install iproute
$ dpkg -L iproute /. /bin /bin/ip /sbin /sbin/rtmon /sbin/tc /sbin/rtacct /sbin/ss /usr /usr/bin /usr/bin/lnstat /usr/bin/nstat /usr/bin/routef /usr/bin/routel /usr/lib /usr/lib/tc /usr/lib/tc/m_xt.so /usr/lib/tc/q_atm.so /usr/lib/tc/experimental.dist /usr/lib/tc/normal.dist /usr/lib/tc/pareto.dist /usr/lib/tc/paretonormal.dist /usr/sbin /usr/sbin/arpd /usr/share /usr/share/man /usr/share/man/man8 /usr/share/man/man8/tc-bfifo.8.gz /usr/share/man/man8/ip.8.gz /usr/share/man/man8/routel.8.gz /usr/share/man/man8/rtacct.8.gz /usr/share/man/man8/rtmon.8.gz /usr/share/man/man8/ss.8.gz /usr/share/man/man8/tc-cbq-details.8.gz /usr/share/man/man8/tc-cbq.8.gz /usr/share/man/man8/tc-drr.8.gz /usr/share/man/man8/tc-htb.8.gz /usr/share/man/man8/tc-pfifo_fast.8.gz /usr/share/man/man8/tc-prio.8.gz /usr/share/man/man8/tc-red.8.gz /usr/share/man/man8/tc-sfq.8.gz /usr/share/man/man8/tc-tbf.8.gz /usr/share/man/man8/tc.8.gz /usr/share/man/man8/arpd.8.gz /usr/share/man/man8/lnstat.8.gz /usr/share/man/man8/tc-pfifo.8.gz /usr/share/man/man3 /usr/share/man/man3/libnetlink.3.gz /usr/share/doc /usr/share/doc/iproute /usr/share/doc/iproute/README.Debian /usr/share/doc/iproute/copyright /usr/share/doc/iproute/changelog.Debian.gz /etc /etc/iproute2 /etc/iproute2/ematch_map /etc/iproute2/rt_dsfield /etc/iproute2/rt_protos /etc/iproute2/rt_realms /etc/iproute2/rt_scopes /etc/iproute2/rt_tables /sbin/ip /usr/bin/ctstat /usr/bin/rtstat /usr/lib/tc/m_ipt.so /usr/share/man/man8/routef.8.gz /usr/share/man/man8/nstat.8.gz /usr/share/man/man8/ctstat.8.gz / usr/share/man/man8/rtstat.8.gz
Mostra les dades de la interfície de xarxa (similar a la sortida de ifconfig). Útil per saber si la interfície de xarxa té link (vegeu també mii-tool i/o ethtool)
Exemples:
$ sudo ip link show eth0 2: eth0: <NO-CARRIER,BROADCAST,MULTICAST,PROMISC,UP> mtu 1500 qdisc pfifo_fast state DOWN qlen 1000 link/ether 00:1d:09:59:10:39 brd ff:ff:ff:ff:ff:ff
Activar mode promiscu:
$ sudo ip link set eth0 promisc on
Per desactivar-lo:
$ sudo ip link set eth0 promisc off
Llegiu abans l'article VLAN, especialment la introducció.
Consulteu l'ajuda amb:
$ ip link add foo type vlan help Usage: ... vlan id VLANID [ FLAG-LIST ] [ ingress-qos-map QOS-MAP ] [ egress-qos-map QOS-MAP ] VLANID := 0-4095 FLAG-LIST := [ FLAG-LIST ] FLAG FLAG := [ reorder_hdr { on | off } ] [ gvrp { on | off } ] [ loose_binding { on | off } ] QOS-MAP := [ QOS-MAP ] QOS-MAPPING QOS-MAPPING := FROM:TO
Consulteu Linux_VLAN#Ordre_IP per a veure exemples.
Permet activar o desactivar una interfície de xarxa:
$ sudo ip link set dev eth0 up
Amb l'"obsoleta" ordre ifconfig seria:
$ sudo ifconfig eth0 up
L'ordre ip route s'utilitza per configurar les rutes i està pensada per substituir route. A diferència de route permet Policy Routing (route només permet encaminar segons la IP de destinació) Vegeu:
http://lartc.org/howto/lartc.iproute2.html#LARTC.IPROUTE2.WHY
i lartc.
Per exemple la comanda:
$ sudo route add -net 192.168.10.0 netmask 255.255.255.0 gw 192.168.1.20
És equivalent a:
$ sudo ip route add dev eth0 to 192.168.10.0/24 via 192.168.1.20
Per entendre les tècniques d'Advanced Routing cal entendre com el nucli del sistema encamina. Consulteu route selection
Per esborrar la cache de la taula de rutes:
$ sudo ip route flush cache
Per consultar la cache utilitzeu:
$ sudo ip route show cache
#!/bin/bash #During debugging, show pre-execution conditions echo ***Before echo ...Rules... ip ru sh echo ...Routes... ip ro sh echo ...Rules for table WAN1... ip ro sh table WAN1 echo ...Rules for table WAN2... ip ro sh table WAN2 echo #This script flushes all routes and rules, EXCEPT those specified to remain # Copyright, 2003, Carol Anne Ogdin. This script is freely available # for use under the terms of the GNU General Public License published at # http://www.gnu.org/copyleft/gpl.html. Any improvements/enhancements # gratefully accepted; send them to caogdin (at) deepwoods (dot) com. # (Constants for the script) # We must know the device names of interfaces (such as our local LAN, and lo) # that should NEVER be taken down, so we can retain LAN-based control of the # router (where our administrator is working). For AWK, they're separated # by an "or" operator (vertical bar) iifs="eth0|lo" # interfaces we never touch (awk regexp) # Next, we need to know the non-standard tables (if any) we use. Again,for # AWK, these need to be separated by vertical bars. # (In a future version, this information could be obtained by parsing # /etc/iproute2/rt_tables ours="WAN1|WAN2" # our table/lookup names used (awk regexp) # (End of constants) keepers="dev ($iifs)" # devices NOT to be removed tables="lookup ($ours)" # rules that look like this are to be removed # Initialize, and clean up any lingering stuff from prior test executions # Step 1: Remove all default route(s), if any # Note a condition of this script: Every ip ro sh and ip ru sh must # produce lines that are complete entries. The only exception is the # "default" route which is separately deleted first because, if you're # configured for "split access," (see LARTC) may display on several # successive lines. ip route delete default &>/dev/null # Always get rid of default first # How the AWK program is constructed to delete all routes on $iifs # $0 !~ $keepers {{ Select only lines that aren't to be kept # print "ip route delete "Issue the command-building command # $0 and output the routing table entry as arguments # | "bash" } Finally, pipe the constructed command to bash # Step 2: Remove main routes not excluded by $keepers ip route show | awk -v k="$keepers" '$0 !~ k \ { print " ip route delete " $0 | "bash" }' # Step 3: Remove all routes from our tables for wan in ${ours//|/ }; do ip route flush table $wan &>/dev/null done # Remove all our rules # How the AWK program is constructed to get the results we want # $0 ~ $tables {{ Select only lines that are to be removed # sub(/from all /,""); For those lines, delete any "from all " string # print "ip rule delete " Issue the command-building command # substr($0, 8) and output all except the rule # # | "bash" } Finally, pipe the constructed command to bash ip rule show | awk -v k="$tables" '$0 ~ k \ { sub(/from all/,""); print "ip rule delete " substr($0, 8) | "bash" }' ip route flush cache # Flush the cache so nothing lingers # End of GNU General Public Licensed script. # While testing this script: Show results. echo echo ***After echo ...Rules... ip ru sh echo ...Routes... ip ro sh echo ...Rules for table WAN1... ip ro sh table WAN1 echo ...Rules for table WAN2... ip ro sh table WAN2
ip rule add unicast from 192.168.100.17 table 5
és el mateix que:
ip rule add from 192.168.100.17 table 5
Altres exemples:
ip rule add unicast iif eth7 table 5 ip rule add unicast fwmark 4 table 4
Exemples:
ip rule add nat 193.7.255.184 from 172.16.82.184 ip rule add nat 10.40.0.0 from 172.40.0.0/16
Example 4.18. unreachable rule type
ip rule add unreachable iif eth2 tos 0xc0 ip rule add unreachable iif wan0 fwmark 5 ip rule add unreachable from 192.168.7.0/25
Example 4.19. prohibit rule type
ip rule add prohibit from 209.10.26.51 ip rule add prohibit to 64.65.64.0/18 ip rule add prohibit fwmark 7
Example 4.20. blackhole rule type
ip rule add blackhole from 209.10.26.51 ip rule add blackhole from 172.19.40.0/24 ip rule add blackhole to 10.182.17.64/28
Example 4.14. throw route types
ip route add throw default ip route add throw 10.79.0.0/16 ip route add throw 172.16.0.0/12
Example 4.8. broadcast route types
ip route add table local broadcast 10.10.20.255 dev eth0 proto kernel scope link src 10.10.20.67 ip route add table local broadcast 192.168.43.31 dev eth4 proto kernel scope link src 192.168.43.14
Example 4.9. local route types
ip route add table local local 10.10.20.64 dev eth0 proto kernel scope host src 10.10.20.67 ip route add table local local 192.168.43.12 dev eth4 proto kernel scope host src 192.168.43.14
Permet monitoritzar els esdeveniments de les targetes de xarxa del sistema:
$ sudo ip monitor all
Per exemple detectarà els link UP i link DOWN o els canvis a la taula arp. Per exemple
$ sudo ip monitor all 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae STALE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae STALE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae REACHABLE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae STALE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae REACHABLE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae STALE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae REACHABLE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae STALE 192.168.1.1 dev eth0 lladdr 00:25:69:3f:d5:ae REACHABLE
Específicament podeu monitoritzar les rutes amb:
$ sudo ip monitor route ... ff02::1:2 via ff02::1:2 dev alumnat metric 0 cache mtu 1500 advmss 1440 hoplimit 4294967295
IMPORTANT: Aquesta ordre només mostra les rutes que s'afegeixen o s'eliminen al sistema no mostra pas la cache de la taula de rutes. Consulteu ip route flush cache i ip route show cache
Ho podeu provar si executeu en una terminal:
$ sudo ip monitor route
I sense tancar aquesta terminal a un altre terminal modifiqueu les taules de rutes, per exemple:
$ sudo ip route add 192.168.0.0/24 via 192.168.1.1
Per l'altre terminal apareixerà:
192.168.0.0/24 via 192.168.1.1 dev wlan0
Si consulteu l'ajuda:
$ sudo ip monitor help Usage: ip monitor [ all | LISTofOBJECTS ]
Si no s'especifica res s'aplica all. Segons els manual ($ man ip) els objectes possibles són:
OBJECT := { link | addr | addrlabel | route | rule | neigh | tunnel | maddr | mroute | monitor }
Permet implementar Policy routing
Amb ip rule add podem afegir normes d'encaminament de forma que puguem definir Polítiques de rutes més elaborades que les utilitzades per defecte amb ordres com route (bàsicament route només permet definir rutes per IP de destinació)
$ sudo ip rule show 0: from all lookup local 32766: from all lookup main 32767: from all lookup default
El següent exemple envia a la taula John els paquets amb IP d'origen 10.0.0.10:
$ ip rule add from 10.0.0.10 table John
NOTA: La taula John cal que estigui especificada a: /etc/iproute2/rt_tables
$ ip rule del XXXXXXXXXXXXXX
On XXXXXXXX és el mateix que es va posar al fer el add. Si per exemple vam executar:
$ ip rule add from 10.0.0.10 table John
Cal posar:
ip rule del from 10.0.0.10 table John
NOTA: 0/0 indica tot (all)
Exemple:
# ip rule add from I.P.OF.PPP0 pri 200 table PPP0 # ip rule add from I.P.OF.PPP1 pri 300 table PPP1
On pri (o priority) controla la prioritat. Quan major és el número que s'indica MENOR és la prioritat. La prioritat va de 0 en endavant fins a la prioritat 32767 sent la 0 la més prioritària. Les taules per defecte són
$ sudo ip rule show 0: from all lookup local 32766: from all lookup main 32767: from all lookup default
És a dir la taula de rutes per a loopback/localhost és la de màxima prioritat i les taules main i default són les últimes taules. Normalment entre estos dos extrems estaran les polítiques explícites.
Recursos:
Cal afegir una nova norma a una nova taula:
Definim la nova taula de rutes:
$ sudo su # echo 200 John >> /etc/iproute2/rt_tables
Afegim la norma
# ip rule add from 10.0.0.10 table John
I la consultem:
# ip rule ls 0: from all lookup local 32765: from 10.0.0.10 lookup John 32766: from all lookup main 32767: from all lookup default
En aquest cas, abans de la taula principal (i després de local!) s'aplicarà una nova taula de rutes quan els paquet provinguin de la IP 10.0.0.10. Ara només cal definir la ruta especial per a la taula John
# ip route add default via 195.96.98.253 dev ppp2 table John # ip route flush cache
NOTA: A l'exemple no oblideu de configurar també les rutes locals!
Ara John utilitzarà un gateway que no és el gateway per defecte que apareix a l'ordre route!
Enrutament segons una marca establerta amb iptables:
Crear les taules:
# echo 200 PPP0 >> /etc/iproute2/rt_tables # echo 201 PPP1 >> /etc/iproute2/rt_tables
Afegir les dos entrades a la taula de rutes (xarxa local i default gw). L'exemple és amb una interfície PPP directament connectada a Internet.
# ip route add MY.GA.TE.WAY dev ppp0 table PPP0 # ip route add default via MY.GA.TE.WAY dev ppp0 table PPP0
i el mateix amb ppp1
# ip route add MY.GA.TE.WAY dev ppp1 table PPP1 # ip route add default via MY.GA.TE.WAY dev ppp1 table PPP1
IMPORTANT: Canvieu el valor MY.GA.TE.WAY per la IP dels vostres gateways als proveidor de serveis 1 i al 2!
Mostreu els canvis:
# ip route list table PPP0 MY.GA.TE.WAY dev ppp0 scope link default via MY.GA.TE.WAY dev ppp0 # ip route list table PPP1 MY.GA.TE.WAY dev ppp1 scope link default via MY.GA.TE.WAY dev ppp1
Ara marquem els paquets, per exemple marcarem els paquets d'un usuari concret:
$ sudo iptables -t mangle -A OUTPUT -m owner --uid-owner 108 -j MARK --set-mark 1
L'usuari té el UUID 108.
Alternativa que no sabem si funciona:
$ sudo iptables -t mangle -A OUTPUT -m owner --cmd-owner sshd -j MARK --set-mark 1
( another sidenote: AFAIK, the '--cmd-owner' flag does not work in recent ( >= 2.6.15 ) kernels
Ara afegim una norma d'enrutament:
# ip rule add fwmark 1 pri 100 table PPP1
Envia tot el que tingui la marca 1 a la taula PPP1.
Encara ens queda activar el SNAT
# iptables -t nat -A POSTROUTING -o ppp1 -j SNAT --to-source=I.P.OF.PPP1
O Masquerade si la IP no és fixa:
# iptables -t nat -A POSTROUTING -o ppp1 -j MASQUERADE
També cal desactivar rp_filter
# echo 0 > /proc/sys/net/ipv4/conf/ppp1/rp_filter
Ara cal assegurar-se que tots els paquets que entren per les interfícies de xarxa connectades a Internet, també utilizin la ruta que els asseguri que retornen per la mateixa targeta de xarxa:
# ip rule add from I.P.OF.PPP0 pri 200 table PPP0 # ip rule add from I.P.OF.PPP1 pri 300 table PPP1
FIxeu-vos que la prioritat d'aquestes dos normes ha de ser menor (número més alt!) que la norma ue qenvia cap a la taula PPP1 els paquets amb la marca 1.
Finalment la taula de normes ha de quedar:
# ip rule list 0: from all lookup local 100: from all fwmark 0x1 lookup PPP1 200: from I.P.OF.PPP0 lookup PPP0 300: from I.P.OF.PPP1 lookup PPP1 32766: from all lookup main 32767: from all lookup default
Recursos:
Permet simular una petició provocant que s'inicii l'algorisme de "routing selection". Quan s'acaba l'algorisme aleshores mostra els camí escollit.
NOTA: En certa manera és similar a fer un ping i després consultar la cache amb: $ ip route show cache
# ip -s route get 127.0.0.1/32 ip -s route get 127.0.0.1/32 local 127.0.0.1 dev lo src 127.0.0.1 cache <local> users 1 used 1 mtu 16436 advmss 16396 # ip -s route get 127.0.0.1/32 local 127.0.0.1 dev lo src 127.0.0.1 cache <local> users 1 used 2 mtu 16436 advmss 16396 TODO: Once the route cache has been emptied, new route lookups (if not by a packet, then manually with ip route get) will result in a new lookup to the kernel routing tables.
Suposem creada la taula 8.
# ip route add default via 205.254.211.254 table 8 # ip rule add tos 0x08 table 8 # ip route flush cache # ip rule show 0: from all lookup local 32765: from all tos 0x08 lookup 8 32766: from all lookup main 32767: from all lookup 253
Tingueu en compte que la nova norma s'afegeix. Ho podem canviar especificant l'opció prio i indican directament el número de prioritat. Ara qualsevol paquet que s'enruti en aquesta màquina provingui de la targeta de xarxa que provingui serà enviat a la taula 8. Si cap ruta de la taula 8 se li apliques (no és el cas ja que em definit una ruta per defecte) aleshores s'aplicaria la taula de següent prioritat (main).
# ip rule add from 192.168.100.17 tos 0x08 fwmark 4 table 7
Si tenim 2 ADSL i hi ha peticions que venen de l'exterior (per exemple accés a servidors web amb ports DNAT) i tenim policy routing cal assegurar-se que les peticions que venen per una línia són contestades per la mateixa línia. Consulteu:
http://lartc.org/lartc.html#AEN268
També es pot fer amb iptables, marques i remarcant els paquets que són d'un connexió ja establerta.
header 1 | header 2 | header 3 |
---|---|---|
row 1, cell 1 | row 1, cell 2 | row 1, cell 3 |
row 2, cell 1 | row 2, cell 2 | row 2, cell 3 |
Vegeu també arp
TODO
B.4. ip neighbor
Part of the iproute2 command suite, ip neighbor provides a command line interface to display the neighbor table (ARP cache), insert permanent entries, remove specific entries and remove a large number of entries. For peculiarities and commonalities of the iproute2 tools, refer to Section H.2, “Some general remarks about iproute2 tools”.
The more commonly used analog to ip neighbor show, arp -n displays the ARP cache in a possibly more recognizable format.
Example B.13. Displaying the ARP cache with ip neighbor show
[[email protected]]# ip neighbor show 192.168.99.254 dev eth0 lladdr 00:80:c8:f8:5c:73 nud reachable
On routers and other machines with large ARP caches, you may find you wish to look at the ARP cache only on a particular interface. By specifying the interface on which you wish to see the neighbor table, you can limit the output.
Example B.14. Displaying the ARP cache on an interface with ip neighbor show
[[email protected]]# ip neighbor show dev eth0 205.254.211.39 lladdr 00:02:b3:a1:b8:df nud delay 205.254.211.54 lladdr 00:d0:b7:80:ce:ce nud delay 205.254.211.179 lladdr 00:80:c8:f8:5c:72 nud reachable
Another way to limit the output is to specify the subnet in which you are interested. Simply append the subnet specification to the command.
Example B.15. Displaying the ARP cache for a particular network with ip neighbor show
[[email protected]]# ip neighbor show 192.168.100.0/24 192.168.100.1 dev eth3 lladdr 00:c0:7b:7d:00:c8 nud stale 192.168.100.17 dev eth0 lladdr 00:80:c8:e8:4b:8e nud reachable
Note that in the case of masq-gw, there are neighbor table entries for IPs on more than one interface, because masq-gw breaks the 192.168.100.0/24 network into two parts. This is an advanced technique described in fuller detail in Section 9.3, “Breaking a network in two with proxy ARP”.
In addition to displaying the neighbor table, it is possible to make static mappings. For paranoid systems administrators, who do not want to enable ARP on their networks or on particular links, the ip neighbor add command may prove useful. Refer to Section 2.3, “ARP filtering” for a discussion of the ramifications of disabling ARP.
In Example B.16, “Entering a permanent entry into the ARP cache with ip neighbor add”, let's assume that the service router is incapable of correctly answering ARP requests. The administrator of masq-gw could make a permanent entry in the ARP cache mapping 192.168.100.1 to the link layer address of service-router.
Example B.16. Entering a permanent entry into the ARP cache with ip neighbor add
[[email protected]]# ip neighbor add 192.168.100.1 lladdr 00:c0:7b:7d:00:c8 dev eth3 nud permanent
This creates an entry in the neighbor table which maps 192.168.100.1 to link layer address 00:c0:7b:7d:00:c8. Subsequent IP packets bound for 192.168.100.1 will be encapsulated in Ethernet frames with 00:c0:7b:7d:00:c8 in the destination bytes. This permanent mapping cannot be overridden by ARP. It would need to be removed with ip neighbor delete.
For those who insist on such a thing, there is support for creating and deleting proxy ARP entries with ip neighbor, although this has been deprecated. For a long discussion of this topic, see this discussion on the kernel mailing list. Other tools should be used to create proxy ARP entries. Refer to Section B.1, “arp”, Section 9.3, “Breaking a network in two with proxy ARP” and Section 2.2, “Proxy ARP”.
Example B.17. Entering a proxy ARP entry with ip neighbor add proxy
[[email protected]]# ip neighbor add proxy 192.168.100.1 dev eth0
Strangely, the ip neighbor show command does not display any entries added and deleted with ip neighbor add proxy, so arp is required to view these entries. In short, don't use ip neighbor add proxy.
Entries can also be modified at any time. This allows learned entries to be replaced with static entries if there's already an entry in the ARP cache for a specified IP.
Example B.18. Altering an entry in the ARP cache with ip neighbor change
[[email protected]]# ip neighbor add 192.168.99.254 lladdr 00:80:c8:27:69:2d dev eth3 RTNETLINK answers: File exists [[email protected]]# ip neighbor show 192.168.99.254 192.168.99.254 dev eth0 lladdr 00:80:c8:f8:5c:73 nud reachable [[email protected]]# ip neighbor change 192.168.99.254 lladdr 00:80:c8:27:69:2d dev eth3 [[email protected]]# ip neighbor show 192.168.99.254 192.168.99.254 dev eth0 lladdr 00:80:c8:27:69:2d nud permanent
To remove the entry we added above in Example B.16, “Entering a permanent entry into the ARP cache with ip neighbor add”, we could run the following command. This invalidates the entry forcing the NUD of the entry into failed state.
Example B.19. Removing an entry from the ARP cache with ip neighbor del
[[email protected]]# ip neighbor del 192.168.100.1 dev eth3 [[email protected]]# ip neighbor show dev eth3 192.168.100.1 nud failed
Subsequent attempts to reach the IP address 192.168.100.1 will require the generation of a new ARP request, which (you hope!) returns the new or currently available link layer address.
While I have never found a good use for the ip neighbor flush command, it is provided, and accepts a destination network address as an argument. Without a destination network address, an interface specification is required.
Example B.20. Removing learned entries from the ARP cache with ip neighbor flush
[[email protected]]# ip neighbor flush dev eth3
Although it is not commonly required, the ip neighbor tool is a convenient tool for displaying and altering the ARP cache (neighbor table).
Vegeu també ifconfig.
Podeu consultar la sintaxi utilitzant l'opció help:
$ sudo ip addr help Usage: ip addr {add|change|replace} IFADDR dev STRING [ LIFETIME ] [ CONFFLAG-LIST ] ip addr del IFADDR dev STRING ip addr {show|flush} [ dev STRING ] [ scope SCOPE-ID ] [ to PREFIX ] [ FLAG-LIST ] [ label PATTERN ] IFADDR := PREFIX | ADDR peer PREFIX [ broadcast ADDR ] [ anycast ADDR ] [ label STRING ] [ scope SCOPE-ID ] SCOPE-ID := [ host | link | global | NUMBER ] FLAG-LIST := [ FLAG-LIST ] FLAG FLAG := [ permanent | dynamic | secondary | primary | tentative | deprecated | dadfailed | temporary | CONFFLAG-LIST ] CONFFLAG-LIST := [ CONFFLAG-LIST ] CONFFLAG CONFFLAG := [ home | nodad ] LIFETIME := [ valid_lft LFT ] [ preferred_lft LFT ] LFT := forever | SECONDS
Per configurar a nivell IP una interfície de xarxa podeu utilitzar la següent sintaxi:
$ ip addr add IP/NETMASK brd BROADCAST-ADDR dev INTERFACE.VID
Un exemple:
$ sudo ip addr add 192.168.100.1/24 brd 192.168.100.255 dev eth0
Amb ifconfig (comanda "obsoleta") seria:
$ sudo ifconfig eth0 192.168.100.1/24
Primer consulteu-la amb:
$ sudo ip addr ... 2: eth0: <BROADCAST,MULTICAST,PROMISC> mtu 1500 qdisc pfifo_fast state DOWN qlen 1000 link/ether 00:1d:09:59:10:39 brd ff:ff:ff:ff:ff:ff inet 192.168.1.249/24 brd 192.168.1.255 scope global eth0
El que està en negreta és el que cal utilitzar per eliminar la configuració:
$ sudo ip addr del 192.168.1.249/24 brd 192.168.1.255 dev eth0
NOTA: Fixeu-vos que la mateixa comanda que s'utilitza per afegir una adreça IP es pot "reutilitzar" per a eliminar-la només canviant add per del
IMPORTANT: Observeu que no cal definir cap nom especial a la interfície de xarxa, és a dir no cal el format TARGETA_FISICA:ALIASING. També observeu que no hi ha manera de veure les adreces IP extres afegides per la comanda ip amb l'ordre ifconfig.
Consulteu IP_Aliasing#Ip_aliasing_amb_l.27ordre_ip.
Vegeu també IP Aliasing.
Consulteu Policy_Routing#Guardar_els_canvis_de_forma_permanent per veure un exemple de com combinar els scripts d'arrancada de xarxa de ifupdown (carpetes .d de /etc/network) i el fitxer /etc/rc.local.
NOTA: A rc.local es posa el que es vol estar segur que només s'executa un cop. Als altres scripts per evitar múltiples execucions només s'executa el que cal un sol cop a cada interfície de xarxa.
Si teniu un ruter o màquina connectat a més d'una línia ADSL, en algun moment us trobareu que voleu accedir des de Internet a aquest router i us plantejareu la opció d'accedir-hi des de qualsevol dels dos routers. Si tenim la màquina configurada amb taules de rutes normals (sense policy routing, configurades amb l'ordre route en comptes de l'ordre ip) només un dels dos routers ADSL serà el gateway per defecte.
Imagineu el següent esquema:
/------\ ISP1 +----------+ /- -\ +--------------+ | / Internet |----| | Firewall |----- Red Interna \ -/ +--------------+ | \-------/ ISP2 +----------+
ISP1: Router ADSL multilloc
ISP2: Router ADSL monolloc
Si la taula de rutes del router és només:
$ route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 80.32.57.64 0.0.0.0 255.255.255.192 U 0 0 0 internet2 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 intranet 192.168.11.0 0.0.0.0 255.255.255.0 U 0 0 0 internet1 0.0.0.0 192.168.11.1 0.0.0.0 UG 100 0 0 internet1
Si des de una màquina d'Internet feu un ping al ISP2:
$ ping 80.32.57.101 PING 80.32.57.101 (80.32.57.101) 56(84) bytes of data. ^C --- 80.32.57.101 ping statistics --- 117 packets transmitted, 0 received, 100% packet loss, time 116169ms
Veureu que no respon. Però el paquet podeu comprovar que arriba a la màquina per la interfície que pertoca (internet2):
$ sudo tcpdump -n -i internet2 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on internet2, link-type EN10MB (Ethernet), capture size 96 bytes 05:29:12.840780 IP 80.103.175.51 > 80.32.57.101: ICMP echo request, id 28754, seq 10, length 64 05:29:13.848222 IP 80.103.175.51 > 80.32.57.101: ICMP echo request, id 28754, seq 11, length 64 05:29:14.856897 IP 80.103.175.51 > 80.32.57.101: ICMP echo request, id 28754, seq 12, length 64 ...
El problema és que el paquet de resposta surt pel gateway per defecte que és el connectat a la interfície internet1 en comptes de tornar per la mateixa interfície de xarxa (internet2):
$ sudo tcpdump -n -i internet1 not port 22 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on internet1, link-type EN10MB (Ethernet), capture size 96 bytes 05:31:03.298757 IP 80.32.57.101 > 80.103.175.51: ICMP echo reply, id 28754, seq 120, length 64 05:31:04.298311 IP 80.32.57.101 > 80.103.175.51: ICMP echo reply, id 28754, seq 121, length 64 05:31:05.297868 IP 80.32.57.101 > 80.103.175.51: ICMP echo reply, id 28754, seq 122, length 64 ...
Anem a veure com ho podem solucionar amb policy routing. Primer cal configurar una taula de rutes per la internet2. Afegiu noves taules de rutes al fitxer /etc/iproute2/rt_tables:
$ sudo joe /etc/iproute2/rt_tables
Afegiu les línies:
200 internet1 201 internet2
NOTA: La taula internet1 ja la creem tot i que en aquest article no al utilitzarem . El nom de la taula de rutes no té perquè ser el mateix que el de la interfície. El número indica la prioritat de la taula. Busqueu més informació a aquest mateix article i a l'ordre ip
Consulteu la taula de rutes per defecte:
$ sudo ip route list 80.32.57.64/26 dev internet2 proto kernel scope link src 80.32.57.101 192.168.1.0/24 dev intranet proto kernel scope link src 192.168.1.5 192.168.11.0/24 dev internet1 proto kernel scope link src 192.168.11.2 default via 192.168.11.1 dev internet1 metric 100
La taula de rutes internet2 encara està buida:
$ sudo ip route list table internet2
Afegim rutes a la taula de rutes 2. Es pot fer fàcilment copiant les rutes de la taula per defecte, la sintaxi és:
$ sudo ip route add RUTA_COPIADA_DE_LA_TAULA_PER_DEFECTE table internet2
És a dir:
$ sudo ip route add 80.32.57.64/26 dev internet2 proto kernel scope link src 80.32.57.101 table internet2 $ sudo ip route add 192.168.1.0/24 dev intranet proto kernel scope link src 192.168.1.5 table internet2 $ sudo ip route add 192.168.11.0/24 dev internet1 proto kernel scope link src 192.168.11.2 table internet2
ara ja teniu rutes a la taula 2:
$ sudo ip route list table internet2 80.32.57.64/26 dev internet2 proto kernel scope link src 80.32.57.101 192.168.1.0/24 dev intranet proto kernel scope link src 192.168.1.5 192.168.11.0/24 dev internet1 proto kernel scope link src 192.168.11.2
Ara només falta el gateway per defecte. A aquesta taula el gateway per defecte serà el del ISP de la connexió internet2: 80.32.57.65. Per tant:
$ sudo ip route add default via 80.32.57.65 dev internet2 metric 100 table internet2
Ara la taula de rutes internet2 queda:
$ sudo ip route list table internet2 80.32.57.64/26 dev internet2 proto kernel scope link src 80.32.57.101 192.168.1.0/24 dev intranet proto kernel scope link src 192.168.1.5 192.168.11.0/24 dev internet1 proto kernel scope link src 192.168.11.2 default via 80.32.57.65 dev internet2 metric 100
Aquesta taula de rutes però encara no l'utilitza ningú. Cal afegir alguna norma (policy) de rutes.
NOTA: El que anem a fer ara és quelcom similar al que es fa a l'article Load_Balancing#Squid_i_tcp_outgoing_address
Li diem al router que els paquets amb IP d'origen la IP de la interfície internet1 surtin per la taula internet1 i el mateix amb els paquets amb IP d'origen la de la ip de la interfície internet2:
$ sudo ip rule add from 80.32.57.101 table internet2
Si creesim la taula internet1 també faríem:
$ sudo ip rule add from 192.168.11.2 table internet1
Ara els pings ja contesten.
Per a comprovar el policy routing podeu utilitzar l'ordre traceroute:
$ sudo traceroute -n -s 80.32.57.101 www.google.com traceroute to www.google.com (66.249.92.104), 30 hops max, 60 byte packets 1 80.32.57.65 4.567 ms 4.560 ms 4.742 ms 2 10.0.209.129 42.872 ms 45.306 ms 47.519 ms 3 80.58.53.20 51.030 ms 53.645 ms 56.080 ms 4 84.16.6.69 109.057 ms 109.542 ms 110.231 ms 5 84.16.13.126 86.809 ms 84.16.13.142 89.503 ms 92.189 ms 6 84.16.6.106 110.836 ms 84.16.6.98 107.998 ms 110.953 ms 7 209.85.250.142 113.969 ms 78.295 ms 78.643 ms 8 64.233.175.115 74.147 ms 74.547 ms 74.381 ms 9 66.249.92.104 78.795 ms 77.541 ms 77.295 ms
Fixeu-vos que surt pel gateway del ISP2. En canvi amb l'altre IP:
$ sudo traceroute -n -s 192.168.11.2 www.google.com traceroute to www.google.com (66.249.92.104), 30 hops max, 60 byte packets 1 192.168.11.1 2.389 ms 2.668 ms 2.951 ms 2 * * * 3 10.4.13.29 18.271 ms 19.313 ms 20.802 ms 4 212.145.1.238 23.072 ms 24.005 ms 24.889 ms 5 217.130.2.225 36.108 ms 36.478 ms 37.652 ms 6 * * * 7 * * * 8 85.205.24.225 27.876 ms 85.205.24.229 25.932 ms 26.266 ms 9 195.81.200.209 27.413 ms 85.205.1.254 27.527 ms 28.117 ms 10 89.202.161.22 43.928 ms 216.239.49.230 28.574 ms 28.469 ms 11 74.125.50.105 62.854 ms 209.85.240.28 44.139 ms 44.313 ms 12 209.85.250.142 44.536 ms 66.249.95.24 43.602 ms 209.85.250.142 45.392 ms 13 64.233.175.115 69.461 ms 54.987 ms 49.192 ms 14 66.249.92.104 44.309 ms 44.293 ms 43.894 ms
NOTA: Consulteu abans l'apartat anterior Multigateway
Continuem amb el mateix esquema que l'apartat anterior. Ara però volem fer DNAT (el que comunament es coneix com obrir un port o Port Forwarding). La idea és accedir al servidor web (Apache) d'una màquina de la xarxa interna, les dades de la màquina són;
Això ho fem amb iptables:
$ sudo iptables -t nat -A PREROUTING -i internet2 -p tcp --dport 8090 -j DNAT --to=192.168.1.7:80
Fixeu-vos que la connexió es farà des de la internet2, és a dir volem que el servidor web sigui accessible amb la URL:
http://80.32.57.101:8090/
Si ho proveu us donarà un error. Si tornem a depurar:
$ sudo watch iptables -nvL -t nat Every 2,0s: iptables -nvL -t nat Fri Jul 16 06:07:50 2010 Chain PREROUTING (policy ACCEPT 1446 packets, 202K bytes) pkts bytes target prot opt in out source destination 2 120 DNAT tcp -- internet2 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8090 to:192.168.0.7:80 ...
Com podeu veure la norma s'aplica (2 paquets al contador de l'exemple) i els paquets arriben:
Si feu un nmap al port us apareixerà com filtrat:
$ nmap -p 8090 80.32.57.101 Starting Nmap 5.00 ( http://nmap.org ) at 2010-07-16 05:59 CEST Interesting ports on 101.Red-80-32-57.staticIP.rima-tde.net (80.32.57.101): PORT STATE SERVICE 8090/tcp filtered unknown
I també podeu veure com rebeu els paquets:
$ sudo tcpdump -n -i internet2 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on internet2, link-type EN10MB (Ethernet), capture size 96 bytes 06:11:19.094266 IP 80.103.175.51.45276 > 80.32.57.101.8090: Flags [S], seq 2436355941, win 5840, options [mss 1452,sackOK,TS val 29128727 ecr 0,nop,wscale 6], length 0
Per saber per que no funciona cal tenir en compte el camí que segueix un paquet al nucli del sistema operatiu Linux:
Citant http://bulma.net/body.phtml?nIdNoticia=2145:
Cuando un paquete va del cliente al servidor, lo primero que se encuentra (que sea relevante para esta explicación) es la lista PREROUTING de la tabla nat, donde se hace el DNAT. En el DNAT se cambia la dirección destino del paquete, y al enrutarse posteriormente, como el kernel ve que va dirigido al servidor, mete el paquete hacia la red interna.
El problema está en que cuando las respuestas del servidor hacia el cliente pasan por el firewall, no se deshace el DNAT antes del enrutado. El kernel primero enrutará el paquete y luego le cambiará la IP origen, deshaciendo el DNAT. ¡Pero nuestro policy routing estaba enrutando según la dirección origen! Ahí esta el problema, no podemos enrutar por dirección origen los paquetes que son respuesta de otro que sufrió un proceso de DNAT.
La solució és encaminar per marques combinant iptables i iproute utilitzant el mòdul d'iptables connection track match ( no confondre amb el mòdul conntrack) que s'encarrega de mantindre les taules de NAT al kernel que permeten fer i desfer NAT (tant SNAT com DNAT).
Cal afegir les següent normes ABANS del DNAT:
$ sudo iptables -t mangle -I PREROUTING 1 -m conntrack --ctorigdst 80.32.57.101 -j MARK --set-mark=2
IMPORTANT: Amb -I fem un insert i així afegim les normes abans de la norma de DNAT
Comproveu que els paquets es marquen executant:
$ sudo watch iptables -nvL -t mangle Every 2,0s: iptables -nvL -t mangle Fri Jul 16 06:38:37 2010 Chain PREROUTING (policy ACCEPT 1073 packets, 96360 bytes) pkts bytes target prot opt in out source destination 5 300 MARK all -- * * 0.0.0.0/0 0.0.0.0/0 ctorigdst 80.32.57.101 MARK xset 0x2/0xffffffff ...
I tornant a demanar la pàgina:
http://80.32.57.101:8090
Ara només falta que encaminem segons la marca:
$ sudo ip rule add fwmark 2 table internet2
Consulteu com queden les normes de Policy Routing:
$ sudo ip rule list 0: from all lookup local 32764: from all fwmark 0x2 lookup internet2 32765: from 80.32.57.101 lookup internet2 32766: from all lookup main 32767: from all lookup default
IMPORTANT: També cal que la màquina interna (a l'exemple 192.168.1.7) tingui com a gateway el firewall sobre el que estem aplicant les normes!
Recursos:
Suposeu el següent esquema:
Cal afegir una nova taula:
$ sudo joe /etc/iproute2/rt_tables # # reserved values # 255 local 254 main 253 default 0 unspec # # local # #1 inr.ruhep 200 guifi
Per tal que el sistema comenci a aplicar aquesta taula:
$ sudo ip route flush table guifi
Si consulteu la taula per defecte:
$ sudo ip route show 172.31.255.254 dev ppp0 proto kernel scope link src 85.49.2.201 192.168.93.0/24 dev internet3 proto kernel scope link src 192.168.93.2 192.168.92.0/24 dev internet2 proto kernel scope link src 192.168.92.2 192.168.111.0/24 dev internet1 proto kernel scope link src 192.168.111.19 192.168.10.0/24 dev intranet proto kernel scope link src 192.168.10.1 default dev ppp0 scope link
NOTA: L'ordre anterior és equivalent a $ route -n, route només mostra la taula per defecte
Ara consulteu la taula nova:
$ sudo ip route show table guifi
Com l'acabem de crear està buida. Anem a afegir una entrada cap a la xarxa guifi.net. Per fer-ho a la taula de rutes per defecte seria:
$ sudo route add -net 10.0.0.0 netmask 255.0.0.0 gw 192.168.92.1
NOTA: guifi.net és una xarxa privada de classe A: 10.0.0.0/8 o 10.0.0.0/255.0.0.0
A la taula per defecte quedaria:
$ sudo ip route show 172.31.255.254 dev ppp0 proto kernel scope link src 85.49.2.201 192.168.93.0/24 dev internet3 proto kernel scope link src 192.168.93.2 192.168.92.0/24 dev internet2 proto kernel scope link src 192.168.92.2 192.168.111.0/24 dev internet1 proto kernel scope link src 192.168.111.19 192.168.10.0/24 dev intranet proto kernel scope link src 192.168.10.1 10.0.0.0/8 via 192.168.92.1 dev internet2 default dev ppp0 scope link
Però no volem posar-ho en aquesta taula:
$ sudo route del -net 10.0.0.0 netmask 255.0.0.0 gw 192.168.92.1
Per afegir rutes a taules que no siguin la per defecte cal utilitzar ip route.
$ sudo ip route add table guifi 10.0.0.0/8 via 192.168.92.1 dev internet2
Ara la taula ja té una ruta:
$ sudo ip route show table guifi 10.0.0.0/8 via 192.168.92.1 dev internet2
Ara només cal utilitzar aquesta ruta afegir una política de rutes (ip rule). Per defecte només s'apliquen les polítiques per defecte:
$ sudo ip rule show 0: from all lookup local 32766: from all lookup main 32767: from all lookup default
Per afegir una nova norma:
$ sudo ip rule add from 192.168.10.45 lookup guifi 0: from all lookup local 32765: from 192.168.10.45 lookup guifi 32766: from all lookup main 32767: from all lookup default
Ara només queda afegir el SNAT:
$ sudo iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -o internet2 -j MASQUERADE
L'única màquina que utilitza aquest gateway és la 192.168.10.45. Qualsevol altre (inclòs el router!) surt pel gateway per defecte del router.