Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Friday, February 22, 2013

Prevent DOS with iptables


Prevent DOS with iptables

After a recent conversation on the Ubuntu Forums I wanted to post an example of using iptables.
Of course there are several types of DOS attacks , in this post I will demonstrating the use if iptables to limit the traffic on port 80.
The goal is to keep your web server “responsive” to legitimate traffic, but to throttle back on excessive (potential DOS) traffic.
In this demonstration iptables is configured :
  1. The default policy is ACCEPT (to prevent lockout in the event of flushing the rules with iptables -F).
  2. “Legitimate” traffic is then allowed. In this example I am allowing traffic only on port 80.
  3. All other traffic is then blocked at the end of the INPUT chain (the final rule in the INPUT chain is to DROP all traffic).
The rules I will demonstrate are as follows:

First rule : Limit NEW traffic on port 80

sudo iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m limit --limit 50/minute --limit-burst 200 -j ACCEPT
Lets break that rule down into intelligible chunks.
-p tcp --dport 80 => Specifies traffic on port 80 (Normally Apache, but as you can see here I am using nginx).
-m state NEW => This rule applies to NEW connections.
-m limit --limit 50/minute --limit-burst 200 -j ACCEPT =>This is the essence of preventing DOS.
  • “--limit-burst” is a bit confusing, but in a nutshell 200 new connections (packets really) are allowed before the limit of 50 NEW connections (packets) per minute is applied.
For a more technical review of this rule, see this netfilet page. Scroll down to a bit to the “limit” section.

Second rule – Limit established traffic

This rule applies to RELATED and ESTABLISHED all traffic on all ports, but is very liberal (and thus should not affect traffic on port 22 or DNS).
If you understood the above rule, you should understand this one as well.
sudo iptables -A INPUT -m state --state RELATED,ESTABLISHED -m limit --limit 50/second --limit-burst 50 -j ACCEPT
In summary, 50 ESTABLISHED (and/or RELATED) connections (packets really) are allowed before the limit of 50 ESTABLISHED (and/or RELATED) connections (packets) per second is applied.
Do not let that rule fool you, although it seems very open, it does put some limits on your connections.
Test it for yourself, try using the first rule with and without the second rule.

Full set of rules

After the above commands, here is the complete set of rules I am testing:
iptables-save
# Generated by iptables-save v1.4.4 on --
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
# Completed on --
# Generated by iptables-save --
*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
# Completed on --
# Generated by iptables-save v1.4.4 on --
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -m limit --limit 50/sec \
--limit-burst 50 -j ACCEPT
-A INPUT -p icmp -m limit --limit 1/sec -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -m state --state NEW -m limit --limit 50/min \
--limit-burst 200 -j ACCEPT
-A INPUT -j LOG
-A INPUT -j DROP
-A FORWARD -j DROP
-A OUTPUT -o lo -j ACCEPT
COMMIT
# Completed on --
This rule set is for demonstration only and is NOT a complete set of rules for a web server. Do no use this rule set unmodified on a production server.

Testing the rule set

Human interaction

Open Firefox, point it to your web page. The web page should load nice and fast.
Hit F5 repetitively, load the page as fast as you can. Your web site should remain nice and responsive.
So far, so good, we want our site to remain responsive.

Simulated DOS

Actual DOS attacks are many times faster then humans, here I will use ab.
See this link or the Apache documentation for information of ab.

Baseline, without the above 2 rules

ab -n 100 -c 10 http://bodhi's_test_server.com/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking bodhi's_test_server.com (be patient).....done


Server Software:        nginx
Server Hostname:       bodhi's_test_server.com
Server Port:            80

Document Path:          /
Document Length:        59786 bytes

Concurrency Level:      10
Time taken for tests:   13.174 seconds
Complete requests:      100
Failed requests:        0
Write errors:           0
Total transferred:      6002700 bytes
HTML transferred:       5978600 bytes
Requests per second:    7.59 [#/sec] (mean)
Time per request:       1317.369 [ms] (mean)
Time per request:       131.737 [ms] (mean, across all concurrent requests)
Transfer rate:          444.98 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:      122  129   2.2    128     134
Processing:  1151 1182  19.1   1177    1260
Waiting:      125  132   8.2    128     170
Total:       1280 1310  19.3   1305    1390

Percentage of the requests served within a certain time (ms)
  50%   1305
  66%   1313
  75%   1316
  80%   1321
  90%   1328
  95%   1354
  98%   1386
  99%   1390
 100%   1390 (longest request)
Notice:
Requests per second: 7.59 [#/sec] .
Total time for requests: 13 seconds .
(Data) Transfer rate: 444.98 [Kbytes/sec] .

With the above rules

First attempt:
ab -n 100 -c 10 http://bodhi's_test_server.com/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking bodhi's_test_server.com (be patient)...
apr_poll: The timeout specified has expired (70007)
Total of 99 requests completed
Oh no ! timed out, LOL
Second attempt (I reduced the number of requests to 90):
ab -n 90 -c 10 http://bodhi's_test_server.com/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking bodhi's_test_server.com (be patient).....done


Server Software:        nginx
Server Hostname:       bodhi's_test_server.com
Server Port:            80

Document Path:          /
Document Length:        59786 bytes

Concurrency Level:      10
Time taken for tests:   69.684 seconds
Complete requests:      90
Failed requests:        0
Write errors:           0
Total transferred:      5402430 bytes
HTML transferred:       5380740 bytes
Requests per second:    1.29 [#/sec] (mean)
Time per request:       7742.658 [ms] (mean)
Time per request:       774.266 [ms] (mean, across all concurrent requests)
Transfer rate:          75.71 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:      123  128   4.3    127     155
Processing:  1036 6269 10081.4   1921   51059
Waiting:      125 1240 5908.7    128   49656
Total:       1159 6396 10081.1   2044   51186

Percentage of the requests served within a certain time (ms)
  50%   2044
  66%   2981
  75%   5478
  80%   7047
  90%  20358
  95%  27356
  98%  48218
  99%  51186
 100%  51186 (longest request)
Notice :
Requests per second: 1.29 [#/sec] (mean)
Total time for requests: 69 seconds.
(Data) Transfer rate: 75.71 [Kbytes/sec] [Kbytes/sec].

For those unfamiliar with ab, that is a “minor” DOS

For comparison, here is what ab can do to the server (iptables was flushed [disabled]):
ab -n 1000 -c 100 http://bodhi's_test_server.com/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking bodhi's_test_server.com (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:        nginx
Server Hostname:       bodhi's_test_server.com
Server Port:               80

Document Path:          /
Document Length:        58708 bytes

Concurrency Level:      100
Time taken for tests:   59.324 seconds
Complete requests:      1000
Failed requests:        945
   (Connect: 0, Receive: 0, Length: 945, Exceptions: 0)
Write errors:           0
Total transferred:      59190450 bytes
HTML transferred:       58945935 bytes
Requests per second:    16.86 [#/sec] (mean)
Time per request:       5932.368 [ms] (mean)
Time per request:       59.324 [ms] (mean, across all concurrent requests)
Transfer rate:          974.37 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:      127  908 817.9    788    8016
Processing:   735 4779 1805.2   4368   15707
Waiting:      128  981 827.2    811   12143
Total:       1058 5687 1880.8   5269   17450

Percentage of the requests served within a certain time (ms)
  50%   5269
  66%   5899
  75%   6340
  80%   6863
  90%   8078
  95%   9001
  98%  10937
  99%  11730
 100%  17450 (longest request)

Notice :
Requests per second: 16.86 [#/sec]
Total time for requests: 69 seconds.
(Data) Transfer rate: 974.37 [Kbytes/sec] .
As you can see, the server has no problem dishing out 974.37 [Kbytes/sec] !!!

Closing remarks

Hopefully you now understand this “simple” example limiting a DOS on port 80.
With these rules your web site remains responsive to human interaction in firefox. Go ahead, hit F5 (refresh the page) as fast as you can, see if you can get your web page to slow down =) .
The difference is that as with a DOS attack, ab is hitting the server faster then you can with F5 , so your site is responsive to “normal” activity, but blocks DOS.
Obviously this is but one example and there are several types of DOS attacks. The goal is to demonstrate the use of iptables using a few “simple” rules.
You task is to take this knowledge and apply it to you own server.

Thursday, February 14, 2013

CentOS Linux install and configure NTP to synchronize the system clock


Q. How do I install and configure NTP under CentOS Linux 5 server to synchronize the system clock?
A. You can easily install NTP (Network Time Protocol, a means of transmitting time signals over a computer network) using yum command under Redhat or CentOS/Fedora core Linux.

Procedure

Login as the root user
Type the following command to install ntp
# yum install ntp
Turn on service
# chkconfig ntpd on
Synchronize the system clock with 0.pool.ntp.org server:
# ntpdate pool.ntp.org
Start the NTP:
# /etc/init.d/ntpd start

Install lamp with 1 command in Ubuntu 12.04, 12.10 QuantalQuetzal & LinuxMint13


This tutorial was has been tested on Ubuntu 10.04, 10.10, 11.04, 11.10, 12.04 LTS Precise Pangolin. Also tested in LinuxMint13 and works fine.
Open terminal and Type the command :install it   first  with


sudo apt-get install tasksel

Now to install LAMP, type the taskel command in terminal :

sudo  tasksel

And select LAMP Server


During the installation  you  will be  asked  to insert the  mysql root  password
Now check if php is working :

$sudo vi /var/www/info.php
and add
<?php
phpinfo();
?>
save and exit
restart apache2 ,
#sudo /etc/init.d/apache2 restart

sudo  apt-get  install  phpmyadmin
To login  to phpmyadmin, open browser and type :
http://ip/phpmyadmin   or http://localhost/phpmyadmin




Tuesday, October 16, 2012

Internet Access Through pptp vpn server on centos

Internet Access Through pptp vpn server on centos

Installation and Configuration of PPTP
Add the Poptop Yum Repository
rpm -Uhv http://poptop.sourceforge.net/yum/stable/rhel5/pptp-release-current.noarch.rpm
yum install ppp pptpd
Configure Kernel
Edit /etc/sysctl.conf
FROM net.ipv4.ip_forward = 0 To net.ipv4.ip_forward = 1
Verify changes sysctl –p
Configure Client Network Options
Modify /etc/pptpd.conf
localip 192.168.50.1
remoteip 192.168.50.2-15
Modify /etc/ppp/options.pptpd
ms-dns 8.8.8.8
ms-dns 8.8.4.4
Configure Client Access
Edit /etc/ppp/chap-secrets.
# Secrets for authentication using CHAP
# client        server  secret                  IP addresses
mccarrms        *       mccarrms-password       *
IPTables Rules
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -p gre -j ACCEPT
-A INPUT -p gre -j ACCEPT
-A INPUT -p gre -j ACCEPT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p esp -j ACCEPT
-A RH-Firewall-1-INPUT -p ah -j ACCEPT
-A RH-Firewall-1-INPUT -d 224.0.0.251 -p udp -m udp --dport 5353 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 25 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 2049 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport 137 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport 53 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport 138 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 139 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 445 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 23 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 1723 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 47 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 8245 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
*nat
:PREROUTING ACCEPT [1788:95928]
:POSTROUTING ACCEPT [90:5683]
:OUTPUT ACCEPT [90:5683]
-A POSTROUTING -s 192.168.50.0/255.255.255.0 -o eth0 -j MASQUERADE
-A POSTROUTING -o ppp0 -j MASQUERADE
COMMIT

Reference link
http://docs.cslabs.clarkson.edu/wiki/Install_PPTP_on_CentOS_5
https://www.centos.org/modules/newbb/viewtopic.php?topic_id=38783
http://blog.colovirt.com/2009/06/02/linux-security-iptables-cli-list-rules-without-dns-resolution/
http://serverfault.com/questions/407656/connect-linux-server-to-vpn-server-via-pptp
http://www.thegeekstuff.com/2011/06/iptables-rules-examples/

Wednesday, September 5, 2012

shell script to find linux memory process usage

shell script to find linux memory process usage

Hi,
The following script will check for top 20 processes which uses maximum memory resource in the server and will store it in “overusage” file only if the free memory goes below 700MB. Set cron to execute this script whenever needed.
 
#!/bin/bash
#High RAM usage checker
r=`free -m |awk 'NR==2' |awk '{ print$4 }'`
if [ $r -lt 700 ];
then
ps -e -orss=,args= | sort -b -k1,1n |tail -n 20 >> overusage
exit
fi

Monday, September 3, 2012

how to change timezone in centos

To change Timezone on centos 5 you need to follow the below mention Setup

1.yum install system-config-date
2. execute setup command on linux cli then see below figure



 3.Then you need to select 'Timezone Configuration' and press Enter Key and then you will get below figure.
4.From here select your require timezone and press Enter key.

Tuesday, August 7, 2012

Linux Monitoring Tools

Need to monitor Linux server performance? Try these built-in command and a few add-on tools. Most Linux distributions are equipped with tons of monitoring. These tools provide metrics which can be used to get information about system activities. You can use these tools to find the possible causes of a performance problem. The commands discussed below are some of the most basic commands when it comes to system analysis and debugging server

Monitoring the system:
pstree Processes and parent-child relationships
top Show top processes
iostat Report CPU statistics and input/output statistics for devices and partitions.
ps -auxw process status
uname -a print system information
cat /proc/version Display Linux kernel version in use.
cat /etc/redhat-release Display Red Hat Linux Release. (also /etc/issue)
uptime Tell how long the system has been running. Also number of users and system's load average.
w Show who is logged on and what they are doing.
/sbin/lsmod List all currently loaded kernel modules.
Same as cat /proc/modules
/sbin/runlevel Displays the system's current runlevel.
hostname Displays/changes the system's node name. (Must also manually change hostname setting in /etc/sysconfig/network. Command will change entry in /etc/hosts)
service Red Hat/Fedora command to display status of system services.
Example: service --status-all
Help: service --help




Process Management:

  • pstree -p
    OR
  • ps -auxw
    OR
  • top
  • kill <process-id-number>
  • killall <command-name>
Memory Usage:

vmstat Monitor virtual memory
free Display amount of free and used memory in the system. (Also: cat /proc/meminfo)
pamp Display/examine memory map and libraries (so). Usage: pmap pid
top Show top processes
sar -B Show statistics on page swapping.
time -v date Show system page size, page faults, etc of a process during execution. Note you must fully qualify the command as "/usr/bin/time" to avoid using the bash shell command "time".
cat /proc/sys/vm/freepages Display virtual memory "free pages".
One may increase/decrease this limit: echo 300 400 500 > /proc/sys/vm/freepages
cat /proc/meminfo Show memory size and usage.
 
  Filesystems and Storage Devices:

df -k report filesystem disk space usage. (-k reports in Kbytes)
du -sh Calculates file space usage for a given directory. (and everything under it) (-s option summarizes)
mount Displays all mounted devices, their mount point, filesystem, and access. Used with command line arguments to mount file system.
cat /proc/filesystems Display filesystems currently in use.
cat /proc/mounts Display mounted filesystems currently in use.
showmount Displays mount info for NFS filesystems.
cat /proc/swaps Displays swap partition(s) size, type and quantity used.
cat /proc/ide/hda/any-file Displays disk information held by kernel.




  • cfdisk - Curses based disk partition table manipulator. (very nice)
  • fdisk- Manipulate/configure the partition table.
  • sfdisk - Manipulate/configure the partition table.
  • fsck - Manipulate/configure the partition table. 
User Info:

who Displays currently logged in users.
Use who -uH for idle time and terminal info.


w Displays currently logged in users and processes they are running.
whoami  Displays user id.
groups Display groups you are part of.
Use groups user-id to display groups for a given user.
set Display all environment variables in your current environment.
id Display user and all group ids.
Use id user-id to display info for another user id.
last Listing of most recent logins by users. Show where from, date and time of login (ftp, ssh, ...) Also see lastlog command.
Show last 100 logins: last -100
history Shell command to display previously entered commands.

Monday, August 6, 2012

Vi Commands Cheat Sheet

The ultimate Vi cheat sheet for anyone learning Vi Commands or the Vi editor in general. Keep this guide close by when using the editor and you will learn how to use Vi in no time. Vim commands will be the same as Vi for the most part – Windows however has Gvim which allows some GUI interaction.

I – Inserts text at the beginning of the text line, not the beginning column of the vi screen
a – Appends to the end of the right of the cursor
A – Appends at the end of the current line
o – Begins a new line below the current line
O – Drops the current line and begins a new one in its place

Vi Replace

cw – Vi replace a single word from the current cursor position. To replace a whole word, you put the cursor on the the first character of the word.
c$ – replace the current line but doesn’t extend to change the rest of a wrapped sentence on the screen
r – Vi Replace the character under the cursor
R – Replaced the text on the same line until Esc is pressed, but it doesn’t change text on the next line. Instead, it pushes to ahead of the current changes.

Vi Delete


 x – Deletes a single character under the cursor
X – Deletes a single character before the cursor
dw – Deletes a single word that’s currently under the cursor, from the cursor position onward.

Vi Delete Line


 dd – Vi delete line, regardless of the cursors position on the line
D – Deletes all text from the cursor position to the end of the line
dL – Deletes all text from the cursor position to the end of the screen
dG – Deletes all text from the cursor to the EOF
d^ – Deletes all text from the beginning of the line to the cursor

Vi Copy & Paste

 Commands for Vi copy & paste:

yy – Vi copy line – copies a line of text to the unnamed buffer
3yy – Copies 3 lines of text to the unnamed buffer
yw – Copies a word (under the cursor) to the unnamed buffer
3yw – Copies 3 words to the unnamed buffer
P – Pastes the contents 0f the unnamed buffer to the right of the cursor
p – Pastes the contents of the unnamed buffer to the left of the cursor

Navigation Within a File

This may confuse you to start with,
H - This is the left arrow; it’s easy to remember because it’s the leftmost key in the four key set
J – Use this for the down arrow; I remember this by thinking of jown instead of down.
K – This is the up arrow; I remember this by thinking of kup for up.
L – Use this for the right arrow; I remember this as L is right, which I always thought sounded dumb, it’s alright on the right side of the keyboard…

Vi Page Down

Ctrl+F – Vi page down – Moves forward a page
Ctrl+D – Moves forward half a page

Vi Page Up

Ctrl+B – Vi page up – Moves back a page
Ctrl+U – Moves backward a half-page

Named and Unnamed Buffers

“ayy – Pulls a line the named buffer (a), overwriting the current contents
“Ayy – Appends the current line to the buffer
“A3yy – Pulls three lines from the current cursor position and appends the lines to the A buffer
“ap – Pastes the a buffer to the right of the cursor (the case of the buffer letter is meaningless)

Vi Search

How to perform a Vi Search.
N – Vi Search forward
Shift+N – Search Backward

Vi Search and Replace

:s/bob/BOB/ – Replaces the first instance of bob with BOB
:s/bob/BOB/g – Replaces all instances of bob with BOB in that line (note g stands for global)
:%s/bob/BOB/g – Replaces all instances of bob with BOB in that file no matter how many exist or how many changes made to each line

Vi Search for Part of a Word

A fuzzy search allows you to find something that you only know part of, for example if you wanted to find all instances of lines starting with the word “Uber” you would use the following:
/^Uber
To find all instances of the word “ninja” at the end of a line you would use:
/ninja$
In some instances you’ll need to find what’s called a metacharacter. For example, say you wanted to find the instances in a file for the asterisk character (*), because it stands for many characters. You could use something like this:
/The \* character
Another example might be finding the text ninja, with the period being treated only as a period. Otherwise, you’d find ninjas, ninja?, ninja! and so on. To find JUST ninja you would use the following:
/ninja\.
Finally, matching a range of characters is handy, such as trying to find all instances of the version number string v2.9. You either have to perform several searches of use something like this:
/v2.[1-9]
The square brackets denote a single character, stretching from the first character to the one after the dash. If you wanted instead to find all versions of the word the, including THE, THe and tHE, you would use the following:
/ [tT] [hH [eE]

Options in Vi

set number
set tabstop=5
set noh1search
The above code should be placed in the .exrc file which is located in the users home dir.
There are more than 60 options available in vi, to view them all type
:set all
To find out about an options status type
:set optionname?
:set number – turns on line numbers
:set nonumber – turns the number option off

Advanced Vi commands

How to run external commands in vi:
Say for example you want to run “ls -l” inside of vi as you can’t remember a file name, you would enter:
:! ls -l
Pressing enter or command will return you to the vi session. If the output is more than one screen it is piped to the more command.

Joining lines in vi

Back space only works on current lines, so to join lines in vi you need to position the curser in either line and press Shift+J

Split windows in vi

When you are editing a file and want to see a different section of the file or even a different file altogether, you can use the following:
:split – This splits the window horizontally
:vsplit – this splits the file vertically, with the same file on each side
To switch between the windows, hit Ctrl+W
To edit two files in vi at the same time, open the first file and then type:
:split file2
To set the hight of the split window:
:15split /blah/file
The above will split the top 15 lines of the screen and display the contents of the /blah/file.
To close the split window, take focus by hitting Ctrl+W and then enter :close
Or to close all the other split windows, take focus of the main window and enter:
: only
This will close all other windows apart from your window :p

Vi Save

 :w – Vi Save, write the file out to disk
Vi Save & Exit

:q – Vi exit – this will close Vi
:wq – Vi save & exit
: x – Vi exit, and prompts it you want to save on exit.
Shift+ZZ - Alternative way to save and exit Vi
:q! – Exits vi and discards and changes you made
:wq! – Vi Save and exit if you are root and do not have the write bit set for the file you are attempting to write.

Misc / Additional

U – Vi Undo, easy to remember, enter U in command mode to undo the last command.
:+X+! – In command mode this will undo everything you have done since the last disk write.
Ctrl+G – Shows the file name, total number of lines and the current position expressed as a percentage of the total number of lines in the file.

Multipliers

Just about any keystroke or action can be done multiple times by prefixing it with a number.
For example to move the curser to line 5 you would press 5g. To move 12 words to the right you would enter 12W.
If you have any additional commands or questions / suggestions drop us a comment below.

Friday, August 3, 2012

Passive Mode FTP with iptables

There’s lots of advice on the net about how to setup a server with iptables to allow passive mode FTP. Below is the approach that we’ve found to be most effective.
Start by configuring your FTP daemon to use a fixed range of ports. We use 41361 to 65534 which is the IANA registered ephemeral port range. The exact config depends on what FTP software you’re using:
vsftpd
Edit /etc/vsftpd/vsftpd.conf and add the following lines:
pasv_min_port=49152 
pasv_max_port=65534
proftpd
Edit /etc/proftpd.conf and add to the Global section:
</Global>
......
PassivePorts 49152 65534
</Global>
Now restart your FTP service so the changes take effect.
Next you’ll need to configure the ip_conntrack_ftp iptables module to load. On Redhat/CentOS just edit /etc/sysconfig/iptables-config and add “ip_conntrack_ftp” to the IPTABLES_MODULES like this:
IPTABLES_MODULES="ip_conntrack_ftp"
Now restart the iptables service:
/sbin/service iptables restart
You can verify that the correct port range has been registered with lsmod like this:
lsmod | grep conntrack_ftp
and you’ll get something like this:
ip_conntrack_ftp       41361  0
ip_conntrack           91621  2 ip_conntrack_ftp,xt_state
And that’s all it takes to get passive mode ftp working behind iptables.
One extra note: If your server is NATed behind a physical firewall then you’ll probable need to load the “ip_nat_ftp” iptables module.