Showing posts with label Red Hat 6. Show all posts
Showing posts with label Red Hat 6. 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

Installing Apache on Red Hat 6

Like most other things in Red Hat, Apache can be quickly and easily set up using the package manager. The process is simple. The only thing to remember is that the package and the service are not called Apache, but httpd.

Install Apache

Open a root shell
su -
Install the Apache web server:
yum -y install httpd
Configure the system to start Apache at boot
chkconfig httpd on
Start the Apache web server:
service httpd start

Test the Apache Installation

To test, copy and paste the following into /var/www/html/index.html:
<html>
<head>
<title>Dougie&#39;s Linux Hints Test Web Page</title>
</head>
<body>
This is a test Web Page.
</body>
</html>

Save the file. Then, still from the root shell, run the command:
elinks http://localhost
This will access the webpage created above, proving the web server is up and running.

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

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.

Thursday, 15 May 2014

Install MySQL on RedHat Linux 6

1) Install the MySQL core components: yum install -y mysql mysql-server 2) Start MySQL. service mysqld start 3) Add a MySQL root user (this is an internal MySQL account and has nothing to do with the Linux root user). mysqladmin -u root password 'password' 4) Authenticate in MySQL as root. After entering the root password, a mysql> prompt will be shown [root]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.61 Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

5) Check the MySQL internal users. Be sure to include the semicolon at the end of the command. mysql> select host, user, password from user;
+---------------------+------------+-------------------------------------------+
| host                | user       | password                                  |
+---------------------+------------+-------------------------------------------+
| localhost           | root       | *1CF65C563AC2756B0409CB694208C3F2DAC5E7EA |
| rose.com            | root       |                                           |
| 127.0.0.1           | root       |                                           |
| localhost           |            |                                           |
| rose.com            |            |                                           |
+---------------------+------------+-------------------------------------------+
5 rows in set (0.00 sec)

mysql>
6) Create a MySQL user: mysql> CREATE USER 'mysqluser'@'localhost' IDENTIFIED BY 'mysqlpassword'; 7) Give the new user DBA permissions: mysql> GRANT ALL PRIVILEGES ON *.* TO 'mysqluser'@'localhost' WITH GRANT OPTION; 8) Exit from the MySQL management interface: mysql> quit
Bye
9) Test the new user: [root]# mysql -u mysqlUser -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.61 Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> quit
bye

Wednesday, 14 May 2014

Migrating a MySQL Database To A New Red Hat Host

The location of MySQL Data is stored in /etc/my.cnf. By default, the data is stored locally in /var/lib/mysql.

To change the location of the data:

This example shows a migration from rose to martha. It assumes that the destination server has been set up with a standard LAMP environment.

Preparation

1) Log into mysql on the original host
mysql -h rose -u root -p 2) Add a new root user for the new host mysql> CREATE USER 'root'@'martha' IDENTIFIED BY '<RootPassword>';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'martha' WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)
where <RootPassword> is the root password

3) Check that the new user has been added. This is included in the 'mysql' database. mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select host, user, password from user;
+---------------------+------------+-------------------------------------------+
| host                | user       | password                                  |
+---------------------+------------+-------------------------------------------+
| localhost           | root       | *1CF65C563AC2756B0409CB694208C3F2DAC5E7EA |
| rose.com            | root       |                                           |
| 127.0.0.1           | root       |                                           |
| ::1                 | root       |                                           |
| localhost           |            |                                           |
| rose.com            |            |                                           |
| localhost           | ben        | 235814907f27996c                          |
| localhost           | test_admin | 70de51425df9d787                          |
| localhost           | jamie      | 2a8bf64a7c1bffc4                          |
| %                   | jamie      | 2a8bf64a7c1bffc4                          |
| %                   | polly      | 0d49ee5a14e0b5d7                          |
| localhost           | polly      | 0d49ee5a14e0b5d7                          |
| martha              | root       | 1afe817735574e3d                          |
+---------------------+------------+-------------------------------------------+
13 rows in set (0.00 sec)
4) Exit from MySQL mysql> quit
Bye

Close MySQL on the Old Host

5) Make sure all users are off the database

6) Stop mysql /etc/init.d/mysqld stop

Open MySQL on the New Host

7) On the new host, edit /etc/my.cnf, and change the value of datadir to point at the location of the data. If the data is moving, qv Change the Location of MySQL Data Storage

8) Restart mysql /etc/init.d/mysqld start 9) Open MySQL and test that databases can be seen [root@martha testdevdb]#  mysql -h martha -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.1.61 Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases
    -> ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| polly              |
| jamie              |
| mysql              |
| performance_schema |
| test               |
+--------------------+
6 rows in set (0.04 sec)

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select host, user, password from user;
+---------------------+------------+-------------------------------------------+
| host                | user       | password                                  |
+---------------------+------------+-------------------------------------------+
| localhost           | root       | *1CF65C563AC2756B0409CB694208C3F2DAC5E7EA |
| rose.com            | root       |                                           |
| 127.0.0.1           | root       |                                           |
| ::1                 | root       |                                           |
| localhost           |            |                                           |
| rose.com            |            |                                           |
| localhost           | ben        | 235814907f27996c                          |
| localhost           | test_admin | 70de51425df9d787                          |
| localhost           | jamie      | 2a8bf64a7c1bffc4                          |
| %                   | jamie      | 2a8bf64a7c1bffc4                          |
| %                   | polly      | 0d49ee5a14e0b5d7                          |
| localhost           | polly      | 0d49ee5a14e0b5d7                          |
| martha              | root       | 1afe817735574e3d                          |
+---------------------+------------+-------------------------------------------+
13 rows in set (0.00 sec)

mysql> quit
Bye

Reset All Root Passwords

Reset all root passwords to the standard. This can only be done by putting MySQL into skip-grant-tables mode. (qv http://www.howtoforge.com/setting-changing-resetting-mysql-root-passwords)

10) Stop MySQL and restart in skip-grant-tables mode [root@martha testdevdb]# /etc/init.d/mysqld stop
Stopping mysqld:                                           [  OK  ]
[root@martha testdevdb]# mysqld_safe --skip-grant-tables &
[1] 19498
[root@martha testdevdb]# 130703 14:34:16 mysqld_safe Logging to '/var/log/mysqld.log'.
130703 14:34:16 mysqld_safe Starting mysqld daemon with
databases from /testdir/testdev/testdevdb
11) Login to MySQL [root@martha testdevdb]# mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.61 Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
12) Select the 'mysql' database mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
13) Set the root password for all hosts mysql> update user set password=PASSWORD("<RootPassword>") where User='root';
Query OK, 5 rows affected (0.00 sec)
Rows matched: 5  Changed: 5  Warnings: 0
where <RootPassword> is the root password
14) Reload the privileges from the grant tables, then exit mysql mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql> quit
Bye
15) Stop MySQL and restart without skip-grant-tables [root@martha testdevdb]# /etc/init.d/mysqld stop
130703 14:35:56 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
Stopping mysqld:                                           [  OK  ]
[1]+  Done                    mysqld_safe --skip-grant-tables
[root@martha testdevdb]# /etc/init.d/mysqld start
Starting mysqld:                                           [  OK  ]
16) Check that the root users have been updated [root@martha testdevdb]#  mysql -h martha -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.1.61 Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select host, user, password from user;
+---------------------+------------+-------------------------------------------+
| host                | user       | password                                  |
+---------------------+------------+-------------------------------------------+
| localhost           | root       | *B85234EF763B03A804D8ACBA611FDAB53B80723A |
| rose.com            | root       | *B85234EF763B03A804D8ACBA611FDAB53B80723A |
| 127.0.0.1           | root       | *B85234EF763B03A804D8ACBA611FDAB53B80723A |
| ::1                 | root       | *B85234EF763B03A804D8ACBA611FDAB53B80723A |
| localhost           |            |                                           |
| rose.com            |            |                                           |
| localhost           | ben        | 235814907f27996c                          |
| localhost           | test_admin | 70de51425df9d787                          |
| localhost           | jamie      | 2a8bf64a7c1bffc4                          |
| %                   | jamie      | 2a8bf64a7c1bffc4                          |
| %                   | polly      | 0d49ee5a14e0b5d7                          |
| localhost           | polly      | 0d49ee5a14e0b5d7                          |
| martha              | root       | *B85234EF763B03A804D8ACBA611FDAB53B80723A |
+---------------------+------------+-------------------------------------------+
13 rows in set (0.00 sec)

mysql> quit
Bye

Force Compatibility

17) Check that all the tables are compatable with the version of MySQL [root@martha testdevdb]# mysql_upgrade -p -u root
Enter password:
Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
Running 'mysqlcheck with default connection arguments
Running 'mysqlcheck with default connection arguments
jamie.559_MT4                                      OK
jamie.559_MT5                                      OK
...
...
...
Running 'mysql_fix_privilege_tables'...
WARNING: NULL values of the 'character_set_client' column ('mysql.proc' table) have
been updated with a default value (latin1). Please verify if necessary.
WARNING: NULL values of the 'collation_connection' column ('mysql.proc' table) have
been updated with a default value (latin1_swedish_ci). Please verify if necessary.
WARNING: NULL values of the 'db_collation' column ('mysql.proc' table) have been
updated with default values. Please verify if necessary.
OK

[root@martha testdevdb]#  mysql -h localhost -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 181
Server version: 5.1.61 Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'martha' WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)

mysql> Bye
[root@martha testdevdb]# logout
Connection to martha closed.
root@system /testdir/testdev/testdevdb> exit
#


Setting up a Red Hat Linux Server for Crashdump

Kdump refers to crash dump. It allows a dedicated kernel to activate if the server crashes.

Configure the amount of memory to be reserved for the kdump kernel

Edit /boot/grub/grub.conf. Add add crashkernel=<size>M or crashkernel=auto to the end of the kernel line for the active kernel.

Note that the crashkernel=auto option only reserves the memory if the physical memory of the system is equal to or greater than:
  • 2 GB on 32-bit and 64-bit x86 architectures;
  • 2 GB on PowerPC if the page size is 4 KB, or 8 GB otherwise;
  • 4 GB on IBM S/390.

Edit /etc/kdump.conf

The core dump can be either stored as a file in a local file system, written directly to a device, or sent over a network using the NFS (Network File System) or SSH (Secure Shell) protocol. By default, the vmcore file is stored in the /var/crash/ directory of the local file system. To change this, as root, edit the options in the /etc/kdump.conf configuration file.

Saving the core dump in a local directory

Find the line that reads #path /var/crash Unhash it, and update it with the required directory path.

Saving the core dump to a different partition

In addition to the path command above, unhash the line that reads:#ext4 /dev/sda3Change both the file system type and the device (a device name, a file system label, and UUID are all supported) as required. For example: ext3 /dev/sda4
path /usr/local/cores

Writing the core dump file directly to a device

Unhash the line that reads#raw /dev/sda5 Replace the value with a desired device name. For example:
raw /dev/sdb1

Write the core dump file to a remote machine using NFS

Unhash the line that reads#net my.server.com:/export/tmpReplace the value with a valid hostname and directory path. For example: net penguin.example.com:/export/cores

Write the core dump file to a remote machine using SSH

Unhash the line that reads#net user@my.server.comreplace the value with a valid username and hostname. For example: net dougie@linuxhints.example.com

Configure the Core Collector

To reduce the size of the vmcore dump file, kdump allows you to specify a core collector to compress the data, and optionally leave out all irrelevant information. The only fully supported core collector is makedumpfile.

Enabling the core collector

As root, edit /etc/kdump.conf, and unhash the line that reads#core_collector makedumpfile -c --message-level 1 -d 31. Edit the command line options as described below.
To enable the dump file compression, add the -c parameter. For example: core_collector makedumpfile -c To remove certain pages from the dump, add the -d value parameter, where value is a sum of values of pages you want to omit as described in the following table:
OptionDescription
1Zero pages
2Cache pages
4Cache private
8User pages
16Free pages
For example, to remove both zero and free pages, use the following:
core_collector makedumpfile -d 17 -c

Enable kdump on startup

chkconfig kdump on

Start kdump

service kdump start So what all this does is create a small portion of memory which is reserved to run another tiny instance of linux – should the system crash the tiny linux will copy stuff to the appropriate crashdump area.

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