Thứ Năm, 6 tháng 9, 2012

IPTables Linux firewall with packet string-matching support

by Anton Chuvakin

Linux firewalling code has come a long way since the time ipfwadm was introduced in kernel version 1.2.1 in 1995. Ipfwadm enabled standard TCP/IP packet filtering features such as filtering by source/target addresses and port numbers. Then, in early 1999, when the first stable 2.2.0 kernel was released, firewalling code was replaced with new ipchains-controlled code. New features included support for chains of rules, fragmentation handling, better network address translation (NAT) support and several usability improvements. Readers should be reminded that Linux firewalling includes kernel-level code (usually in form of loadable module or kernel source patch) and user-level code (a control utility such as /usr/bin/ipchains, that is used to insert packet rules into kernel-space). Thus whenever new Linux firewalling code was introduced it involved both kernel and userspace code rewrite.
With the release of 2.4 in 2001, iptables code came out. It introduced many important improvements such as stateful firewalling, filtering packets based on any combination of TCP flags and on MAC address, more configurable and flexible logging, powerful and easy to use support for network address translation (NAT) and transparent proxies, DoS blocking support by rate-limiting and others. (For details see, for example A Comparison of iptables Automation Tools.)
However, the most important architectural addition was the introduction of the modular architecture. For example, ipchains and ipfwadm compatibility mode is implemented as a set of kernel modules that can be inserted into the running kernel to provide the corresponding functionality. In addition, user-coded modules are now possible. For example, filtering by port range, TTL value and time of packet arrival, stateful inspection for custom protocols, and random packet inspection are not part of the iptables suite, but were implemented later. Many new and interesting modules were coded. To program a module one has to create a kernel-level part that will be compiled into a loadable module and user-level part that will be used to control the filtering behavior. For more details see Rusty Russell's Linux iptables HOWTO.
This article will cover string pattern matching functionality (evidently, implemented as a module), which allows limited investigation of the packet payload. This is a significant breakthrough for iptables technology since it goes beyond inspecting TCP/IP flags, which is standard for packet filter firewalls. It is well-known that firewalls can be loosely categorized into proxies and packet filters. The latter "know" the application-level protocols such as telnet, HTTP or SMTP and can inspect the protocol payloads and verify the commands. This comes at a significant performance penalty since packets have to be processed higher in the network protocol stack in application layer. For each inspected protocol a new proxy should be written. The packet filters, on the other hand, can usually only inspect source and target addresses and ports, TCP/IP flags and have to totally ignore higher-layer protocol payloads. Due to that reason, they are usually much faster than proxy firewalls (3-10 times). Thus proxies are used for more granular security while packet filters are used on higher bandwidth lines for higher throughput.
In light of the above, adding content inspection capabilities in iptables presents an attempt to cross the bridge between two firewall groups without getting stuck in disadvantages of either method. It also clearly demonstrated an advantage of a new modular architecture over old ipchains code. It should be noted that packet filter such as iptables does not become higher-layer-protocol-aware since it still operates at network level (layer 3 in OSI structure), but is only allowed to peek at payloads, rather than analyze the application-level communication structure.
Before the string matching module was started in May 2001, there were attempts to add content inspection to iptables-based firewalls. One such project is Hogwash, which couples the Snort IDS rule-matching engine with iptables in order to respond to packets with attack signatures in them.
Now we will provide a step-by-step direction for enabling string matching packet inspection for RedHat Linux. Standard RH 7.2 comes with iptables 1.2.3 and 1.2.4 is available as an RPM update. However, string-matching functionality is not included in either since it is marked as "experimental" by developers. Thus some kernel recompilation is required.
If you are using RH 7.1-7.2 you already have kernel version 2.4 installed. You need at least 2.4.4 for the latest iptables 1.2.4 to function. It is always recommended to download the latest kernel version available from you system distributor. At present, there is one exception from this rule: iptables-1.2.4 string matching patch does not seem to work with 2.4.9 kernel version. You should have kernel source RPM package installed (that usually puts the full source tree in /usr/src/linux-2.4.x) or just have the kernel source downloaded from elsewhere (such as www.kernel.org or one of its mirrors).
For this article, the latest 2.4.16 will be used as an example. Test were also run with 2.4.7 kernel shipped with RedHat 7.2, but the 2.4.7 kernel is not recommended due to several minor bugs in security mechanisms such as SYN-cookie protection and iptables save/restore functionality.
Surely it is redundant to remind the reader to backup the entire kernel source tree before starting the experiment or keep a source RPM handy. Keep in mind, that the latter will only help if you have not compiled the kernel before.
Now, iptables code should be downloaded from http://netfilter.samba.org/iptables-1.2.4.tar.bz2 . After archive is unpacked, the iptables should be configured and the appropriate source code merged with the kernel source tree. The semi-automated program is available for that purpose. First, one might want to run the program to include the iptables patches that are already considered stable, but have not been included in the kernel release. From the directory where iptables are unpacked (in this example iptables are in /home/anton/iptables-1.2.4 and kernel source is in /usr/src/linux-2.4.16) run:
 make pending-patches KERNEL_DIR=/usr/src/linux-2.4.16 
That will start the process of interactive patch application. It appears, that, while you can safely apply all of those patches, none are required for iptables string support. Say y (yes) to whichever patches you think will be needed for your installation. If you want to play it safe choose none.
Now we are ready to apply experimental patches such as string matching support. Run:
 make patch-o-matic KERNEL_DIR=/usr/src/linux-2.4.16 
In the interactive session that follows answer y (yes) to application of string.patch. The program will go though all available patches, including the stable ones.
 Testing... string.patch NOT APPLIED ( 2 missing files) The string patch: Author: Emmanuel Roger  Status: Working, not with kernel 2.4.9 This patch adds CONFIG_IP_NF_MATCH_STRING which allows you to match a string in a whole packet. THIS PATCH DOES NOT WORK WITH KERNEL 2.4.9 ! Do you want to apply this patch [N/y/t/f/q/?] y 
While the rest of the patches may sound like fun as well, they are not relevant to this article. If you choose to install any other patches, heed the warnings given by developers about what patches break functionality (such as dropped tables patch). Make sure you do not install the MAC filtering patch since it was recently found to contain a bug.
Now we are ready to compile the user-space code and the libraries:
 make KERNEL_DIR=/usr/src/linux-2.4.16 
and then install them (iptables program goes in /usr/local/user/sbin and libraries go into /usr/local/lib/iptables). As root:
 make install KERNEL_DIR=/usr/src/linux-2.4.16 
Now we are ready to configure and compile the kernel:
 cd /usr/src/linux-2.4.16 
Any of the kernel configuration methods can be used. Detailed discussion of this is provided in a huge number of Internet sources such as kernel HOWTO. In brief:
 make xconfig 
In the GUI that appears got to Netfilter configuration and choose m (for modular support) in String match support (EXPERIMENTAL). See picture

Then follow with a standard
 make dep ; make bzImage ; make modules ; make modules_install 
Now install the kernel itself using you favorite method and reboot. Upon reboot, test whether the iptables with string support is enabled. As root:
 /usr/local/sbin/iptables -m string -help 
It should produce the iptables standard help message appended by:
 STRING match v1.2.4 options: --string [!] string Match a string in a packet 
The resulting functionality will allow you to match packets by the content. Some real life tests can be performed using netcat or telnet to make sure we can really grab packets by the content.
Run:
 iptables -A INPUT -m string --string "test" -j LOG --log-level
 info --log-prefix "TEST" 
Then start a netcat server by:
 nc -l -p 3456 
Connect to it via:
 telnet localhost 3456 
Now type:
 test whatevertestdoes 
It should produce the message similar to the following in your log files (providing you log messages with severity level ‘info’ somewhere)
 Nov 27 23:16:53 pua kernel:
 TEST IN=lo OUT=MAC=00:00:00:00:00:00:00:00:00:00:00:00:08:00  
SRC=127.0.0.1 DST=127.0.0.1 LEN=2154 TOS=0x00 PREC=0x00 TTL=64 
ID=42880 DF PROTO=TCP SPT=3128 DPT=33018 WINDOW=32767 RES=0x00 ACK PSH URGP=0 Nov 27 23:16:53 pua kernel:
 TEST IN=lo OUT=MAC=00:00:00:00:00:00:00:00:00:00:00:00:08:00  
SRC=127.0.0.1 DST=127.0.0.1LEN=1830 TOS=0x00 PREC=0x00 TTL=64 
ID=17451 DF PROTO=TCP SPT=8000 DPT=33017 WINDOW=32767 RES=0x00 ACK PSH URGP=0 
Every time the string test is present in TCP/IP packets, the above log message is produced. What is it good for? Many things. As was suggested in the excellent article, Filtering packets based on string matching, by sysctl at Linuxguru.net, it can be used to block all those pesky IIS worms from filling your UNIX web server log files with requests to cmd.exe etc. Those worms cannot hurt you, but if your /var partition (where logs are usually stored) is not too big this measure can be pretty helpful. Just silently drop all those port 80 requests or log them using the message limiting facility:
To silently drop them:
 iptables -I INPUT -j DROP -p tcp -s 0.0.0.0/0 -m string --string "cmd.exe" 
To only log no more then 1 message per hour:
 iptables -I INPUT -j LOG -p tcp -s 0.0.0.0/0 -m string --string "cmd.exe" -m limit
 --limit 1/hour 
Replace the string with whatever the new Windows "worm-of-the-moment" is requesting and just add another rule.
You can also stop requests to things you do not want to have retrieved from your Web server. Apparently, test.cgi should be removed, rather than put into iptables rules. However, in some cases the ability to stop requests for specific documents at the TCP/IP level before they reach the Web server access control facility might provide the needed "defense in-depth" for your Web infrastructure.
Another great suggestion from Bill Stearns (author of Mason firewall building script) is to convert your Snort network IDS rules into iptables rules with string support. Snort IDS attack signature database contains about 1200 signatures and appears to be the biggest publicly available attack database suitable for instant deployment. The ability to use the ready-made signatures for iptables is of immense value. The page that describes his experimental software is at http://www.stearns.org/snort2iptables/. There, you can find the shell script to convert a standard Snort ruleset into iptables rules. Here are a couple of examples for well-known Linux attacks against mountd and bind network daemons:
Snort rules:
 1. alert udp $EXTERNAL_NET any -> $HOME_NET 518
  (msg:"EXPLOIT ntalkd x86 linux overflow";
  content:"|0103 0000 000 0 0001 0002 02e8|";
 reference:bugtraq,210;  classtype:attempted-admin; sid:313; rev:2;)   2. alert tcp $EXTERNAL_NET any -> $HOME_NET 53
  (msg:"EXPLOIT named tsig infoleak";
 content: "|AB CD 09 80 00 00 00 01 00 00 00 00 00 00 01 00 01 20 20 20 20 02 61|";
 reference:cve,CAN-2000-0010; reference:bugtraq,2302; reference:arachnids,482;
  classtype:attempted-admin; sid:303; rev:3;) 3. alert udp $EXTERNAL_NET any -> $HOME_NET 635
 (msg:"EXPLOIT x86 linux mountd overflow";
 content:"|5eb0 0289 06fe c889 4604 b006 8946|";
reference:cve,CVE-1999-0002; classtype:attempted-admin; sid:315; rev:1;) 
Converted iptables rules:
 1. iptables -A SnortRules -p udp -s $EXTERNAL_NET -d $HOME_NET --dport 518 -m 
string --string "   è" -j LOG --log-prefix "SID313 " # "EXPLOIT ntalkd x86
 linux overflow" bugtraq,210 classtype: attempted-admin sid:313 
 2. iptables -A SnortRules -p tcp -s $EXTERNAL_NET -d $HOME_NET --dport 53 -m 
string --string "«Í .a" -j LOG --log-prefix " 
SID303 " # "EXPLOIT named tsig infoleak" cve,CAN-2000-0010 bugtraq,2302
 arachnids,482 classtype:attempted-admin sid:303 
 3. iptables -A SnortRules -p udp -s $EXTERNAL_NET -d $HOME_NET --dport 635 -m 
string --string "^° ‰ þȉF ° ‰F" -j LOG --log-prefix " cve-CVE-1999-0002
 " # "EXPLOIT x86 linux mountd overflow" classtype:attempted-admin sid:315 
It is easy to see that the above conversion uses the buffer overflow string used for the above exploits to catch the attack. Some rules are not converted mostly due to the fact that Snort is still "smarter" than iptables in fragmentation handling.
Overall, iptables with string support can be used to protect networks (if deployed on the organization gateway) and individual hosts (deployed as a part of host hardening) from many attacks on the network services that have to be open to the world (WWW, mail, DNS, ftp) and have not been protected by ordinary packet filters. In addition, iptables string matching can also help with policy enforcement - just implement the rules that stop inappropriate content by keyword. There might be better solutions of implementing the content scanning, but another layer of protection never hurts.
Anton Chuvakin, Ph.D. is in the process of looking for another infosec job after having his fun dot-bomb experience. He spends his plentiful pastime running Linux, building a small infosec portal and preparing for CISSP.
This article originally appeared on SecurityFocus.com -- reproduction in whole or in part is not allowed without expressed written consent.

Linux Iptables Limit the number of incoming tcp connection / syn-flood attacks

by on June 26, 2005 · 16 comments· Last updated October 14, 2007

A SYN flood is a form of denial-of-service attack in which an attacker sends a succession of SYN requests to a target's system. This is a well known type of attack and is generally not effective against modern networks. It works if a server allocates resources after receiving a SYN, but before it has received the ACK.
if Half-open connections bind resources on the server, it may be possible to take up all these resources by flooding the server with SYN messages. Syn flood is common attack and it can be block with following iptables rules:
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j RETURN
All incoming connection are allowed till limit is reached:
  • --limit 1/s: Maximum average matching rate in seconds
  • --limit-burst 3: Maximum initial number of packets to match
Open our iptables script, add the rules as follows:
# Limit the number of incoming tcp connections
# Interface 0 incoming syn-flood protection
iptables -N syn_flood
iptables -A INPUT -p tcp --syn -j syn_flood
iptables -A syn_flood -m limit --limit 1/s --limit-burst 3 -j RETURN
iptables -A syn_flood -j DROP
#Limiting the incoming icmp ping request:
iptables -A INPUT -p icmp -m limit --limit  1/s --limit-burst 1 -j ACCEPT
iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 1 -j LOG --log-prefix PING-DROP:
iptables -A INPUT -p icmp -j DROP
iptables -A OUTPUT -p icmp -j ACCEPT
First rule will accept ping connections to 1 per second, with an initial burst of 1. If this level crossed it will log the packet with PING-DROP in /var/log/message file. Third rule will drop packet if it tries to cross this limit. Fourth and final rule will allow you to use the continue established ping request of existing connection.
Where,
  • ‐‐limit rate: Maximum average matching rate: specified as a number, with an optional ‘/second’, ‘/minute’, ‘/hour’, or ‘/day’ suffix; the default is 3/hour.
  • ‐‐limit‐burst number: Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5.
You need to adjust the –limit-rate and –limit-burst according to your network traffic and requirements.
Let us assume that you need to limit incoming connection to ssh server (port 22) no more than 10 connections in a 10 minute:
iptables -I INPUT -p tcp -s 0/0 -d $SERVER_IP --sport 513:65535 --dport 22 -m state --state NEW,ESTABLISHED -m recent --set -j ACCEPT
iptables -I INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 600 --hitcount 11 -j DROP
iptables -A OUTPUT -p tcp -s $SERVER_IP -d 0/0 --sport 22 --dport 513:65535 -m state --state ESTABLISHED -j ACCEPT

Thứ Tư, 29 tháng 8, 2012

Simple DoS protection with mod_security

ModSecurity™ is an open source, free web application firewall (WAF) Apache module. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.
It can do many things for you, such as detecting for XSS, SQL injection or file inclusion attacks.
A special use of mod_security can be simple protection from DoS attacks. Suppose your apache or application logs reveal that some specific IP is requesting too many pages per second (e.g 30 pages/sec from a single IP when your normal peak is 5 globally). In the best case scenario this could result in a slight decrease of the performance of the site which could be noticeable by the other users. In the worst case scenario it could bring the whole site down (denial of service). This attack could of course be unintentional. A misconfigured crawler or a spam bot could be the source of the problem, but in any case you’d like to block such requests.
Here is a possible configuration for mod_security to prevent those simple DoS attacks with explanatory comments:

SecRuleEngine On

SecAuditEngine RelevantOnly
SecAuditLogType Serial
SecAuditLog logs/mod_security.log

# a folder where mod_security will store data variables
SecDataDir logs/mod_security-data

# ignore requests from localhost or some other IP
SecRule REMOTE_ADDR "^127\.0\.0\.1$" "phase:1,nolog,allow"

# for all non static urls count requests per second per ip
# (increase var requests by one, expires in 1 second)
SecRule REQUEST_BASENAME "!(\.avi$|\.bmp$|\.css$|\.doc$|\.flv$|\.gif$|\
                            \.htm$|\.html$|\.ico$|\.jpg$|\.js$|\.mp3$|\
                            \.mpeg$|\.pdf$|\.png$|\.pps$|\.ppt$|\.swf$|\
                            \.txt$|\.wmv$|\.xls$|\.xml$|\.zip$)"\
                            "phase:1,nolog,pass,initcol:ip=%{REMOTE_ADDR},setvar:ip.requests=+1,expirevar:ip.requests=1"

# if there where more than 5 requests per second for this IP
# set var block to 1 (expires in 5 seconds) and increase var blocks by one (expires in an hour)
SecRule ip:requests "@eq 5" "phase:1,pass,nolog,setvar:ip.block=1,expirevar:ip.block=5,setvar:ip.blocks=+1,expirevar:ip.blocks=3600"

# if user was blocked more than 5 times (var blocks>5), log and return http 403
SecRule ip:blocks "@ge 5" "phase:1,deny,log,logdata:'req/sec: %{ip.requests}, blocks: %{ip.blocks}',status:403"

# if user is blocked (var block=1), log and return http 403
SecRule ip:block "@eq 1" "phase:1,deny,log,logdata:'req/sec: %{ip.requests}, blocks: %{ip.blocks}',status:403"

# 403 is some static page or message
ErrorDocument 403 "<center><h2>take it easy yo!"
 
 
In case you experiment with this configuration on production make sure you keep an eye on mod_security.log to validate that you are really blocking out requests that you intend to.
Good luck!


from http://blog.cherouvim.com/

 

Thứ Ba, 21 tháng 8, 2012

Eight Ways to Blacklist with Apache’s mod_rewrite



Eight Ways to Blacklist with Apache’s mod_rewrite

With the imminent release of the next series of (4G) blacklist articles here at Perishable Press, now is the perfect time to examine eight of the most commonly employed blacklisting methods achieved with Apache’s incredible rewrite module, mod_rewrite. In addition to facilitating site security, the techniques presented in this article will improve your understanding of the different rewrite methods available with mod_rewrite.

Blacklist via Request Method

This first blacklisting method evaluates the client’s request method. Every time a client attempts to connect to your server, it sends a message indicating the type of connection it wishes to make. There are many different types of request methods recognized by Apache. The two most common methods are GET and POST requests, which are required for “getting” and “posting” data to and from the server. In most cases, these are the only request methods required to operate a dynamic website. Allowing more request methods than are necessary increases your site’s vulnerability. Thus, to restrict the types of request methods available to clients, we use this block of Apache directives:
<IfModule mod_rewrite.c>
 RewriteEngine On
 ServerSignature Off
 Options +FollowSymLinks
 RewriteCond %{REQUEST_METHOD} ^(delete|head|trace|track) [NC]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
The key to this rewrite method is the REQUEST_METHOD in the rewrite condition. First we invoke some precautionary security measures, and then we evaluate the request method against our list of prohibited types. Apache will then compare each client request method against the blacklisted expressions and subsequently deny access to any forbidden requests. Here we are blocking delete and head because they are unecessary, and also blocking trace and track because they violate the same-origin rules for clients. Of course, I encourage you to do your own research and establish your own request-method security policy.

Blacklist via the Request

The next blacklisting method is based on the client’s request. When a client attempts to connect to the server, it sends a full HTTP request string that specifies the request method, request URI, and transfer-protocol version. Note that additional headers sent by the browser are not included in the request string. Here is a typical example:
GET blog/index.html HTTP/1.1
This long request string may be checked against a list of prohibited characters to protect against malicious requests and other exploitative behavior. Here is an example of sanitizing client requests by way of Apache’s THE_REQUEST variable:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{THE_REQUEST} ^.*(\\r|\\n|%0A|%0D).* [NC]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
Here we are evaluating the entire client-request string against a list of prohibited entities. While there are many character strings common to malicious requests, this example focuses on the prevention of HTTP response splitting, cross-site scripting attacks, cache poisoning, and similar dual-header exploits. Although these are some of the most common types of attacks, there are many others. I encourage you to check your server logs, do some research, and sanitize accordingly.

Blacklist via the Referrer

Blacklisting via the HTTP referrer is an excellent way to block referrer spam, defend against penetration tests, and protect against other malicious activity. The HTTP referrer is identified as the source of an incoming link to a web page. For example, if a visitor arrives at your site through a link they found in the Google search results, the referrer would be the Google page from whence the visitor came. Sounds straightforward, and it is.
Unfortantely, one of the biggest spam problems on the Web involves the abuse of HTTP referrer data. In order to improve search-engine rank, spambots will repeatedly visit your site using their spam domain as the referrer. The referrer is generally faked, and the bots frequently visit via HEAD requests for the sake of efficiency. If the target site publicizes their access logs, the spam sites will receive a search-engine boost from links in the referrer statistics.
Fortunately, by taking advantage of mod_rewrite’s HTTP_REFERER variable, we can forge a powerful, customized referrer blacklist. Here’s our example:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{HTTP_REFERER} ^(.*)(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC,OR]
 RewriteCond %{HTTP_REFERER} ^http://(www\.)?.*(-|.)?adult(-|.).*$  [NC,OR]
 RewriteCond %{HTTP_REFERER} ^http://(www\.)?.*(-|.)?poker(-|.).*$  [NC,OR]
 RewriteCond %{HTTP_REFERER} ^http://(www\.)?.*(-|.)?drugs(-|.).*$  [NC]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
Same basic pattern as before: check for the availability of the rewrite module, enable the rewrite engine, and then specify the prohibited character strings using the HTTP_REFERER variable and as many rewrite conditions as necessary. In this case, we are blocking a series of potentially malicious characters in the first condition, and then blacklisting any referrer containing the terms “adult”, “poker”, or “drugs”. Of course, we may blacklist as many referrer strings as needed by simply emulating the exisiting rewrite conditions. Just don’t get carried away — I have seen some referrer blacklists that are over 4000 lines long!

Blacklist via Cookies

Protecting your site against malicious cookie exploits is greatly facilitated by using Apache’s HTTP_COOKIE variable. HTTP cookies are chunks of data sent by the server to the web client upon initialization. The browser then sends the cookie information back to the server for each subsequent visit. This enables the server to authenticate users, track sessions, and store preferences. A common example of the type of functionality enabled by cookies is the shopping cart. Information about the items placed in a user’s shopping cart may be stored in a cookie, thereby enabling server scripts to respond accordingly.
Generally, a cookie consists of a unique string of alphanumeric text and persists for the duration of a user’s session. Apache’s mod_cookie module generates cookie values randomly and upon request. Once a cookie has been set, it may be used as a database key for further processing, behavior logging, session tracking, and much more. Unfortunately, this useful technology may be abused by attackers to penetrate and infiltrate your server’s defenses. Cookie-based protocols are vulnerable to a variety of exploits, including cookie poisoning, cross-site scripting, and cross-site cooking. By adding malicious characters, scripts, and other content to cookies, attackers may find and exploit sensitive vulnerabilities.
The good news is that we may defend against most of this nonsense by using Apache’s HTTP_COOKIE variable to blacklist characters known to be associated with malicious cookie exploits. Here is an example that does the job:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{HTTP_COOKIE} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
This is as straightforward as it looks. Check for the required rewrite module, enable the rewrite engine, and deny requests for any HTTP_COOKIEs containing the specified list of prohibited characters. In this list you will see characters generally required to execute any sort of scripted attack: opening and closing angle brackets, single quotation marks, and a variety of hexadecimal equivalents. Feel free to expand this list with additional characters as you see fit. As always, recommendations are most welcome.

Blacklist via Request URI

Use of Apache’s REQUEST_URI variable is frequently seen in conjunction with URL canonicalization. The REQUEST_URI variable targets the requested resource specified in the full HTTP request string. Thus, we may use Apache’s THE_REQUEST variable to target the entire request string (as discussed above), while using the REQUEST_URI variable to target the actual request URI. For example, the REQUEST_URI variable refers to the “blog/index.html” portion of the following, full HTTP request line:
GET blog/index.html HTTP/1.1
For canonicalization purposes, this is exactly the type of information that must be focused on and manipulated in order to achieve precise, uniform URLs. Likewise, for blacklisting malicious request activity such as the kind of nonsense usually exposed in your server’s access and error logs, targeting, evaluating, and denying malicious URL requests is easily accomplished by taking advantage of Apache’s REQUEST_URI variable.
As you can imagine, blacklisting via REQUEST_URI is an excellent way to eliminate scores of malicious behavior. Here is an example that includes some of the same characters and strings that are blocked in the upcoming 4G Blacklist:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_URI} ^.*(,|;|:|<|>|">|"<|/|\\\.\.\\).* [NC,OR]
 RewriteCond %{REQUEST_URI} ^.*(\=|\@|\[|\]|\^|\`|\{|\}|\~).* [NC,OR]
 RewriteCond %{REQUEST_URI} ^.*(\'|%0A|%0D|%27|%3C|%3E|).* [NC]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
Again, same general pattern of directives as before, only this time we are specifying forbidden characters via the REQUEST_URI variable. Here we are denying any URL requests containing invalid characters, including different types of brackets, various punctuational characters, and some key hexadecimal equivalents. Of course, the possibilities are endless, and the blacklist should be customized according to your specific security strategy and unfolding blacklisting needs.

Blacklist via the User Agent

Blacklisting via user-agent is a commonly seen strategy that yields questionable results. The concept of blacklisting user-agents revolves around the idea that every browser, bot, and spider that visits your server identifies itself with a specific user-agent character string. Thus, user-agents associated with malicious, unfriendly, or otherwise unwanted behavior may be identified and blacklisted in order to prevent against future access. This is a well-known blacklisting strategy that has resulted in some extensive and effective user-agent blacklists.
Of course, the downside to this method involves the fact that user-agent information is easily forged, making it difficult to know for certain the true identity of blacklisted clients. By simply changing their user-agent to an unknown identity, malicious bots may bypass every blacklist on the Internet. Many evil “scumbots” indeed do this very thing, which explains the incredibly vast number of blacklisted user-agents. Even so, there are certain limits to the extent to which certain user-agent strings may be changed. For example, GNU’s Wget and the cURL command-line tool are difficult to forge, and many other clients have hard-coded user-agent strings that are difficult to change.
On Apache servers, user-agents are easily identified and blacklisted via the HTTP_USER_AGENT variable. Here is an example:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{HTTP_USER_AGENT} ^$                                                              [OR]
 RewriteCond %{HTTP_USER_AGENT} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).*                            [NC,OR]
 RewriteCond %{HTTP_USER_AGENT} ^.*(HTTrack|clshttp|archiver|loader|email|nikto|miner|python).* [NC,OR]
 RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|libwww\-perl|curl|wget|harvest|scan|grab|extract).* [NC]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
This method works just like the others: check for the mod_rewrite module, enable the rewrite engine, and proceed to deny access to any user-agent that includes any of the blacklisted character strings in its name. As with our previous blacklisting techniques, here we are prohibiting angle brackets, single quotation marks, and various hexadecimal equivalents. Additionally, we include a handful of user-agent strings commonly associated with server attacks and other malicious behavior. We certainly don’t need anything associated with libwww-perl hitting our server, and many of the others are included in just about every user-agent blacklist that you can find. There are tons of other nasty user-agent scumbots out there, so feel free to beef things up with a few of your own.

Blacklist via the Query String

Protecting your server against malicious query-string activity is extremely important. Whereas static URLs summon pages, their appended query strings transmit data and pass variables throughout the domain. Query-string information interacts with scripts and databases, influencing behavior and determining results. This relatively open channel of communication is easily accessible and prone to external manipulation. By altering data and inserting malicious code, attackers may penetrate and exploit your sever directly through the query string.
Fortunately, we can protect our server against malicious query-string exploits with the help of Apache’s invaluable QUERY_STRING variable. By taking advantage of this variable, we can ensure the legitimacy and quality of query-string input by screening out and denying access to a known collection of potentially harmful character strings. Here is an example that will keep our query strings squeaky clean:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{QUERY_STRING} ^.*(localhost|loopback|127\.0\.0\.1).*                                [NC,OR]
 RewriteCond %{QUERY_STRING} ^.*(\.|\*|;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|).*                 [NC,OR]
 RewriteCond %{QUERY_STRING} ^.*(md5|benchmark|union|select|insert|cast|set|declare|drop|update).* [NC]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
As you can see, here we are using the QUERY_STRING variable to check all query-string input against a list of prohibited alphanumeric characters strings. This strategy will deny access to any URL-request that includes a query-string containing localhost references, invalid punctuation, hexadecimal equivalents, and various SQL commands. Blacklisting these enitities protects us from common cross-site scripting (XSS), remote shell attacks, and SQL injection. And, while this a good start, it pales in comparison to the new query-string directives of the upcoming 4G Blacklist. ;)

Blacklist via IP Address

Last but certainly not least, we can blacklist according to IP address. Blacklisting sites based on IP is probably the oldest method in the book and works great for denying site access to stalkers, scrapers, spammers, trolls, and many other types of troublesome morons. The catch is that the method only works when the perpetrators are coming from the same location. An easy way to bypass any IP blacklist is to simply use a different ISP or visit via proxy server. Even so, there is no lack of mindless creeps out there roaming the Internet, who sit there, using the same machine, day after day, relentlessly harassing innocent websites. For these types of lazy, no-life losers, blacklisting via IP address is the perfect solution. Here is a hypothetical example demonstrating several ways to blacklist IPs:
# block individual IPs
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REMOTE_ADDR} ^123\.456\.789\.1 [OR]
 RewriteCond %{REMOTE_ADDR} ^456\.789\.123\.2 [OR]
 RewriteCond %{REMOTE_ADDR} ^789\.123\.456\.3 [OR]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
 
# block ranges of IPs
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REMOTE_ADDR} ^123\. [OR]
 RewriteCond %{REMOTE_ADDR} ^456\.789\. [OR]
 RewriteCond %{REMOTE_ADDR} ^789\.123\.456\. [OR]
 RewriteRule ^(.*)$ - [F,L]
</IfModule>
 
# alt block IP method
<Limit GET POST PUT>
 order allow,deny
 allow from all
 deny from 123.
 deny from 123.456.
 deny from 123.456.789.0
</Limit>
In the first block, we are blacklisting three specific IP addresses using Apache’s mod_rewrite and its associated REMOTE_ADDR variable. Each of the hypothetical IPs listed represent a specific, individual address. Then, in the next code block, we are blocking three different ranges of IPs by omitting numerical data from the targeted IP string. In the first line we target any IP beginning with “123.”, which is an enormous number of addresses. In the second line, we block a different, more restrictive range by including the second portion of the address. Finally, in the third line, we block a different, much smaller range of IPs by including a third portion of the address.
Then, just for kicks, I threw in an alternate method of blocking IPs. This is an equally effective method that enables you to block IP addresses and ranges as specifically as necessary. Each deny line pattern-matches according to the specified IP string.

Dealing with Blacklisted Visitors

In each of these eight blacklisting techniques, we respond to all blacklisted visitors with the server’s default “403 Forbidden” error. This page serves its purpose and requires very little to deliver in terms of system resources, however there is much more that you can do with blacklisted traffic. Here are a few ideas:
Redirect to home page
More subtle than the 403 error, this redirect strategy routes blocked traffic directly to the home page. To use, replace the RewriteRule directive (i.e., the entire line) with the following code:
RewriteRule ^(.*)$ http://your-domain.tld/ [F,L]
Redirect to external site
The possibilities here are endless. Just make sure you think twice about the destination, as any scum that you redirect to another site will be seen as coming from your own. Even so, here is the code that you would use to replace the RewriteRule directive in any of the examples above:
RewriteRule ^(.*)$ http://external-domain.tld/some-target/page.html [F,L]
Redirect them back to their own site
This is one of my favorites. It’s like having a magic shield that reflects attacks back at the attacker. Send a clear message by using this code as the RewriteRule directive in any of our blacklisting methods:
RewriteRule ^(.*)$ http://%{REMOTE_ADDR}/ [F,L]
Custom processing
For those of you with a little skill, it is possible to redirect your unwelcome guests to a fail-safe page that explains the situation to the client while logging all of the information behind the scenes. This is perhaps the most useful approach for understanding your traffic and developing an optimal security strategy. The code would look something like this, depending on your file name and its location:
RewriteRule ^(.*)$ /home/path/blacklisting-script.php [F,L]

Closure

This article presents eight effective techniques for protecting your server and preventing malicious behavior. While each of these methods may be used individually, they are designed to secure different aspects of your environment and thus provide a more complete type of firewall protection when combined into a synergized whole. Even when combining these techniques, however, keep in mind that blacklisting various protocols serves to complement a more robust and comprehensive security strategy. Once understood, these methods provide the average webmaster an easy, effective way of defending against unwanted behavior and enhancing the overall security of their sites.

Thứ Hai, 20 tháng 8, 2012

Block BitTorrent traffic on your Linux firewall using iptables - Block string by Iptables

Block BitTorrent traffic on your Linux firewall using iptables

Filed under: Debian,linux,Security — Tags: , , , , , — admin @ 7:25 pm
The following script will block and log un-encrypted BitTorrent & DHT traffic on your Linux firewall.
I have personally tested it on debian 5 lenny , but I am almost sure it should work pretty well on any new Linux distros.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
iptables -N LOGDROP > /dev/null 2> /dev/null
iptables -F LOGDROP
iptables -A LOGDROP -j LOG --log-prefix "LOGDROP "
iptables -A LOGDROP -j DROP
 
#Torrent
iptables -A FORWARD -m string --algo bm --string "BitTorrent" -j LOGDROP
iptables -A FORWARD -m string --algo bm --string "BitTorrent protocol" -j LOGDROP
iptables -A FORWARD -m string --algo bm --string "peer_id=" -j LOGDROP
iptables -A FORWARD -m string --algo bm --string ".torrent" -j LOGDROP
iptables -A FORWARD -m string --algo bm --string "announce.php?passkey=" -j LOGDROP
iptables -A FORWARD -m string --algo bm --string "torrent" -j LOGDROP
iptables -A FORWARD -m string --algo bm --string "announce" -j LOGDROP
iptables -A FORWARD -m string --algo bm --string "info_hash" -j LOGDROP
 
# DHT keyword
iptables -A FORWARD -m string --string "get_peers" --algo bm -j LOGDROP
iptables -A FORWARD -m string --string "announce_peer" --algo bm -j LOGDROP
iptables -A FORWARD -m string --string "find_node" --algo bm -j LOGDROP

Chủ Nhật, 8 tháng 4, 2012

Remove the “host currently has no management network redundancy”

Remove the “host currently has no management network redundancy” warning from your whitebox HA enabled ESX cluster

When you completed building your ESX cluster from so called whitebox machines, you might see a warning sign at the cluster level. It will tell you the management network has no redundancy. This is probably correct because whitebox clusters usually don’t have 2 NIC’s for the management network.

To loose this irritating warning message do the following.
  1. Go to the properties of your cluster
  2. Select HA from the left pane
  3. Click the ‘Advanced Options’ button
  4. Fill in the first column of the first row by double clicking and typing the value ‘das.ignoreRedundantNetWarning’
  5. Fill in the second column of the same row by double clicking and typing the value ‘True’
  6. Close the Advanced Options window
  7. Now deselect the option ‘Enable HA’ and press OK
  8. HA will be disabled, this will take some time
  9. Go back to the options and select ‘Enable HA’ and press OK
  10. HA will be enabled and the warning will be gone

 

Thứ Sáu, 6 tháng 4, 2012

Vmware HA

Vmware HA: The number of heartbeat datastores for host is 1, which is less than required: 2

 

das.ignoreinsufficienthbdatastore – Disables configuration issues created if the host does not
have sufficient heartbeat datastores for vSphere HA. Default
value is false.
To disable the message, you will need to add this new advanced setting under the “vSphere HA” Advanced Options second and set the value to be true.



Supported vSphere 5.0 Advanced Options

There are several advanced configuration options that one can use to modify the operation of vSphere HA 5.0.  The following lists the supported options that relate to vSphere HA 5.0.  As the use of these options can significantly impact the operation of vSphere HA and hence the availability protection provided, it is highly recommended that users fully understand the use and ramifications of using these options.
A KB Article will be released soon for reference.
 HA Advanced Options
The following advanced options can be configured on a per-cluster basis through the use of the HA Advanced Options section of the user interface.  In some cases, the use of an option requires you to reconfigure vSphere HA on all hosts before the option takes effect.
Name
Default
Valid values
Description
Reconfig?
das.isolationAddressX


Sets the address to ping to determine if a host is isolated from the network. This address is pinged only when heartbeats are not received from any other host in the cluster. If not specified, the default gateway of the management network is used. This default gateway has to be a reliable address that is available, so that the host can determine if it is isolated from the network. You can specify multiple isolation addresses (up to 10) for the cluster: das.isolationaddressX, where X = 1-10. Typically you should specify one per management network. Specifying too many addresses makes isolation detection take too long.
Y
das.allowNetworkX


This option is only recommended for ESXi 3.5 hosts. To control the network selection for ESXi 4.0 and more recent hosts, use the UI to specifiy the port groups that are to be used for management. Port group names of management networks to use for HA communication. X should be replaced by 0-9. If not used, all appropriate networks will be used.
Y
das.useDefaultIsolationAddress

true/
false
By default, vSphere HA uses the default gateway of the console network as an isolation address. This attribute specifies whether or not this default is used
Y
das.isolationShutdownTimeout
300

The period of time in seconds the system waits for a virtual machine to shut down before powering it off. This only applies if the host's isolation response is Shut down VM.
N
das.maxvmrestartcount
5

Defines the maximum number of times a HA master agent will try restart a VM after a failure before giving up and reporting it was unable to restart the VM.
N
das.maxftvmrestartcount
5

Defines the maximum number of times a HA master agent will try to start a secondary VM of an vSphere Fault Tolerance VM pair before giving up and reporting it could not.
N
das.ignoreRedundantNetWarning
false
true/
false
Suppress the host config issue about lack of redundant management networks on a host in a HA enabled cluster
N
das.vmMemoryMinMB
0

Defines the default memory resource value assigned to a virtual machine if its memory reservation is not specified or zero. This is used for the Host Failures Cluster Tolerates admission control policy
N
das.vmCpuMinMHz
256

Defines the default CPU resource value assigned to a virtual machine if its CPU reservation is not specified or zero. This is used for the Host Failures Cluster Tolerates admission control policy. If no value is specified, the default is 256MHz.
N
das.slotCpuInMHz


Defines the maximum bound on the CPU slot size. If this option is used, the slot size is the smaller of this value or the maximum CPU reservation of any powered-on virtual machine in the cluster.

das.slotMemInMB


Defines the maximum bound on the memory slot size. If this option is used, the slot size is the smaller of this value or the maximum memory reservation plus memory overhead of any powered-on virtual machine in the cluster.

das.includeFTcomplianceChecks
true
true/
false
Controls whether vSphere Fault Tolerance compliance checks should be run as part of the cluster compliance checks. Set this option to false to avoid cluster compliance failures when Fault Tolerance is not being used in a cluster.
N
das.maxFtVmsPerHost
4
0 means no limit
Defines the maximum number of vSphere Fault Tolerance primary of secondary VMs that can be placed on a host during normal operation.When a value greater than zero is defined, attempts to power on more than the specified number of FT VMs on a the same host will fail. Further, vSphere DRS, if enabled, won’t exceed this limit. However, vSphere DRS won’t correct any violations of the limit and vSphere HA will ignore the limit when responding to a failure.
N
das.ignoreInsufficientHbDatastore
false
true/
false
Suppress the host config issue that the number of heartbeat datastores is less than das.heartbeatDsPerHost
N
das.heartbeatDsPerHost
2
2-5
Defines the number of required heartbeat datastores per host. vCenter Server will attempt to chose the specified number and if it cannot, will report a configuration issue on the host. This issue can be suppressed using the das.ignoreInsufficientHbDatastore option.
Y

HA Agent (FDM) Configuration Options

The following options are set on a per-host basis by editing the fdm.cfg file on the host.  Alternately, these can also be set on a per-cluster basis through the vSphere Client by prepending ‘das.config.’ to the option name.  Use of any of these options requires a restart for them to take effect.

Name
Default
Description
Cluster Manager
fdm.deadIcmpPingInterval
10
ICPM pings are used to determine whether a slave host is network accessible when the FDM on that host is not connected to the master. This parameter controls the interval (expressed in seconds) between pings.
fdm.icmpPingTimeout
5
Defines the time to wait in seconds for an ICMP ping reply before assuming the host being pinged is not network accessible.
fdm.hostTimeout
10
Controls how long a master FDM waits in seconds for a slave FDM to respond to a heartbeat before declaring the slave host not connected and initiating the workflow to determine whether the host is dead, isolated, or partitioned.
fdm.stateLogInterval
600
Frequency in seconds to log cluster state.
fdm.nodeGoodness
0
When a master election is held, the FDMs exchange a goodness value, and the FDM with the largest goodness value is elected master. Ties are broken using the host IDs assigned by VC. This parameter can be used to override the computed goodness value for a given FDM. To force a specific host to be elected master each time an election is held and the host is active, set this option to a large positive value.  This option should not be specified on a per-cluster basis.
Inventory Manager
fdm.ft.cleanupTimeout
900
When a vSphere Fault Tolerance VM is powered on by vCenter Server, vCenter Server informs the HA master agent that it is doing so. This option controls how many seconds the HA master agent waits for the power on of the secondary VM to succeed. If the power on takes longer than this time (most likely because vCenter Server has lost contact with the host or has failed), the master agent will attempt to power on the secondary VM.
fdm.storageVmotionCleanupTimeout
900
When a storage vmotion is done in a HA enabled cluster using pre 5.0 hosts and the home datastore of the VM is being moved, HA may interpret the completion of the storage vmotion as a failure, and may attempt to restart the source VM. To avoid this issue, the HA master agent waits the specified number of seconds for a storage vmotion to complete. When the storage vmotion completes or the timer expires, the master will assess whether a failure occurred.
Policy Manager
fdm.policy.unknownStateMonitorPeriod
10
Defines the number of seconds the HA master agent waits after it detects that a VM has failed before it attempts to restart the VM.
FDM Service
fdm.event.maxMasterEvents
1000
Defines the maximum number of events cached by the master
fdm.event.maxSlaveEvents
600
Defines the maximum number of events cached by a slave.

VPXD Configuration Options
The following options are configure the behavior of vpxd.  Editing the vpxd.cfg file, which will affect all clusters in the inventory of vCenter Server, sets them.  All of these options require a restart of vpxd in order for them to take effect.
Name
Default
Description
vpxd.das.reportNoMasterSec
120
How long to wait in seconds before appending a cluster config issue to report that vCenter Server was unable to locate the HA master agent for the corresponding cluster.
vpxd.das.sendProtectListIntervalSec
60
Minimum time (in seconds) between consecutive calls by vCenter Server to the HA master agent to request that it protect a new VM.
vpxd.das.aamMemoryLimit
100
Memory limit in MB for AAM resource pool (used for FDM)
vpxd.das.electionWaitTimeSec
120
When configuring HA on a host, how long to wait in seconds after sending the host list to a new host for the FDM to become configured (change to master or slave state)
vpxd.das.heartbeatPanicMaxTimeout
60
Defines the value HA uses (in seconds) when configuring the host Misc.HeartbeatPanicTimeout advanced option
vpxd.das.slotMemMinMB
0
Default value in MB to use for memory reservation if no user value is set on any VM. Use to compute the slot size for HA admission control.
vpxd.das.slotCpuMinMHz
32
Default value in MHz to use for cpureservation if no user value is set on any VM. Use to compute the slot size for HA admission control

Thứ Ba, 3 tháng 4, 2012

Automatic Update NTP At Boot Time


Resetting the clock at boot time with ntpdate

The system clock is initialized from the hardware clock by the /etc/init.d/boot.clock script. (At least this is true in SuSE 8.1 and later; when booting Red Hat Linux 6.x, the system clock is initialized by /etc/rc.d/rc.sysinit instead.) Unfortunately, when this runs, the network has not yet been fully initialized, so it is not possible to query servers. Instead, it is better to run ntpdate from the /etc/init.d/boot.local script (called /etc/rc.d/rc.local in older versions), which is run as the very last thing when booting up (in run levels 2, 3, and 5, which is appropriate). Setting the system clock twice like this may leave it off by a bit during boot, but the amount by which it is off can be limited for the next boot by resetting the hardware clock after initializing the system clock from the NTP servers. You can do all of this by adding the following two lines to the end of your /etc/init.d/boot.local script (after replacing the server names):
    ntpdate -sb server1 [server2 ...]
    hwclock --systohc
The next time you boot, the hardware clock will only be off by the amount of drift between boots. (You should first check to see that you have hwclock on your system.)

The "-b" option forces the system clock to be set in one jump, rather than attempting to slew it gradually, and is recommended by the ntpdate documentation page when booting.
Note that this double clock setting procedure is essentially equivalent to what the standard boot-time startup scripts for ntpd do, so making the clock jump back and forth at boot time can't be all that bad. (It can make the log files harder to decipher, though.)
Unfortunately, the system boot scripts are very vendor-dependent, so this recipe may not work for your configuration. If there is an /etc/init.d/rc.local 2or /etc/init.d/boot.local script, it probably works the same way; otherwise, you will need to figure out something different for your flavor of Linux/*BSD/etc.

Thứ Tư, 28 tháng 3, 2012

Mount WIndows Share

Simple edit /etc/fstab and add the line

//ip windows/share /mymount cifs nosuid,nodev,noexec,credentials=/etc/samba/auth.smb,uid=500,gid=500,file_mode=0664,dir_mode=0755 0 0


then make a file

# vi /etc/samba/auth.smb





username=your user
password=your password

OpenVPN on Centos

This is step by step guide to create VPN network in two model Site to Site and Client to Site in bridge mode.

Please response any missing or incorrect...


# rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
# wget http://packages.sw.be/lzo/lzo-2.04-1.el5.rf.i386.rpm
# wget http://packages.sw.be/lzo/lzo-2.04-1.el5.rf.x86_64.rpm
# wget http://packages.sw.be/lzo/lzo-devel-2.04-1.el5.rf.i386.rpm
# wget http://packages.sw.be/lzo/lzo-devel-2.04-1.el5.rf.x86_64.rpm
# rpm -K lzo-*
# rpm -K lzo-* 
# wget http://packages.sw.be/openvpn/openvpn-2.1.4-1.el5.rf.x86_64.rpm
# rpm -K openvpn-2.1.4-1.el5.rf.x86_64.rpm
# rpm -ivh openvpn-2.1.4-1.el5.rf.x86_64.rpm 
OR 
# wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.1-1.el5.rf.i386.rpm
# rpm -Uvh rpmforge-release*# yum install openvpn
# chkconfig openvpn on
 
# cd /usr/share/doc/openvpn-2.2.0/easy-rsa/2.0
 goto last line and edit some infor
export KEY_COUNTRY="US"
export KEY_PROVINCE="CA"
export KEY_CITY="SanFrancisco"
export KEY_ORG="Fort-Funston"
export KEY_EMAIL="me@myhost.mydomain"

then save and return to continue...

# chmod 775 -R /usr/share/doc/openvpn-2.2.0/easy-rsa/2.0
# source ./vars
# ./clean-all
# ./build-ca

Generating a 1024 bit RSA private key
............++++++
...........++++++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [KG]:
State or Province Name (full name) [NA]:
Locality Name (eg, city) [BISHKEK]:
Organization Name (eg, company) [OpenVPN-TEST]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:OpenVPN-CA
Email Address [me@myhost.mydomain]:
 

Generate certificate & key for server

 

# ./build-key-server server
 
Generating client certificates is very similar to the previous step. On Linux/BSD/Unix:
# ./build-key client1
# ./build-key client2
# ./build-key client3
 or 
 
# openvpn --genkey --secret ta.key 
 
In this sample i try to make a bridge VPN so now I create a bridge ethernet on server
 
# yum install bridge-utils
 
then goto edit  /usr/share/doc/openvpn-2.2.0/sample-scripts/bridge-start

remember only edit correct IP for bridge interface
 
# ./bridge-start
 
for startup at boot time
 
go to find /etc/init.d/openvpn
 
find start session and add two line below
 
./etc/openvpn/bridge-start
 route add default gw your ip gateway br0 
Here is the config file at server site 
 
if using same key file in two locate.

here is config for site to site using same key file

# Which local IP address should OpenVPN
# listen on? (optional)
# local a.b.c.d
port 1111 
proto udp
dev tun0
ifconfig 10.8.0.1 10.8.0.2 # ip tunnel
secret /etc/openvpn/easy-rsa/keys/ta.key # key need to generation
push "route 192.168.50.0 255.255.255.0" # server site's IP
route 192.168.70.0 255.255.255.0 10.8.0.2 # other sie's IP
keepalive 10 120
comp-lzo
persist-key
persist-tun
status /var/log/openvpn-status.log
log         /var/log/openvpn.log
log-append  /var/log/openvpn.log
verb 3
mute 20
 
 
and other site config in my simple this site run ms windows so just down load binary package
from openvpn.net then download then create some file to log and save at config folder after 
that create config file client.ovpn which content below here...
 
Remember : copy ta.key from server site to this folder also.

remote your.VPN.server.IP  
port 1111
proto udp
dev tun
ifconfig 10.8.0.2 10.8.0.1
secret ta.key
route 192.168.50.0 255.255.255.0 10.8.0.1
keepalive 10 120
comp-lzo
persist-key
persist-tun
status openvpn-status.log
log /path/to/file/openvpn.log
log-append /path/to/file/openvpn.log
verb 2
mute 20

...and config bridge client to server.


here is server.conf


script-security 2
tls-server
port 1111
;proto tcp
proto udp
dev tap0
;dev tun
;dev-node tap0
ca ca.crt
cert server.crt
key server.key  # This file should be kept secret
dh dh1024.pem
ifconfig-pool-persist ipp.txt
server-bridge 192.168.50.8 255.255.255.0 192.168.50.150 192.168.50.152
server-bridge
push "route 192.168.50.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"
push "dhcp-option DNS 192.168.50.1"
;push "dhcp-option DNS 208.67.220.220"
client-to-client
keepalive 10 120
comp-lzo
persist-key
persist-tun
status /var/log/openvpn-status.log
log         /var/log/openvpn.log
log-append  /var/log/openvpn.log
verb 3
mute 20



...


and client.conf

before to do this step remember rename Tap-Adapter when install Openvpn for windows to "Tap"




client
dev tap
dev-node Tap
proto udp
remote your.VPN.server.ip
persist-key
persist-tun
ca ca.crt
cert client1.crt
key client1.key
ns-cert-type-server
comp-lzo
status /path/to/openvpn-status.log
log         /path/to/openvpn.log
log-append  /path/to/openvpn.log
verb 3
mute 20

 
Now let give it a try...
 
Problem with Centos5 for Openvpn version under 2.2.2.
When trying to auto startup script at init.d/openvpn i was met permission denied. 
==> Solution is uninstall this version by rpm -e or by yum remove and then download new version from 
openvpn.net. Before install new version we must update openssl by two package if want to success for
install new version by two command..

yum install openssl
yum install openssl-devel 
 
now unpack openvpn.ver.tar.gz and then follow command to install
 
# ./configure
# make
# make install