суббота, 28 июня 2014 г.

Проксификация программ на Linux

Решение подходит в т.ч. и для windows приложений запускаемых через wine
Ставим пакет dante-client (он даст нам утилиту socksify)
sudo apt-get install dante-client
Настраиваем (в Ubuntu настройки тут – /etc/dante.conf)
В конце файла:
route {
   from: 0.0.0.0/0 to: 0.0.0.0/0 via: 192.168.1.25 port = 3128
   proxyprotocol: http_v1.0
}
Где 192.168.1.25 – адрес http прокси, 3128 – порт прокси.
Запуск нужного приложения делается следующей командой:

socksify <имя_приложения>
Для Wine вобщем-то то же самое, но дописываем еще и имя запускаемой в wine программы, например для World of Warcraft:
socksify wine icq.exe

RPM Packages Verification

The command rpm -V (The options -y and --verify are equivalent) verifies an installed package. It can alert you to changes made to any of the files installed by RPM.
Also, if a package requires capabilities provided by another package, it can make sure the other package is installed, too.
rpm -V
Output format:
SM5DLUGT c filename
Where:
S is the file size.
M is the file's mode.
5 is the MD5 checksum of the file.
D is the file's major and minor numbers.
L is the file's symbolic link contents.
U is owner of the file.
G is the file's group.
T is the modification time of the file.
c appears only if the file is a configuration file. This is handy for quickly identifying config files, as they are very likely to change, and therefore, very unlikely to verify successfully.


Each of the eight attribute flags will only appear if there is a problem. Otherwise, a "." will be printed in that flag's place.
rpm -Vv $(rpm -qf /sbin/ifdown --qf="%{name}\n") | more

 http://www.rpm.org/max-rpm/s1-rpm-verify-output.html
 http://www.rpm.org/max-rpm/s1-rpm-verify-what-to-verify.html

SSH авторизация по ключу

mik@m1k:~$ ssh-keygen -t dsa -b 1024 -f /home/user/.ssh/id_dsa
-t dsa - тип ключа. Есть rsa и dsa. Dsa это для второй версии ssh, которая сейчас везде по умолчанию. Rsa - первая версия ssh.
-b 1024 (optional) длина ключа
-f /home/user/.ssh/id_dsa - (optional) каталог и имя файла где будет сохранен ключ id_dsa и его публичный ключ id_dsa.pub

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

В итоге получаем два файла id_dsa и id_dsa.pub. PUB ключ - это публичный, а id_dsa секретный.
 Переносим файл id_dsa.pub на сервер, к которому мы будем подключаться. Помещаем в директорию /home/user/.ssh/ того пользователя под которым мы будем соединяться по ssh.

Делаем это либо в ручную копированием и вставкой ключа, либо следующей командой:
ssh-copy-id -i .ssh/id_rsa.pub root@212.90.160.1
Теперь надо изменить конфигурацию ssh сервера (файл /etc/ssh/sshd_config) той машины куда мы перенесли публичный ключ.
Раскомментируем строки по которым мы разрешим использовать ключи.
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys
Переименовываем ключ id_dsa.pub в файл authorized_keys, назначаем файлу правами 600 и оставляем файл в папке /home/user/.ssh.

Пробуем соединиться с сервером:
В случае если имя ключа имеет название по умолчанию (id_dsa), ключ можно не указывать.
 ssh user@212.90.160.1

Если же при генерации ключа было указано имя отличное от id_dsa, например id_dsa2, то нужно явно указать имя ключа.

ssh -i /home/user/.ssh/id_dsa2 user@212.90.160.1

Выставив в конфигурации sshd PermitRootLogin no мы запретим авторизацию по паролю для рута, а указав UsePAM no мы сможем подключиться к серверу только по ключу.

четверг, 29 мая 2014 г.

How to block shells in 777 directories

Add this to your httpd.conf file. Change directory name.
<Directory "/www/site.ru/images">

php_flag engine off
RemoveHandler .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml
AddType application/x-httpd-php-source .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml
AddType "text/html" .php .cgi .pl .fcgi .fpl .phtml .shtml .php2 .php3 .php4 .php5 .asp .jsp

</Directory>

php_flag engine off - disable php

 RemoveHandler - disable processing of files with given extensions. This directive removes any handler associations for files with the given extensions. Consequently, .htaccess files in subdirectories can undo any associations inherited from parent directories or the server configuration files.

AddType - AddType добавит Content-Type в HTTP-заголовок - это нужно, чтобы браузер показывал исходный код PHP как текст, а не пытался сохранить.
AddType "text/html" 

AllowOverride

Эта директива регулирует отношения между глобальным файлом доступа и пользовательскими файлами .htaccess. В директиве указываются разделенные пробелами опции управления доступом, переопределение которых в файле .htaccess, находящемся в дереве каталогов ниже этого каталога, разрешено. Возможные значения директивы:

• None. Сервер игнорирует файлы .htaccess в этом каталоге. Если вы не намерены использовать для каталога файлы .htaccess, вам следует явно установить эту опцию, поскольку это повысит производительность сервера.

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

• Options. Разрешает использование директивы Options (см. ниже раздел ?Options¦),

• Filelnfo. Разрешает использование в файлах .htaccess директив Add-Туре и AddEncoding (см. раздел ?srm/conf: карта ресурсов сервера¦, содержащий полное описание).

• AuthConfig. Разрешает использование директив AuthName, AuthType, AuthUserFile и AuthGroupFile, необходимых для защиты каталогов паролями.

• Limit. Разрешает использование директивы секционирования <Limit>. См. раздел, посвященный директиве <Limit>, в котором приведено подробное описание.

Options

Директива Options позволяет управлять тем, какие функции сервера доступны для использования в каталоге, указанном в секции <Directory> или в файле .htaccess. В директиве Options можно использовать следующие аргументы:

• None. В указанном каталоге не разрешается использование каких-либо функций.

• All В указанном каталоге разрешается использование всех возможностей (принимается по умолчанию).

• FollowSymLinks. Сервер следует символьным ссылкам, имеющимся в указанном каталоге.

• SymLinksIfOwnerMatch. Сервер следует символьным ссылкам, только если каталог назначения принадлежит тому же пользователю, что и сама ссылка.

• ExecCGI. В указанном каталоге разрешается выполнение сценариев CGI.

• Includes. В указанном каталоге разрешено использование серверных включений. Использование серверных включений требует, чтобы сервер производил синтаксический разбор всех HTML-файлов перед отправкой их клиентам. Нечего и говорить, что это крайне нагружает сервер, поэтому мы бы порекомендовали отключить эту опцию. Если вам необходимы серверные включения, разрешите их на уровне отдельных файлов при помощи директивы AddType, как это описано в разделе ?srm/conf: карта ресурсов сервера¦

• Indexes. Сервер разрешает пользователям заказывать индексную страницу указанного каталога. Выключение этой опции запрещает передачу только списка файлов в каталоге, но не файла index.html.

• IncludesNoExec. Эта директива разрешает использование в указанном каталоге серверных включений, но запрещает запуск из них внешних программ.

 

Order, Deny, Allow

Директива Order управляет состоянием доступа по умолчанию и порядок, в котором доступ разрешается или запрещается. Order может принимать 3 значения:
  • Allow,Deny - доступ по умолчанию запрещен, кроме хостов, указанных в строке после Allow from.
  • Deny,Allow - доступ по умолчанию разрешен, кроме хостов, указанных в строке после Deny from
  • Mutual-failure - разрешен доступ только для тех хостов, которые присутствуют в Allow и отсутствуют в Deny.
Следующий пример отличается только значением Order: "Deny,Allow" вместо "Allow,Deny". Но логика предоставления прав доступа Apache изменится, на первый взгляд, весьма не ожиданно. Доступ будет открыт абсолютно ко всем доменам, даже к поддомену foo.apache.org, явно запрещенному строкой "Deny from foo.apache.org". Это происходит потому, что порядок строк "Allow from ..." и "Deny from ..." не имеет значения. Порядок установки правил задается директивой Order, изходя из чего Апач сначала запрещает доступ к foo.apache.org, а потом перезаписывает это правило, изходя из директивы "Allow from apache.org".

Order Deny,Allow
Allow from apache.org
Deny from foo.apache.org

вторник, 13 мая 2014 г.

Установка tor, privoxy and torsocks in Linux

Try

Debian-like

sudo apt-get update
sudo apt-get install tor tor-geoipdb

Fedora

sudo yum install tor
If you get fault, let's do next:  

Step 1: Add Tor Repository

Firstly we need to add tor yum repository in our system. To create tor repository create file /etc/yum.repos.d/tor.repo and add following content on basis of your system.

For CentOS/RHEL 6

[Tor]
name=Tor Project Repo
baseurl=http://deb.torproject.org/torproject.org/rpm/el/6/$basearch/
gpgcheck=1
enabled=1
gpgkey=http://deb.torproject.org/torproject.org/rpm/RPM-GPG-KEY-torproject.org.asc

For Fedora 20

[Tor]
name=Tor Project Repo
baseurl=http://deb.torproject.org/torproject.org/rpm/fc/20/$basearch/
gpgcheck=1
enabled=1
gpgkey=http://deb.torproject.org/torproject.org/rpm/RPM-GPG-KEY-torproject.org.asc

Step 2: Install Tor

yum install tor

Start Tor

tor
or
sudo /etc/init.d/tor start
sudo /etc/init.d/privoxy start
or
sudo /etc/init.d/torsocks start

Следующие основные пакеты будут автоматически также установлены :
tor  Анонимизирующая сеть для TCP
tor-geoipdb  GeoIP база данных для Tor
torsocks  Упрощает использование SOCKS-совместимых приложений с Tor

Использование torsocks:
torsocks (like a torify) is an improved wrapper that explictly rejects UDP, safely resolves DNS lookups and properly socksifies your TCP connections.
torsocks wget -q -O - ip.appspot.com
or
torify ssh user@host
The configuration file of Privoxy is located in /etc/privoxy/config
# Generally, this file goes in /etc/privoxy/config
#
# Tor listens as a SOCKS4a proxy here:
forward-socks4a / 127.0.0.1:9050 .
confdir /etc/privoxy
logdir /var/log/privoxy
# actionsfile standard  # Internal purpose, recommended
actionsfile default.action   # Main actions file
actionsfile user.action      # User customizations
filterfile default.filter

# Don't log interesting things, only startup messages, warnings and errors
logfile logfile
#jarfile jarfile
#debug   0    # show each GET/POST/CONNECT request
debug   4096 # Startup banner and warnings
debug   8192 # Errors - *we highly recommended enabling this*

user-manual /usr/share/doc/privoxy/user-manual
listen-address  127.0.0.1:8118
toggle  1
enable-remote-toggle 0
enable-edit-actions 0
enable-remote-http-toggle 0
buffer-limit 4096
If you got any problems with torsocks, you need to install and configure it by manually. In my case I had to patch torsocks to prevent arriving errors. https://code.google.com/p/torsocks/issues/detail?id=3

вторник, 29 апреля 2014 г.

SQL injection scanners benchmark

Positives (vulnerable)False positives (not vulnerable)Positives with unstable responseFalse positives with unstable response
Total16224114562016840
sqlmap 0.8-11128229576229
skipfish 1.81b10937378237
wapiti 2.2.1111515813443
acunetix7395010030
w3af 1.0-rc5133161981572126

Potential HTTP Headers for SQL injections

HTTP Header fields
HTTP header fields are components of the message header of requests and responses in the Hypertext Transfer Protocol (HTTP). They define the operating parameters of an HTTP transaction.
Example: Request HTTP
GET / HTTP/1.1
Connection: Keep-Alive
Keep-Alive: 300
Accept:*/*
Host: host
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16 ( .NET CLR 3.5.30729; .NET4.0E)
Cookie: guest_id=v1%3A1328019064; pid=v1%3A1328839311134
We can consider the HTTP Cookies, when are stored in databases for sessions identification, as the first potential HTTP variables which should be tested. We will see next in an example of Cookie based SQL injection. There are also other HTTP headers related to the application.

X-Forwarded-For

X-Forwarded-For is an HTTP header field considered as a de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer.

We will see an example of this flaw basing of a form submission.
$req = mysql_query("SELECT user,password FROM admins WHERE user='".sanitize($_POST['user'])."' AND password='".md5($_POST['password'])."' AND ip_adr='".ip_adr()."'"); 
The variable login is correctly controlled due to the sanitize() method.
function sanitize($param){ if (is_numeric($param)) { return $param; } else { return mysql_real_escape_string($param); } }
Let us inspect the ip variable. It is allocating the output of the ip_addr() method.
function ip_adr() { if
(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip_adr = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip_adr = $_SERVER["REMOTE_ADDR"]; } if (preg_match("#^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}#",$ip_addr)) { return $ip_adr; } else { return $_SERVER["REMOTE_ADDR"]; } }
Obviously, the IP address is retrieved from the HTTP header X_FORWARDED_FOR. This later is controlled by the preg_match which verifies if this parameter does hold at least one IP address. As a matter of fact, the environment variable HTTP_X_FORWARDED_FOR is not properly sanitized before its value being used in the SQL query. This can lead to run any SQL query by injecting arbitrary SQL code into this field.
The simple modification of this header field to something like:
GET /index.php HTTP/1.1
Host: [host]
X_FORWARDED_FOR :127.0.0.1' or 1=1#
will lead to bypass the authentication control.


User-agent

User agent is an HTTP header field gives the software program used by the original client. This is for statistical purposes and the tracing of protocol violations. It should be included. The first white space delimited word must be the software product name, with an optional slash and version designator.
Not all applications are written to capture the user-agent data, but sometimes applications are designed to store such information (ex: shopping cart providers) to make use of it. In this case, it’s worth investigating the user-agent header for possible issues.
HTTP query example:
GET /index.php HTTP/1.1
Host: [host]
User-Agent: aaa' or 1/* 
 
Referer

Referer is another HTTP header which can be vulnerable to SQL injection once the application is storing it in database without sanitizing it. It’s an optional header field that allows the client to specify, for the server’s benefit, the address ( URI ) of the document (or element within the document) from which the URI in the request was obtained. This allows a server to generate lists of back-links to documents, for interest, logging, etc. It allows bad links to be traced for maintenance.
Example:
GET /index.php HTTP/1.1 Host: [host] User-Agent: aaa' or 1/* Referer: http://www.yaboukir.com

Attacker’s perspective?

As we all know, injection flaws are ranked the first in The OWASP Top 10 Web Application Security Risks. Attackers are increasingly seeking for injection points to get full access of your databases. No matter the injection input vector’s type, whether it’s a GET, POST, Cookie or other HTTP headers; the important for intruders is always to have at least one injection point which let them start the exploitation phase.

Manually testing Cookie based SQL injections

Sqlmap as example

Sqlmap is a popular open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers.
Sqlmap supports the HTTP cookie features so it can be useful in two ways:
  • Authentication based upon cookies when the web application requires that.
  • Detection and exploitation of SQL injection on such header values.
By default sqlmap tests all GET parameters and POST parameters. When the value of –level is set to 2 or above it tests also HTTP Cookie header values. When this value is set to 3 or above, it tests also HTTP User-Agent and HTTP Referer header value for SQL injections. It is however possible to manually specify a comma-separated list of parameter(s) that you want sqlmap to test. This will bypass the dependence on the value of –level too.

Tested HTTP parameter Level in sqlmap
GET 1 (Default)
POST 1 (Default)
HTTP Cookie 2 ≥
HTTP User-Agent 3 ≥
HTTP Referer 3 ≥

For instance, to test for GET parameter id and for HTTP User-Agent only, provide -p id,user-agent.
This is an example of how we can test the parameter named security of an HTTP Cookie of the DVWA (Damn Vulnerable Web Application).
./sqlmap.py -u 'http://127.0.0.1/vulnerabilities/sqli/?id=1&Submit=Submit#'
--cookie='PHPSESSID=0e4jfbrgd8190ig3uba7rvsip1; security=low'
--string='First name' --dbs --level 3 -p PHPSESSID
 
 
 

Туннелирование порта через SSH

Например, работаем на виртуальном хостинге, там Apache, MySQL. Хотим подключить визуальный клиент администрирования MySQL. Много есть случаев, когда было бы удобно коннектится на удаленном компьютере к его локальным портам.
Организация туннеля

Давайте попробуем подключить клиент администрирования MySQL на удаленном компьютере.

Естественно считаем, что вход по SSH по ключу уже настроен.

Тогда поднять туннель не просто, а очень просто. На своем локальном компьютере выполняем команду:
ssh -f username@remote_host -L 127.0.0.1:4306:127.0.0.1:3306 -N

Где:

-f    Говорит ssh уйти в бэкграунд
username    Имя пользователя на удаленном компьютере
remote_host    Имя или IP адрес удаленного хоста
-L 127.0.0.1:4306:127.0.0.1:3306    Пробросить тоннель с локального порта 4306 на удаленный порт 3306
-N    Не выполнять команду на удаленном хосте.
Подключение клиента

Теперь можно подключать клиента. Запускаем mysql-admin и конфигурируем его следующим образом:
Server Hostname:    127.0.0.1
Port:    4306

Пользователь и пароль - ну ясно, так как у нас сконфигурировано.

Примечание: Мы перенаправили с нашего хоста порт 4306, для того, чтобы в случае, если у нас на локальном хосте тоже работает MySQL, не мешать ему.

http://blog.swlogic.eu/2011/07/16/tunnelirovanie-porta-cherez-ssh/