Linux ip route routing table

Linux ip route routing table

Linux kernel 2.2 and 2.4 support multiple routing tables [22] . Beyond the two commonly used routing tables (the local and main routing tables), the kernel supports up to 252 additional routing tables.

The multiple routing table system provides a flexible infrastructure on top of which to implement policy routing. By allowing multiple traditional routing tables (keyed primarily to destination address) to be combined with the routing policy database (RPDB) (keyed primarily to source address), the kernel supports a well-known and well-understood interface while simultaneously expanding and extending its routing capabilities. Each routing table still operates in the traditional and expected fashion. Linux simply allows you to choose from a number of routing tables, and to traverse routing tables in a user-definable sequence until a matching route is found.

Any given routing table can contain an arbitrary number of entries, each of which is keyed on the following characteristics (cf. Table 4.1, “Keys used for hash table lookups during route selection”)

destination address; a network or host address (primary key)

tos; Type of Service

For practical purposes, this means that (even) a single routing table can contain multiple routes to the same destination if the ToS differs on each route or if the route applies to a different interface [23] .

The ip route and ip rule commands have built in support for the special tables main and local . Any other routing tables can be referred to by number or an administratively maintained mapping file, /etc/iproute2/rt_tables .

The format of this file is extraordinarily simple. Each line represents one mapping of an arbitrary string to an integer. Comments are allowed.

Example 4.6. Typical content of /etc/iproute2/rt_tables

The local table is a special routing table maintained by the kernel. Users can remove entries from the local routing table at their own risk. Users cannot add entries to the local routing table. The file /etc/iproute2/rt_tables need not exist, as the iproute2 tools have a hard-coded entry for the local table.

The main routing table is the table operated upon by route and, when not otherwise specified, by ip route . The file /etc/iproute2/rt_tables need not exist, as the iproute2 tools have a hard-coded entry for the main table.

The default routing table is another special routing table, but WHY is it special.

Operating on the unspec routing table appears to operate on all routing tables simultaneously. Is this true!? What does that imply?

This is an example indicating that table 1 is known by the name inr.ruhep. Any references to table inr.ruhep in an ip rule or ip route will substitue the value 1 for the word inr.ruhep.

The routing table manipulated by the conventional route command is the main routing table. Additionally, the use of both ip address and ifconfig will cause the kernel to alter the local routing table (and usually the main routing table). For further documentation on how to manipulate the other routing tables, see the command description of ip route .

4.8.1. Routing Table Entries (Routes)

Each routing table can contain an arbitrary number of route entries. Aside from the local routing table, which is maintained by the kernel, and the main routing table which is partially maintained by the kernel, all routing tables are controlled by the administrator or routing software. All routes on a machine can be changed or removed [25] .

Each of the following route types is available for use with the ip route command. Each route type causes a particular sort of behaviour, which is identified in the textual description. Compare the route types described below with the rule types available for use in the RPDB.

A unicast route is the most common route in routing tables. This is a typical route to a destination network address, which describes the path to the destination. Even complex routes, such as nexthop routes are considered unicast routes. If no route type is specified on the command line, the route is assumed to be a unicast route.

Example 4.7. unicast route types

This route type is used for link layer devices (such as Ethernet cards) which support the notion of a broadcast address. This route type is used only in the local routing table [26] and is typically handled by the kernel.

Example 4.8. broadcast route types

The kernel will add entries into the local routing table when IP addresses are added to an interface. This means that the IPs are locally hosted IPs [27] .

Example 4.9. local route types

Читайте также:  Linux не вводить пароль при входе

This route entry is added by the kernel in the local routing table, when the user attempts to configure stateless NAT. See Section 5.3, “Stateless NAT with iproute2 ” for a fuller discussion of network address translation in general. [28] .

Example 4.10. nat route types

When a request for a routing decision returns a destination with an unreachable route type, an ICMP unreachable is generated and returned to the source address.

Example 4.11. unreachable route types

When a request for a routing decision returns a destination with a prohibit route type, the kernel generates an ICMP prohibited to return to the source address.

Example 4.12. prohibit route types

A packet matching a route with the route type blackhole is discarded. No ICMP is sent and no packet is forwarded.

Example 4.13. blackhole route types

The throw route type is a convenient route type which causes a route lookup in a routing table to fail, returning the routing selection process to the RPDB. This is useful when there are additional routing tables. Note that there is an implicit throw if no default route exists in a routing table, so the route created by the first command in the example is superfluous, although legal.

Example 4.14. throw route types

The power of these route types when combined with the routing policy database can hardly be understated. All of these route types can be used without the RPDB, although the throw route doesn’t make much sense outside of a multiple routing table installation.

4.8.2. The Local Routing Table

The local routing table is maintained by the kernel. Normally, the local routing table should not be manipulated, but it is available for viewing. In Example D.12, “Viewing the local routing table with ip route show table local ”, you’ll see two of the common uses of the local routing table. The first common use is the specification of broadcast address, necessary only for link layers which support broadcast addressing. The second common type of entry in a local routing table is a route to a locally hosted IP.

The route types found in the local routing table are local , nat and broadcast . These route types are not relevant in other routing tables, and other route types cannot be used in the local routing table.

If the the machine has several IP addresses on one Ethernet interface, there will be a route to each locally hosted IP in the local routing table. This is a normal side effect of bringing up an IP address on an interface under linux. Maintenance of the broadcast and local routes in the local routing table can only be done by the kernel.

Example 4.15. Kernel maintenance of the local routing table

Note in Example 4.15, “Kernel maintenance of the local routing table”, that the kernel adds not only the route for the locally connected network in the main routing table, but also the three required special addresses in the local routing table. Any IP addresses which are locally hosted on the box will have local entries in the local table. The network address and broadcast address are both entered as broadcast type addresses on the interface to which they have been bound. Conceptually, there is significance to the distinction between a network and broadcast address, but practically, they are treated analogously, by other networking gear as well as the linux kernel.

There is one other type of route which commonly ends up in the local routing table. When using iproute2 NAT, there will be entries in the local routing table for each network address translation. Refer to Example D.21, “Creating a NAT route for a single IP with ip route add nat ” and Example D.22, “Creating a NAT route for an entire network with ip route add nat ” for example output.

4.8.3. The Main Routing Table

The main routing table is the routing table most people think of when considering a linux routing table. When no table is specified to an ip route command, the kernel assumes the main routing table. The route command only manipulates the main routing table.

Similarly to the local table, the main table is populated automatically by the kernel when new interfaces are brought up with IP addresses. Consult the main routing table before and after ip address add 192.168.254.254/24 brd + dev eth1 in Example 4.15, “Kernel maintenance of the local routing table” for a concrete example of this kernel behaviour. Also, visit this summary of side effects of interface definition and activation with ifconfig or ip address .

[22] The kernel must be compiled with the option CONFIG_IP_MULTIPLE_TABLES=y . This is common in vendor and stock kernels, both 2.2 and 2.4.

[23] If somebody has used scope or oif as additional keys in a routing table, and has an example, I’d love to see it, for possible inclusion in this documentation.

[24] Can anybody describe to me what is in table 0? It looks almost like an aggregation of the routing entries in routing tables 254 and 255.

Читайте также:  Paragon hard disk manager восстановление загрузки windows

[25] Once again, I recommend caution when altering the local routing table. Removing local route types from the local routing table can break networking in strange and wonderful ways.

[26] OK, I’m not absolutely sure you can’t use the broadcast route in other routing tables, but I believe you can’t. Testing forthcoming.

[27] Ibid. I’m not sure that local route types can be used in any routing table other than the local routing table. Testing forthcoming.

[28] Ibid. nat route types might be ineffectual outside the local routing table. Testing forthcoming.

Источник

RootUsers

Guides, tutorials, reviews and news for System Administrators.

How To Display Routing Table In Linux

The routing table is used to show you where various different network subnets will be routed to. Here are three different commands that you can use to print out the routing table in Linux.

Using ip command

The current recommended way of printing the routing table in Linux is with the ip command followed by route, as demonstrated below.

If you’re in a hurry you can also shorten this to ‘ip r’ which will print the same output. While this is the current recommended method of printing out the routing table in Linux, you will see that the output doesn’t look as nice as older options.

Check out our IP command examples for further information on how you can use this to display networking information.

Using netstat command

While this is a popular way of printing out routing information in Linux, netstat is actually deprecated and replaced instead with ip route – it even says so in the manual page. Nevertheless as it is still widely used, we have included it here.

Netstat combined with the -r option will display the kernel routing tables. This is commonly used with the -n option, which will only show numerical addresses rather than performing any sort of name resolution.

Using route command

The manual page for route also states that it is obsolete and has been replaced by the ip route command previously mentioned, again as this is still used, here’s an example of it. Like netstat, the -n option is used to display numeric information only.

Summary

As we have seen there are a few ways to display the routing information in Linux, however most are now considered obsolete with ‘ip route’ being the current recommended method, despite the output in my opinion not looking as neat as the others.

Источник

Роутинг и policy-routing в Linux при помощи iproute2

Речь в статье пойдет о роутинге сетевых пакетов в Linux. А конкретно – о типе роутинга под названием policy-routing (роутинг на основании политик). Этот тип роутинга позволяет маршрутизировать пакеты на основании ряда достаточно гибких правил, в отличие от классического механизма маршрутизации destination-routing (роутинг на основании адреса назначения). Policy-routing применяется в случае наличия нескольких сетевых интерфейсов и необходимости отправлять определенные пакеты на определенный интерфейс, причем пакеты определяются не по адресу назначения или не только по адресу назначения. Например, policy-routing может использоваться для: балансировки трафика между несколькими внешними каналами (аплинками), обеспечения доступа к серверу в случае нескольких аплинков, при необходимости отправлять пакеты с разных внутренних адресов через разные внешние интерфейсы, даже для отправки пакетов на разные TCP-порты через разные интерфейсы и т.д.
Для управления сетевыми интерфейсами, маршрутизацией и шейпированием в Linux служит пакет утилит iproute2.

Этот набор утилит лишь задает настройки, реально вся работа выполняется ядром Linux. Для поддержки ядром policy-routing оно должно быть собрано с включенными опциями IP: advanced router (CONFIG_IP_ADVANCED_ROUTER) и IP: policy routing (CONFIG_IP_MULTIPLE_TABLES), находящимися в разделе Networking support -> Networking options -> TCP/IP networking.

ip route

Для настройки роутинга служит команда ip route. Выполненная без параметров, она покажет список текущих правил маршрутизации (не все правила, об этом чуть позже):

Так будет выглядеть роутинг при использовании на интерфейсе eth0 IP-адреса 192.168.12.101 с маской подсети 255.255.255.0 и шлюзом по умолчанию 192.168.12.1.
Мы видим, что трафик на подсеть 192.168.12.0/24 уходит через интерфейс eth0. proto kernel означает, что роутинг был задан ядром автоматически при задании IP интерфейса. scope link означает, что эта запись является действительной только для этого интерфейса (eth0). src 192.168.12.101 задает IP-адрес отправителя для пакетов, попадающих под это правило роутинга.
Трафик на любые другие хосты, не попадающие в подсеть 192.168.12.0/24 будет уходить на шлюз 192.168.12.1 через интерфейс eth0 ( default via 192.168.12.1 dev eth0 ). Кстати, при отправке пакетов на шлюз, IP-адрес назначения не изменяется, просто в Ethernet-фрейме в качестве MAC-адреса получателя будет указан MAC-адрес шлюза (часто даже специалисты со стажем путаются в этом моменте). Шлюз в свою очередь меняет IP-адрес отправителя, если используется NAT, либо просто отправляет пакет дальше. В данном случае используются приватный адрес (192.168.12.101), так что шлюз скорее всего делает NAT.
А теперь залезем в роутинг поглубже. На самом деле, таблиц маршрутизации несколько, а также можно создавать свои таблицы маршрутизации. Изначально предопределены таблицы local, main и default. В таблицу local ядро заносит записи для локальных IP адресов (чтобы трафик на эти IP-адреса оставался локальным и не пытался уходить во внешнюю сеть), а также для бродкастов. Таблица main является основной и именно она используется, если в команде не указано какую таблицу использовать (т.е. выше мы видели именно таблицу main). Таблица default изначально пуста. Давайте бегло взглянем на содержимое таблицы local:

Читайте также:  Как включить темную тему windows 10 без активации

broadcast и local определяют типы записей (выше мы рассматривали тип default ). Тип broadcast означает, что пакеты соответствующие этой записи будут отправлены как broadcast-пакеты, в соответствии с настройками интерфейса. local – пакеты будут отправлены локально. scope host указывает, что эта запись действительная только для этого хоста.
Для просмотра содержимого конкретной таблицы используется команда ip route show table TABLE_NAME . Для просмотра содержимого всех таблиц в качестве TABLE_NAME следует указывать all , unspec или 0 . Все таблицы на самом деле имеют цифровые идентификаторы, их символьные имена задаются в файле /etc/iproute2/rt_tables и используются лишь для удобства.

ip rule

Как же ядро выбирает, в какую таблицу отправлять пакеты? Все логично – для этого есть правила. В нашем случае:

Число в начале строки – идентификатор правила, from all – условие, означает пакеты с любых адресов, lookup указывает в какую таблицу направлять пакет. Если пакет подпадает под несколько правил, то он проходит их все по порядку возрастания идентификатора. Конечно, если пакет подпадет под какую-либо запись маршрутизации, то последующие записи маршрутизации и последующие правила он уже проходить не будет.
Возможные условия:

  • from – мы уже рассматривали выше, это проверка отправителя пакета.
  • to – получатель пакета.
  • iif – имя интерфейса, на который пришел пакет.
  • oif – имя интерфейса, с которого уходит пакет. Это условие действует только для пакетов, исходящих из локальных сокетов, привязанных к конкретному интерфейсу.
  • tos – значение поля TOS IP-пакета.
  • fwmark – проверка значения FWMARK пакета. Это условие дает потрясающую гибкость правил. При помощи правил iptables можно отфильтровать пакеты по огромному количеству признаков и установить определенные значения FWMARK. А затем эти значения учитывать при роутинге.

Условия можно комбинировать, например from 192.168.1.0/24 to 10.0.0.0/8 , а также можно использовать префикc not , который указывает, что пакет не должен соответствовать условию, чтобы подпадать под это правило.
Итак, мы разобрались что такое таблицы маршрутизации и правила маршрутизации. А создание собственных таблиц и правил маршрутизации это и есть policy-routing, он же PBR (policy based routing). Кстати SBR (source based routing) или source-routing в Linux является частным случаем policy-routing, это использование условия from в правиле маршрутизации.

Простой пример

Теперь рассмотрим простой пример. У нас есть некий шлюз, на него приходят пакеты с IP 192.168.1.20. Пакеты с этого IP нужно отправлять на шлюз 10.1.0.1. Чтобы это реализовать делаем следующее:
Создаем таблицу с единственным правилом:

Создаем правило, отправляющее нужные пакеты в нужную таблицу:

Как видите, все просто.

Доступность сервера через несколько аплинков

Теперь более реалистичный пример. Имеется два аплинка до двух провайдеров, необходимо обеспечить доступность сервера с обоих каналов:

В качестве маршрута по умолчанию используется один из провайдеров, не важно какой. При этом веб-сервер будет доступен только через сеть этого провайдера. Запросы через сеть другого провайдера приходить будут, но ответные пакеты будут уходить на шлюз по умолчанию и ничего из этого не выйдет.
Решается это весьма просто:
Определяем таблицы:

Думаю теперь уже объяснять смысл этих строк не надо. Аналогичным образом можно сделать доступность сервера по более чем двум аплинкам.

Балансировка трафика между аплинками

Делается одной элегантной командой:

Эта запись заменит существующий default-роутинг в таблице main. При этом маршрут будет выбираться в зависимости от веса шлюза ( weight ). Например, при указании весов 7 и 3, через первый шлюз будет уходить 70% соединений, а через второй – 30%. Есть один момент, который при этом надо учитывать: ядро кэширует маршруты, и маршрут для какого-либо хоста через определенный шлюз будет висеть в таблице еще некоторое время после последнего обращения к этой записи. А маршрут до часто используемых хостов может не успевать сбрасываться и будет все время обновляться в кэше, оставаясь на одном и том же шлюзе. Если это проблема, то можно иногда очищать кэш вручную командой ip route flush cache .

Использование маркировки пакетов при помощи iptables

Допустим нам нужно, чтобы пакеты на 80 порт уходили только через 11.22.33.1. Для этого делаем следующее:

Первой командой маркируем все пакеты, идущие на 80 порт. Второй командой создаем таблицу маршрутизации. Третьей командой заворачиваем все пакеты с указанной маркировкой в нужную таблицу.
Опять же все просто. Рассмотрим также использование модуля iptables CONNMARK. Он позволяет отслеживать и маркировать все пакеты, относящиеся к определенному соединению. Например, можно маркировать пакеты по определенному признаку еще в цепочке INPUT, а затем автоматически маркировать пакеты, относящиеся к этим соединениям и в цепочке OUTPUT. Используется он так:

Пакеты, приходящие с eth0 маркируются 2, а с eth1 – 4 (строки 1 и 2). Правило на третьей строке проверяет принадлежность пакета к тому или иному соединению и восстанавливает маркировки (которые были заданы для входящих) для исходящих пакетов.
Надеюсь изложенный материал поможет вам оценить всю гибкость роутинга в Linux. Спасибо за внимание 🙂

Источник

Оцените статью