User:Tom/RHCE EX300

From RoggeWiki
Jump to navigation Jump to search

RHCSA & RHCE Red Hat Enterprise Linux 7: Training and Exam Preparation Guide (EX200 and EX300) third edition march 2015 by Asghar Ghori.

RHCE

Aandachtspunten

- selinux. - link aggregate. subnet gw. - limit ssh to two subnets. - scripting - ipv6 twee hosts. - portforwarding 1000 to 100 only for restricted subnet. - email two systems to another host - Kerberos. - - - - NFS. - SAMBA. - Apache - - - scripting. - iSCSI target. - iSCSI initiator. - Mariadb.

Hoofdstuk 14 Writing Shell Scripts

Indicate the shell in which the script will run

#!/bin/bash

Add a new path to the existing PATH setting.

#export PATH=$PATH:/usr/local/bin

Debug a shell script.

#bash -x /usr/local/bin/sysinfo.sh


set number       Number lines of files

Command line arguments $0 $1, $#, $*, $$

  • $0 scriptname
  • $1 first argument
  • $# # of arguments
  • $* all arguments
  • $$ PID of the script)
  1. ${10} for arguments above 9.
shift    Move command arguments one position to the left. During this move the value of the first argument is lost

echo -e  Enables interpretation of backslash escapes. See man echo for escape sequences.
read Var Read user input from the keyboard
$?       Exit code

test     Test conditions (man test) int1 -eq int2
if condition then action else action fi
if condition then action elif condition then action else action fi

Looping Statements

for do done
while do done
until do done

Test Conditions

case $var in 
     val1)
           ;;
     val2)
           ;;
     *)
           ;;
esac

See man bash for more details.

Hoofdstuk 15 Configuring Bonding, Teaming, IPv6 and Routing

Link aggregation is a technique by which two or more network interfaces are logically configured to provide higher performance using their combined bandwith and fault tolerance should all but one of them fail. Two common methodsfor link aggregation are bonding and teaming and both are supported natively in RHEL7.

Link Aggregation

Link aggregation is a term to combine the capabilities of two or more physical or virtual Ethernet network interfaces to function as a single network pipe. RHEL7 supports two link aggregation methods that are referred to as bonding and teaming.

Bonding and teaming can be configured using tools such as the Network Manager CLI or TUI or the GNOME Network Connections GUI.

Interface Bonding

Interface bonding provides the ability to bind two or more network interfaces together into a single logical bonded channel that acts as the master for all slave interfaces that are added to it. The support for bonding is integrated entirely into the kernel as a loadable module. This module is called bonding.

Configure Interface bonding by Editing Files

In this exercise you will add two new interfaces on 192.168.1.0/24 network to server1 and call them eth2 and eth3. Form a bond by creating configuration files and executing appropiate commands to activate. Reboot to verify bond activation. Assign hostname server1bond.example.org with alias serv1bond. Add IP and hostname to /etc/hosts.

Add two network devices to server1 using the virtual console for server1 on host1. Logon to server1 and tun the ip command to check the new interfaces.

[root@server1 ~]# ip addr
...
4: eth2: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master bond0 state UP qlen 1000
    link/ether 52:54:00:1f:65:38 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::5054:ff:fe1f:6538/64 scope link
       valid_lft forever preferred_lft forever
5: eth3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master team0 state UP qlen 1000
    link/ether 52:54:00:6a:f7:a4 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::5054:ff:fe6a:f7a4/64 scope link
       valid_lft forever preferred_lft forever
...
[root@server1 ~]#

The output indicates the presence of two new interfaces by the name eth2 and eth3.

Load the bonding driver called bonding in the kernel with the modprobe command if it is not already loaded. Verify with the modinfo command.

[root@server1 ~]# modprobe bonding
[root@server1 ~]# modinfo bonding
filename:       /lib/modules/3.10.0-327.22.2.el7.x86_64/kernel/drivers/net/bonding/bonding.ko
author:         Thomas Davis, tadavis@lbl.gov and many others
description:    Ethernet Channel Bonding Driver, v3.7.1
version:        3.7.1
license:        GPL
alias:          rtnl-link-bond
rhelversion:    7.2
srcversion:     49765A3F5CDFF2C3DCFD8E6
depends:
intree:         Y
vermagic:       3.10.0-327.22.2.el7.x86_64 SMP mod_unload modversions
signer:         CentOS Linux kernel signing key
sig_key:        A9:80:1A:61:B3:68:60:1C:40:EB:DB:D5:DF:D1:F3:A7:70:07:BF:A4
sig_hashalgo:   sha256
parm:           max_bonds:Max number of bonded devices (int)
parm:           tx_queues:Max number of transmit queues (default = 16) (int)
parm:           num_grat_arp:Number of peer notifications to send on failover event (alias of num_unsol_na) (int)
parm:           num_unsol_na:Number of peer notifications to send on failover event (alias of num_grat_arp) (int)
parm:           miimon:Link check interval in milliseconds (int)
parm:           updelay:Delay before considering link up, in milliseconds (int)
parm:           downdelay:Delay before considering link down, in milliseconds (int)
parm:           use_carrier:Use netif_carrier_ok (vs MII ioctls) in miimon; 0 for off, 1 for on (default) (int)
parm:           mode:Mode of operation; 0 for balance-rr, 1 for active-backup, 2 for balance-xor, 3 for broadcast, 4 for 802.3ad, 5 for balance-tlb, 6 for balance-alb (charp)
parm:           primary:Primary network device to use (charp )
parm:           primary_reselect:Reselect primary slave once it comes up; 0 for always (default), 1 for only if speed of primary is better, 2 for only on  active slave failure (charp)
parm:           lacp_rate:LACPDU tx rate to request from 802.3ad partner; 0 for slow, 1 for fast (charp)
parm:           ad_select:803.ad aggregation selection logic; 0 for stable (default), 1 for bandwidth, 2 for count (charp)
parm:           min_links:Minimum number of available links before turning on carrier (int)
parm:           xmit_hash_policy:balance-xor and 802.3ad hashing method; 0 for layer 2 (default), 1 for layer 3+4, 2 for layer 2+3, 3 for encap layer 2+3, 4 for encap layer 3+4 (charp)
parm:           arp_interval:arp interval in milliseconds (int)
parm:           arp_ip_target:arp targets in n.n.n.n form (array of charp)
parm:           arp_validate:validate src/dst of ARP probes; 0 for none (default), 1 for active, 2 for backup, 3 for all (charp)
parm:           arp_all_targets:fail on any/all arp targets timeout; 0 for any (default), 1 for all (charp)
parm:           fail_over_mac:For active-backup, do not set all slaves to the same MAC; 0 for none (default), 1 for active, 2 for follow (charp)
parm:           all_slaves_active:Keep all frames received on an interface by setting active flag for all slaves; 0 for never (default), 1 for always. (int)
parm:           resend_igmp:Number of IGMP membership reports to send on link failure (int)
parm:           packets_per_slave:Packets to send per slave in balance-rr mode; 0 for a random slave, 1 packet per slave (default), >1 packets per slave. (int)
parm:           lp_interval:The number of seconds between instances where the bonding driver sends learning packets to each slaves peer switch. The default is  1. (uint)
[root@server1 ~]#

Generate UUIDs for both new interfaces using the uuidgen command.

[root@server1 ~]# uuidgen eth2 
90454e94-3c7f-4e5f-8d04-5367fe8aaf96
[root@server1 ~]# uuidgen eth3
bcf28a1e-808e-4d0a-9e1e-0ab2fc01986e
[root@server1 ~]#

Create file /etc/sysconfig/network-scripts/ifcfg-bond0 for bond0 with the following settings:

[root@server1 network-scripts]# cat /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
NAME=bond0
TYPE=Bond
BONDING_MASTER=yes
BONDING_OPTS="mode=balance-rr"
ONBOOT=yes
BOOTPROTO=none
IPADDR=192.168.122.111
NETMASK=255.255.255.0
GATEWAY=192.168.122.1
IPV4_FAILURE=no
IPV6INIT=no
[root@server1 network-scripts]#

Create file ifcfg-eth2 and ifcfg-eth3 files in the /etc/sysconfig/network-scripts.

[root@server1 network-scripts]# cat /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
NAME=bond0
TYPE=Bond
BONDING_MASTER=yes
BONDING_OPTS="mode=balance-rr"
ONBOOT=yes
BOOTPROTO=none
IPADDR=192.168.122.111
NETMASK=255.255.255.0
GATEWAY=192.168.122.1
IPV4_FAILURE=no
IPV6INIT=no
[root@server1 network-scripts]# cat ifcfg-eth2
DEVICE=eth2
NAME=eth2
UUID=2e63ec5c-a82e-43ba-bdbe-5d43a18cc3c6
TYPE=Ethernet
ONBOOT=yes
MASTER=bond0
SLAVE=yes
[root@server1 network-scripts]# cat ifcfg-eth3
DEVICE=eth3
NAME=eth3
UUID=bbf8d1ab-7557-482f-b344-21e17fdb5eff
Type=Ethernet
ONBOOT=yes
MASTER=bond0
SLAVE=yes
[root@server1 network-scripts]#

Deactivate and activate bond0 with the ifdown and ifup command, verify with the ip addr command and perform a reboot to ensure the configuration survives a reboot.

[root@server1 ~]# ifdown bond0
[root@server1 ~]# ifup bond0 
[root@server1 ~]# ip addr
[root@server1 ~]# reboot

Open /etc/hosts and append the following entry.

[root@server1 ~]# vi /etc/hosts
192.168.1.110  server1bond.example.org server1bond
Configure Interface Bonding with NetworkManager CLI

The nmcli command is a NetworkManager tool that allows you to add, show, alter, delete, start and stop bonding and teaming interfaces and control and report their status.

The exercise will be done on server2 , the interface allocation will be done on host1. Two new interfaces eth2 and eth3 will be added to server2. Configure a bond and activate it using NetworkManager commands. Reboot to verify bond activation.

Check the operational status of the NetworkManager service.

[root@server2 ~]# systemctl status NetworkManager
● NetworkManager.service - Network Manager
   Loaded: loaded (/usr/lib/systemd/system/NetworkManager.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2016-07-03 23:21:46 CEST; 3 days ago
 Main PID: 703 (NetworkManager)
   CGroup: /system.slice/NetworkManager.service
           ├─703 /usr/sbin/NetworkManager --no-daemon
           └─895 /usr/bin/teamd -o -n -U -D -N -t team0 
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  (team0): IPv6 config waiting until carrie... on
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  (team0): device state change: ip-config -... 0]
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  (team0): device state change: ip-check ->... 0]
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  (team0): device state change: secondaries... 0]
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  NetworkManager state is now CONNECTED_GLOBAL
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  NetworkManager state is now CONNECTED_SITE
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  NetworkManager state is now CONNECTED_GLOBAL
Jul 03 23:21:51 server2 NetworkManager[703]: <info>  (team0): Activation: successful, device a...ed.
Jul 03 23:21:53 server2 NetworkManager[703]: <info>  Policy set 'eth0' (eth0) as default for I...NS.
Jul 03 23:21:55 server2 NetworkManager[703]: <info>  startup complete
Hint: Some lines were ellipsized, use -l to show in full.
[root@server2 ~]#

List available network interfaces including the ones just added.

[root@server2 ~]# nmcli dev status
DEVICE  TYPE      STATE      CONNECTION
bond0   bond      connected  bond0
eth0    ethernet  connected  eth0
eth1    ethernet  connected  bond-slave-eth1
eth2    ethernet  connected  bond-slave-eth2
eth3    ethernet  connected  eth3
eth4    ethernet  connected  eth4
team0   team      connected  team0
lo      loopbaack  unmanaged  --
[root@server2 ~]#

Load the bonding driver in the kernel with the modprobe command if it is not already loaded and verify with the modinfo command.

[root@server2 ~]# modprobe bonding
[root@server2 ~]# modinfo bonding
filename:       /lib/modules/3.10.0-327.18.2.el7.x86_64/kernel/drivers/net/bonding/bonding.ko
author:         Thomas Davis, tadavis@lbl.gov and many others
description:    Ethernet Channel Bonding Driver, v3.7.1
version:        3.7.1
license:        GPL
alias:          rtnl-link-bond
rhelversion:    7.2
srcversion:     49765A3F5CDFF2C3DCFD8E6
depends:
intree:         Y
vermagic:       3.10.0-327.18.2.el7.x86_64 SMP mod_unload modversions
signer:         CentOS Linux kernel signing key
sig_key:        EB:27:91:DE:1A:BE:A5:F9:5A:A5:BC:B8:91:E1:33:2B:ED:29:8E:5E
sig_hashalgo:   sha256
parm:           max_bonds:Max number of bonded devices (int)
parm:           tx_queues:Max number of transmit queues (default = 16) (int)
parm:           num_grat_arp:Number of peer notifications to send on failover event (alias of num_unsol_na) (int)
parm:           num_unsol_na:Number of peer notifications to send on failover event (alias of num_grat_arp) (int)
parm:           miimon:Link check interval in milliseconds (int)
parm:           updelay:Delay before considering link up, in milliseconds (int)
parm:           downdelay:Delay before considering link down, in milliseconds (int)
parm:           use_carrier:Use netif_carrier_ok (vs MII ioctls) in miimon; 0 for off, 1 for on (default) (int)
parm:           mode:Mode of operation; 0 for balance-rr, 1 for active-backup, 2 for balance-xor, 3 for broadcast, 4 for 802.3ad, 5 for balance-tlb, 6 for balance-alb (charp)
parm:           primary:Primary network device to use (charp)
parm:           primary_reselect:Reselect primary slave once it comes up; 0 for always (default), 1 for only if speed of primary is better, 2 for only on active slave failure (charp)
parm:           lacp_rate:LACPDU tx rate to request from 802.3ad partner; 0 for slow, 1 for fast (charp)
parm:           ad_select:803.ad aggregation selection logic; 0 for stable (default), 1 for bandwidth, 2 for count (charp)
parm:           min_links:Minimum number of available links before turning on carrier (int)
parm:           xmit_hash_policy:balance-xor and 802.3ad hashing method; 0 for layer 2 (default), 1 for layer 3+4, 2 for layer 2+3, 3 for encap layer 2+3, 4 for encap layer 3+4 (charp)
parm:           arp_interval:arp interval in milliseconds (int)
parm:           arp_ip_target:arp targets in n.n.n.n form (array of charp)
parm:           arp_validate:validate src/dst of ARP probes; 0 for none (default), 1 for active, 2 for backup, 3 for all (charp)
parm:           arp_all_targets:fail on any/all arp targets timeout; 0 for any (default), 1 for all (charp)
parm:           fail_over_mac:For active-backup, do not set all slaves to the same MAC; 0 for none (default), 1 for active, 2 for follow (charp)
parm:           all_slaves_active:Keep all frames received on an interface by setting active flag for all slaves; 0 for never (default), 1 for always. (int)
parm:           resend_igmp:Number of IGMP membership reports to send on link failure (int)
parm:           packets_per_slave:Packets to send per slave in balance-rr mode; 0 for a random slave, 1 packet per slave (default), >1 packets per slave. (int)
parm:           lp_interval:The number of seconds between instances where the bonding driver sends learning packets to each slaves peer switch. The default is 1. (uint)
[root@server2 ~]#

Add a logical interface called bond0 of type bond with connection name bond0, load balancing policy round-robin, IP address 192.168.122.112/24 and gateway 192.168.122.1

[root@server2 ~]# nmcli dev status
DEVICE  TYPE      STATE         CONNECTION
eth0    ethernet  connected     eth0
eth3    ethernet  connected     eth3
eth4    ethernet  connected     eth4
team0   team      connected     team0
eth1    ethernet  disconnected  --
eth2    ethernet  disconnected  --
lo      loopback  unmanaged     --
[root@server2 ~]# nmcli con add type bond con-name bond0 ifname bond0 mode balance-rr ip4 192.168.122.112/24 gw4 192.168.122.1
Connection 'bond0' (3a3657d8-189d-462f-bbfb-d76167dcf890) successfully added.
[root@server2 ~]#

This command has added a bond device and created /etc/sysconfig/network-scripts/ifcfg-bond0.

[root@server2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
BONDING_OPTS=mode=balance-rr
TYPE=Bond
BONDING_MASTER=yes
BOOTPROTO=none
IPADDR=192.168.122.112
PREFIX=24
GATEWAY=192.168.122.1
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=bond0
UUID=3a3657d8-189d-462f-bbfb-d76167dcf890
ONBOOT=yes
[root@server2 ~]#

Now add slave interfaces eth1 and eth2 to the master bond device bond0.

[root@server2 ~]# nmcli con add type bond-slave ifname eth1 master bond0
Connection 'bond-slave-eth1' (bfa37034-b685-409f-9e9e-23a7b13a4939) successfully added.
[root@server2 ~]# nmcli con add type bond-slave ifname eth2 master bond0
Connection 'bond-slave-eth2' (f5152103-78b3-49eb-baab-fe890305d85d) successfully added.
[root@server2 ~]#

This command has added eth1 and eth2 interfaces as slaves to bond0 and has created files ifcfg-bond-slave-eth1 and ifcfg-bond-slave-eth2 in directory /etc/sysconfig/network-scripts.

[root@server2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-bond-slave-eth1
TYPE=Ethernet
NAME=bond-slave-eth1
UUID=bfa37034-b685-409f-9e9e-23a7b13a4939
DEVICE=eth1
ONBOOT=yes
MASTER=bond0
SLAVE=yes
[root@server2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-bond-slave-eth2
TYPE=Ethernet
NAME=bond-slave-eth2
UUID=f5152103-78b3-49eb-baab-fe890305d85d
DEVICE=eth2
ONBOOT=yes
MASTER=bond0
SLAVE=yes
[root@server2 ~]#

Activate bond0.

[root@server2 ~]# nmcli con down bond0
Connection 'bond0' successfully deactivated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/8)
[root@server2 ~]# nmcli con up  bond0
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/11)
[root@server2 ~]#

And check the new connection and IP assignments.

 [root@server2 ~]# ip addr|grep bond0
3: eth1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master bond0 state UP qlen 1000
4: eth2: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master bond0 state UP qlen 1000
7: bond0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
    inet 192.168.122.112/24 brd 192.168.122.255 scope global bond0
[root@server2 ~]# nmcli con show
NAME             UUID                                  TYPE            DEVICE
eth3             0e87dd30-b785-4b68-ae9f-565478e3f136  802-3-ethernet  --
bond-slave-eth2  f5152103-78b3-49eb-baab-fe890305d85d  802-3-ethernet  eth2
eth4             4d91a659-3606-44c5-9291-ed5cff38776a  802-3-ethernet  --
eth3             8a11e510-aa77-496f-8acb-0adb7aef9a12  802-3-ethernet  eth3
team0            c8f6bad2-2700-40d2-8286-acc38e87f74e  team            team0
eth4             804f1ee0-0bbe-4fc5-b77b-d072462b9d51  802-3-ethernet  eth4
bond0            3a3657d8-189d-462f-bbfb-d76167dcf890  bond            bond0
bond-slave-eth1  bfa37034-b685-409f-9e9e-23a7b13a4939  802-3-ethernet  eth1
eth0             9086b45c-33a0-4f59-b402-2a63c37086f9  802-3-ethernet  eth0
[root@server2 ~]# nmcli con show --active
NAME             UUID                                  TYPE            DEVICE
bond-slave-eth2  f5152103-78b3-49eb-baab-fe890305d85d  802-3-ethernet  eth2
eth3             8a11e510-aa77-496f-8acb-0adb7aef9a12  802-3-ethernet  eth3
team0            c8f6bad2-2700-40d2-8286-acc38e87f74e  team            team0
eth4             804f1ee0-0bbe-4fc5-b77b-d072462b9d51  802-3-ethernet  eth4
bond0            3a3657d8-189d-462f-bbfb-d76167dcf890  bond            bond0
bond-slave-eth1  bfa37034-b685-409f-9e9e-23a7b13a4939  802-3-ethernet  eth1
eth0             9086b45c-33a0-4f59-b402-2a63c37086f9  802-3-ethernet  eth0
[root@server2 ~]#

Reboot and verify the connections again.

Interface Teaming

Interface teaming is introduced in RHEL7 as an additional choice to implement enhance throughput and fault tolerance at the network interface level. Teaming is a new implementation. Teaming handels the flow of network packets faster that bonding does.And, unline bonding, which is accomplished purely in the kernel space and provides no user control over its operation, teaming only requires the integration of the essential code into the kernel and the rest is implemented via the teamd daemon, which gives users the ability to control it with the teamdctl command.

Like bonding, teaming can be configured by either editing the files directly or using the NetworkManager CLI, TUI or Gnome Network GUI.


Configure Interface Teaming with Network Manager CLI

Add two new interfaces to server2 and call them eth3 and eth4. Configure a team using NetworkManager CLI and reboot to verfiy team activation. Assign the hostname an alias for the team IP address and run a ping from another server to confirm connectivity.

Add two virtual network devices to server'2.

Check the status of the NetworkManager service.

[root@server2 ~]# systemctl status NetworkManager
● NetworkManager.service - Network Manager
   Loaded: loaded (/usr/lib/systemd/system/NetworkManager.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2016-07-07 11:01:23 CEST; 3h 18min ago
 Main PID: 690 (NetworkManager)
   CGroup: /system.slice/NetworkManager.service
           ├─690 /usr/sbin/NetworkManager --no-daemon
           └─772 /usr/bin/teamd -o -n -U -D -N -t team0
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (eth1): device state change: ip-config ->... 0]
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (eth1): device state change: secondaries ... 0]
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (eth1): Activation: successful, device ac...ed.
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (bond0): link connected
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (eth2): device state change: config -> ip... 0]
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (bond0): enslaved bond slave eth2
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (eth2): Activation: connection 'bond-slav...ion
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (eth2): device state change: ip-config ->... 0]
Jul 07 11:35:46 server2 NetworkManager[690]: <info>  (eth2): device state change: secondaries ... 0]
Jul 07 11:35:47 server2 NetworkManager[690]: <info>  (eth2): Activation: successful, device ac...ed.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server2 ~]#

List all available network interfaces including the ones just added.

[root@server2 ~]# nmcli dev status
DEVICE  TYPE      STATE      CONNECTION
bond0   bond      connected  bond0
eth0    ethernet  connected  eth0
eth1    ethernet  connected  bond-slave-eth1
eth2    ethernet  connected  bond-slave-eth2
eth3    ethernet  connected  Wired connection 2
eth4    ethernet  connected  Wired connection 1
lo      loopback  unmanaged  --
[root@server2 ~]#

Load the teamdriver in the kernel and verify.

[root@server2 ~]# modprobe team
[root@server2 ~]# modinfo team
filename:       /lib/modules/3.10.0-327.18.2.el7.x86_64/kernel/drivers/net/team/team.ko
alias:          rtnl-link-team
description:    Ethernet team device driver
author:         Jiri Pirko <jpirko@redhat.com>
license:        GPL v2
rhelversion:    7.2
srcversion:     C59FD6905408120CA7C83CD
depends:
intree:         Y
vermagic:       3.10.0-327.18.2.el7.x86_64 SMP mod_unload modversions
signer:         CentOS Linux kernel signing key
sig_key:        EB:27:91:DE:1A:BE:A5:F9:5A:A5:BC:B8:91:E1:33:2B:ED:29:8E:5E
sig_hashalgo:   sha256
[root@server2 ~]#

Add a logical interface called ´´team0´´ of type team with connection name team0, IP address 192.168.122.122-24 and gateway 192.168.122.1

[root@server2 ~]# nmcli con add type team con-name team0 ifname team0 ip4 192.168.122.122/24 gw4 192.168.122.1
Connection 'team0' (7e4157b1-b416-4d59-a70a-d263c86d6419) successfully added.
[root@server2 ~]#

This command has added a bond device and created file /etc/sysconfig/network-scripts/ifcfg/team/.

[root@server2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-team0
DEVICE=team0
DEVICETYPE=Team
BOOTPROTO=none
IPADDR=192.168.122.122
PREFIX=24
GATEWAY=192.168.122.1
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=team0
UUID=7e4157b1-b416-4d59-a70a-d263c86d6419
ONBOOT=yes
[root@server2 ~]#

Add eth3 and eth4 interfaces as slaves to the team.

[root@server2 ~]# nmcli con add type team-slave con-name eth3 ifname eth3 master team0
Connection 'eth3' (b2dfeb9c-750f-4340-8b1c-11d1d8495380) successfully added.
[root@server2 ~]# nmcli con add type team-slave con-name eth4 ifname eth4  master team0
Connection 'eth4' (4e40798d-1530-4e12-8c8c-8a93994a2983) successfully added.
[root@server2 ~]#

This command has added interfaces eth3 and eth4 as slaves to team0 and has created files ifcfg-eth3 and ifcfg-eth4 in directory etc/sysconfig/network-scripts.

[root@server2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth3
NAME=eth3
UUID=b2dfeb9c-750f-4340-8b1c-11d1d8495380
DEVICE=eth3
ONBOOT=yes
TEAM_MASTER=team0
DEVICETYPE=TeamPort
[root@server2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth4
NAME=eth4
UUID=4e40798d-1530-4e12-8c8c-8a93994a2983
DEVICE=eth4
ONBOOT=yes
TEAM_MASTER=team0
DEVICETYPE=TeamPort
[root@server2 ~]#

Activate team0.

[root@server2 ~]# nmcli con up team0
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/27)
[root@server2 ~]#

Check the new connection and IP assignments.

[root@server2 ~]# ip addr|grep team
14: team0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
    inet 192.168.

Show the connection for the team and slaves.

[root@server2 ~]# nmcli con show|egrep 'team0|eth3|eth4' 
Wired connection 1  717124f9-86bf-4d4b-9883-4c3d54f4a2c5  802-3-ethernet  eth4
eth4                4e40798d-1530-4e12-8c8c-8a93994a2983  802-3-ethernet  --
eth3                b2dfeb9c-750f-4340-8b1c-11d1d8495380  802-3-ethernet  --
team0               7e4157b1-b416-4d59-a70a-d263c86d6419  team            team0
Wired connection 2  27b05974-258d-4ae1-9c0b-81d04ff85ca0  802-3-ethernet  eth3
[root@server2 ~]#

Get the details of the team devices.

[root@server2 ~]# teamnl team0 ports  Gaat kennelijk iets mis. Prima.
 6: eth4: up 0Mbit HD
 5: eth3: up 0Mbit HD
[root@server2 ~]#
[root@server2 ~]# teamdctl team0 state
setup:
  runner: roundrobin
ports:
  eth3
    link watches:
      link summary: up
      instance[link_watch_0]:
        name: ethtool
        link: up
        down count: 0
  eth4
    link watches:
      link summary: up
      instance[link_watch_0]:
        name: ethtool
        link: up
        down count: 0
[root@server2 ~]#

Add the following entry to the h/etc/hosts file.

192.168.122.122 server2t server2t.roggeware.nl

And reboot the system to verify persistence accross reboots.

IPv6

IPv6 is a 128-bit software address providing access to 2 power 128 addresses. IPv6 addresses contain eight colon-separated groups of four hexadecimal numbers.

Below the ip addr command outpt shows IPv6 address for configured interfaces.

[root@server2 ~]# ip addr|grep inet6
    inet6 ::1/128 scope host
    inet6 2602:306:cc2d:f591::b/64 scope global
    inet6 fe80::5054:ff:fe7b:595a/64 scope link
    inet6 fe80::5054:ff:feea:a5e0/64 scope link tentative dadfailed
    inet6 fe80::5054:ff:febe:9f27/64 scope link
[root@server2 ~]#

Managing IPv6

IPv6 can be assigned to interfaces using any of the network management tools available to su. Entries added with the ip command do not survice system reboots.

Configure and Test IPv6 Addresses

An IPv6 address is represented as eight groups of four hexadecimal digits, each group representing 16 bits (two octets). The groups are separated by colons (:). An example of an IPv6 address is:

   2001:0db8:85a3:0000:0000:8a2e:0370:7334

The hexadecimal digits are case-insensitive, but IETF recommendations suggest the use of lower case letters. The full representation of eight 4-digit groups may be simplified by several techniques, eliminating parts of the representation.

Leading zeroes

Leading zeroes in a group may be omitted.[1] Thus, the example address may be written as:

   2001:db8:85a3:0:0:8a2e:370:7334

Groups of zeroes

One consecutive group of zero value may be replaced with a single empty group using two consecutive colons (::).[1] Thus, the example address can be further simplified:

   2001:db8:85a3::8a2e:370:7334

The localhost (loopback) address, 0:0:0:0:0:0:0:1, and the IPv6 unspecified address, 0:0:0:0:0:0:0:0, are reduced to ::1 and ::, respectively.

This two-colon replacement may only be applied once in an address, because multiple occurrences would create an ambiguous representation.

Dotted-quad notation

During the transition of the Internet from IPv4 to IPv6 it is typical to operate in a mixed addressing environment, and for this purpose a special notation has been introduced to express IPv4-mapped and IPv4-compatible IPv6 addresses by writing the final 32 bits of an address in the familiar IPv4 dotted-quad notation. For example, the IPv4-mapped IPv6 address ::ffff:c000:0280 is usually written as ::ffff:192.0.2.128, thus expressing clearly the original IPv4 address that was mapped to IPv6. IPv6 addressen in adaper en hosts file. config met nmtui.

Routing

Routing is the process of choosing paths on the network along which to send network traffic. This process is implemented with the deployment of specialized hardware devices called routers.

When systems on two distinct networks communicate with each other, proper routes must be in place for them to be able to talk.

One of three rules is applied in the routing mechanism to determin the correct route.

  • If the source and destination systems are on the same network, the packet is sent directly to the desination system.
  • If the source and destination systems are on two different networks, all defined (static or dynamic) routes are tried one after the other. If a proper route is determined, the packet is forwarded to it, which then forwards the packet to the correct destination.
  • If the source and destination system are on two different networks but no routes are defined between them, the packet is forwarded to the defalt router (or the default gateway), which attempts to search for an appropiate route to the destination. If found, the packet is delivered to the destination system.
Routing Table

A routing table preserves information about available routes and their status. It may be built and updated dynamically or manually by adding or removing routes. The ip command can be used to view entries in the routing table on our RHEL7 system.

[root@atlas ~]# ip route
default via 192.168.1.254 dev enp3s0
169.254.0.0/16 dev enp3s0  scope link  metric 1002
169.254.0.0/16 dev enp4s1  scope link  metric 1004
192.168.1.0/24 dev enp3s0  proto kernel  scope link  src 192.168.1.100
192.168.1.0/24 dev enp4s1  proto kernel  scope link  src 192.168.1.101
192.168.2.0/24 dev virbr1  proto kernel  scope link  src 192.168.2.1
192.168.3.0/24 dev virbr2  proto kernel  scope link  src 192.168.3.1
192.168.122.0/24 dev virbr0  proto kernel  scope link  src 192.168.122.1
[root@atlas ~]#

Other commands, such as route, will display additional columns of information that include flags, references, use and iface.Common flags are U (route is up), H (destination is a host), G (route is a gateway).

[root@atlas ~]# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         router.home     0.0.0.0         UG    0      0        0 enp3s0
link-local      0.0.0.0         255.255.0.0     U     1002   0        0 enp3s0
link-local      0.0.0.0         255.255.0.0     U     1004   0        0 enp4s1
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 enp3s0
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 enp4s1
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 virbr1
192.168.3.0     0.0.0.0         255.255.255.0   U     0      0        0 virbr2
192.168.122.0   0.0.0.0         255.255.255.0   U     0      0        0 virbr0
[root@atlas ~]#
Managing Routes

Managing routes involves addign, modifying and deleting routes and setting the default route. The ip command, the NetworkManage UI, the Network Settings GUI or the Network Connections Gui can be used for route administration. Entries added with the ip command do not survive system reboots. Those added with the other tools stay persistent as they are saved in specific route-* files in the /etc/sysconfig/network-srcipts directory.

Add Static Routes Manually

Temporarily add a static route to network 192.168.3.0/24 via eth1 with gateway 192.168.0.1 and another to network 192.168.4.0/24 via team0 with gateway 192.168.2.1 using the ip command.

Add a static route.

[root@server1 ~]# ip route add 192.168.3.0/24 via 192.168.122.1 dev eth0


Add a static route to 192.168.4.0/24 via team0 with gateway 192.168.122.1.

[root@server1 ~]# ip route  add 192.168.4.0/24 via 192.168.122.1 dev team0

Show the routing table to validate the addition of the new routes.

[root@server1 ~]# ip route
default via 192.168.122.1 dev eth0 
169.254.0.0/16 dev eth0  scope link  metric 1002
169.254.0.0/16 dev team0  scope link  metric 1009
192.168.3.0/24 via 192.168.122.1 dev eth0
192.168.4.0/24 via 192.168.122.1 dev team0
192.168.122.0/24 dev eth0  proto kernel  scope link  src 192.168.122.101
192.168.122.0/24 dev team0  proto kernel  scope link  src 192.168.122.121
[root@server1 ~]#

Reboot the system and run ip route again to confirm the removal of the new routes.

create files route-eth1 and route-team0 in /etc/sysconfig/network-scripts and insert the following entries.

[root@server1 ~]# cat /etc/sysconfig/network-scripts/route-eth0
ADDRESS0=192.168.3.0
NETMASK0=255.255.255.0
GATEWAY0=192.168.122.1
[root@server1 ~]# cat /etc/sysconfig/network-scripts/route-team0
ADDRESS0=192.168.4.0
NETMASK0=255.255.255.0
GATEWAY0=192.168.122.1
[root@server1 ~]#

Have a look at script /etc/sysconfig/network-scripts/ifuproutes for the route-dev file.

Restart eth0 and team0 for the routes to take effect.

[root@server1 ~]# ifdown eth0; ifup eth0;
[root@server1 ~]# ifdown team0; ifup team0;
[root@server1 ~]#

Run the ip route command again to validate the presence of the new routes.

Delete both routes by removing ther entries from the routing table and deleting the configuration files.

[root@server1 ~]# ip route del 192.168.3.0/24 
[root@server1 ~]# ip route del 192.168.4.0/24
[root@server1 ~]# rm -f route-eth1 route-team0
[root@server1 ~]#

Confirm the deletion wiith ip route. You should not see the routes.

Commands

modprobe bonding       Add and remove modules from the kernel
modinfo bonding        Show information about a kernel module
uuidgen eth2           Generate UUIDs
systemctl status NetworkManager
nmcli dev status
nmcli con add type bond con-name bond0 ifname bond0 mode balance-rr ip4 192.168.122.112 gw4 192.168.122.1
nmcli con add type bond-slave ifname eth1 master bond0
nmcli con edit         X GUI.
nmcli con up bond0
nmcli con show 
nmtui               Indien NetworkManager aktief is
yum install teamd    software
modprobe team 
modinfo team
nmcli con add type team con-name team0 ifname team0 ip4 192.168.122.122/24 gw4 192.168.122.1
nmcli con add type team-slave con-name eth4 ifname eth4 master team0
nmtui 
nm-connection-editor    Graphical Network Administration Tool, including bonding and teaming
teamd
teamdctl
teamnl

IPv6 128bit 1204:bab1:21d1:bb43:23a1:9bde:87df:bac9
Zowel IPv4 als IPv6 adressen kunnen op een adapter gezet worden.
ping6
RIP    Routing Information protocol
OSPF   Open Shortest Path First
ip route, route, netstat -rn
ip route add
ip route del

Files

/etc/sysconfig/network-scripts/ifcfg-bond0
                              /ifcfg-eth2
                              /ifcfg-eth3

Hoofdstuk 16 Synchronizing Time with NTP

The Network Time Protocol service maintains the clock on the system and keeps it synchronized with a more accurate and reliable source of time.

Understanding Network Time Protocol

Network Time Protocol (NTP) is a networking protocol for synchronizing the system clock with timeservers that are physically closer and redundant for high accuracy and reliability. NTP supports both client-server and peer-to-peer configurations with an option too user either public-key or symmetric-key cryptographgy for authentication.

The NTP daemon, called ntpd, uses the UDP protocl over well-known port 123 and it runs on all participating servers, peers and clients.

Time Source

A time source is any device that acts as a provider of time to other devices. The most accurate source of time is provided by atomic clocks that are deployed around the globe. Atomic clocks uses Universal Time, Coordinated (UTC) for time accuracy. When choosing a time source for a network, preference should be given to the one that is physically close and takes the least amount of time to send and receive NTP packets.

Local System Clock

You can arrange for one of the RHEL systems to function as a provider of time using its own clock. This requires the maintenance of correct time on this server either manually of automatically via the cron daemon. This server has no way of synchronizing itself with a more reliable and precise external time source. using a local clock as a timeserver with reliance on its own clock is the least recommended option.

Internet-Based Public Timeserver

Several public time servers are available (visit www.ntp.org for a list) are available via the internet. To use a time source, you may need to open a port in the firewall to allow NTP traffic to pass through. Internet-based timeservers are spread around the world and are typically operated by government agencies, research organizations and universities.

Radio/Atomic Clock

A radio clock is regarded as the most accurate provider of time. A radio clock receives time updates from one or more atomic clocks. Global Positioning System (GPS), National Istitue of science and Technology (NIST) radio station WWVB broadcasts in the Americas and DCF77 radio broadcasts in Europe are some popular radio clock methods.

NTP Roles

A role is a function that a system performs from an NTP standpoint. A system can be configured to assume one or more of the following roles.

Primary NTP Server

A primary NTP server gets time from one of the time sources mentioned above and provides time to one or more secondary servers or clients, or both. It can also be configured to broadcast time to seconary servers and clients.

Secondary NTP Server

A secondary NTP server receives time from a primary server or directly from one of the time sources mentioned above. It can be used to provide time to a set of clients to offload the primary, or for redundancy.

NTP Peer

An NTP peer provides time to an NTP server and receives time from it. All peers work at the same stratum level and all of them are considered equally reliable. Both primary and secondary servers can be peers of each other.

NTP Client

An NTP client receives time from either a primary or a secondary server. A client can be configured in one of the following ways.

  • As a polling client that contacts a defined NTP server directly for time synchronization.
  • As a broadcast client that listens to time broadcasts by an NTP server. The NTP server must be configured in the broadcast modei order for a broadcast client to be able to bind to it. A broadcast NTP configuration cannot span the local subnet.
  • A multicast client operates in a similar fashion as a broadcast client; however it is able to span the local subnet. The NTP server must be configured in the multicast mode in order for a client to work with it.
  • A manycast client automatically discovers manycast NTP servers and uses the ones with the best performance. The NTP server must be configured in the manycast mode in order for a manycast client to work with it.

Stratum Levels

There are different types of time sources available to synchronize the system time. These time sources are categorized hierarchically into multiple levels ,w hich are referred to as stratum levels based on their distance from the reference clock.

The reference clocks operate at stratum level 0. Besides stratum 0, there are fifteen addional stratum levels that range between 1 and 15. A stratum 0 device cannot be used on the network directly. It is attached to one of the computers via an RS-232 connection, and then that computer is configured to operate at stratum 1. Servers function at stratum 1 are called time servers (or primary time servers) and they can be set up to provide time to stratum 2 servers over a network via NTP packets. Similarly, a stratum 3 server can be configured to synchronize its time with a stratum 2 server, and so on. Servers sharing the smae stratum can be configured as peers to exchange time updates with each other.

Managing Network Time Protocol

This section discusses the management tasks including installing the NTP software, configuring an NTP server, peer and client, configuring a broadcast NTP server and client using a combiantion of manual file editing and commands and testing the configuraions

NTP Packages and Utilities

There is only one required software package that needs to be installed on the system for NTP. This package is called "ntp" and includes all the necessary support to configure the system as an NTP server, peer or client. Additionally a package called "ntpdate" may also be installed to get access to a command that is used to update the system with an NTP server without the involvement of the ntpd daemon.

[root@server1 ~]# yum list installed |grep ^ntp
ntp.x86_64                            4.2.6p5-22.el7.centos.2        @updates
ntpdate.x86_64                        4.2.6p5-22.el7.centos.2        @updates
[root@server1 ~]#

These packages bring several administration commands, some of which are described below.

  • ntpdate Updates the system date and time immediately. Deprecated. User ntpd -q instead.
  • ntpq Queries the NTP daemon.
  • ntpd NTP daemon program that must run on a system to use it as a server, peer or client.
  • ntpstat Shows time synchronization status.

NTP Configuration File

The key configuration file is called /etc/ntp.conf. This file can be modified by hand. This file is the only file that needs to be modified for NTP server, peer or client.

Use Pre-Defined NTP Polling Client

By default, the NTP software comes pe-configured for use as an NTP client. The configuration file /etc/ntp.conf already has four public NTP server entries. You will activate the NTP service and checkk to ensure that is is functional.

Install the NTP software.

[root@server2 ~]# yum install ntp
Package ntp-4.2.6p5-22.el7.centos.2.x86_64 already installed and latest version
Nothing to do
[root@server2 ~]#

Ensure that the public NTP entries are in /etc/ntp.conf.

[root@server2 ~]# grep ^server /etc/ntp.conf
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
server 3.centos.pool.ntp.org iburst
[root@server2 ~]#

Enable the ntpd daemon to autostart at reboots.

[root@server2 ~]# systemctl enable ntpd
Created symlink from /etc/systemd/system/multi-user.target.wants/ntpd.service to /usr/lib/systemd/system/ntpd.service.
[root@server2 ~]#

Start the ntp service and check its status.

[root@server2 ~]# systemctl start ntpd
[root@server2 ~]# systemctl status ntpd
â ntpd.service - Network Time Service
   Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2016-07-08 17:40:49 CEST; 6s ago
  Process: 3821 ExecStart=/usr/sbin/ntpd -u ntp:ntp $OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 3822 (ntpd)
   CGroup: /system.slice/ntpd.service
           ââ3822 /usr/sbin/ntpd -u ntp:ntp -g
Jul 08 17:40:49 server2 ntpd[3822]: Listen normally on 7 lo ::1 UDP 123
Jul 08 17:40:49 server2 ntpd[3822]: Listen normally on 8 eth0 2602:306:cc2d:f591::b UDP 123
Jul 08 17:40:49 server2 ntpd[3822]: Listen normally on 9 eth0 fe80::5054:ff:fe7b:595a UDP 123
Jul 08 17:40:49 server2 ntpd[3822]: Listening on routing socket on fd #26 for interface updates
Jul 08 17:40:49 server2 systemd[1]: Started Network Time Service.
Jul 08 17:40:49 server2 ntpd[3822]: 0.0.0.0 c016 06 restart
Jul 08 17:40:49 server2 ntpd[3822]: 0.0.0.0 c012 02 freq_set kernel -0.061 PPM
Jul 08 17:40:50 server2 ntpd[3822]: 0.0.0.0 c61c 0c clock_step +1.408934 s
Jul 08 17:40:52 server2 ntpd[3822]: 0.0.0.0 c614 04 freq_mode
Jul 08 17:40:53 server2 ntpd[3822]: 0.0.0.0 c618 08 no_sys_peer
[root@server2 ~]#

Check whether the system is bound to the NTP servers.

[root@server2 ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
+ntp2.edutel.nl  80.94.65.10      2 u    6   64    3    9.663    1.286   1.046
+db.communibase. 193.79.237.14    2 u    7   64    3   10.360    3.902   0.940
 ntp.newfx.nl    .STEP.          16 u    -   64    0    0.000    0.000   0.000
*37.97.195.195   193.79.237.14    2 u   10   64    3   11.719    4.271   1.141
[root@server2 ~]#

The above output indicates that the ntpd daemon on server2 is currently bound to an NTP server 37.97.195.195.

Configure NTP Server and Polling Client

Exercise for server1 (NTP server) and server2 (NTP client). Server1 will be set up as an NTP server and sync time to its local clock and provide time to clients on the network. Server2 will be configured as a polling client to obtain time from server1.

Install the NTP software on server1.

[root@server1 ~]# yum install ntp
Package ntp-4.2.6p5-22.el7.centos.2.x86_64 already installed and latest version
Nothing to do
[root@server1 ~]#

Comment out all server entries from /etc/ntp.conf and add a new one with 127.127.1.0.

[root@server1 ~]# grep server /etc/ntp.conf
# Use public servers from the pool.ntp.org project.
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
server 127.127.1.0
[root@server1 ~]#

Enable the NTP service to start at reboots, open port 123 and start the ntpd daemon.

[root@server1 ~]# systemctl enable ntpd
[root@server1 ~]# firewall-cmd --permanent --add-service ntp
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# systemctl stop ntpd 
[root@server1 ~]# systemctl start ntpd
[root@server1 ~]# systemctl status ntpd
â ntpd.service - Network Time Service
   Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Sat 2016-07-09 11:33:35 CEST; 6s ago
   Process: 27745 ExecStart=/usr/sbin/ntpd -u ntp:ntp $OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 27746 (ntpd)
   CGroup: /system.slice/ntpd.service
           ââ27746 /usr/sbin/ntpd -u ntp:ntp -g
Jul 09 11:33:34 server1 ntpd[27746]: Listen normally on 7 eth0 2602:306:cc2d:f591::a UDP 123
Jul 09 11:33:34 server1 ntpd[27746]: Listen normally on 8 team0 fe80::5054:ff:fe6a:f7a4 UDP 123
Jul 09 11:33:34 server1 ntpd[27746]: Listen normally on 9 eth3 fe80::5054:ff:fe6a:f7a4 UDP 123
Jul 09 11:33:34 server1 ntpd[27746]: Listen normally on 10 eth1 fe80::5054:ff:fe1f:6538 UDP 123
Jul 09 11:33:34 server1 ntpd[27746]: Listen normally on 11 eth0 fe80::5054:ff:fe18:5661 UDP 123
Jul 09 11:33:34 server1 ntpd[27746]: Listening on routing socket on fd #28 for interface updates
Jul 09 11:33:34 server1 ntpd[27746]: 0.0.0.0 c016 06 restart
Jul 09 11:33:34 server1 ntpd[27746]: 0.0.0.0 c012 02 freq_set kernel 14.150 PPM
Jul 09 11:33:35 server1 systemd[1]: Started Network Time Service.
Jul 09 11:33:35 server1 ntpd[27746]: 0.0.0.0 c515 05 clock_sync
[root@server1 ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*LOCAL(0)        .LOCL.           5 l    9   64    1    0.000    0.000   0.000
[root@server1 ~]#

The above output shows that the ntpd daemon on server1 is using its own clock as the timeserver.

Disable the server directives in the /etc/ntp.conf file on server2 and add the following to user server1 as a time server.

[root@server2 ~]# grep server /etc/ntp.conf
# Use public servers from the pool.ntp.org project.
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
server server1.roggeware.nl
[root@server2 ~]#

Restart ntpd and check the status of binding with ntpq.

[root@server2 ~]# systemctl restart ntpd
[root@server2 ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*server1         LOCAL(0)         6 u    3   64    1    0.524   -2.423   0.000
[root@server2 ~]# ntpstat
synchronised to NTP server (192.168.122.101) at stratum 7
   time correct to within 8389 ms
   polling server every 64 s
[root@server2 ~]#

Configure an NTP Peer

Configure host1 as a peer of TNP server server1 and test the configuration.

Install the NTP software on host1.

[root@atlas ~]# yum install ntp
Resolving Dependencies
--> Running transaction check
---> Package ntp.x86_64 0:4.2.6p5-22.el7.centos.1 will be updated
---> Package ntp.x86_64 0:4.2.6p5-22.el7.centos.2 will be an update
--> Processing Dependency: ntpdate = 4.2.6p5-22.el7.centos.2 for package: ntp-4.2.6p5-22.el7.centos.2.x86_64
--> Running transaction check
---> Package ntpdate.x86_64 0:4.2.6p5-22.el7.centos.1 will be updated
---> Package ntpdate.x86_64 0:4.2.6p5-22.el7.centos.2 will be an update
--> Finished Dependency Resolution
Dependencies Resolved
=================================================================================================================
 Package               Arch                 Version                                  Repository             Size
=================================================================================================================
Updating:
 ntp                   x86_64               4.2.6p5-22.el7.centos.2                  updates               544 k
Updating for dependencies:
 ntpdate               x86_64               4.2.6p5-22.el7.centos.2                  updates                84 k
Transaction Summary
=================================================================================================================
Upgrade  1 Package (+1 Dependent package)

[root@atlas ~]#

Comment out all server directives from /etc/ntp.conf and add the peer directive with hostname server1.

[root@atlas ~]# egrep "peer|server" /etc/ntp.conf
restrict default nomodify notrap nopeer noquery
# Use public servers from the pool.ntp.org project.
#server 0.nl.pool.ntp.org iburst
#server 1.nl.pool.ntp.org iburst
#server 2.nl.pool.ntp.org iburst
#server 3.nl.pool.ntp.org iburst
peer server1.roggeware.nl
[root@atlas ~]#

Enable the NTP service and open UDP port 123 in the firewall.

[root@atlas ~]# systemctl enable ntp
[root@atlas ~]# firewall-cmd --permanent --add-service ntp
success
[root@atlas ~]# firewall-cmd --reload
success
[root@atlas ~]#

Restart the ntpd daemon and check its status.

[root@atlas ~]# systemctl restart ntpd
[root@atlas ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*server1         LOCAL(0)         6 u    6   64    1    0.544    0.140   0.000
[root@atlas ~]#

Configure a Broadcast Server and Client

server2 Will be set up as an NTP client to obtain time from the original four NTP servers and broadcast time to devices on the local network. Open UDP port 123 in the firewall to allow NTP traffic to pass through. Configure host1 as a broadcast client to get time from the broadcast. Assumption that NTP software is already installed.

Ensure that the server directives as defined in /etc/ntp.conf on server2 are as shown below:

server 0.nl.pool.ntp.org iburst
server 1.nl.pool.ntp.org iburst
server 2.nl.pool.ntp.org iburst
server 3.nl.pool.ntp.org iburst
broadcast 192.168.1.255

Enable the NTP server, add UDP port 123 to the firewall configuration, restart ntpd and check its status.

[root@server2 ~]# systemctl enable ntpd
[root@server2 ~]# firewall-cmd --permanent --add-service ntp
success
[root@server2 ~]# firewall-cmd --reload
success
[root@server2 ~]# systemctl restart ntpd
[root@server2 ~]# ntpq -p
    remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 pomo.komputilo. 195.13.23.5      3 u    1   64    1   15.685    0.132   0.000
 +ntp1.monshouwer 193.79.237.14    2 u    1   64    1   13.622    0.610   0.215
 services.freshd .STEP.          16 u    -   64    0    0.000    0.000   0.000
*146.185.139.19  193.67.79.202    2 u    1   64    1   11.285    1.905   0.000
 192.168.1.255   .BCST.          16 u    -   64    0    0.000    0.000   0.000
[root@server2 ~]#

The above output shows that the ntpd daemon on server2 is using the public NTP as the provider of time. It also shows that this server is broadcasting time to devices on the 192.168.1.0 network.

Disable the server directoives in the /etc/ntp.conf file on host1 and add broadcastclient and disable directives as shown.

#server 0.nl.pool.ntp.org iburst
#server 1.nl.pool.ntp.org iburst
#server 2.nl.pool.ntp.org iburst
#server 3.nl.pool.ntp.org iburst
#peer server1.roggeware.nl
broadcastclient                 # broadcast client
[root@atlas ~]# systemctl restart ntpd
[root@atlas ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*server2b        195.191.113.251  3 u   52   64   16    0.058   -0.064   0.086
[root@atlas ~]#

Overview of System-Config-Date Tool

The NTP client service can be set up using the graphical System-Config-Date tool. This tool is not installed by default.

Run the following to install it.

[root@atlas ~]# yum install system-config-date
Package system-config-date-1.10.6-2.el7.centos.noarch already installed and latest version
Nothing to do
[root@atlas ~]#

In order to run this tool, execute system-config-date in an X terminal window. A graphical window will show up were you can configure NTP servers and let the ntpdate command run immediately.

Update System Clock Manually

You can run the ntpdate command anytime to bring the system clock close to the time on an NTP server. The NPT service must not to be running in order for this command to work. Run ntpdate manually and specify either the hostname or the IP address of the remote time server.

For example, to bring the clock on server1 at par with the clockon server2, tun the following on server1.

[root@server1 ~]# systemctl stop ntpd
[root@server1 ~]# ntpdate server2
11 Jul 16:43:26 ntpdate[7284]: adjust time server 192.168.122.102 offset -0.255794 sec
[root@server1 ~]# systemctl start ntpd
[root@server1 ~]#

Querying NTP Servers

Command ntpq is used for querying NTP servers. Option -p prints a list of NTP servers known to the system along with a summary of their status.

[root@server2 ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
xwww.elandsgrach 193.67.79.202    2 u   82  256  377    6.703  -104.78   7.887
+x.ns.gin.ntt.ne 249.224.99.213   2 u   23  256  377   10.932   -0.341   3.268
 tt52.ripe.net   .INIT.          16 u    - 1024    0    0.000    0.000   0.000
*ntp1.monshouwer 193.79.237.14    2 u  101  256  377   12.794    9.196   2.620
 192.168.122.255 .BCST.          16 u    -   64    0    0.000    0.000   0.000
[root@server2 ~]#

This command produces ten columns of output.

  • remote Shows IP addresses or hostnames of NTP servers and peers. Each IP/hostname may be preceeded by one of the following characters:
    • * Indicated the current source of synchronisation
    • # Indicates the server selected for synchronisation,but distance exceeds the maximum.
    • o Displays the server selected for synchronisation.
    • + Indicates the system considered for synchronisation.
    • x Designated false ticker by the intersection algorythm.
    • . Indicates the systems picked up from the end of the candidate list.
    • - Indicated the systems not considered for synchronisation.
    • blank. Indicates the server rejected because of high stratum level or failed sanity checks.
  • refid Shows a reference ID for each time server.
  • st Displays stratum level. 16 indicates an invalid level.
  • t Shows available types; l=local, u=unicast, m=multicast, b=broadcast and -=netaddr.
  • when Displays time, in seconds, when a response was last received from the server.
  • poll Shows a polling interval. Default is 64 seconds.
  • reach Expresses the number of successful attempts to reach the server.
    • 001 Most recent probe was answered.
    • 357 One probe was unanswered.
    • 377 All recent probes were answered.
  • delay Indicates a length of time in milliseconds, it took for the reply packet to return in response to a query sent to the server.
  • offset Shows a time difference, in milliseconds, between server and client clocks.
  • jitter Displays a variation of offset measurement between samples. This is an error-bound estimate.
man ntp.conf.
ntpd used UDP over well-known port 123
NTP roles: Primary NTP server, Secondary NTP server, NTP peer, NTP client.
NTP Client can be configured as a polling, broadcast, multicast or manycast client.
Packages ntp and ntpdate
Commands ntpdate, ntpq, ntpd and ntpstat.
NTP Configuration file /etc/ntp.conf.
Key directives driftfile, logfile restrict, server, peer, broadcast, crypto, includefile, keys. See man ntp.conf.
firewall-cmd --permanent --add-service ntp;reload
Package system-config-date for system-config-date tool
Output ntpq -p is important

Commands
ntpdc 
ntpdate 
ntpstat

Hoofdstuk 17 Working with Firewalld and Kerberos

Firewalld is a new way of interacting with iptables rules. It allows the administrator to enter new security rules and activate them during runtime without disconnecting existing connections.

Network Address Translation is a feature that enables a system on the internal network to access the Internet via an intermediary device. IP masquerading, in contrast, enables more than one system on the internal network to access the Internet via an intermediary device. In either case, the systems IP address on the internal network are concealed from the outside world and only one IP address is seen. That one IP address is of the intermediary device.

Kerberos is a client/server authentication protocol that works on the basis of digital tickets to allow systems communication over non-secure networks. Kerberos uses a combination of Kerberos services and encrypted keys for the implmentation of secure authentication mechanism on the network.

Understanding Firewalld

RHEL7 has introduced an improved mechanism for security rules management called firewalld (dynamic firewall). One of the primary reasosn for adding the support for firewalld is its ability to activate changes dynamically without disconnecting established connections.

Firewalld supports the D-BUS implementation and it brings the concept of network zones to manage the security rules. Everything in firewalld is related to one or more zones. Iptables does not have a daemon process, as it is purely implemented in the kernel space. We can activate either of the two at a time.

Firewalld configuration is stored in the /etc/firewalld directory and can be customized as desired. The userland management tools are the command firewall-cmd and the graphical tool called firewall-config. In addition, it allows us to create and modify zone and service information by hand and activate them as desired.

Network Zones

Firewalld zones classify incoming network traffic for simplified firewall management. Zones define the level of trust for network connections based on principles such as a source IP or network interface for incoming network traffic. The inbound traffic is checked against zone settings and it is handled appropiately as per configured rules in the zone. Each zone can have its own list of services and ports that are opened or closed.

Firewalld proves nine zones by default. These system-defined zones file are XML-formatted and are located in the /usr/lib/firewalld/zones directory. By default, the public zone is the default zone.

[root@atlas zones]# ls -l /etc/firewalld/zones/
total 32
-rw-r--r--. 1 root root 424 Oct 16  2015 home.xml
-rw-r--r--. 1 root root 424 Oct  6  2015 home.xml.old
-rw-r--r--. 1 root root 415 Oct 16  2015 internal.xml
-rw-r--r--. 1 root root 415 Oct  6  2015 internal.xml.old
-rw-r--r--. 1 root root 590 Jul 11 22:35 public.xml
-rw-r--r--. 1 root root 562 Jul 11 14:23 public.xml.old
-rw-r--r--. 1 root root 342 Oct 16  2015 work.xml
-rw-r--r--. 1 root root 342 Oct  6  2015 work.xml.old
[root@atlas zones]#

Each zone on the system may have one or more interfaces assigned to it. When a service request arrives, firewalld checks whether it is already defined in a zone by the IP it is originated from (the source network) or the network interface it is coming through. If yes, it binds the request with that zone, otherwise it binds the request with the default zone.

Services

Services are an essential component of firewalld zones. In fact, using services in zones is the preferred method for firewalld configuration and management. Service configuration is stored in separate XML files located in the /usr/lib/firewalld/services and /etc/firewalld/services directories for system- and user-defined services respectively. The configuration files in the user-defined service directory take precedence over the ones located in the other directory.

A service typically contains a port number, protocol, and an IP address.

Ports can also be defined directly without using the service configuration technique. In essence, defining network ports does not require the presence of a service or a service configuration file.

[root@atlas services]# ls -l /usr/lib/firewalld/services
total 216
-rw-r-----. 1 root root 412 Nov 20  2015 amanda-client.xml
-rw-r-----. 1 root root 320 Nov 20  2015 bacula-client.xml
-rw-r-----. 1 root root 346 Nov 20  2015 bacula.xml
-rw-r-----. 1 root root 305 Nov 20  2015 dhcpv6-client.xml
-rw-r-----. 1 root root 234 Nov 20  2015 dhcpv6.xml
-rw-r-----. 1 root root 227 Nov 20  2015 dhcp.xml
-rw-r-----. 1 root root 346 Nov 20  2015 dns.xml
...
-rw-r-----. 1 root root 211 Nov 20  2015 transmission-client.xml
-rw-r-----. 1 root root 593 Nov 20  2015 vdsm.xml
-rw-r-----. 1 root root 475 Nov 20  2015 vnc-server.xml
-rw-r-----. 1 root root 310 Nov 20  2015 wbem-https.xml
[root@atlas services]#

Ports

Network ports in firewalld may also be defined directly without using the service configuration technique. In essence, defining network ports does not require the presence of a service or a service configuration file. The same two tools, firewall-cmd and firewall-config, used for zone configuration are also used for port configuration.

Direct Interface and Rich Language

Firewalld offers the possibility to pass security rules directly to iptables using the direct interface mode, but these rules are not persistent. To address this problem, Firewalld provides the support for a high-level language, called the rich language, that allows us to build complex rules without the knowledge of iptables syntax. The rich language rules are also built and managed with the same two management tools, firewall-cmd and firewall-config.

Rich Language uses several elements to set rules and name them. These elements includes a source address or range with an appropiate netmask, destination address or range, service name, port number or range, protocol, masquerade (enable or disable); forward-port (destination port or range to divert traffic to), log and loglevel, and an action (accept, reject, drop).

Network Address Translation and IP Masquerading

Network Address Translation (NAT) refers to the process of altering the IP address of a source or destination network that is enclosed in a datagram packet header while it passes through a device that supports this type of modification. In other words, NAT allows a system on the internal network (home or corporate network) to access an external network (the Internet) using a single registered IP address configured on an intermediary device (a router or firewall).

IP masquerading is a variant of NAT and it allows several systems on the internal network (192.168.0.0) to access the Internet using that single IP of the intermediary device.

Port Forwarding

We may have to redirect inbound traffic to a port to access an application servicing on that port on our internal system. This port is defined on the intermediary device (router or netfilter module on RHEL). For example, to allow external access to the HTTP service listening on port 8080 on an internal system, both internal system IP and port number are defined on the intermediary device to ensure inbound requests are forwarded to the desired destination. This feature is referred to as port forwarding or port mapping.

Managing Firewalld

Firewalld offers a single command called firewall-cmd to view and manage firewall rulesets including those for masquerading and port forwarding. It gives us the ability to enter rules either on a persistent or temporary basis. The persistent rules are recorded in appropiate files and are not activated unless the firewalld service is restarted or instructed to reload the rules from the files.

The firewall-cmd has many opions to view and manage its own operation, as well as view and administer zones, services, ports, masquerading, port forwarding and so on.

Some samples:

To display whether the service is running.

[root@server1 ~]# firewall-cmd --state
running
[root@server1 ~]#

The systemctl command may also be used for this purpose.

[root@server1 ~]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2016-07-11 17:46:52 CEST; 2 days ago
 Main PID: 698 (firewalld)
   CGroup: /system.slice/firewalld.service
           └─698 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
Jul 11 17:46:48 server1 systemd[1]: Starting firewalld - dynamic firewall daemon...
Jul 11 17:46:52 server1 systemd[1]: Started firewalld - dynamic firewall daemon.
[root@server1 ~]#

To restart the service.

[root@server1 ~]# systemctl restart firewalld
[root@server1 ~]#

To reload the permanent rules without interrupting existing persistent connections.

[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]#

Firewalld Command Options for Zone Management

firewall-cmd --get-default-zone or --set-default-zone       Displays/sets the default zone for both runtime and persistent configurations.
             --get-active-zones or --get-zones              Displays all active / available zones.
             --list-all         or --list-all-zones         Lists details for the default zone or all zones.
             --new-zone         or --delete-zone            Adds a new zone or delets a zone
             --permanent                                    Used to make a permanent change. Creates or updates appropiate zone files.
             --zone                                         Used for operations on a non-default zone.
View and Manage Zones

This exercise demonstrates the use of various zone management options. Display the default, summary and details for all active and available zones. Display details for a specific zone. Add a new zone, confirm the creation and delte this zone.

Display the current default zone setting.

root@server1 ~]# firewall-cmd --get-default-zone
public
[root@server1 ~]#

Display a list of all active zones along with the interfaces assigned to them.

[root@server2 ~]# firewall-cmd --get-active-zones
public
  interfaces: bond0 eth0 eth1 eth2 eth3 eth4 team0
[root@server2 ~]#

Display details for all active zones.

[root@server2 ~]# firewall-cmd --list-all
public (default, active)
  interfaces: bond0 eth0 eth1 eth2 eth3 eth4 team0
  sources:
  services: dhcpv6-client http iscsitarget ntp smtp ssh
  ports: 514/tcp
  masquerade: no
  forward-ports:
  icmp-blocks:
  rich rules:
[root@server2 ~]#

Display a list of all available zones.

[root@server2 ~]# firewall-cmd --get-zones
block dmz drop external home internal public trusted work
[root@server2 ~]#

Display details for all available zones.

[root@server2 ~]# firewall-cmd --list-all-zones
block
  interfaces:
  sources:
  services:
  ports:
  masquerade: no
  forward-ports:
  icmp-blocks:
  rich rules:
dmz
  interfaces:
  sources:
  services: ssh
  ports:
  masquerade: no
  forward-ports:
  icmp-blocks:
  rich rules: 
...
public (default, active)
 interfaces: bond0 eth0 eth1 eth2 eth3 eth4 team0
 sources:
 services: dhcpv6-client http iscsitarget ntp smtp ssh
 ports: 514/tcp
 masquerade: no
 forward-ports:
 icmp-blocks:
 rich rules:
[root@server2 ~]#

Display details for a specific zone.

[root@server2 ~]# firewall-cmd --list-all --zone external
external
  interfaces:
  sources:
  services: ssh
  ports:
  masquerade: yes
  forward-ports:
  icmp-blocks:
  rich rules:
[root@server2 ~]#

Add a new zone called testzone and show its file contents.

[root@server1 ~]# firewall-cmd --new-zone testzone --permanent
success
[root@server1 ~]# cat /etc/firewalld/zones/testzone.xml
<?xml version="1.0" encoding="utf-8"?>
<zone>
</zone>
[root@server1 ~]#

Remove the testzone and confirm the deletion of the corresponding file.

[root@server1 ~]# firewall-cmd --delete-zone testzone --permanent
success
[root@server1 ~]# cat /etc/firewalld/zones/testzone.xml
cat: /etc/firewalld/zones/testzone.xml: No such file or directory
[root@server1 ~]#

Change the default zone to external and verify.

[root@server1 ~]# firewall-cmd --set-default-zone external
success
[root@server1 ~]# firewall-cmd --get-default-zone
external
[root@server1 ~]# firewall-cmd --get-default
external
[root@server1 ~]#

The default zone information is registered in the /etc/firewalld/firewalld.conf file. grep for the DefaultZone to confirm the new setting.

[root@server1 ~]# grep DefaultZ /etc/firewalld/firewalld.conf
DefaultZone=external
[root@server1 ~]#

Reset the default zone value to the public zone and confirm.

[root@server1 ~]# firewall-cmd --set-default-zone public
success
[root@server1 ~]# firewall-cmd --get-default-zone
public
[root@server1 ~]#

Firewall Command Options for Service Management

firewall-cmd --get-services                   Displays available services.              
             --list-services                  List services for a zone.
             --query-services                 Tells wether a service is added.
             --add-service                    Adds a service to the zone.
             --remove-service                 Removes a service from a zone.
             --new-service                    Adds a new service.
             --delete-service                 Deletes an existing service.
             --zone                           Used for operations on a non-default zone.
View and Manage Services

Tis exercise will demonstrate the use of various service management options. Display all services, list all services for default and internal zones, query whether the tftp service is available. Add a new service and remove this service.

List all available services.

[root@server1 ~]# firewall-cmd --get-services
RH-Satellite-6 amanda-client bacula bacula-client dhcp dhcpv6 dhcpv6-client dns freeipa-ldap
freeipa-ldaps freeipa-replication ftp high-availability http https imaps ipp ipp-client ipsec
iscsi-target kerberos kpasswd ldap ldaps libvirt libvirt-tls mdns mountd ms-wbt mysql nfs ntp
openvpn pmcd pmproxy pmwebapi pmwebapis pop3s postgresql proxy-dhcp radius rpc-bind rsyncd 
samba samba-client smtp ssh telnet tftp tftp-client transmission-client vdsm vnc-server wbem-https
[root@server1 ~]#

List all services defined in the default (public) and internal zones.

[root@server1 ~]# firewall-cmd --list-service
dhcpv6-client dns http https mysql nfs ntp openvpn samba ssh
[root@server1 ~]# firewall-cmd --zone internal --list-service
dhcpv6-client ipp-client mdns samba-client ssh
[root@server1 ~]#

Query whether the tftp service is available in public and work zones.

[root@server1 ~]# firewall-cmd  --query-service tftp
no
[root@server1 ~]# firewall-cmd  --query-service tftp --zone work
no
[root@server1 ~]#

Create a service template for a new service called testservice and check the file.

[root@server1 ~]# firewall-cmd --new-service testservice --permanent
success
[root@server1 ~]# cat /etc/firewalld/services/testservice.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
</service>
[root@server1 ~]#

Modify the testservice.xml and include the following.

[root@server1 services]# cat /etc/firewalld/services/testservice.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
<short>testservice</short>
<description>Custom testservice</description>
<port protocol="tcp" port="11111"/>
</service>
[root@server1 services]#

Add the testservice to the work zone and activate it.

[root@server1 services]# firewall-cmd --add-service testservice --zone work --permanent
success
[root@server1 services]# firewall-cmd --reload
success
[root@server1 services]#

List all services for the work zone to confirm the presence and activation of the new service.

[root@server1 services]# firewall-cmd --zone work --list-services
dhcpv6-client ipp-client ssh testservice
[root@server1 services]#

Remove the testservice service from the work zone and then delete it from the system.

[root@server1 services]# firewall-cmd --remove-service testservice --zone work --permanent
success
[root@server1 services]# firewall-cmd --delete-service testservice --permanent
success
[root@server1 services]#

Reload the rules and list all services for the workzone to verify the deletion.

[root@server1 services]# firewall-cmd --list-services --zone work
dhcpv6-client ipp-client ssh
[root@server1 services]#

Firewall Command Options for Port Management

Viewing and managing firewalld ports involves several tasks that can be performed with the firewall-cmd command. Several options are available.

firewall-cmd --list-ports                     Lists ports added to a zone.
             --add-port                       Adds a port to a zone.
             --remove-port                    Removes a port from a zone.
             --query-port                     Checks whether a port is added to a zone.
             --permanent                      Used with the add and remove options for persistence.
             --zone                           Used for operations on a non-default zone.
View and Manage Ports

This exercise will demonstrate the use of various port management options. Display all ports for the default zone and query whether TCP port 53 is added to the DMZ zone. Add TCP port 53 to the default zone persistenly and UDP port range 1000-1010 to the work zone temporarily. Finally, remove port 53 and port range 1000-1010 from the respective zones.

Display ports defined for the default zone.

[root@server1 ~]# firewall-cmd --list-ports
8989/tcp
[root@server1 ~]#

Query whether TCP port 53 is added to the dmz zone.

[root@server1 ~]# firewall-cmd --zone dmz --query-port=53/tcp
no
[root@server1 ~]#

Add TCP port 53 to the default (public) zone permanently and activate it.

[root@server1 ~]# firewall-cmd --permanent --zone public --add-port=53/tcp
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --zone public --query-port=53/tcp
yes
[root@server1 ~]# firewall-cmd --list-ports
8989/tcp 53/tcp
[root@server1 ~]#

Add UDP port range 1000 to 1010 to the work zone temporarily and confirm the addition.

[root@server1 ~]# firewall-cmd --zone work --add-port=1000-1010/udp
success
[root@server1 ~]# firewall-cmd --list-ports --zone=work
1000-1010/udp
[root@server1 ~]#


Remove temporary port range 1000-1010 from the work zone and confirm.

[root@server1 ~]# firewall-cmd --remove-port=1000-1010/udp --zone work
success
[root@server1 ~]# firewall-cmd --list-ports --zone=work
[root@server1 ~]#

Remove port 53 from the default zone permanently and confirm.

[root@server1 ~]# firewall-cmd --remove-port=53/tcp --permanent
success
[root@server1 ~]# firewall-cmd --list-ports
8989/tcp 53/tcp
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-ports
8989/tcp
[root@server1 ~]#

Firewall Command Options for Using Rich Language Rules

Viewing and managing firewalld rich rules involves several teasks that can be performend with the firewall-cmd command. Several options are available.

firewall-cmd --list-rich-rules         List rich rules added to a zone.
             --add-rich-rule           Adds a rich rule to a zone.
             --remove-rich-rule        Removes a rich rule from a zone.
             --query-rich-rule         Checks whether a rich rule is added to a zone.
             --permanent               Used with the add and remove options.
             --zone                    Used for operations on a non-default zone.

For each permanent change, the corresponding zone file is updated in the /etc/firewalld/zonesdirectory.

Manage Rules Using Rich Language

In this exercise you will add a persistent rule to the default zone and a temporary rich rule to the dmz with a twenty-four hour validity. List the added rules. Last, you will remove both rich rules and confirm.

Add a persistent rich rule to the default zone to allow inbound HTTP access from network 192.168.3.0/24. This rule should log messages with prefix "HTTP Allow rule" at the info level.

[root@server1 ~]# firewall-cmd --add-rich-rule 'rule family="ipv4" source address="192.168.3.0/24" \
service name="http" log prefix="HTTP Allow Rule" level="info" accept' --permanent
success
[root@server1 ~]## firewall-cmd --reload
success
[root@server1 ~]#


Display the code added to the default zone file for this permanent rule.

[root@server1 ~]# cat /etc/firewalld/zones/public.xml
<?xml version="1.0" encoding="utf-8"?>
<zone>
  <short>Public</short>
  <description>For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
  <service name="samba"/>
  <service name="http"/>
  <service name="dns"/>
  <service name="ntp"/>
  <service name="dhcpv6-client"/>
  <service name="mysql"/>
  <service name="nfs"/>
  <service name="ssh"/>
  <service name="https"/>
  <service name="openvpn"/>
  <port protocol="tcp" port="8989"/>
  <rule family="ipv4">
    <source address="192.168.3.0/24"/>
    <service name="http"/>
    <log prefix="HTTP Allow Rule" level="info"/>
    <accept/>
  </rule>
</zone>
[root@server1 ~]#

Add a temporary rich rule to the dmx zone to reject inbound telnet access from network 192.168.4.0/24. This rule should log messages with a prefix "Telnet Access Denied"at the info level and should automatically expire after remain in place for 24 hours.

[root@server1 ~]# firewall-cmd --add-rich-rule 'rule family="ipv4" source address="192.168.4.0/24" \
service name="telnet" log prefix="Telnet Access Denied" level="info" reject' \ 
--timeout="86400"  --zone dmz
success
[root@server1 ~]#

Display both rich rules.

[root@server1 ~]# firewall-cmd --list-rich-rules
rule family="ipv4" source address="192.168.3.0/24" service name="http" log prefix="HTTP Allow Rule" level="info" accept
[root@server1 ~]# firewall-cmd --list-rich-rules --zone dmz 
rule family="ipv4" source address="192.168.4.0/24" service name="telnet" log   prefix="Telnet Access Denied" level="info" reject
[root@server1 ~]#


Remove both rules.

[root@server1 ~]# firewall-cmd --remove-rich-rule 'rule family="ipv4" source address="192.168.3.0/24" service name="http" log prefix="HTTP Allow Rule" level="info" accept' --permanent
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]#

Confirm the deletion of both rules.

[root@server1 ~]# firewall-cmd --list-rich-rules
[root@server1 ~]# firewall-cmd --list-rich-rules --zone dmz
[root@server1 ~]#

Firewalld Command Options for Masquerade Management

Viewing and managing firewalld masquerading involves several tasks that can be performed with the firewall-cmd command. Several options are available.

firewall-cmd --add-masquerade                  Adds a masquerade to a zone.
             --remove-masquerade               Removes a masquerade from a zone.
             --query-masquerade                Checks whether a masquerade is added to a zone.
             --permanent                       Used with the add and remove options for persistence.
             --zone                            Used for operations on a non-default zone.

For each permanent change, the corresponding zone file is updated in the /etc/firewalld/zones directory.

Add and Remove Masquerading

This exercise will use internal and external zones. It is assumed that the internal zone has eth1 (192.168.0.111) and the external zone has team0 (192.168.2.110) interfaces added.

Add masquerading support to the external zone:
[root@server1 ~]# firewall-cmd --add-masquerade --zone external
success
[root@server1 ~]#

Query on the external zone to confirm the setting.

[root@server1 ~]# firewall-cmd --query-masquerade --zone external
yes
[root@server1 ~]#


Remove masquerading from the external zone.

[root@server1 ~]# firewall-cmd --remove-masquerade --zone external
success
[root@server1 ~]# firewall-cmd --query-masquerade --zone external
no
[root@server1 ~]#


Firewalld Command Options for Port Forwarding

Viewing and managing firewalld port forwarding involves several tasks that can be performed with the firewall-cmd command. Several options are available.

firewall-cmd --list-forward-ports              List all forwarded ports for a zone.
             --add-forward-port                Adds a port to a zone to forward traffic to.
             --remove-forward-port             Removes a forwarded port from a zone.
             --query-forward-port              Checks whether a port is set for forwarding in a zone.
             --permanent                       Used with the add and remove options for persistence.
             --zone                            Used for operations on a non-default zone.

For each permanent change, the corresponding zone file is updated in the /etc/firewalld/zones directory.

Add and Remove Port Forwarding

In this exercise, masqueradin will be enabled on the external zone first and then demonostrate the use of various port forwarding opions. Forward inbound traffic to a local port, ftp traffic to a range of ports, smtp traffic to a different IP and tftp traffic to a port on a different IP permanently. Activate the rules and display them. Finally, remove all port forwarding rules configured in this exercise.

Enable masquerading on the external zone.

[root@server1 ~]# firewall-cmd  --zone external --add-masquerade
success
[root@server1 ~]#

Forward inbound telnet traffic to port 1000 on the same system.

[root@server1 ~]# firewall-cmd --zone external --add-forward-port port=23:proto=tcp:toport=1000 --permanent
success
[root@server1 ~]#

Forward inbound ftp traffic to port range 1001 to 1005 on the same system:

[root@server1 ~]# firewall-cmd --add-forward-port port=ftp:proto=tcp:toport=1001-1005 --zone external --permanent
success
[root@server1 ~]#

Forward inbound smtp traffic to the same port number but to IP 192.168.0.121:

[root@server1 ~]# firewall-cmd --add-forward-port port=smtp:proto=tcp:toaddr=192.168.1.100 --zone external --permanent
success
[root@server1 ~]#

Forward inbound tftp traffic to 192.168.0.121:1010

[root@server1 ~]# firewall-cmd --add-forward-port port=tftp:proto=tcp:toport=1010:toaddr=192.168.0.121 --zone external --permanent
success
[root@server1 ~]#

Activate and display the persistent rules.

[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-forward-ports
[root@server1 ~]# firewall-cmd --list-forward-ports --zone external
port=25:proto=tcp:toport=:toaddr=192.168.1.121
port=21:proto=tcp:toport=1001-1005:toaddr=
port=69:proto=tcp:toport=1010:toaddr=192.168.0.121
port=25:proto=tcp:toport=:toaddr=192.168.1.100
port=23:proto=tcp:toport=1000:toaddr=
[root@server1 ~]#

Remove all port forwarding rules added to the external zone. Reload and confirm deletion.

[root@server1 ~]# firewall-cmd --zone external --list-forward-port
port=25:proto=tcp:toport=:toaddr=192.168.1.121
port=21:proto=tcp:toport=1001-1005:toaddr=
port=69:proto=tcp:toport=1010:toaddr=192.168.0.121
port=25:proto=tcp:toport=:toaddr=192.168.1.100
port=23:proto=tcp:toport=1000:toaddr=
[root@server1 ~]# firewall-cmd --zone external --permanent --remove-forward-port  port=25:proto=tcp:toport=:toaddr=192.168.1.121
success
[root@server1 ~]# firewall-cmd --zone external --permanent --remove-forward-port port=21:proto=tcp:toport=1001-1005:toaddr=
success
[root@server1 ~]# firewall-cmd --zone external --permanent --remove-forward-port port=69:proto=tcp:toport=1010:toaddr=192.168.0.121
success
[root@server1 ~]# firewall-cmd --zone external --permanent --remove-forward-port port=25:proto=tcp:toport=:toaddr=192.168.1.100
success
[root@server1 ~]# firewall-cmd --zone external --permanent --remove-forward-port port=23:proto=tcp:toport=1000:toaddr=
success
[root@server1 ~]# firewall-cmd --zone external --list-forward-port  
port=25:proto=tcp:toport=:toaddr=192.168.1.121
port=21:proto=tcp:toport=1001-1005:toaddr=
port=69:proto=tcp:toport=1010:toaddr=192.168.0.121
port=25:proto=tcp:toport=:toaddr=192.168.1.100
port=23:proto=tcp:toport=1000:toaddr=
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --zone external --list-forward-port
port=25:proto=tcp:toport=:toaddr=192.168.1.100
port=69:proto=tcp:toport=1010:toaddr=192.168.0.121
port=21:proto=tcp:toport=1001-1005:toaddr=
[root@server1 ~]# firewall-cmd --zone external --permanent --remove-forward-port port=25:proto=tcp:toport=:toaddr=192.168.1.100
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --zone external --list-forward-port
[root@server1 ~]#

Notice that forward rules added with named service, also must be deleted with named service. Add ftp can only be removed with port=ftp, not with port=21.

Firewalld Command Summary

firewall-config   Firewalld GUI configuration tool.
firewall-cmd --state, --get-default-zone, --get-active-zones, --get-zones, --list-all, --list-all-zones 
             --list-all -zone public, 
             --net-zone testzone --permanent, --delete-zone testzone --permanent
             --get-services
             --list-services
             --query-service
             --list-ports --add-port --remove-port --query-port --permanent --zone
             --list-rich-rules --add-rich-rule --remove-rich-rule --query-rich-rule --permanent --zone
             --add-masquerade --remove-masquerade --query-masquerade --permanent --zone
             --list-forward-ports --add-forward-port --remove-forward-port query-forward-port --permanent --zone

Firewalld Files

firewall-config             Firewalld GUI configuration tool.
/etc/firewalld              Firewalld configuration files.
/etc/firewalld/zones        User-defines zones.
/etc/firewalld/services     User-defined services.
/usr/lib/firewalld/zones    System-defined zones.
/usr/lib/firewalld/services Service configuration.
/var/log/messages
/var/log/secure

Understanding and Managing Kerberos

The default user authentication scheme employed in RHEL and most other operation systems requires a user to enter their password at each login attempt and at each use of a remote service, such as rlogin, rcp, rsh, telnet, ftp, NFS and Samba.

Kerberos is a network authentication protocol that presents a secure mechanism using a blend of secret-key cryptography and a thrusted third party to authenticate users to services running on remote servers.

The Kerberos authentication system mechanism surrounds a central administration server that generates, issues, and validates digital identities for users and systems within its administrative domain. A user is initially granted a master ticket that is used to identify the user to that central server. When the user needs to access a service that runs on a remote server within the administrative domain, the user's master ticket is presented to the central server as a proof of identity, along with a request to allow access to the remote service. Upon validation of the user's identity, the central server provides the user with another ticket that is used as an authorization to access that particular remote service. The user forwards this new ticket to the remote service to gain access.

Both master and additional tickets are stored locally on the client system. For each subsequent access attempt to this service, the stored service ticket is used for identification and authentication, eliminating the need for password transmission over the network.

Kerberos uses port 88 for general communication and port 749 for the administration of Kerberos database via commands such as kadmin and kpasswd. Kerberos may be configured to use either TCP oor UDP protocol. The Kerberos ticketing system relies heavily on resolving hostnames and on accurate timestamps to issue and expire tickets. Therefore it requires adequate clock synchronisation and a working DNS or an accurate /etc/hosts too function correctly.

[root@server1 ~]# grep -i kerberos /etc/services
kerberos        88/tcp          kerberos5 krb5  # Kerberos v5
kerberos        88/udp          kerberos5 krb5  # Kerberos v5
kpasswd         464/tcp         kpwd            # Kerberos "passwd"
kpasswd         464/udp         kpwd            # Kerberos "passwd"
kerberos-adm    749/tcp                         # Kerberos `kadmin' (v5)
kerberos-adm    749/udp                         # kerberos administration
kerberos-iv     750/udp         kerberos4 kerberos-sec kdc loadav
kerberos-iv     750/tcp         kerberos4 kerberos-sec kdc rfile
krb524          4444/tcp        nv-video        # Kerberos 5 to 4 ticket xlator
krb524          4444/udp        nv-video        # Kerberos 5 to 4 ticket xlator
afs3-kaserver   7004/tcp                        # AFS/Kerberos authentication service
afs3-kaserver   7004/udp                        # AFS/Kerberos authentication service
# Kerberos (Project Athena/MIT) services
# Note that these are for Kerberos v4, and are unregistered/unofficial.  Sites
kerberos_master 751/udp         pump            # Kerberos authentication
kerberos_master 751/tcp         pump            # Kerberos authentication
passwd_server   752/udp         qrh             # Kerberos passwd server
krbupdate       760/tcp         kreg ns         # Kerberos registration
kpop            1109/tcp                        # Pop with Kerberos
knetd           2053/tcp        lot105-ds-upd   # Kerberos de-multiplexor
# Kerberos 5 services, also not registered with IANA
krb5_prop       754/tcp         tell            # Kerberos slave propagation
eklogin         2105/tcp        minipay         # Kerberos encrypted rlogin
kamanda         10081/tcp       famdc           # amanda backup services (Kerberos)
kamanda         10081/udp       famdc           # amanda backup services (Kerberos)
kftp-data       6620/tcp                # Kerberos V5 FTP Data
kftp-data       6620/udp                # Kerberos V5 FTP Data
kftp            6621/tcp                # Kerberos V5 FTP Control
kftp            6621/udp                # Kerberos V5 FTP Control
ktelnet         6623/tcp                # Kerberos V5 Telnet
ktelnet         6623/udp                # Kerberos V5 Telnet
[root@server1 ~]#

Terminology

Several key Kerberos terms need to be comprehended before going into further detail.

  • Authentication: The proces of verifying the identity of a user or service.
  • Authentication Service (AS): A service that runs on the Key Distribution Center (KDC) server to authenticate clients and issue initial tickets.
  • Client: A user or service (suchs as NFS or Samba) that requests for the issuance of tickets to use network services.
  • Credentials: A ticket along with relevant encryption keys.
  • Principal: A verified client (user or service) that is recorded in the KDC database and to which the KDC can assign tickets.
  • Realm: The administrative territory of a KDC, with one or more KDCs and several principals.
  • Service Host: A system that runs a kerberized service that clients can use.
  • Session key: An encrypted key that is used to secure communication among clients, KDCs and service hosts.
  • Service Ticket: An encrypted digital certificate used to authenticate a uuser to a specific network service. It is issued by the TGS after validating a user's TGT and it contains a session key, the principal name, and expiration time and more.
  • Ticket Granting Service (TGS): A service that runs on the KDC to generate and issue service tickets to clients.
  • Ticket Granting Ticket (TGT): An initial encrypted digital certificate that is used to identify tha client to TGS at the time of requesting service tickets. It is issued by the AS after validationg the client's presence in the KDC database.

How Kerberos Authenticates Clients

The Kerberos authentication process can be separated into three parts; an initial stage of getting a TGT (passport), a service stage to obtain a service ticket (visa) and access the service (travel to the visa issuing country).

A user contacts the AS for initial authentication via the kinit command. The AS asks for the user's password, validates it and generates a TGT for the user. The AS also produces a session key using the user's password. The AS returns the credentials (TGT plus session key) to the user. The credentials are saved in the clients credential cache.

Later, when the user needs to access a service running on a remote service host, they send the TGT and the session key to the TGS asking to grant the desired access. The TGS verfies the user's credentials by decrypting the TGT and assembles a service ticket for the desired service and encrypts it with the hosts secret key. It transmits the service ticket to the user along with a session key. The user stores the service ticket in their credential cache. The user presents these credentials to the service host, which decrypts the service ticket with its secret key and validates the users identity and the authorisation to access the service. The user is then allowed to access the service.

Kerberos Packages and Utilities

There are two software packages that provide Kerberos server and client functionality. These packages are krb5-server and krb5-workstation. Several tools become available after the Kerberos software is installed. Find some of the commands below.

kinit        Obtains and caches TGT.
kdestroy     Destroys tickets stored in credential cache.
klist        List cached tickets.
kpasswd      Changes a principal's password.
kadmin       Administers Kerberos  database via the kadmind daemon.
kadmin.local Same as kadmin, but performs operations directly on the KDC database.

Configure a Client to Authenticate Using Kerberos

Install the required package with #yum install krb5-workstation and ensure that /etc/krb5.conf has the following directives set:

[root@server1 ~]# yum install krb5-workstation
Package krb5-workstation-1.13.2-12.el7_2.x86_64 already installed and latest version
Nothing to do
[root@server1 ~]#

Ensure that file /etc/krb5.conf has the following directives set.

[libdefaults]
  dns_lookup_realm = false              <---
  dns_lookup_kdc = false                <---
  ticket_lifetime = 24h
  renew_lifetime = 7d
  forwardable = true
  rdns = false
  default_realm = EXAMPLE.COM           <---
  default_ccache_name = KEYRING:persistent:%{uid}
[realms]
  EXAMPLE.COM = {
  kdc = server2.example.com
  admin_server = server2.example.com
  }
[domain_realm]
  .example.com = EXAMPLE.COM
  example.com = EXAMPLE.COM

Login as the root principal (assumed to be added as part of Kerberos server setup) and add server1 as a host principal to the KDC database:

#kadmin -p root/admin
kadmin:addprinc -randkey host/server1.example.com

While logged in, extract the principal's key and store it locally in a keytab file called krb5.keytab in the /etc directory.

kadmin:ktadd -l /etc/krb5/keytab host/server1.example.com

Activate the use of Kerberos for authentication:

#authconfig --enablekrb5 --update

Edit the /etc/ssh/ssh_config client configuration file and ensure te following two lines are set as shown:

GSSAPIAuthentication yes
GSSAPIDelegateCredentials yes

Login as user1 annd execure the kinit command to obtain a TGT from the KDC. Enter the passowrd for user1 when prompted

$kinit
Password for user1@exemple.com:

List the TGT details received in the previous step:

$klist

Overview of Authentication Configuration Tool for Kerberos Client Setup

The graphical tool allows you to configure the Kerberos client service on the system. This tool may be invoked by runing the authconfig-gtk or the system-config-authentication command in an X-terminal.

Hoofdstuk 18 Tuning Kernel Parameters, Reporting System Usage and Logging Remotely

Understanding and Tuning Kernel Parameters

Run-Time Parameters

Run-time parameters control the kernel behaviour while the system is operation. The current list of active run-time parameters may be viewed with the command sysctl -a.

Runtime values for these parameters are stored in various files located under sub-directories in the /proc/sys directory and can be altered on the fly by changing associated files. Temporary changes can be accomplished with the sysctl or echo command. To make the change survive across system-boots, the value must be defined in the /etc/sysctl.conf file or in a file under the /etc/sysctl.d directory.

Boot-Time Parameters

Boot-time parameters, also referred to as command-line options, affect the boot behaviour of the kernel. Their purpose is to pass any hardware specific information that the kernel would not be able to determine automatically. Boot-time parameters are supplied to the kernel via the GRUB2 interface. The entire boot string along with the command-line options can be viewed after boot with cat /proc/cmdline. Defaults are stored in /boot/grub2/grub.cfg.

Generation System Usage Reports

The sysstat Toolset

The sysstat toolset includes several additional monitoring and performance reporting commands such as cifsiostat, iosta, mpstat,nfsiostat,pidstat,sadf and sar. The sysstat service references two configuration files, sysstat and sysstat.ioconf, located in directory /etc/sysconfig.

In addition to the two configuration files, a cron job file/etc/cron.d/sysstat is available.


The dstat Tool

The dstat package includes a single monitoring and reporting tool, wich is called dstat.


Logging System Messages Remotely

Local and remote logging is supported by the rsyslogd service. Configuration files are /etc/rsyslog.conf and the /etc/rsyslog.d directory.

Configure a System as a Loghost

Open /etc/rsyslog.conf and uncomment the following two directives:

# Provides TCP syslog reception
#$ModLoad imtcp
#$InputTCPServerRun 514

Add TCP port 514 to the default firewalld zone, and load the new rule:

#firewall-cmd --permanent --add-port 514/tcp
#firewall-cmd --reload

Set the correct SELinux port type on TCP port 514

#semanage port -a -t syslogd_port_t -p tcp 514

And enable and restart the rsyslog service

#systemctl enable rsyslog
#systemctl restart rsyslog

Configure a System as a Loghost Client

Open /etc/rsyslog.conf file and add the following to the bottom of the file:

*.* @@192.168.0.120:514

Set the rsyslog service to autostart at each system reboot, rstart rsyslog and check it's operating state:

#systemctl enable rsyslog
#systemctl restart rsyslog
#systemctl status rsyslog

Generate a custom log message:

#logger -i "This is a test message from root on server 1" 

Log on to the loghost and tail the /var/log/messages file:

#tail /var/log/messages

...

sysctl -a, sysctl -p
/proc/sys
echo 18 >/proc/sys/...
/etc/sysctl.conf
/etc/sysctl.d
/usr/lib/sysctl.d/00-system.conf
/boot/grub2/grub.cfg
/proc/cmdline                        Boot-Time parameters aka command-line options
df, vmstat, top
Package sysstat: cifsiostat, iostat, mpstat,nfsiostat, pidstat, sa1, sa2, sadc, sadf, sar, dstat
/etc/sysconfig/sysstat
/etc/sysconfig/sysstat.ioconf
/etc/cron.d/sysstat
Package dstat, dstat

Chapter 19 Sharing Block Storage with iSCSI

iSCSI is a storage networking protocol used to share a computer's local storage with remote clients using the SCSI commandset over an existing IP network infrastructure. The client sees the shared storage as a locally attached harddisk and can use any available tool to manage it.

Understanding the iSCSI Protocol

The Internet Small Computer System Interface (iSCSI) is a storage networking transport protocol that carries SCSI commands over IP networks, including the internet.

Unlike the NFS and CIFS protocols that are used for network filesharing, iSCSI presents the network storage to clients as a local raw block disk drive. In iSCSI nomenclature, a storage server is referred to as a target and a client is referred to as an initiator.

Terminology

The iSCSI technology has several terms. The most important terms are described below.

  • ACL: An ACL (Access Control List) controls an iSCSI client access to target LUNs.
  • Addressing: iSCSI assigns a unique address to each target server. It supports muliple addressing formats. The IQN (iSCSI Qualified Name) is most common.
  • Alias: An alias is an optional string of up to 255 characters that may be defined to give a description to an iSCSI LUN.
  • Authentication: Authentication allows initiators and targets to prove their identity at the time of discovery and normal access. CHAP-based authentication (Challenge-Handshake Authentication Protocol) uses usernames and passwords, but hide the network transmission of passwords. These methods are referred to as CHAP initiator authentication and mutual CHAP authentication. The third option, demo mode, is the default option and it is used to disable the authentication feature.
  • Backstore: A backstore is a local storage resource that serves as the backend for the LUN presented to the initiator. A backstore can be any physical or virtual disk (block) or a plain file (fileio) or a ramdisk image.
  • Initiator: An initiator is a client system that accesses LUNs presented by a target server. Initiators are either software- or hardware-driven. A software initiator is a kernel module that uses the iSCSI protocol to emulate a discovered LUN as a block SCSI disk. A hardware initiator uses a dedicated piece of hardware called an HBA. An HBA offloads system processors, resulting in improved system performance.
  • iSNS: An iSNS (Internet Storage Name Service) is a protocol that is used by an initiator to discover shared LUNs.
  • LUN: A LUN (Logical Unit Number) represents a single addressable logical SCSI disk that is exported on the target server.
  • Node: A node is a single discoverable object on the iSCSI SAN. It may represent a target server or an initiator. A node is identified by its IP address or a unique iSCSI address.
  • Portal: A portal is a combination of an IP address and TCP port that a target server listens on and initiators connect to. iSCSI uses TCP port 3260 by default.
  • Target: A target is a server that emulates a backstore as a LUN for use by an initiator over an iSCSI SAN. A target may be a dedicated hardware RAID array or a RHEL server with appropiate software support loaded.
  • TPG: A TPG (Target Portal Group) represents one or more network portals assigned to a target LUN for running iSCSI sessions for that LUN.

Packages

A single package, targetcli, needs to be installed on the target server in order to provide the iSCSI target functionality. On the client side iscsi-initiator-utils package is installed. This package brings the iscsiadm management command and /etc/iscsi/iscsid.conf file.

Managing iSCSI Target Server and Initiator

Managing iSCSI on the target servers involves setting up a backstore, building an iSCSI target on the backstore, assigning a network portal, creating a LUN, exporting the LUN, establishing an ACL, and saving the configuration.

Managing iSCSI on the initiator involves discovering a target server for LUNs, logging on to discovered target LUNs, and using disk management tools to partition, format and mount the LUNs.

Understanding the targetcli Command for Target Administration

The targetcli command is an administration shell that allows you to display , create, modify and delete target LUNs. Several kernel modules are loaded in memory to support the setup and operation. You can view the modules that are currently loaded by running the lsmod command:

[root@server2 ~]#lsmod|grep target
target_core_pscsi      19318  0
target_core_file       27472  2
target_core_iblock     27510  2
iscsi_target_mod      295398  9
target_core_mod       371914  19 target_core_iblock,target_core_pscsi,iscsi_target_mod,target_core_file
crc_t10dif             12714  1 target_core_mod
[root@server2 ~]#

Command targetcli invokes a shell interface. Available subcommands can be view with subcommand help.

ls              Shows the downward view of the tree from the current location.
pwd             Displays the current location in the tree.
cd              Navigates in the tree.
exit            Quits the interface.
saveconfig      Saves the modifications.
get/set         Gets (or sets) configuration attributes.
sessions        Displays details for open sessions.

Use the ls, pwd and cd commands to navigate in the object hierarchy.

[root@server2 ~]# targetcli
targetcli shell version 2.1.fb41
Copyright 2011-2013 by Datera, Inc and others.
For help on commands, type 'help'. 
/> pwd 
/
/> ls
o- / ................................................................................................ [...]
  o- backstores ..................................................................................... [...]
  | o- block ......................................................................... [Storage Objects: 1]
  | | o- iscsidisk1 .............................................. [/dev/vdb (2.0GiB) write-thru activated]
  | o- fileio ........................................................................ [Storage Objects: 1]
  | | o- iscsifile1 .................................. [/usr/iscsifile1.img (50.0MiB) write-back activated]
  | o- pscsi ......................................................................... [Storage Objects: 0]
  | o- ramdisk ....................................................................... [Storage Objects: 0]
  o- iscsi ................................................................................... [Targets: 2]
  | o- iqn.2016-01.com.example.server2:iscsifile1 ............................................... [TPGs: 1]
  | | o- tpg1 ......................................................................... [gen-acls, no-auth]
  | |   o- acls ................................................................................. [ACLs: 0]
  | |   o- luns ................................................................................. [LUNs: 1]
  | |   | o- lun0 ............................................... [fileio/iscsifile1 (/usr/iscsifile1.img)]
  | |   o- portals ........................................................................... [Portals: 1]
  | |     o- 192.168.122.102:3260 .................................................................... [OK]
  | o- iqn.2016-01.roggeware.nl.server2:iscsidisk1 .............................................. [TPGs: 1]
  |   o- tpg1 ......................................................................... [gen-acls, no-auth]
  |     o- acls ................................................................................. [ACLs: 0]
  |     o- luns ................................................................................. [LUNs: 1]
  |     | o- lun0 ........................................................... [block/iscsidisk1 (/dev/vdb)]
  |     o- portals ........................................................................... [Portals: 1]
  |       o- 192.168.122.102:3260 .................................................................... [OK]
  o- loopback ................................................................................ [Targets: 0]
/>

Adding 1x2GB Virtual Disk to Target Server

Create a 3GB virtual disk for iSCSCI excercises on host1 and attach it to server2.

#cd /var/lib/libvirt/images
#qemu-img create -f raw server2.iscsi.2.img 3G
Formatting 'server2.iscsi.2.img', fmt=raw size=3221225472
[root@atlas images]# ls -l
-rw-------. 1 qemu qemu 10739318784 Jun 24 14:30 rhel7.0.qcow2
-rw-------. 1 qemu qemu 10737418240 Jun 24 14:37 rocrail.img
-rw-r--r--. 1 root root  3221225472 Jun 24 14:37 server2.iscsi.2.img
[root@atlas images]#

Now attach it to server2 using the virsh command.

[root@atlas images]#virsh domblklist server2 --details
Type       Device     Target     Source
------------------------------------------------
file       disk       vda        /var/lib/libvirt/rhpol_virsh/rgvol_virsh.img
file       disk       vdb        /var/lib/libvirt/images/server2.iscsi.img
[root@atlas images]#virsh attach-disk server2 --source /var/lib/libvirt/images/server2.iscsi.2.img  --target vdc --persistent
Disk attached successfully
[root@atlas images]#virsh domblklist server2 --details
Type       Device     Target     Source
------------------------------------------------
file       disk       vda        /var/lib/libvirt/rhpol_virsh/rgvol_virsh.img
file       disk       vdb        /var/lib/libvirt/images/server2.iscsi.img
file       disk       vdc        /var/lib/libvirt/images/server2.iscsi.2.img
[root@server2 ~]# lsblk
NAME            MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
vda             252:0    0   10G  0 disk
ââvda1          252:1    0  500M  0 part /boot
ââvda2          252:2    0  9.5G  0 part
  ââcentos-root 253:0    0  8.5G  0 lvm  /
  ââcentos-swap 253:1    0    1G  0 lvm  [SWAP]
vdb             252:16   0    2G  0 disk
ââvdb1          252:17   0    2G  0 part
vdc             252:32   0    3G  0 disk

[root@server2 ~]#

Disk vdc will be configured on server2 as an iSCSI target LUN and accessed as a block disk by server1 (iSCSI initiator).

Configure a Disk-Based iSCSI Target LUN

You will install the targetcli software on server2, set the target service to autostart at system reboots, define disk vdc as a backstore, build a target using this backstore, assign a network portal to the target, create a LUN in the target, disable authentication and create and activate a firewalld service for iSCSI port 3260.

#yum install targetcli
#systemctl enable target

Add the disk to the backstore

#targetcli
/>cd /backstores/block
/>ls
/backstores/block>ls
o- block ...................................................................... [Storage Objects: 1]
  o- iscsidisk1 ........................................... [/dev/vdb (2.0GiB) write-thru activated]
/backstores/block>/backstores/block> create iscsidisk2 dev=/dev/vdc
Created block storage object iscsidisk2 using /dev/vdc.
/backstores/block>ls
o- block ...................................................................... [Storage Objects: 2]
  o- iscsidisk1 ........................................... [/dev/vdb (2.0GiB) write-thru activated]
  o- iscsidisk2 ......................................... [/dev/vdc (3.0GiB) write-thru deactivated]
/backstores/block>

Build an iSCSI target with address iqn.2015-01.com.example.server2.iscsidisk2

/iscsi>create iqn.2016-01.roggeware.nl.server2:iscsidisk2
Created target iqn.2016-01.roggeware.nl.server2:iscsidisk2.
Created TPG 1.
Default portal not created, TPGs within a target cannot share ip:port.
/iscsi> ls
o- iscsi .............................................................................. [Targets: 3]
 o- iqn.2016-01.com.example.server2:iscsifile1 .......................................... [TPGs: 1]
 | o- tpg1 .................................................................... [gen-acls, no-auth]
 |   o- acls ............................................................................ [ACLs: 0]
 |   o- luns ............................................................................ [LUNs: 1]
 |   | o- lun0 .......................................... [fileio/iscsifile1 (/usr/iscsifile1.img)]
 |   o- portals ...................................................................... [Portals: 1]
 |     o- 192.168.122.102:3260 ............................................................... [OK]
 o- iqn.2016-01.roggeware.nl.server2:iscsidisk1 ......................................... [TPGs: 1]
 | o- tpg1 .................................................................... [gen-acls, no-auth]
 |   o- acls ............................................................................ [ACLs: 0]
 |   o- luns ............................................................................ [LUNs: 1]
 |   | o- lun0 ...................................................... [block/iscsidisk1 (/dev/vdb)]
 |   o- portals ...................................................................... [Portals: 1]
 |     o- 192.168.122.102:3260 ............................................................... [OK]
 o- iqn.2016-01.roggeware.nl.server2:iscsidisk2 ......................................... [TPGs: 1]
   o- tpg1 ................................................................. [no-gen-acls, no-auth]
     o- acls ............................................................................ [ACLs: 0]
     o- luns ............................................................................ [LUNs: 0]
     o- portals ...................................................................... [Portals: 0]

Create a network portal for the target using IP addres 192.168.122.102

/iscsi> cd iqn.2016-01.roggeware.nl.server2:iscsidisk2/tpg1/
/iscsi/iqn.20...csidisk2/tpg1> ls
o- tpg1 ..................................................................... [no-gen-acls, no-auth]
  o- acls ................................................................................ [ACLs: 0]
  o- luns ................................................................................ [LUNs: 0]
  o- portals .......................................................................... [Portals: 0]
/iscsi/iqn.20...csidisk2/tpg1> portals/ create 192.168.122.102
Using default IP port 3260
Created network portal 192.168.122.102:3260.
/iscsi/iqn.20...csidisk2/tpg1> ls
o- tpg1 ..................................................................... [no-gen-acls, no-auth]
  o- acls ................................................................................ [ACLs: 0]
  o- luns ................................................................................ [LUNs: 0]
  o- portals .......................................................................... [Portals: 1]
    o- 192.168.122.102:3260 ................................................................... [OK]

Create a LUN called lun0 in the target and export it to the network

/iscsi/iqn.20...csidisk2/tpg1> luns/ create /backstores/block/iscsidisk2
Created LUN 0.
/iscsi/iqn.20...csidisk2/tpg1> ls
o- tpg1 ..................................................................... [no-gen-acls, no-auth]
  o- acls ................................................................................ [ACLs: 0]
  o- luns ................................................................................ [LUNs: 1]
  | o- lun0 .......................................................... [block/iscsidisk2 (/dev/vdc)]
  o- portals .......................................................................... [Portals: 1]
    o- 192.168.122.102:3260 ................................................................... [OK]

Disable authentication so that any initiator can access this lun.

/iscsi/iqn.20...csidisk2/tpg1> set attribute authentication=0 demo_mode_write_protect=0 generate_node_acls=1
Parameter authentication is now '0'.
Parameter demo_mode_write_protect is now '0'.
Parameter generate_node_acls is now '1'.
/iscsi/iqn.20...csidisk2/tpg1>

Return to the root of the tree and display the entire configuration:

/iscsi/iqn.20...csidisk2/tpg1> cd /
/> ls
o- / ......................................................................................... [...]
  o- backstores .............................................................................. [...]
  | o- block .................................................................. [Storage Objects: 2]
  | | o- iscsidisk1 ....................................... [/dev/vdb (2.0GiB) write-thru activated]
  | | o- iscsidisk2 ....................................... [/dev/vdc (3.0GiB) write-thru activated]
  | o- fileio ................................................................. [Storage Objects: 1]
  | | o- iscsifile1 ........................... [/usr/iscsifile1.img (50.0MiB) write-back activated]
  | o- pscsi .................................................................. [Storage Objects: 0]
  | o- ramdisk ................................................................ [Storage Objects: 0]
  o- iscsi ............................................................................ [Targets: 3]
  | o- iqn.2016-01.com.example.server2:iscsifile1 ........................................ [TPGs: 1]
  | | o- tpg1 .................................................................. [gen-acls, no-auth]
  | |   o- acls .......................................................................... [ACLs: 0]
  | |   o- luns .......................................................................... [LUNs: 1]
  | |   | o- lun0 ........................................ [fileio/iscsifile1 (/usr/iscsifile1.img)]
  | |   o- portals .................................................................... [Portals: 1]
  | |     o- 192.168.122.102:3260 ............................................................. [OK]
  | o- iqn.2016-01.roggeware.nl.server2:iscsidisk1 ....................................... [TPGs: 1]
  | | o- tpg1 .................................................................. [gen-acls, no-auth]
  | |   o- acls .......................................................................... [ACLs: 0]
  | |   o- luns .......................................................................... [LUNs: 1]
  | |   | o- lun0 .................................................... [block/iscsidisk1 (/dev/vdb)]
  | |   o- portals .................................................................... [Portals: 1]
  | |     o- 192.168.122.102:3260 ............................................................. [OK] 
  | o- iqn.2016-01.roggeware.nl.server2:iscsidisk2 ....................................... [TPGs: 1]
  |   o- tpg1 .................................................................. [gen-acls, no-auth]
  |     o- acls .......................................................................... [ACLs: 0]
  |     o- luns .......................................................................... [LUNs: 1]
  |     | o- lun0 .................................................... [block/iscsidisk2 (/dev/vdc)]
  |     o- portals .................................................................... [Portals: 1]
  |       o- 192.168.122.102:3260 ............................................................. [OK]
  o- loopback ......................................................................... [Targets: 0]
/>

Exit out of the shell interface. By default, the auto_save_on_exit directive is set to true.

/> exit
Global pref auto_save_on_exit=true
Last 10 configs saved in /etc/target/backup.
Configuration saved to /etc/target/saveconfig.json
[root@server2 ~]#

Add a service called iscsitarget by creating a file called iscsitarget.xml in the /etc/firewalld/services directory to permit iSCSC traffic on port 3260.

[root@server2 services]# pwd
/etc/firewalld/services
[root@server2 services]# cat iscsitarget.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
 <short>iSCSI</short>
 <description>This is to permit the iSCSI traffix to pass thtough the firewall</description>
 <port protocol="tcp" port="3260"/>
</service>
[root@server2 services]#

And add the new service to firewalld and activate it

[root@server2 services]# firewall-cmd --permanent --add-service iscsitarget;firewall-cmd --reload
success
success
[root@server2 services]#

Understanding the iscsiadm Command for Initiator Administration

The primary tool to discover iSCSI targets, to log in to them and to manage the iSCSI discovery database is the iscsiadm command. This command interacts with the iscsid daemon and reads the /etc/iscsi/iscsid.conf file for configuration directives at the time of discovering and logging in to new targets. The iscsiadm command has four modes of operation.

  • Discovery - Queries the specifed portal for available targets based on the configuration defined in /etc/iscsi/iscsi.conf file. Records found are stored in discovery database files in the /var/lib/iscsi directory.
  • Node - Establishes a session with the target and creates a corresponding device file for each discovered LUN in the target.
  • Session - Displays current session information.
  • Iface - Defines network portals

There are several options available with the iscsiadm command. Some of them are

-D (--discover)    Discovers targets using discovery records. If no matching record is found, a new record is created based on settings in /etc/iscsi/iscsi.conf.
-l (--login)       Logs in to the speciified target.
-L (--loginall)    Logs in to all discovered targets.
-m (--mode)        Specifies one of the supported modes of operation.
-p (--portal)      Specifies a target server portal.
-o (--op)          Specifies one of the supported database operators: new, delete, update, show or non-persistent.
-T (--targetname)  Specfifies a target name.
-t (--type)        Specifes a type of discovery. Sendtargets (st) is usually used.
-u (--logout)      Logs out from a target.
-U (--logoutall)   Logs out from all targets.
The /etc/iscsi/iscsid.conf File

The /etc/iscsi/iscsid.conf file is the iSCSI initiator configuration file that defines several options for the iscsid daemon that dictate how to handle an iSCSI initator via the iscsiadm command. During an iSCSI target discovery, the iscsiadm command references this file and creates discovery and node records, and stores them in send_targets (or other supported discovery type) and nodes subdirectories under the /var/lib/iscsi/ directory. The records saved in send_targets are used when you attempt to perform discovery on the same target server again, and the records saved in nodes are used when you attemot to log in to the discovered targets.

The /etc/iscsi/initiatorname.iscsi File

The /etc/iscsi/initiatorname.iscsi file stores the discovered node names along with optional aliases using the InitiatorName and InitiatorAlias directives, respectively. This file is read by the iscsid daemon on startup and it is used by the iscsiadm command to determinenode names and aliases.

[root@server1 ~]# cat /etc/iscsi/initiatorname.iscsi
InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsidisk1
Initiatorname=iqn.2016-01.com.example.server2:iscsifile1
[root@server1 ~]#

Mount the iSCSI Target on Initiator

You will install the iscsi-initiator-utils software package on server1, set iscsid service to autostart at system reboots, discover available targets, log in to a discovered target and create a filesystem using LVM. And add an entry to /etc/fstab file and mount it manually. Reboot the system to verify the mount at reboot.

Run yum to install the required package and set the iscsid service to autostart at system reboots

#yum install iscsi-initiator-utils
#systemctl enable iscsid

Execute the iscsiadm command in sendtargets type (-t discovery mode (-m) to locate available iSCSI targets from the specified portal (-p)

#iscsiadm -m discovery -t st -p 192.168.122.102
[root@server1 ~]# iscsiadm -m discovery -t st -p 192.168.122.102
192.168.122.102:3260,1 iqn.2016-01.com.example.server2:iscsifile1
192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk1
192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk2
[root@server1 ~]#

The above command also adds the new record to appropiate discovery database files located in the /var/lib/iscsi directory and starts the iscsi daemon. Log in (-l) to the target (-T) in node mode (-m) at the specified portal (-p) to establish a target/initiator session.

[root@server1 ~]# 'iscsiadm -m node -T iqn.2016-01.roggeware.nl.server2:iscsidisk2 -p 192.168.122.102 -l
Logging in to [iface: default, target:  iqn.2016-01.roggeware.nl.server2:iscsidisk2, portal: 192.168.122.102,3260] (multiple)
Login to [iface: default, target: iqn.2016-01.roggeware.nl.server2:iscsidisk2, portal: 192.168.122.102,3260] successful.
[root@server1 ~]#

View the information for the established iSCSI session (-m) and specify printlevel (-P) 1 for verbosity.

[root@server1 ~]# iscsiadm -m session -P1
Target: iqn.2016-01.roggeware.nl.server2:iscsidisk1 (non-flash)
        Current Portal: 192.168.122.102:3260,1
        Persistent Portal: 192.168.122.102:3260,1
                **********
                Interface:
                **********
                Iface Name: default
                Iface Transport: tcp
                Iface Initiatorname: iqn.2016-01.roggeware.nl.server2:iscsidisk1
                Iface IPaddress: 192.168.122.111
                Iface HWaddress: <empty>
                Iface Netdev: <empty>
                SID: 1
                iSCSI Connection State: LOGGED IN
                iSCSI Session State: LOGGED_IN
                Internal iscsid Session State: NO CHANGE
Target: iqn.2016-01.com.example.server2:iscsifile1 (non-flash)
        Current Portal: 192.168.122.102:3260,1
        Persistent Portal: 192.168.122.102:3260,1
                **********
                Interface:
                **********
                Iface Name: default
                Iface Transport: tcp
                Iface Initiatorname: iqn.2016-01.roggeware.nl.server2:iscsidisk1
                Iface IPaddress: 192.168.122.111
                Iface HWaddress: <empty>
                Iface Netdev: <empty>
                SID: 2
                iSCSI Connection State: LOGGED IN
                iSCSI Session State: LOGGED_IN
                Internal iscsid Session State: NO CHANGE
Target: iqn.2016-01.roggeware.nl.server2:iscsidisk2 (non-flash)
        Current Portal: 192.168.122.102:3260,1
        Persistent Portal: 192.168.122.102:3260,1
                **********
                Interface:
                **********
                Iface Name: default
                Iface Transport: tcp
                Iface Initiatorname: iqn.2016-01.roggeware.nl.server2:iscsidisk1
                Iface IPaddress: 192.168.122.111
                Iface HWaddress: <empty>
                Iface Netdev: <empty>
                SID: 3
                iSCSI Connection State: LOGGED IN
                iSCSI Session State: LOGGED_IN
                Internal iscsid Session State: NO CHANGE
[root@server1 ~]# 

The output shows details for the target and the established session. It also shows the name of the LUN as identified on the initiator at the bottom of the output.

Edit the /etc/iscsi/initiatorname.iscsi file and add the target information:

[root@server1 ~]# cat /etc/iscsi/initiatorname.iscsi
InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsidisk1
InitiatorName=iqn.2016-01.com.example.server2:iscsifile1
InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsidisk2
[root@server1 ~]#

Execute the lsblk and fdisk commands to see the new LUN.

[root@server1 ~]# lsblk|grep sdc
sdc                  8:32   0    3G  0 disk
[root@server1 ~]# fdisk -l|grep sdc
WARNING: fdisk GPT support is currently new, and therefore in an experimental phase. Use at your own discretion.
Disk /dev/sdc: 3221 MB, 3221225472 bytes, 6291456 sectors
[root@server1 ~]#

The /var/log/messages// file has captured several messages for the new LUN.

[root@server1 ~]# grep sdc /var/log/messages
Jun 25 12:28:02 server1 kernel: sd 4:0:0:0: [sdc] 6291456 512-byte logical blocks: (3.22 GB/3.00 GiB)
Jun 25 12:28:02 server1 kernel: sd 4:0:0:0: [sdc] Write Protect is off
Jun 25 12:28:02 server1 kernel: sd 4:0:0:0: [sdc] Write cache: enabled, read cache: enabled, supports DPO and FUA
Jun 25 12:28:02 server1 kernel: sdc: unknown partition table
Jun 25 12:28:02 server1 kernel: sd 4:0:0:0: [sdc] Attached SCSI disk
Jun 25 12:50:25 server1 kernel: sd 4:0:0:0: [sdc] 6291456 512-byte logical blocks: (3.22 GB/3.00 GiB)
Jun 25 12:50:25 server1 kernel: sd 4:0:0:0: [sdc] Write Protect is off
Jun 25 12:50:25 server1 kernel: sd 4:0:0:0: [sdc] Write cache: enabled, read cache: enabled, supports DPO and FUA
Jun 25 12:50:25 server1 kernel: sdc: unknown partition table
Jun 25 12:50:25 server1 kernel: sd 4:0:0:0: [sdc] Attached SCSI disk
[root@server1 ~]#

Use LVM to initialize this LUN, crate a volume group and add the physical volume to it. Create a logical volume of size 1GB, format the logical volume with xfs structures, create a mountpoint, add an entry to /etc/fstab (make shure to use the _netdev option, mount the new filesystem and confirm the mount.

[root@server1 ~]# pvcreate /dev/sdc
  /dev/sdc: Data alignment must not exceed device size.
  Format-specific initialisation of physical volume /dev/sdc failed.
  Failed to setup physical volume "/dev/sdc"
[root@server1 ~]# pvcreate --dataalignment 8m --dataalignmentoffset 4m /dev/sdc 
  Physical volume "/dev/sdc" successfully created
[root@server1 ~]# vgcreate iscsi /dev/sdc
  Volume group "iscsi" successfully created
[root@server1 ~]# lvcreate -L 1G iscsi -n lviscsi
  Logical volume "lviscsi" created.
[root@server1 ~]#mkfs.xfs /dev/iscsi/lviscsi
meta-data=/dev/iscsi/lviscsi     isize=256    agcount=4, agsize=65536 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=0        finobt=0
data     =                       bsize=4096   blocks=262144, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=0
log      =internal log           bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
[root@server1 ~]#cat /etc/fstab
/dev/mapper/centos-root                         /       xfs     defaults        0 0
UUID=3d0dd9cb-d7d1-49b6-a6f7-f71acfbb49d4       /boot   xfs     defaults        0 0
/dev/mapper/centos-swap                         swap    swap    defaults,pri=1  0 0
UUID=95ddc2a2-49c8-425b-a9b8-aad7d171542c       swap    swap    defaults,pri=1  0 0
UUID=768fe142-803b-4bfe-a269-1f246a49fd84       swap    swap    defaults,pri=1  0 0
/dev/iscsi/lviscsi                              /iscsi  xfs     _netdev         0 0
[root@server1 ~]#mount /iscsi
[root@server1 ~]# df -h|grep scsi
/dev/mapper/iscsi-lviscsi 1014M   33M  982M   4% /iscsi
[root@server1 ~]#

Configure a File-Based iSCSI Target and Mount it on Initiator

In this exercise you will configure a 300MB plain file as a backstore, build a target using this backstore, assign a network portal to the target,,create a LUN in the target, export the LUN, diable authentication, and create and activate a firewalld service for iSCSI port 3260. You will discover this target on the initiator, log in to it, and create a filesystem using parted. You will add an entry to /etc/fstab suign the filesystem's UUID and mount the filesystem manually and reboot to ensure the filesystem is mounted automatically.

Configure iSCSI Target Server

Create a file iscsifile2.img of 300MB in the /usr directory as a fileio type backstore called iscsifile2 and display the construction.

[root@server2 ~]# targetcli /backstores/fileio create iscsifile2 /usr/iscsifile2.img 300M
fileio iscsifile2 with size 314572800
[root@server2 ~]# targetcli ls /backstores/fileio
o- fileio ..................................................................... [Storage Objects: 2]
  o- iscsifile1 ............................... [/usr/iscsifile1.img (50.0MiB) write-back activated]
  o- iscsifile2 ............................ [/usr/iscsifile2.img (300.0MiB) write-back deactivated]
[root@server2 ~]#

Build an iSCSI target with address iqn.2016-01.roggeware.nl.server2:iscsifile2 on the iscsifile2 backstore in the default TPG and display the construction.

[root@server2 ~]# targetcli /iscsi create iqn.2016-01.roggeware.nl.server2:iscsifile2
Created target iqn.2016-01.roggeware.nl.server2:iscsifile2.
Created TPG 1.
Default portal not created, TPGs within a target cannot share ip:port.
[root@server2 ~]# targetcli ls  /iscsi
o- iscsi .............................................................................. [Targets: 4]
  o- iqn.2016-01.com.example.server2:iscsifile1 .......................................... [TPGs: 1]
  | o- tpg1 .................................................................... [gen-acls, no-auth]
  |   o- acls ............................................................................ [ACLs: 0]
  |   o- luns ............................................................................ [LUNs: 1]
  |   | o- lun0 .......................................... [fileio/iscsifile1 (/usr/iscsifile1.img)]
  |   o- portals ...................................................................... [Portals: 1]
  |     o- 192.168.122.102:3260 ............................................................... [OK]
...
  o- iqn.2016-01.roggeware.nl.server2:iscsifile2 ......................................... [TPGs: 1]
    o- tpg1 ................................................................. [no-gen-acls, no-auth]
      o- acls ............................................................................ [ACLs: 0]
      o- luns ............................................................................ [LUNs: 0]
      o- portals ...................................................................... [Portals: 0]
[root@server2 ~]#

Create a network portal for the target using the IP 192.168.122.102 to be used for iSCSI traffic and the default port. This will make the target discoverable nad accessible on te network. Display the configuration.

[root@server2 ~]# targetcli /iscsi/iqn.2016-01.roggeware.nl.server2:iscsifile2/tpg1/portals create 192.168.122.102
Using default IP port 3260
Created network portal 192.168.122.102:3260.
[root@server2 ~]# targetcli ls /iscsi/iqn.2016-01.roggeware.nl.server2:iscsifile2/tpg1
o- tpg1 ..................................................................... [no-gen-acls, no-auth]
  o- acls ................................................................................ [ACLs: 0]
  o- luns ................................................................................ [LUNs: 0]
  o- portals .......................................................................... [Portals: 1]
    o- 192.168.122.102:3260 ................................................................... [OK]
[root@server2 ~]#

Create a LUN called lun0 in the target and export it to the network. And display the LUN construction.

[root@server2 ~]# targetcli /iscsi/iqn.2016-01.roggeware.nl.server2:iscsifile2/tpg1/luns create /backstores/fileio/iscsifile2
Created LUN 0.
[root@server2 ~]# targetcli ls /iscsi/iqn.2016-01.roggeware.nl.server2:iscsifile2/tpg1
o- tpg1 ..................................................................... [no-gen-acls, no-auth]
  o- acls ................................................................................ [ACLs: 0]
  o- luns ................................................................................ [LUNs: 1]
  | o- lun0 .............................................. [fileio/iscsifile2 (/usr/iscsifile2.img)]
  o- portals .......................................................................... [Portals: 1]
    o- 192.168.122.102:3260 ................................................................... [OK]
[root@server2 ~]#


Disable authentication so that any initiator can access this LUN and display the configuration. demo_mode_write_protect=0 makes the LUN write-enabled and the generate_node_acls=1 attribute enables the use of TPG-wide authentication settings (this disables any user-defined ACLs.

[root@server2 ~]# targetcli /iscsi/iqn.2016-01.roggeware.nl.server2:iscsifile2/tpg1 set attribute authentication=0 demo_mode_write_protect=0 generate_node_acls=1
Parameter authentication is now '0'.
Parameter demo_mode_write_protect is now '0'.
Parameter generate_node_acls is now '1'.
[root@server2 ~]# targetcli ls
o- / ......................................................................................... [...]
  o- backstores .............................................................................. [...]
  | o- block .................................................................. [Storage Objects: 2]
  | | o- iscsidisk1 ....................................... [/dev/vdb (2.0GiB) write-thru activated]
  | | o- iscsidisk2 ....................................... [/dev/vdc (3.0GiB) write-thru activated]
  | o- fileio ................................................................. [Storage Objects: 2]
  | | o- iscsifile1 ........................... [/usr/iscsifile1.img (50.0MiB) write-back activated]
  | | o- iscsifile2 .......................... [/usr/iscsifile2.img (300.0MiB) write-back activated]
  | o- pscsi .................................................................. [Storage Objects: 0]
  | o- ramdisk ................................................................ [Storage Objects: 0]
  o- iscsi ............................................................................ [Targets: 4]
  | o- iqn.2016-01.com.example.server2:iscsifile1 ........................................ [TPGs: 1]
  | | o- tpg1 .................................................................. [gen-acls, no-auth]
  | |   o- acls .......................................................................... [ACLs: 0]
  | |   o- luns .......................................................................... [LUNs: 1]
  | |   | o- lun0 ........................................ [fileio/iscsifile1 (/usr/iscsifile1.img)]
  | |   o- portals .................................................................... [Portals: 1]
  | |     o- 192.168.122.102:3260 ............................................................. [OK]
...
  | o- iqn.2016-01.roggeware.nl.server2:iscsifile2 ....................................... [TPGs: 1]
  |   o- tpg1 .................................................................. [gen-acls, no-auth]
  |     o- acls .......................................................................... [ACLs: 0]
  |     o- luns .......................................................................... [LUNs: 1]
  |     | o- lun0 ........................................ [fileio/iscsifile2 (/usr/iscsifile2.img)]
  |     o- portals .................................................................... [Portals: 1]
  |       o- 192.168.122.102:3260 ............................................................. [OK]
  o- loopback ......................................................................... [Targets: 0]
[root@server2 ~]#

Save the configuration to /etc/target/saveconfig.json

[root@server2 ~]# targetcli saveconfig
Last 10 configs saved in /etc/target/backup.
Configuration saved to /etc/target/saveconfig.json
[root@server2 ~]#

Add a service called iscsitarget by creating a file called iscsitarget.cml in the /etc/firewalld/services directory to permet iSCSI traffic on port 3260. Create this file and add the service permanently to the firewall configuration.

[root@server2 ~]# cat /etc/firewalld/services/iscsitarget.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
 <short>iSCSI</short>
 <description>This is to permit the iSCSI traffix to pass thtough the firewall</description>
 <port protocol="tcp" port="3260"/>
</service>
[root@server2 ~]#firewall-cmd --permanent --add-service iscsitarget;firewall-cmd --reload
Configure iSCSI Initiator Server

Set the iscsid service to autostart at system reboots.

#systemctl enable iscsid

Execute the iscsiadm command in sendtargets (-t) discovery mode (-m) to locate available iscsi targets from the specified portal -p

[root@server1 ~]# iscsiadm -m session
tcp: [1] 192.168.122.102:3260,1 iqn.2016-01.com.example.server2:iscsifile1 (non-flash)
tcp: [2] 192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk1 (non-flash)
tcp: [3] 192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk2 (non-flash)
[root@server1 ~]# iscsiadm -m discovery -t st -p 192.168.122.102
192.168.122.102:3260,1 iqn.2016-01.com.example.server2:iscsifile1
192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk1
192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk2
192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsifile2
#[root@server1 ~]# iscsiadm -m session
tcp: [1] 192.168.122.102:3260,1 iqn.2016-01.com.example.server2:iscsifile1 (non-flash)
tcp: [2] 192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk1 (non-flash)
tcp: [3] 192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk2 (non-flash)
[root@server1 ~]#

The above command also adds the new record to appropiate discovery database files located in the /var/lib/iscsi directory and starts the iscsid daemon. This information persists until you delete it.

Login (-l) to the target (-T) in node mode (-m) at the specified portal (-p) to establish a target/initiator session.

[root@server1]# iscsiadm -m node -T iqn.2016-01.roggeware.nl.server2:iscsifile2 -p 192.168.122.102 -l
Logging in to [iface: default, target: iqn.2016-01.roggeware.nl.server2:iscsifile2, portal: 192.168.122.102,3260] (multiple)
Login to [iface: default, target: iqn.2016-01.roggeware.nl.server2:iscsifile2, portal: 192.168.122.102,3260] successful.
[root@server1]# iscsiadm -m session
tcp: [1] 192.168.122.102:3260,1 iqn.2016-01.com.example.server2:iscsifile1 (non-flash)
tcp: [2] 192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk1 (non-flash)
tcp: [3] 192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsidisk2 (non-flash)
tcp: [4] 192.168.122.102:3260,1 iqn.2016-01.roggeware.nl.server2:iscsifile2 (non-flash)
[root@server1]#

View information for the established iSCSI session (-m) and specify printlevel (-P) 3 for verbosity.

[root@server1 ~]# iscsiadm -m session -P3
iSCSI Transport Class version 2.0-870
version 6.2.0.873-30
Target: iqn.2016-01.com.example.server2:iscsifile1 (non-flash)
        Current Portal: 192.168.122.102:3260,1
        Persistent Portal: 192.168.122.102:3260,1
                **********
                Interface:
                **********
                Iface Name: default
                Iface Transport: tcp
                Iface Initiatorname: iqn.2016-01.roggeware.nl.server2:iscsidisk1
                Iface IPaddress: 192.168.122.111
                Iface HWaddress: <empty>
                Iface Netdev: <empty>
                SID: 1
                iSCSI Connection State: LOGGED IN
                iSCSI Session State: LOGGED_IN
                Internal iscsid Session State: NO CHANGE
                *********
                Timeouts:
                *********
                Recovery Timeout: 120
                Target Reset Timeout: 30
                LUN Reset Timeout: 30
                Abort Timeout: 15
                *****
                CHAP:
                *****
                username: <empty>
                password: ********
                username_in: <empty>
                password_in: ********
                ************************
                Negotiated iSCSI params:
                ************************
                HeaderDigest: None
                DataDigest: None
                MaxRecvDataSegmentLength: 262144
                MaxXmitDataSegmentLength: 262144
                FirstBurstLength: 65536
                MaxBurstLength: 262144
                ImmediateData: Yes
                InitialR2T: Yes
                MaxOutstandingR2T: 1
                ************************
                Attached SCSI devices:
                ************************
                Host Number: 2  State: running
                scsi2 Channel 00 Id 0 Lun: 0
                        Attached scsi disk sdc          State: running
Target: iqn.2016-01.roggeware.nl.server2:iscsidisk1 (non-flash)
        Current Portal: 192.168.122.102:3260,1
        Persistent Portal: 192.168.122.102:3260,1
                **********
                Interface:
                **********
                Iface Name: default
                Iface Transport: tcp
                Iface Initiatorname: iqn.2016-01.roggeware.nl.server2:iscsidisk1
                Iface IPaddress: 192.168.122.111
                Iface HWaddress: <empty>
                Iface Netdev: <empty>
                SID: 2
                iSCSI Connection State: LOGGED IN
                iSCSI Session State: LOGGED_IN
                Internal iscsid Session State: NO CHANGE
                *********
                Timeouts:
                *********
                Recovery Timeout: 120
                Target Reset Timeout: 30
                LUN Reset Timeout: 30
                Abort Timeout: 15
                *****
                CHAP:
                *****
                username: <empty>
                password: ********
                username_in: <empty>
                password_in: ********
                ************************
                Negotiated iSCSI params:
                ************************
                HeaderDigest: None
                DataDigest: None
                MaxRecvDataSegmentLength: 262144
                MaxXmitDataSegmentLength: 262144
                FirstBurstLength: 65536
                MaxBurstLength: 262144
                ImmediateData: Yes
                InitialR2T: Yes
                MaxOutstandingR2T: 1
                ************************
                Attached SCSI devices:
                ************************
                Host Number: 3  State: running
                scsi3 Channel 00 Id 0 Lun: 0
                        Attached scsi disk sdb          State: running
Target: iqn.2016-01.roggeware.nl.server2:iscsidisk2 (non-flash)
        Current Portal: 192.168.122.102:3260,1 
        Persistent Portal: 192.168.122.102:3260,1
                **********
                Interface:
                **********
                Iface Name: default
                Iface Transport: tcp
                Iface Initiatorname: iqn.2016-01.roggeware.nl.server2:iscsidisk1
                Iface IPaddress: 192.168.122.111
                Iface HWaddress: <empty>
                Iface Netdev: <empty>
                SID: 3
                iSCSI Connection State: LOGGED IN
                iSCSI Session State: LOGGED_IN
                Internal iscsid Session State: NO CHANGE
                *********
                Timeouts:
                *********
                Recovery Timeout: 120
                Target Reset Timeout: 30
                LUN Reset Timeout: 30
                Abort Timeout: 15
                *****
                CHAP:
                *****
                username: <empty>
                password: ********
                username_in: <empty>
                password_in: ********
                ************************
                Negotiated iSCSI params:
                ************************
                HeaderDigest: None
                DataDigest: None
                MaxRecvDataSegmentLength: 262144
                MaxXmitDataSegmentLength: 262144
                FirstBurstLength: 65536
                MaxBurstLength: 262144
                ImmediateData: Yes
                InitialR2T: Yes
                MaxOutstandingR2T: 1
                ************************
                Attached SCSI devices:
                ************************
                Host Number: 4  State: running
                scsi4 Channel 00 Id 0 Lun: 0
                        Attached scsi disk sda          State: running
Target: iqn.2016-01.roggeware.nl.server2:iscsifile2 (non-flash)
        Current Portal: 192.168.122.102:3260,1
        Persistent Portal: 192.168.122.102:3260,1
                **********
                Interface:
                **********
                Iface Name: default
                Iface Transport: tcp
                Iface Initiatorname: iqn.2016-01.roggeware.nl.server2:iscsidisk1
                Iface IPaddress: 192.168.122.111
                Iface HWaddress: <empty>
                Iface Netdev: <empty>
                SID: 4
                iSCSI Connection State: LOGGED IN
                iSCSI Session State: LOGGED_IN
                Internal iscsid Session State: NO CHANGE
                *********
                Timeouts:
                *********
                Recovery Timeout: 120
                Target Reset Timeout: 30
                LUN Reset Timeout: 30
                Abort Timeout: 15
                *****
                CHAP:
                *****
                username: <empty>
                password: ********
                username_in: <empty>
                password_in: ********
                ************************
                Negotiated iSCSI params:
                ************************
                HeaderDigest: None
                DataDigest: None
                MaxRecvDataSegmentLength: 262144
                MaxXmitDataSegmentLength: 262144 
                FirstBurstLength: 65536
                MaxBurstLength: 262144
                ImmediateData: Yes
                InitialR2T: Yes
                MaxOutstandingR2T: 1
                ************************
                Attached SCSI devices:
                ************************
                Host Number: 5  State: running
                scsi5 Channel 00 Id 0 Lun: 0
                        Attached scsi disk sdd          State: running
[root@server1 ~]#

The output shows details for the target and the established session. It also shows the name of the LUN (sdd) as identified on the initiator at the very bottom of the output.

Edit the /etc/iscsi/initatorname.iscsi file and add the target information.

[root@server1 ~]# cat /etc/iscsi/initiatorname.iscsi
InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsidisk1
Initiatorname=iqn.2016-01.com.example.server2:iscsifile1
InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsidisk2
InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsifile2
[root@server1 ~]#

Execute the lsblk and fdisk commands and grep for sdd to see the new LUN.

[root@server1 ~]# lsblk|grep sdd
sdd                  8:48   0  300M  0 disk
[root@server1 ~]# fdisk -l|grep sdd
WARNING: fdisk GPT support is currently new, and therefore in an experimental phase. Use at your own discretion.
Disk /dev/sdd: 314 MB, 314572800 bytes, 614400 sectors
[root@server1 ~]#

The /var/log/messages file has captured several messages for the new LUN.

[root@server1 ~]# grep sdd /var/log/messages
Jun 27 17:21:28 server1 kernel: sd 5:0:0:0: [sdd] 614400 512-byte logical blocks: (314 MB/300 MiB)
Jun 27 17:21:28 server1 kernel: sd 5:0:0:0: [sdd] Write Protect is off
Jun 27 17:21:28 server1 kernel: sd 5:0:0:0: [sdd] Write cache: enabled, read cache: enabled, supports DPO and FUA
Jun 27 17:21:28 server1 kernel: sdd: unknown partition table
Jun 27 17:21:28 server1 kernel: sd 5:0:0:0: [sdd] Attached SCSI disk
[root@server1 ~]#

Use parted to label disk /dev/sdd, create a 200MB primary partition, display the disk's partition table, format the partition with ext4 structures, create mountpoint /iscsifile2, determine UUID, add an entry to /etc/fstab using the UUID and make sure to use the _netdev option.

[root@server1 ~]# parted /dev/sdd mklabel msdos
Information: You may need to update /etc/fstab.
[root@server1 ~]# parted /dev/sdd mkpart primary 1 200m
Warning: The resulting partition is not properly aligned for best performance.
Ignore/Cancel? I
Information: You may need to update /etc/fstab.
[root@server1 ~]# parted /dev/sdb print
Model: LIO-ORG iscsidisk1 (scsi)
Disk /dev/sdb: 2147MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:
Number  Start   End    Size   Type     File system  Flags
1      1000kB  200MB  199MB  primary
[root@server1 ~]#
[root@server1 ~]# mkfs.ext4 /dev/sdd1
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
Stride=0 blocks, Stripe width=8192 blocks
48768 inodes, 194336 blocks
9716 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=33816576
24 block groups
8192 blocks per group, 8192 fragments per group
2032 inodes per group
Superblock backups stored on blocks:
        8193, 24577, 40961, 57345, 73729
Allocating group tables: done
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done
[root@server1 ~]# mkdir /iscsifile2
[root@server1 ~]# blkid |grep sdd
/dev/sdd1: UUID="4d679483-d0bc-42e5-a8bf-28826d0ce8bf" TYPE="ext4"
[root@server1 ~]# vi /etc/fstab
[root@server1 ~]# cat /etc/fstab
/dev/mapper/centos-root                         /       xfs     defaults        0 0
UUID=3d0dd9cb-d7d1-49b6-a6f7-f71acfbb49d4       /boot   xfs     defaults        0 0
/dev/mapper/centos-swap                         swap    swap    defaults,pri=1  0 0
UUID=95ddc2a2-49c8-425b-a9b8-aad7d171542c       swap    swap    defaults,pri=1  0 0
UUID=768fe142-803b-4bfe-a269-1f246a49fd84       swap    swap    defaults,pri=1  0 0
UUID=fd6dc73b-24f4-4c14-a91e-25b4cdafec93       /aap    ext4    defaults        0 0
/dev/iscsi/lviscsi                              /iscsi  xfs     _netdev         0 0
UUID="4d679483-d0bc-42e5-a8bf-28826d0ce8bf"     /iscsifile2 ext4 _netdev 0 0
[root@server1 ~]# mount /iscsifile2
[root@server1 ~]# df -h
Filesystem                 Size  Used Avail Use% Mounted on
/dev/mapper/centos-root    8.5G  2.3G  6.3G  27% /
devtmpfs                   487M     0  487M   0% /dev
tmpfs                      497M     0  497M   0% /dev/shm
tmpfs                      497M   20M  478M   4% /run
tmpfs                      497M     0  497M   0% /sys/fs/cgroup
/dev/mapper/aap-aaplv       93M   26M   61M  30% /aap
/dev/vda1                  497M  295M  203M  60% /boot
/dev/mapper/iscsi-lviscsi 1014M   33M  982M   4% /iscsi
tmpfs                      100M     0  100M   0% /run/user/99
tmpfs                      100M     0  100M   0% /run/user/0
/dev/sdd1                  180M  1.6M  165M   1% /iscsifile2
[root@server1 ~]# df -h |grep file2
/dev/sdd1                  180M  1.6M  165M   1% /iscsifile2
[root@server1 ~]#

Reboot the server and ensure that the client configuration survives a reboot.

Summary

yum install targetcli                       Software package target server.
systemctl enable target
targetcli 
    /backstores/block/ create iscsdisk dev=/dev/sda
    /iscsi>create iqn.2016-01.roggeware.nl.server2:iscsidisk2
    /iscsi/iqn.20...csidisk2/tpg1/portals> create 192.168.122.102
    /iscsi/iqn.20...csidisk2/tpg1> set attribute authentication=0 demo_mode_write_protect=0 generate_node_acls=1
firewall-cmd --permanent --add-service iscsitarget;firewall-cmd --reload
yum install iscsi-initiator-utils
systemctl enable iscsid
iscsiadm -m discovery -t st -p 192.168.122.102
iscsiadm -m node -T iqn.2016-01.roggeware.nl.server2:iscsidisk2 -p 192.168.122.102 -l
iscsiadm -m session -P1
[root@server1 ~]# cat /etc/iscsi/initiatorname.iscsi
      InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsidisk1
      InitiatorName=iqn.2016-01.com.example.server2:iscsifile1
      InitiatorName=iqn.2016-01.roggeware.nl.server2:iscsidisk2
      [root@server1 ~]#
/etc/fstab add option _netdev
targetcli     for target administration, package targetclt
targetcli     saveconfig
iscsiadm      for initiator administration, package iscsi-initiator-utils
iscsiadm      -m discovery -t st -p 192.168.122.102    Locate available targets
iscsiadm      -m node -T iqn.2016-01.roggeware.nl.server2:iscsidisk1 -p 192.168.122.102 -l         Login (-l) to target (-T) in node mode (-m) at portal (-p)
iscsiadm      -m session 
systemctl enable iscsid

Files

/etc/iscsi/iscsi.conf              Used during target discovery.
/etc/iscsi/initatorname.iscsi      Stores nodenames.
/var/lib/iscsi/

Chapter 20 Sharing File Storage with NFS

Understanding Network Filesystem

Network File System (NFS) is a networking protocol that allows file sharing over the network. The remote system that makes its shares available for network access is referred to as an NFS server and the process of making the shares acceible is referred to as exporting. The shares are accessed by systems called NFS clients and the process of making the shares accessible is referred to as mounting. A system can provide both server and client functionality concurrently.

A sub-directory, or the parent directory of a share cannot be re-exported if it exists in the same filesystem. Similarly, a mounted share cannot be exported further.

NFS uses the Remote Procedure Call (RPC) and eXternal Data Representation (XDR) mechanisms that allow a server and a client to communicate with each other.

NFS Versions

RHEL7 provides support for NFS versions 3, 4.0 and 4.1, with NFSv4 being the default. NFSv3 supports both TCP and UDP transport protocols , asynchronous writes and 64-bit file sizes (supports files larger than 2GB). NFSv4 and NFSv4.1 are Internet Engineering Task Force (IETF) standard protocols that provide all of the features of NFSv3 protocol plus the ability to transit firewalls and work on the Internet, enhanced security, encrypted transfer, support for ACLs, greater scalability, better cross-platform interoperability and better handling of system crashes.

This chapter will focus on the NFSv4 protocol, which is the default protocol in RHEL7.

NFS Security

NFSv4 guarantees secure operations on WANs. When an NFS client attempt to access a remote share, an exchange of information takes place with the server to identify the client and the user on the server., authenticate them to the server, and authorize their access to the share. In-transit data between the two entities is encrypted to prevent eavesdropping and unauthorized access. NFS may be configured to use an existing kerberos server for authentication, integrity and data encryption. The NFS protocol uses TCP port 2049 for all communications between server and client.

NFS Daemons

NFS is a client/server protocol that employs several daemon programs to work together in order to export and mount shares, and manage I/O between them. One daemon runs on the server and the rest runs on both the server and the client.

  • NFSD NFS server process, responds to client requests on TCP port 2049 for file access and operations. Provides file locking and recovery mechanism.
  • rpcbind Runs on both server and client, converts RPC program numbers into universal addresses to facilitate communnication for other RPC-based processes.
  • rpc.rquotad Runs on both server and client, displays user quota informationfor a remotely mounted share on the server and it allows the setup of user quotas on a mounted share on the client.
  • rpc.idmapd Rns on both the server and the client to control the mappingsof UIDs and GIDs with teir corresponding usernames and groupnames based on the configuration defined in /etc/idmapd.conf..

NFS Commands

There are numerous commands available to establish and manage NFS shares and to monitor their I/O. A proper understanding of the usage of these commands is necessary for smooth administration of NFS

  • exportfs Server command that exports shares listed in the /etc/exports file and the files in the /etc/exports.d directory with .exports extension.
  • mount Client command that mounts a share specified at the command line or listed in the /etc/fstab, and adds an entry to the /etc/mtab file.
  • nfsiostat Client command tat provides NFS I/O statistics on mounted shares by consulting the /proc/self/mountstats file.
  • nfsstat Displays NFS and RPC statistics by consulting the /proc/net/rpc/nfsd (server) and /proc/net/rpc/nfs (client) files.
  • mountstats Client command that displays per-mount statistics by consulting the /proc/self/mountstats file.

Commands such as rpcinfo and showmount are also available; however they are not needed in an NFSv4 environment.

NFS Configuration and Functional Files

NFS reads configuration data from various files at startup and during its operation.

  • /etc/exports server file that contains share definitions for export.
  • /var/lib/nfs/etab Server file that records entries for exported shares wether or not they are remotely mounted. This file is updated each time a share is exported or unexported.
  • /etc/nfsmount.conf Client file that defines settings used at mounting shares.
  • /etc/fstab Client file system table that contains a list of shares to be mounted at system reboots or manually with the mount command.
  • /etc/sysconfig/nfs A server- and client-side NFS startup configuration file.

Of these, exports and fstab files are manually updated, nfsmount.conf and /etc/sysconfig/nfs files do not need any modification if NFSv4 is used with default settings. The etab and mtab files are automatically updated when the exportfs and mount/umount commands are executed.

The /etc/exports File and NFS Server Options

The /etc/exports file defines the configuration for NFS shares. it contains one-line entry per share to be exported. For each share, a pathname, client information and options are included. Options must be enclosed in within parentheses and there must not be any space following the hostname. Some of the options are described below with their defaults in brackets

  • * Represents all possible matches for hostnames, IP addresses, domain names or network addresses.
  • all_squash(no_all_squash)[no_all_squash] treats all users, including the root user on the client as anonymous users.
  • anongid=GID[65534] Assigns this GID explicitly to anonymous groups on the client.
  • anonuid=UID [65534] Assigns this uid explicitly to anonymous users on the client.
  • async(sync)[sync] Replies to client requests before changs made by previous requests are written to disk.
  • fsid Identifies the type of share being exported. Options are device number, root or UUID/ This option applies to filesystem shares only.
  • mp Exports only if the specified share is a filesystem.
  • root_squash(no_root_squash)[root_squash] Prevents the root user on the client from gaining superuser access on mounted shares by mapping root to an unprivilidged user account called nfsnobody with UID 65534.
  • rw(ro)[ro] Allows file modifications on the client.
  • sec[sec=sys] Limits the share export to clinets using one of these security methods: sys, krb5, krb5i or krb5p. The sys option uses local UIDs and GIDs and the rest use Kerberos for user authentication.
  • secure/(insecure)[secure]] Allows access only on clients using ports lower than 1024.
  • subtree_check(no_subtree_check)[no_subtree_check] Enalbes permission checks on higher-level direcotries of a share.
  • wdelay(no_wdelay)[wdelay] Delays data writes to a share it it expects the arrivl of another write request to the same share soon, thereby reducing the number of actual writes to the share.

Command man 5 exports describes the options.

The following shows a few sample entries to understand the syntax of the exports file.

/exports1   client1 client2 client3.example.com(rw,insecure)
/exports2   client4.example.com(rw) 192.168.1.20(no_root_squash) 192.168.0.0/24

The first example will export /export1 to client1 and client2 using all the defaults and to client3.example.com with read/write and insecure options. The second example will export /export2 to client4.example.com with read/write option to a client with IP 192.168.1.20 with no_root_squahs option and to the 192.168.0.0.24 netowrk with all the default options.

Configuring NFS Server and Client

This section presents several exercises how to setup NFS service and export a share, mount the share on the client and start the NFS client processes, export and mount another share for group collaboration and export a different share with Kerberos authentication.

SELinux Requirements for NFS Operation

By default SELinux policy allows NFS to export shares on the network without making any changes to either file contexts or booleans. All NFS daemons are confined by default and are labeled with appropiate domain types. For instance, the nfsd process is labeled with kernel_t type, rpcbind is labeled with the rpcbind_t type. This information can be verified with the following.

[root@server1 ~]# ps -efZ|grep 'nfs|rpc'
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 19949 19931  0 11:51 pts/0 00:00:00 grep --color=auto nfs|rpc
[root@server1 ~]#

Similarly, NFS configuration and functional files already have proper SELinux contacts in place and need no modifications. For instance, the context on /etc/exports is.

[root@server1 ~]# ls -lZ /etc/exports
-rw-r--r--. root root system_u:object_r:exports_t:s0   /etc/exports
[root@server1 ~]#

However, any directory or filesystem that you want to export on the network for sharing purposes will need to have either public_content_ro_t or public_content_rw_t SELinux type applied. This is only required if more than one file-sharing service, such as a combination of NFS and CIFS, NFS and FTP or CIFS and FTP, are used.

The SELinux policy includes numerous booleans that may be of interest from an NFS operation standpoint.Most of these booleans relate to services such as HTTP, KVM and FP that want to use mounted NFS shares to store their files. To list the booleans other than the ones mentioned above, run the getsebool command.

[root@server1 ~]# getsebool -a|egrep '^nfs|^use_nfs'
nfs_export_all_ro --> on
nfs_export_all_rw --> on
nfsd_anon_write --> off
use_nfs_home_dirs --> off
[root@server1 ~]#

The output lists four booleans.

  • nfs_export_all_ro Allows/disallows share exports in read-only mode.
  • nfs_export_all_rw Allows/disallows share exports in read/write mode.
  • nfsd_anon_write Allows/disallows the nfsd daemon to write anonymously to public directories on clients.
  • use_nfs_home_dirs Allows/disallows NFS clients to mount user home directories.

Export Shares to NFS Client

Create a directory called /common and export it with the NFSv4 protocol to server2 in read/write mode with root squash disabled. Create another directory called /nfsrhcsa and export it with the NFSv4 protocol to server2 in read-only mode. Ensure that appropiate SELinux controls are enabled for the NFS service and it is allowed through the firewall. Confirm exports using a command and a file.

Install the NFS package called nfs-utils and create directories for mountpoints.

[root@server1 ~]# yum install nfs-utils
Package 1:nfs-utils-1.3.0-0.21.el7_2.1.x86_64 already installed and latest version
Nothing to do
[root@server1 ~]# mkdir /common /nfsrhcsa
[root@server1 ~]#

Activate the SELinux booleans persistently to allow NFS exports in both read-only adn read/write modes and verify the activation.

[root@server1 ~]# setsebool -P nfs_export_all_ro=1 nfs_export_all_rw=1
[root@server1 ~]# getsebool -a|grep nfs_exp
nfs_export_all_ro --> on
_export_all_rw --> on
[root@server1 ~]#

Add the NFS service persistently to the firewalld configuration to allow the NFS traffic on TCP port 2049 and load the rule.

[root@server1 ~]# firewall-cmd --add-service nfs --permanent
success
[root@server1 ~]# firewall-cmd --list-services
dhcpv6-client dns http https mysql nfs ntp ssh
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-services
dhcpv6-client dns http https mysql nfs ntp ssh
[root@server1 ~]#

Set the rpcbind and NFS services to autostart at system reboots and start these services.

[root@server1 ~]# systemctl enable rpcbind nfs-server
Created symlink from /etc/systemd/system/multi-user.target.wants/nfs-server.service to /usr/lib/systemd/system/nfs-server.service.
Created symlink from /etc/systemd/system/sockets.target.wants/rpcbind.socket to /usr/lib/systemd/system/rpcbind.socket.
[root@server1 ~]# systemctl start rpcbind nfs
[root@server1 ~]#

Open /etc/exports file and add an entry for /common to export it to server2 with read/write and no_root_squash options, and an entry for /nfsrhcsa to export it to server2 using the sync option. And export the entries defined in /etc/exports.

[root@server1 ~]# cat /etc/exports
/common         server2.roggeware.nl(rw,no_root_squash)
/nfsrhcsa       server2.roggeware.nl(sync)
[root@server1 ~]# exportfs -avr
exporting server2:/nfsdata
exporting server2:/nfsrhcsa
[root@server1 ~]#

Show the contents of /var/lib/nfs/etab.

[root@server1 ~]# cat /var/lib/nfs/etab
/nfsrhcsa        server2(ro,sync,wdelay,hide,nocrossmnt,secure,root_squash,no_all_squash,no_subtree_check,secure_locks,acl,no_pnfs,anonuid=65534,anongid=65534,sec=sys,ro,secure,root_squash,no_all_ squash)
/common  server2(rw,sync,wdelay,hide,nocrossmnt,secure,no_root_squash,no_all_squash,no_subtree_check,secure_locks,acl,no_pnfs,anonuid=65534,anongid=65534,sec=sys,rw,secure,no_root_squash,no_all_squash)
[root@server1 ~]#

The NFS service is now setup on server1 If you want to unexport one of these shares, you can do this with the exprtfs command by specifying the -u option.

[root@server1 ~]# exportfs -u server2:/common [root@server1 ~]# exportfs -v /nfsrhcsa server2(ro,wdelay,root_squash,no_subtree_check,sec=sys,ro,secure,root_squash,no_all_squash) [root@server1 ~]#

NFS Client Options

You have just shared a directory as an NFS share on the network. On the client, the mount command is used to connect the NFS share to the filesystem hierarchy. This command supports several options.

  • ac(noac)[ac] Specifies to cache file attributes for better performance.
  • async(syn)[sync]Causes the I/O th happen asynchroneously.
  • defaults Selects the following default options automatically: rw,suid,dev,exec,auto,nouser and async.
  • fg/bg[fg] Use fg for shares that must be available. If a foreground fails it is retried for retry minutes. With bg mount attempts are tried repeatedly for retry minutes in the background without hampering the system boot process or haning the client.
  • hard/soft[hard] With hard, the client tries repeatedly to mount a share until it either successds or times out. With soft, if a mount is tried for retrans times unsuccessfully, an error message is displayed
  • _netdev Mounts a share only ofater the networking has been started.
  • remount Attempts to remont an already mounted share with, perhaps,different options.
  • rw/ro[rw]rw allows file modifications and ro prevents file modifications.
  • sec=mode[sys] Specified the type of security. Default used UIDs and GIDs. Additional choices are krb5, krb5i and krb5p.
  • suid/nosuid[suid] Allows users to run setuid and setgid programs.

See man mount and man exports for all options.

Mount a Share on NFS Client

Access and mount the /common share on server2. Create mount point /nfsthcemnt and add an entry to the filesystem table for mount during boot. Confirm and test the mount.

Install the NFS package and create the mount point.

[root@server2 ~]# yum install nfs-utils
Installed Packages
nfs-utils.x86_64                               1:1.3.0-0.21.el7_2.1                                @updates
[root@server2 ~]# mkdir /nfsrhcemnt
[root@server2 ~]#

Set the rpcbind service to autostart at system reboots and start the service.

[root@server2 ~]# systemctl enable rpcbind
Created symlink from /etc/systemd/system/sockets.target.wants/rpcbind.socket to /usr/lib/systemd/system/rpcbind.socket.
[root@server2 ~]# systemctl start rpcbind' 
[root@server2 ~]# systemctl status rpcbind
â rpcbind.service - RPC bind service
  Loaded: loaded (/usr/lib/systemd/system/rpcbind.service; indirect; vendor preset: enabled)
  Active: active (running) since Fri 2016-07-01 11:59:53 CEST; 7s ago
  Process: 26411 ExecStart=/sbin/rpcbind -w ${RPCBIND_ARGS} (code=exited, status=0/SUCCESS)
 Main PID: 26412 (rpcbind)
   CGroup: /system.slice/rpcbind.service
           ââ26412 /sbin/rpcbind -w
Jul 01 11:59:52 server2 systemd[1]: Starting RPC bind service...
Jul 01 11:59:53 server2 systemd[1]: Started RPC bind service.
[root@server2 ~]#

Open /etc/fstab and add the following entry.

[root@server2 ~]# cat /etc/fstab
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=16ad26a9-2cf6-44ac-bc0d-832be1ef8911 /boot xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
server1.roggeware.nl:/common    /nfsrhcemnt     nfs     _netdev,rw      0 0  <===
[root@server2 ~]#
[root@server2 ~]# mount /nfsrhcemnt
[root@server2 ~]# df -h
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/centos-root       8.5G  1.8G  6.8G  21% /
...
/dev/vda1                     497M  277M  221M  56% /boot
server1.roggeware.nl:/common  8.5G  2.3G  6.3G  27% /nfsrhcemnt
[root@server2 ~]#

Create file /nfsrhcemnt/nfsrhcetest and confirm the creation.

[root@server2 /]# echo aap>/nfsrhcemnt/nfsrhcetest
[root@server2 /]# ls -l /nfsrhcemnt/nfsrhcetest
-rw-r--r--. 1 root root 4 Jul  1  2016 /nfsrhcemnt/nfsrhcetest
[root@server2 /]#

Export a Share for Group Collaboration on NFS Client

On server1 create a group, add members, create a direcotry, enable gid and export it to server2. On server2 create users and group, create mountpoint, add entry to /etc/fstab and mount the share. Confirm mount and permissions.

Add group, users and directory, set ownership and enable setgid. And verify configuration.

[root@server1 ~]# groupadd -g 7777 nfssdatagrp
[root@server1 ~]# usermod -G nfssdatagrp user3
[root@server1 ~]# usermod -G nfssdatagrp user4
[root@server1 ~]# mkdir /nfssdata
[root@server1 ~]# chown nfsnobody:nfssdatagrp /nfssdata
[root@server1 ~]# chmod 2770 /nfssdata
[root@server1 ~]# ll -d /nfssdata
drwxrws---. 2 nfsnobody nfssdatagrp 36 Feb 12 11:15 /nfsdata
[root@server1 ~]#

Add the following line to /etc/exports and export the entry.

[root@server1 ~]# cat /etc/exports
/common         server2.roggeware.nl(rw,no_root_squash)
/nfssdata       server2.roggeware.nl(rw,no_root_squash)
#[root@server1 ~]# exportfs -avr
exporting server2:/nfsdata
exporting server2:/common
[root@server1 ~]#

Show contents of /var/lib/nfs/etab.

[ root@server1 ~]# cat /var/lib/nfs/etab
/nfsdata        server2(rw,sync,wdelay,hide,nocrossmnt,secure,no_root_squash,no_all_squash,no_subtree_check,secure_locks,acl,no_pnfs,anonuid=65534,anongid=65534,sec=sys,rw,secure,no_root_squash,no_all_squash)
/nfsrhcsa       server2(ro,sync,wdelay,hide,nocrossmnt,secure,root_squash,no_all_squash,no_subtree_check,secure_locks,acl,no_pnfs,anonuid=65534,anongid=65534,sec=sys,ro,secure,root_squash,no_all_squash)
/common server2(rw,sync,wdelay,hide,nocrossmnt,secure,no_root_squash,no_all_squash,no_subtree_check,secure_locks,acl,no_pnfs,anonuid=65534,anongid=65534,sec=sys,rw,secure,no_root_squash,no_all_squash)
[root@server1 ~]#

On the NFS client, server.

[root@server2 /]# groupadd -g 7777 nfssdatagrp
[root@server2 /]# useradd user3;useradd user4
[root@server2 /]# echo user123|passwd --stdin user3
Changing password for user user3.
passwd: all authentication tokens updated successfully.
[root@server2 /]# echo user123|passwd --stdin user4
Changing password for user user4.
passwd: all authentication tokens updated successfully.
[root@server2 /]# usermod -G nfssdatagrp user3
[root@server2 /]# usermod -G nfssdatagrp user4

Open /etc/fstab and add the following entry.

[root@server2 /]# cat /etc/fstab
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=16ad26a9-2cf6-44ac-bc0d-832be1ef8911 /boot xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
server1.roggeware.nl:/common    /nfsrhcemnt     nfs     _netdev,rw      0 0
server1.roggeware.nl:/nfsdata   /nfssdatamnt    nfs     _netdev,rw      0 0   <===
[root@server2 /]#

Create the mountpoint and mount the share and confirm the mount.

[root@server2 /]# mkdir /nfssdatamnt/
[root@server2 /]# mount /nfssdatamnt
[root@server2 /]# df -h
Filesystem                     Size  Used Avail Use% Mounted on
/dev/mapper/centos-root        8.5G  1.8G  6.8G  21% /
devtmpfs                       487M     0  487M   0% /dev
tmpfs                          497M     0  497M   0% /dev/shm
tmpfs                          497M   57M  441M  12% /run
tmpfs                          497M     0  497M   0% /sys/fs/cgroup
/dev/vda1                      497M  277M  221M  56% /boot
tmpfs                          100M     0  100M   0% /run/user/0
server1.roggeware.nl:/common   8.5G  2.3G  6.3G  27% /nfsrhcemnt
server1.roggeware.nl:/nfssdata 8.5G  2.3G  6.3G  27% /nfssdatamnt
[root@server2 /]#

Confirm that /nfssdatamnt has proper permissions and owning group.

[root@server2 /]# ls -ld /nfsdatamnt/
drwxrws---. 2 nfsnobody nfsdatagrp 36 Feb 12 11:15 /nfsdatamnt/
[root@server2 /]#

Logon as user3 and create a file, and login as user4 and create another file. And verify the correct creation of the files.

[root@server2 nfsdatamnt]# su - user3
Last login: Fri Feb 12 11:14:40 CET 2016 on pts/0
[user3@server2 ~]$ cd /nfsdatamnt
[user3@server2 nfsdatamnt]$ echo Aapje>filecreatedbyuser3
[user3@server2 nfsdatamnt]$ ls -l
totaal 4
-rw-rw-r--. 1 user3 nfsdatagrp 0 12 feb 11:15 aapuser3
-rw-rw-r--. 1 user4 nfsdatagrp 0 12 feb 11:15 aapuser4
-rw-rw-r--. 1 user3 nfsdatagrp 6  1 jul  2016 filecreatedbyuser3
[user3@server2 nfsdatamnt]$ exit
uitgelogd
[root@server2 nfsdatamnt]# su - user4
Last login: Fri Feb 12 11:15:14 CET 2016 on pts/0
[user4@server2 ~]$ cd /nfsdatamnt/
[user4@server2 nfsdatamnt]$ echo Aapje>filecreatedbyuser4
[user4@server2 nfsdatamnt]$ ls -l
totaal 8
-rw-rw-r--. 1 user3 nfsdatagrp 0 12 feb 11:15 aapuser3
-rw-rw-r--. 1 user4 nfsdatagrp 0 12 feb 11:15 aapuser4
-rw-rw-r--. 1 user3 nfsdatagrp 6  1 jul  2016 filecreatedbyuser3
-rw-rw-r--. 1 user4 nfsdatagrp 6  1 jul  2016 filecreatedbyuser4
[user4@server2 nfsdatamnt]$ id
UID=1002(user4) GID=1002(user4) groepen=1002(user4),7777(nfsdatagrp) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[user4@server2 nfsdatamnt]$

Provide Secure Access to NFS Share with Kerberos

LAB 
server3 NFS server
server4 NFS client
kdc     Kerberos server

server1 Is the NFS server and server2 is the Kerberos server and NFS client.

server2 runs Kerberos services (both KDC and admin services) for realm EXAMPLE.COM and root user is added as an admin principal, DNS is disabled, the hosts file is updated with mappings for server1 and server2 and these servers are added as host principals (host/server1) and (host/server2) to the KDC database with their keytab files stored in the /etc directory by name krb5.keytab.

Exam tips:

  • You may have to copy an existing keytab file from a specified locationto the /etc directory.
  • You do not have to worry about updating the /etc/hosts file. DNS will be in place.

On the NFS server server1.

Create and export a /nfskrb5 directory with the following entry in /ext/exports.

[root@server1 ~]# cat /etc/exports
/common         server2.roggeware.nl(rw,no_root_squash)
/nfsrhcsa       server2.roggeware.nl(sync)
/nfsdata        server2.roggeware.nl(rw,no_root_squash)
/nfskrb5        server2.roggeware.nl(sec=krb5p,rw,no_root_squash)  <===
[root@server1 ~]#

Activate nfs-secure-server service at system reboot, start and verify the service.

[root@server1 ~]# systemctl enable nfs-secure-server    <=== Werkt niet op mijn CentOS 7, lijkt wel alleen voor RHEL7

On the NFS client server2.

Activate the nfs-secure server at system reboots, start and verify.

[root@server2 nfsdatamnt]# systemctl enable nfs-secure
Failed to execute operation: No such file or director
[root@server2 nfsdatamnt]# systemctl start nfs-secure
[root@server2 nfsdatamnt]# systemctl status nfs-secure
â rpc-gssd.service - RPC security service for NFS client and server
   Loaded: loaded (/usr/lib/systemd/system/rpc-gssd.service; static; vendor preset: disabled)
   Active: inactive (dead)
Condition: start condition failed at Fri 2016-07-01 15:45:46 CEST; 10s ago
           ConditionPathExists=/etc/krb5.keytab was not met 
Mar 21 23:16:09 server2 systemd[1]: Started RPC security service for NFS client and server.
Jul 01 12:09:08 server2 systemd[1]: Started RPC security service for NFS client and server.
Jul 01 15:45:46 server2 systemd[1]: Started RPC security service for NFS client and server.
[root@server2 nfsdatamnt]#

Open /etc/fstab and add the following entry.

/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=16ad26a9-2cf6-44ac-bc0d-832be1ef8911 /boot xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
server1.roggeware.nl:/common    /nfsrhcemnt     nfs     _netdev,rw      0 0
server1.roggeware.nl:/nfsdata   /nfsdatamnt     nfs     _netdev,rw      0 0
server1.roggeware.nl:/nfskrb5   /nfskrb5mnt     nfs     sec=krb5p       0 0    <===
[root@server2 nfsdatamnt]#
Create the mountpoint and mount the new share.
[root@server2 /]# mkdir /nfskrb5mnt
[root@server2 /]# mount /nfskrb5mnt
mount.nfs: an incorrect mount option was specified
[root@server2 /]

Monitoring NFS Activities

Monitoring NFS activities involves capturing and displaying read and write statistics on the NFS server and client. Tools as nfsstat, nfsiostat and mountstats are available.

The nfsstat command can be run on both the NFS server and client to produce NFS and RPC I/O statistics.

The nfsiostat command is an NFS client utility that produces read and write statistics for wach mounted share

The mountstat TOM

yum install nfs-utils
getsebool -a|grep nfs_export
setsebool -P nfs_export_all_ro=1 nfs_export_all_rw=1
firewall-cmd --add-service nfs
firewall-cmd --reload
firewall-cmd --list-services
systemctl enable rpcbind nfs-server
/etc/exports          /common server2.example.com(rw,no_root_squash)     
/etc/fstab            server1.example.com:/common     /nfsrhcemnt   nfs _netdev,rw 0 0
/var/lib/nfs/etab
/etc/sysconfig/nfs

exportfs -avr
exportfs -u server2.example.com:/common
man exports
nfsstat
nfsiostat
mountstats

Chapter 21 Sharing File Storage with Samba

Samba is a networking protocol that allows Linux and Unix systems to share file and print resources with Windows and other Linux and Unix systems. RHEL& includes the support for Samba v4.1, which uses the SMB3 prtocol that allows encrypted transport connections. The Samba service is configured with the help of a single configuration file and a few commands.

Understanding Samba

Server Message Block (SMB) now widely known as the Common Internet File System (CIFS).

The system that shares it file and print resources is referred to as a Samba server and the system that accesses those shared resources is referred to as a Samba client. A single system can be configured to provide both server and client functionality concurrently.

A Samba server can:

  • Act as a print server for windows systems.
  • Be configured as a Primary Domain Controller (PDC) and as a Backup Domain Controller. for a Samba-based PDC.
  • Be set up as an Active Directory member server on a Windows network.
  • Provide Windows Internet Name Service (WINS) name resolution.

Samba Daemon

Samba and CIFS are client/server protocols that employ the smbd daemon on the server to share and manage direcotries and filesystems This daemon process uses TCP port 445 for operation and it is also responsible for share locking and user authentication.

Samba Commands

There are numerous commands available to establish and manage Samba. A proper understanding of the usage of these commands is essential for smooth operation.

* mount        Mounts a Samba share specified at the command line or listed in the /etc/fstab file. Adds an entry to /etc/mtab
* mount.cifs   Mounts a Samba share on the client.
* pdbedit      Maintains a local user database in /var/lib/samba/private/smbpasswd on the server.
* smbclient    Connects to a Samba share to perform FTP-like operations.
* smbpasswd    Changes Samba user passwords.
* testparm     Tests the syntax of the smb.conf file
* umount

Samba Configuraiton and Functional Files

Samba references several files at startup and during its operation.

  • /etc/samba/smb.conf Samba server configuration file.
  • /etc/samba/smbusers Maintains Samba and Linux user mappings.
  • /etc/sysconfig/samba Contains directives used at Samba startup.
  • /var/lib/samba/private/smbpasswd Maintains Samba user passwords.
  • /var/log/samba Directory location for Samba logs.

Understanding Samba Configuration File

The /etc/samba/smb.conf file is the primary configuration file for setting up a Samba server. This file has two major sections: Global Settings and Share Definitions. An excerpt from this file:

[root@server1 ~]# cat /etc/samba/smb.conf
[global]
        workgroup = EXAMPLE
        server string = server1 is the Samba Server Sharing /common and /smbrhcsa
        interfaces = lo eth0 192.168.122.
        hosts allow = 127. 192.168.122. .roggeware.nl 
        log file = /var/log/samba/log.%m
        max log size = 5000
        security = user
        passdb backend = smbpasswd
[common]
        comment         = /common directory available to user10
        hosts deny      = 192.168.22.0/24
        browsable       = yes
        path            = /common
        public          = yes
        valid users     = user10
        write list      = user10
        writeable       = yes 
[smbrhcsa]
        comment         = /smbrhcsa directory available to user1
        browsable       = yes
        path            = /smbrhcsa
        public          = yes
        valid users     = user1
        write list      = user1
        writable        = yes
[root@server1 ~]#

Check the man pages for smb.conf for details.

Samba Software Packages

There are several packages that need to be installed.

[root@server1 ~]# yum list installed|grep samba
samba.x86_64                          4.2.10-6.2.el7_2               @updates
samba-client.x86_64                   4.2.10-6.2.el7_2               @updates
samba-client-libs.x86_64              4.2.10-6.2.el7_2               @updates
samba-common.noarch                   4.2.10-6.2.el7_2               @updates
samba-common-libs.x86_64              4.2.10-6.2.el7_2               @updates
samba-common-tools.x86_64             4.2.10-6.2.el7_2               @updates
samba-libs.x86_64                     4.2.10-6.2.el7_2               @updates
[root@server1 ~]#
  • samba Provides Sambe server support.
  • samba-client Includes utuilites for operations on server and client.
  • samba-common Provides Samba man pages, commands and configuration files.
  • samba-libs Contains library routines used by Samba server and client.
  • cifs-utils Client-side utilities for managing CIFS shares.

A Samba server needs all packages exept for the cifs-utils package. On the client side only cifs-utils and samba-client packages are needed.

Configuring Samba Server and Client

This section presents several exercises to set up the Samba service and share a directory or file system.

SELinux Requirements for Samba Operation

Let's look at the Samba-specific SELinux contexts on processes and files and also see the booleans that may need to be modified for Samba to function properly. The Samba daemon is confied by defalt and is labeled appropiately with smbd_t domain type. This can be verified with the following.

[root@server1 ~]# ps -efZ|grep smbd
system_u:system_r:smbd_t:s0     root      2301     1  0 Jun30 ?        00:00:04 /usr/sbin/smbd
system_u:system_r:smbd_t:s0     root      4790  2301  0 Jun30 ?        00:00:00 /usr/sbin/smbd
[root@server1 ~]#

Similarly, Samba configuration and functional files already have proper SELinux contexts in place; therefore they need no modifications. For instance, the context on the /etc/samba/smb.conf file is.

[root@server1 ~]# ls -lZ /etc/samba/smb.conf
-rw-r--r--. root root system_u:object_r:samba_etc_t:s0 /etc/samba/smb.conf
[root@server1 ~]#

However, any direcotry or file system that you want to share on the network with Samba alone needs to have samba_share_t type applied to it. In case of multiple file-sharing services such as a combination of CIFS and NFS, sharing the same directory or filesystem, you will need to use euther the public_content_ro_t or public_content_rw_t type instead.

There is one boolean called samba_share_nfs which is enabled in case the same directory or filesystem is shared via both NFS and CIFS. To list Samba-related booleans, run the getsebool command as follows.

[root@server1 ~]# getsebool -a|egrep 'samba|smb|cifs'
cobbler_use_cifs --> off
ftpd_use_cifs --> off
git_cgi_use_cifs --> off
git_system_use_cifs --> off
httpd_use_cifs --> off
ksmtuned_use_cifs --> off
mpd_use_cifs --> off
polipo_use_cifs --> off
samba_create_home_dirs --> off
samba_domain_controller --> off
samba_enable_home_dirs --> off
samba_export_all_ro --> on                       <=== Allows/disallows Samba to share in read-only mode
samba_export_all_rw --> on                       <=== Allows/disallows Samba to share in read-write mode
samba_load_libgfapi --> off
samba_portmapper --> off
samba_run_unconfined --> off
samba_share_fusefs --> off
samba_share_nfs --> on
sanlock_use_samba --> off
smbd_anon_write --> off                          <=== Allows/disallows Samba to write to public directories with public_content_rw_t type
tmpreaper_use_samba --> off
use_samba_home_dirs --> off
virt_sandbox_use_samba --> off
virt_use_samba --> off
[root@server1 ~]#

Some of the booleans will be used in the exercises.

Provide Network Shares to Samba Client

Exercise done on server1.

part1: Share /common direcotry (path) which you also share via NFS in the previous chapter. Make this share browsable with login (vald users) and write access (writeable) given only to user10 (write list) from systems in the example.com domain. This share should have read-only access (public) given to user3 and it should not be accessible (hosts deny) from 192.168.2.0/24 network.

part2: Create a direcotry /smbrhcsa (path) in browsable mode (browsable) with loing (valid users) and write (writable) access aloocated only to (write list) user1 and read-only (public) access to user3.

Arrange proper SELinux controls and allow it through the firewall.

Install Samba server package samba and samba-client and create directory /smbrhcsa.

[root@server1 ~]# yum install samba samba-client
Package samba-4.2.10-6.2.el7_2.x86_64 already installed and latest version
Package samba-client-4.2.10-6.2.el7_2.x86_64 already installed and latest version
Nothing to do
[root@server1 ~]# mkdir /smbrhcsa
[root@server1 ~]#

Activate the SELinux Booleans persistently to allow Samba shares in both read-only and read-write modes to share /common and verify the activation.

[root@server1 ~]# setsebool -P samba_export_all_ro=1 samba_export_all_rw=1 samba_share_nfs=1
[root@server1 ~]# getsebool samba_export_all_ro samba_export_all_rw samba_share_nfs
samba_export_all_ro --> on
samba_export_all_rw --> on
samba_share_nfs --> on
[root@server1 ~]#

Add SELinux file types public_content_rw_t on /common and samba_share_t on /smbrhcsa directories to the SELinux policies and apply the new contexts on both directories and confirm.

[root@server1 ~]# semanage fcontext -at public_content_rw_t "/common(/.*)?"
[root@server1 ~]# semanage fcontext -at samba_share_t "/smbrhcsa(/.*)?"
[root@server1 ~]# ls -lZd /common
drwxr-xr-x. root root unconfined_u:object_r:samba_share_t:s0 /common
[root@server1 ~]# restorecon /common /smbrhcsa
[root@server1 ~]# ls -lZd /common /smbrhcsa
drwxr-xr-x. root root unconfined_u:object_r:public_content_rw_t:s0 /common
drwxr-xr-x. root root unconfined_u:object_r:samba_share_t:s0 /smbrhcsa
[root@server1 ~]#

Add the Samba service persistently to the firewalld configuration to allow Samba trafixpon TCP port 445.

[root@server1 ~]# firewall-cmd --permanent --add-service samba
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-service
dhcpv6-client dns http https mysql nfs ntp samba ssh
[root@server1 ~]#

Rename /etc/samba/smb.conf to smb.conf.original and create a new smb.conf.

[root@server1 samba]# cat smb.conf
[global]
        workgroup = EXAMPLE
        server string = server1 is the Samba Server Sharing /common and /smbrhcsa
        interfaces = lo eth0 192.168.122.
        hosts allow = 127. 192.168.122. .roggeware.nl
        log file = /var/log/samba/log.%m
        max log size = 5000
        security = user
        passdb backend = smbpasswd
[common]
        comment         = /common directory available to user10
        hosts deny      = 192.168.22.0/24
        browsable       = yes
        path            = /common
        public          = yes
        valid users     = user10
        write list      = user10
        writeable       = yes
[smbrhcsa]
        comment         = /smbrhcsa directory available to user1
        browsable       = yes
        path            = /smbrhcsa
        public          = yes
        valid users     = user1
        write list      = user1
        writable        = yes
[root@server1 samba]#

Execute the testparm command to check for syntax errors. Use the -v switch to dispolay other default values that are not defined in the file.

[root@server1 samba]# testparm
Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
Processing section "[common]"
Processing section "[smbrhcsa]"
Loaded services file OK.
Server role: ROLE_STANDALONE
Press enter to see a dump of your service definitions
# Global parameters
[global]
        workgroup = EXAMPLE
...
[smbrhcsa]
        comment = /smbrhcsa directory available to user1
        path = /smbrhcsa
        valid users = user1
        write list = user1
        read only = No
        guest ok = Yes
[root@server1 samba]#

Create Linux user user10 with password user123 and add user10 to Samba user database /var/lib/samba/private/smbpasswd and assign password user123. Show the contents of the smbpasswd file.

[root@server1 samba]# useradd user10
[root@server1 samba]# echo user123|passwd --stdin user10
Changing password for user user10.
passwd: all authentication tokens updated successfully.
[root@server1 samba]# smbpasswd -a user10
New SMB password:
Retype new SMB password:
[root@server1 samba]# cat /var/lib/samba/private/smbpasswd
user10:1005:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:EACB2C6A3AAA4ED476ED2741BE8C7A4E:[U          ]:LCT-5776D0FA:
[root@server1 samba]#

Display (-L) the user information verbosely using the pdbedit command.

[root@server1 samba]# pdbedit -Lv
--------------
Unix username:        user10
NT username:
Account Flags:        [U          ]
User SID:             S-1-5-21-2626351804-4208986171-2860593508-3010
Primary Group SID:    S-1-5-21-2626351804-4208986171-2860593508-513
Full Name:
Home Directory:       \\server1\user10
HomeDir Drive:
Logon Script:
Profile Path:         \\server1\user10\profile
Domain:               SERVER1
Account desc:
Workstations:
Munged dial:
Logon time:           0
Logoff time:          never
Kickoff time:         never
Password last set:    Fri, 01 Jul 2016 22:22:18 CEST
Password can change:  Fri, 01 Jul 2016 22:22:18 CEST
Password must change: never
Last bad password   : 0
Bad password count  : 0
Logon hours         : FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
[root@server1 samba]#

Set the Samba service smb to autostart at system reboot, start the service and confirm the status.

[root@server1 samba]# systemctl enable smb
[root@server1 samba]# systemctl start smb
[root@server1 samba]# systemctl status smb
â smb.service - Samba SMB Daemon
   Loaded: loaded (/usr/lib/systemd/system/smb.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2016-06-30 13:03:55 CEST; 1 day 9h ago
 Main PID: 2301 (smbd)
   Status: "smbd: ready to serve connections..."
   CGroup: /system.slice/smb.service
           ââ2301 /usr/sbin/smbd
           ââ4790 /usr/sbin/smbd
Jul 01 21:47:10 server1 smbd[4790]:   failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL
Jul 01 22:00:11 server1 smbd[22389]: [2016/07/01 22:00:11.319557,  0] ../source3/printing/print_cups...ect)
Jul 01 22:00:11 server1 smbd[22389]:   Unable to connect to CUPS server localhost:631 - Transport en...cted
Jul 01 22:00:11 server1 smbd[4790]: [2016/07/01 22:00:11.323154,  0] ../source3/printing/print_cups...back)
Jul 01 22:00:11 server1 smbd[4790]:   failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL
Jul 01 22:13:11 server1 smbd[23176]: [2016/07/01 22:13:11.799842,  0] ../source3/printing/print_cups...ect)
Jul 01 22:13:11 server1 smbd[23176]:   Unable to connect to CUPS server localhost:631 - Transport en...cted
Jul 01 22:13:11 server1 smbd[4790]: [2016/07/01 22:13:11.803140,  0] ../source3/printing/print_cups...back)
Jul 01 22:13:11 server1 smbd[4790]:   failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL
Jul 01 22:25:59 server1 systemd[1]: Started Samba SMB Daemon.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server1 samba]#

List (-L) the shares available on the server as user10 (-U) using the smbclient command.

[root@server1 samba]# smbclient -L //localhost -U user10
Enter user10's password:
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
        Sharename       Type      Comment
        ---------       ----      -------
        common          Disk      /common directory available to user10
        smbrhcsa        Disk      /smbrhcsa directory available to user1
        IPC$            IPC       IPC Service (server1 is the Samba Server Sharing /common and /smbrhcsa)
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
        Server               Comment
        ---------            -------
        Workgroup            Master
        ---------            -------
[root@server1 samba]#

The Samvba service is now set up on server1 with /common and //smbrhcsa shared over the network and are available for accessing and mounting on the client.

Access and Mount a Share on Samba client

On server2, access and mount the /common share exported in the previous exercise. Create user10 with same UID as used on server1. Create mount point /smbrhcemnt and add an entry to the filesystem table to enable mounting at boot. Confirm share access and mountusign commands, test access by creating a file in the mount point and viewing it on the Samba server. Store username and password for user10 in a file owned by root with 0400 permissions.

Install the Samba client package samba-client and cifs-utils.

[root@server2 ~]# yum install samba-client cifs-utils
Package samba-client-4.2.10-6.2.el7_2.x86_64 already installed and latest version
Package cifs-utils-6.2-7.el7.x86_64 already installed and latest version
Nothing to do
[root@server2 ~]#

Create Linux user user10 with password user123

[root@server1 ~]# id user10
uid=1005(user10) gid=1005(user10) groups=1005(user10),7778(dba)
root@server2 ~]# useradd user10
[root@server2 ~]# echo user123|passwd --stdin user10
Changing password for user user10.
passwd: all authentication tokens updated successfully.
[root@server2 ~]# id user10
uid=1005(user10) gid=1005(user10) groups=1005(user10)
[root@server2 ~]#

List (-L) what shares are available from server1 using the smbclient command.

[root@server2 ~]# smbclient -L //server1/common -U user10
Enter user10's password:
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
        Sharename       Type      Comment
        ---------       ----      -------
        common          Disk      /common directory available to user10
        smbrhcsa        Disk      /smbrhcsa directory available to user1
        IPC$            IPC       IPC Service (server1 is the Samba Server Sharing /common and /smbr         hcsa)
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
        Server               Comment
        ---------            -------
        Workgroup            Master
        ---------            -------
[root@server2 ~]#

Logon to the /common share as user10 using the cmbclient cpmmand.

[root@server2 ~]# smbclient -L //server1/common -U user10
Enter user10's password:
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10] 
        Sharename       Type      Comment
        ---------       ----      -------
        common          Disk      /common directory available to user10
        smbrhcsa        Disk      /smbrhcsa directory available to user1
        IPC$            IPC       IPC Service (server1 is the Samba Server Sharing /common and /smbr         hcsa)
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10] 
        Server               Comment
        ---------            -------
        Workgroup            Master
       ---------            -------
[root@server2 ~]# smbclient //server1/common -U user10
Enter user10's password:
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
smb: \>

The connection is successfully established with the /common share. You can run the help command, use ls to list files, use get/mget and put/mput to transfer one or more files. Issue exit when done.

Create mount point /smbrhcemnt and mount /common/ on /smbrhcemnt as user10.

[root@server2 ~]# mkdir /smbrhcemnt
[root@server2 ~]# mount //server1/common /smbrhcemnt -o username=user10
Password for user10@//server1/common:  *******
[root@server2 ~]# 

Command man mount.cifs describes, amongst others, the options username and credentials.

Execute the df and mount commands to check the status of the share.

[root@server2 ~]#df -h
Filesystem                     Size  Used Avail Use% Mounted on
/dev/mapper/centos-root        8.5G  1.8G  6.8G  21% /
devtmpfs                       487M     0  487M   0% /dev
tmpfs                          497M     0  497M   0% /dev/shm
tmpfs                          497M   57M  441M  12% /run
tmpfs                          497M     0  497M   0% /sys/fs/cgroup
/dev/vda1                      497M  277M  221M  56% /boot
server1.roggeware.nl:/common   8.5G  2.3G  6.3G  27% /nfsrhcemnt
server1.roggeware.nl:/nfsdata  8.5G  2.3G  6.3G  27% /nfsdatamnt
tmpfs                          100M     0  100M   0% /run/user/0
//server1/common               8.5G  2.3G  6.3G  27% /smbrhcemnt      <===
[root@server2 smbrhcemnt]# mount|grep smbrhce
//server1/common on /smbrhcemnt type cifs  (rw,relatime,vers=1.0,cache=strict,username=user10,domain=SERVER1,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.122.101,unix,posixpaths,serverino,acl,rsize=1048576,wsize=65536,actimeo=1)
[root@server2 smbrhcemnt]#

Create a file called /etc/samba/smbrhcecred and add the credentials for user10 to it.

[root@server2 smbrhcemnt]# cat /etc/samba/smbrhcecred
username=user10
password=user123
[root@server2 smbrhcemnt]# ls -l /etc/samba/smbrhcecred
-rwxr-xr-x. 1 root root 33 Jul  2 19:30 /etc/samba/smbrhcecred
[root@server2 smbrhcemnt]# chown root /etc/samba/smbrhcecred
[root@server2 smbrhcemnt]# chmod 0400 /etc/samba/smbrhcecred
[root@server2 smbrhcemnt]# ls -l /etc/samba/smbrhcecred
-r--------. 1 root root 33 Jul  2 19:30 /etc/samba/smbrhcecred
[root@server2 smbrhcemnt]#

Open /etc/fstab and add the following entry.

[root@server2 smbrhcemnt]# cat /etc/fstab
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=16ad26a9-2cf6-44ac-bc0d-832be1ef8911 /boot xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
server1.roggeware.nl:/common    /nfsrhcemnt     nfs     _netdev,rw      0 0
server1.roggeware.nl:/nfsdata   /nfsdatamnt     nfs     _netdev,rw      0 0
server1.roggeware.nl:/nfskrb5   /nfskrb5mnt     nfs     sec=krb5p       0 0
//server1/common                /smbrhcemnt     cifs    _netdev,rw,credentials=/etc/samba/etc/samba/smbrhcecred 0 0   <===
[root@server2 smbrhcemnt]#

Add the _netdev option to instruct the system to wait for networking to establish before attempting to mount this filesystem.

Create a file called smbrhcetest as user10 under /smbrhcemnt and confirm its creation by running ll on the Samba server.

ERROR Schrijven file door user10 lukt hier niet

Provide a Share for Group Collaboration on Samba Client

In this exercise you will create on server1 users user11 and user12 and a group called smbgrp. Add the users to this group, create directory /smbsdata, set owning group to dmbgrp, permssion 0770 and share /smbsdata for group collaboration. Create on server2 users user11 and user12 and group smbgrp, add both users to this group as members. Create /smbsdatamnt mount point for this share and add an entry to /etc/fstab. Mount the share on /smbsdatamnt and confirm the mount. Login as user3 and user4 and create files for group collaboration.

On server1 create user11 and user12 with password user123, add group smbgrp with GID 8888, add the users as members to group 'smbgrp and create the smbsdata directory.

[root@server1 ~]# useradd user11;useradd user12
[root@server1 ~]# echo user123|passwd --stdin user11
Changing password for user user11.
passwd: all authentication tokens updated successfully.
[root@server1 ~]# echo user123|passwd --stdin user12
Changing password for user user12.
passwd: all authentication tokens updated successfully.
[root@server1 ~]# groupadd -g 8888 smbgrp
[root@server1 ~]# usermod -G smbgrp user11 
[root@server1 ~]# usermod -G smbgrp user12
[root@server1 ~]# mkdir /smbsdata
[root@server1 ~]#

Set owning group on /smbsdata to smbgrp and set permissions to 0770.

[root@server1 ~]# chgrp smbgrp /smbsdata/
[root@server1 ~]# chmod 0770 /smbsdata/
[root@server1 ~]# ls -ld /smbsdata/
drwxrwx---. 2 root smbgrp 6 Jul  3 14:20 /smbsdata/
[root@server1 ~]#

Activate the SELinux booleans persistently to allow the share in both read-only and read/write modes and verify the activation.

[root@server1 ~]# setsebool  -P samba_export_all_ro=1 samba_export_all_rw=1
getsebool samba_export_all_ro samba_export_all_rw
[root@server1 ~]# getsebool samba_export_all_ro samba_export_all_rw
samba_export_all_ro --> on
samba_export_all_rw --> on
[root@server1 ~]#

Add SELinux file context with type samba_share_t on /smbsdata to the SELinux policiy rules, apply the new contect on the directory and confirm. Use command seinfo -t to list all available types.

[root@server1 ~]# semanage fcontext -at samba_share_t "/smbsdata(/.*)?"
[root@server1 ~]# restorecon -v /smbsdata
restorecon reset /smbsdata context unconfined_u:object_r:default_t:s0->unconfined_u:object_r:samba_share_t:s0
[root@server1 ~]# ls -ldZ /smbsdata
drwxrwx---. root smbgrp unconfined_u:object_r:samba_share_t:s0 /smbsdata
[root@server1 ~]#

Add the Samba service persistently to the firewalld configuration to allow Samba traffix on TCP port 445, and load the rule.

[root@server1 ~]# firewall-cmd --permanent --add-service samba
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-services
dhcpv6-client dns http https mysql nfs ntp samba ssh
[root@server1 ~]#

Append the following to /etc/samba/smb.config and verify the configuration.

[smbsdata]

       comment         = /smbsdata directory for group collaboration
       browsable       = yes
       path            = /smbsdata
       public          = no
       valid users     = @smbgrp
       write list      = @smbgrp
       writeable       = yes
       force group     =+smbgrp
       create mask     = 0770
[root@server1 ~]# testparm
Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
Processing section "[common]"
Processing section "[smbrhcsa]"
Processing section "[smbsdata]"
Loaded services file OK.
Server role: ROLE_STANDALONE
Press enter to see a dump of your service definitions
# Global parameters
[global]
       workgroup = EXAMPLE
...
[smbsdata]
        comment = /smbsdata directory for group collaboration
        path = /smbsdata
        valid users = @smbgrp
        write list = @smbgrp
        force group = +smbgrp
        read only = No
        create mask = 0770
[root@server1 ~]#

Add user11 and user12 to the Samba user database /var/lib/samba/private/smbpasswd and assign them password user123.

[root@server1 ~]# smbpasswd -a user11
New SMB password:
Retype new SMB password:
Added user user11.
[root@server1 ~]# smbpasswd -a user12
New SMB password:
Retype new SMB password:
Added user user12.
[root@server1 ~]# cat /var/lib/samba/private/smbpasswd
user10:1005:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:EACB2C6A3AAA4ED476ED2741BE8C7A4E:[U          ]:LCT-5776D0FA:
user11:1006:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:EACB2C6A3AAA4ED476ED2741BE8C7A4E:[U          ]:LCT-577908F8:
user12:1008:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:EACB2C6A3AAA4ED476ED2741BE8C7A4E:[U          ]:LCT-577908FE:
[root@server1 ~]#

Display the user information using the pdbedit command.

[root@server1 ~]# pdbedit -Lv
---------------
Unix username:        user10
NT username:
Account Flags:        [U          ]
User SID:             S-1-5-21-2626351804-4208986171-2860593508-3010
Primary Group SID:    S-1-5-21-2626351804-4208986171-2860593508-513
Full Name:
Home Directory:       \\server1\user10
HomeDir Drive:
Logon Script:
Profile Path:         \\server1\user10\profile
Domain:               SERVER1
Account desc:
Workstations:
Munged dial:
Logon time:           0
Logoff time:          never
Kickoff time:         never
Password last set:    Fri, 01 Jul 2016 22:22:18 CEST
Password can change:  Fri, 01 Jul 2016 22:22:18 CEST
Password must change: never
Last bad password   : 0
Bad password count  : 0
Logon hours         : FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
---------------
Unix username:        user11
NT username:
Account Flags:        [U          ]
User SID:             S-1-5-21-2626351804-4208986171-2860593508-3012
Primary Group SID:    S-1-5-21-2626351804-4208986171-2860593508-513
Full Name:
Home Directory:       \\server1\user11
HomeDir Drive:
Logon Script:
Profile Path:         \\server1\user11\profile
Domain:               SERVER1
Account desc:
Workstations:
Munged dial:
Logon time:           0
Logoff time:          never
Kickoff time:         never
Password last set:    Sun, 03 Jul 2016 14:45:44 CEST
Password can change:  Sun, 03 Jul 2016 14:45:44 CEST
Password must change: never
Last bad password   : 0
Bad password count  : 0
Logon hours         : FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
---------------
Unix username:        user12
NT username:
Account Flags:        [U          ]
User SID:             S-1-5-21-2626351804-4208986171-2860593508-3016
Primary Group SID:    S-1-5-21-2626351804-4208986171-2860593508-513
Full Name:
Home Directory:       \\server1\user12
HomeDir Drive:
Logon Script:
Profile Path:         \\server1\user12\profile
Domain:               SERVER1
Account desc:
Workstations:
Munged dial:
Logon time:           0
Logoff time:          never
Kickoff time:         never
Password last set:    Sun, 03 Jul 2016 14:45:50 CEST
Password can change:  Sun, 03 Jul 2016 14:45:50 CEST
Password must change: never
Last bad password   : 0
Bad password count  : 0
Logon hours         : FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
[root@server1 ~]#

Set the Samba service to autostart at boot, start the service and verify the status.

[root@server1 ~]# systemctl enable smb
[root@server1 ~]# systemctl start smb
[root@server1 ~]# systemctl status smb
â smb.service - Samba SMB Daemon
   Loaded: loaded (/usr/lib/systemd/system/smb.service; enabled; vendor preset: disabled)
   Active: active (running) since Sat 2016-07-02 19:53:37 CEST; 18h ago
 Main PID: 26729 (smbd)
   Status: "smbd: ready to serve connections..."
   CGroup: /system.slice/smb.service
           ââ26729 /usr/sbin/smbd
           ââ26731 /usr/sbin/smbd
           ââ26748 /usr/sbin/smbd
Jul 03 14:20:18 server1 smbd[29822]:   Unable to connect to CUPS server localhost:631 - Trans...cted
Jul 03 14:20:18 server1 smbd[26731]: [2016/07/03 14:20:18.311007,  0] ../source3/printing/pri...ack)
Jul 03 14:20:18 server1 smbd[26731]:   failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL
Jul 03 14:33:18 server1 smbd[26731]: [2016/07/03 14:33:18.790280,  0] ../source3/printing/pri...ack)
Jul 03 14:33:18 server1 smbd[26731]:   failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL
Jul 03 14:46:19 server1 smbd[30289]: [2016/07/03 14:46:19.128314,  0] ../source3/printing/pri...ect)
Jul 03 14:46:19 server1 smbd[30289]:   Unable to connect to CUPS server localhost:631 - Trans...cted
Jul 03 14:46:19 server1 smbd[26731]: [2016/07/03 14:46:19.130632,  0] ../source3/printing/pri...ack)
Jul 03 14:46:19 server1 smbd[26731]:   failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL
Jul 03 14:50:40 server1 systemd[1]: Started Samba SMB Daemon.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server1 ~]#

List the shares available on the server as user11 using the smbclient command:

[root@server1 ~]# smbclient -L //server1 -U user11
Enter user11's password:
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
        Sharename       Type      Comment
        ---------       ----      -------
        common          Disk      /common directory available to user10
        smbrhcsa        Disk      /smbrhcsa directory available to user1
        smbsdata        Disk      /smbsdata directory for group collaboration
        IPC$            IPC       IPC Service (server1 is the Samba Server Sharing /common and /smbrhcsa)
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
        Server               Comment
        ---------            -------
        Workgroup            Master
        ---------            -------
[root@server1 ~]#

On server2, the Samba client, create users user11 and user12 with password user123 (matching UIDs/GIDs as on server1). Create group smbgrp with GID 8888 and add user user11 and user12 as members to this group.

[root@server2 ~]# useradd user11;useradd user12
[root@server2 ~]# echo user123|passwd --stdin user11
Changing password for user user11.
passwd: all authentication tokens updated successfully.
[root@server2 ~]# echo user123|passwd --stdin user12
Changing password for user user12.
passwd: all authentication tokens updated successfully.
[root@server2 ~]# groupadd -g 888 smbgrp
[root@server2 ~]# usermod -G smbgrp user11
[root@server2 ~]# usermod -G smbgrp user12
[root@server2 ~]#

Lis (-L) what shares are available from server1 using the smbclient command.

[root@server2 ~]# smbclient -L //server1 -U user11
Enter user11's password:
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]   
        Sharename       Type      Comment
        ---------       ----      -------
        common          Disk      /common directory available to user10
        smbrhcsa        Disk      /smbrhcsa directory available to user1
        smbsdata        Disk      /smbsdata directory for group collaboration
        IPC$            IPC       IPC Service (server1 is the Samba Server Sharing /common and /smbrhcsa)
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
        Server               Comment
        ---------            -------
        Workgroup            Master
        ---------            -------
[root@server2 ~]#

Logon to the /smbsdata share as user11 using the smbclient command.

[root@server2 ~]# smbclient //server1/smbsdata -U user11
Enter user11's password:
Domain=[EXAMPLE] OS=[Windows 6.1] Server=[Samba 4.2.10]
smb: \>

Create /smbsdatamnt mountpoint and mount /smbsdata on the smbsdatamnt mount point as user11.

[root@server2 ~]# mkdir /smbsdatamnt
[root@server2 ~]# mount //server1/smbsdata /smbsdatamnt -o username=user11
Password for user11@//server1/smbsdata:  *******
[root@server2 ~]#

Execute the df and mount commandsto check the status of the share.

[root@server2 ~]# df
Filesystem                    1K-blocks    Used Available Use% Mounted on

/dev/mapper/centos-root 8869888 1822608 7047280 21% / //server1/common 8869888 2331940 6537948 27% /smbrhcemnt tmpfs 101692 0 101692 0% /run/user/0 //server1/smbsdata 8869888 2331940 6537948 27% /smbsdatamnt <=== [root@server2 ~]# mount

...

/dev/vda1 on /boot type xfs (rw,relatime,seclabel,attr2,inode64,noquota) server1.roggeware.nl:/common on /nfsrhcemnt type nfs4 (rw,relatime,vers=4.0,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.122.102,local_lock=none,addr=192.168.122.101,_netdev) server1.roggeware.nl:/nfsdata on /nfsdatamnt type nfs4 (rw,relatime,vers=4.0,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.122.102,local_lock=none,addr=192.168.122.101,_netdev) //server1/common on /smbrhcemnt type cifs (rw,relatime,vers=1.0,cache=strict,username=user10,domain=SERVER1,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.122.101,unix,posixpaths,serverino,acl,rsize=1048576,wsize=65536,actimeo=1) //server1/smbsdata on /smbsdatamnt type cifs (rw,relatime,vers=1.0,cache=strict,username=user11,domain=SERVER1,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.122.101,unix,posixpaths,serverino,acl,rsize=1048576,wsize=65536,actimeo=1) [root@server2 ~]#

Create /etc/samba/smbsdatacred file and add the credentials for user11 to it so that this user is able to mount this share. Set ownership to root and file permissions to 0400.

[root@server2 ~]# cat /etc/samba/smbsdatacred
username=user11
password=user123
[root@server2 ~]# chown root  /etc/samba/smbsdatacred
[root@server2 ~]# chmod 0400 /etc/samba/smbsdatacred
[root@server2 ~]# ls -l /etc/samba/smbsdatacred
-r--------. 1 root root 33 Jul  3 22:18 /etc/samba/smbsdatacred
[root@server2 ~]#

Add the following entry to /etc/fstab// to mount the share at reboot. Perform umount mount to test the new fstab entry.

[root@server2 ~]# cat /etc/fstab
...
server1.roggeware.nl:/common    /nfsrhcemnt     nfs     _netdev,rw      0 0
server1.roggeware.nl:/nfsdata   /nfsdatamnt     nfs     _netdev,rw      0 0
server1.roggeware.nl:/nfskrb5   /nfskrb5mnt     nfs     sec=krb5p       0 0
//server1/common                /smbrhcemnt     cifs    rw,credentials=/etc/samba/smbrhcecred 0 0
//server1/smbsdata               /smbsdatamnt  cifs    _netdev,rw,credentials=/etc/samba/smbsdatacred  0 0
[root@server2 ~]#
[root@server2 ~]# umount /smbsdatamnt
[root@server2 ~]# mount /smbsdatamnt
[root@server2 ~]# mount|grep sdata
server1.roggeware.nl:/nfsdata on /nfsdatamnt type nfs4  (rw,relatime,vers=4.0,rsize=131072,wsize=131072,namlen=2 55,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.122.102,local_lock=none,addr=192.168.122.101,_netdev)
//server1/smbsdata on /smbsdatamnt type cifs  (rw,relatime,vers=1.0,cache=strict,username=user11,domain=SERVER1,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.122.101,unix,posixpaths,serverino,acl,rsize=1048576,wsize=65536,actimeo=1)
[root@server2 ~]# mount|grep sdatamnt
server1.roggeware.nl:/nfsdata on /nfsdatamnt type nfs4  (rw,relatime,vers=4.0,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.122.102,local_lock=none,addr=192.168.122.101,_netdev)
//server1/smbsdata on /

smbsdatamnt type cifs (rw,relatime,vers=1.0,cache=strict,username=user11,domain=SERVER1,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.122.101,unix,posixpaths,serverino,acl,rsize=104 8576,wsize=65536,actimeo=1)

[root@server2 ~]# mount|grep smbsdatamnt
//server1/smbsdata on /smbsdatamnt type cifs (rw,relatime,vers=1.0,cache=strict,username=user11,domain=SERVER1,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.122.101,unix,posixpaths,serverino,acl,rsize=104 8576,wsize=65536,actimeo=1) 
[root@server2 ~]#

Create a file called smbsdatatest11 as user11 and another file called smbsdatatest12 as user12' under smbsdatamnt. List the directorycontents to ensure both files have owning group smbgrp.

[root@server2 ~]# ls -l /smbsdatamnt/

total 0

[root@server2 ~]# su - user11
Last login: Sun Jul  3 22:29:07 CEST 2016 on pts/0
[user11@server2 ~]$ touch /smbsdatamnt/smbsdatatest11;exit
uitgelogd
[root@server2 ~]# su - user12
[user12@server2 ~]$  touch /smbsdatamnt/smbsdatatest12;exit
uitgelogd
[root@server2 ~]# ls -l /smbsdatamnt/
total 0
-rw-rw----. 1 user11 smbgrp 0 Jul  3 22:31 smbsdatatest11
-rw-rw----. 1 user11 smbgrp 0 Jul  3 22:32 smbsdatatest12
[root@server2 ~]#

Provide Secure Access to Samba Share with Kerberos

This exercise assumes that server2 is running Kerberos services (both KDC and admin services) for realm example.com, the root user is added as an admin principal, DNS is disabled, and the hosts file is updated with appropiate mappings for both server1 and server2. Samba services run on server1.

In this exercise you will add the Samba server as a cifs principal and produce a keytab for it and store it locally. Add appropiate entries to the Samba server for a share and test access on the client.

On the Kerberos server server2.

Login as the root principal and add server1 as a cifs principal to the KDC database.

# kadmin -p root/padmin
Authenticating as principal root/admin with password.
Password for root/admin@EXAMPLE.COM:
kadmin:addprinc -randkey cifs/server1.example.com
WARNING: no policy specified for cifs/server1.example.com@EXAMPLE.COM: defaulting to no policy
Principal "cifs/server1.example.com@EXAMPLE.COM" created.

Generate a leytab for the new principal and store it in the /etc/krb5.kettab file.

kadmin:ktadd -k /etc/krb5.keytab cifs/server1.example.com

Ensure that the file has the ownership and owning group set to root and permissions to 0600.

Copy the keytab file to the Samba server server1.

#scp -pr /etc/krb5.keytab server1:/etc

On server1.

Follow the steps provided in exercise "Provide Network Shares to Samba Client"to create and share /smbkrb5 directory to create and share /smbkrb5 directory for user7 access with security set to ADS and Kerberos realm set to EXAMPLE.COM.

On server2.

Confirm access to the share by logging in to ut using Kerberos (-k) credentials.

#smbclient -l //server1/smbkrb5 -U user7

Create /smbkrb5mnt mount point.

#mkdir /smbkrb5mnt

Mount /smbkrb5 on to the /smbkrb5mnt mount point as user7.

#mount //server1/smbkrb5 /smbkrb5mnt -o username=user7,sec=krb5,rw

Verify the mount with the df and mount commands. Open the /etc/fstab file and add the following entry.

//server1/smbkrb5 /smbkrb5mnt cifs username=user7,rw,sec=krb5 0 0

Create a file called smbkrb5test as user7 under /smbkrb5mnt and check its existence on the Samba server.

Chapter 22 Hosting Websites with Apache

HTTP and the Apache Web Server

Apache Commands

apachectl     Starts, stops and checks status of the httpd process. Systemctl may also be used.
htpasswd      Create and updates files to store usernames and passwords for basic authentication of Apache users.
httpd         Server program for the Apache webservice.
              -t         verify configuration file
              -D vhosts verify vhost configuration file

Apache Configuration Files

By default, all Apache web server configuration and supporting files are stored under the /etc/httpd directory. The primary configuration file, httpd.conf, is under the conf sub-directory. Additional files are under conf.d


/etc/httpd                      Default directory for all configuration files.
/run/httpd                      Runtime information.
/usr/lib64/httpd/modules        Additional Apache modules.
/var/log/httpd                  Apache logfiles.
/usr/share/doc/httpd-2.4.6  
[root@localhost ~]# ls -lR /etc/httpd/
/etc/httpd/:
total 4
drwxr-xr-x. 2 root root   35 Jul 18 21:47 conf
drwxr-xr-x. 2 root root   78 Jul 18 21:47 conf.d
drwxr-xr-x. 2 root root 4096 Jul 18 21:47 conf.modules.d
lrwxrwxrwx. 1 root root   19 Jul 18 21:47 logs -> ../../var/log/httpd
lrwxrwxrwx. 1 root root   29 Jul 18 21:47 modules -> ../../usr/lib64/httpd/modules
lrwxrwxrwx. 1 root root   10 Jul 18 21:47 run -> /run/httpd 
/etc/httpd/conf: 
total 28
-rw-r--r--. 1 root root 11753 May 12 12:16 httpd.conf
-rw-r--r--. 1 root root 13077 May 12 12:28 magic
/etc/httpd/conf.d:
total 16
-rw-r--r--. 1 root root 2926 May 12 12:27 autoindex.conf
-rw-r--r--. 1 root root  366 May 12 12:28 README
-rw-r--r--. 1 root root 1252 May 12 12:16 userdir.conf
-rw-r--r--. 1 root root  824 May 12 12:16 welcome.conf 
/etc/httpd/conf.modules.d:
total 28
-rw-r--r--. 1 root root 3739 May 12 12:16 00-base.conf
-rw-r--r--. 1 root root  139 May 12 12:16 00-dav.conf
-rw-r--r--. 1 root root   41 May 12 12:16 00-lua.conf
-rw-r--r--. 1 root root  742 May 12 12:16 00-mpm.conf
-rw-r--r--. 1 root root  957 May 12 12:16 00-proxy.conf
-rw-r--r--. 1 root root   88 May 12 12:16 00-systemd.conf
-rw-r--r--. 1 root root  451 May 12 12:16 01-cgi.conf
[root@localhost ~]#

Apache Log Files

Apache log files are located in the /var/log/httpd directory, which is symbolically linked from the /etc/httpd/logs directory.

Apache Software Packages

[root@localhost ~]# yum list installed|grep http
httpd.x86_64                            2.4.6-40.el7.centos.1          @updates
httpd-tools.x86_64                      2.4.6-40.el7.centos.1          @updates
[root@localhost ~]#
httpd
httpd-manual              html pages in /usr/share/httpd/manual accessible with links or elinks.
httpd-tools

Configuring Apache Web Servers

Having gone through the material provided in this chapter so far and the knowledge and understanding developed based on that, you should now be able to perform the exercises provided in this section. You might need to adjust settings presented in these exercises to make them work on your systems.

SELinux Requirements for Apache Operation

There are a number of booleans associated with the Apache service. Run the SELinux Configuration tool system-config-selinux, go to Boolean and the filter out "httpd". This will list all associated booleans. Some of the booleans that effect Apache are described below.

httpd_anon_write              Allows/disallows Apache to write to directories labeled with the public_content_rw_t type, such as public directories.
httpd_sys_script_anon_write   Allows/disallows Apache scripts to write to direcotries labeled with the public_content_rw_t type, such as public directories.
httpd_enable_cgi              Enables/disables execution of CGI scripts labeled with the httpd_sys_scrpt_exec_t type.
httpd_enable_ftp_server       Allows/disallows Apache to act as a FTP server and listen on port 21.
httpd_enable_homedirs         Enables/disables Apache's access to user home directories.
httpd_use_cifs                Allows/disallows Apache to use mounted Samba shares with cifs_t type.
httpd_use_nfs                 Allows/disallows Apache to use mounted NFS shares with nfs_t type.

In addition to the booleans, having proper SELinux file context on Apache files and direcotries is mandatory for Apache to operate smoothly. There are three key directories where the Apache information is typically stored: /etc/httpd, /var/www and /var/lg/httpd. Run the ll command with the -Zd option on these directories to check the current SELinux content.

[root@localhost ~]# ls -lZd /etc/httpd
drwxr-xr-x. root root system_u:object_r:httpd_config_t:s0 /etc/httpd
[root@localhost ~]# ls -lZd /var/www
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /var/www
[root@localhost ~]# ls -lZd /var/log/httpd/
drwx------. root root system_u:object_r:httpd_log_t:s0 /var/log/httpd/
[root@localhost ~]#

Configure the Default Apache Web Server

This exercise will setup an Apache web server for basic operation using the default settings in the httpd.conf file. Install the Apache web server software and the elinks text browser. Ensure that appropiate firewall rules are in place to allow HTTP traffic to pass through. Enable the HTTP service to autostart at system reboots and start the service. Test the web server functionality by accessing the default page fro the elinks web browser. Install elinks web browser on server2 and access the default web browser from there.

Install the software packages for Apache and elinks.

[root@server1 ~]# yum install httpd elinks
Package httpd-2.4.6-40.el7.centos.4.x86_64 already installed and latest version
Installed:
  elinks.x86_64 0:0.12-0.36.pre6.el7
Complete!
[root@server1 ~]#

Add the http service to firewalld persistently and reload the rules to allow traffic on HTTP port 80 and set the Apache service to autostart.

[root@server1 ~]# firewall-cmd --permanent --add-service http
success
[root@server1 ~]# firewall-cmd --list-service
-client ssh
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-service
dhcpv6-client http ssh
[root@server1 ~]# systemctl enable httpd
Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.
[root@server1 ~]#

Start the Apache service and check the status.

[root@server1 ~]# systemctl start httpd
[root@server1 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2016-07-19 20:57:40 CEST; 43s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 10669 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─10669 /usr/sbin/httpd -DFOREGROUND
           ├─10670 /usr/sbin/httpd -DFOREGROUND
           ├─10671 /usr/sbin/httpd -DFOREGROUND
           ├─10672 /usr/sbin/httpd -DFOREGROUND
           ├─10673 /usr/sbin/httpd -DFOREGROUND
           └─10674 /usr/sbin/httpd -DFOREGROUND
Jul 19 20:57:39 server1 systemd[1]: Starting The Apache HTTP Server...
Jul 19 20:57:40 server1 httpd[10669]: AH00558: httpd: Could not reliably determine the server...sage
Jul 19 20:57:40 server1 systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server1 ~]#

Verify access to the default web page using the following to show the Apache Test Page.

[root@server1 ~]# elinks http://localhost

Run the tail command on the error_log and access_log files in the /var/log/httpd directory to view any error and access messages generated.

On server2 (web client). Install the elinks browser software and access the web server using the elinks browser.

[root@server2 ~]# yum install elinks
Package elinks-0.12-0.36.pre6.el7.x86_64 already installed and latest version
Nothing to do
[root@server2 ~]#

Access the web server using the elinks browser.

[root@server2 ~]# elinks http://server1

You should be able to see the default web page.

Modify the Default Web Server to Use a Different Home Page and Hostname

This exercse modifies the webserver configured in the previous exercise and use webserver1.roggeware.nl as its hostname with alias webserver1. Create a new home page in the default DocumentRoot directory. Test theweb server funcitonality using the new hostname from both systems.

Create a web page in the default DocumentRoot directory var/www/html.

[root@server1 ~]# cat /var/www/html/index.html
This is webserver 1 (Exercise 22-2)
[root@server1 ~]#

Modify the entry for ´´server1´´ in the /etc/hosts file.

[root@server1 ~]# grep web /etc/hosts
192.168.122.110 server1 server1.roggeware.nl webserver1 webserver1.roggeware.nl
[root@server1 ~]#

Open the /etc/httpd/conf/httpd.conf file and modify the following.

[root@server1 ~]# egrep "ServerA|ServerN" /etc/httpd/conf/httpd.conf
ServerAdmin root@webserver1.roggeware.nl
ServerName webserver1.roggeware.nl
[root@server1 ~]#

Check the syntax of httpd.conf with the httpd -t command.

[root@server1 ~]# httpd -t
Syntax OK
[root@server1 ~]#

Verify access to the new web page using the following.

[root@server1 ~]# elinks http://webserver1.roggeware.nl

Run the tail command on the error_log and access_log files located in the /var/log/httpd directory. Log on to server2 and update the entry for server1 in the /etc/hosts file as done on server1.

[root@server2 ~]# elinks http://webserver1

You should be able to see the web server1 web page.

Extend the Web Server to Provide Access to a Private Directory

In this exercise you will extend the functionality of the web server configured and updated in the previous two exercises to provide access to a private directory called privusr located under a different DocumentRoot called /var. You will restrict access to this private directory for user1 only.

Create the private directory in DocumentRoot and change ownership to user1 and permissions to 0711.

[root@server1 ~]# mkdir /var/privusr
[root@server1 ~]# chown user1:user1 /var/privusr
[root@server1 ~]# chmod 0711 /var/privusr/
[root@server1 ~]#

Create an index.html file in the private directory.

[root@server1 ~]# cat /var/privusr/index.html
This is webserver1. Exercise providing user1 access to a private directory.
[root@server1 ~]#

Add SELinux file context with type httpd_sys_content_t on the var'privusr directory to the SELinx policy and apply the new rule to the directory.

[root@server1 ~]# semanage fcontext -at httpd_sys_content_t "/var/privusr(/.*)?"
[root@server1 ~]# restorecon -Rv /var/privusr
restorecon reset /var/privusr context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
restorecon reset /var/privusr/index.html context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
[root@server1 ~]#

Add the new file content to the SELinux policy first, and then apply it. THis will prevent toe context to reset to the original value should SELinux relabeling happen.

Open the httpd.conf and add the following.

<Directory "/var/privusr">
    AllowOverride AuthConfig
</Directory>

And check the syntax of httpd.conf with httpd -t

[root@server1 ~]# httpd -t
Syntax OK
[root@server1 ~]#

Create the .htaccess file in the /var/privusr direcotry and add the following to it.

[root@server1 ~]# cat /var/privusr/.htaccess
AuthType Basic
AuthName "Password-protected User Contents. Enter your credentials to login:
AuthUserFile "/etc/httpd/conf/.userdb"
Require user user1

[root@server1 ~]#

Set password for user1 and store it in the AuthUserFile using the htpasswd command. Display the contents of the AuthUserFile.

[root@server1 ~]# cd /etc/httpd/conf
[root@server1 conf]# htpasswd -c .userdb user1
New password:
Re-type new password:
Adding password for user user1
[root@server1 conf]# cat .userdb
user1:$apr1$zk9dTPzt$FeJy6jbSkurSNhQNvGWrs1
[root@server1 conf]#

Change owning group on the AuthUserFile to apache and permissions to 0640.

[root@server1 conf]# chown apache .userdb
[root@server1 conf]# chmod 0640 .userdb
[root@server1 conf]# ls -l .userdb
-rw-r-----. 1 apache root 44 Jul 21 21:36 .userdb
[root@server1 conf]#

Restart the Apache web service.

[root@server1 conf]# systemctl restart httpd
root@server1 conf]#

Test the configuration for user1 from local and remote systems using the firefox browser

[root@server1 ]# elinks http://webserver1.roggeware.nl/privusr
[root@server2 ]# elinks http://webserver1/privusr

Run the tail command on the error_log and access_log files to view error and access logs.

Modify the Web server to Provide Access to Group-Managed Contents

This exercise should be done on server1. The functionality of the web server will be modifiedand updated to provide access too a directory called privgrp for group collaboration. Access to this directory will be restricted fordba members only. Do not change what was done in the previous exercises.

Create the directory for group-managed contents in DocumentRoot.

[root@server1 ~]# mkdir /var/privgrp

Create group dba and add user10 and user11 as its members.

[root@server1 ~]# groupadd dba
[root@server1 ~]# usermod -G dba user10
[root@server1 ~]# usermod -G dba user11
[root@server1 ~]# chgrp dba /var/privgrp
[root@server1 ~]# chmod 0771 /var/privgrp/
[root@server1 ~]# ls -ld /var/privgrp/
drwxrwx--x. 2 root dba 6 Jul 22 22:30 /var/privgrp/
[root@server1 ~]#

Create an index.html in the directory.

[root@server1 ~]# cat /var/privgrp/index.html
This is webserver1 providing dba group members access to /var/privgrp directory
[root@server1 ~]#

Add SELinux file context with type httpd_sys_content_t on the /var/grp/privgrp directory ti the SELinux policy and apply the new rule to the directory.

[root@server1 ~]# semanage fcontext -at httpd_sys_content_t "/var/privgrp(/.*)?"
[root@server1 ~]# restorecon -Rv /var/privgrp
restorecon reset /var/privgrp context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
restorecon reset /var/privgrp/index.html context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
[root@server1 ~]# ls -lZd /var/privgrp/
drwxrwx--x. root dba unconfined_u:object_r:httpd_sys_content_t:s0 /var/privgrp/
[root@server1 ~]#

Open the /etc/httpd/conf/httpd.conf and modify the following.

ServerAdmin root@webserver1.roggeware.nl
ServerName webserver1.roggeware.nl
DocumentRoot "/var"
<Directory "/var/privusr">
    AllowOverride AuthConfig
</Directory>
<Directory "/var/privgrp">
    AllowOverride AuthConfig
</Directory>

Check the syntax of the httpd.conf file for any errors.

[root@server1 ~]# httpd -t
Syntax OK
[root@server1 ~]#

Create the .htaccess file in the /var/privgrp directory and add the following to it.

[root@server1 privgrp]# cat /var/privgrp/.htaccess
AuthType Basic
AuthName "Password-protected Group Contents. Enter your credentials to log in:"
AuthUserFile "/etc/httpd/conf/.grouppassworddb"
AuthGroupFile "/etc/httpd/conf/.groupdb"
Require group dba
[root@server1 privgrp]#

Create AuthGroupFile (/etc/httpd/conf/.groupdb) and add group information.

[root@server1 privgrp]# cat /etc/httpd/conf/.groupdb
dba:user10 user11
[root@server1 privgrp]#

Change the owning group on the AuthGroupFile to apache and permissions to 0640.

[root@server1 privgrp]# chgrp apache /etc/httpd/conf/.groupdb
[root@server1 privgrp]# chmod 0640 /etc/httpd/conf/.groupdb
[root@server1 privgrp]# ls -ld /etc/httpd/conf/.groupdb
-rw-r-----. 1 root apache 18 Jul 22 23:13 /etc/httpd/conf/.groupdb
[root@server1 privgrp]#

Set passwords for group membmers user10 and user11 and store the in the AuthUserFile /etc/httpd/conf/.

[root@server1 privgrp]# cd /etc/httpd/conf
[root@server1 conf]# htpasswd -c .grouppasswordb user10
New password:
Re-type new password:
Adding password for user user10
[root@server1 conf]# htpasswd  .grouppasswordb user11
New password:
Re-type new password:
Adding password for user user11
[root@server1 conf]# cat .grouppasswordb
user10:$apr1$BfT4.OpS$xV8iAkllqRs.igi.fXLO90
user11:$apr1$LzAbp8j9$BJbC5oEJHgGsHUsPnKQP1/
[root@server1 conf]#

Restart the Apache web service.

[root@server1 conf]# systemctl restart httpd
[root@server1 conf]#

Test the configuration for user10 and user11 from local and remote systems using the elinks browser.

Modify the Web Server to Limit Access to Select Hosts on a Non-Default Port

In this exercise you will modify on server1 the functionality of the web server configured and updated in the previous exercises to allow access from systems in the roggeware.nl domain and 192.168.1 network only and via port 8989. Do not make any other changes.

Modify the prvious /etc/httpd/conf/httpd.conf file contents as follows.

ServerAdmin root@webserver1.roggeware.nl
ServerName webserver1.roggeware.nl:8989
DocumentRoot "/var"
<Directory "/var/privusr">
    AllowOverride AuthConfig
    Require host roggeware.nl
    Require ip 192.168.1.0/24
</Directory>
<Directory "/var/privgrp">
    AllowOverride AuthConfig
    Require host roggeware.nl
    Require ip 192.168.1.0/24
</Directory>

Check the syntax of the httpd.conf file for any errors.

[root@server1 ~]# httpd -t
Syntax OK
[root@server1 ~]#


Restart the Apache web service Add TCP port 8989 to the default firewalld zone.

[root@server1 ~]# systemctl restart httpd
[root@server1 ~]# firewall-cmd --permanent --add-port 8989/tcp;firewall-cmd --reload
success
success
[root@server1 ~]#

Add TCP port 8989 with SELinux type http_port_t to the SELinux polcy and confirm.

[root@server1 ~]# semanage port -at http_port_t -p tcp 8989
[root@server1 ~]# semanage port -l|grep http_port_t
http_port_t                    tcp      8989, 80, 81, 443, 488, 8008, 8009, 8443, 9000
[root@server1 ~]#

Test the configuration from systems in the roggeware.nl domain and on 192.168.1.0/24 network by typing the following URLs in the browser.

http://webserver1.roggeware.nl:8989/privusr
http://webserver1.roggeware.nl:8989/privgrp

Run the tail command on the error_lo and access_log files located in the /var/log/httpd directory to view error and access logs.

Understanding and Configuring Apache Virtual Hosts

Apache allows to run multiple virtual hosts on a single system for shared hosting of several distinct websites. Each hosted website can either share a common IP address or be configured with a unique IP. Both mechanisms direct the inbound traffic to an appropiate virtual host.

Virtual Host Configuration File

The primary configuration file for defining virtual hosts is httpd.conf. A preferred approach is to have a separate file for each virtual host stored in the /etc/httpd/conf.d directory to avoid cluttering httpd.conf. A sample container for a virtual host os provided below to understand its syntax.

<VirtualHost *:80>
DocumentRoot /var/www/html/vh1.example.com
ServerAdmin admin1@vh1.example.com
ServerName vh1.example.com
ErrorLog logs/vh1.example.com-error_log
CustomLog logs/vh1.example.com-access_log common
</virtual host>

Virtual host configuration files are checked for syntax errors with the command httpd -D DUMP_VHOSTS.

Configure a Simple Virtual Host

This exercise for server1 assumes that httpd and elinks software packages are already installed, http service is enabled in the firewall, and it is configured to autostart at system reboots.

You will configure a virtual host called vhost1.roggeware.nl with alias vhost1 and test the functionality by accessing it from the elinks web browser.

Create a file in the /etc/httpd/conf.d directory called vhost1.conf.

[root@server1 ~]# cat /etc/httpd/conf.d/vhost1.conf
<VirtualHost *:80>
        ServerAdmin admin@vhost1.roggeware.nl
        DocumentRoot /var/www/html/vhost1
        ServerName vhost1.roggeware.nl
        ErrorLog logs/vhost1-error_log
        CustomLog logs/vhost1-access_log combined
</VirtualHost>
[root@server1 ~]#

Create DocumentRoot directory and create an index.html.

[root@server1 ~]# mkdir /var/www/html/vhost1
[root@server1 ~]# cat /var/www/html/vhost1/index.html
This web page is used to test a Simple Virtual Host configuration
[root@server1 ~]#

Check the syntax of the virtual host configuration for any errors.

[root@server1 ~]# httpd -D DUMP_VHOSTS
VirtualHost configuration:
*:80                   vhost1.roggeware.nl (/etc/httpd/conf.d/vhost1.conf:1)
[root@server1 ~]#

Open the /etc/hosts file and modify the server1 entry to look like.

[root@server1 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.122.110 server1 server1.roggeware.nl webserver1 webserver1.roggeware.nl vhost1 vhost1.roggeware.nl
192.168.122.120 server2 server2.roggeware.nl
[root@server1 ~]#

Make the above changes to the hosts file on server2 and host1 as well to do the test from these hosts as well.

Restart the Apache server process.

[root@server1 ~]# systemctl restart httpd
[root@server1 ~]#

Test access from both local and remote locations using elinks.

[root@server1 ~]# elinks http://vhost1.roggeware.nl
[root@server2 ~]# elinks http://vhost1.roggeware.nl

Configure a More Complex Virtual Host

For this exercise on server1 it is assumed that httpd and elinks software packages are already installed and the http service is configured to autostart at system reboots.

In this exercise you will configure a virtul host called vhost2.example.com with alias vhost2, DocumentRoot /var/vhost2, and port 8900. Yuo will make necessary adjustments in firewalld and SELinux configuration. Test the functionality by accessing it with the elinks browser.

Create a file in the /etc/httpd/conf.d directory called vhost2.conf containing the following text.

[root@server1 ~]# cat /etc/httpd/conf.d/vhost2.conf
<VirtualHost *:8900>
        ServerAdmin admin@vhost2.roggeware.nl
        DocumentRoot /var/vhost2
        ServerName vhost2.roggeware.nl
        ErrorLog logs/vhost2-error_log
        CustomLog logs/vhost2-access_log combined
</VirtualHost>
[root@server1 ~]#

Create DocumentRoot for storing web content and create an index.html with some text.

[root@server1 ~]# mkdir /var/vhost2
[root@server1 ~]# cat /var/vhost2/index.html
This web page is to test a more complex virtual host setup
[root@server1 ~]#

Check the syntax of the virtual host configuration.

[root@server1 ~]# httpd -D DUMP_VHOSTS 
VirtualHost configuration:
*:80                   vhost1.roggeware.nl (/etc/httpd/conf.d/vhost1.conf:1)
*:8900                 vhost2.roggeware.nl (/etc/httpd/conf.d/vhost2.conf:1)
[root@server1 ~]#

Edit /etc/hosts file and modify the server1ipv4 entry to look like.

[root@server1 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.122.110 server1 server1.roggeware.nl webserver1 webserver1.roggeware.nl vhost1 vhost1.roggeware.nl
192.168.122.111 server1ipv4 server1ipv4.roggeware.nl vhost2 vhost2.roggeware.nl
192.168.122.120 server2 server2.roggeware.nl
[root@server1 ~]#

Make the above change to the hosts file on server2 as wel to test from that virtual host.

Add SELinux file context with type httpd_sys_content_t on the /var/host2 directory to the SELinux policy and apply yhe new rul to DocumentRoot recursively.

[root@server1 ~]# semanage fcontext -at httpd_sys_content_t "/var/vhost2(/.*)?"
[root@server1 ~]# restorecon -Rv /var/vhost2
restorecon reset /var/vhost2 context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
restorecon reset /var/vhost2/index.html context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
[root@server1 ~]#

Add TCP port 8900 with SELInux type http_port_t to the SELinux policy and confirm

[root@server1 ~]# semanage port -at http_port_t 8900 -p tcp
[root@server1 ~]# semanage port -l|grep 8900
http_port_t                    tcp      8900, 8989, 80, 81, 443, 488, 8008, 8009, 8443, 9000
[root@server1 ~]#

Add port 8900 to the default firewall zone

[root@server1 ~]# firewall-cmd --add-port 8900/tcp --permanent
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-ports
8900/tcp 8989/tcp
[root@server1 ~]#

Restart the Apache server process.

[root@server1 ~]# systemctl restart httpd
[root@server1 ~]#

Test access from server1 and server2 using elinks.

Understanding and Configuring Apache Web Servers over SSL/TLS

Secure Sockets Layer (SSL) is a cryptographic protocol that allows networked systems to communicate securely. SSL can be used with the Transport Layer Security (TLS) protocol to add data integrity, privacy and secure authentication. Apache web server that operates on top of SSL and TLS layers mey be referred to as HTTPS (HyperText Transfer Protocol Secure) or SSL web servers. An HTTPS server uses a digital identity certificate in order to prove its authenticicity to clients when they attempt to pform a connection. A trusted digital identity certificate is signed and issued by a Certificate Authority (CA). To obtain one, the applicant generates a private/public encrypption key pair and a Certificate Signing Request (CSR) on the server for which the certificate is desired. The CSR contains applicant identity as well as the public key and the hostname of the system. The CSR is encoded before it is transmitted to the CA. The CA reviews the CSR and issues a signed certificate after validating the data provided in the CSR.

Another type of digital certificates is referred to as a self-signed certificate. A self-signed certificate is produced locally on the system and is primarily used for testing purposes. During its creation you can skip answering most identity quesitons.

HTPS/SSL Software Packages

There are two software packages that need to be installed on the system to set up an HTTPS web server. These packages add necessary support to the kernel and bring the tools and configuration files that are used for setting up secure web servers.

  • mod_ssl Provides configuration files necessary to configure a secure web server over SSL and TLS layers.
  • openssl Manages certificates and supports secure communication between systems.

The installation of mod_ssl installs the ssl.conf file in the /etc/httpd/conf.d directory, which is the configuration file for setting up a secure web server. This file is equivalent to the httpd.conf file used for non-secure Apache web servers. The openssl package loads the openssl command and a directory tree with some templates under /etc/pki

[root@server1 ]#  yum list installed |egrep '^mod|openssl'
mod_ssl.x86_64                          1:2.4.6-40.el7.centos.4        @updates
openssl.x86_64                          1:1.0.1e-51.el7_2.5            @updates
openssl-libs.x86_64                     1:1.0.1e-51.el7_2.5            @updates
[root@server1 ]#

The OpenSSL Toolkit

The openssl toolkit offers a variety of subcommands to create and manage encryption keys, CSRs and digital certificates, test HTTPS server and client connections. If called without any arguments, openssl enters the interactive mode with an OpenSSL> prompt. There are over a 100 subcommands and are divided into three sets: standard, cipher (encoding and encryption) and message-digest (detection of and protection against data-corruption). You can list subcommands for each set by running the openssl command as follows:

[root@server1 ~]# openssl list-standard-commands
[root@server1 ~]# openssl list-cipher-commands
[root@server1 ~]# openssl list-message-digest-commands

Command openssl with an invalid argument lists all three command sets. This file sets directoves necessary to run secure web servers. It is divided into two sections ; SSL Global Context and SSL Virtual Host Context.

The OpenSSL Configuration File and its Analysis

By default, the SSL configuration file ssl.conf is stored in the /etc/httpd/conf.d directory.

[root@server1 ~]# ll /etc/httpd/conf.d/ssl.conf
-rw-r--r--. 1 root root 9438 Jul 18 17:22 /etc/httpd/conf.d/ssl.conf
[root@server1 ~]#

This file is processed after the httpd.conf file completes its processing at Apache service startup. It is divided into two sections.

The SSL Global Context section includes directives that apply to the default secure server and to all secure virtual hosts. These directives are not typically modified as their defaults are sufficient for most implementations.

The SSL Virtual Host Context section contains plenty of directives.

The <VirtualHost_default_:443> directive idnetifies the port number with an IP address or *. The next five directives -- DocmentRoot, ServerName, ErrorLog, TransferLog and Loglevel -- and the CustomLog before the end of the file have the same meaning that was provided under the httpd.conf file. The SSLEngine directive must be set to on if you intend to use SSL. The next three directives -- SSLProtocol, SSL CertificateFile and SSLCertificateKeyFile -- specify the SSL version to use, the location of the SSL certificate and the location of the SSL key. The <Files> and <Directory> sub-containers specify the file types containing dynamic contents and their location.

OpenSSL Log Files

OpenSSL log files are located in the /var/log/httpd directory, which is symbolically linked from the /etc/httpd/logs directory. An ll on this directory for ssl logs is shown below. The ssl_access_log, ssl_error_log and ssl_request_log files capture access to the web server, error messages and request messages respectively.


Generate a Key Pair and Self-Signed Certificate

In this exercise on server1 you will generate enryption keys and a self-signed certificate for use in the next exercise using the openssl command and move the key to the default location.

Install mod_ssl and openssl packages.

[root@server1 ~]# yum install mod_ssl openssl
Package 1:mod_ssl-2.4.6-40.el7.centos.4.x86_64 already installed and latest version
Package 1:openssl-1.0.1e-51.el7_2.5.x86_64 already installed and latest version
Nothing to do
[root@server1 ~]

Change into /etc/pki/tls/certs directory and generate a private key of 2048 bits using the RSA algorithm. Save the key in a file called server1.roggeware.nl.key.

[root@server1 certs]# openssl genpkey -algorithm rsa -pkeyopt rsa_keygen_bits:2048 -out server1.roggeware.nl.key
...........+++
......................................+++
[root@server1 certs]# ls -l
total 20
lrwxrwxrwx. 1 root root   49 Jul 18 18:24 ca-bundle.crt -> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
lrwxrwxrwx. 1 root root   55 Jul 18 18:24 ca-bundle.trust.crt -> /etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt
-rw-------. 1 root root 1391 Jul 25 21:44 localhost.crt
-rwxr-xr-x. 1 root root  610 May  9 10:10 make-dummy-cert
-rw-r--r--. 1 root root 2388 May  9 10:10 Makefile
-rwxr-xr-x. 1 root root  829 May  9 10:10 renew-dummy-cert
-rw-r--r--. 1 root root 1708 Jul 26 23:02 server1.roggeware.nl.key
[root@server1 certs]#

Create a certificate signing request using the private key generated in the previous step and store it in a file called server1.roggeware.nl.csr. Enter data as indicated in the output below.

[root@server1 certs]# openssl req -new -key server1.roggeware.nl.key -out server1.roggeware.nl.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CA
State or Province Name (full name) []:Ontario
Locality Name (eg, city) [Default City]:Toronta
Organization Name (eg, company) [Default Company Ltd]:roggeware
Organizational Unit Name (eg, section) []:roggeware
Common Name (eg, your name or your server's hostname) []:server1.roggeware.nl
Email Address []:info@server1.roggeware.nl
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@server1 certs]# ls -l
total 24
lrwxrwxrwx. 1 root root   49 Jul 18 18:24 ca-bundle.crt -> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
lrwxrwxrwx. 1 root root   55 Jul 18 18:24 ca-bundle.trust.crt -> /etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt
-rw-------. 1 root root 1391 Jul 25 21:44 localhost.crt
-rwxr-xr-x. 1 root root  610 May  9 10:10 make-dummy-cert
-rw-r--r--. 1 root root 2388 May  9 10:10 Makefile
-rwxr-xr-x. 1 root root  829 May  9 10:10 renew-dummy-cert
-rw-r--r--. 1 root root 1086 Jul 26 23:06 server1.roggeware.nl.csr
-rw-r--r--. 1 root root 1708 Jul 26 23:02 server1.roggeware.nl.key
[root@server1 certs]#

Generate a self-signed certificate (server1.roggeware.nl.crt) with a validity of 120 days using the private key (server1.roggeware.nl.key) and certificate signing request (server1.roggeware.nl.csr) created in previous steps.

[root@server1 certs]# openssl x509 -req -days 120 -signkey server1.roggeware.nl.key -in server1.roggeware.nl.csr -out server1.roggeware.nl.crt
Signature ok
subject=/C=CA/ST=Ontario/L=Toronta/O=roggeware/OU=roggeware/CN=server1.roggeware.nl/emailAddress=info@server1.roggeware.nl
Getting Private key
[root@server1 certs]#

List the three files generated as a result.

[root@server1 certs]# ls -l server1.*
-rw-r--r--. 1 root root 1363 Jul 27 21:27 server1.roggeware.nl.crt
-rw-r--r--. 1 root root 1086 Jul 26 23:06 server1.roggeware.nl.csr
-rw-r--r--. 1 root root 1708 Jul 26 23:02 server1.roggeware.nl.key
[root@server1 certs]#

Protect the private key with permissions 0600 and store it in the /etc/pki/tls/private directory.

[root@server1 certs]# chmod 0600 server1.roggeware.nl.key
[root@server1 certs]# mv server1.roggeware.nl.key ../private
[root@server1 certs]# ls -l /etc/pki/tls/private/'
total 8
-rw-------. 1 root root 1679 Jul 25 21:44 localhost.key
-rw-------. 1 root root 1708 Jul 26 23:02 server1.roggeware.nl.key
[root@server1 certs]#

Check the validity and status of the certificate using the openssl command.

[root@server1 conf.d]# openssl s_client -connect localhost:443 -state
CONNECTED(00000003)
SSL_connect:before/connect initialization
SSL_connect:SSLv2/v3 write client hello A
SSL_connect:SSLv3 read server hello A
depth=0 C = --, ST = SomeState, L = SomeCity, O = SomeOrganization, OU = SomeOrganizationalUnit, CN = server1, emailAddress = root@server1
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 C = --, ST = SomeState, L = SomeCity, O = SomeOrganization, OU = SomeOrganizationalUnit, CN = server1, emailAddress = root@server1
verify error:num=21:unable to verify the first certificate
verify return:1
SSL_connect:SSLv3 read server certificate A
SSL_connect:SSLv3 read server key exchange A
SSL_connect:SSLv3 read server done A
SSL_connect:SSLv3 write client key exchange A
SSL_connect:SSLv3 write change cipher spec A
SSL_connect:SSLv3 write finished A
SSL_connect:SSLv3 flush data
SSL_connect:SSLv3 read server session ticket A
SSL_connect:SSLv3 read finished A
---
Certificate chain
 0 s:/C=--/ST=SomeState/L=SomeCity/O=SomeOrganization/OU=SomeOrganizationalUnit/CN=server1/emailAddress=root@server1
   i:/C=--/ST=SomeState/L=SomeCity/O=SomeOrganization/OU=SomeOrganizationalUnit/CN=server1/emailAddress=root@server1
---
Server certificate
-----BEGIN CERTIFICATE-----
MIID1jCCAr6gAwIBAgICMNcwDQYJKoZIhvcNAQELBQAwgZ8xCzAJBgNVBAYTAi0t
MRIwEAYDVQQIDAlTb21lU3RhdGUxETAPBgNVBAcMCFNvbWVDaXR5MRkwFwYDVQQK
DBBTb21lT3JnYW5pemF0aW9uMR8wHQYDVQQLDBZTb21lT3JnYW5pemF0aW9uYWxV
bml0MRAwDgYDVQQDDAdzZXJ2ZXIxMRswGQYJKoZIhvcNAQkBFgxyb290QHNlcnZl
cjEwHhcNMTYwNzI1MTk0NDU5WhcNMTcwNzI1MTk0NDU5WjCBnzELMAkGA1UEBhMC
LS0xEjAQBgNVBAgMCVNvbWVTdGF0ZTERMA8GA1UEBwwIU29tZUNpdHkxGTAXBgNV
BAoMEFNvbWVPcmdhbml6YXRpb24xHzAdBgNVBAsMFlNvbWVPcmdhbml6YXRpb25h
bFVuaXQxEDAOBgNVBAMMB3NlcnZlcjExGzAZBgkqhkiG9w0BCQEWDHJvb3RAc2Vy
dmVyMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMggTqtfl59S72yr
jTkZwTk1ISWiqXOis6dmw2nFj2depIdusnWy08+3Ug52fCZP89biJot+AsF1wdjZ
XRPkS0lG0xJpL/5WtaTcbwKc2aoEqTqoIHTk+/PviWWlPhjaPsiVi//qgHTifK2Z
YgOI/riS/FBxVfx3W5gfaNNNiKUjjelxDg/7nK84zoUh6Pk0mc2wRNakhj0MNVfD
qafFkvW9YoRDCORY7RSO1tBGxtu0cNwgmRbjKmFULNVIpRRScBSYJJ1JOjlkOKcr
JTC6CAg88eiTtIJnqt0oN4tDgJRzK6li5eOJfXNQmvZKV+2tMcgoKKEqoSMl0t4+
IGyCv5MCAwEAAaMaMBgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwDQYJKoZIhvcN
AQELBQADggEBAKYFnWN9WEa7+LtR0obG+7bMAZ0Upr4slUctnr+3wk9P8B/snnE9
wn6jJt8x0kH/gm0O+jpZG5xsB4Q81Lw+Thva3tPvf4O2YiGJ38jMsDrujxP42ZLt
SbfdbxD9jalNOSqb3knJ9kaAEIHFX2C72pUlXozqtWTWuKUkwcPqZN3TIzB9+36p
/VYHumq71iMAezmb3giKbmXZKPqjdNNOucBMLUlJzjOJ39TBMxRTWQ4bG+gNJaN5
UDxg2UzQM7HTeIwo9L3VsXh3AASQg6gt6BcVCFelSfu0Lq/4ThnDmIpN0RHIYOAs
lCGL5oDj53pxljYZ8z93ZkzgsekcrWxwo+w=
-----END CERTIFICATE-----
subject=/C=--/ST=SomeState/L=SomeCity/O=SomeOrganization/OU=SomeOrganizationalUnit/CN=server1/emailAddress=root@server1
issuer=/C=--/ST=SomeState/L=SomeCity/O=SomeOrganization/OU=SomeOrganizationalUnit/CN=server1/emailAddress=root@server1
---
No client certificate CA names sent
Server Temp Key: ECDH, secp521r1, 521 bits
---
SSL handshake has read 1745 bytes and written 441 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: FB3B2C9CEC63AA3A9DE5F11053C2A5CE6F9A10CD92BE7D23B079C7D8CBCB30AA
    Session-ID-ctx:
    Master-Key: 92D8E726B4712C4993415690E159D5BC93B3A8537441F5519852F91EA27C010BE4D0CDB5F9C68FA9404EE51429CB728C
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - ed 2d 17 fd 13 15 00 71-fb 98 d8 5a e9 72 f2 19   .-.....q...Z.r..
    0010 - 7a 50 ce 0d 67 a3 cc 67-0a 44 3a db 0a a9 c7 5e   zP..g..g.D:....^
    0020 - 23 30 94 3f a2 88 11 6f-a1 7f 83 d6 1e a4 87 43   #0.?...o.......C
    0030 - eb 4c d0 b2 fe 80 06 91-9b 91 a8 bd 06 9b 1d 3f   .L.............?
    0040 - 06 e2 6f 19 b0 41 0c 03-51 53 d3 e3 d1 30 52 d1   ..o..A..QS...0R.
    0050 - bf 7d 87 6d ca d6 57 29-d0 3f c7 3c aa cb 35 39   .}.m..W).?.<..59
    0060 - 1c 8f 2f 31 f1 b4 1b 5b-a1 49 12 04 ee 41 54 a3   ../1...[.I...AT.
    0070 - a9 46 47 8c 11 0c de 5e-59 6b 78 ec 99 73 c8 f3   .FG....^Ykx..s..
    0080 - 6f 40 c8 ce 7c 21 aa b5-20 7f 66 b1 cc 64 e2 d4   o@..|!.. .f..d..
    0090 - f4 11 65 d6 cf 9e 07 95-98 46 d7 dc 8c 70 83 5e   ..e......F...p.^
    00a0 - b6 21 35 45 25 86 ab 71-37 d4 a4 ba b5 83 e4 89   .!5E%..q7.......
    00b0 - ee 21 54 c7 db ec 51 96-71 a8 f4 fe 4b b1 3f 77   .!T...Q.q...K.?w 
    Start Time: 1469648064
    Timeout   : 300 (sec)
    Verify return code: 21 (unable to verify the first certificate)
---
read:errno=0
SSL3 alert write:warning:close notify
[root@server1 conf.d]#

This key and the certificate will be used in the next exercise.

Configure a Secure Virtual Host

In this exercise for server1 you will configure a secure virtual host on default port 443 using the encryption key and certficate generated in the previous exercis. You will make necessary adjustments in firewalld and SELinux configurations. Test the web server functionality by accessing it from the elinks browser.

Create DocumentRoot.

[root@server1 conf.d]# mkdir /var/www/html/secure
[root@server1 conf.d]#

Open the /etc/httpd/conf.d/ssl.conf file and modify the directives as per below.

<VirtualHost *:443>
DocumentRoot "/var/www/html/secure"
ServerName server1.roggeware.nl:443
SSLCertificateFile /etc/pki/tls/certs/server1.roggeware.nl.crt
SSLCertificateKeyFile /etc/pki/tls/private/server1.roggeware.nl.key
</VirtualHost>

Check the syntax of the virtual host configuration file.

[root@server1 conf.d]# httpd -D DUMP_VHOSTS
VirtualHost configuration:
 *:443                  server1.roggeware.nl (/etc/httpd/conf.d/ssl.conf:56)
*:80                   vhost1.roggeware.nl (/etc/httpd/conf.d/vhost1.conf:1)
*:8900                 vhost2.roggeware.nl (/etc/httpd/conf.d/vhost2.conf:1)
[root@server1 conf.d]#

Create index.html in DocumentRoot with some text.

[root@server1 conf.d]# cat /var/www/html/secure/index.html
This web page is to test a more complex virtual host setup with ssl.
[root@server1 conf.d]#

Apply the default SELinux file context on the /var/www/html/secure directory.

[root@server1 conf.d]# restorecon -Rv /var/www/html
[root@server1 conf.d]#

Add the https service to firewalld persistently.

[root@server1 httpd]# firewall-cmd --add-service https --permanent
success
[root@server1 httpd]# firewall-cmd --list-service
dhcpv6-client http ssh
[root@server1 httpd]# firewall-cmd --reload
success
[root@server1 httpd]# firewall-cmd --list-service
dhcpv6-client http https ssh
[root@server1 httpd]#

Restart the Apache service.

[root@server1 conf.d]# systemctl restart httpd
[root@server1 conf.d]#

Test access from both local and remote systems using elinks.

[root@server1 conf.d]# elinks https://server1.roggeware.nl


Overview of CGI and CGI scripts

So far we have talked about web servers that show static content in a browser window. These web servers read index.html files and simply display that information as-is on the screen.

Apache allows us to add dynamic content to our websites. This interfacing between a program and web server can be implemented using the Common Gateway Interface (CGI) method. CGI presents a standard technique of generating dynamic content on websites using these programs which are referred to as CGI Scripts. CGI scripts may be written in Perl, Ruby, Python, C, shell or some other programming language.

A very basic CGI script sets the type of content to process, such as text or text/html, followed by what to execute. This sections briefly describes the setup of a non-secure web server that executes a CGI script and display the output on the screen. The ScriptAlias directive in the httpd.conf file defines the location of storing CGI files.

Deploy a Basic CGI Script

For this exercise on server1 it is assumed that httpd and elinks software packages are already installed, http service is enabled and all is configured to autostart at system reboot.

You will configre a web server to execute a CGI script and display its output in a browser window. You will configure appropiate SELinux settings.

Create a script called systime.sh in the /var/www/html/cig-bin directory and add the following text.

[root@atlas ~]# cat /var/www/cgi-bin/systime.sh
#!/bin/bash
echo "Content-type: text"
echo
echo "The current system time is `date`"
[root@atlas ~]#

Add the execute permission to this script for everyone.

[root@atlas ~]# chmod +x /var/www/cgi-bin/systime.sh
[root@atlas ~]# ls -l /var/www/cgi-bin/systime.sh
-rwxr-xr-x. 1 root root 85 Jul 28 22:00 /var/www/cgi-bin/systime.sh

Activate the SELinux boolean to enable cgi scripts.

[root@atlas ~]# setsebool -P httpd_enable_cgi 1

Restart the Apache service.

[root@atlas ~]# systemctl restart httpd

Test access from both local and remote systems using elinks.

Run a Basic CGI Script from a non-default location

For this exercise on server1 it is assumed that httpd and elinks software packages are already installed, http service is enabled and all is configured to autostart at system reboot.

You will configure a web server to execute a CGI script and display its output in a browser window. You will store the CGI script in /var/dynpage directory and configure appropiate SELinux settings.

Create /var/dynpage directory to store CGI scripts.

[root@server1 ~]# mkdir /var/dynpage
[root@server1 ~]#


Create a script called sysmem.sh in the /var/dynpage directory.

[root@server1 ~]# cat /var/dynpage/sysmem.sh
#!/bin/bash
echo -e "Content-type: text\n"
echo
echo "The system memory usage is $(free -m)"
[root@server1 ~]#

Add execution permission to this script for everyone.

[root@server1 ~]# chmod +x /var/dynpage/sysmem.sh
[root@server1 ~]# ls -l /var/dynpage/sysmem.sh
-rwxr-xr-x. 1 root root 95 Jul 29 17:11 /var/dynpage/sysmem.sh
[root@server1 ~]#

Activate the SELinux boolean httpd_enable_cgi.

[root@server1 ~]# setsebool -P httpd_enable_cgi 1
[root@server1 ~]# getsebool httpd_enable_cgi
httpd_enable_cgi --> on
[root@server1 ~]#

Add SELinux file context with type httpd_sys_script_exec_t on the /var/dynpage directory and apply the new rule recursively.

[root@server1 ~]# semanage fcontext -at httpd_sys_script_exec_t "/var/dynpage(/.*)?"
[root@server1 ~]# restorecon -Rv /var/dynpage
restorecon reset /var/dynpage context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_script_exec_t:s0
restorecon reset /var/dynpage/sysmem.sh context unconfined_u:object_r:var_t:s0->unconfined_u:object_r:httpd_sys_script_exec_t:s0
[root@server1 ~]# ls -lZ /var/dynpage/sysmem.sh
-rwxr-xr-x. root root unconfined_u:object_r:httpd_sys_script_exec_t:s0 /var/dynpage/sysmem.sh
[root@server1 ~]#

Open the httpd.conf file and modify the ScriptAlias directive as follows.

ScriptAlias /cgi-bin/ "/var/dynpage/"
<Directory "/var/dynpage/">
    AllowOverride None
    Options None
    Require all granted
</Directory>

Restart the Apache service.

[root@server1 httpd]# httpd -t
Syntax OK
[root@server1 httpd]# httpd -D DUMP_VHOSTS
VirtualHost configuration:
*:443                  server1.roggeware.nl (/etc/httpd/conf.d/ssl.conf:56)
*:80                   vhost1.roggeware.nl (/etc/httpd/conf.d/vhost1.conf:1)
*:8900                 vhost2.roggeware.nl (/etc/httpd/conf.d/vhost2.conf:1)
[root@server1 httpd]# systemctl restart httpd
[root@server1 httpd]#

Test access from both local and remote systems using elinks.


  system-config-selinux              SELinux Configuration Tool
 getsebool -a|grep httpd
firewall-cmd --permanent -add-service=http
firewall-cmd --reload
firewall-cmd --permanent -add-port 8900/tcp
semanage fcontext -at httpd_sys_content_t "/var/vhost2(/.*)?"
restorecon -Rv /var/vhost2
elinks http://localhost

Understanding and Configuring Apache Web Servers over SSL/TLS

CA  Certificate Authority.
CSR Certificate Signing Request.

OpenSSL logfiles are in /etc/httpd/logs which is a symbolic link to /var/log/httpd/

Software Packages
mod_ssl 
openssl
elinks
httpd-manual
Commands
openssl list-standard-commands
openssl genpkey -algorithm rsa -pkeyopt rsa_keygen_bits:2048 -out server1.example.com.key      Generate private key.
openssl req -new -key server1.example.com.key -out server1.example.com.csr
openssl x509 -req -days 120 -signkey server1.example.com.key -in server1.example.com.csr -out server1.example.com.crt
openssl s_client -coonect localhost:443 -state
httpd -D DUMP_VHOSTS
restorecon -Rv /var/www/html
firewall-cmd --permanent --add-servce https
elinks /usr/share/httpd/manual/index.html                         Shows all documentation about Apache. Install httpd-manual first.
Files
/etc/httpd/conf.d/ssl.conf    Installed by package mod_ssl.
/etc/pki/tls/certs            Default location for certificates.

Chapter 23 Sending and Receiving Electronic Mail

SMTP and the Email System

Simple Mail Transport Protocol (SMTP) is a networking protocol that is responisible for transporting email messages from one email server to another. The protocol runs on top of the IP protocol and uses port 25 for its operation.

An email message typically has four parts: The sender's ID and dmain name, the receiver's email address, a subject line and a message body. he SMTP protocol uses the first two items to determine the sender's and receiver's domains, based on whihc it decides wheterh the message is destined for the local network. If the message isdestined for the local network, the SMTP delivers the message to the receiving user's mailbox, If not, it sends tbe message across the internet to the correct target system.

Common Terms

  • MUA Mail User Agent. An email client program to compose messages and to submit them to an outging MTA.
  • MSA Mail Submission Agent. Responsible for accepting new mail messages from a MUA. The mSA function may be intergrated within a MUA or MTA, or a seperate program
  • MTA Mail transport Agent. Responsible for transporting a message from a sending mail server, and another MTA is responsible for accepting the message at a receving mail server and they both use SMTP. The most widely used MTA is sendmail
  • MDA Mail Delivery Agent. Responsible for delivering an incoming message to a local mail spool location for storage. Can be a separate program or integrated within an MTA
  • POP Post Office Protocol.Used by a MUA and it is responsible for downloading user mail messages from the mail server to their local inboxes.
  • IMAP Internet Message Access Protocol. Used by an MUA and is repsonsible for downloading user mail messages from the mail server to their local inboxes.
  • Smart Host (Relay). A smart host is an MTA that is configured withthe intent to deliver messages on behalf of other systems
  • Mail Queue. A mail queue is a directory location where submittted email messages are stored temporarily for further processing. Default mail queue for Postfix is located in the /var/spool/postfix directory.
  • Mailbox. A mailbox is a location for storing user email messages. By default, a mailbox file is created under the /var/sppol/mail directory for each user account creeated on the system with a matching name.

How the Email System Works

Understanding Postfix

Postfix Daemons

master, nqmgr, pickup, smtpd

Postfix Commands

alternatives         Displays and sets the default MTA.
                     --set mta
                     --display mta
mail/mailx           Sends and receives email.
postalias/newalias   Processes the alias database (/etc/aliases by default).
postconf             Displays and modifies the Postfix configuration stored in the main.cf file.
                     -d   Display default settings.
                     -n   Display settings defined in main.cf.
postfix              Controls operation of Postfix servcies, including start, stop, health, and reload config.
                     check   Check main.cf for syntax errors.
postmap              Process and converts some configuration files into Postfix-compatible databases.
postqueue/mailq      Lists and controls Postfix queue.

Postfix Configuration Files

/etc/postfix                 Postfix directory with configuration files.
/etc/postfix/access          Establish access control based on emailaddress, hosts, domains or network address. man 5 access.
/etc/postfix/access.db       Run postmap /etc/postfix/access to update this database.
/etc/postfix/canonical       Run postmap /etc/postfix/canonical to update this database. man 5 canonical.
/etc/postfix/generic         establish mapping for local and non-local mailaddresses. Syntax identical to canonical.
/etc/postfix/main.cf    
/etc/postfix/master.cf     
/etc/postfix/relocated
/etc/postfix/transport
/etc/postfix/virtual       
/etc/aliases
/var/lib/postfix
/var/log/maillog
/var/spool/postfix
/var/spool/mail

Managing Postfix

Managing Postfix involves several configuration and administration tasks, including setting up Postfix as a network mail server and as a smart host, applying appropiate access controls, mapping email addresses and creating aliases.

SElinux requirements for the postfix operation

By default, all Postfix daemons, including master, pickup and qmgr, run confined in their own domains and are labelled appropiately.

[root@server1 ~]# ps -eZ|grep postf
system_u:system_r:postfix_master_t:s0 1736 ?   00:02:22 master
system_u:system_r:postfix_qmgr_t:s0 1754 ?     00:00:19 qmgr
system_u:system_r:postfix_pickup_t:s0 10128 ?  00:00:00 pickup
[root@server1 ~]#

The associated SELinux file types are.

[root@server1 ~]# ls -lZd /etc/postfix /var/lib/postfix /var/spool/postfix
drwxr-xr-x. root    root system_u:object_r:postfix_etc_t:s0 /etc/postfix
drwx------. postfix root system_u:object_r:postfix_data_t:s0 /var/lib/postfix
drwxr-xr-x. root    root system_u:object_r:postfix_spool_t:s0 /var/spool/postfix
[root@server1 ~]#

The SELinux type associated with the SMTP port.

[root@server1 ~]# semanage port -l|grep smtp
smtp_port_t                    tcp      25, 465, 587
[root@server1 ~]#

There is a solo boolean associated with Postfix. This is turned on by default.

[root@server1 ~]# getsebool -a|grep postf
postfix_local_write_mail_spool --> on
[root@server1 ~]#

By looking at the above SELinux settings for Postfix, there are no changes required to make Postfix run smoothly in the SELinux enforcing mode.

Configure a Central Mail Server

In this exercise on server1 you will configure Postfix to serve systems on the local networkk (192.168.122.0/24). Add server1 as the MTA in the roggeware.nl domain, listen on all network interfaces with DNS lookups disabled. Checkk Postfix configuration for sybtax errors, configure host-based rules in firewalld, set Postfix to autostart at system reboot, start Postfix service and ensure that it is set as the default MTA. Send an email to user3 to ensure that the email service is working for local usrs.

Install the Postfix software package.

[root@server1 ~]# yum install postfix
Package 2:postfix-2.10.1-6.el7.x86_64 already installed and latest version
Nothing to do
[root@server1 ~]#


Open the main.cf file and set the following directives.

myhostname = server1.roggeware.nl
mydomain = roggeware.nl
myorigin = $myhostname
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks = 192.168.122.0/24, 127.0.0.0/8
disable_dns_lookups = yes

The default method for the mail system to resolve hostnames is DNS. However, in the absence of a DNS service you can instruct the mal system to use the hosts file instead by defining the disable_dns_lookups directive in the main.cf file and settings its value to yes.

Check for any syntax errors in the main.cf file using the postfix command.

[root@server1 postfix]# postfix check
[root@server1 postfix]#

Review the changes mode in the main.cf file with the postconf command.

[root@server1 # 'postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
disable_dns_lookups = yes
html_directory = no
inet_interfaces = all
inet_protocols = all
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mydomain = roggeware.nl
myhostname = server1.roggeware.nl
mynetworks = 192.168.122.0/24, 127.0.0.0/8
myorigin = $myhostname
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES
sample_directory = /usr/share/doc/postfix-2.10.1/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
unknown_local_recipient_reject_code = 550
[root@server1 ]#

Add the smtp service to firewalld persistently and reload the rules to allow traffic on the SMTP port.

[root@server1 postfix]# firewall-cmd --add-service smtp --permanent
success
[root@server1 postfix]# firewall-cmd --list-service
dhcpv6-client http https ssh
[root@server1 postfix]# firewall-cmd --reload
success
[root@server1 postfix]# firewall-cmd --list-service
dhcpv6-client http https smtp ssh
[root@server1 postfix]#

Set Postfix to autostart at system reboot.

[root@server1 postfix]# systemctl enable postfix [root@server1 postfix]#

Start the Postfix service and check its operation status.

[root@server1 postfix]# systemctl start postfix
[root@server1 postfix]# systemctl status postfix
â postfix.service - Postfix Mail Transport Agent
   Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; vendor preset: disabled)
   Active: active (running) since Sat 2016-07-30 14:48:33 CEST; 5s ago
  Process: 10698 ExecStop=/usr/sbin/postfix stop (code=exited, status=0/SUCCESS)
  Process: 10718 ExecStart=/usr/sbin/postfix start (code=exited, status=0/SUCCESS)
  Process: 10716 ExecStartPre=/usr/libexec/postfix/chroot-update (code=exited, status=0/SUCCESS)
  Process: 10714 ExecStartPre=/usr/libexec/postfix/aliasesdb (code=exited, status=0/SUCCESS)
 Main PID: 10790 (master)
   CGroup: /system.slice/postfix.service
           ââ10790 /usr/libexec/postfix/master -w
           ââ10791 pickup -l -t unix -u
           ââ10792 qmgr -l -t unix -u
Jul 30 14:48:31 server1 systemd[1]: Starting Postfix Mail Transport Agent...
Jul 30 14:48:32 server1 postfix/postfix-script[10788]: starting the Postfix mail system
Jul 30 14:48:33 server1 postfix/master[10790]: daemon started -- version 2.10.1, configuration...fix
Jul 30 14:48:33 server1 systemd[1]: Started Postfix Mail Transport Agent.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server1 postfix]#

Configure Postfix as the default MTA using the alternatives command and verify.

[root@server1 postfix]# alternatives --set mta /usr/sbin/sendmail.postfix
[root@server1 postfix]# alternatives --display mta
mta - status is manual.
 link currently points to /usr/sbin/sendmail.postfix
/usr/sbin/sendmail.postfix - priority 30
 slave mta-mailq: /usr/bin/mailq.postfix
 slave mta-newaliases: /usr/bin/newaliases.postfix
 slave mta-pam: /etc/pam.d/smtp.postfix
 slave mta-rmail: /usr/bin/rmail.postfix
 slave mta-sendmail: /usr/lib/sendmail.postfix
 slave mta-mailqman: /usr/share/man/man1/mailq.postfix.1.gz
 slave mta-newaliasesman: /usr/share/man/man1/newaliases.postfix.1.gz
 slave mta-sendmailman: /usr/share/man/man1/sendmail.postfix.1.gz
 slave mta-aliasesman: /usr/share/man/man5/aliases.postfix.5.gz
Current `best' version is /usr/sbin/sendmail.postfix.
[root@server1 postfix]#

Mail a message to user3 with subject "Local delivery test" to test local mail delivery. (Install mailx package if the mail command is not available)>

[root@server1 postfix]# date|mail -s "Local delivery test" user3
[root@server1 postfix]#

Switch to the user3 account and run the mail command to check whether this user has received the email.

[root@server1 postfix]# su - user3
[user3@server1 ~]$ mail
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/user3": 1 message 1 new
>N  1 root                  Sat Jul 30 14:54  18/636   "Local delivery test"
&
Message  1:
From root@server1.roggeware.nl  Sat Jul 30 14:54:11 2016
Return-Path: <root@server1.roggeware.nl>
X -Original-To: user3
Delivered-To: user3@server1.roggeware.nl
Date: Sat, 30 Jul 2016 14:54:10 +0200
To: user3@server1.roggeware.nl
Subject: Local delivery test
User-Agent: Heirloom mailx 12.5 7/5/10
Content-Type: text/plain; charset=us-ascii
From: root@server1.roggeware.nl (root)
Status: R  
Sat Jul 30 14:54:10 CEST 2016
& 'q
Held 1 message in /var/spool/mail/user3
[user3@server1 ~]$

You can tail the /var/log/maillog file to view messages generated.

[root@server1 postfix]# tail /var/log/maillog
Jul 30 14:48:24 server1 postfix/postfix-script[10704]: stopping the Postfix mail system
Jul 30 14:48:24 server1 postfix/master[1736]: terminating on signal 15
Jul 30 14:48:32 server1 postfix/postfix-script[10788]: starting the Postfix mail system
Jul 30 14:48:33 server1 postfix/master[10790]: daemon started -- version 2.10.1, configuration /etc/postfix
Jul 30 14:54:10 server1 postfix/pickup[10791]: D0062679AB: uid=0 from=<root>
Jul 30 14:54:10 server1 postfix/cleanup[10868]: D0062679AB: message-id=<20160730125410.D0062679AB@server1.roggeware.nl>
Jul 30 14:54:10 server1 postfix/qmgr[10792]: D0062679AB: from=<root@server1.roggeware.nl>, size=488, nrcpt=1 (queue active)
Jul 30 14:54:11 server1 postfix/local[10870]: D0062679AB: to=<user3@server1.roggeware.nl>, orig_to=<user3>, relay=local, delay=0.33, delays=0.19/0.07/0/0.07, dsn=2.0.0,    status=sent (delivered to mailbox)
Jul 30 14:54:11 server1 postfix/qmgr[10792]: D0062679AB: removed
[root@server1 postfix]#

Test Central Mail Server from Remote Client

In this exercise server2 acts as a mail client and server1 as mail server.

You will install the Postfix software package , modify it to avoid DNS lookups, enable Postfix, and start it. Send mail to root on the mail server for verification. Log on to server1 as root and verify the receipt.

Install the Postfix software package on the mail client, server2.

[root@server2 ~]# yum install postfix
Package 2:postfix-2.10.1-6.el7.x86_64 already installed and latest version
Nothing to do
[root@server2 ~]#

Open the main.cf file and add the followig directive at the beginning of the file and run postfix check to verify the syntax.

disable_dns_lookups = yes
[root@server2 ~]# postfix check
[root@server2 ~]#

Set Postfix to start at system boot.

[root@server2 ~]# systemctl enable postfix
[root@server2 ~]# systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
   Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2016-07-22 22:30:14 CEST; 1 weeks 1 days ago
 Main PID: 1521 (master)
   CGroup: /system.slice/postfix.service
           ├─1521 /usr/libexec/postfix/master -w
           ├─1531 qmgr -l -t unix -u
           └─7896 pickup -l -t unix -u
Jul 22 22:30:12 server2 systemd[1]: Starting Postfix Mail Transport Agent...
Jul 22 22:30:14 server2 postfix/master[1521]: daemon started -- version 2.10.1, configuration ...fix
Jul 22 22:30:14 server2 systemd[1]: Started Postfix Mail Transport Agent.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server2 ~]#

Mail a message to root@server1.roggeware.nl with subject "Remote delivery test" to test network mail delivery.

[root@server2 ~]# which mail
/usr/bin/which: no mail in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)
[root@server2 ~]# which mailx
/usr/bin/which: no mailx in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)
[root@server2 ~]# yum install mailx
Resolving Dependencies
--> Running transaction check
---> Package mailx.x86_64 0:12.5-12.el7_0 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
====================================================================================================
 Package              Arch                  Version                       Repository           Size
====================================================================================================
Installing:
 mailx                x86_64                12.5-12.el7_0                 base                244 k
Transaction Summary
====================================================================================================
Install  1 Package
Total download size: 244 k
Installed size: 466 k
Is this ok [y/d/N]: y
Downloading packages:
mailx-12.5-12.el7_0.x86_64.rpm                                               | 244 kB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : mailx-12.5-12.el7_0.x86_64                                                       1/1
  Verifying  : mailx-12.5-12.el7_0.x86_64                                                       1/1
Installed:
  mailx.x86_64 0:12.5-12.el7_0 
Complete!
[root@server2 ~]#
[root@server2 ~]# date|mailx -s "Remote delivery test" root@server1.roggeware.nl
[root@server2 ~]#

Run the mail command on server1 to check whether the email has been received.

[root@server1 ~]# mail
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/root": 1 message 1 new
>N  1 root                  Sun Jul 31 11:42  21/846   "Remote delivery test"
&
Message  1:
From root@server2.localdomain  Sun Jul 31 11:42:00 2016
Return-Path: <root@server2.localdomain>
X-Original-To: root@server1.roggeware.nl
Delivered-To: root@server1.roggeware.nl
Date: Sun, 31 Jul 2016 11:41:59 +0200
To: root@server1.roggeware.nl
Subject: Remote delivery test
User-Agent: Heirloom mailx 12.5 7/5/10
Content-Type: text/plain; charset=us-ascii
From: root@server2.localdomain (root)
Status: R
Sun Jul 31 11:41:59 CEST 2016
& q
Held 1 message in /var/spool/mail/root
You have mail in /var/spool/mail/root
[root@server1 ~]#

Tail the /var/log/maillog file on both servers to view messages generated during the implementation of this exercise. You can find the incoming mail in the /var/spool/mail directory.

Configure Postfix to Forward Local Mail to a Central Mail Server and Reject Incoming Mail

This exercise should be done on host1 (mail client) and server1 (mail server).

You will install and configure Postfix on host1 to deny all incoming mail (access control) and forward (relayhost) localhost mail to the central mail server (server1). Disable the use of DNS for lookups. Ensure that any mail received on the central mail server appears to have originated from roggeware.nl and not atlas.roggeware.nl. Check the postfix configuration for any errors, configure appropiate host-based access rules in firewalld, enable and start postfix service and ensure it is the default MTA. Send a mail to a local user user1 on host1 nad confirm its receipt on the mail server.

On host1 install the postfix software package.

[root@atlas ~]# yum install postfix
Package 2:postfix-2.10.1-6.el7.x86_64 already installed and latest version
Nothing to do
[root@atlas ~]#

Open the main.cf and set or modify the directives below and check for any syntax errors.

myhostname = atlas.roggeware.nl
mydomain = roggeware.nl
myorigin = $mydomain
inet_interfaces = localhost
mydestination = localhost
relayhost = server1.roggeware.nl
disable_dns_lookups = yes
[root@atlas ~]# postfix check
[root@atlas ~]#

Review the changes made in main.cf with the command postconf -n.

[root@atlas ~]# postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
disable_dns_lookups = yes
html_directory = no
inet_interfaces = localhost
inet_protocols = all
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = localhost
mydomain = roggeware.nl
myhostname = atlas.roggeware.nl
mynetworks = 192.168.0.0/16,127.0.0.0/8
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES
relayhost = server1.roggeware.nl
sample_directory = /usr/share/doc/postfix-2.10.1/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
unknown_local_recipient_reject_code = 550
[root@atlas ~]#

Add the smtp service to firewalld persistently and reload the rules to allow SMTP traffic.

[root@atlas ~]# firewall-cmd --add-service smtp --permanent
success
[root@atlas ~]# firewall-cmd --reload
success
[root@atlas ~]# firewall-cmd --list-services
dhcpv6-client ftp http https ntp openvpn samba smtp ssh
[root@atlas ~]#

Enable postfix to start at boot time and start postfix.

[root@atlas ~]# systemctl enable postfix
[root@atlas ~]# systemctl start postfix
[root@atlas ~]# systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
   Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2016-07-31 14:14:29 CEST; 40s ago
 Main PID: 9169 (master)
   CGroup: /system.slice/postfix.service
           ├─9169 /usr/libexec/postfix/master -w
           ├─9170 pickup -l -t unix -u
           └─9171 qmgr -l -t unix -u
Jul 31 14:14:29 atlas.roggeware.nl postfix/postfix-script[9167]: starting the Postfix mail system
Jul 31 14:14:29 atlas.roggeware.nl postfix/master[9169]: daemon started -- version 2.10.1, conf...ix
Hint: Some lines were ellipsized, use -l to show in full.
[root@atlas ~]#

Configure Postfix as the default MTA using the alternatives command, and verify.

[root@atlas ~]# alternatives --set mta /usr/sbin/sendmail.postfix
[root@atlas ~]# alternatives --display mta|grep curr
 link currently points to /usr/sbin/sendmail.postfix
[root@atlas ~]#

Mail a message to user1 (this account should exist on both host1 and server1) with the subject "Relay Host Delivery Test".

[root@atlas ~]#  date|mail -s "Relay Host Delivery Test" user1
[root@atlas ~]#

On the mail server server1. Logon to server1 as user1 and run the mail command th check whether this user has received the email.

[root@server1 ~]# su - user1
[user1@server1 ~]$ mail
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/user1": 1 message 1 new
>N  1 root                  Sun Jul 31 14:20  21/800   "Relay Host Delivery Test"
&
Message  1:
From root@roggeware.nl  Sun Jul 31 14:20:02 2016
Return-Path: <root@roggeware.nl>
X-Original-To: user1@roggeware.nl
Delivered-To: user1@roggeware.nl
Date: Sun, 31 Jul 2016 14:20:13 +0200
To: user1@roggeware.nl
Subject: Relay Host Delivery Test
User-Agent: Heirloom mailx 12.5 7/5/10
Content-Type: text/plain; charset=us-ascii
From: root@roggeware.nl (root)
Status: R
Sun Jul 31 14:20:13 CEST 2016 
& q
Held 1 message in /var/spool/mail/user1
[user1@server1 ~]$

Tail the /var/log/maillog file on both servers to view messages generated during the implementation of this exercise. In addition you can find the incoming mail for the user in /var/spool/mail directory.

[root@atlas ~]# vi /var/log/maillog
Jul 31 14:14:29 atlas postfix/postfix-script[9167]: starting the Postfix mail system
Jul 31 14:14:29 atlas postfix/master[9169]: daemon started -- version 2.10.1, configuration /etc/postfix
Jul 31 14:20:13 atlas postfix/pickup[9170]: AEED3C007A1F: uid=0 from=<root>
Jul 31 14:20:13 atlas postfix/cleanup[9589]: AEED3C007A1F: message-id=<20160731122013.AEED3C007A1F@atlas.roggeware.nl>
Jul 31 14:20:13 atlas postfix/qmgr[9171]: AEED3C007A1F: from=<root@roggeware.nl>, size=477, nrcpt=1 (queue active)
Jul 31 14:20:13 atlas postfix/smtp[9591]: AEED3C007A1F: to=<user1@roggeware.nl>, orig_to=<user1>, relay=server1.roggeware.nl[192.168.122.110]:25, delay=0.3,  delays=0.06/0.03/0.12/0.09, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as A0317679AB )
Jul 31 14:20:13 atlas postfix/qmgr[9171]: AEED3C007A1F: removed
[root@server1 ~]# vi /var/log/maillog
Jul 31 14:20:02 server1 postfix/smtpd[11749]: warning: hostname gateway does not resolve to address 192.168.122.1
Jul 31 14:20:02 server1 postfix/smtpd[11749]: connect from unknown[192.168.122.1]
Jul 31 14:20:02 server1 postfix/smtpd[11749]: A0317679AB: client=unknown[192.168.122.1]
Jul 31 14:20:02 server1 postfix/cleanup[11752]: A0317679AB: message-id=<20160731122013.AEED3C007A1F@atlas.roggeware.nl>
Jul 31 14:20:02 server1 postfix/qmgr[10792]: A0317679AB: from=<root@roggeware.nl>, size=666, nrcpt=1 (queue active)
Jul 31 14:20:02 server1 postfix/smtpd[11749]: disconnect from unknown[192.168.122.1]
Jul 31 14:20:02 server1 postfix/local[11753]: A0317679AB: to=<user1@roggeware.nl>, relay=local, delay=0.11, delays=0.07/0.03/0/0.01, dsn=2.0.0, status=sent (delivered to  mailbox)
Jul 31 14:20:02 server1 postfix/qmgr[10792]: A0317679AB: removed
[root@server1 ~]# cd /var/spool/mail
[root@server1 mail]# ls -l
total 12
-rw-------. 1 root   mail 1696 Jul 31 11:52 root
-rw-rw----. 1 user1  mail  811 Jul 31 14:20 user1
-rw-rw----. 1 user10 mail    0 Jul 22 22:31 user10
-rw-rw----. 1 user11 mail    0 Jul 22 22:32 user11
-rw-rw----. 1 user3  mail  647 Jul 30 14:56 user3
[root@server1 mail]# cat user1
From root@roggeware.nl  Sun Jul 31 14:20:02 2016
Return-Path: <root@roggeware.nl>
X-Original-To: user1@roggeware.nl
Delivered-To: user1@roggeware.nl
Received: from atlas.roggeware.nl (unknown [192.168.122.1])
        by server1.roggeware.nl (Postfix) with ESMTP id A0317679AB
        for <user1@roggeware.nl>; Sun, 31 Jul 2016 14:20:02 +0200 (CEST)
Received: by atlas.roggeware.nl (Postfix, from userid 0)
        id AEED3C007A1F; Sun, 31 Jul 2016 14:20:13 +0200 (CEST)
Date: Sun, 31 Jul 2016 14:20:13 +0200
To: user1@roggeware.nl
Subject: Relay Host Delivery Test
User-Agent: Heirloom mailx 12.5 7/5/10
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Message-Id: <20160731122013.AEED3C007A1F@atlas.roggeware.nl>
From: root@roggeware.nl (root)
Status: RO
Sun Jul 31 14:20:13 CEST 2016
[root@server1 mail]#

Configure Postfix to Receive Local Network Mail and Forward All Mail to a Central Mail Server

This exercise involves host1 (relay host), server1 (mail server) and server2 (mail client).

On the relay host host1. Open the main.cf file and set the following directives.

myhostname = atlas.roggeware.nl
mydomain = roggeware.nl
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
relayhost = server1.roggeware.nl
disable_dns_lookups = yes

Restart the Postfix service.

[root@atlas mail]# postfix check
[root@atlas mail]# systemctl restart postfix
[root@atlas mail]#

On the mail client server2. Mail a message to user1@host1.roggeware.nl with subject "Relay Host Delivery Test" to test the relay host functionality from a network system.

[root@server2 ~]# date|mail -s "Relay Host Delivery Test" user1@atlas.roggeware.nl
[root@server2 ~]#

On the mail server server1. Logon to server1 as user1 and run the mail command to check whether this user has received the email.

Tail the /var/log/maillog file on host1 and server1 to view messages generated during the testing.

Deze oefening werkt nog niet.

Chapter 24 Configuring DNS

Determining the IP address of a hostname is referred to as forward name resolution or simply name resolution and determining the hostname associated with an IP address is reffered to as reverse name resolution.

Domain Name System and Name Resolution

What is Bind

DNS Name Space and Domains

The DNS Name Space is an hierarchical organization of all the domains on the internet. The root of the name space is represented by a dot. The hierarchy right below the root represents top-level domains (TLD) that are either generic, such as .com, .net , .org and .gov, and referred to as gTLDs or specific to a two-letter country-code, such as .ca and .uk and referred to as ccTLDs. Sub-domains fall under domains and are separated by a dot.

DNS Root Servers

DNS Roles

Types of Nameserver Configurations

DNS Zones and Zone Files

BIND Software Packages and Service Daemon

bind        Provides software to configure a DNS server.
bind-libs   Contains library files for bind and bind-utils packages.
bind-utils  Comprises of resolver tools, such as dig, host and nslookup

Daemon named listens on well-know port 53 and supports both TCP and UDP protocols for operation. See /usr/share/doc/bind for example named configuration files.

Analysis of the Default Nameserver Configuration File

Analysis of the Default Zone Configuration File

DNS Message Logging

Configuring Bind Server

SELinux Requirements for BIND Operation

Let's look at the BIND-specific SELinux contexts on processes, files and port and also see the booleans that may require a toggel for BIND to function properly.


By default, the named daemon runs confied in its own domain and is labeled appropiately with domain type named_t.

Configure a Caching-Only DNS Server

You will configure server1 as a primary DNS server. Install BIND software, midufy named.conf file, set the BIND service to autostart, start the BIND service and open port 53 in the firewall.

Install the BIND software packages.

[root@atlas target]# yum install bind-utils bind
Package 32:bind-utils-9.9.4-29.el7_2.3.x86_64 already installed and latest version
Resolving Dependencies
--> Running transaction check
 ---> Package bind.x86_64 32:9.9.4-29.el7_2.3 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
====================================================================================================
 Package           Arch                Version                           Repository            Size
====================================================================================================
Installing:
 bind              x86_64              32:9.9.4-29.el7_2.3               updates              1.8 M
Transaction Summary
====================================================================================================
Install  1 Package
Total download size: 1.8 M
Installed size: 4.3 M
Is this ok [y/d/N]: y
Downloading packages:
bind-9.9.4-29.el7_2.3.x86_64.rpm                                             | 1.8 MB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 32:bind-9.9.4-29.el7_2.3.x86_64                                                  1/1
  Verifying  : 32:bind-9.9.4-29.el7_2.3.x86_64                                                  1/1
Installed:
  bind.x86_64 32:9.9.4-29.el7_2.3
Complete!
[root@atlas target]#

Open the named.conf file and set the following directives.

options {
    listen-on port 53 { any; };
    allow-query     { any; };
    recursion yes;
    dnssec-enable no;
    dnssec-validation no;
};

Check the configuration file using the named-checkconf command.

[root@atlas target]# named-checkconf
[root@atlas target]#

Set named to autostart at system boot.

[root@atlas target]# systemctl enable named Created symlink from /etc/systemd/system/multi-user.target.wants/named.service to /usr/lib/systemd/system/named.service. [root@atlas target]#

Start the BIND service and check its operational status.

[root@atlas target]# systemctl start named
[root@atlas target]# systemctl status named
● named.service - Berkeley Internet Name Domain (DNS)
   Loaded: loaded (/usr/lib/systemd/system/named.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2016-08-01 12:06:53 CEST; 24s ago
  Process: 15606 ExecStart=/usr/sbin/named -u named $OPTIONS (code=exited, status=0/SUCCESS)
  Process: 15602 ExecStartPre=/bin/bash -c if [ ! "$DISABLE_ZONE_CHECKING" == "yes" ]; then /usr/sbin/named-checkconf -z /etc/named.conf; else echo "Checking of zone files  is disabled"; fi (code=exited, status=0/SUCCESS)
 Main PID: 15607 (named)
   CGroup: /system.slice/named.service
           └─15607 /usr/sbin/named -u named
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: command channel listening on 127.0.0.1#953
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: command channel listening on ::1#953
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: managed-keys-zone: loaded serial 0
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: zone 0.in-addr.arpa/IN: loaded serial 0
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: zone 1.0.0.127.in-addr.arpa/IN: loaded serial 0
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: zone localhost/IN: loaded serial 0
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: zone localhost.localdomain/IN: loaded serial 0
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: zone 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0....l 0
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: all zones loaded
Aug 01 12:06:53 atlas.roggeware.nl named[15607]: running
Hint: Some lines were ellipsized, use -l to show in full.
[root@atlas target]#

Add the named service to firewalld persistently and reload the new rules to allow traffic on DNS port 53.

[root@server1 etc]# firewall-cmd --list-services
dhcpv6-client http https smtp ssh
[root@server1 etc]# firewall-cmd --add-service dns --permanent
success
[root@server1 etc]# firewall-cmd --reload
success
[root@server1 etc]# firewall-cmd --list-services
dhcpv6-client dns http https smtp ssh
[root@server1 etc]#

Understanding, Configuring and Troubleshooting DNS Client

Overview of DNS Client Configuration Files

Overview of DNS Lookup Utilities

Configure DNS Client and Test Server Configuration

In this exercise on server2 you will install the bind-utils package and testthe caching-only nameserver you set up in the previous exercise. Modify the resolver configuration file and add an entry for the new nameserver. Ensure that the name service file contains proper hosts entry. Test nameserver agan.

Install the DNS Client software package bind-utils.

[root@atlas ~]# yum install bind-utils
Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos, subscription-manager
This system is not registered with Subscription Management. You can use subscription-manager to register.
Repository epel-debuginfo is listed more than once in the configuration
Repository epel-source is listed more than once in the configuration
Loading mirror speeds from cached hostfile
 * base: mirror.oxilion.nl
 * epel: mirror.kinamo.be
 * extras: mirror.denit.net
 * updates: mirror.oxilion.nl
Package 32:bind-utils-9.9.4-29.el7_2.3.x86_64 already installed and latest version
Nothing to do
[root@atlas ~]#

Test the functionality of the caching-only nameserver with the dig and host commands.

[root@atlas ~]# dig @server1 linux.org
; <<>> DiG 9.9.4-RedHat-9.9.4-29.el7_2.3 <<>> @server1 linux.org
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47935
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 3
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;linux.org.                     IN      A
;; ANSWER SECTION:
linux.org.              3600    IN      A       104.225.135.13
;; AUTHORITY SECTION:
linux.org.              86400   IN      NS      ns1.iqnection.com.
linux.org.              86400   IN      NS      ns2.iqnection.com. 
;; ADDITIONAL SECTION:
ns2.iqnection.com.      3600    IN      A       204.77.2.207
ns1.iqnection.com.      3600    IN      A       45.79.199.45 
;; Query time: 409 msec
;; SERVER: 192.168.122.110#53(192.168.122.110)
;; WHEN: Mon Aug 01 14:11:26 CEST 2016
;; MSG SIZE  rcvd: 135 
[root@atlas ~]#
[root@atlas ~]# host linux.org 192.168.122.110
Using domain server:
Name: 192.168.122.110
Address: 192.168.122.110#53
Aliases:
linux.org has address 104.225.135.13
linux.org mail is handled by 20 iqdig11.iqnection.com.
[root@atlas ~]#

The above demonstrates the use of the hostname and IP address of the caching-only nameserver at the command line.

Open the resolver configuration file and add the following entry.

nameserver 192.168.122.110

Open the name server switch configuration file and ensure the hosts entry looks like the following.

hosts:      files dns

Test the functionality of the caching-only nameserver again wit the dig and nslookup commands without specifying the nameserver at the command line.

[root@atlas ~]# dig linux.org
; <<>> DiG 9.9.4-RedHat-9.9.4-29.el7_2.3 <<>> linux.org
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 17962
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 3
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;linux.org.                     IN      A
;; ANSWER SECTION:
linux.org.              3173    IN      A       104.225.135.13
;; AUTHORITY SECTION:
linux.org.              85973   IN      NS      ns1.iqnection.com.
linux.org.              85973   IN      NS      ns2.iqnection.com. 
;; ADDITIONAL SECTION:
ns2.iqnection.com.      3173    IN      A       204.77.2.207
ns1.iqnection.com.      3173    IN      A       45.79.199.45 
;; Query time: 1 msec
;; SERVER: 192.168.122.110#53(192.168.122.110)
;; WHEN: Mon Aug 01 14:18:32 CEST 2016
;; MSG SIZE  rcvd: 135
[root@atlas ~]# nslookup linux.org
Server:         192.168.122.110
Address:        192.168.122.110#53
Non-authoritative answer:
Name:   linux.org
Address: 104.225.135.13
[root@atlas ~]#

The abouve outputs indicate that both commands now use the caching nameserver for lookups without being explicitly supplied at the command line.

Troubleshooting DNS Client Issues

DNS Commands

systemctl enable named
systemctl start named
named-checkconf

DNS related files

/etc/named.conf
/usr/share/doc/bind
/var/log/messages
/var/named.rfc1912.zones
/var/named/                    Zone files

SeLinux requirements

ps -eZ |grep named shows domain type named_t.
semanage port -l|grep dns
getsebool -a |grep ^named

Chapter 25 Managing MariaDB

Understanding Databases, DBMS and MariaDB

What is a relational Database?

Overview of MariaDB

MariaDB Software Packages and Service Daemon

MariaDB Commands

MariaDB Configuration Files

The primary configuration file for MariaDB is the /etc/my.cnf, which sets global defaults for mysql shell program, mysqld_safe startup script and the mysqld daemon process. The includedir at the bottom of the file instructs the startup program to look for additional configuration files in the /etc/my.cnf.d directory and process them if they exists.

[root@server1 ~]# ls -l /etc/my.cnf
-rw-r--r--. 1 root root 570 Mar 31 16:49 /etc/my.cnf
[root@server1 ~]# ls -l /etc/my.cnf.d/
total 4
-rw-r--r--. 1 root root 232 Dec  9  2015 mysql-clients.cnf
[root@server1 ~]#

Logging MariaDB Messages

The default file for storing MariaDB logs is mariadb.log located in var/log/mariadb directory, as defined in the /etc/my.cnf file.

Managing MariaDB

SELinux Requirements for MAriaDB Operation

Install and Configure MariaDB

In this exercise on server1 you will install the MariaDB server software, including dependent packages, secure its installation and setup a password for the root user account to access MariaDB.

Install the MariaDB server software package.

[root@server1 ~]# yum install mariadb-server
Resolving Dependencies
--> Running transaction check
---> Package mariadb-server.x86_64 1:5.5.47-1.el7_2 will be installed
--> Processing Dependency: mariadb(x86-64) = 1:5.5.47-1.el7_2 for package: 1:mariadb-server-5.5.47-1.el7_2.x86_64
--> Processing Dependency: perl-DBI for package: 1:mariadb-server-5.5.47-1.el7_2.x86_64
--> Processing Dependency: perl-DBD-MySQL for package: 1:mariadb-server-5.5.47-1.el7_2.x86_64
...
---> Package perl-parent.noarch 1:0.225-244.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
====================================================================================================
 Package                          Arch            Version                    Repository        Size
====================================================================================================
Installing:
 mariadb-server                   x86_64          1:5.5.47-1.el7_2           updates           11 M
Installing for dependencies:
 mariadb                          x86_64          1:5.5.47-1.el7_2           updates          8.9 M
 perl                             x86_64          4:5.16.3-286.el7           base             8.0 M
 perl-Carp                        noarch          1.26-244.el7               base              19 k
 perl-Compress-Raw-Bzip2          x86_64          2.061-3.el7                base              32 k
 perl-Compress-Raw-Zlib           x86_64          1:2.061-4.el7              base              57 k
 ...
 perl-threads                     x86_64          1.87-4.el7                 base              49 k
 perl-threads-shared              x86_64          1.43-6.el7                 base              39 k
Transaction Summary
====================================================================================================
Install  1 Package (+36 Dependent packages)
Total download size: 32 M
Installed size: 144 M
Is this ok [y/d/N]: y
Downloading packages:
(1/37): perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64.rpm                       |  32 kB  00:00:00
(2/37): perl-Compress-Raw-Zlib-2.061-4.el7.x86_64.rpm                        |  57 kB  00:00:00
...
(35/37): mariadb-5.5.47-1.el7_2.x86_64.rpm                                   | 8.9 MB  00:00:08
(36/37): mariadb-server-5.5.47-1.el7_2.x86_64.rpm                            |  11 MB  00:00:09
(37/37): perl-5.16.3-286.el7.x86_64.rpm                                      | 8.0 MB  00:00:09
----------------------------------------------------------------------------------------------------
Total                                                               3.3 MB/s |  32 MB  00:00:09
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
 Installing : 1:perl-parent-0.225-244.el7.noarch                                              1/37
 Installing : perl-HTTP-Tiny-0.033-3.el7.noarch                                               2/37
 ...
 Installing : perl-DBD-MySQL-4.023-5.el7.x86_64                                              36/37
 Installing : 1:mariadb-server-5.5.47-1.el7_2.x86_64                                         37/37
 Verifying  : perl-HTTP-Tiny-0.033-3.el7.noarch                                               1/37
 Verifying  : perl-threads-shared-1.43-6.el7.x86_64                                           2/37
 ...
 Verifying  : perl-Filter-1.49-3.el7.x86_64                                                  36/37
 Verifying  : perl-Text-ParseWords-3.29-4.el7.noarch                                         37/37
Installed:
  mariadb-server.x86_64 1:5.5.47-1.el7_2
Dependency Installed:
  mariadb.x86_64 1:5.5.47-1.el7_2                  perl.x86_64 4:5.16.3-286.el7
  perl-Carp.noarch 0:1.26-244.el7                  perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7
  ...
  perl-parent.noarch 1:0.225-244.el7               perl-podlators.noarch 0:2.5.1-3.el7
  perl-threads.x86_64 0:1.87-4.el7                 perl-threads-shared.x86_64 0:1.43-6.el7
Complete!
[root@server1 ~]#

Set MariaDB service to autostart at system reboots and start the mariadb service.

[root@server1 ~]# systemctl enable mariadb
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@server1 ~]# systemctl start mariadb
[root@server1 ~]# systemctl status mariadb
â mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2016-08-03 11:36:49 CEST; 5s ago
  Process: 5021 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
 Process: 4942 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 5020 (mysqld_safe)
   CGroup: /system.slice/mariadb.service
           ââ5020 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
           ââ5179 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/l...
Aug 03 11:36:45 server1 mariadb-prepare-db-dir[4942]: The latest information about MariaDB is a.../.
Aug 03 11:36:45 server1 mariadb-prepare-db-dir[4942]: You can find additional information about...t:
Aug 03 11:36:45 server1 mariadb-prepare-db-dir[4942]: http://dev.mysql.com
Aug 03 11:36:45 server1 mariadb-prepare-db-dir[4942]: Support MariaDB development by buying sup...DB
Aug 03 11:36:45 server1 mariadb-prepare-db-dir[4942]: Corporation Ab. You can contact us about ...m.
Aug 03 11:36:45 server1 mariadb-prepare-db-dir[4942]: Alternatively consider joining our commun...t:
Aug 03 11:36:45 server1 mariadb-prepare-db-dir[4942]: http://mariadb.com/kb/en/contributing-to-...t/
Aug 03 11:36:46 server1 mysqld_safe[5020]: 160803 11:36:46 mysqld_safe Logging to '/var/log/ma...g'.
Aug 03 11:36:46 server1 mysqld_safe[5020]: 160803 11:36:46 mysqld_safe Starting mysqld daemon ...sql
Aug 03 11:36:49 server1 systemd[1]: Started MariaDB database server.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server1 ~]#

Secure access to MariaDB installation using the mysql_secure_installation script and enter information as highlighted.

[root@server1 ~]# mysql_secure_installation
/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
Set root password? [Y/n]
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n]
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] n
 ... skipping.
By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] n
 ... skipping.
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n]
 ... Success!
Cleaning up...
All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
[root@server1 ~]#

Add the MariaDB service to firewalld persistently and reload the rules to allow (mysql) traffic on port 3306.

[root@server1 ~]# firewall-cmd --list-services
dhcpv6-client dns http https smtp ssh
[root@server1 ~]# firewall-cmd --add-service mysql --permanent
success
[root@server1 ~]# firewall-cmd --reload
success
[root@server1 ~]# firewall-cmd --list-service
dhcpv6-client dns http https mysql smtp ssh
[root@server1 ~]#

Starting the MariaDB Shell and Understanding its Usage

One you have started the MariaDB server software installed and root password set up, you can invoke is shell interface with the mysql command.

[root@server1 ~]# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 7
Server version: 5.5.47-MariaDB MariaDB Server
Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>

The MariaDB shell prompt appears. Several subcommands are available.

MariaDB [(none)]> help
General information about MariaDB can be found at
http://mariadb.org
List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
edit      (\e) Edit command with $EDITOR.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit.
go        (\g) Send command to mysql server.
help      (\h) Display this help.
nopager   (\n) Disable pager, print to stdout.
notee     (\t) Don't write into outfile.
pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
system    (\!) Execute a system shell command.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement. 
For server side help, type 'help contents' 
MariaDB [(none)]>

Create Database and Table and Insert Records

In this exercise you will create a database called rhce and create a table called scientists in this database.

List what databases are available.

MariaDB [(none)]> show databases;'
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)
MariaDB [(none)]>

Create a database called rhce using the create command. |Verify the creation with command show databases.

MariaDB [(none)]> create database rhce;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| rhce               |
| test               |
+--------------------+
5 rows in set (0.00 sec)
MariaDB [(none)]>


Select the new database for further actions using the use command.

MariaDB [(none)]> use rhce;
Database changed
MariaDB [rhce]>

Notice that the prompt has changed to reflect the selected database.

Create a table called scientists in the rhce database using the create subcommand.

MariaDB [rhce]> create table scientists (Sno int,Firstname varchar(20),Lastname varchar(20),City varchar(20),Country varchar(20),Age int);
Query OK, 0 rows affected (0.02 sec)
MariaDB [rhce]>

Display the structure of the table with the describe subcommand.

MariaDB [rhce]> describe scientists;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| Sno       | int(11)     | YES  |     | NULL    |       |
| Firstname | varchar(20) | YES  |     | NULL    |       |
| Lastname  | varchar(20) | YES  |     | NULL    |       |
| City      | varchar(20) | YES  |     | NULL    |       |
| Country   | varchar(20) | YES  |     | NULL    |       |
| Age       | int(11)     | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
MariaDB [rhce]>

Insert all the records to the table using the insert subcommand.

MariaDB [rhce]> insert into scientists values('1','Albert','Einstein','Ulm','Germany',76);
Query OK, 1 row affected (0.04 sec)
MariaDB [rhce]> insert into scientists values('2','Isaac','Newton','Woolsthorpe','UK',84);
Query OK, 1 row affected (0.01 sec)
MariaDB [rhce]> insert into scientists values('3','Marie','Curie','Warsaw','Poland',67);
Query OK, 1 row affected (0.01 sec)
MariaDB [rhce]> insert into scientists values('4','Galileo','Galilei','Pisa','Italy',78);
Query OK, 1 row affected (0.01 sec)
MariaDB [rhce]> insert into scientists values('5','Thomas','Edison','Milan','USA',84);
Query OK, 1 row affected (0.02 sec)
MariaDB [rhce]> insert into scientists values('6','Alexander','Bell','Edinburg','UK',75);
Query OK, 1 row affected (0.02 sec)
MariaDB [rhce]> insert into scientists values('7','Louis','Pasteur','Dole','France',73);
Query OK, 1 row affected (0.02 sec)
MariaDB [rhce]> insert into scientists values('8','Nicolaus','Copernicus','Toruri','Poland',70);
Query OK, 1 row affected (0.04 sec)
MariaDB [rhce]> insert into scientists values('9','James','Maxwell','Edinburg','UK',48);
Query OK, 1 row affected (0.01 sec)
MariaDB [rhce]> insert into scientists values('10','Pierre','Curie','Paris','France',47);
Query OK, 1 row affected (0.03 sec)
MariaDB [rhce]>

Query all the records to confirm their addition to the table using the select subcommand.

MariaDB [rhce]> select * from scientists;

+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    1 | Albert    | Einstein   | Ulm         | Germany |   76 |
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    7 | Louis     | Pasteur    | Dole        | France  |   73 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
+------+-----------+------------+-------------+---------+------+
10 rows in set (0.00 sec)
MariaDB [rhce]>

Perform SQL Queries against a Database

In this exercise you will perform a number of queries agains the database rhce.

Query all stored records.

MariaDB [rhce]> select * from scientists;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    1 | Albert    | Einstein   | Ulm         | Germany |   76 |
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    7 | Louis     | Pasteur    | Dole        | France  |   73 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
+------+-----------+------------+-------------+---------+------+
10 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists who died at the age of 84.

MariaDB [rhce]> select * from scientists where Age=84;
+------+-----------+----------+-------------+---------+------+
| Sno  | Firstname | Lastname | City        | Country | Age  |
+------+-----------+----------+-------------+---------+------+
|    2 | Isaac     | Newton   | Woolsthorpe | UK      |   84 |
|    5 | Thomas    | Edison   | Milan       | USA     |   84 |
+------+-----------+----------+-------------+---------+------+
2 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists who lived for 75 or more years.

MariaDB [rhce]> select * from scientists where Age > 75;
+------+-----------+----------+-------------+---------+------+
| Sno  | Firstname | Lastname | City        | Country | Age  |
+------+-----------+----------+-------------+---------+------+
|    1 | Albert    | Einstein | Ulm         | Germany |   76 |
|    2 | Isaac     | Newton   | Woolsthorpe | UK      |   84 |
|    4 | Galileo   | Galilei  | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison   | Milan       | USA     |   84 |
+------+-----------+----------+-------------+---------+------+
4 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists with last name "Curie".

MariaDB [rhce]> select * from scientists where Lastname='Curie';
+------+-----------+----------+--------+---------+------+
| Sno  | Firstname | Lastname | City   | Country | Age  |
+------+-----------+----------+--------+---------+------+
|    3 | Marie     | Curie    | Warsaw | Poland  |   67 |
|   10 | Pierre    | Curie    | Paris  | France  |   47 |
+------+-----------+----------+--------+---------+------+
2 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists who were born in Poland and Germany.

MariaDB [rhce]> select * from scientists where Country='Poland' or Country='Germany';
+------+-----------+------------+--------+---------+------+
| Sno  | Firstname | Lastname   | City   | Country | Age  |
+------+-----------+------------+--------+---------+------+
|    1 | Albert    | Einstein   | Ulm    | Germany |   76 |
|    3 | Marie     | Curie      | Warsaw | Poland  |   67 |
|    8 | Nicolaus  | Copernicus | Toruri | Poland  |   70 |
+------+-----------+------------+--------+---------+------+
3 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists sorted by their first names.

MariaDB [rhce]> select * from scientists order by firstname;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    1 | Albert    | Einstein   | Ulm         | Germany |   76 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|    7 | Louis     | Pasteur    | Dole        | France  |   73 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
+------+-----------+------------+-------------+---------+------+
10 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists sorted by their last names in descending order.

MariaDB [rhce]> select * from scientists order by lastname desc;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    7 | Louis     | Pasteur    | Dole        | France  |   73 |
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    1 | Albert    | Einstein   | Ulm         | Germany |   76 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
+------+-----------+------------+-------------+---------+------+
10 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists who were born in countries starting with the letter U and followed by any letters.

MariaDB [rhce]> select * from scientists where Country like 'U%';
+------+-----------+----------+-------------+---------+------+
| Sno  | Firstname | Lastname | City        | Country | Age  |
+------+-----------+----------+-------------+---------+------+
|    2 | Isaac     | Newton   | Woolsthorpe | UK      |   84 |
|    5 | Thomas    | Edison   | Milan       | USA     |   84 |
|    6 | Alexander | Bell     | Edinburg    | UK      |   75 |
|    9 | James     | Maxwell  | Edinburg    | UK      |   48 |
+------+-----------+----------+-------------+---------+------+
4 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists who were born in France, Germany and Italy, with output sorted in reverse on the first column.

MariaDB [rhce]> select * from scientists where Country='France' or Country='Germany' or Country='Italy' order by Sno desc;
+------+-----------+----------+-------+---------+------+
| Sno  | Firstname | Lastname | City  | Country | Age  |
+------+-----------+----------+-------+---------+------+
|   10 | Pierre    | Curie    | Paris | France  |   47 |
|    7 | Louis     | Pasteur  | Dole  | France  |   73 |
|    4 | Galileo   | Galilei  | Pisa  | Italy   |   78 |
|    1 | Albert    | Einstein | Ulm   | Germany |   76 |
+------+-----------+----------+-------+---------+------+
4 rows in set (0.00 sec)
MariaDB [rhce]>

Query records for all scientists who died in their 70's.

MariaDB [rhce]> select * from scientists where Age like '7%';
+------+-----------+------------+----------+---------+------+
| Sno  | Firstname | Lastname   | City     | Country | Age  |
+------+-----------+------------+----------+---------+------+
|    1 | Albert    | Einstein   | Ulm      | Germany |   76 |
|    4 | Galileo   | Galilei    | Pisa     | Italy   |   78 |
|    6 | Alexander | Bell       | Edinburg | UK      |   75 |
|    7 | Louis     | Pasteur    | Dole     | France  |   73 |
|    8 | Nicolaus  | Copernicus | Toruri   | Poland  |   70 |
+------+-----------+------------+----------+---------+------+
5 rows in set (0.00 sec)
MariaDB [rhce]>

Rename Table and Update and Delete Records

In this exercise you will rename the table scientists to science without affecting the data, update two records and then delete them.

Rename the table scientists to science.

MariaDB [rhce]> rename table scientists to science;
Query OK, 0 rows affected (0.02 sec)
MariaDB [rhce]>

And confirm the change.

MariaDB [rhce]> show tables;
+----------------+
| Tables_in_rhce |
+----------------+
| science        |
+----------------+
1 row in set (0.00 sec)
MariaDB [rhce]>

Verify that the records in the renamed table are unaffected.

MariaDB [rhce]> select * from science;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+ 
|    1 | Albert    | Einstein   | Ulm         | Germany |   76 |
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    7 | Louis     | Pasteur    | Dole        | France  |   73 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
+------+-----------+------------+-------------+---------+------+
10 rows in set (0.00 sec)
MariaDB [rhce]>

Replace the fields Albert Einstein with Benjamijn Franklin using the update command.

MariaDB [rhce]> update science set Firstname='Benjamin', Lastname='Franklin' where Sno='1';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0
MariaDB [rhce]> select * from science;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    1 | Benjamin  | Franklin   | Ulm         | Germany |   76 |
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    7 | Louis     | Pasteur    | Dole        | France  |   73 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
+------+-----------+------------+-------------+---------+------+
10 rows in set (0.00 sec)
MariaDB [rhce]>

Replace the fields Paris and 73 for Sno 7 with Cannes and 75 using the update command.

MariaDB [rhce]> update science set City='Cannes',Age=75 where Sno=7;
Query OK, 1 row affected (0.03 sec)
Rows matched: 1  Changed: 1  Warnings: 0
MariaDB [rhce]> select * from science;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    1 | Benjamin  | Franklin   | Ulm         | Germany |   76 |
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    7 | Louis     | Pasteur    | Cannes      | France  |   75 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
+------+-----------+------------+-------------+---------+------+
10 rows in set (0.00 sec)
MariaDB [rhce]>

Delete records numbers 1 and 7 from the table using the delete command.

MariaDB [rhce]> delete from science where Sno=1 or Sno=7;
Query OK, 2 rows affected (0.01 sec)
MariaDB [rhce]> select * from science;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
+------+-----------+------------+-------------+---------+------+
8 rows in set (0.00 sec)
MariaDB [rhce]>

Backing Up and Restoring a Database or Table

MariaDB offers a tool called mysqldump for creating logical backups of data. To restore, the mysql tool can be used.

To backup all databases on the system, use the --all-databases option with the command and redirecto the output to a file.

[root@server1 ~]# mysqldump -u root -p --all-databases >db_bkp_all.sql
Enter password:
[root@server1 ~]#

To restore a specific database, such as DB1, from the above.

[root@server1 ~]# mysql -u root -p DB1 <db_bkp_all.sql
Enter password:
ERROR 1049 (42000): Unknown database 'DB1'
[root@server1 ~]#

To backup specific databases, use the --database option with the commnad and specify the database names to be backed up.

[root@server1 ~]# mysqldump -u root -p --databases DB1 DB2 DB3 >db_bkp_db123.sql' 
Enter password:
mysqldump: Got error: 1049: "Unknown database 'DB1'" when selecting the database
[root@server1 ~]#

To restore all three databases from the above.

[root@server1 ~]# mysql -u root -p <db_bkp_db123.sql
Enter password:
[root@server1 ~]#

To backup specific tables, such as tbl1 and tbl2, located in a databases called DB1.

[root@server1 ~]# mysqldump -u root -p --databases DB1 tbl1 tbl2 >db_bkp_tbl12.sql
Enter password:
mysqldump: Got error: 1049: "Unknown database 'DB1'" when selecting the database
[root@server1 ~]#

To restore only tbl1 from the above.

[root@server1 ~]# mysql -u root -p DB1 tbl1 <db_bkp_tbl12.sql

Backup, Drop, Recreate and Restore a Database

In this exercise you will create a dump of the rhce database in a file in /tmp and then drop the entire database. Recreate the database and restore the original structure.

Create a dump of the rhce database using the mysqldump command and store it in /tmp/rhce_db.sql file.

[root@server1 ~]# mysqldump -u root -p --databases rhce >/tmp/rhce_db.sql
Enter password:
[root@server1 ~]# ls -l /tmp/rhce_db.sql
-rw-r--r--. 1 root root 2472 Aug  4 10:15 /tmp/rhce_db.sql
[root@server1 ~]#

Drop the rhce database.

MariaDB [(none)]> drop database rhce;
Query OK, 1 row affected (0.03 sec)
MariaDB [(none)]>

Confirm the removal of the database.

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)
MariaDB [(none)]>

Recreate the rhce database and exit the shell.

MariaDB [(none)]> create database rhce;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| rhce               |
| test               |
+--------------------+
5 rows in set (0.00 sec)
MariaDB [(none)]> quit
Bye
[root@server1 ~]#

Restore the rhce database from the /tmp/rhce_db.sql dump using the mysql command.

[root@server1 ~]# mysql -u root -p </tmp/rhce_db.sql
Enter password:
[root@server1 ~]#

Log back in with the rhce database selected and verify the presence of the science table.

[root@server1 ~]# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 5.5.47-MariaDB MariaDB Server
Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> use rhce;
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
MariaDB [rhce]> select * from science;
+------+-----------+------------+-------------+---------+------+
| Sno  | Firstname | Lastname   | City        | Country | Age  |
+------+-----------+------------+-------------+---------+------+
|    2 | Isaac     | Newton     | Woolsthorpe | UK      |   84 |
|    3 | Marie     | Curie      | Warsaw      | Poland  |   67 |
|    4 | Galileo   | Galilei    | Pisa        | Italy   |   78 |
|    5 | Thomas    | Edison     | Milan       | USA     |   84 |
|    6 | Alexander | Bell       | Edinburg    | UK      |   75 |
|    8 | Nicolaus  | Copernicus | Toruri      | Poland  |   70 |
|    9 | James     | Maxwell    | Edinburg    | UK      |   48 |
|   10 | Pierre    | Curie      | Paris       | France  |   47 |
+------+-----------+------------+-------------+---------+------+
8 rows in set (0.00 sec)
MariaDB [rhce]>

Define users and grant permissions

MariaDB [(none)]> create user 'user2@localhost' identified by 'user2';
MariaDB [(none)]> show grants for user2@localhost;set password for user2@localhost  = password('user2');
MariaDB [(none)]> show grants for user2@localhost;
MariaDB [(none)]> grant all on rhce.* to user2@localhost;

Grant Permissions

  • ALL – Allow complete access to a specific database. If a database is not specified, then allow complete access to the entirety of MySQL.
  • CREATE – Allow a user to create databases and tables.
  • DELETE – Allow a user to delete rows from a table.
  • DROP – Allow a user to drop databases and tables.
  • GRANT OPTION – Allow a user to grant or remove another user’s privileges.
  • INSERT – Allow a user to insert rows from a table.
  • SELECT – Allow a user to select data from a database.
  • SHOW DATABASES- Allow a user to view a list of all databases.
  • UPDATE – Allow a user to update rows in a table.

Packages

mariadb          Provides MariaDB client programs and a configuration file
mariadb-server   Contains MariaDB server, tools, and configuration and logfiles
mariadb-libs     Comprises of essential library files for MariaDB client programs

The MariaDB server package also loads the mysql daemon binary file . This daeom process listens on port 3306 and supports both TCP and UDP protocols for operation.. It must run on the system to allow client access.

MariaDB Commands

mysql                        Command line shell interface for administration and query.
mysql_secure_installation    Improves the security of MariaDB installation.
mysqldump                    Backs up or restores one or more tables or database.

Maria DB Configuration Files

/etc/my.cnf        Global defaults. Primary configuration file
/etc/my.cnf.d/     Directory for configuration files.
/etc/my.cnf.d/client.cnf
/etc/my.cnf.d/mysql-clients.cnf
/etc/my.cnf.d/server.cnf
/var/log/mariadb/mariadb.log

SELinux Requirements for MariaDB Operation

By default the mysqld daemon runs confined in its own domain with domain-type mysqld_t.

ps -eZ|grep mysqld    --> system_u:system_r:mysqld_t:s0    5245 ?        00:06:00 mysqld

The SELinux filetype associated with the mysqld daemon file is mysql_exec_t, configuration files in the /etc/my.cnf.d directory is etc_t, database files in the /var/lib/mysql directory is mysqld_db_t and logfiles in /var/log/mariadb is mysql_log_t.

ll -dZ /usr/libexec/mysqld /etc/my.cnf.d /var/lib/mysql    /var/log/mariadb
drwxr-xr-x. root  root  system_u:object_r:mysqld_etc_t:s0  /etc/my.cnf.d
-rwxr-xr-x. root  root  system_u:object_r:mysqld_exec_t:s0 /usr/libexec/mysqld
drwxr-xr-x. mysql mysql system_u:object_r:mysqld_db_t:s0   /var/lib/mysql
drwxr-x---. mysql mysql system_u:object_r:mysqld_log_t:s0  /var/log/mariadb
semanage port -l|grep mysql
mysqld_port_t                  tcp      1186, 3306, 63132-63164
getsebool -a|grep mysql
mysql_connect_any --> off
selinuxuser_mysql_connect_enabled --> off

Install MariaDB

yum install mariadb-server
systemctl enable mariadb
mysql_secure_installation
firewall-cmd --permanent --add-service mysql;firewall-cmd --reload
systemctl start mariadb

Start the MariaDB Shell and Understand its Usage

mysql -u root -p       Start the MariaDB shell
help
status

Subcommands for Database and Table Operations

create, drop, show
delete, describe
insert, rename, select , update
show databases;
create database database;
use database;
create table scientists(Sno int,FirstName varchar(20), LastName varchar(20), City varchar(20),Country varchar(20),Age int);
describe scientists;
insert into scientists values('1','Albert','Einstein','Ulm','Germany','76');
select * from scientists where FirstName='Albert';
select * from scientists where Age>77;
select * from scientists where Country='Poland' or Country='Germany';
select * from scientists order by FirstName;
select * from scientists order by LastName desc;
select * from scientists where Contry like 'U%'; where Age like '7%';
rename table scientists to science;
update science set FirstName='Benjamin',LastName='Franklin' where Sno='1';
delete from science where Sno='1' or Sno='7';

Backing Up and Restoring a Database or Table

mysqldump -u root -p --all-databases  >db.all.sql        Backup all.
mysqldump -u root -p rhce1            >db.rhce1.sql      Backup specific database.
mysql: create database rhce1                             Create database to be restored (if it does not exists).
mysql     -u root -p rhce1            <db.all.sql        Restore specific database.
mysqldump -u root -p DB1 tbl1 tbl2    >db.tbl12.sql      Backup specific tables.
mysql     -u root -p DB1 tbl1         <db.tbl12.sql      Restore specific table.