Ipv6 routing in linux

Настройка маршрутизатора IPv6 на Linux

В статье рассматривается пример настройки маршрутизатора для проброса IPv6 сети в локальную сеть и автонастройка клиентов.

Настройки должны подойти для любых linux-дистрибутивов, но могут отличаться нарпимер команды установки или названия пакетов. В статье примеры приведены для CentOS 6.5.

Исходное состояние:
  1. Есть аккаунт на tunnelbroker.net
  2. Чистый CentOS 6.5 с двумя интерфейсами: в локальную сеть и в публичный интернет с прямым (можно динамическим) IP-адресом.
Будет получено в итоге

Шлюз из локальной сети в IPv6-интернет, на котором разрешены исходящие подключения и запрещены входящие (чтобы кто попало в локальную сеть не ломился). Маршрутизатор анонсирует себя в локальной сети и клиенты автоматически настраиваются на сеть без состояния.

НЕ будет рассматриваться
Создание туннеля
  1. На tunnelbroker.net слева нажать ссылку «Create Regular Tunnel”
  2. Вписать текущий IP шлюзв в поле IPv4 Endpoint (Your side).
  3. С сервера, который будет шлюзом попинговать каждый предложенный IP из списка „Available Tunnel Servers” и выбрать сервер с минимальным пингом. Туннель привязывается к этому серверу и весь трафик будет идти через него. Поменять этот сервер потом можно будет только путем создания нового туннеля. Для целей статьи пусть это будет сервер 1.2.3.4. Нажать Create tunnel.
Подключение шлюза к туннелю

    Если на шлюзе настроен firewall — разрешить для выбранного сервера пинг-запросы и трафик по протоколу 41. Для простоты — можно разрешить весь трафик с сервера-шлюза.

При публикации некоторые кавычки поменялись с правильных на “красивые», так что как будет работать скрипт после копирования непонятно. Правильный вариант можно скачать тут.

Этот скрипт нужно запускать с параметрами up (включение шлюза) или down — выключение шлюза. Скрипт можно запускать много раз подряд. У меня он настроен для автозапуска после подключения к интернету в /etc/ppp/ip-up.local. После запуска этого скрипта IPv6-сеть появится на самом шлюзе, можно проверить попинговав сам брокера

Настройка маршрутизации трафика из/в локальную сеть

В этот момент если вручную настроить IPv6 на компьютерах локальной сети то он уже будет работать.

Автоматическая настройка клиентов

В этот момент IPv6 должен заработать в локальной сети для всех устройств которые поддерживают его автонастройку, можно проверять на сайте test-ipv6.com.

Источник

Настройка IPv6 в ОС Linux Debian v7.XX, Ubuntu v14.XX, CentOS v6.XX и FreeBSD v10.XX

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

Linux Debian v7.XX, Ubuntu v14.XX
CentOS v6.XX
FreeBSD v10.XX

После внедрения поддержки IPv6, на хостинговой площадке компании в которой я работаю, у нас возникла необходимость автоматизировать настройку VDS соответствующим образом. Необходимо оговорится, что речь идет не о каком-либо туннелировании, а полноценной поддержке. Т.е. сетевая инфраструктура в дата-центре обеспечивает коммутацию и маршрутизацию IPv6, имеются соответствующие стыки по BGPv6 с магистральными провайдерами Internet.

Читайте также:  Запускается windows вместо grub

Адреса назначаются и прописываются в настройках ОС статично, т.е. функционал автоматического конфигурирования IPv6 не задействуется. Это связано с особенностями учета адресного пространства и обеспечения безопасности. Задача осложняется тем, что адресов IPv4 и IPv6 у VDS может быть сразу несколько.

Linux Debian v7.XX, Ubuntu v14.XX

В достаточно свежих дистрибутивах ОС Linux уже присутствует полноценная поддержка IPv6. Поэтому доустанавливать что-либо вручную необходимости нет.
Рассмотрим пример настройки.
«/etc/network/interfaces»

Тут следует обратить внимание на два момента. Во-первых, все адреса IPv6 назначаются непосредственно на сам сетевой интерфейс: в отличие от IPv4 нет необходимости создавать виртуальные адаптеры типа «eth0:X». Во-вторых, шлюз по умолчанию для IPv6 указывается один раз для любого из адресов. Действовать он будет для всех.
Результат настроек в выводе команды «ifconfig»:

Базовую диагностику можно выполнить с помощью команд «ping6 -n -c 4 ipv6.google.com» и «traceroute -n -6 -I ipv6.google.com». Проверить MAC-адреса соседей: «ip -6 neighbor show». Изучить таблицу маршрутизации: «route -n6» или «ip -6 route show». Выяснить, какой из адресов IPv6 используется системой по умолчанию для исходящих подключений: «ip -6 route get 2a00:1450:4013:c01::65».

CentOS v6.XX

Настройка CentOS замысловатее из-за того, что опций несколько больше, и они раскиданы по нескольким файлам.
«/etc/sysconfig/network»

В целом картина аналогична Debian. Виртуальные сетевые интерфейсы «eth0:X» необходимы только для IPv4. Опции «NETWORKING_IPV6» и «IPV6INIT» включают поддержку IPv6. В «IPV6_DEFAULTGW» указываем шлюз по умолчанию. Первый адрес IPv6 назначается в «IPV6ADDR», все остальные перечисляются в «IPV6ADDR_SECONDARIES».

Вывод команды «ifconfig» аналогичен Debian:

FreeBSD v10.XX

В ОС FreeBSD уже также есть все необходимое для поддержки IPv6.
Рассмотрим пример настройки.
» /etc/rc.conf»

Основной адрес IPv6 указывается в опции «ifconfig_xn0_ipv6». Поскольку в FreeBSD механизм виртуальных сетевых интерфейсов для IPv4 не используется, то все дополнительные адреса, в том числе IPv6, перечисляются в «ifconfig_xn0_aliases».
Вывод команды «ifconfig» немного отличается от ОС Linux.

Инструмент для диагностики также немного другой: «ping6 -n -c 4 ipv6.google.com» и «traceroute6 -n ipv6.google.com». Проверить MAC-адреса соседей: «ndp -an». Изучить таблицу маршрутизации: «netstat -rn6». Выяснить, какой из адресов IPv6 используется системой по умолчанию для исходящих подключений: «route -nv6 get 2a00:1450:4013:c01::65».

В данном случае адресом по умолчанию является тот, что указан самым последним в выводе команды: «2a04:XXXX:1::12».

Источник

Packetblog

Technology, Photo, Travel, Personal ideas sandbox

Linux IPv6 Static Routes – Ubuntu/Debian & Fedora/RedHat

Looking at my blog statistics I realized that my most popular posts are those related to practical configuration and How To. This post will be one of them.

During the various tests I’ve performed on Linux platforms, one issue that was common – that if you configure a default gateway like that:

Ubuntu/Debian

iface eth0 inet6 static
address xxxx:xxxx::xxxx/64
gateway xxxx:xxxx::yyyy

Fedora/RedHat

vi /etc/sysconfig/network
NETWORKING_IPV6=yes

vi /etc/sysconfig/network-scripts/ifcfg-eth0

IPV6INIT=yes
IPV6ADDR=xxxx:xxxx::xxxx/64
IPV6_DEFAULTGW=xxxx:xxxx::yyyy

The above works fine when you do network restarts however will fail after a system reboot. The failure is rather interesting. After the reboot it looks like everything is fine till the moment you do some traffic. For instance doing a ping6 will allow one single packet, after which the default is present in the routing table but no packets flow. The situation can be ameliorated by putting in your

/etc/rc.local

ip -6 route add ::/0 via xxxx:xxxx::yyyy dev eth0

The drawback is that even if it works after reboots, you will have to manually add it back after a network restart.
This was not good enough for production.

Читайте также:  Родительский контроль windows 10 служба

After searching for some time I finally found how to configure static routes in the right manner so they would work after both reboots and network restart.
An article describing that can be found here or here.

The typical configuration for Ubuntu will be:

vi /etc/network/interfaces

iface eth0 inet6 static
address xxxx:xxxx::xxxx
netmask 64
up ip -6 route add ::/0 via xxxx:xxxx::yyyy dev eth0
down ip -6 route del ::/0 via xxxx:xxxx::yyyy dev eth0

so the routes would add/delete themselves on interface ups or downs.

In case of Fedora/RedHat there is a substitute for the well know

Источник

Practical Networking for Linux Admins: IPv6 Routing

Our story so far: We have learned the important bits about TCP/IP, IPv6, and IPv4 and IPv6 LAN Addressing, which is all very excellent. But, if you want your computers to talk to each other, then you must know about routing.

Simple Test Lab

Now we have a good use for the ip command. ip assigns multiple addresses to network interfaces, which is totally groovy because you can practice setting up and testing routing without needing a herd of computers. All you need to get started is two computers connected to the same Ethernet switch. In the following examples, I’m using a desktop PC and a laptop connected to an old 8-port gigabit switch. Yes, I know, there are newer switches that are so fast they reach the future before we do. Any Ethernet switch you want to use is fine.

If you are using Network Manager it will try to find a DHCP server when you plug in your Ethernet cables, so don’t run any name services on your test lab.

Assigning and Removing IP Addresses

First check your network interface names. The output is snipped for clarity:

My Ubuntu system likes to give network interfaces strange names. enp0s25 is my wired Ethernet interface. Let’s give it an IPv6 address from the range reserved for examples and documentation (see Practical Networking for Linux Admins: Real IPv6):

Let us admire our new address (again with trimmed output), and note also how the link local address is assigned automatically:

Assign an address to the second host:

Now the two hosts can ping each other. Remember, ping6 requires specifying the network interface, even if you only have one:

You can also ping the link local addresses:

link/ether is the MAC address. Note the scope values of global and link . global is a routable address, while link is the link local address that operates only within a single network segment. In IPv4 networks this is called a broadcast domain, which contains all hosts within a single logical network segment. Unlike IPv4 networks, IPv6 does not use a broadcast address. IPv4 has three address types: unicast, multicast and broadcast. As the excellent TCP/IP Guide says:

“Broadcast addressing as a distinct addressing method is gone in IPv6. Broadcast functionality is implemented using multicast addressing to groups of devices.”

Delete an address this way:

Create Route

Now we’ll add a second address to one of our test machines that’s in a different subnet. In the 2001:0db8::0/64 network, the first four octets define the network, and the last four are the host addresses. The “2” in the host address on my second test machine helps me remember which machine is which, so I’ll recycle that for the new subnet:

I ping the new address from the first test machine, to no avail:

Читайте также:  Основные понятия ос windows папка

So, I’ll create a route to the new subnet. Run ip -6 route show first to see your existing routing table, and copy it for a reference. Then create the new route:

Now look what ping does:

Success! We are networking nerds deluxe! Just to make sure, delete the route and try ping again:

None of these configurations survive a reboot. This is good news when you want to wipe everything and start over, but not so good news when you want to keep them. Every Linux distribution has its own special way of configuring IP addresses and static routes. If you’re running Network Manager you can configure everything with it. You can also push all of this to clients with a DHCP server, such as the excellent Dnsmasq, which provides name services, router advertisement, and network booting. All of which are large topics for another day. Until then, be well and enjoy being an IPv6 guru.

Learn more about Linux through the free “Introduction to Linux” course from The Linux Foundation and edX.

Источник

IPv6 router guide

This guide provides details on setting up IPv6 routing on a Gentoo Linux system.

Contents

Preliminaries

Basic kernel configuration

Any kernels version v2.6.0 or higher will easily support IPv6 connections. The new USAGI IPv6 stack is integrated to the kernel since Linux v2.6.0.

Enter the kernel source directory and begin kernel configuration:

Testing IPv6 support

After enabling the recommended options, recompile the kernel, then reboot into the new IPv6-enabled kernel.

If the sys-apps/iproute2 package is not yet installed, it is highly recommended to do so before continuing with this guide. iproute2 is a network configuration suite that contains ip , the famous replacement for ifconfig , route , iptunnel and others.

If IPv6 is working, the loopback device should show an IPv6 address:

Before proceeding any further, make sure to add ipv6 to the list of USE variables in make.conf , so that future emerges of packages will include IPv6 support.

Tunnel configuration

Basic configuration

Most ISPs still do not offer any native IPv6 connections. To get around this limitation, there are several «tunnel brokers» around the globe that offer free IPv6 tunnels. This will allow to tunnel all the IPv6 connections through an IPv4 connection.

Broker Location
Hurricane Electric North America, Europe, Asia
Freenet6 US (discontinued 2016)
SixXS Europe (discontinued 2017-06-06)
Singnet Singapore (unknown status, broken link as of 2021)
Aarnet Australia/South Pacific (discontinued 2019-05-04)

Below is an example for setting up a tunnel with a popular North American tunnel Hurricane Electric.

Hurricane Electric

Hurricane Electric (HE for short) offers free IPv6 tunnels and allocates a /64 block of addresses for each customer. It also allows configuration of reverse DNS. Getting a tunnel from HE is as easy as going to https://www.tunnelbroker.net/ and filling out a one page form.

After a tunnel is approved and a /64 block is allocated, start to configure the system. HE provides sample configurations based on ifconfig and the iproute utilities. The following two examples assume that the following configuration is used:

Local IPv4 Address (eth0) 68.36.91.195
HE IPv4 Address 64.71.128.82
Local IPv6 tunnel Address 2001:470:1F00:FFFF::2
Remote IPv6 tunnel Address 2001:470:1F00:FFFF::1
IPv6 Block 2001:470:1F00:296::/64

Using the sys-apps/iproute2 package and the ip command, do the following.

Create a tunnel between the local (eth0) IPv4 and HE’s remote IPv4 address:

Extract the tunneling overhead from the MTU:

Источник

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