Как получить “не зависящий от провайдера” IP-адрес для домашнего сервера?
Несколько лет назад я решил отказаться от использования внешних почтовых сервисов решил купить домен и настроить домашний сервер для приема всей моей корреспонденции. Работа была завершена очень быстро и я получил свой работающий на домашнем сервере почтовый домен! Некоторое время все работало гладко и ничего не предвещало проблем. Я споекйно наслаждася полным контролем над потоками почты в мой ящик..
Но немного позже мой провайдер решил удешевить мой способ подключения (для себя) и назначить приватный IP-адрес для моего сервера(192.168.192.2). Не сложно предположить, с этого момента мой почтовый сервер перестал быть доступен из реального мира и мой почтовый домен перестал функционировать.
Самым простым решением было бы переставить MX-записи моего домена на реальный мейл-сервер во внешней сети и использовать fetchmail или что-то похожее для доставки почты на домашний сервер. Но это решение не было достаточно гибким и я решил взять один из адресов, принадлежащих IP-пулу моего работодателя (я работаю на хостинговую компанию и ее владелец разрешил построение описанной здесь конфигурации) и назначить его на мой домашний сервер, сделав его таким образом доступным для реального мира. Вы можете сказать: “Это невозможно! Нельзя назначить чужой реальный IP на интерфейс внутри приватной сети другого провайдера!”. Да, в общем случае это так и есть, но при помощи небольшой хитрости с использованием Linux policy routing и тунеллирования это становится возможным. Эта статья расскажет Вам, как это можно сделать.
Во-первых, я выбрал один из адресов (RE.AL.AD.DR) в сети моего работодателя и организовал ip-over-tcp тунель с домашнего сервера на один из хостинговых серверов технической площадки работодателя. Это было сделано при помощи отличного средства для построения тунелей под UNIX – утилиты vtun от Максима Краснянского. Конфигураионные файлы для обоих серверов будут представлены позже в этой статье. На данном шаге я получил следующие интерфейсы со стороны на “мирового” и домашнего серверов:
- Сторона “мирового” сервера:
#ifconfig tun0 tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet addr:10.200.0.1 P-t-P:RE.AL.AD.DR Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1450 Metric:1 RX packets:8 errors:0 dropped:0 overruns:0 frame:0 TX packets:8 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:546 (546.0 b) TX bytes:494 (494.0 b) - Сторона домашнего сервера:
#ifconfig tun0 tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet addr:RE.AL.AD.DR P-t-P:10.200.0.1 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1450 Metric:1 RX packets:8 errors:0 dropped:0 overruns:0 frame:0 TX packets:8 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:494 (494.0 b) TX bytes:546 (546.0 b)
В приведенных выше выдержках используются 2 IP-адреса:
- RE.AL.AD.DR – реальный IP-адрес, который был установлен на тунеле со стороны домашнего сервера.
- 10.200.0.1 – произвольно выбранный (мною) приватный IP-адрес на “мировом” сервере.
Далее, мне нужно было заставить мой домашний сервер отправлять ответы на все запросы к сервисам по адресу RE.AL.AD.DR через тунельный интерфейс. Этой цели удалось добиться использую следующий надор команд для конфигурирования Linux policy routing в скрипте подьема тунельного интерфейса:
ip "rule add fwmark 65 table hof"; ip "route add default via 10.220.0.1 dev tun0 table hof"; firewall "-t mangle -A PREROUTING -s RE.AL.AD.DR -j MARK --set-mark 65"; firewall "-t mangle -A OUTPUT -s RE.AL.AD.DR -j MARK --set-mark 65";
Эти команды добавляют в систему новую таблицу маршрутизации с именем hof (для которой необходимо добавить отдельную строку в файле /etc/iproute2/rt_tables в виде “имя_таблицы числовой_идентификатор”), затоем добавляют в созданную таблицу маршрут по-умолчанию через конец тунеля на стороне “мирового” сервера и, наконец, помечают все пакеты с адреса RE.AL.AD.DR для маршрутизации при помощи таблицы hof.
Последним шагом необходимо было настроить “мировой” сервер так, чтобы он анонсировал при помощи arp-фреймов адрес RE.AL.AD.DR со своим MAC-адресом в ethernet-сеть в сторону своего маршрутизатора. Я использовал для этого маленькую утилиту farpd из официального репозитария дистрибутива Debian GNU/Linux. При помощи этой утилиты возможно анунсирование любого IP-адреса при помощи arp-фреймов в сеть, соединенную с определенным интерфейсом сервера:
/usr/sbin/farpd -i eth0 RE.AL.AD.DR
Вот и все! После выполнения описанных шагов, любое ПО на моем домашнем сервере, настроенное на использование моего нового IP-адреса address (RE.AL.AD.DR) будет доступно из реального мира сети Internet. На данный момент я могу без проблем менять провайдеров, обеспечивающих мне доступ в Сеть и это никак не повлияет на работу моего сервера так-как мой IP постоянно перемещается вместе со мною.
Как я и обещал, фрагменты конфигурационных файлов для vtun доступны для удобного скачивания:
Удачи Вам в ваших испытаниях описанной схемы получения собственного выделенного не зависимого от провайдера IP-адреса!
Related posts:

38 Responses to this entry
Понравилось. автор молодец.
Thank you, this is a valuable article – definitely a Bookmarker
You just made the front page of Digg
Why not find a better ISP that is willing to give you a real public IP?
2Charlie Hayes: When this configuration has been created, I was not able to pay a lot of money for high quality internet connection with real IP. I worked in small ISP as duty unix admin…
2Search Engines Web: Yeah! I am really happy! My blog is on the main page of the DIGG!
Interesting article, I need to do some test on it.
Oh sweet…
“Why not find a better ISP that is willing to give you a real public IP?”
Because you have no control over what your ISP decides to do… Hmm, in this case, if you loose your job, you loose your IP. Bah.. you cannot have everything.. At least, this solution is cheaper for him.
Kiltak
[Geeks Are Sexy] Tech. News
thank you
thank you
thank you
been trying to find this stuff for a long time now.
no use. some of us need free tunneling.
I am sure your employer really liked that you used their address space and probably company time, bandwidth an network resources to help you host your mail.
They know about this tunnel and this work has been done in my private time.
There are lots of ways do do the same thing using IPSEC, GRE, IP-in-IP, even SSH and a proxy, but this kind of thing is a violation of pretty much every companies Internet usage policy, which most people sign when hired. If your company is cool with it, great. But for 99.9% of the people, doing something like this can result in termination of employment and/or legal action. Most may say it won’t happen, but trust me, I know firsthand that it does.
I thought this article was going to be about getting ARIN to provide /32 that he could put in his back pocket and trip around with. Not sure how this is provider independant, cuz *someone* is SWIPing the IP block out to his employer… therefore being a provider?
2Paula Abdool: “Provider Independent” is quoted in article subject!
2Will: As I said, my employer knows about this configurations and that is rhy I can say: “My company is great!”
[...] ———- Most ppl won’t need this. However, this may be somewhat useful for my network course next semester.read more | digg story [...]
“provider-independent”, huh?
What happens when your employer is forced to renumber or their provider changes or something similar occurs? You’ll just be renumbering again. Just get a decent ISP and skip all the bullsh*t.
Go check out this guy’s “Resume/CV” page and scroll down to his “Employment History”. He’s presently employed by “New Age Opt-in”. Sounds like a spammer to me!
Jeremy, why do you trying to say something bad? As you can read here:
New Age Opt-In company sends mail only to people which are subscribed to it!
[...] read more | digg story [...]
Scoundrel: Unfortunatly thanks to the actions of some people, ANY opt-in company will be scutinized(And remember that Digg Users are really… yeah.. about things like that) Since most of the fake ‘opt-in’ companies claim that too its all too common.
-=DD32=-
Wow check out his schooling :X and I’m over here with about an 8th of that…
Yes, IP will be independent from ISP you’re using at home.Decent ISP is good but not each and every ISP offers statical real IP addresses.Some are using dynamic IPs only.LAN Ethernet ISPs are often preferring private IPs because they’re at begin of their way so it costs too much to pay for IP range.Also as you maybe aware, IPv4 uses 32 bits for addressing.When each device needs its IP (yeah, each mobile phone, for example) there is simple not enough IP addresses so such situation will be even worse in future.
As said many times on NANOG, “I highly encourage my competitors to do this.”
TCP in TCP tunnels are bad ideas in general. It shouldn’t take too much googling to figure out what the rubber band effect is.
[...] Anyway, this is a short post. The link can be found here, from this guy who wrote how to setup virtual tunneling. [...]
OpenVPN would be a much better solution. Configuration is extremely simple, it uses tun/tap devices, and it encrypts the connection over SSL.
2baron: What type of tunnel will be used is not significant. The idea of this article is how to use linux policy routing in real life.
[...] Homo-Adminus Blog » How To Get “Provider Independent” IP Address For Your Home Server? (tags: howto network web linux) [...]
[...] read more | digg story [...]
ДлÑ? раÑ?Ñ?мотренного примера задачу можно решить проще и без iptables/packet mangling.
ВмеÑ?то
ip “rule add fwmark 65 table hof”;
ip “route add default via 10.220.0.1 dev tun0 table hofâ€?;
firewall “-t mangle -A PREROUTING -s RE.AL.AD.DR -j MARK –set-mark 65″;
firewall “-t mangle -A OUTPUT -s RE.AL.AD.DR -j MARK –set-mark 65″;
доÑ?таточно указать
ip rule add from RE.AL.AD.DR table hof
ip route add default via 10.220.0.1 dev tun0 table hof
а вмеÑ?то
/usr/sbin/farpd -i eth0 RE.AL.AD.DR
можно иÑ?пользовать вÑ?троенные в Ñ?дро возможноÑ?ти по прокÑ?ированию arp:
ip nei add proxy RE.AL.AD.DR dev eth0
в общем, Ñ?татейка так Ñ?ебе
[...] This article is about how to provider-independent real IP address for your home server behind the NAT.read more | digg story [...]
[...] permalink nochmal zur Urspungsfrage: Das ganze hat schonmal jemand gemacht… How To Get “Provider Independent” IP Address For Your Home Server? :: Homo-Adminus Blog by Alexey Kovyrin aber es hat ganz einfach 2 Nachteile gegen
Просто супер рецепт.
Уже записал и запомнил, обязательно пригодится.
Here you can find the real provider-independent addresses: http://www.getownip.com
Hosting your own mail server can be a great learning experience and all but it must be hard to get all your mail delivered.
Very nice and informative article. We are a small internet provider in Czech republic, we don't want to waste our finances to register LIR and don't want to spend our time negotiating with RIPE to get an additional blok of ipaddresses. You offer much cheaper and faster solution that is suttable for company like ours! We definitely should make a deal with you =)
Hi Jiri! If you want to get an independent address space without signing LIR contract, just call us +420721207705 and we can arrange meeting. We can request resources from RIPE for you.
To find public ip address,several online tools available such as http://www.ipaddressfinder.info