Showing posts with label ServerSecurity. Show all posts
Showing posts with label ServerSecurity. Show all posts

Sunday, 3 August 2014

Creating a Super user with root Privileges


Sudo is a program which can be used by normal users to execute programs as super user or any other user. Sudo access is controlled by /etc/sudoers. The users listed in /etc/sudoers file can execute commands with an effective user id of 0 and a group id of root's group.

The file '/etc/sudoers' should be edited with the editor "visudo".

 First, create a user called "ctechz"
 

# useradd ctechz
# passwd
ctechz

 To give a specific group of users limited root privileges, edit the file with visudo as follows:


 # visudo

03. Go down to the line ‘# User privilege specification‘and add the following line.


ctechz ALL=(ALL) ALL

ctechz : name of user to be allowed to use sudo
ALL : Allow sudo access from any terminal ( any machine ).
(ALL) : Allow sudo command to be executed as any user.
ALL : Allow all commands to be executed.


OR

Create a user with uid 0

# useradd -u 0 -o jeff

 -u, --uid UID force use the UID for the new user account
 -o, --non-unique allow create user with duplicate
 


OR

Create a Normal user and edit its uid in /etc/passwd file and make it as ZERO

Monday, 9 December 2013

DoS Attack Detection In Linux


You can simply use netstat command to print out a list of all open connection to your Linux box. The list will be sorted out using sort command including total number of connections from a specific IP address.

Login as the root user and type the following command,

# netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n


Tuesday, 27 August 2013

How to Examining Local Network Activities in a system

Problem: Want to examine network use occurring on your local machine.

Solution: To print a summary of network use,

# netstat --inet             connected sockets
# netstat --inet --listening  Server sockets
# netstat --inet --all        Both
 
To assign dynamically assigned ports for RPC processes,

# rpcinfo -p [host]

To list network connections for all processes:

# lsof -i[tcp][udp][@host][:port]

To list all open files for specific processes:

# lsof -p pid
# lsof -c command
# lsof -u username

To list all open files for all processes

# lsof

You can also select processes by ID (-p), command name (-c), or username (-u)
# lsof -a -c myprog -u tony

Note: Programs like ps, netstat, and lsof obtain information from the linux kernel via the /proc filesystem.
      
The most important files for networking are /proc/net/tcp and /proc/net/udp, both consulted by netstat. Kernel parameters related to networking can be found in the /proc/sys/net directory.

Information for individual processes is located in /proc/<pid> directories, where <pid> is the process id, for example, the file
 /proc/12345/cmdline contains the orginal command line that invoked the (current running) process 12345.

Friday, 23 August 2013

How to check for Suspecious Account Use


Problem: Want to find out unusual or dangerous usage of accounts on your system: dormant user accounts, recent logins to system accounts etc. 


Solutions:
 
1. To print information about the last login for each uesr:
    # lastlog -u username

# lastlog -u root
Username   Port     From             Latest
root          pts/2    192.168.1.3  Wed Aug 14 21:43:11 -0700 2013

# lastlog -u ctechz
Username         Port     From             Latest
ctechz                                     **Never logged in**

2. To print entire login history:
    # last username

[root@localhost ~]# last ctechz
ctechz   pts/3      192.168.0.30   Thu Jun 27 05:32 - 05:32  (00:00)   
ctechz   pts/3      192.168.0.30   Thu Jun 27 05:31 - 05:31  (00:00)   
ctechz   pts/2      192.168.0.30   Tue Jun 25 04:38 - 04:39  (00:01)   
ctechz   pts/2      192.168.0.30   Tue Jun 25 04:18 - down   (00:04)
 
3. To print failed login attempts:
    # lastb username

# lastb ctechz
ctechz  ssh:notty  192.168.0.30  Tue Jun 25 04:38 - 04:38 (00:00)   
ctechz  ssh:notty  192.168.0.30  Tue Jun 25 04:18 - 04:18 (00:00)   
ctechz  ssh:notty  192.168.0.30  Mon Jun 24 22:42 - 22:42 (00:00)    
  

To enable recording of bad logins:
  # touch /var/log/btmp
 # chown --reference=/var/log/wtmp /var/log/btmp
 # chmod --reference=/var/log/wtmp /var/log/btmp


Note:-
Attackers look for inactive accounts that are still enables, in the hope that intrusions will escape detection for long periods of time.

  Linux systems record each user's last login time in the database /var/log/lastlog. The terminal and remote system name, if any are also noted.

The /var/log/lastlog is a database not a log file.

In contrast, the btmp log file will grow slowly (unless you are under attack) but it should be rotated like other log file.
 You can either add btmp to the wtmp entry in /etc/logrotate.conf or add a similar entry in a separate file in the /etc/logrotate.d dir

A history of all logins and logouts is recorded in the log file /var/log/wtmp. The "last" command scans this log file to produce a report of all login sessions,in reverse chronological order, sorted by login time.

Failed login attempts can also be recorded in the log file /var/log/btmp, but this is not done by default. To enable recording of bad logins, create the btmp file manually, using the same owner, group, and permissions as for the wtmp file. The "lastb" command prints the history of bad logins.

In Linux/Unix operating systems everything is logged some where.
Most of the system logs are logged in to /var/log folder. This folder contains logs related to different services and applications.
In this folder we have some files such as utmp, wtmp and btmp.
These files contains all the details about login’s and logout’s which are from local as well as from remote systems and system status such as uptime etc.

utmp will give you complete picture of users logins at which terminals, logouts, system events and current status of the system, system boot time etc.


wtmp gives historical data of utmp.
btmp records only failed login attempts.

Normally when we try to view these files using cat command or vi editor they used to throw some junk characters and garbage values or in encrypted form or hex values. The output of these files when open with vi or cat command are shown below to show how wtmp file look when opened with vi.

We can read this file with only last command.


"last" command is one of the important command which will give you how logged in, when they logged in and when they logged out etc info on the screen.

# last
This last command display many details about user login/logout activity. The same command can be used to view wtmp, utmp and btmp files.

To open wtmp file and view its content use below command
 

# last -f /var/log/wtmp

jeffin   pts/2    192.168.0.30  Tue Jun 25 01:59 - down   (00:23)   
root     pts/1        :0.0           Tue Jun 25 01:59 - down   (00:24)   
root     :0                             Tue Jun 25 01:59 - down   (00:24)   
root     :0                             Tue Jun 25 01:59 - 01:59  (00:00)   
reboot   system boot  2.6.18-194.el5   Tue Jun 25 01:57 (00:26)   
jeffin   pts/2    192.168.0.30  Tue Jun 25 01:43 - down   (00:11)   
jeffin   pts/2    192.168.0.30  Tue Jun 25 01:41 - 01:43  (00:01)   
ctechz  pts/3   192.168.0.30  Mon Jun 24 23:38 - 23:38  (00:00)   
ctechz  pts/3   192.168.0.30  Mon Jun 24 23:31 - 23:31  (00:00) 

To see still logged in users view utmp file use last command
# last -f /var/run/utmp

To view btmp file use same command
# last -f /var/log/btmp
                                                         gone - no logout
root     ssh:notty  192.168.0.30 Tue Jun 25 03:49 - 04:18 (00:28)   
root     ssh:notty  192.168.0.30 Tue Jun 25 03:37 - 03:49 (00:12)   
cteechz  ssh:notty 192.168.0.30 Mon Jun 24 23:37-03:37 (04:00)   
cteechz  ssh:notty 192.168.0.30 Mon Jun 24 23:37 - 23:37 (00:00)


How to install chkrootkit on centos

Checking for Rootkits in a system
 

chkrootkit is a collection of tools to detect the presence of rootkits.  chkrootkit uses C and shell scripts to perform a detailed process check, and scans systems binaries to detect kit signatures. Upon detection, in most cases, it can remove rootkits too.
 

The following lists the chkrootkit internal programs and what each of them do.


chkrootkit-Program         Purpose

chkrootkit          Main script to check for tampered

                     system files

strings.c           Detects and performs string replacement

ifpromisc.c         Checks network interface 

                     for promiscuous mode

chklastlog.c,
chkwtmp.c  Checks if lastlog and wtmp
                           entries are deleted

chkproc.c,chkdirs.c  Checks for Linux kernel 
                         module-based Trojans

# md5sum chkrootkit.tat.gz

# tar -xvjf chkrootkit.tat.gz

# cd chkrootkit-*
# make sense
# ./chkrootkit

# ./chkrootkit -p /mnt/cdroam OR

# ./chkrootkit

chkrootkit tessts for the presence of certain rootkits,worms and trojans on your system. if you have been hacked it is a good first step to diagnosis.

Crond run chkrootkit hourly shoot in the mail administrator is ctechz@ctechz.com
 

# vi /etc/cron.hourly/chkrootkit.sh

#!/bin/bash
chkrootkit | mail -s “Hour chkrootkit from Servername” ctechz@ctechz.com

# chmod +x /etc/cron.hourly/chkrootkit.sh

How to install Rkhunter (Rootkit Hunter) in centos

Rkhunter (Rootkit Hunter)  that scans backdoors, rootkits and local exploits on your systems. It scans hidden files, wrong permissions set on binaries, suspicious strings in kernel etc.

Download the package

# cd /opt/hunter
# wget http://ncu.dl.sourceforge.net/project/rkhunter/rkhunter/1.4.0/rkhunter-1.4.0.tar.gz

Run the following commands as root

# tar -xvf rkhunter-1.4.0.tar.gz
# cd rkhunter-1.4.0
# ./installer.sh --layout default --install


Fill up the database properties

# /usr/local/bin/rkhunter --update
# /usr/local/bin/rkhunter --propupd


Setup cronjob and Email alert for daily

Create a file called rkhunter.sh under /etc/cron.daily/ which scans your system daily

# vi /etc/cron.daily/rkhunter.sh

replace “ServerNameHere” with "YourServerName” and “your@email.com” with your “Email Id“.


#!/bin/sh
(
/usr/local/bin/rkhunter --versioncheck
/usr/local/bin/rkhunter --update
/usr/local/bin/rkhunter --cronjob --report-warnings-only
) | /bin/mail -s 'rkhunter Daily Run (PutYourServerNameHere)' your@email.com


# chmod 644 /etc/cron.daily/rkhunter.sh

Manual Scanning and usage

To scan the entire file system, run the Rkhunter as a root user.
# rkhunter --check

The above command generates log file under /var/log/rkhunter.log with the checks results made by Rkhunter.

For more information and options please run the following command.
# rkhunter --help






How to test for open ports in a system

Problem: Want a listing of open network ports on your system
 

Solution: Probe your ports from a remote system.

Test a Specific TCP port(ssh):-

# telnet target.example.com ssh
# nc -v -z target.example.com ssh

To scan most of the interesting TCP ports:-
# nmap -v target.example.com

To test a specific UDP port (1024)
# nc -v -z -u target.example.com 1024

To scan most of the interesting UDP ports (slowly!)
# nmap -v -sU target.example.com

To do host discovery (only) for a range of address, without port scanning
# nmap -v -sP 10.12.104.200-222

To do OS fingerprinting
# nmap -v -O target.example.com

 Namp command is a powerful and widely used tool for network security testing. It gathers information about target systems in three distinct phace:-


1. Host Discovery: 

Initial probes to determine which machines are responding within an address range.

2. Port Scanning: 

Test to find open ports that are not protected by firewalls, and are accepting connections

3. OS fingerprinting: Will get more details about the targets

To probe a single target, host name or address:
# nmap -v target.example.com
# nmap -v 10.12.200.115

-v option give more info, also can use -v -v option for more details

You can also scan a range of address:-
# nmap -v target.example.com/24
# nmap -v 10.12.200.115/24
# nmap -v 10.12.200.0-255
# nmap -v "10.12.200.*"

nmapfe is a graphical front end that run nmap with an appropriate command line.

Use nmap -P option if your tcp or icmp ping is blocked.

The goal of host discovery is to avoid wasting time performing port scanning for unused addresses.If you know your targets are up you can disable host discovery with the -P0(zero) option.

The simplest way to test a tcp port is to try to connect with telnet. 


The port might be open,
# telnet target.example.com ssh
  trying target.example.com.....
   connecting to target.example.com.
   Escape character is '^]'.
  

or closed(ie, passed by the firewall, but having no server accepting connections on the target)


# telnet target.example.com 33333
  trying target.example.com.....
  telnet: connection to address 10.12.19.99: connection refused

or blocked(filtered by firewall):
 

# telnet target.example.com 137
  trying target.example.com.....
  telnet: connection to address 10.12.19.99: connection timed out
 


The nc command is an even better way to probe ports:

# nc -z -vv target.example.com ssh 33333 137

target.example.com [10.12.19.99] 22 (ssh) open
target.example.com [10.12.19.99] 33333 (?):Connection refused
target.example.com [10.12.19.99] 137 (netbios-ns):Connection timed out
 


The -z option requests a probe, without transferring any data.

UDP ports are harder to probe than TCP ports, because packet delivery is not guaranteed.

Tuesday, 20 August 2013

How to find passwordless Accounts in a system

 Finding Accounts with no Passwords

awk -F":" '($2 == "!" || $2 == "*" || $2 == "!!" || $2 == "" ) {print $1 ": has no password at all"}' /etc/shadow



How to find Super User accounts in a system

  Find super user accounts

awk -F":" '($3 == "0") {print $1 ": is a root Account"}' /etc/passwd


Monday, 19 August 2013

Server Testing And Monitoring


Logins and Passwords: Testing password strength, 
 locating accounts with no passwords, tracking suspicious login activity.

FileSystems: Searching them for weak security, 

 and looking for rootkits.

Networking: Looking for open ports, Observing local 

 network use, packet-sniffing, tracing network processes,
and Detecting intrusions.

Logging: Reading your system logs, configure syslog, 

rotating log files.
   

 Testing Login Passwords(John the Ripper)

Problem: You want to check that all login passwords in your system password databases are strong


Solution: Use the John the Ripper, a password-cracking utility. After the software installed run,

###export PATH=/opt/john/run/ ----- export to the path
### cd /var/lib/john  --- depends on installation

un-tar the package
# cd /opt/john
# umask 077
# cd /run/
# unshadow /etc/passwd /etc/shadow > mypasswords
# john mypasswords

Cracked passwords will be written into the file john.pot, Cracked username/password pairs can be shown after the fact with the -show option

# john -show mypasswords

You can instruct john to crack the passwords of only only certain users or groups with the option -users:u1,u2... or -groups:g1,g2.....

# john -users:smith,jones,jeff mypasswords

Running John with no options will print usage information.

By Default, Redhat 8 uses MD5-hashed passwords stored in /etc/shadow, rather than the traditional DES-based crypt() hashes stored in /etc/passwd, this is effected by the md5 and shadow directives in /etc/pam.d/system-auth:

The unshadow command gathers the account and hash information together again for cracking. If your passwords change you will have to re-run the unshadow command to build an up-to-date password file for cracking.

In general cracking pgms use dictionaries of common words when attempting to crack a password, trying not only the words but also permutations, misspellings, caps etc. The default dic(/var/lib/john/password.lst) is small, so obtain larger once for effective cracking. Also add words appropriate to your environment etc

Some available dictionaries are:
ftp://ftp.cerias.purdue.edu/pub/dict/wordlists
ftp://ftp.ox.ac.uk/pub/wordlists/
 


concatenate your desired word lists into a single file, and point to it with the wordlist directive in /var/lib/john/john.ini

The supported options are as follows, square brackets denote optional arguments:

--single              "single crack" mode
Enables the "single crack" mode, using rules from the configuration file section [List.Rules:Single].

--wordlist=FILE      wordlist mode, read words from FILE,
--stdin              or from stdin

These are used to enable the wordlist mode.

Protecting Files and Directories

  
 Restrict users from accessing Files
 

Problem: You want to prevent other users on your machine from reading your files,

Solution: To protect existing files and directories,
# chmod 600 file_name
# chmod 700 directory_name

To protect future files and directories
# umask 077

Prohibiting Directory Listing

Problem: You want to prohibit directory listing for a particular directory, yet still permit the file within to be accessed by name,
 

Solution: Use a directory that has read permission disabled, but execute permission enabled,

# mkdir dir
# chmod 0111 dir
# ls -ld dir
# ls dir
/bin/ls : dir: permission denied

To permit only yourself to list a directory owned by you
# chmod 0711 dir
# ls -ld dir

Friday, 28 June 2013

How to install Linux Malware Detect (LMD) / Maldet

Malware can be trojans, viruses, spyware, adware, rootkits or any other malicious programs which can be very harmful to any computer user.
 

Linux Malware Detect (LMD) is an open source and free malware scanner and detector for Unix/Linux based operating systems.

Downloading latest LMD package
 

# wget http://www.rfxn.com/downloads/maldetect-current.tar.gz
 

Install the package

cd /opt
# gunzip maldetect-current.tar.gz
# tar -xvf maldetect-current.tar

# cd maldetect-1.4.2
./install.sh
 


Configuring LMD

By default all options are fully commented in the configuration file, so configure it according to your needs.

email_alert : If you would like to receive email alerts, then it should be set to 1.
email_subj : Set your email subject here.
email_addr : Add your email address to receive malware alerts.
quar_hits : The default quarantine action for malware hits, it should be set 1.
quar_clean : Cleaing detected malware injections, must set to 1.
quar_susp : The default suspend action for users wih hits, set it as per your requirements.
quar_susp_minuid : Minimum userid that can be suspended.

# cd /usr/local/maldetect/
vim conf.maldet


and enable the options you needed to check while running maldet

To scan it Manually

# maldet --scan-all /home

You performed a scan but failed to turn on the quarantine option, don’t worry just use the following command to turn on and quarantine all previous malware scan results.

# maldet --quarantine SCANID
OR
# maldet --clean SCANID

For Daily Scan

By default installation keeps LMD script under /etc/cron.daily/maldet and it is used to perform a daily scans, update of signatures, quarantine etc, and sends a daily report of malware scan to your specified emails.


If you need to add additional paths to be scanned, then you should edit this file accordingly to your requirements.

# vi /etc/cron.daily/maldet

Thursday, 27 June 2013

How to block SSH Server Attacks Using DenyHosts

DenyHosts is an open source and free log-based intrusion prevention security program for SSH servers.(Brute Force Attacks).
It is intended to monitor and analyzes SSH server logs for invalid login attempts, dictionary based attacks and brute force attacks by blocking the originating IP addresses by adding an entry to /etc/hosts.deny file on the server and prevents the IP address from making any further such login attempts.

First add EPEL Repository
 

# wget http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm 

# rpm -ivh epel-release-5-4.noarch.rpm

Verify EPEL Repo
# yum repolist

Then install denyhost
 

# yum install denyhosts

Configuring DenyHosts for Whitelist IP Addresses
 

Once the Denyhosts installed, make sure to whitelist your own IP address, so you will never get locked out. To do this, open a file /etc/hosts.allow,

# vim /etc/hosts.allow
   sshd: public_ip_address
   sshd: local_ip_address

Add the each IP address one-by-one on a separate line, that you never want to block.

Configuring DenyHosts for Email Alerts
 

The main configuration file is located under /etc/denyhosts.conf. This file is used to send email alerts about suspicious logins and restricted hosts.

# vim /etc/denyhosts.conf
Search for the ‘ADMIN_EMAIL‘ and add your email address here to receive email alerts about suspicious logins.


SECURE_LOG = /var/log/secure
HOSTS_DENY = /etc/hosts.deny
BLOCK_SERVICE  = sshd
DENY_THRESHOLD_INVALID = 5 ---- block each host after the number of failed login attempts has exceeded this value.This value applies to invalid user login attempts
DENY_THRESHOLD_VALID = 10 ---  block each host after the number of failed login attempts has exceeded this value. This value applies to valid user login attempts
DENY_THRESHOLD_ROOT = 1 --- block each host after the number of failed login attempts has exceeded this value.This value applies to "root" user login attempts only.
DENY_THRESHOLD_RESTRICTED = 1 --- block each host after the number of failed login attempts has exceeded this value.This value applies to usernames that appear in the WORK_DIR/restricted-usernames file only.
WORK_DIR = /var/lib/denyhosts --- the path that DenyHosts will use for writing data to # (it will be created if it does not already exist).
SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES
HOSTNAME_LOOKUP=YES
LOCK_FILE = /var/lock/subsys/denyhosts
ADMIN_EMAIL = root
SMTP_HOST = localhost
SMTP_PORT = 25
SMTP_FROM = DenyHosts <nobody@localhost>
SMTP_SUBJECT = DenyHosts Report from $[HOSTNAME]
DAEMON_LOG = /var/log/denyhosts
DAEMON_SLEEP = 30s
DAEMON_PURGE = 1h


save the entries in config file.

Restart the denyhost service
 

Once you’ve done with your configuration, restart the denyhosts service for new changes. We also add the denyhosts service to system start-up.

# chkconfig denyhosts on
# service denyhosts start

Watch DenyHosts Logs

To watch denyhosts ssh logs for how many attackers and hackers are attempted to gain access to your server. Use the following command to view the real-time logs.

# tail -f /var/log/secure

Remove Banned IP Address from DenyHosts

If you’ve ever blocked accidentally and want to remove that banned IP address from the denyhosts.
You need to stop the service.

# /etc/init.d/denyhosts stop

To remove or delete banned IP address completely. You need to edit the following files and remove the IP address.

# vim /etc/hosts.deny
# vim /var/lib/denyhosts/hosts
# vim /var/lib/denyhosts/hosts-restricted
# vim /var/lib/denyhosts/hosts-root
# vim /var/lib/denyhosts/hosts-valid
# vim /var/lib/denyhosts/users-hosts


After removing the banned IP Address, restart the service again.
# /etc/init.d/denyhosts start

[
The offending IP address added to all the files under /var/lib/denyhosts directory,so it’s makes very difficult to determine the which files contain the offending IP address.
One of the best way to find out the IP address using grep command. For example to find out IP address
162.10.25.127, do.

cd /var/lib/denyhosts
grep 162.10.25.127 *

]

Whitelist IP Addresses Permanently in DenyHosts

If you’ve list of static IP address that you want to whitelist permanently. Open the file /var/lib/denyhosts/allowed-hosts file.
Whatever IP address included in this file will not be banned by default (consider this as a whilelist).

# vim /var/lib/denyhosts/allowed-hosts
And add the each IP address on separate line. Save and close the file.

# We mustn't block localhost
127.0.0.1
162.10.25.127162.10.25.128
162.10.25.129

Tuesday, 25 June 2013

How to configure a sudo user in linux

If a server needs to be administered by a number of people it is normally not a good idea for them all to use the root account.
This is because it becomes difficult to determine exactly who did what, when and where if everyone logs in with the same credentials. The sudo utility was designed to overcome this difficulty.

The sudo utility allows users defined in the /etc/sudoers configuration file to have temporary access to run commands they would not normally be able to due to file permission restrictions. The commands can be run as user "root" or as any other user defined in the /etc/sudoers configuration file.

When running the command with the sudo prefix, you will be prompted for your regular password before it is executed.
You may run other privileged commands using sudo within a five-minute period without being re-prompted for a password.
All commands run as sudo are logged in the 

 log file /var/log/messages.

say a user try to read the file /etc/sudoers, then normally it shows /etc/sudoers: Permission denied. Due to permission issue as normal users are not permitted to read this file. If we try the same faile with # sudo

# sudo more /etc/sudoers -- it will ask for your password
"ctechz not in the sudoers file. This incident will be reported".


This error will show because we didn't add the user 'ctechz' to sudo users list, so add the user into it.



the above is a normal user, switch as root user and try

# visudo

 General sudoers File Record Format
usernames/group servername = (usernames command can be run as) command
There are some general guidelines when editing this file:-

* Groups are the same as user groups and are differentiated from regular users by a % at the beginning. The Linux user group "users" would be represented by %users.


* You can have multiple usernames per line separated by commas.


* Multiple commands also can be separated by commas. Spaces are considered part of the command.


* The keyword ALL can mean all usernames, groups, commands and servers.


* If you run out of space on a line, you can end it with a back slash (\) and continue on the next line.


* The NOPASSWD keyword provides access without prompting for your password.

## Allow root to run any commands anywhere
root    ALL=(ALL) ALL 

ctechz  ALL=(ALL) ALL  -------> this user can run all commands
              run by root using sudo.

 Sudo shell

If you have sufficient rights configured in sudoers you can also open a root shell by using


# sudo -s
or
# sudo -i

 
If the user dont have any right to perform it shows that user is not in the sudoers file.

How to Limit SSH User Logins in linux

You have large number of user accounts on the systems, then it makes sense that we limit remote access to those users who really need it.
 

Open the config file

 # vim /etc/ssh/sshd_config

and Add an AllowUsers line at the bottom of the file with a space separated by list of usernames.

AllowUsers jeffin ctechz

Restart ssh service # service sshd restart


Note: If you are not able to login into the shell using root account after changing PermitRootLogin to YES, check AllowUsers either remove the line or add root also here.

How to Disable Root SSH Login on Linux

Open ssh config file # vim /etc/ssh/sshd_config
#PermitRootLogin yes

Replace this line by:
 PermitRootLogin no

In this file we can also change the "Port number" and "Banner" details as well and much more.

# service sshd restart


after when we login as "root" user it will show "Access denied" message.

Now login as a normal user and switch as root.

How to Decoding an SSL Certificate

Problem: You want to view information about a given SSL certificate, stored in a PEM file

Solution:
# openssl x509n-text -in filename

This is a quick way to learn who issued a certificate, its begin and end dates, and other pertinent details.

This is a quick way to learn who issued a certificate, its begin and end dates, and other pertinent details.

How to Validate an SSL Certificate

Problem: You want to check that an SSL certificate is valid,

Solution: IF your system's certificates are kept in a file ( as in Red Hat)

# openssl .... -CAfile file_of_CA_certificates.....

To check the certificate of a secure web site

# openssl s_client -quiet -CAfile /usr/share/ssl/cert.pem -connect www.comain.com:443

How to Generate an SSL Certificate Signing Request(CSR)

Problem: You want to obtain an SSL certificate from a trusted certifying authority(CA)
 

Solution: Generate a Certificate Signing Request(CSR)

# make -f /usr/share/ssl/certs/Makefile filename.csr

OR
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 
 -keyout mysitename.key -out mysitename.crt

and send filename.csr to the CA

Make sure that the certificate you have received is in PEM format. Suppose it's in the file cert.pem then decrypt your private key and append it to this file

# openssl rsa -in foo.key >> cert.pem

and then as root

# chown root.root cert.pem
# chmod 400 cert.pem


OR

First, generate a private key on the Linux server that runs Apache webserver using openssl command as shown below.

Generating RSA private key, 1024 bit long modulus.
 
# openssl genrsa -des3 -out www.ctechz.com.key 1024
 
Using the key generate above, you should generate a certificate request file (csr) using openssl as shown below.
 
# openssl req -new -key www.ctechz.com.key -out www.ctechz.com.csr

How to Create Access Control List using PAM

Problem: You need to apply an ACL to an existing service that does no explicitly support ACL's.
 

Solution: Use the listfile PAM module

First make ure the server in question uses PAM for

authentication, and find out which PAM service name it uses. This may be in the server documentation, or it may be clear from examining the server itself and perusing the contents of /etc/pam.d.

Suppose you are dealing with the IMAP mail server. First notice that there is a file called /etc/pam.d/imap Furhter the result of:

# locate imapd
.....
.......
/usr/sbin/imapd

shows that the IMAP server is in /usr/sbin/imapd, and:

# ldd /usr/sbin/imapd
libpam.so.0 => /lib/libpam.so.0 (0x40027000)

Shows that the server is dynamically linked against the PAM library(libpam.so).Create an ACL file for the IMAP service, let's say /etc/imapd.acl and make sure it is not world-writable:

# chmod o-w /etc/imapd.acl

Edit thsi file and place in it the usernames of those accounts authorized to use the IMAP server, one name per line. Then add the following to /etc/pam.d/imap

# account required /lib/security/pam_listfile.so file=/etc/imapd.acl item=user sense=allow onerr=fail

With this configuration, only those users listed in the ACL file will be allowed access to the IMAP service. If the ACL file is missing, PAM will deny access for all accounts. Entries in ACL file can be not only usernames, but also:

Terminal lines (item=tty)
Remote host(item=rhost)
Remote user(item=ruser)
Group membership(item=group)
Login shell(item=shell)

The sense keyword determines how the ACL file is interpreted. sense=allow means that access will be allowed only if the configured item is in the file, and denied otherwise. sense=deny means the opposite.

The onerr keyword indicates what to do if some unexpected error occurs during PAM processing of the "listfile" module-for instance if the ACL file does not exist.

NOTE: To debug problems with PAM modules, look for PAM-specific error messages in /var/log/messages and /var/log/secure
.