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

Tuesday, 17 June 2014

Always Use Sudo

This is part of a series of articles on Red Hat Server Hardening.

Nobody - not even administrators - should ever log in as root unless absolutely necessary. If an administrator needs to run a command with root privileges, they should use sudo.

The sudo tool allows ordinary users to have limited root level administrative access for certain tasks. This allows users to perform specific superuser operations without allowing them full superuser status.

To use sudo to run a command, precede it with the sudo command:
sudo date

The first time a user issues a sudo command during a login session, they will be prompted to enter the administrative password.

The accounts capable of using sudo are specified in the /etc/sudoers file, which is edited with the visudo utility. This file lists users and the commands they can run, along with the password for access (unless the NOPASSWD option is set, then users will not need a password).

A /etc/sudoers entry has the format
     user     host=command

userThe name of the user being granted access
hostA host on the network. For all hosts, use ALL.
commandA list of one or more commands, qualified by options such as whether the password is required. For all commands, use ALL.

So, for example, to give user paul full root-level access to all commands on all hosts:
paul   ALL = ALL

To run as another user, instead of as root, place the alternative user in parentheses before the command. For example, to allow user paul to run as user ringo on the beatle host:
paul   beatle = (ringo) ALL

The command may have an option associated with it. Possible options are:

NOPASSWD /
PASSWD
Determines whether or not the user will require a password to run the command.
NOEXEC /
EXEC
If sudo has been compiled with noexec support, this determines whether or not an executable will be allowed to run further commands itself.
SETENV /
NOSETENV
Determines whether or not users are allowed to override environment variables with the sudo -e command.
LOG_INPUT /
NOLOG_INPUT
Determines whether or not the input to the command is written to the log file.
LOG_OUTPUT /
NOLOG_OUTPUT
Determines whether or not the output from the command is written to the log file.
By default, relevant logs are written to /var/log/secure.

Therefore, to allow user paul to run the kill command on beatle with a password, but to run the lprm command without a password:
paul   beatle = PASSWD: /usr/bin/kill, NOPASSWD: /usr/bin/lprm

A user can see what commands he or she can run by running: sudo -l

Wednesday, 11 June 2014

Remove KDE or GNOME From Linux

X Windows desktops like KDE or GNOME are not required on a server, and waste valuable resources. These should therefore be removed:
yum groupremove “X Window System”

This will remove around 100-150 packages from the server.

Doing this will prevent an intruder from starting an X-Windows session on the server by typing startx at the shell prompt.

Installation of X-Windows can also be completely prevented during initial system installation.

Monday, 9 June 2014

Pluggable Authentication Modules (PAM) Overview

Pluggable Authentication Modules (PAM) is an authentication service that lets a system determine the method of authentication to be performed for users. Traditionally in Linux, authentication has been performed by looking up passwords - the login process looks up the user's password in the password file and verifies it against what the user has entered.

With PAM, user's authentication requests are directed to PAM, which in turn uses a specified method to authenticate the user. This could be a simple password lookup, or it could be a request to an LDAP server, or some other method of authentication. Authentication is centralized and controlled by a specific service, PAM. The actual authentication procedures can be dynamically configured by the system administrator.

There are two types of PAM files: Configuration Files and Modules. Modules carry out the authentication process. These vary according to the kind of authentication needed. An administrator can add or replace modules by simply changing the PAM configuration files

PAM Configuration Files

PAM Configuration files are kept in the /etc/pam.d directory. PAM uses different configuration files for different services that request authentication.

Note:- If the /etc/pam.d/ directory does not exist, PAM will look for the /etc/pam.conf file instead. This is for historical reasons only.

The /etc/pam.d/ directory contains a configuration file for each PAM-aware application or service. The configuration file has the same name as the service to which it controls access. PAM-aware applications and services are responsible for defining their own PAM configuration files. For example, the /etc/pam.d/login PAM configuration file is installed by the login application.

Each PAM configuration file contains a group of directives formatted as follows:
<module interface>  <control flag>   <module name>   <module arguments>

PAM Module Interface

There are four types of PAM module interface, each of which corresponds to a different phase of the authorization process:
Module InterfaceDefinition
auth This module interface authenticates use. For example, it requests and verifies the validity of a password. Modules with this interface can also set credentials, such as group memberships or Kerberos tickets.
account This module interface verifies that access is allowed. For example, it may check if a user account has expired or if a user is allowed to log in at a particular time of day.
password This module interface is used for changing user passwords.
session This module interface configures and manages user sessions. Modules with this interface can also perform additional tasks that are needed to allow access, like mounting a user's home directory and making the user's mailbox available.

PAM Control Flag

All PAM modules return a status of success or fail. The Control Flag determines what PAM does with that status, and how important the success or failure of the module is to the authentication process. 

The control flag will usually have one of the following five values:

Control FlagDefinition
required The module result must be successful for authentication to continue. If the test fails at this point, the user is not notified until the results of all module tests that reference that interface are complete.
requisite The module result must be successful for authentication to continue. However, if a test fails at this point, the user is notified immediately with a message reflecting the first failed required or requisite module test.
sufficient The module result is ignored if it fails. However, if the result of a module flagged sufficient is successful and no previous modules flagged required have failed, then no other results are required and the user is authenticated to the service.
optional The module result is ignored. A module flagged as optional only becomes necessary for successful authentication when no other modules reference the interface.
include Unlike the other controls, this does not relate to how the module result is handled. This flag pulls in all lines in the configuration file which match the given parameter and appends them as an argument to the module.

PAM Module Name and PAM Module Parameters

This is simply the name of the module, followed any parameters that are required to run it.

As previously noted, the authentication process is split into four phases - auth, account, password and session - specified in the configuration file by the Module Interface parameter. Each phase may consist of zero, one or several modules. The overall success or failure of each phase is determined by the combination of the control flags.

PAM Modules

PAM Modules are located in the /lib/security directory. Each returns either a success or failure.

Most of the modules and configuration files included by default with PAM have their own manpages.

It is also possible to write modules from scratch. Documentation on writing modules is included in the /usr/share/doc/pam-<version#> directory.

Friday, 6 June 2014

Configure or Disable SSH

This is part of a series of articles on Red Hat Server Hardening.

SSH is the usual means of accessing and interacting with a server. Unless the keyboard and monitor are physically connected directly to the server, then access will most likely be via SSH. However, if SSH is not required, then disable it:
/sbin/chkconfig sshd off

The default SSH configuration means that automated cracking scripts and bots trying to break into a server know exactly where to go and what to do. They know the name of the root account, and they know they can SSH onto the server on port 22. The first line of defence is therefore to disable direct root access via SSH, and change the access port.

Changes to SSH are made via the SSH configuration file: /etc/ssh/sshd_config.

Prevent direct root login from SSH

In the config file, find the line that reads:
PermitRootLogin yes

Change yes to no. This prevents users from logging into the server as root via SSH. This adds an extra layer of security. Any hacker trying to get into root will have to get in as a normal user first, then try to access root from there. Warning: Make sure you have a regular user account first before doing this, otherwise you will not be able to access root.

Limit SSH access to a subset of users

If possible, limit SSH access to a subset of users. If there are many user accounts on the server, but only a few need to log into it via SSH, then doing this is a worthwhile exercise.This makes a hacker's job even more difficult because they will have to guess the both the name of an authorised user, and their password.

The AllowUsers parameter is not included in /etc/ssh/sshd_config by default, so it will need to be added:
AllowUsers john paul george ringo

Alternatively, create a group called sshusers and only add the users that need remote access:
groupadd sshusers
usermod -aG sshusers john
usermod -aG sshusers paul
usermod -aG sshusers george
usermod -aG sshusers ringo

Then, add the following line to /etc/ssh/sshd_config:
AllowGroups sshusers
Note:- The AllowUsers and AllowGroups parameters are mutually incompatible, with AllowUsers taking precedent.

Change the default SSH port

Change the default SSH port number of 22 to some other higher level port number.
Note:- The Internet Assigned Numbers Authority (IANA) is responsible for the global coordination of the DNS Root, IP addressing, and other Internet protocol resources. It is good practice to follow their port assignment guidelines. Having said that, port numbers are divided into three ranges: Well Known Ports, Registered Ports, and Dynamic and/or Private Ports. The Well Known Ports are those from 0 through 1023 and SHOULD NOT be used. Registered Ports are those from 1024 through 49151 should also be avoided too. Dynamic and/or Private Ports are those from 49152 through 65535 and can be used.
Choose an appropriate port, also making sure it not currently used on the system, and update the following line in /etc/ssh/sshd_config:
Port <New Port Number>
Make sure, obviously, that anyone who needs to ssh onto the server knows the correct port number. To log in, they will need to add -p <new port number> to the end of the ssh command.

Once all of the necessary changes have been made to /etc/ssh/sshd_config, restart the service so that these changes take effect.
service sshd restart

Monday, 2 June 2014

Determine What Country A Website User Is In

One of my other concerns is a website which sells MP3s of original children's music.

These sell all over the world, so it is important that prices are displayed in local currency if possible. The easiest way to do that is by IP address. When the site was originally created, it was built using HTML and javascript, with only a very small amount of PHP to access some tables of IP ranges and the appropriate country. When the website was rebuilt around a MySQL database, this method of identifying the user's country remained, because it worked.

But these things are ever evolving, and the IP ranges I was using quickly went out of date. I have been aware for some time that I need to find a way on automatically making sure that the IP ranges are up to date.

After a bit of looking around, I have found that an up to date CSV file of IP ranges can be downloaded from http://software77.net/geo-ip/. The plan is to download the CSV file automatically on a regular basis, then rebuild the existing PHP arrays.

This can all be accomplished with a simple bash script, run from cron once a week. The IP file is donationware, so I have arranged a regular $5 monthly payment for the privilege which seems fair, I think.

The first step is to download the file. This can be accomplished with a simple wget:
wget http://software77.net/geo-ip/?DL=1 -O ./IpToCountry.csv.gz


The file is compressed, so it needs to be uncompressed. I also extract only the fields that are required. The fields on the incoming file are IP From, IP To, Registry, Assigned, 2-Letter Country Code, 3-Letter Country Code and Country. I only need IP From, IP To and the 2-Letter Country Code.

Both of these tasks can be accomplished in a single command line:
gunzip -c IpToCountry.csv.gz  | awk -F, '!/^#/ {gsub(/"/, "", $0);print $1, $2, $5}'  > ./IpToCountry.csv


This uncompresses the file, strips off all of the comment lines, removes any inverted commas, extracts the necessary fields and creates a stripped down, custom built file that can be used as required.

Next comes the rebuilding of the PHP IP arrays. These consist of 256 numbered files, starting at 0.php through to 255.php. Each of these contains a PHP script defining an array of ranges of IP addresses and the country that they belong to. The appropriate PHP script is included at run time, dependent on the first segment of the IP address.

The first step is to write the header for each script. This opens the php tag and starts to declare the array:
<?php
//-
$ranges=Array(


This  header is identical for all 256 files.

Next, the arrays themselves must be created. These can be converted directly from each line in the CSV file in the format:
"IP From" => array("IP To","2-Digit Country Code")


IP From and IP To are both formatted as a 32-bit integer, rather than the 4 segments traditionally recognised as an IP address. To convert the 4-segment IP address to the 32 bit integer it represents, multiply each segment by increasing factors of 256.

eg for IP address "1.2.3.4"
     (1*256*256*256)+(2*256*256)+(3*256)+4

Similarly, the IP segments can be determined by reversing the process. In this instance, we only need the first of the 4 segments, to determine which file we are writing to. This can be achieved by dividing IP From by (256*256*256), and using only the integer returned.

Finally, a footer is added to the end of all of the files. Like the header, this is identical for all 256 files, simply closing off the array and closing the php tag:
);
?>


The finished script looks like:
#!/bin/bash
#######################################################
#
# csv2IP.sh
#
# Douglas Milne 2 June 2014
#
# Download a csv file of IP address ranges for countries
# and convert to php arrays
#
#######################################################

# create a temporary directory to build the files
# Files are built here, then moved to the correct location on completion
# This minimizes the amount of time the files are unavailable as recreating them can take several minutes
mkdir ~/iptemp 2>/dev/null
cd  ~/iptemp

# Download the csv file
wget http://software77.net/geo-ip/?DL=1 -O ./IpToCountry.csv.gz >/dev/null 2>&1
status=$?
if (( status != 0 ))
then
   echo "Error downloading csv file"
   exit 2
fi
# Uncompress the CSV file and select only the To, From and Country columns
gunzip -c IpToCountry.csv.gz  | awk -F, '!/^#/ {gsub(/"/, "", $0);print $1, $2, $5}'  > ./IpToCountry.csv

# Create a new .php file for the first digit of possible ip addresses, ie 0-255, and write a header to it
for ((i=0; i<=255; i++))
do
   echo -e "<?php\n//-\n\$ranges=Array(" > $i.php
done

# Add the IP ranges as specified in the CSV file to the php files.
# The first digit of each ip address, and therefore the file to write to,
# is determined by the integer result of dividing the address by 16777216
cat IpToCountry.csv | awk '{print $1,$2,$3}' | while
   read ipFrom ipTo Country
do
   (( ipmsb = ipFrom / 16777216 ))
   echo -e "\"$ipFrom\" => array(\"$ipTo\",\"$Country\")," >> $ipmsb.php
done

# Add a footer to each of the php files
# and move the files to the correct location.
for ((i=0; i<=255; i++))
do
   echo -e ");\n?>" >> $i.php
   mv $i.php ~/ip_files
done


By way of example of the output, the file for all IP addresses from 45.0.0.0 to 45.255.255.255 is
$ cat 45.php
<?php
//-
$ranges=Array(
"754974720" => array("755105791","US"),
"757071872" => array("759169023","ZZ"),
"765460480" => array("767557631","UY"),
);
?>

This tells us that some of these are in the US, some are reserved and some are in Uruguay. Most of the output files are considerably larger than this, and some are smaller.

The script is run from cron a couple of times a week. Software77 request that a time other than right on the hour is chosen for download, so that everybody isn't tryng to download at once. It's worth reading the comments in the CSV file and on their website, because breaking the rules can result in a barring.

So how does a webpage make use of this information? The following PHP function takes the IP address of the client
function iptocountry($ip) {
    $numbers = preg_split( "/\./", $ip);  
    include("ip_files/".$numbers[0].".php");
    $code=($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);  
    foreach($ranges as $key => $value){
        if($key<=$code){
            if($ranges[$key][0]>=$code){$two_letter_country_code=$ranges[$key][1];break;}
            }
    }
    return $two_letter_country_code;
}

This function converts the IP address into a 32-bit integer, includes the appropriate array file, then searches through the array until it finds the range that contains the 32-bit integer
This can be called using the "REMOTE_ADDR" entry in the $_SERVER array.
$two_letter_country_code=iptocountry($_SERVER['REMOTE_ADDR']);

Wednesday, 28 May 2014

Send HTML Format Email From Linux

The following script is very useful for sending HTML formatted emails from Linux.

Simply pipe the HTML into it, and the script adds the necessary header information before sending it on it's way. The script assumes that sendmail is installed and configured.

I wrote the original version of this script back in 2006, and it has proved so useful - for presenting daily system reports with warnings in red, for example - that I have used versions of it in most companies that I have done work for ever since.

#!/usr/bin/bash
##################################################################
#
# htmmail
#
# Purpose: To send html formatted emails
#
# Syntax: htmmail [-s Subject] address [address] [address...]
#
# Subject The subject of the email
# address The email address of the intended recipient
#
# The content of the email may be included by piping it
# into the htmmail command.
#
# Author: Douglas Milne
# Date: 27th May 2014
#
##################################################################
#
# Version 1.0 Initial Release
#
##################################################################

# Get options
# s flag argument is the subject of the email
#
while getopts s: value
do
case $value in
s) SUBJECT=$2
;;
\?) echo "$0: unknown option $OPTARG"
;;
esac
done

shift $(expr $OPTIND - 1)

# Remaining arguments are email addresses to send the email
TO=$*

# Set up email header, including content type field
# signifying html format.
# To and Subject as specified above

/usr/lib/sendmail -t << EOF
mime-version: 1.0
content-type: text/html; charset="iso-8859-1"
To: $TO
Subject: $SUBJECT

$(cat)

EOF

Friday, 23 May 2014

Disable CTRL-ALT-DEL On A Linux Box

Pressing the CTRL-ALT-DEL combination of keys on a Linux box forces it to reboot

This is set up within /etc/inittab.

To change how this key combination behaves, edit this file.

Search for the line:
ca::ctrlaltdel:/sbin/shutdown -t3 -r now
and change it to:
ca::ctrlaltdel:/bin/echo "CTRL-ALT-DEL is disabled"
Save the file, then run:
init q
to reload the inittab and activate the change.

How to List Sizes of Sub-Directories

Performing a simple du -h on a Linux directory produces way too much information if there are a lot of sub-directories. To find the sizes of only the directories in the current directory, which is often more useful, look at the last line of the du -h only for sub-directory. To list size of all subdirectories
for x in $(ls); do du -h $x | tail -1; done

Tuesday, 20 May 2014

Firewalls Overview

What is a firewall?

Many systems connected to the internet are open to attempts by outside users to gain unauthorized access by setting up an illegal connection to the system. A firewall prevents any direct unauthorized attempts at access.

A good foundation for network security is to set up a Linux system to operate as a firewall for the network. The firewall can be used to set up either packet filtering or proxies. Packet Filtering is the process of deciding whether or not a packet received by the firewall should be passed on to the local network. The packet filtering software checks the source and destination addresses of the packet and sends the packet on if it is allowed.

Proxies can be used to control access to specific services, such as web or FTP servers. A proxy is required for each service. For example, the web server has its own web proxy, while an FTP server has an FTP proxy. Proxies can also be used to cache commonly used data, such as web pages, so that users do not need to constantly access the originating site.

An additional task performed by firewalls is NAT (Network address translation). Network address translation redirects packets to appropriate destinations. It performs tasks such as redirecting of packets to certain hosts, forwarding packets to other networks and chaning the host source of packets to implement IP masquerading.

The current Linux kernel incorporates support for firewalls using the Netfilter (IPtables) packet filtering package, which implements both packet filtering and NAT tasks for the Linux 2.4 kernel and above.

Implementing a firewall is simply a matter of providing a series of rules to govern what kind of access should be allowed on the system. If that system is also a gateway for a private network, the system's firewall can also help protect the network from outside attacks.

Iptables

Netfilter implements packet filtering and NAT tasks separately using different tables and commands. The command used to execute both is iptables, but for NAT, add the -nat option.

With iptables, different tables of rules can be set up to select packets according to differing criteria. Netfilter supports three tables: filter, nat and mangle. Packet filtering is implemented using a filter table that holds rules for dropping or accepting packets. Network address translation operations are implemented using the nat table. Specialized changes made to packets before they are sent out, when they are received or as they are being forwarded are implemented using the mangle table.

By default, iptables operates on the filter table, which need not be specified. To list the rules use the -L (list) option. This will include a DNS lookup for hostnames, and will show port lables and hostnames. To show only numeric output and avoid the DNS lookup, use the -n (numeric output), which will show IP addresses and port numbers eg
iptables -L -n
Chain input (policy ACCEPT):
Chain forward (policy ACCEPT):
Chain output (policy ACCEPT):

To operate on the nat table, add the -t nat option eg:
iptables -t nat -L -n -v
Chain PREROUTING (policy ACCEPT 867 packets, 146K bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  vlan2  *       0.0.0.0/0            192.168.1.0/24
Chain POSTROUTING (policy ACCEPT 99 packets, 6875 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MASQUERADE  all  --  *      vlan2   0.0.0.0/0            0.0.0.0/0
Chain OUTPUT (policy ACCEPT 99 packets, 6875 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain WANPREROUTING (0 references)
 pkts bytes target     prot opt in     out     source               destination



Monday, 19 May 2014

Duties of a System Administrator

A system administrator is responsible for the day-to-day running of a computer system. Most of what a system administrator is expected to know is performed only rarely, while only a handful of tasks are performed on a day to day basis. A shrewd system administrator will automate as many of these day-to-day tasks as possible. Automation (using scripting, specialized software, system scheduling or a combination of all three) frees the administrator's time, saves money and mitigates against human error.

A system administrator's duties will vary from one organization to another, depending on factors such as the size of the system, the number of users and the purpose of the organization. Nevertheless, basic tasks remain the same, and as such, a system administrator can move from one industry to another with relative ease.

The system administrator's basic job description would be to install, support and maintain servers and other IT hardware. The administrator must also plan for and respond to service outages and other problems.

The following is an inexhaustive list of the responsibilities and duties of a system administrator:

Hardware

  • Hardware monitoring (both system and peripherals)
  • Hardware maintenance and repair (usually a call-out to hardware support)

System

  • System maintenance
  • System performance monitoring
  • System security 
  • Creating file systems
  • Software installation and update
  • Creating backups and ensuring that recovery is fast and accurate
  • Monitor networks and communications

Users

  • User administration
  • Password and identity management

Documentation

  • Documentation of system and processes



Saturday, 17 May 2014

The TCP/IP Protocol Suite

The TCP/IP Protocol Suite consists of many different protocols, each designed for a specific task in a TCP/IP network. The protocols are each known by an acronym.

The three basic protocols are:
ProtocolAcronymTask
Internet ProtocolIPHandles the actual transmissions: the packets of data with sender and receiver in each
Transmission Control ProtocolTCPHandles receiving and sending out communications. It is designed to work cohesive messages or data, checking received packets and sorting them into their designated order, forming the original message. Data sent out is broken into separate , order-designated packets.
User Datagram ProtocolUDPHandles receiving and sending out packets of data, but does not check their order.
The TCP and IP protocols are designed to provide stable and reliable connections that ensure that all data is reorganized into it's original order.

The UDP protocol is designed to send as much data as possible with no guarantee that packets will be received, or placed in their correct order. It is used for transmitting large amounts of data that can survive the loss of a few packets - for example, temporary images, videos and banners displayed on the internet.

Other protocols provide various network and user services. These protocols make use of either TCP or UDP protocol to send and receive packets, which, in turn, use the IP protocol to transmit the packets.

A complete list of protocols is:
ProtocolAcronymTask
Transport
Internet ProtocolIPHandles the actual transmissions: the packets of data with sender and receiver in each
Transmission Control ProtocolTCPHandles receiving and sending out communications. It is designed to work cohesive messages or data, checking received packets and sorting them into their designated order, forming the original message. Data sent out is broken into separate , order-designated packets.
User Datagram ProtocolUDPHandles receiving and sending out packets of data, but does not check their order.
Internet Control Message ProtocolICMPStatus messages for IP.
Routing
Routing Information ProtocolRIPDetermines routing.
Open Shortest Path FirstOSPFDetermines routing.
Network Address
Address Resolution ProtocolARPDetermines unique IP address of systems.
Domain Name ServiceDNSTranslates hostnames into IP addresses.
Reverse Address Resolution ProtocolRARPDetermines addresses of systems.
User Service
File Transfer ProtocolFTPTransmits files from one system to another using TCP.
Trivial File Transfer ProtocolTFTPTransfers files from one system to another using UDP.
TelnetRemote login to another system on the network.
Simple Mail Transfer ProtocolSMTPTransfers email between systems.
Remote Procedure CallRPCAllow programs on remote systems to communicate.
Gateway
Exterior Gateway ProtocolEGPProvides routing for external networks.
Gateway-to-Gateway ProtocolGGPProvides routing between internet gateways.
Interior Gateway ProtocolIGPProvides routing for internal networks.
Network Service
Network File SystemNFSAllows mounting of file systems on remote machines.
Network Information ServiceNISMaintains user accounts across a network.
Boot ProtocolBOOTPStarts system using boot information on server for network.
Simple Network Management ProtocolSNMPProvides status messages on TCP/IP configuration.
Dynamic Host Configuration ProtocolDHCPAutomatically provides network configuration information to host systems.
In a TCP/IP network, messages are broken into small components called datagrams. These are then transmitted through various routes and reassembled into their original message at the destination computer.

Datagrams can in turn be broken down into smaller components, called packets. These are the physical units that are actually transmitted. Sending messages as small components is faster and more reliable than sending them as one single large transmission. If one component is lost or corrupted, only that component must be resent. With a single large transmission, the whole message must be resent.

Configuring and Managing TCP/IP Networks

TCP/IP networks are configured and managed with a set of utilities, ifconfig, route and netstat.
UtilityDescription
ifconfigEnables full configuration of network interfaces, adding new ones and modifying others.
routeEnables full configuration of the routing tables, adding new entries and modifying others.
netstatProvides information about the status of network connections.

Friday, 16 May 2014

MySQL Configuration Files

MySQL supports three different configuration files, one for global settings, one for server specific settings, and an optional one for user-customised settings.

MySQL Global Settings

The /etc/my.cnf configuration file is used for global settings applied to both clients and servers. The /etc/my.cnf file provides information such as the data directory (/var/lib/mysql) and the log file (/var/log/mysql.log) locations, as well as the server base directory (/var/lib).

Options are specified according to different groups, usually the names of server tools, and are arranged in group segments. The group name is specified within square brackets, followed by the options.

For example:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

[mysql.server]
user=mysql
basedir=/var/lib

[safe_mysqld]
err-log=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

The above example specifies the options for the daemon mysqld, server-options mysql.server and the MySQL startup script safe_mysqld. Database files will be placed in /var/lib/mysql. MySQL will run as the mysql user. Server tools and daemons are located in the basedir directory, /var/lib.

To see what options are currently set, you can run mysqld with the --help option
/usr/libexec/mysqld --help

MySQL Server Settings

The /var/lib/mysql/my.cnf file is used for server settings only.

MySQL User Customised Settings

The .my.cnf file allows users to customise their access to MySQL. It is located in a user's home directory.

This file contains user configuration settings such as the password used to access the database and the connection timeouts.

[client]
password=mypassword

[mysql]
no-auto-rehash
set-variable = connect_timeout=2

[mysql-hotcopy]
interactive-timeout

Wednesday, 14 May 2014

Running SSH From Within Cron

SSH does not run from within cron, because it is password authorised.

To get round this, use a script to generate the password prior to running the actual script, eg:
0 9 * * * . /.ssh-agent.sh; /home/milned/scripts/testntp.sh If the call of the ssh-agent.sh script (needed to supply the pass phrase) is omitted, it's just ssh being called inside the bash shell script.

Set Up SSH Agent Forwarding on a Server

This is part of a series of articles on Red Hat Server Hardening.

SSH is the Secure Shell protocol which can be used for command line access, file transfer and application tunnelling.

Overview

Password free access requires a public/private key pair. The server (sshd) has access to the public key, while only you and your SSH client have access to the private key. To authenticate the client convinces the server that it is in possession of the private key without actually sending it.

Private keys are protected by a pass phrase. This pass phrase is required each time the key is used. To allow repeated access without re-keying of the pass phrase, agent forwarding is used.

The SSH agent allows the pass phrase to be entered once only, e.g. at system start-up or in the originating shell and then caches the keys in memory, eliminating the need for the phrase to be entered for each access. Because the agent is forwarded the pass phrase is available for all sessions that can access the keys in the home directory, including chains of sessions.

Steps

The steps required to set up password free access are:
  1. Generate a key pair using OpenSSH
  2. Distribute public keys
  3. Configure agent forwarding

Generate SSH key pair

ssh-keygen is a program in the OpenSSH package that can be used to create key pairs. RSA is the current SSH key standard; DSA and RSA1 keys can be generated for compatibility with older systems.

Use the full path to ssh-keygen to ensure the correct OpenSSH binary is used, key in a pass phrase when prompted and accept the default file locations. 

> /usr/bin/ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/milned/.ssh/id_rsa):
Created directory '/home/milned/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/milned/.ssh/id_rsa.
Your public key has been saved in /home/milned/.ssh/id_rsa.pub.
The key fingerprint is:
77:3f:47:01:92:5f:d0:fe:3e:6a:03:a4:9a:0a:18:26 milned@nyssa

Similarly DSA and RSA1 keys can be generated. Again enter a pass phrase and accept the default file locations as prompted. Using the same pass phrase for all keys will simplify operation of the SSH agent. 

> /usr/bin/ssh-keygen -t dsa
> /usr/bin/ssh-keygen -t rsa1

Distribute SSH Public Keys

The public keys must be distributed to the user's authorized_keys file so that any SSH daemon with access to the user's home directory can use them.

> cd ~/.ssh
> cat *.pub > authorized_keys


Change the permissions on this file so it is not writable by other users.

> chmod go-w authorized_keys

Now check that key authentication is working, by using ssh to connect to the host you are currently logged in to using its hostname. You should be prompted for the pass phrase for one of your keys. If this is the first time you've talked to the machine you will also be asked to accept the host key, which you should do.

> ssh nyssa
The authenticity of host 'nyssa (127.0.0.1)' can't be established.
RSA key fingerprint is 85:4b:2a:53:48:52:9f:61:ed:0a:33:4a:9d:5e:d3:1a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'nyssa' (RSA) to the list of known hosts.
Enter passphrase for key '/home/milned/.ssh/id_rsa':
Last login: Thu Nov 21 17:27:35 2013 from tegan
>


SSH access is now configured to use keys rather than a password to grant access. Access to the key is controlled by a pass phrase. In the next step agent forwarding is set up so that this pass phrase only needs to be entered once.

Configure SSH Agent Forwarding


To check if there is already an agent running use ssh-add.

> /usr/bin/ssh-add -l
Could not open a connection to your authentication agent

If this command reports anything else, then there is an agent running. Otherwise, start an agent using the command:

> exec ssh-agent $SHELL This creates a new shell process as a child of the agent with suitable environment variables set. This agent will live until you exit from this shell, and is only accessible from it.

Running ssh-add should now show the agent is present, but with no identities.
> /usr/bin/ssh-add -l
The agent has no identities
The next step is to add the keys using ssh-add. This will prompt you for the pass phrase for one of your keys, and then assuming they all have the same pass phrase, add them all to the agent:

> /usr/bin/ssh-add
Enter passphrase for /home/milned/.ssh/id_rsa:
Identity added: /home/milned/.ssh/id_rsa (/home/milned/.ssh/id_rsa)
Identity added: /home/milned/.ssh/id_dsa (/home/milned/.ssh/id_dsa)
Identity added: /home/milned/.ssh/identity (milned@nyssa)
Check the keys are available with ssh-add again, which should now report a list of key signatures.
> /usr/bin/ssh-add -l
1024 90:d1:83:5c:2a:33:9b:c7:ba:85:8e:ef:b7:c0:32:05 milned@nyssa (RSA1)
1024 9f:c0:e4:ed:f1:c4:ec:de:6e:af:4c:91:13:8d:58:45 /home/milned/.ssh/id_rsa (RSA)
1024 ab:a1:89:d7:d5:06:d2:d5:c4:18:e6:bc:65:37:96:dc /home/milned/.ssh/id_dsa (DSA)
You should now be able to use ssh to connect to any other machine which is running OpenSSH and has your home directory mounted, and not be prompted for a password. Chaining SSH connections (ssh from a to b and then from b to c) should work via agent forwarding.

Automating SSH Agent Forwarding

Rather than running the above manually, it can be built into the .bashrc file so that it starts automatically when bash is started.

> cd
> cat .bashrc
export PS1="\u@\H \w> "
PATH=$PATH:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin

Amend .bashrc as follows:
export PS1="\u@\H \w> "
PATH=$PATH:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin
ssh-agent > $HOME/.ssh-agent.sh
ssh_agent="$HOME/.ssh-agent.sh"
if [ -f $ssh_agent ]
then
  source $ssh_agent > /dev/null
fi
ssh-add
alias stat="perl -e'print "%o\n",(stat shift)[2] & 07777' $1"
export EDITOR=vi


Commands For Process Management

There are many tasks running at any given moment on a RedHat Server. These tasks are known as processes.

Terminology

When the server boots, many processes are started to provide services on the computer. These are known as daemons. A daemon is a process which is started in the background and provides a service on the server.

Why Do Processes Need Managing

If a process is not responding properly, you may need to send it a specific signal.

Or if a system is busy, it can be helpful to get an overview of the system to see what it is doing.

Useful commands for process management are:

CommandUse
psUsed to show all current processes
killUsed to send signals to processes, such as asking or forcing a process to stop.
pstreeUsed to get an overview of all processes, including the relationship between parent and child processes.
killallUsed to kill all processes, based on the name of the process
topUsed to get an overview of current system activity.