Category Archives: Linux

Change the default MySQL data directory with SELinux enabled

This is a short article that explains how you change the default MySQL data directory and adjust SELinux to account for the changes. The article assumes that you’re running either RHEL, CentOS, Scientific Linux or Fedora with SELinux enabled. This works with the most recent EL (6.2) version.

We’ll be doing this in the following order.

  • Stopping the MySQL server
  • Create a new data directory and move the content from the old data directory
  • Correct the MySQL configuration file
  • Adjust SELinux parameters to accept our new change
  • Starting the MySQL server

Stopping the MySQL server

# service mysqld stop

Create a new data diretory and move the content from the old one

Creating a new data directory

# mkdir /srv/mysql/
# chown mysql:mysql /srv/mysql

Moving the original data files

 # mv /var/lib/mysql/* /srv/mysql/

Correct the MySQL configuration file

Edit the my.cnf file for your distribution. In my example it’s located in the /etc/mysql/ directory. RHEL/CentOS/Scientific Linux put the my.cnf file directly in /etc by default.

# nano /etc/mysql/my.cnf

Change

datadir=/var/lib/mysql

to

datadir=/srv/mysql

and

socket=/var/lib/mysql/mysql.sock

to

socket=/srv/mysql/mysql.sock

and save the file.

Adjust SELinux parameters to accept our new change

Should the following command output “Permissive” or “Disabled” then you may skip the details for SELinux.

# getenforce

Run the semanage command to add a context mapping for /srv/mysql.

# semanage fcontext -a -t mysqld_db_t "/srv/mysql(/.*)?"

Now use the restorecon command to apply this context mapping to the running system.

# restorecon -Rv /srv/mysql

Starting the MySQL server

# service mysqld start

Verifying access and connectivity

$ mysql -u root -p
mysql> show databases;

If this is working, you’re up and running. Should you get a message that says

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’

then add the following to your /etc/my.cnf

[client]
socket = /srv/mysql/mysql.sock

Optionally you can just use

$ mysql -u root -p --protocol tcp

to avoid connecting via the socket.

// CrashMAG

Useful SystemD commands

List all running services

# systemctl

Start/stop or enable/disable services

Activates a service immediately:

# systemctl start foo.service

Deactivates a service immediately:

# systemctl stop foo.service

Restarts a service:

# systemctl restart foo.service

Shows status of a service including whether it is running or not:

# systemctl status foo.service

Enables a service to be started on bootup:

# systemctl enable foo.service

Disables a service to not start during bootup:

# systemctl disable foo.service

Check whether a service is already enabled or not:

# systemctl is-enabled foo.service; echo $?

0 indicates that it is enabled. 1 indicates that it is disabled

How do I change the runlevel?

systemd has the concept of targets which is a more flexible replacement for runlevels in sysvinit.

Run level 3 is emulated by multi-user.target. Run level 5 is emulated by graphical.target. runlevel3.target is a symbolic link to multi-user.target and runlevel5.target is a symbolic link to graphical.target.

You can switch to ‘runlevel 3’ by running

# systemctl isolate multi-user.target (or) systemctl isolate runlevel3.target

You can switch to ‘runlevel 5’ by running

# systemctl isolate graphical.target (or) systemctl isolate runlevel5.target

How do I change the default runlevel?

systemd uses symlinks to point to the default runlevel. You have to delete the existing symlink first before creating a new one

# rm /etc/systemd/system/default.target

Switch to runlevel 3 by default

# ln -sf /lib/systemd/system/multi-user.target /etc/systemd/system/default.target

Switch to runlevel 5 by default

# ln -sf /lib/systemd/system/graphical.target /etc/systemd/system/default.target

systemd does not use /etc/inittab file.

List the current run level

runlevel command still works with systemd. You can continue using that however runlevels is a legacy concept in systemd and is emulated via ‘targets’ and multiple targets can be active at the same time. So the equivalent in systemd terms is

# systemctl list-units --type=target

Powering off the machine

You can use

# poweroff

Some more possibilities are: halt -p, init 0, shutdown -P now

Note that halt used to work the same as poweroff in previous Fedora releases, but systemd distinguishes between the two, so halt without parameters now does exactly what it says – it merely stops the system without turning it off.

 

Service vs. systemd

# service NetworkManager stop

(or)

# systemctl stop NetworkManager.service

Chkconfig vs. systemd

# chkconfig NetworkManager off

(or)

# systemctl disable NetworkManager.service

Readahead

systemd has a built-in readahead implementation is not enabled on upgrades. It should improve bootup speed but your mileage may vary depending on your hardware. To enable it:

# systemctl enable systemd-readahead-collect.service
# systemctl enable systemd-readahead-replay.service

SystemD cheatsheet

service foobar start systemctl start foobar.service Used to start a service (not reboot persistent)
service foobar stop systemctl stop foobar.service Used to stop a service (not reboot persistent)
service foobar restart systemctl restart foobar.service Used to stop and then start a service
service foobar reload systemctl reload foobar.service When supported, reloads the config file without interrupting pending operations.
service foobar condrestart systemctl condrestart foobar.service Restarts if the service is already running.
service foobar status systemctl status foobar.service Tells whether a service is currently running.
ls /etc/rc.d/init.d/ ls /lib/systemd/system/*.service /etc/systemd/system/*.service Used to list the services that can be started or stopped
chkconfig foobar on systemctl enable foobar.service Turn the service on, for start at next boot, or other trigger.
chkconfig foobar off systemctl disable foobar.service Turn the service off for the next reboot, or any other trigger.
chkconfig foobar systemctl is-enabled foobar.service Used to check whether a service is configured to start or not in the current environment.
chkconfig foobar –list ls /etc/systemd/system/*.wants/foobar.service Used to list what levels this service is configured on or off
chkconfig foobar –add Not needed, no equivalent.

References

fedoraproject.org/wiki/Systemd
fedoraproject.org/wiki/SysVinit_to_Systemd_Cheatsheet

Distribution Documentation

Gentoo
Arch
Ubuntu
Debian

// CrashMAG

Self-signed certificate for Apache

These instructions are distribution agnostic. However I used CentOS during my tests, so file paths will match that of CentOS, RHEL, Scientific Linux and Fedora. For any other distribution you’ll have to look that up yourself.

The tools required are OpenSSL, Apache and mod_ssl for Apache. To accomplish this I had to run

# yum install mod_ssl

on my CentOS 5.6 box. Which already had Apache up and running.

Setting up a self-signed certificate using certificate and key

Generate your key and certificate

Most of these parameters explain themselves, see beneath for those who do not.

openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout website.key -out website.crt

-nodes
don’t encrypt the output key
-x509
output a x509 structure instead of a cert. req.

Copy the key and certificate

# cp website.key website.crt /etc/httpd/conf/

Set permissions and ownership on your key and certificate

This way nobody except root has read access.

chmod 440 /etc/httpd/conf/website.key /etc/httpd/conf/website.crt
chown root:root /etc/httpd/conf/website.key /etc/httpd/conf/website.crt

Alter the apache configuration file, also known as httpd.conf

Edit /etc/httpd/conf/httpd.conf with your favorite text editor, in my case, nano. Add the following text at the bottom of the file.

      <VirtualHost *:443>
        SSLEngine on
        # Change the next two lines according to where you've actually
        # stored the certificate and key files.
        SSLCertificateFile /etc/httpd/conf/website.crt
	SSLCertificateKeyFile /etc/httpd/conf/apache2/website.key

        ServerName domain.tld
        SSLOptions StrictRequire
        SSLProtocol all -SSLv2

        DocumentRoot /path/to/ssl/enabled/site
        <Directory /path/to/ssl/enabled/site/>
          SSLRequireSSL
          Order Deny,Allow
          Allow from All
        </Directory>
      </VirtualHost>

StrictRequire
This forces forbidden access when SSLRequireSSL or SSLRequire successfully decided that access should be forbidden. Usually the default is that in the case where a “Satisfy any” directive is used, and other access restrictions are passed, denial of access due to SSLRequireSSL or SSLRequire is overridden (because that’s how the Apache Satisfy mechanism should work.) But for strict access restriction you can use SSLRequireSSL and/or SSLRequire in combination with an “SSLOptions +StrictRequire”. Then an additional “Satisfy Any” has no chance once mod_ssl has decided to deny access.

Enable SSLv3 and TLSv1, but not SSLv2
SSLProtocol all -SSLv2

Setting up a self-signed certificate with the certificate and key in one file

Generate your key and certificate

Most of these parameters explain themselves, see beneath for those who do not.

openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout website.pem -out website.pem

-nodes
don’t encrypt the output key
-x509
output a x509 structure instead of a cert. req.

Copy the key and certificate

# cp website.pem  /etc/httpd/conf/

Set permissions and ownership on your key and certificate

This way nobody except root has read access.

chmod 440 /etc/httpd/conf/website.pem
chown root:root /etc/httpd/conf/website.pem

Alter the apache configuration file, also known as httpd.conf

Edit /etc/httpd/conf/httpd.conf with your favorite text editor, in my case, nano. Add the following text at the bottom of the file.

      <VirtualHost *:443>
        SSLEngine on
        # Change the next line according to where you've actually
        # stored the certificate and key file.
        SSLCertificateFile /etc/httpd/conf/website.pem

        ServerName domain.tld
        SSLOptions StrictRequire
        SSLProtocol all -SSLv2

        DocumentRoot /path/to/ssl/enabled/site
        <Directory /path/to/ssl/enabled/site/>
          SSLRequireSSL
          Order Deny,Allow
          Allow from All
        </Directory>
      </VirtualHost>

StrictRequire
This forces forbidden access when SSLRequireSSL or SSLRequire successfully decided that access should be forbidden. Usually the default is that in the case where a “Satisfy any” directive is used, and other access restrictions are passed, denial of access due to SSLRequireSSL or SSLRequire is overridden (because that’s how the Apache Satisfy mechanism should work.) But for strict access restriction you can use SSLRequireSSL and/or SSLRequire in combination with an “SSLOptions +StrictRequire”. Then an additional “Satisfy Any” has no chance once mod_ssl has decided to deny access.

Enable SSLv3 and TLSv1, but not SSLv2
SSLProtocol all -SSLv2

// CrashMAG

View information about your BIOS from Linux using dmidecode

To get at this information we will use a utility called “dmidecode”. dmidecode is a tool for dumping a computer’s DMI (some say SMBIOS) table contents in a human-readable format.

On CentOS/RHEL/Fedora you may run the following to install it.

# yum install dmidecode

On Arch Linux you may run

# pacman -S dmidecode

The following examples will allow you to see a few important parts of information such as;

  • The manufacturer of your motherboard
  • What type of motherboard you have
  • The version of the BIOS running on your motherboard

To view the manufacturer and what type of motherboard you have, run the following

dmidecode --type system

Example

# dmidecode 2.11
SMBIOS 2.4 present.

Handle 0x0001, DMI type 1, 27 bytes
System Information
        Manufacturer: Gigabyte Technology Co., Ltd.
        Product Name: GA-MA78G-DS3H
        Version:
        Serial Number:
        UUID: 4E2F4100-0000-0000-0000-0000FFFFFFFF
        Wake-up Type: Power Switch
        SKU Number:
        Family:

Handle 0x0034, DMI type 32, 11 bytes
System Boot Information
        Status: No errors detected

To view the version of your BIOS you may run the following

#dmidecode --type bios

Example

# dmidecode 2.11
SMBIOS 2.4 present.

Handle 0x0000, DMI type 0, 24 bytes
BIOS Information
        Vendor: Award Software International, Inc.
        Version: FA
        Release Date: 09/19/2008
        Address: 0xE0000
        Runtime Size: 128 kB
        ROM Size: 1024 kB
        Characteristics:
                ISA is supported
                PCI is supported
                PNP is supported
                APM is supported
                BIOS is upgradeable
                BIOS shadowing is allowed
                Boot from CD is supported
                Selectable boot is supported
                BIOS ROM is socketed
                EDD is supported
                5.25"/360 kB floppy services are supported (int 13h)
                5.25"/1.2 MB floppy services are supported (int 13h)
                3.5"/720 kB floppy services are supported (int 13h)
                3.5"/2.88 MB floppy services are supported (int 13h)
                Print screen service is supported (int 5h)
                8042 keyboard services are supported (int 9h)
                Serial services are supported (int 14h)
                Printer services are supported (int 17h)
                CGA/mono video services are supported (int 10h)
                ACPI is supported
                USB legacy is supported
                AGP is supported
                LS-120 boot is supported
                ATAPI Zip drive boot is supported
                BIOS boot specification is supported
                Targeted content distribution is supported

Handle 0x0029, DMI type 13, 22 bytes
BIOS Language Information
        Language Description Format: Long
        Installable Languages: 3
                n|US|iso8859-1
                n|US|iso8859-1
                r|CA|iso8859-1
        Currently Installed Language: n|US|iso8859-1

There’s also additional options to use with dmidecode. You probably also want to try the following to get an idea of what type of information you can get your hands on.

#dmidecode --type keyword
Valid type keywords are:
  bios
  system
  baseboard
  chassis
  processor
  memory
  cache
  connector
  slot

// CrashMAG

RHEL/Centos 5 minimal installation

There’s no option during the CentOS 5 install, for a minimal installation. The purpose is quite simple, to keep the attack surface as small as possible.

A minimal installation is performed by doing the following

  • During the category/task selection, deselect all package categories, and choose the “Customize now” option at the bottom of screen.
  • During the customized package selection, deselect everything ( including the Base group ).

This will yield you 234 packages with the Centos 5.5 installation media. I’ve attached a .txt file containing all the packages for your leisure.

Link: installed-packages

// CrashMAG

Configuring BIND DNS Server to listen only on a specific IP address

This is a short example driven howto on how you can configure BIND to listen on certain IP addresses which can also be an implicit network interface. IPv6 is also included in the examples. You could also say that this how you disable IPv6 for BIND/named, but it’s implicit to the operation.

listen-on default syntax

Note the “-v6” syntax for IPv6.

IPv4

listen-on port 53 { 127.0.0.1; };

IPv6

listen-on-v6 port 53 { ::1; };

you can also combine several IP addresses

listen-on port 53 { 127.0.0.1; 192.168.0.1; };

From the man page

listen-on [ port integer ] { address_match_element; ... };
listen-on-v6 [ port integer ] { address_match_element; ... };

To listen on all interfaces and IP addresses

listen-on { any;};
listen-on-v6 { any;};

That’s all. A few short tips.

// CrashMAG

Disabling email alerts for cron

Having the cron daemon send email alerts could be a useful feature, but it could also get very tiresome depending on your setup. To disable this feature do the following.

Edit /etc/crontab with your favorite text editor, modify or insert the following line

MAILTO=""

Should you have crontabs set up for different users, use

crontab -e

and insert/edit the relevant configuration parameter as seen above.

Or should you want to disable output for certain jobs you could add

0 1 5 10 * /path/script.sh &> /dev/null

// CrashMAG

Public key authentication with SSH. Both with and without a password.

This article will run through quick and easy examples for setting up public key authentication with SSH. I will include one example that requires a password and one that does not. Typically used for scripts.

I will assume you know why you want to either use the one or the other. Public key authentication can only be set up on a per user/system basis, keep that in mind.

Public key authentication without a password

This the least secure option. It all boils down to how well secured your private key is. (.ssh/id_dsa)

  1. Create a key pair. (Private & public key)
  2. Copy the public key to the remote system.
  3. Log on the remote system.

Create a key pair

[user@localsystem ~]$ ssh-keygen -t dsa

Here’s what you’ll see when you run through this procedure. (“Press [ENTER]” are my comments)

[user@localsystem ~]$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_dsa): Press [ENTER]
Created directory '/home/usr/.ssh'.
Enter passphrase (empty for no passphrase): Press [ENTER]
Enter same passphrase again: Press [ENTER]
Your identification has been saved in /home/user/.ssh/id_dsa.
Your public key has been saved in /home/user/.ssh/id_dsa.pub.
The key fingerprint is:
29:d1:34:6c:53:2b:96:e6:ea:28:fd:c5:3a:cb:0f:65 user@localsystem
The key's randomart image is:
+--[ DSA 1024]----+
|       .o..      |
|       o+o .     |
|      ..*..      |
|       = o       |
|      . E        |
|       *         |
|   .  o o        |
|  . .+.+         |
|   ...*+.        |
+-----------------+

Copy the public key to the remote system

[user@localsystem ~]$ ssh user@remotesystem

If you don’t set the permissions in this step SSH will refuse the public key even if it’s there due to bad ownership.

[user@remotesystem ~]$ mkdir .ssh
[user@remotesystem ~]$ touch .ssh/authorized_keys
[user@remotesystem ~]$ chmod -R u=rwx,go= .ssh
[user@remotesystem ~]$ exit
scp ~/.ssh/id_dsa.pub user@remotesystem:.ssh/authorized_keys

Enter your password when asked, and you’re done.

Log on the remote system

[user@localsystem ~]$ ssh user@remotesystem

Public key authentication with password

This is the route you want to go. Once done, you should also disable logins with passwords only. Do this by editing the /etc/ssh/sshd_config file and add/modify the following parameter “PasswordAuthentication no”. Also make sure “PubkeyAuthentication” is set to “yes”.

  1. Create a key pair. (Private & public key)
  2. Copy the public key to the remote system.
  3. Log on the remote system.

Create the key pair

[user@localsystem ~]$ ssh-keygen -t dsa

Here’s what you’ll see when you run through this procedure. (“[Your Password]” and “Press [ENTER]” are my comments)

[user@localsystem ~]$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_dsa): Press [ENTER]
Created directory '/home/usr/.ssh'.
Enter passphrase (empty for no passphrase): [Your Password]
Enter same passphrase again: [Your Password]
Your identification has been saved in /home/user/.ssh/id_dsa.
Your public key has been saved in /home/user/.ssh/id_dsa.pub.
The key fingerprint is:
29:d1:34:6c:53:2b:96:e6:ea:28:fd:c5:3a:cb:0f:65 user@localsystem
The key's randomart image is:
+--[ DSA 1024]----+
|       .o..      |
|       o+o .     |
|      ..*..      |
|       = o       |
|      . E        |
|       *         |
|   .  o o        |
|  . .+.+         |
|   ...*+.        |
+-----------------+

Copy the public key to the remote system

[user@localsystem ~]$ ssh user@remotesystem

If you don’t set the permissions in this step SSH will refuse the public key even if it’s there due to bad ownership.

[user@remotesystem ~]$ mkdir .ssh
[user@remotesystem ~]$ touch .ssh/authorized_keys
[user@remotesystem ~]$ chmod -R u=rwx,go= .ssh
[user@remotesystem ~]$ exit
scp ~/.ssh/id_dsa.pub user@remotesystem:.ssh/authorized_keys

Enter your password when asked, and you’re done.

Log on the remote system

[user@localsystem ~]$ ssh user@remotesystem

Tip

You can later change the password for your keys by using

[user@localsystem ~]$ ssh-keygen -p

// CrashMAG

Guide and hardning tips for RHEL/CentOS 5 from NSA

As I was looking to see if NSA had updated their guides for RHEL 6 and it turns out they haven’t. I decided it would be a good idea to post about them to give them some better coverage.

This is just a small tip of free and useful information in regards to securing your RHEL/CentOS installation. A lot of the information is general in nature and can therefore be applied to any Linux distribution. It’s definitely worth your time.

I take no credit, the credit goes to NSA for creating the documents to begin with.

Guide to the Secure Configuration of Red Hat Enterprise Linux 5
www.nsa.gov/ia/_files/os/redhat/rhel5-guide-i731.pdf

Red Hat Linux 5 Hardening Tips
www.nsa.gov/ia/_files/factsheets/rhel5-pamphlet-i731.pdf

I just love how just about every section starts with “Disable ‘insert your service here’ if possible…” 😉

// CrashMAG

Setting up sSMTP with GMail

Let me introduce you to the “extremely simple MTA to get mail off the system to a mailhub”. Particularly useful when you don’t want systems to have a full blown MTA installed. Such as Postfix, Exim or Sendmail. I find ssmtp extremely helpful on standalone servers that use Logwatch.

Getting this up and running requires 4 steps.

  • Installing SSMTP
  • Configuring SSMTP
  • Changing the MTA on your system
  • Testing

Installing the daemon, ssmtp.

Use your favorite package manager, in my example I’ll be using YUM. (Fedora/CentOS/RHEL/Scientific Linux). For Centos/RHEL/Scientific Linux 5.5 or 5.6 you need access to the EPEL repository to install sSMTP. Add EPEL to your system using the following command.

rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm

You can find eventual new links from http://download.fedora.redhat.com/pub/epel/5/i386/repoview/epel-release.html

yum install ssmtp

Configuring SSMTP

Edit /etc/ssmtp/ssmtp.conf with your favorite text editor. I’ll be using nano.

nano /etc/ssmtp/ssmtp.conf

Remove all the entries and replace it with the ones beneath.

root=insert_your_email_address here
mailhub=smtp.gmail.com:587
UseTLS=YES
UseSTARTTLS=YES
AuthUser=your_gmail_username_which_you'll_be_using_to_send
AuthPass=password

Changing the MTA

For CentOS/Fedora/RHEL

alternatives --config mta

Press the number that equals /usr/sbin/sendmail.ssmtp and you’re done.

Testing

I’m testing this using the verbose mode just to be able to see the dialogue with the Google SMTP server.

cat random_file | sendmail -v your_email_address

// CrashMAG