Saturday, April 5, 2014

Linux ss command

Bài viết sau đây mô tả về linux ss command. Dòng lệnh này hiện thị nhiều thông tin và nhanh hơn dòng lệnh netstat. Dòng lệnh netstat nhận thông tin từ các file khác nhau trong /proc nên rất chậm. Còn dòng lệnh ss lấy trực tiếp từ kernel space rất nhanh. Dòng lệnh ss-socket statistics, Trong ví dụ sau, dòng lệnh ss check kết nối và socket statisctis.

Links:
Dòng lệnh hữu ích trong linux
Umask và thiết lập umask trong linux
Centos 6.5 tạo User và Group Basic đến Advance
Linux ss command
linux ss command
Hình Ảnh "Linux ss command"

List tất cả các kết nối

whoami@whoami-K53E ~ $ ss | less
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
u_str ESTAB 0 0 * 14579 * 15563
u_str ESTAB 0 0 @/tmp/.X11-unix/X0 11637 * 14172
u_str ESTAB 0 0 @/tmp/dbus-GgD1mQVgda 11874 * 13129
u_str ESTAB 0 0 @/tmp/dbus-cJFLvX3o 13115 * 11856
u_str ESTAB 0 213504 @/tmp/.X11-unix/X0 14727 * 15821
u_str ESTAB 0 0 * 12994 * 14505
u_str ESTAB 0 0 * 17184 * 17634

Dòng lệnh phía trên list tất cả các kết nối tcp,udp và socket

Filter các kết nối tcp,udp và unix

Ta muốn view :)) kết nối tcp,udp or unix ta '-t','-u' or '-x'
whoami@whoami-K53E ~ $ ss -t
State Recv-Q Send-Q Local Address:Port Peer Address:Port
ESTAB 0 0 192.168.1.5:36180 173.252.107.18:https
CLOSE-WAIT 38 0 192.168.1.5:41617 118.214.83.51:https

Dòng lệnh phía trên list kết nối tcp với '-t' option. mặc định, thì nó list "established" hay CONNECTED" mà không list “Listen”, Ta thêm '-a' option list tất cả các kết nối. whoami@whoami-K53E ~ $ ss -t a

Hiển thị tên process và pid

whoami@whoami-K53E ~ $ ss -ltp

Hiện thị socket statistic

whoami@whoami-K53E ~ $ ss -s
Total: 546 (kernel 0)
TCP: 13 (estab 3, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
* 0 - -
RAW 0 0 0
UDP 19 16 3
TCP 13 10 3
INET 32 26 6
FRAG 0 0 0

Chỉ hiển thị kết nối IPv4 or IPv6

show ipv4 :D whoami@whoami-K53E ~ $ ss -tl4
show ipv6 :D whoami@whoami-K53E ~ $ ss -tl6

Filter địa chỉ và số port

Cấu trúc:
$ ss [ OPTIONS ] [ STATE-FILTER ] [ ADDRESS-FILTER ]

whoami@whoami-K53E ~ $ ss -at '( dport = :ssh or sport = :ssh )'
# Filter by address
whoami@whoami-K53E ~$ ss -nt dst 192.168.1.34

More example:
whoami@whoami-K53E ~ $ ss -t4 state time-wait
whoami@whoami-K53E ~ $ ss -t4 state established
whoami@whoami-K53E ~ $ ss -nt dst :443 or dst :80
whoami@whoami-K53E ~ $ # source address is 127.0.0.1 and source port is greater than 5000
whoami@whoami-K53E ~ $ ss -nt src 127.0.0.1 sport gt :5000

Kết luận: “Linux ss command” :D rất hữu ích, rất nhanh :)).Biết thêm thông tin về dòng lệnh
$man ss
Muốn biết thêm thông tin filter ở đây là hệ thống ubuntu,debian ta install. file /usr/share/doc/iproute2-doc/ss.html chứa cấu trúc filter.
whoami@whoami-K53E ~ $ sudo apt-get install iproute2-doc

Read more

Tuesday, April 1, 2014

Dòng lệnh hữu ích trong linux

Bài viết sau đây hướng dẫn về các Dòng lệnh hữu ích trong linux. Cũng như các hệ thống unix,centos,ubuntu....

Links:
Dòng lệnh hữu ích trong linux
Umask và thiết lập umask trong linux
Linux sử dụng Openssl tạo CA
Centos 6.5 tạo User và Group Basic đến Advance
”Linux
Hình Ảnh:Terminal phía trên :)) một số Dòng lệnh hữu ích trong linux

Các dòng lệnh File
$ ls : list danh sách trong thư mục
$ ls -al : list tất cả danh sách và file ẩn trong thư mục
$ mkdir dir : lệnh tạo thư mục
$ mkdir -p /A/B : lệnh tao thư mục có dạng /A/B :)
$ rm file : xóa file
$ rm -rf dir : xóa thư mục
$ cp file1 file1 : copy file1 đến file 2
$ cp -r dir1 dir2 : copy thư mục dir1 đến dir2 nếu thư mục dir2 không có
$ mv file1 file2 : di chuyển file1 đến file2
$ ln -s file link : tạo symbolic link link đến file
$ touch file : tạo và update file
$ more file : output nội dung của file
$ head file : output 10 dòng đầu tiên của file
$ tail file : output 10 dòng cuối của file

Network
$ arp-scan -I interface -l : scan IP address confict
$ ping host : kiểm tra mạng của host
$ whois domain : nhận thông tin whois của domain
$ dig domain : nhận thông tin DNS của domain
$ dig -x host : reverse lookup host
$ wget file : download file
$ ifconfig -a : show thông tin tất cả các cổng và địa chỉ IP
$ ifconfig eth0 mtu 9000 up : set mtu đến 9000
$ ifconfig -a | grep HWaddr : hiển thị địa chỉ MAC
$ ethtool eth0 : show trạng thái ethernet ( set full deplex)
$ netstat -tupl : list các port (tcp,udp,pid) active listing

Install Package
$ dpkg -i dkg.deb : install gói debian
$ dpkg -r dkg.deb: remove gói debian
$ sudo apt-get update ; sudo apt-get upgrade : update và upgrade
$ sudo apt-get install package : install package
$ sudo apt-get remove package : remove package
$ rpm -Uvh dkg.rpm : install gói RPM
$ rpm -e dkgname : remove gói RPM
install từ source $ ./configure
$ make
$ make install

Statistic và Analyze
$ top : hiển thị và update cpu process
$ vmstat 2 : hiển thị thống kê virtual memory
$ tcpdump -i eth0 : capture tất cả các packet trên interface eth0
$ watch df -h : xem dữ liệu thay đổi liên tục
$ ps : Hiển thị các active process
$ ps -aux | grep “iptables” : tìm tất cả các process id liên quan iptables
$ kill -9 “name” : kill process tên “name”

SSH
$ ssh user@host : kết nối ssh như user
$ ssh -p user@host : kết nối ssh sử dụng port

comperssion
$ gzip file : nén file và file có đuôi file.gz
$ gzip -d file.gz : giải nén file.gz
$ tar cf file.tar file : tạo file.tar chứ nội dung file
$ tar xf file.tar : extract file từ file.tar
$ tar czf file.tar.gz file : tạo file tar với nén gzip
$ tar xzf file.tar.gz : extract file tar sử dụng gzip
$ tar cjf file.tar.bz2 : tạo file tar với nén bzip2
$ tar xjf file.tar.bz2 : extract file tar sử dụng bzip2

File permission
$ ls -lFa
drwxr-xr-x 2 whoami whoami 4096 Th03 24 09:38 abc/
-rw-r--r-- 1 whoami whoami 15222 Th03 24 09:14 lenh co ban linux.odt

Note: 'd' là thư mục. '-' là file :) .ví dụ ở trên thư mục abc drwxr-xr-x gồm user:whoami có quyền rwx và group:whoami r-x và other r-x. Sử dụng dòng lệnh chmod để permission.
chmod octal files
octal : 4 -read (r)
2 -write (w)
1 -excute (x)
ví dụ : chmod 777 file : read, write, excute cho tất cả :)

system info
$ cat /etc/lsb-release : xem version bản distro
$ cat /proc/cpuinfo : thông tin cpu
$ cat /proc/meminfo : thông tin memory
$ df -h : show disk theo kb,MB,GB
$ du : show không gian thư mục sử dụng
$ free -h : hiển thị số lượng sử dụng memory trong hệ thống
$ whereis command : locate binary, source, trang manual dòng lệnh
$ which command : locate dòng lệnh
$ w : display thông tin user đang online
$ finger user : display thông tin về user
$ uname -a : show thông tin về kernel
$ last reboot: show lịch sử hệ thống reboot
$ uptime: show system running+load bao lâu.

Kết Luận:Phía trên một số dòng lênh hữu ích trong linux. Sẽ update thêm sau :))


Read more

Monday, March 31, 2014

Haproxy 1.5 Protect Web Server Chống lại Slowloric DOS Attack

Slowloric là gì???
Slowloric là một script mở kết nối TCP và gửi HTTP request header rất chậm đến web server để giữ kết kết.
slowloris attack
Như hình trên, Slowloric Attack gửi HTTP request header không đầy đủ đến web server. Làm server chờ đợi HTPP request đầy đủ và normal user chờ đợi HTTP relay của server. do đó. Normal user bị lỗi 503 service unavailable. Slowloric là attack ở layer 7.

Configuration
defaults
  mode http
  maxconn 19500
  timeout client 60s  
  timeout server 60s
  timeout queue 60s
  timeout connect 4s
  timeout http-request 5s
  option httpclose
  option abortonclose
  balance roundrobin
  option forwardfor #  Biết client's IP trong X-Forwarded-For.
  retries 2
frontend www
  bind :80
  default_backend apache
backend app
  server app1 192.168.1.2:8080 maxconn 1000
Read more

Linux Sử dụng OpenSSL tạo Certificate Authority ( CA )


1.Tạo Private key 
# openssl genrsa -des3 -out www.pvhuu.blogspot.com.key 1024 
2.Tạo Certificate Signing Request ( CSR )
# openssl req -new -key www.pvhuu.blogspot.com.key -out www.pvhuu.blogspot.com.csr

3. Tạo a Self-Signed SSL Certificate
Ví dụ: Tạo một a Self-Signed SSL Certificate hợp lệ 1 năm như sau.
# openssl x509 -req -days 365 -in www.pvhuu.blogspot.com.csr -signkey www.pvhuu.blogspot.com.key -out www.pvhuu.blogspot.com.crt


Read more

Linux Sử dụng Nginx như HTTP Load Balancer

Bài viết sau đây, mô tả các ví dụ và khái niệm liên quan nginx hoạt động như Load Balancer trong hệ thống Linux. Load Blancer thường được sử dụng qua nhiều các application giúp tối ưu resource utilization, maximizing throughput, giảm latency, và đảm bảo fault-tolerant.

Links:
Sử dụng Nginx như HTTP Load Balancer
Hướng dẫn cài đặt nginx 1.5.10
Hướng dẫn cơ bản nginx 1.5.10

Các phương pháp Load Blancer trong Nginx

  • least-connected :Request tiếp theo đến các server với số lượng ít các active connection nhất.
  • ip-hash :một hash-function sử dụng để xác định server nào lựa chọn request tiếp theo (dựa trên client’s IP address).
  • round-robin : các request đến các application server sẽ được distributed trong round-robin.

Hình Ảnh dưới đây Load Balancer trong nginx

Cấu hình mặc định nginx load blancer
http {
    upstream app1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }
    server {
        listen 80;
        location / {
            proxy_pass http://app1;
        }
    }
}

Cấu hình phía trên,có 3 trường hợp application giống nhau chạy trong srv1-srv3. Nếu ta không cấu hình phương thức rõ ràng, mặc định là round-robin

Least connected load balancing

Nginx sẽ cố gắng không để quá tải một ứng dụng máy chủ busy với quá nhiều yêu cầu, distributing request mới đến server ít busy hơn

upstream app1 {
        least_conn;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

Session persistence

Với round-robin hay least-connected load balancing, mỗi request của client có thể distributing đến các server khác nhau. với ip-hash, địa chỉ client sử dụng hashing key để xác định server nào trong server group lựa chọn cho request clients.

upstream app1 {
    ip_hash;
    server srv1.example.com;
    server srv2.example.com;
    server srv3.example.com;
}

Weighted load balancing
upstream app1 {
        server srv1.example.com weight=3;
        server srv2.example.com;
    }

Cấu hình phía trên, giả sử có 5 request mới sẽ distributed qua các ứng dụng như sau: 3 requests sẽ trực tiếp đến srv1, 2 request đến srv2.

Kết Luận
Nginx là một web server cấu hình phức tạp
Read more

Linux Bảo mật Nginx Web Server tốt nhất


Làm thế nào để tăng bảo mật cho nginx web server chạy hệ điều hành Linux hay UNIX
Mặc định Config Files và nginx port
  • /usr/local/nginx/conf/ : Thư mục cấu hình nginx server và /usr/local/nginx/conf/nginx.conf là file cấu hình chính.
  • /usr/local/nginx/html/ : mặc định document location
  • /usr/local/nginx/logs/ : mặc định file logs.
Nginx mặc định port HTTP : TCP 80
Nginx mặc định port HTTPS: : TCP 443

Test file cấu hình nginx khi mỗi lần thay đổi
#/usr/local/nginx/sbin/nginx -t
Mỗi lần thay đổi cấu hình ta load dòng lệnh dưới đây
#/usr/local/nginx/sbin/nginx -s reload

1.Turn on SELINUX
Chạy dòng lênh getsebool -a để xem hệ thống lockdown

#getsebool -a | less
#getsebool -a | grep off
#getsebool -a | grep o

ví dụ : dòng lệnh getsebool -a | grep off

[root@localhost ~]# getsebool -a | grep off
abrt_anon_write --> off
allow_cvs_read_shadow --> off
allow_daemons_use_tcp_wrapper --> off
Để bảo mật, ta thiết lập "on" và thay đổi "off" nếu không muốn áp dụng bằng dòng lệnh setsebool.

2.Cho phép tùy chọn Mount với quyền tối thiểu
Ví dụ: tạo một phân vùng ( partition ) /dev/sda4 và mount /nginx. chắc chắn /nginx mount với quyền ( permissions) noexec,nodev và nosetuid .file /etc/fstab cho mount /nginx như sau.

LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1 2
Note: Tạo phân vùng mới sử dụng dòng lệnh fdisk and mkfs.ext3

3.Cấu hình /etc/sysctl.conf
Thiết lập Linux kernel và networking qua /etc/sysctl.conf
# Avoid a smurf attack
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Turn on protection for bad icmp error messages
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Turn on syncookies for SYN flood attack protection
net.ipv4.tcp_syncookies = 1
# Turn on and log spoofed, source routed, and redirect packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
# No source routed packets here
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Turn on reverse path filtering
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Make sure no one can alter the routing tables
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
# Don't act as a router
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# Turn on execshild
kernel.exec-shield = 1
kernel.randomize_va_space = 1
# Tuen IPv6
net.ipv6.conf.default.router_solicitations = 0
net.ipv6.conf.default.accept_ra_rtr_pref = 0
net.ipv6.conf.default.accept_ra_pinfo = 0
net.ipv6.conf.default.accept_ra_defrtr = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.default.dad_transmits = 0
net.ipv6.conf.default.max_addresses = 1
# Optimization for port usefor LBs
# Increase system file descriptor limit
fs.file-max = 65535
# Allow for more PIDs (to reduce rollover problems); may break some programs 32768
kernel.pid_max = 65536
# Increase system IP port limits
net.ipv4.ip_local_port_range = 2000 65000
# Increase TCP max buffer size setable using setsockopt()
net.ipv4.tcp_rmem = 4096 87380 8388608
net.ipv4.tcp_wmem = 4096 87380 8388608
# Increase Linux auto tuning TCP buffer limits
# min, default, and max number of bytes to use
# set max to at least 4MB, or higher if you use very high BDP paths
# Tcp Windows etc
net.core.rmem_max = 8388608
net.core.wmem_max = 8388608
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_window_scaling = 1

4.Hủy bỏ tất cả các Nginx modules không mong muốn

Gõ dòng lệnh dưới đây để xem modules bật hay tắt trong khi compiling nginx server
# ./configure --help | less
Ví dụ: disable SSI và autoindex modules
# ./configure --without-http_autoindex_module --without-http_ssi_module
# make
# make install

......continuous ..........

Read more

Centos 6.5 Thiết lập MailScanner, Clam Antivirus và SpamAssasin


Chuẩn bị hệ thống
  • Disabled SElinux trong Centos
[root@localhost ~]# vi /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted
  • Add reqpository trong Centos
Xem  version Centos
[root@localhost ~]# cat /etc/redhat-release
CentOS release 6.5 (Final)
Xem Centos 32bit hay 64 bit
[root@localhost ~]# uname -a
Linux localhost.localdomain 2.6.32-431.5.1.el6.x86_64 #1 SMP Wed Feb 12 00:41:43 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

Cài đặt RPMforge trong Centos
Cho 64-bit CentOS 6.*:
#rpm -Uvh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
Cài đặt các gói Dependencies
# yum install gcc cpp perl bzip2 zip unrar make patch automake rpm-build perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib zlib-devel
Cài đặt ClamAV và SpamAssassin 
#yum install clamav spamassassin 
update ClamAV
# freshclam -v
Update và start SpamAssassin
# sa-update
# service spamassassin start
# chkconfig spamassassin on
Fix path MailScanner bằng cách tạo symbolic link
# ln -s /usr/bin/freshclam /usr/local/bin/freshclam 

Cấu hình Postfix
# service postfix stop
# chkconfig postfix off 
Postfix header_checks giữ bất kỳ incoming email mà postfix nhận.
# vi /etc/postfix/main.cf 
## This line is added ##
header_checks = regexp:/etc/postfix/header_checks

#vi /etc/postfix/header_checks 
## This line is added ##
/^Received:/ HOLD

Chuẩn bị MailScanner
MailScanner không có sẵn trong Centos hay Repoforge repositories.
# wget http://www.mailscanner.info/files/4/rpm/MailScanner-4.84.6-1.rpm.tar.gz
# tar zxvf MailScanner-4.84.6-1.rpm.tar.gz
# cd MailScanner-4.84.6-1# ./install.sh 
Cài đặt thư mục cần thiết cho SpamAssassin thay đổi permissions
# mkdir /var/spool/MailScanner/spamassassin
# chown postfix /var/spool/MailScanner/spamassassin
# chown postfix /var/spool/MailScanner/incoming/* 
Cấu hình file MailScanner backup
# vi /etc/MailScanner/MailScanner.conf 
%org-name% = test CentOS Mail Server
%org-long-name% = ORGFULLNAME
%web-site% = ORG WEBSITE
Run As User = postfix
Run As Group = postfix
MTA = postfix
Incoming Queue Dir = /var/spool/postfix/hold
Outgoing Queue Dir = /var/spool/postfix/incoming
Virus Scanners = clamav
## please check /etc/MailScanner/spam.lists.conf for more details ##
Spam List = SBL+XBL
## the directory created earlier ##
SpamAssassin User State Dir = /var/spool/MailScanner/spamassassin
Tại thời điểm này,MailScanner đã có sẵn

Debug MailScanner
# MailScanner -lint 
# service MailScanner start
# chkconfig MailScanner on

Kiểm tra hoạt động MailScanner
# tailf /var/log/maillog
Read more

Centos 6.5 Hướng dẫn cài đặt Nginx 1.5.10


Cài đặt các gói phụ thuộc 
#yum install gcc gcc-c++ make zlib-devel pcre-devel openssl-devel

Download  và cài đặt
#wget http://nginx.org/download/nginx-1.5.10.tar.gz
#./configure
#make
#make install

Setup  chạy cùng với hệ thống
#wget -O /etc/init.d/nginx https://gist.github.com/sairam/5892520/raw/b8195a71e944d46271c8a49f2717f70bcd04bf1a/etc-init.d-nginx
#chmod +x /etc/init.d/nginx
#chkconfig --add nginx
#chkconfig --level 345 nginx on
#service nginx start
Read more

Centos 6.4 How to install LAMP (Linux, Apache, MySQL, PHP)


Step 1: Installing Remi Repository
## RHEL/CentOS 6.4-6.0 - 32 Bit ##
#rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
#rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
## RHEL/CentOS 6.4-6.0 - 64 Bit ##
#rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
#rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm 

Step 2: Installing Apache 2.2.15, MySQL 5.5.34 & PHP 5.5.4
# yum --enablerepo=remi,remi-test install httpd mysql mysql-server php php-common

Step 3: Installing PHP 5.5.4 Modules
# yum --enablerepo=remi,remi-test install php-mysql php-pgsql php-pecl-mongo php-sqlite php-pecl-memcache php-pecl-memcached php-gd php-mbstring php-mcrypt php-xml php-pecl-apc php-cli php-pear php-pdo

Step 4: Starting/Stopping Apache & MySQL
## Enable Apache and MySQL on Run-Levels ##
# chkconfig --levels 235 httpd on
# chkconfig --levels 235 mysqld on
## Apache Commands ##
# service httpd start
# service httpd  stop
# service httpd  status           
## MySQL Commands ##
# service mysqld start
# service mysqld stop
# service mysqld status

Step 5:
Create page phpinfo.php under folder /var/www/html/
<?php
    phpinfo();
?>
-Finish: http://localhost/phpinfo.php



Read more

Centos 6.5 hướng dẫn cài đặt và cấu hình cơ bản Haproxy 1.5

Cài đặt gói phụ thuộc [root@localhost ~]#yum install gcc openssl-devel grouplist -v "development"
Cài đặt Haproxy 1.5-dev.22 trong Centos 6.5 [root@localhost ~]# wget http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev22.tar.gz
[root@localhost ~]# tar -zxvf haproxy-1.5-dev22.tar.gz
[root@localhost ~]# cd haproxy-1.5-dev22
[root@localhost haproxy-1.5-dev22]# make TARGET=linux2628 USE_OPENSSL=1
[root@localhost haproxy-1.5-dev22]# make PREFIX=/usr/local/haproxy install

Reload file cấu hình Haproxy 
[root@localhost haproxy-1.5-dev22]# ./haproxy -f /etc/haproxy/haproxy.cfg -D
Cấu hình cơ bản
global
  log 127.0.0.1 local2
  chroot /var/lib/haproxy
  pidfile /var/run/haproxy.pid
  maxconn 4000
  user haproxy
  group haproxy
  daemon
  stats socket /var/lib/haproxy/stats defaults
  mode http
  log global
  option httplog
  option dontlognull
  option http-server-close
  option forwardfor except 127.0.0.0/8
  option redispatch
  retries 3
  timeout http-request 10s
  timeout queue 1m
  timeout connect 10s
  timeout client 1m
  timeout server 1m
  timeout http-keep-alive 10s
  timeout check 10s
  maxconn 3000
listen stats
  bind *:8080
  stats auth admin:admin
  mode http
  stats enable
  stats hide-version
  stats realm Haproxy\ Statistics
  stats uri /
listen www *:80
  mode http
  balance roundrobin
  cookie SERVERID insert indirect
  option httpchk HEAD /healthcheck HTTP/1.0
  server app1 192.168.1.4:8080 cookie A check
  server app2 192.168.1.5:8080 cookie B check

Kết quả: http://yourIP:80 Haproxy stats Statistics Report http://youIP:8080 Hình dưới chưa có server app nên backend Down :)) . Mang tính chất minh họa :D haproxy stats
haproxy stats
Read more

Sunday, March 30, 2014

Centos 6.5 tạo User và Group basic đến Advance

Bài viết sau đây, hệ điều hành Centos 6.5 tạo user và Group basic đến Advance. Để tạo user trong hệ thống linux và unix, ta sử dụng dòng lệnh “useradd” hoặc “adduser”. Khi ta chạy dòng lệnh “useradd”, nó thực hiện như sau:

  • Edit các file /etc/passwd, /etc/groups, /etc/shadow, và /etc/gshadow cho user mới tạo.
  • Tạo home directory cho user mới.
  • Set quyền truy cập và quyền sở hữu cho user mới tạo
Links:
Dòng lệnh hữu ích trong linux
Umask và thiết lập umask trong linux
Linux sử dụng Openssl tạo CA
Centos 6.5 tạo User và Group Basic đến Advance
Centos 6.5 tạo User và Group basic đến Advance Hình ảnh trên minh họa Centos 6.5 tạo User và Group basic đến Advance :))

Cấu trúc dòng lệnh

useradd [option] username

1.Create mới user

[root@localhost ~]# useradd huu
[root@localhost ~]# passwd huu
Changing password for user huu.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

Khi tạo mới user nó tự động add vào file /etc/passwd. file này lưu trữ thông tin về user.
[root@localhost ~]# cat /etc/passwd | grep huu
huu:x:500:500::/home/huu:/bin/bash

Thông tin user huu phía trên gồm 7 trường và ngăn cách nhau dấu hai chấm ':'
  • username: user huu để login vào hệ thống và giới hạn 1-32 ký tự.
  • Password: x được lưu trong file /etc/shadow và format được mã hóa.
  • userID (UID): mỗi user có user ID (UID) được định danh bằng số. UserID 0 cho user root, 1-99 cho user định sẵn khác.100-999 cho user và goup hệ thống.
  • GroupID (GID): được lưu trong file /etc/group
  • user info: /home/huu thông tin liên quan đến user. sử dụng dòng lệnh 'finger' để biết thông tin liên quan user.
  • Shell: /bin/bash user sử dụng shell bash

2.Tạo user với thư mục khác

Mặc định, dòng lệnh “useradd” tự động tạo user trong thư mục /home. với option '-d' để thay đổi thư mục chứa user.
[root@localhost ~]# useradd -d /data dao
[root@localhost ~]# passwd dao
[root@localhost ~]# cat /etc/passwd | grep dao
dao:x:501:501::/data:/bin/bash

3.Tạo user với user ID

Mặc định, tạo mới user đó tự động gắn user ID là 500, 501 .v.v.v. Ta sử dụng option '-u' để tùy chỉnh user ID.
[root@localhost ~]# useradd -u 555 huu2
huu2:x:555:555::/home/huu2:/bin/bash

4.Tạo user với Group ID

Ta sử dụng option '-g'.
[root@localhost ~]# useradd -u 666 -g 501 huu3
huu3:x:666:501::/home/huu3:/bin/bash

5.add user với nhiều groups

[root@localhost ~]# useradd -G dao,huu huu6
[root@localhost ~]# id huu6
uid=668(huu6) gid=668(huu6) groups=668(huu6),500(huu),501(dao)

6.Tạo user không có thư mục home

ví dụ: ta tạo user để xem log hệ thống và không cần tạo thư mục home. với option '-M'.
[root@localhost ~]# useradd -M huu7
[root@localhost ~]# ls /home/huu7
ls: cannot access /home/huu7: No such file or directory

7.Create user với account expiry date

Mặc đinh, Tạo user trong hệ thống linux thì user sẽ không bao giờ expire date. Ta sử dụng option '-e' với format yyyy-MM-DD
[root@localhost ~]# useradd -e 2014-06-12 huu8
[root@localhost ~]# chage -l huu8
Last password change : Mar 31, 2014
Password expires : never
Password inactive : never
Account expires : Jun 12, 2014
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7

8.Tạo user với passwd expiry date.

Ta sử dụng option '-f'. Mặc định, được set '-1' có nghĩa là never expiry. dòng lệnh dưới đây tạo password hết hạn 23 ngày.
[root@localhost ~]# useradd -e 2014-06-12 -f 23 huu9

9.Add user với custom comment

Ta sử dụng option '-c'.
[root@localhost ~]# useradd -c "phan van Huu" pvhuu
pvhuu:x:673:673:phan van Huu:/home/pvhuu:/bin/bash

10.Thay đổi user sử dụng shell.

Ta sử dụng option '-s'. với các user sử dụng với các shell khác nhau. dòng lệnh sau tạo user không cho phép login vào shell.
[root@localhost ~]# useradd -s /sbin/nologin huu11

11.add user với thư mục home cụ thể, default shell và custom comment

[root@localhost ~]# useradd -m -d /var/www/huu13 -s /bin/bash -c "Huu Phan Van" -U huu13

12.add user không có thư mục home, không shell, không group và custom comment

[root@localhost ~]# useradd -M -N -r -s /bin/false -c "user disable" huu14
huu14:x:498:100:user disable:/home/huu14:/bin/false

Kết Luận: Centos 6.5 tạo user và Group basic đến Advance update thêm sau... :)))

Read more

Centos 6.5 cấu hình cơ bản

Bài viết sau đây hướng dẫn Centos 6.5 cấu hình cơ bản. Cấu hình IP tĩnh,Firewall cơ bản v.v.v

Links:
Dòng lệnh hữu ích trong linux
Umask và thiết lập umask trong linux
Centos 6.5 tạo User và Group Basic đến Advance
Centos 6.5 cấu hình cơ bản
Hình Ảnh trên một số Centos 6.5 cấu hình cơ bản. :))) p>

1.Create User

Create user admin
[root@mail ~]# useradd huu
[root@mail ~]# passwd huu
Changing password for user huu.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

Chỉ cho phép user huu switch qua root như administrator user su mặc định là super user. dòng lệnh su sử dụng switch user khác trong login session. Giới hạn user sử dụng dòng lệnh su.

[root@mail ~]# usermod -G wheel huu
[root@mail ~]# vi /etc/pam.d/su
# uncomment the following line
auth required pam_wheel.so use_uid
auth include system-auth
account sufficient pam_succeed_if.so uid = 0 use_uid quiet
account include system-auth
password include system-auth
session include system-auth
session optional pam_xauth.so

Forward mail root đến user administrator
[root@mail ~]# vi /etc/aliases
# Person who should get root's mail
root: huu
[root@mail ~]# newaliases # Configuration change

2.Enable / Disable Firewall && SElinux

Firewall iptables
[root@mail ~]#service iptables status : kiểm tra trạng thái của firewall
[root@mail ~]#service iptables start : enable firewall
[root@mail ~]#service iptables restart : restart firewall
[root@mail ~]#service iptables stop : stop firewall

Selinux
[root@mail ~]# vi /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
# targeted - Targeted processes are protected,
# mls - Multi Level Security protection.
SELINUXTYPE=targeted

Reboot lại hệ thống :)) .

3.Networking

[root@mail ~]# vi /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
IPADDR=192.168.1.5
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
HWADDR=00:0C:29:9C:AE:41
TYPE=Ethernet
UUID=b04c6559-fc7f-439b-92b6-6dc0a144772a
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=static
#DNS server's IP address
DNS1=8.8.8.8
IPV6INIT=no
USERCTL=no
[root@mail ~]# service network start
[root@mail ~]# chkconfig network on

Disable IPv6 nếu không muốn sử dụng

[root@mail ~]# vi /etc/sysctl.conf
# add at tha last line
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
# reload
[root@mail ~]# sysctl -p

Kết luân: Bài viết trên, Centos 6.5 cấu hình cơ bản. Update thêm. :))

Read more

Sunday, March 16, 2014

UMASK và thiết lập UMASK trong Linux


UMASK là gì
Trong hệ thống default permissions cho một file/forder mới tạo ra trong linux. Hầu hết các bản linux 022 (0022) cho default permissions.

Tính UMASK trong linux
Minimum và maximum giá trị umask trong forder là 000 và 777
Minimum và maximum giá trị umask trong file là 000 và 666
Phía dưới là permissions và giá trị sử dụng umask
0 –Full permissions (Read, Write, Execute)
1 –Write and read
2 –Read and execute
3 –Read only
4 –Write and execute
5 –Write only
6 –Execute onlyadminadmin
7 –No permissions
Ví dụ ta thiết lập file permission khi file mới được tạo có quyền -rw-r--r--(644)

Bước 1: Logical Negate UMASK
Not(022) = 644
Bước 2: Logical AND số 666
666 AND 644 = 644 Một cách tính đơn giản ta lấy 666 - 644 = 022

Hiển thị umask trong hệ thống 
$ umask
0022
$ umask -S
u=rwx,g=rx,o=rx

Làm sao thiết lập default UMASK cho tất cả các user mới tạo
Ta set trong /etc/profile cho tất cả các user mới tạo. Mở file này như quyền root và write dòng lệnh
umask 027
Làm sao thiết lập và thay đổi UMASK cho user đã có
Ta edit file ~/.bashrc cho từng user. Nếu trong hệ thống nhiều file thì ta tạo write shell script

UMASK 0022 và 022 có khác nhau ko????
Giá trị UMASK cho hệ thống security là : 027 (0027)
Để biết nhiều thông tin nhiều  hơn
#man umask 
#info umask


Read more

Linux Boot System


Bài viết này, giúp bạn hiểu về boot sequence từ BIOS để hoàn thành Boot. "Các hệ thống mới hơn sử dụng Extensible Firmware interface (EFI) và GUID Partition Table (GPT) được phổ biến cho drives lớn hơn kích thước 2TB". sau đây hướng dẫn cụ thể về kiến trúc hệ thống x86 và x86_64 sử dụng BIOS để boot system.

Để biết làm thế nào PC start và boot. Code gọi là BIOS ( Basic Input Output service ) được lưu trữ trong non-volatitle memory chẳng hạn như ROM, EEPROM hoặc flash memory. Khi PC turned on hay reboot, code thực thi và thực hiện một power-on self test (POST) để check máy. xác định boot drive từ removable sẵn có hay fixed storage devices và load sector đầu tiên từ Master Boot Record (MBR) trên drive đó.

MBR bao gồm partition table, số lượng code thực thi trong MBR ít hơn 512 bytes. Code này để loaded bởi BIOS từ sector đầu tiên gọi là first stage boot loader hay stage 1 boot loader.

Chuẩn hard drive MBR sử dụng bởi MS DOS, PC DOS và hệ điều hành Windows kiểm tra partition table và tìm một primary partition trên boot drive đó là đánh dấu như active, load từ sector đầu tiên từ partition đó, và chuyển control để bắt đầu loaded code. Một số code mới được biết partition boot record, thực ra là stage 1 boot loader khác, Nhưng đủ thông minh để blocks thành partition. code mới này được gọi là stage 2 boot loader, như sử dụng bởi MS-DOS và PC-DOS, stage 2 loader trực tiếp load một phần của hệ đều hành.


Nếu bạn muốn chạy nhiều hệ đều hành, bạn có thể sử dụng chương trình ( chẳng hạn như DOS FDISK) để thay đổi active partition và reboot.
Các giải pháp sử dụng một số code đặc biệt để cho phép ta chọn hệ đều hành để boot.
Loadin
Một  chương trình DOS thực thi để gọi một hệ thống DOS đang chạy để boot một Linux partition.
OS/2 Boot manager
Một chương trình install trong một dedicated partition nhỏ. Cho phép ta chọn hệ đều hành qua menu.
Một smart boot loader
Là một chương trình mà reside trên phân vùng hệ đều hành và gọi partition boot record của một active partition hoặc bởi master boot record. ví dụ như:
  • BootMagic
  • LILO
  • GRUB
  • GRUB2
Chain loading
Khi một boot manager có thể load boot manager khác, ví dụ: bạn sử dụng LILO trong một partition để chain load GRUB trong một partition khác để access GRUB menu cho partition đó.
Linux boot loaders
ở đây ta  tập trung vào LILO và GRUB như là boot load với hầu hết Linux distributions. Khi installation cho distribution bạn cần chọn một boot loader để set up. GRUB và LILO làm việc hầu hết các modern disk dưới kích thước 2TB
Summarize boot process cho PC:
  1. khi pc turned on thì BIOS thực hiện self test.
  2. khi một máy đã pass qua self test thì BIOS load master boot record (MBR thường 512-byte sector đầu tiên của boot drive, boot drive thường được sử dụng hard drive đầu tiên của hệ thống.
  3. hard drive, MBR load một stage 1 boot loader, thường LILO hoặc GRUB stage 1 boot loader trên hệ thống linux.
  4. stage 1 boot loader thường load tuần tự các record gọi là stage 2 boot loader.
  5. stage 2 loader load hệ đều hành. Đối với linux, đây là kernel và initial RAM disk (initrd)
LILO: mặc định file cấu hình /etc/lilo.conf.
GRUB: mặc định file cấu hình /boot/grub/grub.conf hay /boot/grub/menu.lst.
Boot event
Trong khi Linux boot, số lượng message rất lớn, mô tả kernel, phần cứng hệ thống. Nếu distribution support hide mode, thì bạn có thể hiển thị boot message bằng cách nhấn phím F2 trong khi boot.

dmesg 
Lệnh này giúp ta review lại kernel message.
#dmesg | head -n 30
#dmesg | tail -n 19

/var/log/messages
các processes sử dụng syslog daemon đến log messages, thường trong file /var/log/messages. Hầu hết các daemon có tên cuối cùng 'd'.

Read more

Tuesday, March 11, 2014

Centos cài đặt Java SDK sử dụng dòng lệnh yum


Làm thế nào cài đặt JDK trong Centos Linux version 6.x sử dụng dòng lệnh yum?
Centos Linux tên các gói JDK 
  1.     java-1.7.0-openjdk - OpenJDK Runtime Environment
  2.     java-1.7.0-openjdk-devel - OpenJDK Development Environment
List tất cả các gói JDK sẵn có trong hệ thống bằng dòng sau:
# yum search java | grep -i --color JDK
Cài đặt Java SDK trong Centos Linux
# yum install java-1.7.0-openjdk java-1.7.0-openjdk-devel
Set biến môi trường JAVA_HOME trong Centos Linux
RHEL và Centos linux cài đặt OpenJDK trong thư mục /usr/lib/jvm/
# ls -l /usr/lib/jvm/
Set JAVA_HOME đến thư mục chứa bin/java thực thi bằng dòng lệnh export
# export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
Mở file cấu hình shell chẳng hạn $HOME/.bashrc đi đến cuối dòng gõ dòng lệnh sau:
#export JAVA_HOME="/usr/lib/jvm/jre-1.7.0-openjdk.x86_64"
Test cài đặt Java
Tạo một chương trình  helloworld.java
$ cat > HelloWorld.java code:
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!!");
    }
}
Lưu và đóng file. compile và run 
$ javac HelloWorld.java
$ java HelloWorld
Kết quả: Hello, World!!


Read more

Monday, March 10, 2014

Nginx xử lý Request như thế nào

Dựa vào tên virtual servers
Cấu hình cơ bản 2 virutal server listen port *:80
server {
   listen 80;
   server_name example.net www.example.net;
   ...
}

server {
   listen 80;
   server_name example.com www.example.com;
   ...
}

Nginx xử lý một request dựa vào trường header "Host" xác định server để chuyển đến. Nếu không đúng bất kỳ một server name hay request không chứa trường header của server name, thì Nginx route request đến default server. Cấu hình ở trên, default server là server đầu tiên. Ta có thể set tham số default_server như sau:
server {
  listen 80 default_server;
  server_name example.net www.example.net;
  ...
}

Note: default server là thuộc tính của listen port và không phải server name

Làm thế nào ngăn chặn xử lý request không định nghĩa server name
Nếu các request không có trường header "Host" thì không cho phép, server sẽ drop các request.
server {
  listen 80;
  server_name "";
  return 444;
}

server_name ""; sẽ đúng tất cả các request mà không có trường header "Host" và trả code 444 và close kết nối.  

Kết hợp name-based và IP-based virtual servers Cấu hình hơi phức tạp
server {
  listen 192.168.1.1:80 ;
  server_name example.net www.example.net;
  ...
}

server {
listen 192.168.1.1:80;
server_name example.com www.example.com;
...
}

Đầu tiên, nginx xử lý địa chỉ IP và port trong server block. Sau đó kiểm tra trường header "Host" đúng với server_name nào.
Read more

Sunday, March 9, 2014

Hướng dẫn cơ bản về Nginx

Bài viết sau đây hướng dẫn cơ bản về nginx và các task đơn giản nó thực hiện. Làm thế nào start và stop nginx, và reload file cấu hình. Mô tả cấu trúc file cấu hình.

Nginx là một master process và có nhiều worker processes. Mục đích chính của master process là đọc và đánh giá cấu hình, và duy trì worker processes. worker processes xử lý các request. số worker processes được định nghĩa trong file cấu hình.
syntax: worker_processes number | auto;
default: worker_processes 1;
context:main 

Tối ưu value phụ thuộc nhiều yếu tố bao gồm: số lượng CPU core có sẵn, số lượng ổ cứng lưu trữ data, và mô hình load. auto ( giá trị này autodetect) .Tham số auto support từ version 1.3.8 và 1.2.5
Mặc định, file cấu hình nginx.conf được đặt trong thư mục /usr/local/nginx/conf, /etc/nginx, hay /usr/local/etc/nginx.
Starting, Stopping, and Reloading Configuration
syntax: nginx -s signal
ở đây signal:
  •     stop — fast shutdown
  •     quit — graceful shutdown
  •     reload — reloading the configuration file
  •     reopen — reopening the log files
Cấu trúc file cấu hình

http {
  server {
   location {
   }
  }
}
Note: Trong http{} có  một hay nhiều server và trong server {} có một hay nhiều location {}

Thiết lập proxy server đơn giản
Thiết lập nginx như một proxy server. có nghĩa là  nhận các request và passes chúng đến các proxied server, nhận các respones và gửi đến các clients. Định nghĩa proxied server  đơn giản listen port 8081 và map tất cả các request đến thư mục /data trong local file system.
server {
  listen 8081;
  root /data;
  location / {
  }
}

Sử dụng định nghĩa proxied server ta modify nó một proxy server. Đặt proxy_pass trong location{}
 server {
  location / {
  proxy_pass http://localhost:8081;
  }
  location /images/ {
  root /data;
  }
}

Read more

Monday, February 24, 2014

Ubuntu Thiết lập địa chỉ IP tĩnh


Mở terminal gõ dòng lệnh:
#vi /etc/network/interfaces
Thay đổi dòng iface eth0 inet dhcp thành iface eth0 inet static và add các dòng dưới đây
  • address 192.168.1.12 ( IP address mà bạn muốn cài đặt cho Ubuntu machine )
  • netmask 255.255.255.0 ( default mask trong trường hợp này là default class c subnet )
  • gateway 192.168.1.1 ( Thường thì IP address của Router )
  • network 192.168.1.0 ( Mạng của machine đang chạy )
  • broadcast 192.168.1.255 ( Message gửi đến tất cả các host cùng thuộc 1 mạng )
  • dns-nameservers 192.168.1.1 ( DNS hay Domain Name Server sử dụng để responing đến queries khi mà bạn searching một website )
-Restart networking :
  • /etc/init.d/networking restart
Read more