Sun 2 Apr 2006
Как получить “не зависящий от провайдера” IP-адрес для домашнего сервера?
Posted by Scoundrel under Networks ·
Несколько лет назад я решил отказаться от использования внешних почтовых сервисов решил купить домен и настроить домашний сервер для приема всей моей корреспонденции. Работа была завершена очень быстро и я получил свой работающий на домашнем сервере почтовый домен! Некоторое время все работало гладко и ничего не предвещало проблем. Я споекйно наслаждася полным контролем над потоками почты в мой ящик..
Но немного позже мой провайдер решил удешевить мой способ подключения (для себя) и назначить приватный 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-адреса!
- Hosting Tricks: Как привязать неограниченное количество доменов к одному хостинг-аккаунту
- Small Tip: How to set up two interface Xen machine
- Hosting Tricks: Как делегировать управление сабдоменом внешнему DNS-серверу
- UltimateGeoCoder - PHP-библиотека для доступа к различным geocoding-сервисам
- Ultimate Geo Coder - a PHP library inteface to miscellaneous geo coding services
April 3rd, 2006 at 8:40 am
Понравилось. автор молодец.
April 3rd, 2006 at 9:39 pm
Thank you, this is a valuable article - definitely a Bookmarker
You just made the front page of Digg
April 3rd, 2006 at 9:40 pm
Why not find a better ISP that is willing to give you a real public IP?
April 3rd, 2006 at 9:47 pm
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…
April 3rd, 2006 at 9:53 pm
2Search Engines Web: Yeah! I am really happy! My blog is on the main page of the DIGG!
April 3rd, 2006 at 9:59 pm
Interesting article, I need to do some test on it.
April 3rd, 2006 at 10:10 pm
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
April 3rd, 2006 at 10:12 pm
thank you
thank you
thank you
been trying to find this stuff for a long time now.
April 3rd, 2006 at 10:15 pm
no use. some of us need free tunneling.
April 3rd, 2006 at 10:50 pm
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.
April 3rd, 2006 at 10:56 pm
They know about this tunnel and this work has been done in my private time.
April 3rd, 2006 at 11:17 pm
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.
April 3rd, 2006 at 11:17 pm
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?
April 3rd, 2006 at 11:19 pm
2Paula Abdool: “Provider Independent” is quoted in article subject!
April 3rd, 2006 at 11:21 pm
2Will: As I said, my employer knows about this configurations and that is rhy I can say: “My company is great!”
April 3rd, 2006 at 11:39 pm
[...] ———- Most ppl won’t need this. However, this may be somewhat useful for my network course next semester.read more | digg story [...]
April 4th, 2006 at 12:14 am
“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.
April 4th, 2006 at 12:32 am
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!
April 4th, 2006 at 12:41 am
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!
April 4th, 2006 at 1:48 am
[...] read more | digg story [...]
April 4th, 2006 at 3:33 am
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=-
April 4th, 2006 at 4:26 am
Wow check out his schooling :X and I’m over here with about an 8th of that…
April 4th, 2006 at 7:01 am
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.
April 4th, 2006 at 7:21 am
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.
April 4th, 2006 at 12:17 pm
[...] Anyway, this is a short post. The link can be found here, from this guy who wrote how to setup virtual tunneling. [...]
April 4th, 2006 at 6:30 pm
OpenVPN would be a much better solution. Configuration is extremely simple, it uses tun/tap devices, and it encrypts the connection over SSL.
April 4th, 2006 at 6:44 pm
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.
April 5th, 2006 at 12:39 am
[...] Homo-Adminus Blog » How To Get “Provider Independent” IP Address For Your Home Server? (tags: howto network web linux) [...]
April 12th, 2006 at 12:41 am
[...] read more | digg story [...]
April 22nd, 2006 at 4:37 pm
ДлÑ? раÑ?Ñ?мотренного примера задачу можно решить проще и без 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
в общем, Ñ?татейка так Ñ?ебе
September 1st, 2006 at 9:23 am
[...] This article is about how to provider-independent real IP address for your home server behind the NAT.read more | digg story [...]
January 5th, 2007 at 3:59 am
[...] 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 gegenber dyndns: a) luft der Traffic auch immer ber die weitergeleitete IP b) ist das Tunneln von tcp ber tcp nicht ganz sauber, glaube das steht auch in den Blog comments. MfG [...]
April 27th, 2007 at 7:04 am
Просто супер рецепт.
Уже записал и запомнил, обязательно пригодится.
April 15th, 2008 at 11:13 pm
Here you can find the real provider-independent addresses: http://www.getownip.com