Monday 30 September 2013

Command to enable/disable ICMP PING

Ping command is basically working on sending an Internet Control Message Protocol (ICMP) echo request packets to the target host and waiting for an ICMP response.

echo “0″ >> /proc/sys/net/ipv4/icmp_echo_ignore_all

Many server provider and host  disabled the PING command to secure the server, refer to the following command to disable the PING command.

echo “1″ >> /proc/sys/net/ipv4/icmp_echo_ignore_all

Backup of mysql database using cron job.

To generate the backup of mysql database using cron job refer following three format as per your requirement.

1) Cron job to generate  database backup in  .sql format

* * * * * /usr/bin/mysqldump -u databaseusername databasename -ppassword > /path of database database.sql

2) Cronjob to compress database backup in .bz2 format

* * * * * /usr/bin/mysqldump -u datbaseusername databasename -pdatbasepassword|bzip2 -c > /path of database database.bz2

3)  Cronjob to compress database backup in .gz format

* * * * * /usr/bin/mysqldump -u databaseusername databasename -ppassword|gzip > /path of databasedatabase.gz

Core Files in Linux

A core file created when ever a program terminates unexpectedly and its also useful for determining what caused the termination. In many Linux server by default they do not produce core files when programs crash or terminates unexpectedly.

On  most of the Linux server core file size limitation is set to 0.You can check the core file size limit set in server by using following command.

root@test [~]# ulimit -c
1000000

In above command core file size limit is 1000000 if output occur empty then it means core file size limit haven’t set on server and you can set it as

root@test [~]# ulimit -c 1000000

or

root@test [~]# ulimit -c unlimited

If you want to test core file limit is working on your server or not? then run following command

kill -s SIGSEGV $$
This above command will crashes your shell and produces core file in the current directory. as core.*

If core file is taking lots of disk space on server and you want to disable it then follow the steps one by one.

root@test [~]#which httpd

/usr/sbin/httpd

root@test [~]#pico /usr/sbin/httpd

And following line in /usr/sbin/httpd

ulimit -c 0

And then restart the Apache server

How to generate the New Password from shell (SSH)?

If you use SSH, use mkpasswd command for creating passwords, always set the strong password, so that you won’t face the hacking issue because hackers always run the brute force attacks to crack the password therefore strong password always help to secure the server from the such attacks

root@redhat[~]#mkpasswd -l 10 -d 5 -C 3 -s 2
L]4P@GhaYdV6ii3

Flush RAM memory In Linux.

root@redhat [~]# free -m
total       used       free     shared    buffers     cached
Mem:        2025       1863        162          0        522        992
-/+ buffers/cache:        349       1676
Swap:         4996          0       4996


Now flush RAM memory.

root@redhat [~]# echo 1 > /proc/sys/vm/drop_caches

Once again check memory usage and check difference.

root@redhat [~]# free -m
total       used       free     shared    buffers     cached
Mem:          2025        353       1671          0          0         28
-/+ buffers/cache:        324       1700
Swap:         4996          0       4996

Rebuild the RPM database.




If you are facing the problem with the rpm then you can simply update the rpm database by using the following command from the shell.The following command allow you to recover the corrupt rpm database.

rm -f /var/lib/rpm/__db*
rpm --rebuilddb

How to delete - (Hypen)file names?

On most servers hackers upload files in -file format and many peoples are not sure about how to delete -files. You can refer following command to any file which started with “hyphen -”.

root@redhat.com[root]#rm -rf ./-hackscripts/

Install eaccelerator tool on Plesk Linux Server

To Install eaccelerator on Plesk Linux Server refer to the following steps and make sure that you have logged in to the shell with the root login details.

cd /usr/local/src/

wget http://sourceforge.net/projects/eaccelerator/files/eaccelerator/eAccelerator%200.9.5.2/eaccelerator-0.9.5.2.zip/download

unzip eaccelerator-0.9.5.2.zip

cd eaccelerator-0.9.5.2/

phpize

On most of the server phpsize command is not working due to that run the command

yum install php-devel

And now try to phpzine once again

phpize

export PHP_PREFIX=”/usr”

$PHP_PREFIX/bin/phpize

./configure -enable-eaccelerator=shared -with-php-config=$PHP_PREFIX/bin/php-config

make

make test

make install

Now make backup for the current working php.ini file

cp -p /etc/php.ini /etc/php.ini-back

nano /etc/php.ini

Now add the following lines in the php.ini file

~~~~~~~
extension=”eaccelerator.so”
eaccelerator.shm_size=”16″
eaccelerator.cache_dir=”/tmp/eaccelerator”
eaccelerator.enable=”1″
eaccelerator.optimizer=”1″
eaccelerator.check_mtime=”1″
eaccelerator.debug=”0″
eaccelerator.filter=”"
eaccelerator.shm_max=”0″
eaccelerator.shm_ttl=”0″
eaccelerator.shm_prune_period=”0″
eaccelerator.shm_only=”0″
eaccelerator.compress=”1″
eaccelerator.compress_level=”9″
~~~~~~~~~~

Now run the following command to check the modules loaded correctly or not.

php -m

Restart the web service

/etc/init.d/httpd stop

/etc/init.d/httpd start

Steps to mount remote directory on Linux Server Using SSHFS

We can mount the remote directory on the Linux Server by using the following three simple commands only.

Login in to the server as a root user and run the commands one by one and make sure that you are using your own remote server ip instead of our test server ip 10.10.10.10

yum install fuse-sshfs

The above command will install the fuse-sshfs

Create the mount directory where you want to mount the remote directory.

mkdir /mnt/remotemount

Now mount the remote directory make sure that you are using the correct remote directory server ip and root password
sshfs root@10.10.10.10:/the_physical_path_which_you_are_mounting  /mnt/remotemount

Now check the mount point

mount

If you want to remove the mount point then use the following command

umount /mnt/remotemount

If above command shows the error “mount point busy” the use the following command

umount -l /mnt/remotemount

Command to delete the session files from the tmp

Basically all the session files stored in the tmp directory and some time due to the excessive connection to mysql, we are facing the tmp directory 100% full problem at that time we can use the following command in cron and remove the session file more then 30 minutes old.

find /tmp -type f -name sess_* -cmin +30 |xargs rm -f


In above command I have used +30 for the 30 minutes, you can use the values as per your requirement.

Linux FSCK options

Many time we face the “read only partition” problem on the Linux Server at that time while rebooting the server from KVM,  its stuck at maintenance mode and some time auto fsck completed the fsck successfully but after that server ge auto rebooted . We can use the following commands to run the fsck manually.

For example the /dev/sda2  partition having the read only partition error message then run the following command, it will take time as per partiton size

fsck -y -p -v /dev/sda1

or

e2fsck -y -v -f /dev/sda1

Many time due to big partition size ,we have to wait for the long time at that time we think fsck process is stuck at that time we can use the following fsck command because its showing the % for the fsck process, so that we are able to see how much % fsck is completed and remaining.

fsck -y -p -C0 /dev/sda2

or

e2fsck -y  -C0 /dev/sda2

Now reboot the server in he init 3 run levele

root@server[~]# init 3

Note : Make sure that partition is not mounted while running fsck.

Linux Server Admin Tasks 1

Every server admin must scan the server for following files once in a week and take the necessary action to secure the server from the hacks.

Simply install the mlocate modules on the server.

yum install mlocate -y

Update the local locate command database, it will take the 15 to 20 minutes as per data present on the server.

updatedb

Now create the new file locate.sh or (scan.sh)  and add the following commands in the file locate.sh and make sure that you have set the 755 permission to the file locate.sh.

locate shell.php
locate irc
locate eggdrop
locate bnc
locate BNC
locate ptlink
locate BitchX
locate guardservices
locate psyBNC
locate .rhosts



If you would like, you can also configure the cron to execute the file  locate.sh as per your requirement, so that no need to run the file manually.


Sunday 29 September 2013

Bypass Phone and SMS verification

First of all we should understand why SMS and Phone Verification System is Important?


* Keep More Visitors for Market

* Providing Extra Security for their Website

* Keep Spammers out

* Daily Advertisement and promotional ads daily


Rather we can able to create and Bypass gmail (facebook, youtube, other shopping sites) without SMS verification. Because gmail allow to create only few account. When you try to create more account with same mobile number, google restricted and you can't create more account. so we can create counterless gmail accounts using following steps.

This method is very useful to Bypass SMS verification and useful when you need to Sign up any account and do not feel comfortable to giving your real number or if you want to create multiple account.

Lets Start Step by Step:


1) First go to this Website : Receive-Sms Online


2) Copy any one number and paste it where they are asking SMS Verification.



3) Simply come back and click the number which you have selected, check it out there is your code sent by google, youtube or whatever else.

Secure Linux Server 2

Here are a few things you need to tweak in order to improve OpenSSH server security.

Default Config Files and SSH Port
/etc/ssh/sshd_config - OpenSSH server configuration file.
/etc/ssh/ssh_config - OpenSSH client configuration file.
~/.ssh/ - Users ssh configuration directory.
~/.ssh/authorized_keys or ~/.ssh/authorized_keys - Lists the public keys (RSA or DSA) that can be used to log into the user’s account
/etc/nologin - If this file exists, sshd refuses to let anyone except root log in.
/etc/hosts.allow and /etc/hosts.deny : Access controls lists that should be enforced by tcp-wrappers are defined here.
SSH default port : TCP 22

SSH Session in Action
#1: Disable OpenSSH Server
Workstations and laptop can work without OpenSSH server. If you need not to provide the remote login and file transfer capabilities of SSH, disable and remove the SSHD server. CentOS / RHEL / Fedora Linux user can disable and remove openssh-server with yum command:
Debian / Ubuntu Linux user can disable and remove the same with apt-get command:
You may need to update your iptables script to remove ssh exception rule. Under CentOS / RHEL / Fedora edit the files /etc/sysconfig/iptables and /etc/sysconfig/ip6tables. Once donerestart iptables service:
#2: Only Use SSH Protocol 2
SSH protocol version 1 (SSH-1) has man-in-the-middle attacks problems and security vulnerabilities. SSH-1 is obsolete and should be avoided at all cost. Open sshd_config file and make sure the following line exists:
Protocol 2

#3: Limit Users' SSH Access
By default all systems user can login via SSH using their password or public key. Sometime you create UNIX / Linux user account for ftp or email purpose. However, those user can login to system using ssh. They will have full access to system tools including compilers and scripting languages such as Perl, Python which can open network ports and do many other fancy things. One of my client has really outdated php script and an attacker was able to create a new account on the system via a php script. However, attacker failed to get into box via ssh because it wasn't in AllowUsers.
Only allow root, firesale and jerry user to use the system via SSH, add the following to sshd_config:
AllowUsers root firesale jerry
Alternatively, you can allow all users to login via SSH but deny only a few users, with the following line:
DenyUsers saroj anjali foo
You can also configure Linux PAM allows or deny login via the sshd server. You can allow list of group name to access or deny access to the ssh.

#4: Configure Idle Log Out Timeout Interval
User can login to server via ssh and you can set an idel timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:
ClientAliveInterval 300
ClientAliveCountMax 0
You are setting an idle timeout interval in seconds (300 secs = 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out).

#5: Disable .rhosts Files
Don't read the user's ~/.rhosts and ~/.shosts files. Update sshd_config with the following settings:
IgnoreRhosts yes
SSH can emulate the behavior of the obsolete rsh command, just disable insecure access via RSH.

#6: Disable Host-Based Authentication
To disable host-based authentication, update sshd_config with the following option:
HostbasedAuthentication no

#7: Disable root Login via SSH
There is no need to login as root via ssh over a network. Normal users can use su or sudo (recommended) to gain root level access. This also make sure you get full auditing information about who ran privileged commands on the system via sudo. To disable root login via SSH, update sshd_config with the following line:
PermitRootLogin no
However, bob made excellent point:
Saying "don't login as root" is h******t. It stems from the days when people sniffed the first packets of sessions so logging in as yourself and su-ing decreased the chance an attacker would see the root pw, and decreast the chance you got spoofed as to your telnet host target, You'd get your password spoofed but not root's pw. Gimme a break. this is 2005 - We have ssh, used properly it's secure. used improperly none of this 1989 will make a damn bit of difference. -Bob

#8: Enable a Warning Banner
Set a warning banner by updating sshd_config with the following line:
Banner /etc/issue
Sample /etc/issue file:
----------------------------------------------------------------------------------------------
You are accessing a XYZ Government (XYZG) Information System (IS) that is provided for authorized use only.
By using this IS (which includes any device attached to this IS), you consent to the following conditions:
+ The XYZG routinely intercepts and monitors communications on this IS for purposes including, but not limited to,
penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM),
law enforcement (LE), and counterintelligence (CI) investigations.
+ At any time, the XYZG may inspect and seize data stored on this IS.
+ Communications using, or data stored on, this IS are not private, are subject to routine monitoring,
interception, and search, and may be disclosed or used for any XYZG authorized purpose.
+ This IS includes security measures (e.g., authentication and access controls) to protect XYZG interests--not
for your personal benefit or privacy.
+ Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching
or monitoring of the content of privileged communications, or work product, related to personal representation
or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work
product are private and confidential. See User Agreement for details.
----------------------------------------------------------------------------------------------
Above is standard sample, consult your legal team for exact user agreement and legal notice details.
#8: Firewall SSH Port # 22
You need to firewall ssh port # 22 by updating iptables or pf firewall configurations. Usually, OpenSSH server must only accept connections from your LAN or other remote WAN sites only.
Netfilter (Iptables) Configuration

Update /etc/sysconfig/iptables (Redhat and friends specific file) to accept connection only from 192.168.1.0/24 and 202.54.1.5/29, enter:
-A RH-Firewall-1-INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -s 202.54.1.5/29 -m state --state NEW -p tcp --dport 22 -j ACCEPT
If you've dual stacked sshd with IPv6, edit /etc/sysconfig/ip6tables (Redhat and friends specific file), enter:
 -A RH-Firewall-1-INPUT -s ipv6network::/ipv6mask -m tcp -p tcp --dport 22 -j ACCEPT
Replace ipv6network::/ipv6mask with actual IPv6 ranges.
*BSD PF Firewall Configuration

If you are using PF firewall update /etc/pf.conf as follows:
pass in on $ext_if inet proto tcp from {192.168.1.0/24, 202.54.1.5/29} to $ssh_server_ip port ssh flags S/SA synproxy state
#9: Change SSH Port and Limit IP Binding
By default SSH listen to all available interfaces and IP address on the system. Limit ssh port binding and change ssh port (by default brute forcing scripts only try to connects to port # 22). To bind to 192.168.1.5 and 202.54.1.5 IPs and to port 300, add or correct the following line:
Port 300
ListenAddress 192.168.1.5
ListenAddress 202.54.1.5
A better approach to use proactive approaches scripts such as fail2ban or denyhosts (see below).
#10: Use Strong SSH Passwords and Passphrase
It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys. Brute force attack works because you use dictionary based passwords. You can force users to avoid passwords against a dictionary attack and use john the ripper tool to find out existing weak passwords. Here is a sample random password generator (put in your ~/.bashrc):
genpasswd()
{

local
l=$1

[
"$l" == ""
] && l=20

tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}
Run it:
Output:
uw8CnDVMwC6vOKgW
#11: Use Public Key Based Authentication
Use public/private key pair with password protection for the private key. See how to use RSA and DSA key based authentication. Never ever use passphrase free key (passphrase key less) login.
#12: Use Keychain Based Authentication
keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys. See how to setup and use keychain software.
#13: Chroot SSHD (Lock Down Users To Their Home Directories)
By default users are allowed to browse the server directories such as /etc/, /bin and so on. You can protect ssh, using os based chroot or use special tools such as rssh. With the release of OpenSSH 4.8p1 or 4.9p1, you no longer have to rely on third-party hacks such as rssh or complicated chroot(1) setups to lock users to their home directories. See this blog post about new ChrootDirectory directive to lock down users to their home directories.
#14: Use TCP Wrappers
TCP Wrapper is a host-based Networking ACL system, used to filter network access to Internet. OpenSSH does supports TCP wrappers. Just update your /etc/hosts.allow file as follows to allow SSH only from 192.168.1.2 172.16.23.12 :
sshd : 192.168.1.2 172.16.23.12
#15: Disable Empty Passwords
You need to explicitly disallow remote login from accounts with empty passwords, update sshd_config with the following line:
PermitEmptyPasswords no
#16: Thwart SSH Crackers (Brute Force Attack)
Brute force is a method of defeating a cryptographic scheme by trying a large number of possibilities using a single or distributed computer network. To prevents brute force attacks against SSH, use the following softwares:
DenyHosts is a Python based security tool for SSH servers. It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.
Explains how to setup DenyHosts under RHEL / Fedora and CentOS Linux.
Fail2ban is a similar program that prevents brute force attacks against SSH.
security/sshguard-pf protect hosts from brute force attacks against ssh and other services using pf.
security/sshguard-ipfw protect hosts from brute force attacks against ssh and other services using ipfw.
security/sshguard-ipfilter protect hosts from brute force attacks against ssh and other services using ipfilter.
security/sshblock block abusive SSH login attempts.
security/sshit checks for SSH/FTP bruteforce and blocks given IPs.
BlockHosts Automatic blocking of abusive IP hosts.
Blacklist Get rid of those bruteforce attempts.
Brute Force Detection A modular shell script for parsing application logs and checking for authentication failures. It does this using a rules system where application specific options are stored including regular expressions for each unique auth format.
IPQ BDB filter May be considered as a fail2ban lite.
#17: Rate-limit Incoming Port # 22 Connections
Both netfilter and pf provides rate-limit option to perform simple throttling on incoming connections on port # 22.
Iptables Example

The following example will drop incoming connections which make more than 5 connection attempts upon port 22 within 60 seconds:
#!/bin/bash
inet_if=eth1
ssh_port=22
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --set
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --update --seconds 60 --hitcount 5 -j DROP

Call above script from your iptables scripts. Another config option:
$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT
$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
# another one line example
# $IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT
See iptables man page for more details.
*BSD PF Example

The following will limits the maximum number of connections per source to 20 and rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.
sshd_server_ip="202.54.1.5"
table <abusive_ips> persist
block in quick from <abusive_ips>
pass in on $ext_if proto tcp to $sshd_server_ip port ssh flags S/SA keep state (max-src-conn 20, max-src-conn-rate 15/5, overload <abusive_ips> flush)
#18: Use Port Knocking
Port knocking is a method of externally opening ports on a firewall by generating a connection attempt on a set of prespecified closed ports. Once a correct sequence of connection attempts is received, the firewall rules are dynamically modified to allow the host which sent the connection attempts to connect over specific port(s). A sample port Knocking example for ssh using iptables:
$IPT -N stage1
$IPT -A stage1 -m recent --remove --name knock
$IPT -A stage1 -p tcp --dport 3456 -m recent --set --name knock2

$IPT -N stage2
$IPT -A stage2 -m recent --remove --name knock2
$IPT -A stage2 -p tcp --dport 2345 -m recent --set --name heaven

$IPT -N door
$IPT -A door -m recent --rcheck --seconds 5 --name knock2 -j stage2
$IPT -A door -m recent --rcheck --seconds 5 --name knock -j stage1
$IPT -A door -p tcp --dport 1234 -m recent --set --name knock

$IPT -A INPUT -m --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT
$IPT -A INPUT -p tcp --syn -j doo
fwknop is an implementation that combines port knocking and passive OS fingerprinting.
Multiple-port knocking Netfilter/IPtables only implementation.
#19: Use Log Analyzer
Read your logs using logwatch or logcheck. These tools make your log reading life easier. It will go through your logs for a given period of time and make a report in the areas that you wish with the detail that you wish. Make sure LogLevel is set to INFO or DEBUG in sshd_config:
LogLevel INFO
#20: Patch OpenSSH and Operating Systems
It is recommended that you use tools such as yum, apt-get, freebsd-update and others to keep systems up to date with the latest security patches.
Other Options
To hide openssh version, you need to update source code and compile openssh again. Make sure following options are enabled in sshd_config:
#  Turn on privilege separation
UsePrivilegeSeparation yes
# Prevent the use of insecure home directory and key file permissions
StrictModes yes
# Turn on  reverse name checking
VerifyReverseMapping yes
# Do you need port forwarding?
AllowTcpForwarding no
X11Forwarding no
#  Specifies whether password authentication is allowed.  The default is yes.
PasswordAuthentication no
Verify your sshd_config file before restarting / reloading changes:
Tighter SSH security with two-factor or three-factor (or more) authentication.

How To Protect Linux Web Server From Hackers

Apache is the most widely used web server over the internet on Linux machines. For better and reliable performance you need to protect your web server from hackers. Here i am going to write some steps which can help you in protecting your web server from hacker. “I am writing this article from some references and apache security tips.”

Steps to secure apache web server
1-Update you apache at regular interval
You should update your linux at a regular interval of time. If you have installed it from source, make sure that upgrade is not going to break any modules or dependencies your Web site has. And if you update Apache, make sure PHP (if used) is updated as well. New holes and security risks are found all the time. You have to ready for that.
2-Turn off unwanted services
There are a some apache services you don’t want to use. All of these services can be disabled or turnoff in the httpd.conf file. Some of these service are:
Directory browsing.
Server side Includes.
CGI execution.
Symbolic links.
3-Use the right user:group
One of the first things to ensure is that Apache does not run as root because if Apache is cracked then an attacker could get control of the root account. One of the biggest offenders is the root user. This can cause some serious issues. Or say both Apache and MySQL are run by the same user/group. If there is a hole in anyone, it can lead to an attack on the other. The best scenario is to make sure Apache is run as the user and group apache. To make this change, open the httpd.conf file and check the lines that read:
User Group
Change these entries to:
User apache Group apache
If you get any errors indicating the group or user do not exist, you’ll have to create them.
4-Disable unused modules
Apache has a ton of modules. To get an idea how many modules your installation is running, issue the command (as the root user) grep -n LoadModule httpd.conf from within your Apache configuration directory. This command will show you every module Apache is loading, along with the line number it falls on. To disable the modules you don’t need, simply comment them out with a single # character at the beginning of the module line.
5-Do not allow browsing outside the document root
Never allow browsing outside the document root. Unless you have a specific need to allow it. Disable this feature. First, you’ll need to edit the document root Directory entry like so:
Order Deny, Allow Deny from all Options None AllowOverride None
Now, if you need to add options to any directory within the document root, you will have to add a new Directory entry for each one.
6-Limit request size
Limit your request size because DDOS attack is always possible for allowing large request. The size of your limit request will depend upon your Web site’s traffic need. By default, LimitRequestBody is set to unlimited.
7-Immunize httpd.conf
Hide your httpd.conf file is one of the best security measures . If a person can’t see it, he can’t change it. To immunize the httpd.conf file, set the immutable bit with the following command:
chattr +i /path/to/httpd.conf
where /path/to/httpd.conf is the path to your Apache configuration file. Now it will be very difficult for anyone to make any changes to httpd.conf.
8-Restrict access
You can restrict access to your internal network by adding the following inside a directory tag in your httpd.conf file:
Order Deny, Allow Deny from all Allow from 192.168.1.0/16
where 192.168.1.0/16 is the configuration matching your internal network. As with all modifications to the httpd.conf file, make sure you restart Apache so the changes take effect.
9- Hide Apache’s version number
This is also one of some good defences. By hiding it, you keep hackers from knowing how to quickly hack your Web server. To hide Apache’s version number, add the following in your document root Directory tag:
ServerSignature Off ServerTokens Prod

How to change default SSH port

This is a quick tutorial about changing SSH port on a Linux server.

Login to your server
Open the following file in your favorite text editor
/etc/ssh/sshd_config
Locate “#Port 22″
Remove the # in front and change 22 to whatever number you wish to use as your port. It should look like “Port 86868″. Save the file
Restart SSH daemon using following command
service sshd restart

Difference between YUM and RPM in Linux

Installing and Uninstalling software, packages might get a little tricky for users that are new to Linux. While windows has a straight forward (probably because you are used to it), Linux has several ways of installing and uninstalling programs. There are operating systems like Ubuntu where you can simply install programs with “apt-get install” command, there are also operating systems like CentOS where you’d need to install programs with “YUM“. Wherein sometimes websites would suggest you to download the .rpm file and then install the program. This post will help you understand the difference between YUM and RPM. Hopefully, this will simplify Linux for you.

1] What is RPM?
Redhat Package Manager, shortly known as RPM is like setup file, somewhat similar to “.exe” files we have in Windows. RPM files are the packages which will install the program in your computer. While commands are very basic and simple to install and uninstall the program, it sometime gets difficult to actually find the links to download these RPM (Linux is as user friendly as a computer can get).

2] What is YUM?
Difference between YUM and RPMYellowdog Updater Modified, shortly known as YUM is like a Library which has all the RPMs indexed in it. Since we’re using Linux, we’re cool, we don’t want to waste our time finding the setup files. Hence, we have an entire Library that already has all the RPMs indexed in it. All we need to do is execute the command “yum install package” where package is the software you’re looking to install. Isn’t it cool? No need to Google around to find your programs. YUM is somewhat like Google for Linux programs. You can even search the possible software with commands like “yum list package” “yum search package” etc.

Hence, you can not possibly find any DIFFERENCE between RPM and YUM because they are NOT competitors. They work with each other. You would most likely end up using YUM in order to install, uninstall the programs. In case YUM doesn’t have your program indexed, then you will need to download the RPM package from the internet in order to install it

H-Sphere Locations





Root directory in HSphere: /hsphere/local


Configuration files:

Common path - /hsphere/local/config
Control panel - /hsphere/local/home/cpanel/arjun/psoft_config/hsphere.properties
DNS - /etc/named.conf
The main named directory - /hsphere/local/var/named/
HTTP - /hsphere/local/config/httpd/httpd.conf
FTP - /hsphere/local/config/ftpd/proftpd.conf
Qmail - /hsphere/local/var/qmail/control/
Mysql - /etc/my.cnf
php.ini - /hsphere/local/config/httpd/php.ini or /usr/local/lib/php.ini


Control Panel features - /hsphere/local/home/cpanel
Scripts in hsphere - /hsphere/shared/scripts/
Location of domains - /hsphere/local/home//
Qmail - /hsphere/local/var/qmail(A symbolic link given to /var/qmail)
Mails - /hsphere/local/var/vpopmail/domains 

Log files paths:

HSphere - /var/log/hsphere/hsphere.log
DNS - /var/log/messages
HTTP - /hsphere/local/var/httpd/logs/
Mail - /var/log/maillog
Horde - /hsphere/local/var/horde/log
FTP - /hsphere/local/var/proftpd/xferlog OR /var/log/proftpd/auth.log
MySQL - /var/log/mysqld.log


Statistics: Webalizer and Modlogan

/hsphere/local/var/staticstics - statistics results from rotatelogs (used for bandwith metering)
/hsphere/shared/ - modlogan and webalizer files
/hsphere/shared/apache/conf/modlogan_user.cfg - ModLogAn config file
/hsphere/shared/apache/conf/webalizer_user.cfg - webalizer config file (if MySQL is installed)
/hsphere/shared/skel/webalizer - skeleton files for webalizer section of the site.
/hsphere/shared/skel/modlogan - skeleton files for ModLogAn section of the site.


FTP and Frontpage:

/hsphere/local/var/proftpd/ - ftp log files
/hsphere/local/config/ftpd/ - ftp config files
/hsphere/shared/sbin/proftpd - ftp daemon file
/hsphere/shared/frontpage - FrontPage installation
/hsphere/local/var/frontpage - FrontPage config files

Others:

/hsphere/local/network/ips - all IP addresses and their netmasks that will be brought up by the system at start up. Used by H-Sphere to control IPs on the server.
/hsphere/shared/apache/htdocs - document root. Place index.html into this directory.
/hsphere/shared/apache/webshell - WebShell installation. This is a web based file manager that comes with H-Sphere
/hsphere/shared/skel - skeleton files for user sites. These are html pages that users see at their address before they upload their site content.
/hsphere/shared/skel/website - skeleton files for new sites
/hsphere/shared/skel/suspended - skeleton files for suspended sites
/hsphere/local/home/cpanel/apache/logs/ssl_engine_log - SSL log file in hshpere

Monday 23 September 2013

Basics of EMail Exchanging-


E-Mail:

You can send message from one computer to another computer using electronic-mail around the world. E-mail is more powerful and more usable tools in today’s world. This E-mail is transfer via into the computer and the computer network. There are many Server are used to exchange these e-mail among the computer to computer and the one network to different network. The mail server is responsible or used to exchange this mail that means a mail server receive or store an e-mail message from client and deliver it to the other client. In this tutorial you will show that how an e-mail message is transfer from sender to receiver and you will also know that what happen during the time of exchanging the mail.

How a Mail Server Works:

Before we begin to configure the Linux Mail Server we need to understand that how an E-Mail system is work. An E-mail system is build-up some element which is described below:

Mail User Agent (MUA)

It works in user machine which is directly run by a user. This is used to compose e-mail message and send it to mail server or receive the mail message from server. It Just an application, such as Outlook, Thunderbird, Pine (used in Linux).

Mail Transfer Agent (MTA)

Mail Transfer Agent is used to transfer message between the machines. After receiving the mail from MUA, Mail Transfer Agent starts its work. In Red Hat Linux the default Mail Transfer Agent is Sendmail or you can also use Postfix to more secure your mail server. In Unix the MTA is qmail. When an email is sent, the message is routed from server to server, all the way to the recipient's email server. After receiving the mail from MUA, MTA read the receiver address from the header part of the mail and find out the receiver server IP address, then MTA try to communicate with the 25 No Port of Server IPs of receiver . If the sender server MTA could establish the connection with receiver server MTA then sender server handover the mail of receiver server MTA using the Simple Mail Transfer Protocol (SMTP).

Mail Delivery Agent (MDA)

MDA/LDA is Mail Delivery Agent or Local Delivery Agent. Both are essentially synonymous. (Actually there are subtle differences between the two).  MDA receive the message from Mail Transfer Agent and lace into the user mailbox. In Red Hat Linux MDA/LDA is procmail.

Simple Mail Transfer Protocol (SMTP)

The SMTP is responsible for transferring the mail message from one MTA to another MTA. That means this is used to transfer mail between the computers in network. It can transfer only ASCII text. It can’t handle font, color, graphics, or attachment with messages. For this you can use MIME (Multi-purpose Internet Mail Extensions or Multimedia Internet Mail Extensions). It’s an encoding protocol like BinHex in Mac and UUEncode in UNIX. That support font, color, graphics, or attachment.  At first it was used as a way of sending more than just text via email. Later the protocol was extended to manage file typing by Web servers. MUAs and MTAs use this protocol for sending e-mails.

Post Office Protocol (POP3)

POP3 stands for a Post Office Protocol version 3. POP3 is a client/server protocol. The POP3 protocol is designed to allow the users to retrieve e-mail messages when they are connected to the email server (via Internet, Ethernet or VPN network connection). Once the email messages are downloaded from the server they can be modified, read and manipulated offline. MUAs can use this protocol to sen and receive e-mails from the server.

Internet Message Access Protocol (IMAP)

The IMAP (Internet Message Access Protocol) is a newer and modern alternative to the POP3 protocol. Unlike POP3, the IMAP allows the users to work with their messages in both online and offline modes. The IMAP-capable email client programs retrieve the messages' headers from the server and can store local copies of the messages in a local (temporary) cache. All the messages are left on the server until they are deleted by the user. This mechanism allows multiple email clients to access a single mailbox and is often used for corporate / business e-mails. MUAs can use this protocol to send and receive e-mails on the server.

Mail-Boxes (Inbox)

A mail-box is container or directory of files, where incoming messages are stored.

Server Configure

In this tutorial you will see that how to configure mail server in a sub domain DNS server named mail.mydomain.com who’s FQDN is ns3.mail.mydomain.com that I have already created. You can also configure the mail server under your main DNS domain that will describe later. So let’s start.

Package required for mail server:  Server Side Packages

Package Name
Description
Sendmail
Default MTA In Red Hat/Fedora Linux
m4
Known as a Macro Processor, used to create sendmail.cf file
Postfix
Another MTA In Linux, used to Exchange secure e-mail
Dovecot
A Package for  Accessing the mailbox
POP3
It’s a Protocol to retrieve the e-mail messages from server
IMAP
It’s an alternative Protocol of POP3
SMTP
Used to transfer e-mail message from one MTA to another MTA
Squirrelmail
A Web Mail Configuration Tool
Php
It’s a scripting language for web development to produce dynamic web pages
Mysql
The most popular Open Source SQL database management system
System-switch-mail
Graphical Tools for Mail Transport Agent Switcher

Client Side Software

Software
Description
Outlook Express
POP3- and IMAP-compatible mail client with a built-in newsreader.
Thunderbird
It’s a graphical email client and newsreader developed by the Mozilla Foundation.
Pine
It’s an application for sending and receiving email in Linux/Unix
Mozilla Firefox, Internet Explorer, Opera, Safari, Or Any Suitable Browser.
Will be used to access mailbox using webmail.

Required configuration file for sendmail:

Sendmail is the default Mail Transfer Agent (MTA) in FreeBSD. sendmail's job is to accept mail from Mail User Agents (MUA) and deliver it to the appropriate mailer as defined by its configuration file. sendmail can also accept network connections and deliver mail to local mailboxes or deliver it to another program.

                sendmail uses the following configuration files:

File Name                                                                                          Function

/etc/mail/access                                                                      sendmail access database file
/etc/mail/aliases                         Mailbox aliases
/etc/mail/local-host-names                Lists of hosts sendmail accepts mail for
/etc/mail/mailer.conf                     Mailer program configuration
/etc/mail/mailertable                     Mailer delivery table
/etc/mail/sendmail.cf                     sendmail master configuration file
/etc/mail/virtusertable                   Virtual users and domain tables

Linux Flavours


Linux Booting Process



1. Bios

2. MBR: Linux or Grub

3. Kernel

4. Init

5. Run Level

BIOS:

The basic Input/output System is the lowest level interface between the computer

and Peripherals

The bios integrity checks on the memory and seeks instruction on the Master

boot record on the floppy drive or hardware

MBR:

The MBR Points to the boot loader (GRUB or Linux Loader)

The Boot loader will then ask for the OS label which will identify, which kernel to

run and where it is located (hardware and partition specified)

The installation process requires to creation, identification of partition and where

to install the OS.

The boot loader then loads the Linux Operating System.

Kernel

The first thing the kernel does is to execute init program, init is the root/parent of

all process executing on Linux

The first process that init starts is a Script /etc/rc.d/rc.sysinit

Based on the appropriate run-level, scripts are executed to start various process

to run the system and make it function.

The kernel is a program that constitutes the central core of a computer operating

system. It has complete control over everything that occurs in the system.

A kernel can be contrasted with a shell (such as bash, csh or ksh in Unix-like

operating systems), which is the outermost part of an operating system and a

program that interacts with user commands. The kernel itself does not interact

directly with the user, but rather interacts with the shell and other programs as

well as with the hardware devices on the system, including the processor (also

called the central processing unit or CPU), memory and disk drives.

Stage 1 and Stage 2

Stage 1 : The primary boot loader, commonly called Stage 1

The primary boot loader must exist in the very small space allocated for the

MBR.which is less than 512 bytes exactly 460 bytes .Therefore only thing the

primary boot loader accomplishes is loading the secondary boot loader ,due to

fact that there is not enough space in MBR.

Stage 2: Loading the secondary boot loader, commonly called stage 2

The secondary boot loader actually brings up the advanced functionality that

allows you to load a specific operating system.

Linux- Server Hardening--

1. File Check:

Check the server behind the IP address above for suspicious files in

#/tmp

Steps:

#cd /usr/local/src

#vi tmpdircheck

find /tmp -type f -name '*[.php,.txt,.pl,.cgi,.dat]' -perm 777 -o -perm 755

#./tmpdircheck

#chmod 0777 /tmp

#/var/tmp

#/dev/shm

#/var/spool/vbox

#/var/spool/squid

#/var/spool/cron

Use "ls -lab" for checking directories as sometimes compromised servers will have hidden files that a

regular "ls" will not show

=========================================================================

2. Killing unwanted Processes:

Check the process tree (ps -efl or ps -auwx) for suspicious processes; (often times the malware / hack

pretends to be an Apache process.)

3.PHP Secure:

register_globals Off

disable_functions = frame,exec,system,passthru,shell_exec,escapeshellarg, scapeshellcmd, proc_close,

proc_open, ini_alter, dl,popen, show_source

4. Password Check:

a. /etc/passwd file

b. Athorized key files

less .ssh/authorized_keys

less .ssh/id_dsa.pub

c./usr/bin/wget (should be 700 and owner and group should be root)

d.last lgoin attempts using 'last' command

e.Cron log

f.Secure log

g.hosts, hosts.allow and hosts.deny

h.Have to run the script find /hsphere/local/home -perm 00777 -exec chmod 755 {} \; (both home and

home2)

i.Find files not owned by a valid user or group.

find / -xdev \( -nouser -o -nogroup \) -print

5. Firewall:

Remove apf and install csf on all the servers (which will be more easier to prevent)

#vi csf.conf

GLOBAL_IGNORE = "64.22.111.82"

CC_DENY = "TR,SY,IL,JO,IQ,IR,GE,VU,LB,AQ,FR,GR,AM,RU,RO,UA,SI,SK,NG,CN,HK"

6.Denial of perl script (.pl) and .pm script upload:

The FTP upload denial (using file extension) can be implemented with the help of Proftp server config

directive "PathDenyFilter"

#vi /hsphere/shared/config/ftpd/proftpd.conf

PathDenyFilter \.pl$|\.py$|\.pm$

:If any of the uploading file extension matches the one specified within this directive, then the file

upload will get denied with the error message as "Forbidded, Illegal File name"

=========================================================================

7.Xen level security:

8.Apache level security:

(a)Find all the httpd group binaries in /bin, /usr/bin, etc and change it to root. Also change all the /usr/

bin/gcc permission to 700

(b)Apache version exposure: (Version 1.3+) Don't allow hackers to learn which version of the web

server software you are running by inducing an error and thus an automated server response. Attacks

are often version specific. Spammers also trigger errors to find email addresses.

ServerSignature Off

Right below that add a line that has the following:

" ServerTokens Prod"

This will identify apache simply as "apache" with no version numbers or OS information

Restart the service

service httpd restart

9. Syctl.conf Hardening:

Check the sysctl file and make sure to have the below settings for IP routing

#vi /etc/sysctl.conf

#Kernel sysctl configuration file for Red Hat Linux

#

# For binary values, 0 is disabled, 1 is enabled. See sysctl(8) and

# sysctl.conf(5) for more details.

# Disables packet forwarding

net.ipv4.ip_forward=0

# Disables IP source routing

net.ipv4.conf.all.accept_source_route = 0

net.ipv4.conf.lo.accept_source_route = 0

net.ipv4.conf.eth0.accept_source_route = 0

net.ipv4.conf.default.accept_source_route = 0

# Enable IP spoofing protection, turn on source route verification

net.ipv4.conf.all.rp_filter = 1

net.ipv4.conf.lo.rp_filter = 1

net.ipv4.conf.eth0.rp_filter = 1

net.ipv4.conf.default.rp_filter = 1

# Disable ICMP Redirect Acceptance

net.ipv4.conf.all.accept_redirects = 0

net.ipv4.conf.lo.accept_redirects = 0

net.ipv4.conf.eth0.accept_redirects = 0

net.ipv4.conf.default.accept_redirects = 0

# Enable Log Spoofed Packets, Source Routed Packets, Redirect Packets

net.ipv4.conf.all.log_martians = 0

net.ipv4.conf.lo.log_martians = 0

net.ipv4.conf.eth0.log_martians = 0

# Disables IP source routing

net.ipv4.conf.all.accept_source_route = 0

net.ipv4.conf.lo.accept_source_route = 0

net.ipv4.conf.eth0.accept_source_route = 0

net.ipv4.conf.default.accept_source_route = 0

# Enable IP spoofing protection, turn on source route verification

net.ipv4.conf.all.rp_filter = 1

net.ipv4.conf.lo.rp_filter = 1

net.ipv4.conf.eth0.rp_filter = 1

net.ipv4.conf.default.rp_filter = 1

# Disable ICMP Redirect Acceptance

net.ipv4.conf.all.accept_redirects = 0

net.ipv4.conf.lo.accept_redirects = 0

net.ipv4.conf.eth0.accept_redirects = 0

net.ipv4.conf.default.accept_redirects = 0

# Disables the magic-sysrq key

kernel.sysrq = 0

# Decrease the time default value for tcp_fin_timeout connection

net.ipv4.tcp_fin_timeout = 15

# Decrease the time default value for tcp_keepalive_time connection

net.ipv4.tcp_keepalive_time = 1800

# Turn off the tcp_window_scaling

net.ipv4.tcp_window_scaling = 0

# Turn off the tcp_sack

net.ipv4.tcp_sack = 0

# Turn off the tcp_timestamps

net.ipv4.tcp_timestamps = 0

# Enable TCP SYN Cookie Protection

net.ipv4.tcp_syncookies = 1

# Enable ignoring broadcasts request

net.ipv4.icmp_echo_ignore_broadcasts = 1

# Enable bad error message Protection

net.ipv4.icmp_ignore_bogus_error_responses = 1

# Log Spoofed Packets, Source Routed Packets, Redirect Packets

net.ipv4.conf.all.log_martians = 1

# Increases the size of the socket queue (effectively, q0).

net.ipv4.tcp_max_syn_backlog = 1024

# Increase the tcp-time-wait buckets pool size

net.ipv4.tcp_max_tw_buckets = 1440000

# Allowed local port range

net.ipv4.ip_local_port_range = 16384 65536

After you make the changes to the file you need to run /sbin/sysctl -p and sysctl -w

net.ipv4.route.flush=1 to enable the changes without a reboot.

10. Syncookies secuirty:

(a)Enable syncookies:

echo 1 > /proc/sys/net/ipv4/tcp_syncookies

(b) /usr file permisisons:

chmod 750 /usr/bin/rcp

chmod 750 /usr/bin/wget

chmod 750 /usr/bin/lynx

chmod 750 /usr/bin/links

chmod 750 /usr/bin/scp

10. Network security:

The first thing you need to do to secure a system from network attacks is find out which processes

are listening for connections and on which ports. There are several time tested tools available for this:

nmap and netstat.

netstat

The following command will show you which ports are being listened on, the IP address of the

listening socket, and which program or PID is associated with the socket (note: running as the superuser or root is necessary for the program field to work properly).

$ netstat -l -n -p -t -u -w

where:

-l is for listening

-n is for IP information

-p is for program/PID information

-t, -u, -w are for tcp, udp and raw socket connections.

Block all the unwanted services.

Tool Installations:

(a). Install RKHunter on all the servers



About Linux



 *  Everything in Linux is a file including the hardware and even the directories.
  * # : Denotes the super(root) user2. # : Denotes the super(root) user2. # : Denotes the super(root) user
  * $ : Denotes the normal user3.  $ : Denotes the normal user3.  $ : Denotes the normal user
  * /root: Denotes the super user’s directory4.  /root: Denotes the super user’s directory4.  /root: Denotes the super user’s directory
* /home: Denotes the normal user’s directory./home: Denotes the normal user’s directory./home: Denotes the normal user’s directory.
 *  Switching between Terminals5.  Switching between Terminals5.  Switching between Terminals
  * Ctrl + Alt + F1-F6: Console login§  Ctrl + Alt + F1-F6: Console login§  Ctrl + Alt + F1-F6: Console login
  * Ctrl + Alt + F7: GUI login§  Ctrl + Alt + F7: GUI login§  Ctrl + Alt + F7: GUI login

LINUX ALL BASIC COMMANDS

Shell command basics
You should already know how shell commands work at a basic level.  To start out, you need to find your Terminal program in which all the above shell can be found , by default most of the Linux distros   bash was the default shell.  The command line you typed is divided up into words. The first word is used as the command name, which is either understood by the shell itself, or used as the name of an external program to run. In either case, the rest of the words are used as arguments to the command.
What is BASH?
BASH = Bourne Again SHell
  1. Bash is a shell written as a free replacement to the standard Bourne Shell (/bin/sh) originally written by Steve Bourne for UNIX systems.
  2. It has all of the features of the original Bourne Shell, plus additions that make it easier to
  3. program with and use from the command line.
  4. Since it is Free Software, it has been adopted as the default shell on most Linux systems.
How is BASH different from the DOS command prompt?
Case Sensitivity In Linux/UNIX, commands and file names are case sensitive, meaning that typing “EXIT” instead of the proper “exit” is a mistake.
“\” vs. “/” -In DOS, the forward-slash “/” is the command argument delimiter,   while the backslash “\” is a directory separator. In Linux/UNIX, the “/” is the directory separator, and the “\” is an escape character._
Filenames The DOS world uses the “eight dot three” file name convention,Meaning that all files followed a format that allowed up to 8 characters in the filename, followed by a period (“dot”), followed by an option extension,up to 3 characters long (e.g. FILENAME.TXT). In UNIX/Linux, there is no such thing as a file extension. Periods can be placed at any part of the filename, and “extensions” may be interpreted differently by all programs, or not at all.
Special Characters
Before we continue to learn about Linux shell commands, it is important to know that there are many symbols and characters that the shell interprets in special ways. This means that certain typed characters: a) cannot be used in certain situations, b) may be used to perform special operations, or, c) must be “escaped” if you want to use them in a normal way.
Escape character. If you want to reference a special character, you must “escape” it with a backslash first.
Example: touch /tmp/filename\*
Directory separator, used to separate a string of directory names.
Example: /usr/src/linux
Current directory. Can also “hide” files when it is the first character in a filename.
.. Parent directory
~ User’s home directory
* Represents 0 or more characters in a filename, or by itself, all files in a directory.
Example: pic*2002 can represent the files pic2002, picJanuary2002,picFeb292002, etc.
? Represents a single character in a filename.
Example: hello?.txt can represent hello1.txt, helloz.txt, but not hello22.txt
[ ] Can be used to represent a range of values, e.g. [0-9], [A-Z], etc.
Example: hello[0-2].txt represents the names hello0.txt, hello1.txt, and hello2.txt
“Pipe”. Redirect the output of one command into another command.
Example: ls | more
Redirect output of a command into a new file. If the file already exists, over-write it.
Example: ls > myfiles.txt
>> Redirect the output of a command onto the end of an existing file.
Example: echo ìMary 555-1234î >> phonenumbers.txt
< Redirect a file as input to a program.
Example: more < phonenumbers.txt
; Command separator. Allows you to execute multiple commands on a single line.
Example: cd /var/log ; less messages
&& Command separator as above, but only runs the second command if the first one
finished without errors.
Example: cd /var/logs && less messages
Execute a command in the background, and immediately get your shell back.
Example: find / -name core > /tmp/corefiles.txt &
Using a Command’s Built-In Help
Many commands have simple “help” screens that can be invoked with special command flags. These flags usually look like “-h” or “–help”.
Example: grep –help
Online Manuals: “Man Pages”
The best source of information for most commands can be found in the online manual pages, known as “man pages” for short. To read a command’s man page, type “man command”.
Examples: man ls                             Get help on the “ls” command.
man man                        A manual about how to use the manual!
Navigating the Linux Filesystem
The Linux filesystem is a tree-like hierarchy hierarchy of directories and files. At the base of the filesystem is the “/” directory, otherwise known as the “root” (not to be confused with the root user). Unlike DOS or Windows filesystems that have multiple “roots”, one for each disk drive, the Linux filesystem mounts all disks somewhere underneath the / filesystem. The following table describes many of the most common Linux directories.
The Linux Directory Layout
Directory Description
The nameless base of the filesystem. All other directories, files, drives, and devices are attached to this root. Commonly (but incorrectly) referred to as the “slash” or “/” directory. The “/” is just a directory separator, not a directory itself.
/bin Essential command binaries (programs) are stored here (bash, ls, mount, tar, etc.)
/boot Static files of the boot loader.
/dev Device files. In Linux, hardware devices are acceessd just like other files, and
they are kept under this directory.
/etc Host-specific system configuration files.
/home Location of users’ personal home directories (e.g. /home/susan).
/lib Essential shared libraries and kernel modules.
/proc Process information pseudo-filesystem. An interface to kernel data structures.
/root The root (superuser) home directory.
/sbin Essential system binaries (fdisk, fsck, init, etc).
/tmp Temporary files. All users have permission to place temporary files here.
/usr The base directory for most shareable, read-only data (programs, libraries,documentation, and much more).
/usr/bin Most user programs are kept here (cc, find, du, etc.).
/usr/include Header files for compiling C programs.
/usr/lib Libraries for most binary programs.
/usr/local “Locally” installed files. This directory only really matters in environments where files are stored on the network. Locally-installed files go in /usr/local/bin, /usr/local/lib,etc.). Also often used for software packages installed from source, or software not officially shipped with the distribution.
/usr/sbin Non-vital system binaries (lpd, useradd, etc.)
/usr/share Architecture-independent data (icons, backgrounds, documentation,  terminfo, man pages, etc.).
/usr/src Program source code. E.g. The Linux Kernel, source RPMs, etc.
/usr/X11R6 The X Window System.
/var Variable data: mail and printer spools, log files, lock files, etc.
Linux System Management
Environment
env Show all environment variables.
export Set the value of a variable so it is visible to all subprocesses that belong to the current shell.
printenv Print all or part of environment.
reset Restores runtime parameters for session to default values.
set Shows how the environment is set up. This is a builtin bash command.
Library management
ldconfig Updates the necessary links for the run time link bindings.
ldd Tells what libraries a given program needs to run.
ltrace A library call tracer.
trace Same as ltrace.
Module and kernel management
depmod Handle loadable modules automatically. Creates a makefile-like dependency file.
dmesg Print or control the kernel ring buffer. This shows the last kernel startup messages.
genksyms Generate symbol version information.
insmod Install loadable kernel module.
lsmod List currently installed kernel modules.
modprobe Used to load a set of modules that are marked with a specified tag.
rmmod Unload loadable modules.
Runtime level management
exit Terminates the shell.
halt Stop the system.
init Process control initialization.
initscript Script that executes inittab commands.
logout Log the user off the system.
poweroff Brings the system down.
reboot Reboot the system.
runlevel List the current and previous runlevel.
setsid Run a program in a new session.
shutdown If your system has many users, use the command “shutdown -h +time message”, where
time is the time in minutes until the system is halted, and message is a short explanation of why the system is shutting down.
# shutdown -h +10 ‘We will install a new disk. System should be back on-line in three hours.’ telinit By requesting run level 1 a system can be taken to single user mode.
System Configuration tools
ctrlaltdel Set the function of the ctrl alt del combination.
isapnp Configure ISA plug and play devices.
kbdconf A Redhat Linux tool which configures the /etc/sysconfig/keyboard file which specifies
the location of the keyboard map file. This is a GUI based tool.
kbdrate Set the keyboard repeat rate and delay time.
kernelcfg A Redhat GUI kernel configuration tool, Start X, then run it from a console session.
linuxconf Redhat’s GUI linux system configuration tool.
lspci List all pci devices.
mesg Control write access to your terminal.
mouseconfig A Redhat Linux tool used to configure the /etc/sysconfig.mouse file. This is a GUI tool.
ndc Script file used to restart, stop, start the DNS server.
Printtool Redhat’s GUI printer configuration tool.
quota Display disk usage and limits.
quotacheck Scan a filesystem for disk usages.
quotaoff Turn file system quotas off.
quotaon Turn file system quotas on.
samba Script file used to stop, start, restart samba services when not run using inetd.
setpci Configure pci devices.
setserial Set/get serial port information.
setterm Set terminal attributes.
setup Set up devices and file systems.
stty Used to configure and print the console devices.
swapon Enable devices and files for paging and swapping.
swapoff Disable devices and files for paging and swapping.
timeconfig A Redhat Linux tool used to configure the /etc/sysconfig/clock file. This is a GUI toolused to set timezone and whether or not the clock is set to GMT time.
tset Used to initialize terminals.
System Information
arch Print machine architecture.
df Shows disk free space.
du Shows disk usage.
free Display used and free memory on the system.
ipcrm Provide information on ipc facilities.
ipcs Same as ipcrm.
lsdev Display information about installed hardware via files in the /proc directory.
lsof List open files.
lspci List PCI devices .
pnpdump Lists ISA plug and play devices resource information.
procinfo Display system status gathered from proc.
pstree Display a tree of processes.
runlevel Find the current and previous system runlevel.
System Logging
klogd Kernel log daemon which intercepts and logs Linux kernel messages.
logger Make entries in the system log.
syslogd Linux system logging utilities.
System Security
System time
cal Calendar.
clock Used to change or get current time. The command “clock -–w” sets the hardware clock.
date Print or set the system date and time.
hwclock Set or read the hardware CMOS clock.
timed Time server daemon to synchronize the host’s time with other machines, normally invoked at boot time from the rc(8) file.
timedc Timed control program.
tzset Used to change the users private time zone by setting the TZ environment variable.
uptime Reports how long the system has been running.
zdump Prints the current time in each zonename named on the command line.
zic Reads text from files named on the command line and creates time conversion files.
X Management and programs
SuperProbe Probe video hardware.
Xconfigurator The Redhat tool used during system setup to configure X.
xconsole Displays messages usually sent to /dev/console.
xf86config Older version of XF86Setup.
XF86Setup A newer X configuration program with a GUI interface which modifies the “/etc/X11/  XF86Config” configuration file.
xvidtune This program will test video modes on the fly without modification to your X  configuration. Read the usr/X11R6/lib/X11/doc/VideoModes.doc file before running this program.
Trace ssytem calls and signals for a binary program.
stty Change and print terminal line settings.
tload Prints a graphic representation of the system load average.
tty Print the filename of the terminal connected to standard input.
uname Print system information, Prints Linux.
vmstat Report virtual memory statistics.
xcpustate Displays CPU states (idle, nice, system, kernel) statistics. Runs in X?
Linux User Management
ac Print statistics about users’ connect time.
accton Turn on accounting of processes. To turn it on type “accton /var/log/pacct”.
adduser Ex: adduser mark – Effect: Adds a user to the system named mark
chage Used to change the time the user’s password will expire.
chfn Change the user full name field finger information
chgrp Changes the group ownership of files.
chown Change the owner of file(s ) to another user.
chpasswd Update password file in batch.
chroot Run command or interactive shell with special root directory.
chsh Change the login shell.
edquota Used to edit user or group quotas. This program uses the vi editor to edit the quota.user and quota.group files. If the environment variable EDITOR is set to emacs, the emacs editor will be used. Type “export EDITOR=emacs” to set that variable.
faillog Examine faillog and set login failure limits.
finger See what users are running on a system.
gpasswd Administer the /etc/group file.
groupadd Create a new group.
grpck Verify the integrity of group files.
grpconv Creates /etc/gshadow from the file /etc/group which converts to shadow passwords.
grpunconv Uses the files /etc/passwd and /etc/shadow to create /etc/passwd, then deletes /etc/
shadow which converts from shadow passwords.
groupdel Delete a group.
groupmod Modify a group.
groups Print the groups a user is in
id Print real and effective user id and group ids.
last Display the last users logged on and how long.
lastb Shows failed login attempts. This command requires the file /var/log/btmp to exist in order to work. Type “touch /var/log/btmp” to begin logging to this file.
lastcomm Display information about previous commands in reverse order. Works only if process accounting is on.
lastlog Formats and prints the contents of the last login.
logname Print user’s login name.
newgrp Lets a suer log in to a new group.
newusers Update and create newusers in batch.
passwd Set a user’s pass word.
pwck Verify integrity of password files.
pwconv Convert to and from shadow passwords and groups.
quota Display users’ limits and current disk usage.
quotaoff Turns system quotas off.
quotaon Turns system quotas on.
quotacheck Used to check a filesystem for usage, and update the quota.user file.
repquota Lists a summary of quota information on filesystems.
sa Generates a summary of information about users’ processes that are stored in the /var/log/pacct file.
smbclient Works similar to an ftp client enabling the user to transfer files to and from a windows based computer.
smbmount Allows a shared directory on a windows machine to be mounted on the Linux machine.
smbpasswd Program to change users passwords for samba.
su Ex: su mark – Effect: changes the user to mark, If not root will need marks password.
sulogin Single user login.
ulimit A bash builtin command for setting the processes a user can run.
useradd Create a new user or update default new user information.
userdel Delete a user account and related files.
usermod Modify a user account.
users Print the user names of users currently logged in.
utmpdump Used for debugging.
vigr Edit the password or group files.
vipw Edit the password or group files.
w Display users logged in and what they are doing.
wall Send a message to everybody’s terminal.
who Display the users logged in.
whoami Print effective user id.
Linux Printing and Programming
Linux Printing
banner Print a large banner on printer.
lpr Print, submits a job to the printer.
Ex: lpr -Pdest filename. Dest is the destination printer. the name of the file to print is  filename.
lpc Lets you check the status of the printer and set its state.
lpq Shows the contents of a spool directory for a given printer.
lprm Removes a job from the printer queue.
gs Ghostscript – A PostScript interpreter.
pr Print a file. Ex: pr filename |pg.
tunelp Set various parameters for the lp device.
Linux Programming
as86 Assembler
awk C programming language – allows finding of lines with specific characters.
bc A precision calculator language.
cproto Reads in c source files and generates function prototypes for all the functions.
ctags Generate tag (index) files for source code.
dialog Display dialog boxes from shell scripts.
egcs GNU project C and C++ compiler.
f2c Converts fortran code to c code.
gawk Pattern scanning and processing language. GNU’s implementation of awk.
gccGNU c and c++ compiler.
cb – C program beautifier
SPARC systems
ctrace – C program debugger
cxref – generate C program cross reference
workshop – SPARCStation development environment
gcc GNU ANSI C Compiler
indent – indent and format C program source
CC – C++ compiler for Suns SPARC systems
g++ GNU C++ Compiler
f77 – Fortran 77 compiler
f90 – Fortran 90 compiler
f95 – Fortran 95 compiler
bc – interactive arithmetic language processor
gcl – GNU Common Lisp
squeak – smalltalk
mathematica – symbolic maths package
matlab – maths package
-g Produce debugging information.
-pg Generate profile info that will allow the gprof program to display timing info.
gdb Debugging program.
gprof In /usr/bin, allows you to tell where most of the execution time is spent in a program.
igawk Gawk with include files.
indent Reformats c source code for consistent indenting and opening and closing bracketsconsistent.
ld The GNU linker.
ld86 Linker for as86.
make GNU make utility to maintain a group of programs.
nm Lists symbols from object files.
objcopy Copy and translate object files.
objdump Display information from object files.
p2c Converts pascal code to c code.
prompt set prompt = “waldo” (in C shell) ps1 = ‘waldo’ (in BOURNE shell)
PS1=”[\u@\h \w]\\$ ” makes prompt = [username@hostname current directory]
see the BASH or your shell’s man page for more information.
size List section sizes and total size.
strip Discard symbols from object files.
xxgdb X windows based graphical user interface to gdb.
Scripting Languages

Perl
 A command interpreter for the Practical Extraction and Report Language (perl).
Python A report language.
Tcl Tool command language shell. Enter by typing tclsh.
info Return information about the state of the Tcl interpreter.
Tk A graphical user extension to Tcl based on X windows. Commands are same as Tcl.
Database Management
Mysql, Oracle and informix are available.
setoracle – set up oracle environment and path on Suns
slplusq – run the Oracle SQL interpreter
sqlldr – run the Oracle SQL data loader
mysql – run the mysql SQL interpreter
Miscellaneous Linux Commands
Keys and keycodes and console
dumpkeys Dump keyboard translation tables.
getkeycodes Print kernel scancode-to-keycode mapping table.
lesskey Specify key bindings for less.
loadkeys Load keyboard translation tables.
psfaddtable Add a unicode character table to a console font.
psfgettable Extract the embedded Unicode character table from a console font.
psfstriptable Remove the embedded Unicode character table from a console font.
resizecons Change kernel idea of the console size.
setkeycodes Load kernel scancode-to-keycode mapping table.
Ncurses functions
captoinfo Convert a termcap description into a terminfo description.
clear Clear the terminal screen.
infocmp Compare or print out terminfo descriptions.
reset Restore run-time parameters for session to default values.
tie Merge or apply WEB change files.
toe Table of terminfo entries.
tput Initialize a terminal or query terminfo database.
tset Terminal initialization.
alias 
Ex:: alias dir=’ls -a’ – Effect: Makes dir list all files (no spaces next
to the = sign).
bison GNU project parser generator.
chvt Change foreground virtual terminal.
crack Program used to find bad passwords or crack security.
cvs Concurrent Versions System.
deallocvt Gets rid of unused virtual terminals.
dumpkeys Dump keyboard translation tables.
fc Fix command. Used to edit the commands in the current history list.
gdbm The GNU database manager.
gpm A cut and paste mouse server.
history Show commands listed in the shell history (last n).
lilo Boot management program.
mc Visual shell for Unix like system. A file manager.
nc A file manager.
pdksh Public domain Korn shell.
pilot Filesystem browser.
PS1=”Please enter a command” Set Bash level 1 response.
PS2=”I need more information” Set Bash level 2 response.
rcs Recision Control system. Change RCS file attributes.
sash Standalone shell with built in commands.
screen Screen manager with VT100 terminal emulation.
sleep Ex: “sleep 2″ – wait 2 seconds.
tcsh C shell with filename completion and command line editing.
unalias Ex: “unalias dir” – Effect: Removes the alias dir.
units Unit conversion program.
variables
l set – Ex: set t=/temp
l unset – Ex: unset t
l echo – Ex: echo $t
zsh The Z shell.
ttysnoop A program that comes with some systems that lets the administrato r to snoop on the user’s terminals.
Rebuild Kernel
Configure Kernel Parameters
make config
make menuconfig
make xconfig
Configuring the kernel with interactive, menu or X window interface.
Compile Kernel Source
make dep
make zImage
make zdisk
make zlilo
make bzImage
Building and installing a new kernel.
Compile Modules
make modules
make modules_install
Building and installing modules.
NFS File Sharing
Files
/etc/fstab file systems mounted during boot.
/etc/exports NFS server export list.
/etc/auto.master auto mount master file.
X Window (XFree86)
startx start X window system.
Xconfigurator (Redhat)
xfree86setup (Slackware)
xf86config setup X server and generate XF86config.
XFree86 -configure
XFreee86 auto configuration (Plug-n-Play), generate a template named “XF86Config.new”
Ctrl+Alt+Del stop  X server (on some system Ctrl+Alt+ESC).
Ctrl+Alt+F1 F1 temporary switch to text mode
Ctrl+Alt+F7 F7 switch back to graphic mode.
SuperProbe detect graphic hardware.
xvidtune adjust X server origin and size.
xmodmap modifying key map and mouse button map.
xhost server access control program for X.
xsetroot root window parameter setting utility for X.
xlsfonts server font list displayer for X.
xset ser preference utility for X.
Linux Document Preparation
addftinfo Add information to troff font files for use with groff.
afmtodit Create font files for use with groff.
colcrt Filter nroff output for CRT previewing.
enscript Convert text files to postscript.
eqn Format equations for troff. Compiles descriptions of equations embedded in troff.
geqn Used to print special symbols and complex equations. Not user friendly.
git GNU interactive tools.
gitaction Per file type action script.
gitkeys Display key sequence utility.
gitmount Allows any block device to be mounted.
gitps A graphical process viewer and killer program.
gitrgrep A recursive grep program.
gitunpack Used to unpack archive files in a given directory.
gitview A hexadecimal or ASC file viewer.
grodvi Convert Groff output to TeX dvi format, normally run by groff.
groff Used as a front end for the groff document formatting system.
grops Postscript driver for groff. invoked by groff.
gtbl Used to prepare charts, multicolumn lists and tabular formats.
hpftodit Create font description files for use with groff.
indxbib Make inverted index for bibliographic databases.
lookbib Search bibliographic databases.
nroff Emulate nroff command with groff.
pfbtops Translate a postscript font in .pbf format to ASCII.
pic Compile pictures for troff or Tex.
psbb Extract bounding box from postscript document.
refer Preprocess bibliographic references for groff.
rpm2html Make an html database from rpm repository.
soelim Interpret .so requests in groff input.
tbl Format tables for groff.
TeX Used to format professionally typeset documents (Chapters, Headings, and paragraphs).
texi2html Texinfo to html converter.
tfmtodit Create font files for use with groff.
troff Formats documents as part of the groff document formatting system.
yacc A parser generator.