Bridge или как обьединять сетевые интерфейсы
Бридж (англ. bridge, мост) - это способ соединения двух сегментов Ethernet на канальном уровне, т.е. без использования протоколов более высокого уровня, таких как IP. Пакеты передаются на основе Ethernet-адресов, а не IP-адресов (как в маршрутизаторе). Поскольку передача выполняется на канальном уровне (уровень 2 модели OSI), все протоколы более высокого уровня прозрачно проходят через мост.
Термины коммутатор, мост и бридж могут использоваться на данной странице как взаимознаменяемые.
Код bridge в Linux является частичной реализацией стандарта ANSI/IEEE 802.1d. Впервые бриджинг в Linux появился в 2.2, затем код был переписан Леннертом Буйтенхеком (Lennert Buytenhek). Код bridge интегрирован в ядра серий 2.4 и 2.6. Железо - Intel Pentum 133 - RAM 32 mb - hdd 1024 mb - 2 сетевые карты 100 Mbps или 1000 Mbps (можно и больше, но желательно одинаковые).
Установка ПО Ставим Linux Debian с минимумом пакетов, сеть не настраиваем. После установки Debian ставим несколько необходимых пакетов:
Код:
# apt-get mc # apt-get install bridge-utils # apt-get install iproute # apt-get install iftop # apt-get install bmon # apt-get install openssh-server # apt-get install iperf
Настройка моста
Узнаем где наши сетевые карты
Код:
# ifconfig
eth1 Link encap:Ethernet HWaddr 00:19:5B:88:B2:85
inet6 addr: fe80::219:5bff:fe88:c287/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3871824 errors:0 dropped:0 overruns:0 frame:0
TX packets:4707022 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1031462268 (983.6 MiB) TX bytes:1375550080 (1.2 GiB)
Interrupt:10 Base address:0x6200
eth2 Link encap:Ethernet HWaddr 00:19:5B:88:C7:86
inet6 addr: fe80::219:5bff:fe88:c288/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4707923 errors:0 dropped:0 overruns:0 frame:0
TX packets:3855788 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1377378066 (1.2 GiB) TX bytes:1020322438 (973.0 MiB)
Interrupt:9 Base address:0x6300
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:56 errors:0 dropped:0 overruns:0 frame:0
TX packets:56 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:4396 (4.2 KiB) TX bytes:4396 (4.2 KiB)
Настройки сети в Linux Debian находятся в файле /etc/network/interfaces У меня на мосте он имеет такой вид: Код:
- The loopback network interface
auto lo iface lo inet loopback
Создаём скрипт /etc/network/if-up.d/bridge
Код:
#!/bin/sh
- Чистим настройки от предыдущего запуска скрипта
ifconfig br0 down # Отключаем интерфейс моста ifconfig eth1 down # Отключаем сетевую карту eth1 ifconfig eth2 down # Отключаем сетевую карту eth2 brctl delbr br0 # Удаляем имя моста
- Запускаем бридж
brctl addbr br0 # Задаём имя бриджу brctl addif br0 eth1 # Указываем какие интерфейсы brctl addif br0 eth2 # работают в режиме моста.
brctl stp br0 off # Отключаем режим STP
# brctl setfd br0 15 # Актуально только при # brctl setageing br0 60 # использовании STP
- Задаём IP моста, для дальнейшего управления им через ssh
ifconfig br0 192.168.110.251 netmask 255.255.0.0 broadcast 192.168.255.255
- Удаляем IP сетевых карт
ifconfig eth1 0.0.0.0 ifconfig eth2 0.0.0.0
- Поднимаем интерфейсы сетевых карт и моста
ifconfig eth1 up ifconfig eth2 up ifconfig br0 up
В принципе мост готов к использованию, надо только перезагрузить компьютер или выполнить скрипт (не забудьте его сделать запускаемым от имени root 774 Код:
# chgrp root /etc/network/if-up.d/bridge # chown root /etc/network/if-up.d/bridge # chmod 774 /etc/network/if-up.d/bridge
Настройка маршрутизации
Может возникнуть необходимость указать с какой стороны находится тот или иной компьютер. Дописываем в наш скрипт следующие команды:
- Сообщаем что ip 192.168.110.200 находится со стороны eth1
Код:
route add -host 192.168.110.200 dev eth1
- Сообщаем что ip 192.168.88.250 находится со стороны eth2
Код:
route add -host 192.168.88.250 dev eth2
- Сообщаем мосту с какой стороны сеть 192.168.55.0/24 (255.255.255.0)
Код:
route add -net 192.168.55.0/24 dev eth1
После таких настроек ваш мост станет немного умнее. Теперь для проверки маршрутизации набираем команду: Код:
# route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.110.200 * 255.255.255.255 UH 0 0 0 eth1 192.168.88.250 * 255.255.255.255 UH 0 0 0 eth2 192.168.55.0 * 255.255.255.0 U 0 0 0 eth1 localnet * 255.255.0.0 U 0 0 0 br0
Удалённое управление мостом
Входим на мост удалённо как пользователь root (под root лучше не работать): Код:
# ssh root@192.168.110.251
Теперь можно работать с мостом как с настольным компьютером в текстовом режиме.
Мониторинг и управление
- Удобная утилита для просмотра загрузки сети и мостаю
Код:
bmon
- Ещё не менее полезная утилита мониторинга сети
Код:
iftop -i br0
- инф. о сетевых интерфейсах
Код:
ifconfig
- поднять (убить) сетевой интерфейс
Код:
ifconfig eth1 up (down)
- инф. о мосте
Код:
brctl show
- таблица MAC-адресов моста
Код:
brctl showmacs br0
- ARP-таблица
Код:
arp -a
- Снифер
Код:
tcpdump host 192.168.110.100
Выдержка из man: NAME
bridge-utils-interfaces - bridge-utils extensions for the interfaces(5)
file format
DESCRIPTION
/etc/network/interfaces contains network interface configuration
information for the ifup(8) and ifdown(8) commands. This manpage
describes the bridge extensions to the standard interfaces(5) file
format.
The main extension is the bridge_ports option, with it you describe
that the interface is a bridge and what ports does it have. These ports
are the interfaces that are part of the bridge, and they shouldn't have
any stanzas defining them on the interfaces file. Other extensions
allow you to tune the bridge options or change a bridge behaviour.
We'll see this with an example:
auto br0
iface br0 inet static
address 192.168.1.2
network 192.168.1.0
netmask 255.255.255.0
broadcast 192.168.1.255
gateway 192.168.1.1
bridge_ports all
Well, after setting this, an ifup br0, or the next reboot, should let
you have a bridge up and running, after waiting for the ports to get to
the forwarding status, of course. This bridge will be using all your
ethX interfaces, as we have stated on the bridge_ports line.
The Debian bridge setup scripts will wait for it to get ready to work.
They do this by trying to guess the maximum time that the bridge will
need to get to the forwarding status, and by default, they will wait
for the bridge to get there, or for the estimated maximum time to go
by. This is done so that the services that are loaded after the bridge
setup have a working network interface and don't fail because the
bridge is still not working. See bridge_maxwait if you want to change
this behaviour.
An example of how to setup a so called anonymous bridge (a bridge
without an assigned IP) would look like this:
iface br1 inet manual
bridge_ports eth1 eth2
bridge_maxwait 0
Here we select the interfaces eth1 and eth2 to be added to the bridge
interface br1, which will be an anonymous bridge, we also tell the
scripts not to wait, as we won't be having any service running on that
interface (it doesn't even have an IP).
An example of a little more complex bridge setup could be:
auto br0
iface br0 inet static
address 192.168.1.2
network 192.168.1.0
netmask 255.255.255.0
broadcast 192.168.1.255
bridge_ports all weird0
bridge_bridgeprio 32767
bridge_portprio eth0 129
bridge_fd 5
In this example we select all the eth* devices plus a weird device to
be added to the bridge, also we change the bridge default priority to a
higher one so that this bridge becomes the root (if there are no
bridges with higher priority on the net, that is) and also we lower
priority of port eth0 so that it is not used if there are other ports
with higher priority to reach the same destination, at the end we lower
the default forward delay.
If there is a need to set up any of the interfaces participating on the
bridge and not the bridge itself, then we must add the commands to set
up those settings in a "pre-up" or "up" statement. This means that if
we have a wireless card that we want to add to a bridge and we want to
set it to master, and select the essid, instead of using the typical
wireless_* commands we could add to the bridge definition something
like this:
pre-up iwconfig wlan0 mode master essid myESSID
Be aware, however, that using wireless cards as part of a bridge is not
a good idea if the card belonging to the bridge is in managed mode.
Trying to bridge packets coming out of our LAN through a wireless card
that is set in managed mode (the card is a client of an AP) is bound to
give problems, as the AP will probably refuse packets with source MAC
addresses which are not associated (this will be the case of other
machines going through the wireless card of the bridge into the AP).
Multiple stanzas of a bridge definition are currently not supported, so
if you want to add a ipv6 and a ipv4 to a bridge do it all in one
definition by using the "up" option. If however you still want to use
multiple stanzas or would like to read more on this bug you can see it
at http://bugs.debian.org/319832
IFACE OPTIONS
A little explanation on the new options that can be used on
/etc/network/interfaces to setup the bridge, so you don't have to go
and look at the scripts...
bridge_ports interface specification
this option must exist for the scripts to setup the bridge, with
it you specify the ports you want to add to your bridge, either
using "none" if you want a bridge without any interfaces or you
want to add them later using brctl, or a list of the interfaces
you want to add separated by spaces, for example:
bridge_ports eth0 eth4
You should not put any lines to configure the interfaces that
will be used by the bridge, as this will be setup automatically
by the scripts when bringing the bridge up.
If you need to specify the interfaces more flexibly, you can use
the following syntax (most useful on a Xen dom0):
bridge_ports regex (eth|vif).*
This means to evaluate (as in egrep(1)) the expressions that
follow after "regex" until either the end or a "noregex"
statement is reached. The regular expressions are evaluated
against all local interfaces and those that match are added.
Specifying "all" is short for "regex eth.* em.* p[0-9].*
noregex" and will get all the ethX and biosdevname-format (emX
and pX) interfaces added to the bridge.
Carrying this to the extremes, the following is valid syntax:
bridge_ports all regex if.0 noregex ext0 regex vif.*
This will add all ethX interfaces, the ifX0 interfaces, the ext0
interface and all vifX interfaces.
bridge_ageing time
set ageing time, default is 300, can have a fractional part.
bridge_bridgeprio priority
set bridge priority, priority is between 0 and 65535, default is
32768, affects bridge id, lowest priority bridge will be the
root.
bridge_fd time
set bridge forward delay to time seconds, default is 15, can
have a fractional part.
bridge_gcint time
set garbage collection interval to time seconds, default is 4,
can have a fractional part.
bridge_hello time
set hello time to time seconds, default is 2, can have a
fractional part.
bridge_hw MAC address
set the Ethernet MAC address of all the bridge interfaces to the
specified one so that the bridge ends up having this hardware
address as well. WARNING: use this only if you know what you are
doing, changing the MAC address of the cards may cause trouble
if you don't know what you are doing. To see the discussion
about this feature and the problems that can cause you can try
to have a look at the bug that asked for this feature visiting
http://bugs.debian.org/271406
bridge_maxage time
set max message age to time seconds, default is 20, can have a
fractional part.
bridge_maxwait time
forces to time seconds the maximum time that the Debian bridge
setup scripts will wait for the bridge ports to get to the
forwarding status, doesn't allow factional part. If it is equal
to 0 then no waiting is done.
bridge_pathcost port cost
set path cost for a port, default is 100, port is the name of
the interface to which this setting applies.
bridge_portprio port priority
set port priority, default is 128, affects port id, port is the
name of the interface to which this setting applies.
bridge_stp state
turn spanning tree protocol on/off, state values are on or yes
to turn stp on and any other thing to set it off, default has
changed to off for security reasons in latest kernels, so you
should specify if you want stp on or off with this option, and
not rely on your kernel's default behaviour.
bridge_waitport time [ports]
wait for a max of time seconds for the specified ports to become
available, if no ports are specified then those specified on
bridge_ports will be used here. Specifying no ports here should
not be used if we are using regex or "all" on bridge_ports, as
it wouldn't work.
Источники:
