find . -type f -mtime +365 -exec rm {} \;Sunday, December 18, 2011
Tuesday, November 29, 2011
java heap space increase in tomcat
edit catalina.sh in tomcat bin folder
add
JAVA_OPTS="-Xms256m -Xmx512m"
Sunday, November 20, 2011
find a string using commandline in linux
grep -r "string" *
find . | xargs grep 'string'
find . -exec grep string {} /dev/null \;
find . | xargs grep 'string'
find . -exec grep string {} /dev/null \;
Tuesday, November 15, 2011
How To Download a RPM Package Using yum Command Without Installing On Linux
would like to only download the packages via yum and not install/update them. How do I download a RPM package using yum command under CentOS Enterprise Linux server 5.x or RHEL 5.x systems?
You need to install plugin called yum-downloadonly. This plugin adds a --downloadonly flag to yum so that yum will only download the packages and not install/update them. Following options supported by this plugin:
[a] --downloadonly : don't update, just download a rpm file
[b] --downloaddir=/path/to/dir : specifies an alternate directory to store packages such as /tmp
Please note following instructions are only tested on CentOS server but should work with RHN and RHEL without any problem.
How do I install yum-downloadonly plugin?
Type the following command to install plugin, enter:# yum install yum-downloadonlySample output:
Loading "fastestmirror" plugin Loading "security" plugin Loading mirror speeds from cached hostfile * base: centos.mirrors.tds.net * updates: mirror.myriadnetwork.com * addons: mirrors.gigenet.com * extras: holmes.umflint.edu Setting up Install Process Parsing package install arguments Resolving Dependencies --> Running transaction check ---> Package yum-downloadonly.noarch 0:1.1.10-9.el5.centos set to be updated --> Finished Dependency Resolution Dependencies Resolved ============================================================================= Package Arch Version Repository Size ============================================================================= Installing: yum-downloadonly noarch 1.1.10-9.el5.centos base 9.0 k Transaction Summary ============================================================================= Install 1 Package(s) Update 0 Package(s) Remove 0 Package(s) Total download size: 9.0 k Is this ok [y/N]: y Downloading Packages: (1/1): yum-downloadonly-1 100% |=========================| 9.0 kB 00:00 Running rpm_check_debug Running Transaction Test Finished Transaction Test Transaction Test Succeeded Running Transaction Installing: yum-downloadonly ######################### [1/1] Installed: yum-downloadonly.noarch 0:1.1.10-9.el5.centos Complete!
How do I download a RPM package only from RHN or CentOS mirror, without installing it?
Download httpd package but don't install/update, enter:# yum update httpd -y --downloadonlyBy default package will by downloaded and stored in /var/cache/yum/ directory. But, you can specifies an alternate directory to store packages such as /opt, enter:
# yum update httpd -y --downloadonly --downloaddir=/optSample output:
yum install httpd -y --downloadonly Loading "downloadonly" plugin Loading "fastestmirror" plugin Loading "security" plugin Loading mirror speeds from cached hostfile * base: centos.mirrors.mypsh.com * updates: mirror.steadfast.net * addons: mirrors.gigenet.com * extras: holmes.umflint.edu Setting up Install Process Parsing package install arguments Resolving Dependencies --> Running transaction check ---> Package httpd.i386 0:2.2.3-11.el5_1.centos.3 set to be updated filelists.xml.gz 100% |=========================| 2.8 MB 00:03 filelists.xml.gz 100% |=========================| 681 kB 00:11 filelists.xml.gz 100% |=========================| 122 kB 00:00 filelists.xml.gz 100% |=========================| 150 B 00:00 --> Finished Dependency Resolution Dependencies Resolved ============================================================================= Package Arch Version Repository Size ============================================================================= Installing: httpd i386 2.2.3-11.el5_1.centos.3 base 1.1 M Transaction Summary ============================================================================= Install 1 Package(s) Update 0 Package(s) Remove 0 Package(s) Total download size: 1.1 M Downloading Packages: (1/1): httpd-2.2.3-11.el5 100% |=========================| 1.1 MB 00:01 exiting because --downloadonly specifiedTo see downloaded file, enter:
# ls -l /opt/*.rpmSample output:
-rw-r--r-- 1 root root 1116426 Jan 17 03:36 /opt/httpd-2.2.3-11.el5_1.centos.3.i386.rpm
-rw-r--r-- 1 root root 83452 Oct 2 2007 /opt/lighttpd-fastcgi-1.4.18-1.el5.rf.i386.rpm
-rw-r--r-- 1 root root 635045 Oct 20 2007 /opt/psad-2.1-1.i386.rpm
Method # 2: yum-utils.noarch Package
yum-utils is a collection of utilities and examples for the yum package manager. It includes utilities by different authors that make yum easier and more powerful to use. These tools include: debuginfo-install, package-cleanup, repoclosure, repodiff, repo-graph, repomanage, repoquery, repo-rss, reposync, repotrack, verifytree, yum-builddep, yum-complete-transaction, yumdownloader, yum-debug-dump and yum-groups-manager.# yum -y install yum-utils.noarchNow use the yumdownloader command which is a program for downloading RPMs from Yum repositories. Type the following command to download httpd rpm file:
# yumdownloader httpdSample outputs:
Loaded plugins: rhnplugin httpd-2.2.3-31.el5_4.2.x86_64.rpm | 1.2 MB 00:00
Howto: Linux server change or setup the timezone
Q. My timezone is pointing to wrong timezone. How do I setup or change the timezone under Linux operating systems?
A. Unix time, or POSIX time, is a system for describing points in time: it is the number of seconds elapsed since midnight UTC on the morning of January 1, 1970, not counting leap seconds.
The definition for time zones can be written in short form as UTC±n (or GMT±n), where n is the offset in hours.
Change Linux timezone
Select the method as per your Linux distribution:If you are using Fedora / RHEL / Cent OS Linux
Type the redhat-config-date command at the command line to start the time and date properties tool.# redhat-config-dateOR type setup and select time zone configuration (good for remote ssh text based Linux server sessiob)
# setupSelect timezone configuration
Now, just follow on screen instructions to change timezone.
Set timezone using /etc/localtime configuration file [any Linux distro]
Often /etc/localtime is a symlink to the file localtime or to the correct time zone file in the system time zone directory.Generic procedure to change timezone
Change directory to /etc# cd /etcCreate a symlink to file localtime:
# ln -sf /usr/share/zoneinfo/EST localtimeOR some distro use /usr/share/zoneinfo/dirname/zonefile format (Red hat and friends)
# ln -sf /usr/share/zoneinfo/EST localtimeOR if you want to set up it to IST (Asia/Calcutta):
# ln -sf /usr/share/zoneinfo/Asia/Calcutta localtimePlease mote that in above example you need to use directory structure i.e. if you want to set the timezone to Calcutta (India) which is located in the Asia directory you will then have to setup using as above.
Use date command to verify that your timezone is changed:
$ dateOutput:
Tue Aug 27 14:46:08 EST 2006
Use of environment variable
You can use TZ environment variable to display date and time according to your timezone:$ export TZ=America/Los_Angeles
$ date
Sample Output:
Thu Aug 27 11:10:08 PST 2006
Linux Set Date and Time From a Command Prompt
How can I set the system date and time from the command prompt (bash shell)? I don't have GUI installed and I am login over ssh session. How can I set date under Linux operating systems?
Use the date command to display the current date and time or set the system date / time over ssh session. You can also run the date command from X terminal as root user.
This is useful if the Linux server time and/or date is wrong, and you need to set it to new values from the shell prompt.
You must login as root user to use date command.
Linux Set Date
Use the following syntax to set new data and time:date --set="STRING"
For example, set new data to 2 Oct 2006 18:00:00, type the following command as root user:
# date -s "2 OCT 2006 18:00:00"OR
# date --set="2 OCT 2006 18:00:00"You can also simplify format using following syntax:
# date +%Y%m%d -s "20081128"Linux Set Time
To set time use the following syntax:# date +%T -s "10:13:13"Where,
- 10: Hour (hh)
- 13: Minute (mm)
- 13: Second (ss)
# date +%T%p -s "6:10:30AM"
# date +%T%p -s "12:10:30PM"Monday, November 14, 2011
Exclude Certain Files When Creating A Tarball Using Tar Command
How can I keep out certain files when creating a tarball? For
/home/me/file1
The GNU version of the tar archiving utility has --exclude and -X options. So to exclude abc and xyz file you need to type the command as follows:
If you have more than 2 files use -X option to specify multiple file names. It reads list of exclude file names from a text file. For example create a file called exclude.txt:
Save and close the file. This lists the file patterns that need to be excluded. Now type the command:
Where,
/home/me/file1
/home/me/dir1 /home/me/dir2 /home/me/abc /home/me/xyzHow do I execute zyz and abc file while using a tar command?
The GNU version of the tar archiving utility has --exclude and -X options. So to exclude abc and xyz file you need to type the command as follows:
$ tar -zcvf /tmp/mybackup.tar.gz --exclude='abc' --exclude='xyz' /home/meIf you have more than 2 files use -X option to specify multiple file names. It reads list of exclude file names from a text file. For example create a file called exclude.txt:
$ vi exclude.txtAppend file names:abc
xyz
*.bak
Save and close the file. This lists the file patterns that need to be excluded. Now type the command:
$ tar -zcvf /tmp/mybackup.tar.gz -X exclude.txt /home/meWhere,
- -X file.txt :exclude files matching patterns listed in FILE file.txt
Thursday, November 3, 2011
Nagios installation
Nagios is the new name for NetSaint, a network/service monitoring tool. It was designed for Linux, but can be compiled and run perfectly well under any UNIX variant as far as I am aware. The monitoring daemon runs intermittent checks on hosts and services you specify.Nagios can send report through sms, email, instant message, etc..
Please follow the steps to install nagios.
Download nagios from source
wget http://prdownloads.sourceforge.net/nagios/nagios-2.9.tar.gz?download
Unpack the sourc file
tar -xzvf nagios-2.9.tar.gz
create user for nagios
Create Installation Directory
useradd nagios
mkdir /usr/local/nagios
Change the owner of the base installtion directory to be the Nagios user and group you added earlier as follows:
chown nagios.nagios /usr/local/nagios
Create a new command file group whose members include the user your web server is running as and the user Nagios is running
as.
as.
groupadd nagcmd
Add the users that your web server and Nagios run as to the newly created group
usermod -G nagcmd nagios
usermod -G nagcmd nobody
Run the configuration script.
./configure –prefix=/usr/local/nagios –with-cgiurl=/nagios/cgi-bin –with-htmurl=/nagios/ –with-nagios-user=nagios –with-nagios-group=nagios –with-command-group=nagcmd
Compile Binaries-
make all
make install
make install-init
Compile Binaries- make
make install
ScriptAlias /nagios/cgi-bin/ /usr/local/nagios/sbin/
<Directory /usr/local/nagios/sbin/>
AllowOverride AuthConfig
Options ExecCGI
Allow from all
Order allow,deny
</Directory>
Alias /nagios/ /usr/local/nagios/share/
<Directory /usr/local/nagios/share>
Options None
AllowOverride AuthConfig
Order allow,deny
Allow from all
</Directory>
Include the file in the Apache configuration file.
Provide a password that will be used when nagiosadmin authenticates to the web server.
htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin
Enable Authentication/Authorization Functionality In The CGIs
Set use_authentication=0 in cgi.cfg file.
authorized_for_system_information=nagiosadmin
authorized_for_configuration_information=nagiosadmin
authorized_for_system_commands=nagiosadmin
authorized_for_all_services=nagiosadmin
authorized_for_all_hosts=nagiosadmin
authorized_for_all_service_commands=nagiosadmin
authorized_for_all_host_commands=nagiosadmin
cd /user/local/nagios/etc
Create directories hosts and services
mkdir hosts.
mkdir services.
Specify the directories in the nagios.cfg file.
cfg_dir=/usr/local/nagios/etc/hosts
cfg_dir=/usr/local/nagios/etc/services
In each of these directories we need to create files for each servers we need to monitor.
Each of these files will contain the hostname and ip of the respective servers.
For this we need to make a copy of the HOSTS block in the localhost.cfg file for each servers.
Similarly we need to make a copy of the SERVICES block of the localhost.cfg for each servers
in the services directory.
We need to specify the emailID where we recieve the alerts in the localhost.cfg file.Each of these files will contain the hostname and ip of the respective servers.
For this we need to make a copy of the HOSTS block in the localhost.cfg file for each servers.
Similarly we need to make a copy of the SERVICES block of the localhost.cfg for each servers
in the services directory.
Also we need to add all the hostname we are monitoring in the HOSTGROUP of the localhost.cfg file.
Once this is done, we need to start nagios.
We can see the logg details of nagios in the /usr/local/nagios/var/nagios. log file.
This completes the configuration of NAGIOS!!!
SAMPLE CONFIGURATION TO ADD A HOST
———————————-
# Generic host definition template – This is NOT a real host, just a template!
define host{
name generic-host ; The name of this host template
notifications_enabled 1 ; Host notifications are enabled
event_handler_enabled 1 ; Host event handler is enabled
flap_detection_enabled 1 ; Flap detection is enabled
failure_prediction_enabled 1 ; Failure prediction is enabled
process_perf_data 1 ; Process performance data
retain_status_information 1 ; Retain status information across program restarts
retain_nonstatus_information 1 ; Retain non-status information across program restarts
notification_period 24×7 ; Send host notifications at any time
register 0 ; DONT REGISTER THIS DEFINITION – ITS NOT A REAL HOST, JUST A TEMPLATE!
}
# Linux host definition template – This is NOT a real host, just a template!
define host{
name swww3.couchsurfing.com ; The name of this host template
use generic-host ; This template inherits other values from the generic-host template
check_period 24×7 ; By default, Linux hosts are checked round the clock
max_check_attempts 10 ; Check each Linux host 10 times (max)
check_command check-host-alive ; Default command to check Linux hosts
notification_period workhours ; Linux admins hate to be woken up, so we only notify during the day
; Note that the notification_period variable is being overridden from ; the value that is inherited from the generic-host template!
notification_interval 120 ; Resend notification every 2 hours
notification_options d,u,r ; Only send notifications for specific host states
contact_groups admins ; Notifications get sent to the admins by default
register 0 ; DONT REGISTER THIS DEFINITION – ITS NOT A REAL HOST, JUST A TEMPLATE!
}
# Since this is a simple configuration file, we only monitor one host – the
# local host (this machine).
define host{
use swww3.couchsurfing.com ; Name of host template to use
; This host definition will inherit all variables that are defined
; in (or inherited by) the linux-server host template definition.
host_name swww3.couchsurfing.com
alias swww3.couchsurfing.com
address 207.210.80.122
}
SAMPLE CONFIGURATION TO ADD SERVICES TO A HOST
———————————————-
# Generic service definition template – This is NOT a real service, just a template!
define service{
name generic-service ; The ‘name’ of this service template
active_checks_enabled 1 ; Active service checks are enabled
passive_checks_enabled 1 ; Passive service checks are enabled/accepted
parallelize_check 1 ; Active service checks should be parallelized (disabling this can lead to major performance problems)
obsess_over_service 1 ; We should obsess over this service (if necessary)
check_freshness 0 ; Default is to NOT check service ‘freshness’
notifications_enabled 1 ; Service notifications are enabled
event_handler_enabled 1 ; Service event handler is enabled
flap_detection_enabled 1 ; Flap detection is enabled
failure_prediction_enabled 1 ; Failure prediction is enabled
process_perf_data 1 ; Process performance data
retain_status_information 1 ; Retain status information across program restarts
retain_nonstatus_information 1 ; Retain non-status information across program restarts
is_volatile 0 ; The service is not volatile
register 0 ; DONT REGISTER THIS DEFINITION – ITS NOT A REAL SERVICE, JUST A TEMPLATE!
}
# Local service definition template – This is NOT a real service, just a template!
define service{
name local-service ; The name of this service template
use generic-service ; Inherit default values from the generic-service definition
check_period 24×7 ; The service can be checked at any time of the day
max_check_attempts 4 ; Re-check the service up to 4 times in order to determine its final (hard) state
normal_check_interval 5 ; Check the service every 5 minutes under normal conditions
retry_check_interval 1 ; Re-check the service every minute until a hard state can be determined
contact_groups admins ; Notifications get sent out to everyone in the ‘admins’ group
notification_options w,u,c,r ; Send notifications about warning, unknown, critical, and recovery events
notification_interval 60 ; Re-notify about service problems every hour
notification_period 24×7 ; Notifications can be sent out at any time
register 0 ; DONT REGISTER THIS DEFINITION – ITS NOT A REAL SERVICE, JUST A TEMPLATE!
}
# Define a service to “ping” the local machine
define service{
use local-service ; Name of service template to use
host_name www4.couchsurfing.com
service_description PING
check_command check_ping!100.0,20%!500.0,60%
}
# Define a service to check the disk space of the root partition
# on the local machine. Warning if < 20% free, critical if
# < 10% free space on partition.
define service{
use local-service ; Name of service template to use
host_name www4.couchsurfing.com
service_description Root Partition
check_command check_local_disk!20%!10%!/
}
# Define a service to check the number of currently logged in
# users on the local machine. Warning if > 20 users, critical
# if > 50 users.
define service{
use local-service ; Name of service template to use
host_name www4.couchsurfing.com
service_description Current Users
check_command check_local_users!20!50
}
# Define a service to check the number of currently running procs
# on the local machine. Warning if > 250 processes, critical if
# > 400 users.
define service{
use local-service ; Name of service template to use
host_name www4.couchsurfing.com
service_description Total Processes
check_command check_local_procs!250!400!RSZDT
}
# Define a service to check the load on the local machine.
define service{
use local-service ; Name of service template to use
host_name www4.couchsurfing.com
service_description Current Load
check_command check_local_load!5.0,4.0,3.0!10.0,6.0,4.0
}
Securing OpenSSH
Contents
- Use Strong Passwords/Usernames
- Disable Root Logins
- Limit User Logins
- Disable Protocol 1
- Use a Non-Standard Port
- Filter SSH at the Firewall
- Use Public/Private Keys for Authentication
- Frequently Asked Question (FAQ)
- Links
OpenSSH (or Secure SHell) has become a de facto standard for remote access replacing the telnet protocol. SSH has made protocols such as telnet redundant due, in most part, to the fact that the connection is encrypted and passwords are no longer sent in plain text for all to see.
However, a default installation of ssh isn't perfect, and when running an ssh server there are a few simple steps that can dramatically harden an installation.
1. Use Strong Passwords/Usernames
One of the first things you'll notice if you have ssh running and exposed to the outside world is that you'll probably log attempts by hackers to guess your username/password. Typically a hacker will scan for port 22 (the default port on which ssh listens) to find machines with ssh running, and then attempt a brute-force attack against it. With strong passwords in place, hopefully any attack will be logged and noticed before it can succeed.
Hopefully you already use strong passwords, but if you are not then try to choose passwords that contains:
- Minimum of 8 characters
- Mix of upper and lower case letters
- Mix of letters and numbers
- Non alphanumeric characters (e.g. special characters such as ! " £ $ % ^ etc)
The benefits of strong passwords aren't specific to ssh, but have an impact on all aspects of systems security. Further information on passwords can be found in the CentOS documentation:
If you absolutely can't prevent your users choosing weak passwords, then consider using randomly generated or difficult to guess usernames for your user accounts. If the bad guys can't guess the username then they can't brute force the password. However, this is still security through obscurity and be aware of information leakage of usernames from things such as email sent from user accounts.
2. Disable Root Logins
SSH server settings are stored in the /etc/ssh/sshd_config file. To disable root logins, make sure you have the following entry:
# Prevent root logins: PermitRootLogin no
and restart the sshd service:
service sshd restart
If you need root access, login as a normal user and use the su command.
3. Limit User Logins
SSH logins can be limited to only certain users who need remote access. If you have many user accounts on the system then it makes sense to limit remote access to only those that really need it thus limiting the impact of a casual user having a weak password. Add an AllowUsers line followed by a space separated list of usernames to /etc/ssh/sshd_config. For example:
AllowUsers alice bob
and restart the sshd service.
4. Disable Protocol 1
SSH has two protocols it may use, protocol 1 and protocol 2. The older protocol 1 is less secure and should be disabled unless you know that you specifically require it. Look for the following line in the /etc/ssh/sshd_config file, uncomment it and amend as shown:
# Protocol 2,1 Protocol 2
and restart the sshd service.
5. Use a Non-Standard Port
By default, ssh listens for incoming connections on port 22. For a hacker to determine ssh is running on your machine, he'll most likely scan port 22 to determine this. An effective method is to run ssh on a non-standard port. Any unused port will do, although one above 1024 is preferable. Many people choose 2222 as an alternative port (as it's easy to remember), just as 8080 is often known as the alternative HTTP port. For this very reason, it's probably not the best choice, as any hacker scanning port 22 will likely also be scanning port 2222 just for good measure. It's better to pick some random high port that's not used for any known services. To make the change, add a line like this to your /etc/ssh/sshd_config file:
# Run ssh on a non-standard port: Port 2345 #Change me
and restart the sshd service. Don't forget to then make any necessary changes to port forwarding in your router and any applicable firewall rules.
Because ssh is no longer listening for connections on the standard port, you will need to tell your client what port to connect on. Using the ssh client from the command line, we may specify the port using the -p switch:
$ ssh -p 2345 myserver
or if you are using the fish protocol in konqueror, for example:
fish://myserver:2345/remote/dir
If you are thinking that this sounds like a pain having to specify the port each time you connect, simply add an entry specifying the port in your local ~/.ssh/config file:
# Client ~/.ssh/config
Host myserver
HostName 72.232.194.162
User bob
Port 2345
~/.ssh/config must have the following permissions:
$ chmod 600 ~/.ssh/config
6. Filter SSH at the Firewall
If you only need remote access from one IP address (say from work to your home server), then consider filtering connections at your firewall by either adding a firewall rule on your router or in iptables to limit access on port 22 to only that specific IP address. For example, in iptables this could be achieved with the following type of rule:
iptables -A INPUT -p tcp -s 72.232.194.162 --dport 22 -j ACCEPT
SSH also natively supports TCP wrappers and access to the ssh service may be similarly controlled using hosts.allow and hosts.deny.
If you are unable to limit source IP addresses, and must open the ssh port globally, then iptables can still help prevent brute-force attacks by logging and blocking repeated attempts to login from the same IP address. For example,
iptables -A INPUT -p tcp --dport 22 -m recent --set --name ssh --rsource iptables -A INPUT -p tcp --dport 22 -m recent ! --rcheck --seconds 60 --hitcount 4 --name ssh --rsource -j ACCEPT
The first rule records the IP address of each attempt to access port 22 using the recent module. The second rule checks to see if that IP address has attempted to connect 4 or more times within the last 60 seconds, and if not then the packet is accepted. Note this rule would require a default policy of DROP on the input chain.
Here's another example, this time using iptables limit module to limit the the number of connections to the ssh port to 3 per minute:
iptables -A INPUT -p tcp --dport 22 --syn -m limit --limit 1/m --limit-burst 3 -j ACCEPT iptables -A INPUT -p tcp --dport 22 --syn -j DROP
The first line will accept new connections on port 22 provided that IP address hasn't made more than 3 connection attempts in the last minute. If more than 3 connection attempts have been made within the last minute, then the second line will DROP the connection.
Don't forget to change the port as appropriate if you are running ssh on a non-standard port. Where possible, filtering at the firewall is an extremely effective method of securing access to an ssh server.
7. Use Public/Private Keys for Authentication
Using encrypted keys for authentication offers two main benefits. Firstly, it is convenient as you no longer need to enter a password (unless you encrypt your keys with password protection) if you use public/private keys. Secondly, once public/private key pair authentication has been set up on the server, you can disable password authentication completely meaning that without an authorized key you can't gain access - so no more password cracking attempts.
It's a relatively simple process to create a public/private key pair and install them for use on your ssh server.
First, create a public/private key pair on the client that you will use to connect to the server (you will need to do this from each client machine from which you connect):
$ ssh-keygen -t rsa
This will create two files in your (hidden) ~/.ssh directory called id_rsa and id_rsa.pub. id_rsa is your private key and id_rsa.pub is your public key.
If you don't want to still be asked for a password each time you connect, just press enter when asked for a password when creating the key pair. It is up to you to decide whether or not you should password encrypt your key when you create it. If you don't password encrypt your key, then anyone gaining access to your local machine will automatically have ssh access to the remote server. Also, root on the local machine has access to your keys although one assumes that if you can't trust root (or root is compromised) then you're in real trouble. Encrypting the key adds additional security at the expense of eliminating the need for entering a password for the ssh server only to be replaced with entering a password for the use of the key.
Now set permissions on your private key:
$ chmod 700 ~/.ssh $ chmod 600 ~/.ssh/id_rsa
Copy the public key (id_rsa.pub) to the server and install it to the authorized_keys list:
$ cat id_rsa.pub >> ~/.ssh/authorized_keys
Note: once you've imported the public key, you can delete it from the server.
and finally set file permissions on the server:
$ chmod 700 ~/.ssh $ chmod 600 ~/.ssh/authorized_keys
The above permissions are required if StrictModes is set to yes in /etc/ssh/sshd_config (the default).
Now when you login to the server you won't be prompted for a password (unless you entered a password when you created your key pair). By default, ssh will first try to authenticate using keys. If no keys are found or authentication fails, then ssh will fall back to conventional password authentication.
Once you've checked you can successfully login to the server using your public/private key pair, you can disable password authentication completely by adding the following setting to your /etc/ssh/sshd_config file:
# Disable password authentication forcing use of keys PasswordAuthentication no
8. Frequently Asked Question (FAQ)
Q: CentOS uses version X of OpenSSH and the latest version is version Y. Version X contained a serious security flaw, should I upgrade?
A: No. The Upstream Vendor has a policy of backporting security patches from the latest releases into the current distribution version. As long as you have the latest updates applied for your CentOS distribution you are fully patched. See here for further details of backporting security patches:
9. Links
Detect and Clean a hacked server T0rnkit Tutorial
Tornkit is a rootkit, a set of programs that is used by an intruder to have unrestricted access to a compromised Linux system. Tornkit is also attempts to hide its presence.
T0rn Rootkit Tornkit is a rootkit, a set of programs that is used by an intruder to have unrestricted access to a compromised Linux system. Tornkit is also attempts to hide its presence.
The t0rn rootkit is designed for speed. By that I mean that it was designed to install quickly on Linux machines. T0rn can do this because it takes very little skill to install and run. All of the binaries that the attacker would need come pre-compiled and the installation process is as simple as ./t0rn. T0rn comes standard with a log cleaner called t0rnsb, a sniffer named t0rns and a log parser called t0rnp.
I am including this so that you all diag and clean up your hacked server.
First of all,
Login to WHM as root
Click Tweak Settings
and please remove the tick from
Allow cPanel users to reset their password via email
Step 1. run chkrootkit, and you will see some INFECTED lines. It will also report that some process are hidden from the ps
chkrootkit
Checking `ifconfig'... INFECTED
Checking `login'... INFECTED
Checking `pstree'... INFECTED
and also:
Checking `lkm'... You have X process hidden for ps command
Warning: Possible LKM Trojan installed
Step 2. /etc/init.d/syslog restart
Shutting down kernel logger: [ OK ]
Shutting down system logger: [ OK ]
Starting system logger: [FAILED]
Starting kernel logger: [ OK ]
Step 3. top
top: error while loading shared libraries: libncurses.so.4: cannot open shared object file: No such file or directory
Step 4. tail /etc/rc.d/rc.sysinit
# Xntps (NTPv3 daemon) startup..
/usr/sbin/xntps -q
--------------------------------------------------------
OK.. looks like someone got to your server as well. Since we know what rootkit it is, let us investigate further.
Configuration files
<please use cat /path/filename/ to read what the files contain>
/usr/include/file.h (for file hiding)
/usr/include/proc.h (for ps proc hiding)
/lib/lidps1.so (for pstree hiding)
/usr/include/hosts.h (for netstat and net-hiding)
/usr/include/log.h (for log hiding)
/lib/lblip.tk/ (backdoored ssh configuration files are in this directory)
/dev/sdr0 (systems md5 checksum)
/lib/ldd.so {placing tks(sniffer), tkp(parser) and tksb(log cleaner)}
Infected Binaries:
top, ps, pstree lsof, md5sum, dir, login, encrypt,ifconfig,find,ls,slocate,
tks,tksb,top,tkpnetstat,pg,syslogd,sz
Infected Librairies:
libproc.a,libproc.so.2.0.6,libproc.so
BackDoor: (located at /lib/lblip.tk)
shdc
shhk.pub
shk
shrs
--------------------------------------------------------
Now, Lets start the cleaning process:
Step 1.pico /etc/rc.d/rc.sysinit
remove the lines that show
# Xntps (NTPv3 daemon) startup..
/usr/sbin/xntps -q
Step 2. reboot the system
WARNING: 2 servers got their kernel removed after reboot.
If your's is the case and that is what the DataCenter complains after reboot, please ask them to do the following:
reboot the system using the redhat CD into rescue mode
chroot to the /mnt/sysimage
reinstall kernel packages
that should fix it.
-- since already in resuce mode, perhaps also ask them to --force install the following rpm's
procps*.rpm
psmisc*.rpm
findutils*.rpm
fileutils*.rpm
util-linux*.rpm
net-tools*.rpm
textutils*.rpm
sysklogd*.rpm
Step 3. After the system is up
cd /lib
rm -rf lblip.tk
Step 4. remove the configuration files given above.
Step 5. cat /etc/redhat-release
note down your version of redhat, then from
www.rpmfind.net
search for the following rpm's
procps*.rpm
psmisc*.rpm
findutils*.rpm
fileutils*.rpm
util-linux*.rpm
net-tools*.rpm
textutils*.rpm
sysklogd*.rpm
-- and rpm --force install them
Step 6. if you see the hosts.h file, it says to hide all IP's from
cat /usr/include/hosts.h
193.60
thus, if you want, you can block all the IP's from 193.60 to your server via iptables.
Step 7. If all goes OK,
please reboot the server, and run chkrootkit again...
You should be OK!
How to install mod_security for Apache
This guide will show you how to install and configure mod_security, the intrusion detection and prevention engine for Apache web server with modsecurity.
What is mod_security or modsecurity?
ModSecurity is an open source intrusion detection and prevention engine for web applications. It operates embedded into the web server, acting as a powerful umbrella - shielding applications from attacks. ModSecurity supports both branches of the Apache web server.
Rfx Networks Recommended:
"mod_security is great and I encourage it be used by everyone; it does have the potential to break some web applications but so far iv seen very few issues to say the least. Likewise it is easy to fix any applications that may break with the granular filter rules that can be setup to either deny or allow certain content. Overall mod_security is a needed addition to apache, providing a layer of security yet unseen for apache. I highly encourage you read the reference document on the modsecurity.org site (under documentation) to better understand each directive and the role it plays in protecting your server and sites."
Requirements:Apache Web Server 1.3x or 2.x
Note: We have confirmed this security addon works with Cpanel based servers.
UPDATE: Sept. 15, 2004:
Changed # Prevent path traversal (..) attacks rules to fix a typo in tutorial.
How to install?
1. Login to your server through SSH and su to the root user.
2. First your going to start out by grabbing the latest version of mod_security
wget http://www.modsecurity.org/download/mod_security-1.7.4.tar.gz
3. Next we untar the archive and cd into the directory:
tar zxvf mod_security-1.7.4.tar.gz
cd mod_security-1.7.4/
4. Now you need to determine which version of apache you use:
APACHE 1.3.x users
cd apache1/ APACHE 2.x users
cd apache2/
5. Lets Compile the module now:
/usr/local/apache/bin/apxs -cia mod_security.c
6. Ok, now its time to edit the httpd conf file. First we will make a backup just incase something goes wrong:
cp /usr/local/apache/conf/httpd.conf /usr/local/apache/conf/httpd.conf.backup
7. Now that we have backed it all up, we can edit the httpd.conf. Replace pico with nano depending on what you have
pico /usr/local/apache/conf/httpd.conf
8. Lets look for something in the config, do this by holding control and pressing W and you are going to search for
<IfModule mod_dir.c> (altho any of the IfModules would work fine)
9. Now add this
<IfModule mod_security.c>
# Turn the filtering engine On or Off
SecFilterEngine On
# Change Server: string
SecServerSignature " "
# Make sure that URL encoding is valid
SecFilterCheckURLEncoding On
# This setting should be set to On only if the Web site is
# using the Unicode encoding. Otherwise it may interfere with
# the normal Web site operation.
SecFilterCheckUnicodeEncoding Off
# Only allow bytes from this range
SecFilterForceByteRange 1 255
# The audit engine works independently and
# can be turned On of Off on the per-server or
# on the per-directory basis. "On" will log everything,
# "DynamicOrRelevant" will log dynamic requests or violations,
# and "RelevantOnly" will only log policy violations
SecAuditEngine RelevantOnly
# The name of the audit log file
SecAuditLog /var/log/httpd/audit_log
# Should mod_security inspect POST payloads
SecFilterScanPOST On
# Action to take by default
SecFilterDefaultAction "deny,log,status:500"
# Require HTTP_USER_AGENT and HTTP_HOST in all requests
SecFilterSelective "HTTP_USER_AGENT|HTTP_HOST" "^$"
# Prevent path traversal (..) attacks
SecFilter "\.\./"
# Weaker XSS protection but allows common HTML tags
SecFilter "<[[:space:]]*script"
# Prevent XSS atacks (HTML/Javascript injection)
SecFilter "<(.|n)+>"
# Very crude filters to prevent SQL injection attacks
SecFilter "delete[[:space:]]+from"
SecFilter "insert[[:space:]]+into"
SecFilter "select.+from"
# Protecting from XSS attacks through the PHP session cookie
SecFilterSelective ARG_PHPSESSID "!^[0-9a-z]*$"
SecFilterSelective COOKIE_PHPSESSID "!^[0-9a-z]*$"
</IfModule>
10. Save the file Ctrl + X then Y
11. Restart Apache
/etc/rc.d/init.d/httpd stop
/etc/rc.d/init.d/httpd start
You've successfully installed mod_security
ModSecurity is an open source intrusion detection and prevention engine for web applications. It operates embedded into the web server, acting as a powerful umbrella - shielding applications from attacks. ModSecurity supports both branches of the Apache web server.
Rfx Networks Recommended:
"mod_security is great and I encourage it be used by everyone; it does have the potential to break some web applications but so far iv seen very few issues to say the least. Likewise it is easy to fix any applications that may break with the granular filter rules that can be setup to either deny or allow certain content. Overall mod_security is a needed addition to apache, providing a layer of security yet unseen for apache. I highly encourage you read the reference document on the modsecurity.org site (under documentation) to better understand each directive and the role it plays in protecting your server and sites."
Requirements:Apache Web Server 1.3x or 2.x
Note: We have confirmed this security addon works with Cpanel based servers.
UPDATE: Sept. 15, 2004:
Changed # Prevent path traversal (..) attacks rules to fix a typo in tutorial.
How to install?
1. Login to your server through SSH and su to the root user.
2. First your going to start out by grabbing the latest version of mod_security
wget http://www.modsecurity.org/download/mod_security-1.7.4.tar.gz
3. Next we untar the archive and cd into the directory:
tar zxvf mod_security-1.7.4.tar.gz
cd mod_security-1.7.4/
4. Now you need to determine which version of apache you use:
APACHE 1.3.x users
cd apache1/ APACHE 2.x users
cd apache2/
5. Lets Compile the module now:
/usr/local/apache/bin/apxs -cia mod_security.c
6. Ok, now its time to edit the httpd conf file. First we will make a backup just incase something goes wrong:
cp /usr/local/apache/conf/httpd.conf /usr/local/apache/conf/httpd.conf.backup
7. Now that we have backed it all up, we can edit the httpd.conf. Replace pico with nano depending on what you have
pico /usr/local/apache/conf/httpd.conf
8. Lets look for something in the config, do this by holding control and pressing W and you are going to search for
<IfModule mod_dir.c> (altho any of the IfModules would work fine)
9. Now add this
<IfModule mod_security.c>
# Turn the filtering engine On or Off
SecFilterEngine On
# Change Server: string
SecServerSignature " "
# Make sure that URL encoding is valid
SecFilterCheckURLEncoding On
# This setting should be set to On only if the Web site is
# using the Unicode encoding. Otherwise it may interfere with
# the normal Web site operation.
SecFilterCheckUnicodeEncoding Off
# Only allow bytes from this range
SecFilterForceByteRange 1 255
# The audit engine works independently and
# can be turned On of Off on the per-server or
# on the per-directory basis. "On" will log everything,
# "DynamicOrRelevant" will log dynamic requests or violations,
# and "RelevantOnly" will only log policy violations
SecAuditEngine RelevantOnly
# The name of the audit log file
SecAuditLog /var/log/httpd/audit_log
# Should mod_security inspect POST payloads
SecFilterScanPOST On
# Action to take by default
SecFilterDefaultAction "deny,log,status:500"
# Require HTTP_USER_AGENT and HTTP_HOST in all requests
SecFilterSelective "HTTP_USER_AGENT|HTTP_HOST" "^$"
# Prevent path traversal (..) attacks
SecFilter "\.\./"
# Weaker XSS protection but allows common HTML tags
SecFilter "<[[:space:]]*script"
# Prevent XSS atacks (HTML/Javascript injection)
SecFilter "<(.|n)+>"
# Very crude filters to prevent SQL injection attacks
SecFilter "delete[[:space:]]+from"
SecFilter "insert[[:space:]]+into"
SecFilter "select.+from"
# Protecting from XSS attacks through the PHP session cookie
SecFilterSelective ARG_PHPSESSID "!^[0-9a-z]*$"
SecFilterSelective COOKIE_PHPSESSID "!^[0-9a-z]*$"
</IfModule>
10. Save the file Ctrl + X then Y
11. Restart Apache
/etc/rc.d/init.d/httpd stop
/etc/rc.d/init.d/httpd start
You've successfully installed mod_security
Rkhunter Installation
Rkhunter is a very useful tool that is used to check for trojans, rootkits, and other security problems.
Rkhunter is a very useful tool that is used to check for trojans, rootkits, and other security problems. This tutorial will touch on installing and setting up a daily report for rkhunter.
Update Aug. 23, 2005
Update Aug. 23, 2005
Installing:
wget http://downloads.rootkit.nl/rkhunter-1.2.7.tar.gztar -zxvf rkhunter-1.2.7.tar.gzcd rkhunter-1.2.7
./installer.sh
Now you can run a test scan with the following command:
/usr/local/bin/rkhunter -c
How to setup a daily scan report?
vi /etc/cron.daily/rkhunter.shadd the following replacing your email address:
#!/bin/bash
(/usr/local/bin/rkhunter -c --cronjob 2>&1 | mail -s "Daily Rkhunter Scan Report" email@domain.com)
chmod +x /etc/cron.daily/rkhunter.sh
Updating rkhunter
gets the latest database updates from their central server and matches your OS better to prevent false positives.
rkhunter --update
I just got a false positive!! What do i do?
False positives are warnings which indicates there is a problem, but aren't really a problem. Example: some Linux distro updated a few common used binaries like `ls` and `ps`. You (as a good sysadmin) update the new packages and run (ofcourse) daily Rootkit Hunter. Rootkit Hunter isn't yet aware of these new files and while scanning it resports some "bad" files. In this case we have a false positive. You could always have your datacenter or a system administrator check out the server to verify that it is not compromised.More information on rkhunter can be found here: http://www.rootkit.nl
Creating a Welcome message for SSH logins
Did you ever want to change or create a new login message anyime someone logs into SSH? We'll show you how it's done.
Did you ever want to change or create a new login message antime someone logs into SSH? We'll show you how it's done.First off login to our server as root. Then type in the following:
vi /etc/motd
Now type in the security login message you wish all users to see once they login to your server through SSH.
Try something like this as a start:
This computer system is for authorized users only. All activity is logged and regulary checked by systems personal. Individuals using this system without authority or in excess of their authority are subject to having all their services revoked. Any illegal services run by user or attempts to take down this server or its services will be reported to local law enforcement, and said user will be punished to the full extent of the law. Anyone using this system consents to these terms.
Save and Exit
Logout of SSH then log back in, you will receive your new greeting!
E-mail Alert on Root SSH Login
Want to be notified instantly when someone logs into your server as root? No problem, check out this nice tutorial on email notification for root logins.
Want to be notified instantly when someone logs into your server as root? No problem, check out this nice tutorial on email notification for root logins. Keeping track of who logs into your server and when is very important, especially when you're dealing with the super user account. We recommend that you use an email address not hosted on the server your sending the alert from.So lets get started!
1. Login to your server and su to root, or any user
2. cd ~/
3. vi .bashrc
4. Scroll to the end of the file then add the following:
echo 'ALERT - Root Shell Access (YourserverName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d"(" -f2 | cut -d")" -f1`" you@yourdomain.com
Replace YourServerName with the handle for your actual server
Replace you@yourdomain.com with your actual email address
5. save and exit
Now logout of SSH, close the connection and log back in! You should receive an email address of the root login alert a few minutes afterwards.
Note: This is a great tool for servers that have multiple admins or if you give someone SSH access for whatever reason, although you should give out the root password to as few people as humanly possible and be sure to change it often.
This will not magically alert you when a hacker runs the latest kernel exploit on your server and logs into SSH because they will create their own SSH/telnet connection. You should keep your system up to date, install a firewall and follow the latest security releases.
Subscribe to:
Posts (Atom)