Showing posts with label vps. Show all posts
Showing posts with label vps. Show all posts

October 14, 2019

fail2ban bans wrong port with iptables

If you created a custom non-SSH action for fail2ban, and while it does get triggered, the offender can still get through, make sure you've used the right iptables ban action. iptables-multiport will work with the ports you specify next to it in your config; if you don't specify any, it reverts to 22 (default SSH). My custom action.d was for Nginx (ports 80 and 443), and the ban essentially didn't work. The key is to use iptables-allports - it will ban the offender completely, regardless of ports, and using it seems to make the most sense anyway. You can check which port was banned by running iptables -L and looking for the chain name matching your jail name. Source: https://serverfault.com/a/382891

February 18, 2017

L2TP/IPSEC VPN on a Debian VPS

ipsec Segmentation Fault

root# invoke-rc.d ipsec start
Job for ipsec.service failed. See 'systemctl status ipsec.service' and 'journalctl -xn' for details.
invoke-rc.d: initscript ipsec, action "start" failed.
root# systemctl status ipsec.service
ipsec.service - LSB: Start Openswan IPsec at boot time
Loaded: loaded (/etc/init.d/ipsec)
Active: failed (Result: exit-code) since Sat 2017-02-18 15:17:07 CET; 3s ago
Process: 844 ExecStart=/etc/init.d/ipsec start (code=exited, status=139)

Feb 18 15:17:07 vpn-example.com systemd[1]: Starting LSB: Start Openswan IPsec at boot time...
Feb 18 15:17:07 vpn-example.com ipsec[844]: Segmentation fault
Feb 18 15:17:07 vpn-example.com ipsec[844]: failed to start openswan IKE daemon - the following error occured:
Feb 18 15:17:07 vpn-example.com systemd[1]: ipsec.service: control process exited, code=exited status=139
Feb 18 15:17:07 vpn-example.com systemd[1]: Failed to start LSB: Start Openswan IPsec at boot time.
Feb 18 15:17:07 vpn-example.com systemd[1]: Unit ipsec.service entered failed state.
root# /etc/init.d/ipsec start
Segmentation fault
failed to start openswan IKE daemon - the following error occured:

Solution: make sure /etc/ipsec.conf has an empty line at the end of file.

source

Verify the configuration

ipsec verify

Using tcpdump to debug L2TP/IPSEC UDP packets

If you're getting the following error:
Error 789: The L2TP connection attempt failed because the security layer encountered a processing error during initial negotiations with the remote computer
You'll need to confirm if the packets are reaching the VPN server:
tcpdump -i any -n -nn icmp or \( udp and \( port 500 or port 1701 or port 4500 \) \) 

source


https://www.elastichosts.com/blog/linux-l2tpipsec-vpn-server/
https://gist.github.com/mietek/4877cd74423bf6925b92
https://wiki.openwrt.org/inbox/openswanxl2tpvpn
https://github.com/xelerance/Openswan/wiki/L2tp-ipsec-configuration-using-openswan-and-xl2tpd
http://blog.jameskyle.org/2012/07/configuring-openswan-ipsec-server/
https://raymii.org/s/tutorials/IPSEC_L2TP_vpn_on_a_Raspberry_Pi_with_Arch_Linux.html
https://habrahabr.ru/company/FastVPS/blog/205162/

February 16, 2017

Как быстро узнать какие HTTP-запросы делает iPhone/iPad с помощью своего прокси-сервера

Мне нужно было быстро посмотреть какие запросы отсылает айфон в интернет, и какие HTTP ответы получает. Для этого нужно использовать HTTP прокси, и если под руками есть VDS-ка, можно задействовать ее.

Шаг 1/2: Установка Squid3


apt-get update
apt-get install -y squid3

Разрешим не-SSL запросы, найдите http_access
# Deny requests to certain unsafe ports
http_access deny !Safe_ports
и раскомментируйте последнюю строку выше.

Если вылетает ошибка доступа (TCP_DENIED/403 Access Denied):

ОШИБКА: Запрошенный URL не может быть получен
При получении URL произошла следующая ошибка Доступ запрещён.
Система контроля доступа не позволяет выполнить ваш запрос сейчас. Обратитесь к вашему администратору

то вам нужно разрешить свой IP-адрес в настройках /etc/squid3/squid.conf:
acl my_ip src 123.123.123.123
http_access allow my_ip
Замените 123.123.123.123 на свой ип-адрес и втавьте фрагмент на самый верх файла конфигурации!

Шаг 2/2: Настройка iOS устройства

Сначала узнаем на каком порту работает squid:
netstat -apn | grep squid | grep LISTEN

На смартфоне/планшете, зайдите в Настройки - Wi-Fi - напротив сети, к которой подключены, нажмите i - пролистайте вниз до PROXY/Прокси HTTP - укажите IP-адрес сервера и номер порта; выключите авторизаци./аутентификацию

Это все. Вы можете отследить запросы в файле /var/log/squid3/access.log.

эта же статья на английском

Debugging iPhone/iPad HTTP requests using squid3 proxy

I needed to debug the requests an iOS app was making. An option is to configure your Wi-Fi setings to use an HTTP proxy, and if you have a Debian VPS/server, I think that'd be the fastest way to get this done.

Step 1/2: Install Squid3


apt-get update
apt-get install -y squid3

Allow non-ssl requests: find the http_access block
# Deny requests to certain unsafe ports
http_access deny !Safe_ports
Comment out the last line.

If you're getting the TCP_DENIED/403 error:

ERROR: The requested URL could not be retrieved
The following error was encountered while trying to retrieve the URL: Access Denied.
Access control configuration prevents your request from being allowed at this time. Please contact your service provider if you feel this is incorrect.

You will have to allow your IP address in /etc/squid3/squid.conf:
acl my_ip src 123.123.123.123
http_access allow my_ip
Replace 123.123.123.123 with your IP address and add the above lines to the very top of the file!

Step 2/2: Configure iOS to use your proxy

Find out your squid port:
netstat -apn | grep squid | grep LISTEN

On your iOS device, go to Settings - Wi-Fi - tap the i in front of the network you're connected to - scroll to PROXY HTTP - add your server IP and port; turn off authentication

That's it. You should now see the requests the iPhone makes in /var/log/squid3/access.log.

December 10, 2016

Перенос файлов между серверами без скачивания на локальный компьютер

Если нужно перенести файлы с одного VPS/VDS или просто сервера на другой, не обязательно сначала скачивать их себе на компьютер, можно скопировать напрямую.

Прежде всего, определимся, что сервер-источник это ОТКУДА нужно перенести, а сервер назначения - это КУДА нужно перенести.

Для этого зайдите по SSH на сервер назначения и воспользуйтесь командой scp:
scp root@source.com:/home/file /home/file

Если нужно перенести всю папку, укажите параметр -r (рекурсивно)
Чтобы сохранить оригинальные даты, укажите -p.
scp -r -p root@source.com:/home/my_dir /home
внимание, дописывать имя нужной папки к пути назначения не нужно
Если на сервере, к которому подключаемся, нестандартный порт SSH. укажите его с помощью -P:
scp -P 22 -r -p root@source.com:/home/my_dir /home

Пароль от пользователя, под которым авторизуетесь, держите наготове, сразу спросит.

Перенесенные файлы сохранят оригинальное время модификации (date changed/modified).

Внимание! В scp нет фильтров по существующим на сервере назначения объектам, и по определённым папкам. Перезапишет всё подряд. Перенося сайт, например, пропустить папку ./.git не выйдет.

September 30, 2014

Как устранить уязвимость Shellshock на сервере или VDS под управлением Debian

Проверьте присутствует ли уязвимость:

env X="() { :;} ; echo busted" bash -c "echo stuff"

Если в выводе содержится "busted", дыра Shellshock присутствует.


Как это выглядит на уязвимой машине под управлением Debian OpenVZ VPS:

Вверху видно что текущая версия Bash это 4.2.


Теперь латаем дыру.


Обновляем список пакетов.

apt-get update

Проверьте свою версию баша. В моем случае это была 4.2+dfsg-0.1+deb7u3. Обновите баш. Здесь описано как выбрать определенную версию пакета для установки в случае если доступны несколько.

apt-get install bash=4.2+dfsg-0.1+deb7u3

Воткак выглядит пропатченный сервер:

Старая версия была 4.2+dfsg-0.1, после обновления стала 4.2+dfsg-0.1+deb7u3. Ну и последний тест, в результате которого значение busted не выводится.


Источник: http://habrahabr.ru/company/mailru/blog/238475/

How to quickly check and fix the Shellshock Bash vulnerability

First, see if this applies to you. Though since all of the bash versions for the last 25 years are vulnerable to this exploit, it most likely does.


To check if your machine has the Shellshock vulnerability, run the following:

env X='() { :;}; echo vulnerable' bash -c "echo this is a test"

If the output includes "busted", the machine is vulnerable to the Shellshock exploit.


Here's an example of how the output looks like on an infected Debian OpenVZ VPS:

At the top of the output you can see the current Bash version being 4.2.


Now, this is the time to update your bash version to the one that is more secure and has the exploit patched.


First, update the package list.

apt-get update

Refer to this in case you get the GPG errors.

Then see what's the latest Bash version you got. In my case it was 4.2+dfsg-0.1+deb7u3. Upgrade Bash to the latest version. Here's how you can specify which version of the package to install in case you have multiple available.

apt-get install bash=4.2+dfsg-0.1+deb7u3

This will install the recent version.


Here's how the patched VPS looks like now:

As you can see, initially the bash version was 4.2+dfsg-0.1, and after the upgrade it's 4.2+dfsg-0.1+deb7u3. Then there's another test which doesn't output the busted value anymore.


Source: http://habrahabr.ru/company/mailru/blog/238475/

UPD: More vulnerabilities to test against: http://en.wikipedia.org/wiki/Shellshock_(software_bug)#Reported_vulnerabilities. Bad news is that not all of those are fixed by the update, so now we wait.

October 22, 2012

Свой DNS-сервер для параноиков

This is how you make a DNS server from your low-end Debian VPS.
apt-get update
apt-get install -y --no-install-recommends resolvconf dnsmasq

sed -i 's,#\(no-resolv\),\1,' /etc/dnsmasq.conf
sed -i 's,#\(no-poll\),\1,' /etc/dnsmasq.conf
sed -i 's,#\(log-queries\),\1,' /etc/dnsmasq.conf
echo "server=208.67.222.222" >> /etc/dnsmasq.conf
echo "log-facility=/var/log/dnsmasq.log" >> /etc/dnsmasq.conf
/etc/init.d/dnsmasq restart

echo "nameserver 127.0.0.1" > /etc/resolv.conf

Теперь можно указать в /etc/hosts список вечно блокируемых на уровне ДНС сайтов:
127.0.0.1 google-analytics.com
127.0.0.1 www.google-analytics.com
127.0.0.1 ssl.google-analytics.com
127.0.0.1 counter.yadro.ru
127.0.0.1 top.list.ru
127.0.0.1 counter.rambler.ru
127.0.0.1 top100-images.rambler.ru
127.0.0.1 mc.yandex.ru
и т.д.
Наполнять любыми доменами по своему желанию.

В статье используется DNS-сервер 208.67.222.222. Список других бесплатныйх ДНСов: (взят отсюда)
Другие DNS-сервисы:

OpenDNS.com:
208.67.222.222
208.67.220.220

http://www.scrubit.com/
67.138.54.100
207.225.209.66

http://www.dnsadvantage.com/
156.154.70.1
156.154.71.1

Level 3 Communications
4.2.2.1
4.2.2.2
4.2.2.3
4.2.2.4
4.2.2.5
4.2.2.6

Verizon
151.197.0.38
151.197.0.39
151.202.0.84
151.202.0.85
151.202.0.85
151.203.0.84
151.203.0.85
199.45.32.37
199.45.32.38
199.45.32.40
199.45.32.43

GTE
192.76.85.133
206.124.64.1

One Connect IP
67.138.54.100

Exetel
220.233.167.31

VRx Network Services
99.166.31.3

SpeakEasy
66.93.87.2
216.231.41.2
216.254.95.2
64.81.45.2
64.81.111.2
64.81.127.2
64.81.79.2
64.81.159.2
66.92.64.2
66.92.224.2
66.92.159.2
64.81.79.2
64.81.159.2
64.81.127.2
64.81.45.2
216.27.175.2
66.92.159.2
66.93.87.2

Sprintlink
199.2.252.10
204.97.212.10
204.117.214.10

Cisco
64.102.255.44
128.107.241.185 

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