Showing posts with label freebsd. Show all posts
Showing posts with label freebsd. Show all posts

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.

March 17, 2012

install openvpn freebsd

cd /usr/ports/security/openvpn && make install clean mkdir /usr/local/etc/openvpn /usr/local/etc/openvpn/easy-rsa /usr/local/etc/openvpn/easy-rsa/keys && cp -R /usr/local/share/doc/openvpn/easy-rsa/2.0/* /usr/local/etc/openvpn/easy-rsa echo "">/usr/local/etc/openvpn/easy-rsa/keys/index.txt && echo "00">/usr/local/etc/openvpn/easy-rsa/keys/serial cd /usr/local/etc/openvpn/easy-rsa chmod +x ./build-ca ./build-dh ./build-inter ./build-key ./build-key-pass ./build-key-pkcs12 ./build-key-server ./build-req ./build-req-pass ./clean-all ./inherit-inter ./list-crl ./openssl*.cnf ./pkitool ./revoke-full ./sign-req ./whichopensslcnf
export KEY_COUNTRY="US" export KEY_PROVINCE="CA" export KEY_CITY="SanFrancisco" export KEY_ORG="Fort-Funston" export KEY_EMAIL="me@example.com"
sh ./clean-all && . ./vars ./build-ca
Generating a 1024 bit RSA private key
..++++++
.........++++++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [US]:
State or Province Name (full name) [CA]:
Locality Name (eg, city) [SanFrancisco]:
Organization Name (eg, company) [Fort-Funston]:
Organizational Unit Name (eg, section) [changeme]:
Common Name (eg, your name or your server's hostname) [changeme]:server2
Name [changeme]:
Email Address [me@example.com]:
./build-key-server server2
Generating a 1024 bit RSA private key
..............++++++
......................................................................++++++
writing new private key to 'server2.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [US]:
State or Province Name (full name) [CA]:
Locality Name (eg, city) [SanFrancisco]:
Organization Name (eg, company) [Fort-Funston]:
Organizational Unit Name (eg, section) [changeme]:
Common Name (eg, your name or your server's hostname) [server2]:
Name [changeme]:
Email Address [me@example.com]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/etc/openvpn/easy-rsa/openssl-0.9.8.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'US'
stateOrProvinceName   :PRINTABLE:'CA'
localityName          :PRINTABLE:'SanFrancisco'
organizationName      :PRINTABLE:'Fort-Funston'
organizationalUnitName:PRINTABLE:'changeme'
commonName            :PRINTABLE:'server2'
name                  :PRINTABLE:'changeme'
emailAddress          :IA5STRING:'me@example.com'
Certificate is to be certified until Mar 15 12:37:05 2022 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
./build-key client2
Generating a 1024 bit RSA private key
.++++++
...++++++
writing new private key to 'client2.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [US]:
State or Province Name (full name) [CA]:
Locality Name (eg, city) [SanFrancisco]:
Organization Name (eg, company) [Fort-Funston]:
Organizational Unit Name (eg, section) [changeme]:
Common Name (eg, your name or your server's hostname) [client2]:
Name [changeme]:
Email Address [me@example.com]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/etc/openvpn/easy-rsa/openssl-0.9.8.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'US'
stateOrProvinceName   :PRINTABLE:'CA'
localityName          :PRINTABLE:'SanFrancisco'
organizationName      :PRINTABLE:'Fort-Funston'
organizationalUnitName:PRINTABLE:'changeme'
commonName            :PRINTABLE:'client2'
name                  :PRINTABLE:'changeme'
emailAddress          :IA5STRING:'me@example.com'
Certificate is to be certified until Mar 15 12:38:53 2022 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
./build-dh exit openvpn --genkey --secret /usr/local/etc/openvpn/easy-rsa/keys/ta.key cp /usr/local/share/doc/openvpn/sample-config-files/server.conf /usr/local/etc/openvpn/openvpn.conf
  • Certificates path:
    Пути к файлам сертификатов:
    ca /usr/local/etc/openvpn/easy-rsa/keys/ca.crt cert /usr/local/etc/openvpn/easy-rsa/keys/server2.crt key /usr/local/etc/openvpn/easy-rsa/keys/server2.key dh /usr/local/etc/openvpn/easy-rsa/keys/dh1024.pem
  • Turn TCP mode on:
    Включаем TCP вместо UDP:
    ;proto udp proto tcp
  • Uncomment the following lines:
    Раскомментируйте следующие строки:
    push "redirect-gateway def1 bypass-dhcp"
    push "dhcp-option DNS 208.67.222.222"
    This will enable routing of all your traffic through the VPN server i.e. your public IP will be same as the assigned to VPS one.
    Именно эти параметры перенаправят весь ваш траффик через сервер, в результате вашим публичным IP станет адрес VDS сервера, а реальный IP будет скрыт.
echo 'openvpn_enable="YES"'>>/etc/rc.conf echo 'openvpn_if="tun"'>>/etc/rc.conf /usr/local/etc/rc.d/openvpn start http://www.lissyara.su/articles/freebsd/security/openvpn/

March 11, 2012

Почему я перешёл с FreeBSD на Debian

Так уж сложилось, что из всего зоопарка многообразия Linux-дистрибутивов я чаще всего пользовался Debian'ом. Особая заслуга здесь дешевых забугорных VPS-провайдеров: многие из них используют виртуализацию на базе технологий OpenVZ или Xen, в результате чего FreeBSD не предлагалась, и в 100% случаев самым вменяемым (для меня) шаблоном оказывался тот самый Debian. А любимая ранее Фрибзда позабылась, оставшись на паре FirstVDS'ных серверов.

January 22, 2012

bash shell urllist crawler

#!/bin/bash
# linux urllist.txt sitemap generator
# run the spider again for deeper URLs
# written by Joachim De Zutter
# released under GPL
site="www.example.com"
startpage="http://www.example.com/"
lynx -dump $startpage | grep -i "$site" | sed -e "s/.*\(http:\/\/.*$site\/[^\"\'<>#\&]*\).*/\1/g" >>urllist.txt
while read a
do
  echo $a
  sort -u urllist.txt | grep -v "\.\.\." >urllist.tmp
  mv urllist.tmp urllist.txt
  lynx -dump $a | grep -i "$site" | sed -e "s/.*\(http:\/\/.*$site\/[^\"\'<>#\&]*\).*/\1/g" >>urllist.txt
done <urllist.txt

November 1, 2011

root

Confucius say:
He who play in root, eventually kill tree.

August 23, 2011

Simple Server Backup To FTP Using TAR

vi /root/backup.sh
#!/bin/sh

# prostoorgru.blogspot.com

### MySQL Connection Params ###
MYSQLU="root"
MYSQLP="hackme"
MYSQLS="localhost"

### FTP Connection params ###
FTPD="/backup/server3"
FTPU="ftp_user"
FTPP="ftp_password"
FTPS="ftp_server"

### Binaries ###
TAR="$(which tar)"
FTP="$(which ftp)"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"

## Time format YYYY-MM-DD_HH-II-SS ###
NOW=$(date +%Y-%m-%d_%H-%M-%S)


### Temporary backup directory ###
TMP_BACKUP_DIR=/tmp/backup$NOW
mkdir $TMP_BACKUP_DIR

### Backup itself ###
# Examples #
cd /etc && $TAR -czpf $TMP_BACKUP_DIR/my-etc-configs.tgz *
cd /home/example.com && $TAR -czpf $TMP_BACKUP_DIR/example.com.tgz --exclude=*.log --exclude=*.zip *
cd /root && $TAR -czpf $TMP_BACKUP_DIR/my-shell-scripts-from-root.tgz *.sh

### MySQL ###
DATABASES="$($MYSQL -u$MYSQLU -h $MYSQLS -p$MYSQLP -Bse 'show databases;')"
for db in $DATABASES
  do
    FILE=$TMP_BACKUP_DIR/$db.sql.gz
    $MYSQLDUMP --add-drop-table --allow-keywords -q -c -u $MYSQLU -h $MYSQLS -p$MYSQLP $db $i | $GZIP -9 > $FILE
done


### Now collect everything into one archive ###
ARCHIVE=`hostname`_$NOW.tgz
cd $TMP_BACKUP_DIR && $TAR -czf $TMP_BACKUP_DIR/$ARCHIVE --exclude=$ARCHIVE *

### Upload to FTP ###
cd $TMP_BACKUP_DIR
$FTP -n $FTPS <<END_SCRIPT
quote USER $FTPU
quote PASS $FTPP
cd $FTPD
mput $ARCHIVE
quit
END_SCRIPT

### Clean ###
rm -rf $TMP_BACKUP_DIR

echo ""
Explanation of commands in "Backup itself" section:
cd %folder_to_back-up% && tar to tmp_dir/%archive_name%.tgz --exclude=%something% *pack_everything*
The last * symbol stands for 'archive everything'. If you need to back up only specific file type, pass the *.ext pattern, e.g. *.php.

This will add an entry to the crontab file telling your system to execute a backup task every 12 hours -- at 1AM and 1PM (i.e. 13:00) at top of the hour (i.e. 00 minutes):
chmod +x /root/backup.sh && echo "00 1,13 * * * sh /root/backup.sh 2>/dev/null" >> /etc/crontab
You can generate any cron schedule that specifically fits your needs.

Sources:

July 30, 2011

freebsd update ports

portsnap fetch

portsnap extract

portsnap fetch update

April 12, 2011

FreeBSD IP alias

FreeBSD IP alias
@/etc/rc.conf
ifconfig_re1="inet %DESIRED_IP% netmask 255.255.255.0"
ifconfig_re1_alias0="inet %REAL_IP% netmask 255.255.255.0"
defaultrouter="%GATEWAY_IP%"

FreeBSD boot time delay

Thats how you change FreeBSD boot time delay to 3 seconds:
@/boot/loader.conf
autoboot_delay="3"

March 27, 2011

cpuinfo freebsd linux

FreeBSD:
sysctl -a | grep -i CPU | less


Linux:
cat /proc/cpuinfo

March 25, 2011

phpmyadmin arrayobject not found

Fatal error: Class 'ArrayObject' not found in /usr/local/www/phpMyAdmin/libraries/List.class.php on line 16

Enable spl.so and simplexml.so libraries.
cd /usr/ports/lang/php5-extensions && make config && make install clean

March 18, 2011

change ssh port freebsd

It's a very good idea to change the default SSH port on working ("production") system. Especially if you enabled root login.

In order to do this, open the /etc/ssh/sshd_config file for editing and uncomment and change the Port directive:
Port 12345

Then restart sshd:
/etc/rc.d/sshd restart


www.freebsdblog.org/77/change-sshd-port/

February 3, 2011

Как рекурсивно массово установить chown на папки и файлы?

Предположим, нам необходимо рекурсивно установить пользователя-владельца some_user (принадлежащего к группе some_group) для всех подпапок и файлов, находящихся в некой директории /home/some_dir. Для этого воспользуемся командой chown, от англ. change owner — сменить владельца.

Заходим в целевую директорию:
cd /home/some_dir


Массово устанавливаем владельцем файлов пользователя some_user из some_group рекурсивно (флаг -R) для абсолюно всего, что лежит в текущей директории (маска *)
chown -R some_user:some_group *


О chmod написано здесь: Как рекурсивно массово установить chmod на папки и файлы?

December 22, 2010

Очистить папку во FreeBSD

Очистка папки в системе FreeBSD может быть выполнена посредством операции удаления rm. Ключи -r и -f (вместе — -rf) позволяют произвести удаление рекурсивно и без лишних вопросов.

Например, просто очистим директорию:
# rm -rf /home/user/data/www/somefolder/*

Или же удалим только файлы с определённым расширением:
# rm -rf /home/user/data/www/somefolder/*.bak

Также доступно удаление по шаблону (затронет лишь те файлы, в имени которых встречается точка с хотя бы двумя символами после нее, т.е. имеющие какое-то расширение):
# rm -rf /home/user/data/www/somefolder/*.??*

September 1, 2010

August 31, 2010

Streamripper + Cron = "Exited with return code 127"?

У меня есть небольшой скрипт record.sh, который при запуске осуществляет запись указанного эфира интернет-радиостанции в файл. Содержимое следующее:
#!/bin/sh
streamripper http://{IP}:{PORT}/{MOUNTPOINT} -a -A -s -d /home/.../records -l 1800 --quiet

При запуске из консоли работает, но из-под cron'а выдает Exited with return code = 127. Решением стало следующее изменение в файле:
#!/bin/sh
/usr/local/bin/streamripper http://{IP}:{PORT}/{MOUNTPOINT} -a -A -s -d /home/.../records -l 1800 --quiet

как видите, помогло указание полного пути к streamripper, т.е. /usr/local/bin/streamripper в моём случае. Чтобы узнать путь к streamripper в своей системе, выполните:
whereis streamripper

May 26, 2010

Установка ejabberd-сервера на FreeBSD

UPD: в этом блоге также есть запись об установке jabberd-сервера, см. тег jabber.

UPD: Памятка мне не забыть вникнуть в -DWITHOUT_JAVA

Ставим erlang:
cd /usr/ports/lang/erlang-lite && make install clean
┌────────────────────────────────────────────────────────────────────┐
│                Options for erlang-lite r13b04_2,1                  │
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │               [ ] JAVA  Enable Java applications               │ │
│ │               [ ] X11   Enable X11 support                     │ │
│ │               [ ] WX    Enable WX Extensions                   │ │
│ │               [X] ODBC  Enable ODBC                            │ │
│ │               [X] SMP   Enable SMP                             │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
│ │                                                                │ │
├─└────────────────────────────────────────────────────────────────┘─┤
│                       [  OK  ]       Cancel                        │
└────────────────────────────────────────────────────────────────────┘

Enable ODBC — разрешили поддержку работы с базами данных (нас интересует MySQL)
cd /usr/ports/net-im/ejabberd && make install clean

echo ejabberd_enable=YES>>/etc/rc.conf

cp /usr/local/etc/ejabberd/ejabberd.cfg.example /usr/local/etc/ejabberd/ejabberd.cfg && cp /usr/local/etc/ejabberd/ejabberdctl.cfg.example /usr/local/etc/ejabberd/ejabberdctl.cfg && cp /usr/local/etc/ejabberd/inetrc.example /usr/local/etc/ejabberd/inetrc


В файле inetrc отредактируйте имя домена.

В файле ejabberd.cfg отредактируйте:
  • {hosts, ["jabber.domain.tld"]}.
  • {auth_method, internal}. -> {auth_method, odbc}.
  • {odbc_server, {mysql, "localhost", "ejabberd", "ejabberd", "ejabberd"}}.
  • {acl, admin, {user, "имя_пользователя_админа", "jabber.domain.tld"}}.
  • Меняем значения:
    mod_last на mod_last_odbc
    mod_offline на mod_offline_odbc
    mod_privacy на mod_privacy_odbc
    mod_private на mod_private_odbc
    mod_roster на mod_roster_odbc
    mod_vcard на mod_vcard_odbc

Сгенерируем самоподписанный сертификат на 10 лет (Внимание! Не забудьте заменить имя домена на своё):
cd /usr/local/etc/ejabberd && openssl req -new -x509 -nodes -newkey rsa:1024 -days 3650 -keyout privkey.pem -out server.pem -subj "/C=XX/ST=XX/L=XX/O=XX/OU=XX/CN=jabber.domain.tld/emailAddress="mail@jabber.domain.tld && cat privkey.pem >> server.pem && rm privkey.pem && mv server.pem ssl.pem


Выдержка из секции listen:
{5222, ejabberd_c2s, [
%%
%% If TLS is compiled in and you installed a SSL
%% certificate, specify the full path to the
%% file and uncomment this line:
%%
{certfile, "/usr/local/etc/ejabberd/ssl.pem"}, starttls,
{access, c2s},
{shaper, c2s_shaper},
{max_stanza_size, 65536}
]},
{5223, ejabberd_c2s, [
{access, c2s},
{certfile, "/usr/local/etc/ejabberd/ssl.pem"}, tls,
{max_stanza_size, 65536}
]},
{5269, ejabberd_s2s_in, [
{shaper, s2s_shaper},
{max_stanza_size, 131072}
]},


Теперь необходимо создать одноимённую БД для ejabberd (я это делал через ISPmanager) и загрузить в неё все таблицы для работы ejabberd. Это можно сделать через консоль или же PHPMyAdmin.
cd /usr/local/etc/ejabberd && fetch http://dl.dropbox.com/u/958658/Misc/ejabberd/mysql.sql && mysql -u root -p -D ejabberd

mysql>\. mysql.sql
mysql> EXIT
Bye


Теперь необходимо установить модуль Erlang, необходимый для работы с MySQL. Узнаём версию ejabberd:
pkg_info | grep ejabberd

У меня была 2.1.35
cd /usr/local/lib/erlang/lib/ejabberd-2.1.5/ebin/ && fetch http://dl.dropbox.com/u/958658/Misc/ejabberd/mysql_r13.tar.gz && tar -xzvf mysql_r13.tar.gz && mv ./mysql_r13/mysql* ./ && rm -rf mysql_r13.tar.gz mysql_r13 && chown -R ejabberd:ejabberd /usr/local/lib/erlang/lib/ejabberd-2.1.5/ebin/mysql*


Внимание! Для ejabberd версии 2.1.3 требовался модуль mysql_r12.tar.gz. Свежую версию я скачал на support.process-one.net.

Запуск:
/usr/local/sbin/ejabberdctl start


Теперь необходимо зарегистрировать указанный выше административный аккаунт. Для управления через web-интерфейс авторизуйтесь полным JID администратора.

Если у вас возникает ошибка Kernel pid terminated (application_controller) ({application_start_failure,kernel,{shutdown,{kernel,start,[normal,[]]}}}) и в /var/log/ejabberd создаётся файл erl_crash_день-время.dump, убедитесь что запускаете ejabberd именно командой /usr/local/sbin/ejabberdctl start

UPDATE Установка mod_logdb, записывающего сообщения в базу данных. Идём в /usr/ports/distfiles/ находим там архив ejabberd-2.1.5, распаковываем его, переходим в получившуюся папку ./ejabberd-2.1.5/src/ и загружаем туда patch-src-mod_logdb-2.1.3.diff. Это — файл патча, применяем его:
cd /usr/ports/distfiles/ejabberd-2.1.5/src && patch -p0 < patch-src-mod_logdb-2.1.3.diff




Устанавливаем:
./configure
gmake install

В конфиг дописываем:
{access, mod_logdb, [{allow, all}]}.

Там, где модули добавляем:
{mod_logdb, [
{dbs, [{mysql5, [{user, "%пользователь_бд%"},{password, "%пароль%"},{server, "localhost"},{port, 3306},{db, "%имя_бд%"}]}]},
{vhosts, [{"localhost", mysql5}]}
]},

May 24, 2010

Изменить информацию о пользователе во FreeBSD

Если необходимо отредактировать пользователя (сменить, например, shell, или домашнюю директорию), воспользуйтесь командой chpass:
chpass username

Здесь username – имя пользователя, информацию о котором необходимо отредактировать. В появившемся редакторе удалите ненужные символы клавишей Delete, введите новые нажав Insert, затем выйдите из режима редактирования нажав Escape и сохраните обновления комбинацией :wq, где w — write (записать), а q — quit (покинуть редактор). Как вы уже могли догадаться, речь идёт о редакторе vi.