Debian exercises

From Training Material
Jump to navigation Jump to search


Debian Exercises

Debian Training Materials

(for 5 days debian course)


Lukasz Sokolowski at nobleprog.com


Shell scripting

  • Unix/Linux shell scripting
    • Bash scripting

Bash programming

UNIX/Linux_Shell_Scripting


Good Password

Honestly, ideally if we never ever WRITE our passwords anywhere, like 100% nowhere.

There is a good way to easly invent and remember passwords.

I've learned it from unix/linux fathers and gurus (-;


THE WAY

  1. Make a short story
    • Spontaneously, not too much braining
    • "Green honey boils with melody."
  2. Choose a pattern
    • Take the 3rd character from each word in my story
    • "enitl"
  3. Decide about capitals
    • Big will be 2 letters, and from even words in my story, starting from the left
    • "eNiTl"
  4. Add numbers
    • Put 3 digits before the odd words from the story
      • number of words in the whole story (5), number of big letters in the password so far (2), the length of the last word in the story (6)
    • "5eN2iT6l"
  5. Special chairs
    • Take 2 specials, let's say 'dot' and 'coma'
      • Wrap the passwd with them
    • ".5eN2iT6l,"
  6. Done! (=
    • Safe password, difficult to crack
    • Easy to remember - memorize the story and the key
    • Or even write the story somewhere and remember only the key

Exercise

Invent your own story and the key - change the password for your main user (not root).

Sudo

  • Configuring and playing with sudo
ls /root
sudo ls /root
# How can we solve it?


# 1sol
su
cd /etc/sudoers.d
touch user_name

user_name ALL=(ALL) ALL

chmod 440 /etc/sudoers.d/user_name
# chmod 400 /etc/sudoers.d/user_name

# To simplify our work, make no need to provide full paths:
exit
nano .bashrc
PATH=$PATH:/usr/sbin:/sbin

Exercise 0

Configure it in 2 'other' ways


Related files, variables, etc

sudo find /etc/ -name "*sudo*"
whereis sudo
man 5 sudo.conf
sudo find / -name "*sudo.conf*"

Exercises

Exercise 1

Get a file listing of an unreadable directory


Exercise 2

List the home directory of user 'steve' on a machine where the file system holding '~steve' is not exported as root


Exercise 3

  • Edit the 'index.html' file as user 'www'
    • Get 'drupal8' from 'bitnami.com', install it and edit it's main index file (=


Exercise 4

View system logs only accessible to root and users in the 'adm' group


Exercise 5

Run an editor as 'rob' with a different primary group (use group 'video')

File system

FSH

Exercise 1

  • Calculate the overall size of each of your system’s top-level directories

Exercise 2

  • Make a file with usage listing of the directories in the '/home' partition
    • Run the commands in a sub-shell to make the 'cd' and 'file redirection' work

Exercise 3

  • As root, cd into /proc and do a directory listing
    • View these files: cpuinfo, meminfo, mounts, swaps, version, partitions, interrupts
    • Look at one of process directories

Packages and GUI

Exercise 1

  • Install mate gui
    • re-login into mate envy
  • Remove completely cinnamon gui
    • make sure the system will still work and that you will be able to login into mate
  • Install vbox guest additions
    • Fix the issue with resizing the window (=

Exercise 2

dpkg

  • Find out what package the file '/etc/logrotate.conf' belongs to
  • List information about the package including all the files it contains
  • Verify the package installation
  • Try to remove the package

Exercise 3

apt

  • List all installed kernel-related packages, and list all installed or available ones
  • Find the dependencies for the bash package
  • Search for metapackages and install one

Turning off and restarting

  • Shutdown, halt, reboot
ls -F /etc/default
less /etc/default/useradd
ls -a /etc/skel
less /etc/skel/.bash_logout

shutdown now
reboot
halt
poweroff

sudo shutdown -h +1 "Power failure"
sudo shutdown -h now
sudo shutdown -r now

Exercises

  1. Reboot the system using shutdown, reboot
  2. Power off the system using shutdown, poweroff


Bootloader

  • GRand Unified Bootloader
  • Alternatives
    • ELILO (EFI systems), IA64 (Itanium), Das U-BOOT (embedded)

Exercise

  • Boot into non-graphical mode
    • Use GRUB
  • Bring it up to graphical mode


Init

init, SysVinit, Systemd, services

# Related files
/etc/hostname
/etc/sysctl.d/*.conf
/etc/os-release
/etc/systemd
/etc/init.d/
/etc/default/
/etc/rcS    ## replace 'S' with a number from '0-6' range

Exercise 1

  • Create a simple startup service (SysVinit way)
    • Make file /etc/init.d/my_service with below content
    • Fix the script (=
      • Look at the files in '/etc/init.d/' and '/etc/default/'
    • Extend this script with restart option
#!/bin/bash
# my_service
# Example of service
#
# chkconfig: 35 69 31
# description: My service.
#
# Source function library (if there is any needed)
# RHEL systems:
# . /etc/sysconfig/my_service
# Debian systems:
. /etc/default/my_service
case "$1" in
  start)
    echo "Running my_service in start mode..."
    touch /var/lock/subsys/my_service
    echo "$0 start at $(date)" >> /var/log/my_service.log
    if [ ${VAR1} = "true" ]
    then
      echo "VAR1 set to true" >> /var/log/my_service.log
    fi
    echo
  ;;
  stop)
    echo "Running the my_service script in stop mode..."
    echo "$0 stop at $(date)" >> /var/log/my_service.log
    if [ ${VAR2} = "true" ]
    then
      echo "VAR2 = true" >> /var/log/my_service.log
    fi
    rm -f /var/lock/subsys/my_service
    echo
  ;;
  *)
    echo "Usage: my_service {start | stop}"
    exit 1
esac
exit 0
# Later use the update-rc.d

Exercise 2

  • Create another startup service (systemd way)
    • Make file /etc/systemd/system/my2nd_service.service
      • Look at the files in '/etc/systemd/system/'
    • Create simple apache error logger and run it via this startup service
  • Make sure it will be loaded when the system starts

Kernel

Kernel services and modules

Exercise 1

sysctl

  • Ping your own system
  • Look at 'net.ipv4.icmp_echo_ignore_all'
    • set the value to 1 using the sysctl
    • check ping again
    • set it back and ping
  • Change 'net.ipv4.icmp_echo_ignore_all' by modifying '/etc/sysctl.conf'
    • activate this setting file without a reboot
    • check that this worked properly
    • restore original content of '/etc/sysctl.conf'

Exercise 2

  • Maximum process ID
    • Get the current maximum PID value
    • Look at currently used PIDs
    • Reset 'pid_max' to a lower value
    • Start a new process and see what it gets as a PID

Exercise 3

  • List all currently loaded kernel modules on your system
  • Load a currently unloaded module on your system
    • Check if it works
  • Remove the loaded module from your system
    • Check it again

Processes

Processes

Exercise 1

Controlling Processes with ulimit

  • Please do: '$ help ulimit' and read '/etc/security/limits.conf' before doing the following steps.
  • Start a new shell by typing bash (or opening a new terminal) so that your changes are only effective in the new shell.
    • View the current limit on the number of open files and explicitly view the hard and soft limits.
  • Set the limit to the hard limit value and verify if it worked.
  • Set the hard limit to 2048 and verify it worked.
  • Try to set the limit back to the previous value. Did it work?

Monitoring the system

System monitoring


Using stress

Stress is a C language program designed to place a configurable amount of stress by generating various kinds of workloads on the system.

$ stress -c 8 -i 4 -m 6 -t 20s

will:
- Fork off 8 CPU-intensive processes, each spinning on a sqrt() calculation.
- Fork off 4 I/O-intensive processes, each spinning on sync() 
- Fork off 6 memory-intensive processes, each spinning on malloc() , allocating 256 MB by default. The size can be changed as in --vm-bytes 128M .
- Run the stress test for 20 seconds


Exercise

- Start up your system’s graphical system monitor, which you can find on your application menu.
- Now begin to put stress on the system. 
--- The exact numbers you use will depend on your system’s resources, such as the number of CPU’s and RAM size.
- For example, doing  '$ stress -m 4 -t 20s'  puts only a memory stressor on the system.

Monitoring I/O

Monitoring, tuning and scheduling I/O

bonnie++, fs_mark, etc

bonnie++ is a widely available benchmarking program that tests and measures the performance of drives and filesystems. 

Results can be read from the terminal window or directed to a file, and also to a csv format (comma separated value). 
Companion programs, bon csv2html and bon csv2txt, can be used convert to html and plain text output formats.

A quick test can be obtained with a command like:
$ time sudo bonnie++ -n 0 -u 0 -r 100 -f -b -d /mnt

where:
 -n 0 means don’t perform the file creation tests.
 -u 0 means run as root.
 -r 100 means pretend you have 100 MB of RAM.
 -f means skip per character I/O tests.
 -b means do a fsync after every write, which forces flushing to disk rather than just writing to cache.
 -d /mnt just specifies the directory to place the temporary file created; make sure it has enough space, in this case 300 MB, available.

On an Ubuntu system, running as a virtual machine under hypervisor on the same physical machine:
$ time sudo bonnie++ -n 0 -u 0 -r 100 -f -b -d /mnt

Using uid:0, gid:0.
Writing intelligently...done
Rewriting...done
Reading intelligently...done
start ’em...done...done...done...done...done...
Version 1.97 ------Sequential Output------ --Sequential Input- --Random-
Concurrency 1 -Per Chr- --Block-- -Rewrite- -Per Chr- --Block-- --Seeks--
Machine Size K/sec %CP K/sec %CP K/sec %CP K/sec %CP K/sec %CP /sec %CP
ubuntu 300M 70000 61 43274 31 470061 96 2554 91
Latency 306ms 201ms 9276us 770ms
1.97,1.97,ubuntu,1,1415983257,300M,,,,70000,61,43274,31,,,470061,96,2554,91,,,,,,,,,,,,,,,,,,,306ms,201ms,,9276us,770ms,,,,,,

You can clearly see the drop in performance.

Assuming you have saved the previous outputs as a file called bonnie++.out , you can convert the output to html:
$ bon_csv2html < bonnie++.out > bonnie++.html

or to plain text with:

$ bon_csv2txt < bonnie++.out > bonnie++.txt

Scheduling

Comparing I/O Schedulers

  • Create a script to compare I/O schedulers
    #!/bin/bash
    NMAX=8
    NMEGS=100
    [[ -n $1 ]] && NMAX=$1
    [[ -n $2 ]] && NMEGS=$2
    echo Doing: $NMAX parallel read/writes on: $NMEGS MB size files
    TIMEFORMAT="%R %U %S"
    ##############################################################
    # simple test of parallel reads
    do_read_test(){
      for n in $(seq 1 $NMAX) ; do
        cat file$n > /dev/null &
      done
      # wait for previous jobs to finish
      wait
    }
    
    # simple test of parallel writes
    do_write_test(){
      for n in $(seq 1 $NMAX) ; do
        [[ -f fileout$n ]] && rm -f fileout$n
        (cp file1 fileout$n && sync) &
      done
      # wait for previous jobs to finish
      wait
    }
    
    # create some files for reading, ok if they are the same
    create_input_files(){
      [[ -f file1 ]] || dd if=/dev/urandom of=file1 bs=1M count=$NMEGS
      for n in $(seq 1 $NMAX) ; do
        [[ -f file$n ]] || cp file1 file$n
      done
    }
    
    echo -e "\ncreating as needed random input files"
    create_input_files
    
    ##############################################################
    # begin the actual work
    # do parallel read test
    echo -e "\ndoing timings of parallel reads\n"
    echo -e " REAL USER SYS\n"
    for iosched in noop deadline cfq ; do
      echo testing IOSCHED = $iosched
      echo $iosched > /sys/block/sda/queue/scheduler
      cat /sys/block/sda/queue/scheduler
    # echo -e "\nclearing the memory caches\n"
      echo 3 > /proc/sys/vm/drop_caches
      time do_read_test
    done
    ##############################################################
    # do parallel write test
    echo -e "\ndoing timings of parallel writes\n"
    echo -e " REAL USER SYS\n"
    for iosched in noop deadline cfq ; do
      echo testing IOSCHED = $iosched
      echo $iosched > /sys/block/sda/queue/scheduler
      cat /sys/block/sda/queue/scheduler
      time do_write_test
    done
    ##############################################################
    
  • Make it executable
  • The script should:
    • Cycle through the available I/O schedulers on a hard disk while doing a configurable number of parallel reads and writes of files of a configurable size.
    • Test reads and writes as separate steps.
    • When testing reads make sure you’re actually reading from disk and not from cached pages of memory
      • you can flush out the cache by doing: '$ echo 3 > /proc/sys/vm/drop_caches' before doing the reads. You can cat into '/dev/null' to avoid writing to disk.
    • Make sure all reads are complete before obtaining timing information; this can be done by issuing a wait command under the shell.
    • Test writes by simply copying a file (which will be in cached memory after the first read) multiple times simultaneously.
      • To make sure you wait for all writes to complete before you get timing information you can issue a 'sync' call.
  • Script takes two arguments
    • The first is the number of simultaneous reads and writes to perform.
    • The second is the size (in MB) of each file.
  • This script must be run as root as it echoes values into the /proc and /sys directory trees.
  • Compare the results you obtain using different I/O schedulers.

Recovering and rescue

System rescue

  • Recover from a corrupted GRUB configuration
    • Spoil the grub and modify the kernel line by removing the first character of the value in the field named UUID
    • Take note of which character you removed, you will replace it in rescue mode
    • In rescue mode, agree when asked to search for filesystems.
    • If prompted, open a shell, and explore the rescue system by running utilities such as 'mount' and 'ps'
  • Recovering from Password Failure
    • chroot /mnt/sysimage
  • Recovering from Partition Table Corruption:
1. Login as root and save your MBR:

$ dd if=/dev/sda of=/root/mbrsave bs=446 count=1
1+0 records in
1+0 records out
446 bytes (446 B) copied, 0.00976759 s, 45.7 kB/s

Be careful: make sure you issue the exact command above and that the file saved has the right length:
$ sudo ls -l /root/mbrsave
-rw-r--r-- 1 root root 446 Nov 12 07:54 mbrsave

2. Now we are going to obliterate the MBR with:

$ dd if=/dev/zero of=/dev/sda bs=446 count=1
1+0 records in
1+0 records out
446 bytes (446 B) copied, 0.000124091 s, 3.6 MB/s

3. Reboot the system; it should fail.

4. Reboot into the rescue environment and restore the MBR:

$ dd if=/mnt/sysimage/root/mbrsave of=/dev/sda bs=446 count=1


5. Exit from the rescue environment and reboot. The system should boot properly now.

Devices

Devices, udev

Exercise

  • Create and implement a rule on your system that will create a symlink called myusb when a USB device is plugged in.
  • Plug in a USB device to your system. It can be a pen drive, mouse, webcam, etc.
    • Note: If you are running a virtual machine under a hypervisor, you will have to make sure the USB device is seen by the guest, which usually is just a mouse click which also disconnects it from the host.
  • Get a listing of the '/dev' directory and see if your symlink was created.
  • Remove the USB device. (If it is a drive you should always umount it first for safety.)
  • See if your symbolic link still exists in '/dev'

Partitions

Partitioning, Formatting Disks, Encrypting Disks

Using a File as a Disk Partition Image

We are going to create a file that will be used as a container for a full hard disk partition image, and for all intents and purposes can be used like a real hard partition. 

1. Create a file full of zeros 1 GB in length:
$ dd if=/dev/zero of=imagefile bs=1M count=1024

You can make a much smaller file if you like or don’t have that much available space in the partition you are creating the file on.



2. Put a filesystem on it:

$ mkfs.ext4 imagefile
mke2fs 1.42.9 (28-Dec-2013)
imagefile is not a block special device.
Proceed anyway? (y,n) y
Discarding device blocks: done
.....

Of course you can format with a different filesystem, doing mkfs.ext3, mkfs.vfat, mkfs.xfs etc.



3. Mount it somewhere:
$ mkdir mntpoint
$ sudo mount -o loop imagefile mntpoint

You can now use this to your heart’s content, putting files etc. on it.



4. When you are done unmount it with:

$ sudo umount mntpoint
An alternative method to using the loop option to mount would be:
$ sudo losetup /dev/loop2 imagefile
$ sudo mount /dev/loop2 mntpoint
....
$ sudo umount mntpoint
$ sudo losetup -d /dev/loop2

You can use /dev/loop[0-7] but you have to be careful they are not already in use.

You should note that using a loop device file instead of a real partition can be useful, but it is pretty worthless for doing any kind of
measurements or benchmarking. This is because you are placing one filesystem layer on top of another, which can only have a negative
effect on performance, and mostly you just use the behavior of the underlying filesystem the image file is created on.

Exercise 1

In this exercise we will show how to put more than one partition and have it behave as an entire disk.

Partitioning a Disk Image File
The next level of complication is to divide the container file into multiple partitions, each of which can be used to hold a filesystem, or a swap
area.


You can reuse the image file created in the previous exercise or create a new one.

1. Run fdisk on your imagefile:

$ sudo fdisk -C 130 imagefile
Device does not contain a recognized partition table
Building a new DOS disk label with disk identifier 0x6280ced3.
Welcome to fdisk (util-linux 2.23.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
Command (m for help):


The -C 130 sets the number of phony cylinders in the drive, and is only necessary in old versions of fdisk, which unfortunately you
will find on RHEL 6. However, it will do no harm on other distributions.


2. Type m to get a list of commands:

Command (m for help): m
Command action
a toggle a bootable flag
b edit bsd disklabel
c toggle the dos compatibility flag
d delete a partition
g create a new empty GPT partition table
G create an IRIX (SGI) partition table
l list known partition types
m print this menu
n add a new partition
o create a new empty DOS partition table
p print the partition table
q quit without saving changes
s create a new empty Sun disklabel
t change a partition’s system id
u change display/entry units
v verify the partition table
w write table to disk and exit
x extra functionality (experts only)
Command (m for help):


3. Create a new primary partition and make it 256 MB (or whatever size you would like:

Command (m for help): n
Partition type:
  p primary (0 primary, 0 extended, 4 free)
  e extended
Select (default p): p
Partition number (1-4, default 1): 1
First sector (2048-2097151, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-2097151, default 2097151): +256M
Partition 1 of type Linux and of size 256 MiB is set


4. Add a second primary partition also of 256 MB in size:

Command (m for help): n

Partition type:
  p primary (1 primary, 0 extended, 3 free)
  e extended
Select (default p): p
Partition number (2-4, default 2): 2
First sector (526336-2097151, default 526336):
Using default value 526336
Last sector, +sectors or +size{K,M,G} (526336-2097151, default 2097151): +256M
Partition 2 of type Linux and of size 256 MiB is set

Command (m for help): p

Disk imagefile: 1073 MB, 1073741824 bytes, 2097152 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x6280ced3
Device Boot Start End Blocks Id System
imagefile1 2048 526335 262144 83 Linux
imagefile2 526336 1050623 262144 83 Linux



5. Write the partition table to disk and exit:
Command (m for help): w
The partition table has been altered!
Syncing disks.

While this has given us some good practice, we haven’t yet seen a way to use the two partitions we just created.
We’ll start over in the next exercise with a method that lets us do so.

Exercise 2

Using losetup and parted

We are going to experiment more with:
* Loop devices and losetup
* parted to partition at the command line non-interactively.

You should read the man pages for 'losetup' and 'parted' before doing the following procedures.

Once again, you can reuse the image file or, better still, zero it out and start freshly or with another file.

1. Associate the image file with a loop device:

$ sudo losetup -f
/dev/loop1

$ sudo losetup /dev/loop1 imagefile

where the first command finds the first free loop device. The reason to do this is you may already be using one or more loop devices.
For example, on the system that this is being written on, before the above command is executed:

$ losetup -a
/dev/loop0: []: (/usr/src/KERNELS.sqfs)

a squashfs compressed, read-only filesystem is already mounted using /dev/loop0 . (The output of this command will vary with
distribution.) If we were to ignore this and use losetup on /dev/loop0 we would almost definitely corrupt the file.



2. Create a disk partition label on the loop device (image file):

$ sudo parted -s /dev/loop1 mklabel msdos



3. Create three primary partitions on the loop device:

$ sudo parted -s /dev/loop1 unit MB mkpart primary ext4 0 256
$ sudo parted -s /dev/loop1 unit MB mkpart primary ext4 256 512
$ sudo parted -s /dev/loop1 unit MB mkpart primary ext4 512 1024



4. Check the partition table:

$ fdisk -l /dev/loop1
Disk /dev/loop1: 1073 MB, 1073741824 bytes, 2097152 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x00050c11
Device Boot Start End Blocks Id System
/dev/loop1p1 1 500000 250000 83 Linux
/dev/loop1p2 500001 1000000 250000 83 Linux
/dev/loop1p3 1000001 2000000 500000 83 Linux



5. What happens next depends on what distribution you are on.
For example, on RHEL 7 and Ubuntu 16.04 you will find new device nodes have been created:

$ ls -l /dev/loop1*
brw-rw---- 1 root disk 7, 1 Oct 7 14:54 /dev/loop1
brw-rw---- 1 root disk 259, 0 Oct 7 14:54 /dev/loop1p1
brw-rw---- 1 root disk 259, 3 Oct 7 14:54 /dev/loop1p2
brw-rw---- 1 root disk 259, 4 Oct 7 14:54 /dev/loop1p3
and we will use them in the following.



6. Put filesystems on the partitions:

$ sudo mkfs.ext3 /dev/loop1p1
$ sudo mkfs.ext4 /dev/loop1p2
$ sudo mkfs.vfat /dev/loop1p3



7. Mount all three filesystems and show they are available:

$ mkdir mnt1 mnt2 mnt3
$ sudo mount /dev/loop1p1 mnt1
$ sudo mount /dev/loop1p2 mnt2
$ sudo mount /dev/loop1p3 mnt3
$ df -Th
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda1 ext4 29G 8.5G 19G 32% /
....
/dev/loop1p1 ext3 233M 2.1M 219M 1% mnt1
/dev/loop1p2 ext4 233M 2.1M 215M 1% mnt2
/dev/loop1p3 vfat 489M 0 489M 0% mnt3



8. After using the filesystems to your heart’s content you can unwind it all:

$ sudo umount mnt1 mnt2 mnt3
$ rmdir mnt1 mnt2 mnt3
$ sudo losetup -d /dev/loop0

Exercise 3

Disk Encryption

  • In this exercise, you will encrypt a partition on the disk in order to provide a measure of security in the event that the hard drive or laptop is stolen.
  • Reviewing the cryptsetup documentation first would be a good idea ( man cryptsetup and cryptsetup --help ).
    • Create a new partition for the encrypted block device with fdisk. Make sure the kernel is aware of the new partition table. A reboot will do this but there are other methods.
    • Format the partition with cryptsetup using LUKS for the crypto layer.
    • Create the un-encrypted pass through device by opening the encrypted block device, i.e., secret-disk .
    • Add an entry to /etc/crypttab so that the system prompts for the passphrase on reboot.
    • Format the filesystem as an ext4 filesystem.
    • Create a mount point for the new filesystem, i.e. /secret .
    • Add an entry to /etc/fstab so that the filesystem is mounted on boot.
    • Try and mount the encrypted filesystem.
    • Validate the entire configuration by rebooting.


Exercise 4

Encrypted Swap

In this exercise, we will be encrypting the swap partition. Data written to the swap device can contain sensitive information.
Because swap is backed by an actual partition, it is important to consider the security implications of having an unencrypted swap partition.
The process for encrypting is similar to the previous exercise, except we will not create a file system on the encrypted block device.
In this case, we are also going to use the existing swap device by first de-activating it and then formatting it for use as an encrypted swap device.

It would be a little bit safer to use a fresh partition below, or you can safely reuse the encrypted partition you set up in the previous exercise.
At the end we explain what to do if you have problems restoring.

You may want to revert back to the original unencrypted partition when we are done by just running 'mkswap' on it again when it is not being
used.

1. Find out what partition you are currently using for swap and then deactivate it:

$ cat /proc/swaps
Filename Type Size Used Priority
/dev/sda11 partition 4193776 0 -1

$ sudo swapoff /dev/sda11



2. Do the same steps as in the previous exercise to set up encryption:

$ sudo cryptsetup luksFormat /dev/sda11 # may use --cipher aes option
$ sudo cryptsetup luksOpen /dev/sda11 swapcrypt



3. Format the encrypted device to use with swap:

$ sudo mkswap /dev/mapper/swapcrypt



4. Now test to see if it actually works by activating it:

$ sudo swapon /dev/mapper/swapcrypt
$ cat /proc/swaps



5. To ensure the encrypted swap partition can be activated at boot you need to do two things:

(a) Add a line to /etc/crypttab so that the system prompts for the passphrase on reboot:
swapcrypt /dev/sda11 /dev/urandom swap,cipher=aes-cbc-essiv:sha256,size=256

(Note /dev/urandom is preferred over /dev/random for reasons involving potential entropy shortages as discussed in the
man page for crypttab .) 
You don’t need the detailed options that follow, but it's a good example of what more you can do.

(b) Add an entry to the /etc/fstab file so that the swap device is activated on boot
/dev/mapper/swapcrypt none swap defaults 0 0



6. You can validate the entire configuration by rebooting.

To restore your original unencrypted partition:
$ sudo swapoff /dev/mapper/swapcrypt
$ sudo cyyptsetup luksClose swapcrypt
$ sudo mkswap /dev/sda11
$ sudo swapon -a

If the swapon command fails it is likely because '/etc/fstab' no longer properly describes the swap partition.
If this partition is described in there by actual device node ( /dev/sda11 ) there won’t be a problem.
You can fix either by changing the line in there to be:

/dev/sda11 swap swap defaults 0 0

or by giving a label when formatting and using it as in:

$ sudo mkswap -L SWAP /dev/sda11

and then putting in the file:

LABEL=SWAP swap swap defaults 0 0

Swap and Quotas

Swap, Quotas, Usage

Exercise 1

Managing Swap Space

Examine your current swap space by doing:

$ cat /proc/swaps

Filename Type Size Used Priority
/dev/sda11 partition 4193776 0 -1

We will now add more swap space by adding either a new partition or a file. To use a file we can do:

$ dd if=/dev/zero of=swpfile bs=1M count=1024

1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 1.30576 s, 822 MB/s

$ mkswap swpfile

Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=85bb62e5-84b0-4fdd-848b-4f8a289f0c4c

(For a real partition just feed mkswap the partition name, but be aware all data on it will be erased!)

Activate the new swap space:
$ sudo swapon swpfile

swapon: /tmp/swpfile: insecure permissions 0664, 0600 suggested.
swapon: /tmp/swpfile: insecure file owner 500, 0 (root) suggested.

Notice RHEL 7 warns us we are being insecure, we really should fix with:

$ sudo chown root:root swpfile
$ sudo chmod 600 swpfile

and ensure it is being used:
$ cat /proc/swaps

Filename Type Size Used Priority
/dev/sda11 partition 4193776 0 -1
/tmp/swpfile file 1048572 0 -2

Note the Priority field; swap partitions or files of lower priority will not be used until higher priority ones are filled.

Remove the swap file from use and delete it to save space:

$ sudo swapoff swpfile
$ sudo rm swpfile

Exercise 2

Filesystem Quotas

  • Change the entry in '/etc/fstab' for your new filesystem to use user quotas (change noexec to usrquota in the entry for /mnt/tempdir )
    • Then remount the filesystem.
  • Initialize quotas on the new filesystem
    • and then turn the quota checking system on
  • Now set some quota limits for the normal user account:
    • a soft limit of 500 blocks
    • and a hard limit of 1000 blocks.
  • As the normal user, attempt to use dd to create some files to exceed the quota limits.
    • Create bigfile1 (200 blocks) and bigfile2 (400 blocks).
    • You should get a warning. Why?
  • Create bigfile3 (600 blocks).
    • You should get an error message. Why? Look closely at the file sizes.
  • Eliminate the persistent mount line you inserted in /etc/fstab

PAM

PAM Configuration

Deny login access after a certain number of failed attempts

  • This is done with the pam tally2 module. In this exercise we are going to deny login through ssh after three failed login attempts.
    • Edit '/etc/pam.d/sshd' and configure it to deny login after three failed attempts
      • Hint: add the following two lines to the file:
         auth required pam_tally2.so deny=3 onerr=fail
         account required pam_tally2.so
        
    • Try to login three times as a particular user (who has an account) while mistyping the password.
    • Try to login as the same user with the correct password.
    • Check to see how many failed logins there are for the user.
    • Reset the failed login counter.
    • Check again to see how many failed logins there are.
    • Try to login again with the correct password.

Logical Volumes and RAID

LVM, RAID

Exercise 1

Logical Volumes


We are going to create a logical volume using two 250 MB partitions. We are going to assume you have real partitionable disk space available.

  • Create two 250 MB partitions of type logical volume ( 8e ).
  • Convert the partitions to physical volumes.
  • Create a volume group named 'myvg' and add the two physical volumes to it. Use the default extent size.
  • Allocate a 300 MB logical volume named 'mylvm' from volume group 'myvg'.
  • Format and mount the logical volume 'mylvm' at '/mylvm'
  • Use lvdisplay to view information about the logical volume.
  • Grow the logical volume and corresponding filesystem to 350 MB.

Example of solution

1. Execute:

$ sudo fdisk /dev/sda

using whatever hard disk is appropriate, and create the two partitions. 
While in fdisk, typing t will let you set the partition type to '8e' .
While it doesn’t matter if you don’t set the type, it is a good idea to lessen confusion.
Use w to rewrite the partition table and exit, and then

$ sudo partprobe -s

or reboot to make sure the new partitions take effect.


2. Assuming the new partitions are /dev/sdaX and /dev/sdaY :

$ sudo pvcreate /dev/sdaX
$ sudo pvcreate /dev/sdaY
$ sudo pvdisplay


3. $ sudo vgcreate myvg /dev/sdaX /dev/sdaY
$ sudo vgdisplay


4. $ sudo lvcreate -L 300M -n mylvm myvg
$ sudo lvdisplay


5. $ sudo mkfs.ext4 /dev/myvg/mylvm
$ mkdir /mylvm
$ sudo mount /dev/myvg/mylvm /mylvm

If you want the mount to be persistent, edit /etc/fstab to include the line:

/dev/myvg/mylvm /mylvm ext4 defaults 0 0


6. $ sudo lvdisplay


7. $ df -h
$ sudo lvextend -L 350M /dev/myvg/mylvm
$ sudo resize2fs /dev/myvg/mylvm
$ df -h

or

$ sudo lvextend -r -L +50M /dev/myvg/mylvm

Exercise 2

Creating a RAID Device


The process will be the same whether the partitions are on one drive or several (Although there is obviously little reason to actually create a RAID on a single device).

  • Create two 200 MB partitions of type raid ( fd ) either on your hard disk using 'fdisk', or using LVM.
  • Create a RAID 1 device named '/dev/md0' using the two partitions.
  • Format the RAID device as an 'ext4' filesystem. Then mount it at '/myraid' and make the mount persistent.
  • Place the information about '/dev/md0' in '/etc/mdadm.conf' file using 'mdadm'.
    • (Depending on your distribution, this file may not previously exist.)
  • Examine '/proc/mdstat' to see the status of your RAID device

Networking

Exercise 1

Static Configuration of a Network Interface

  • Show your current IP address, default route and DNS settings for eth0(might be a different name)
    • Keep a copy of them for resetting later
  • Bring down eth0 and reconfigure to use a static address instead of DHCP
    • use the information you just recorded
  • Bring the interface back up
    • configure the nameserver resolver with the information that you noted before
    • Verify your hostname and then ping it.
  • Make sure your configuration works after a reboot
  • Restore the previous configuration

Exercise 2

Adding a Static Hostname

  • In this exercise we will add entries to the local host database.
    • Open /etc/hosts and add an entry for mysystem.mydomain that will point to the IP address associated with your network card.
    • Add a second entry that will make all references to ad.doubleclick.net point to 127.0.0.1 .
    • As an optional exercise, download the host file from: http://winhelp2002.mvps.org/hosts2.htm or more directly from http://winhelp2002.mvps.org/hosts.txt , and install it on your system.
      • Do you notice any difference using your browser with and without the new host file in place?

Exercise 3

Adding a Network Interface Alias/Address using nmcli

We are going to add an additional IPv4 address to your system and make it persistent.

We will do this without editing files under /dev directly, using nmcli.

1. First obtain your current internet address and interface name:

$ sudo nmcli con

NAME UUID TYPE DEVICE
Auto Ethernet 1c46bf37-2e4c-460d-8b20-421540f7d0e2 802-3-ethernet ens33
virbr0 a84a332f-38e3-445a-a377-4363a8eb963f bridge virbr0

shows the name of the connection is Auto Ethernet .

$ sudo nmcli con show "Auto Ethernet" | grep IP4.ADDRESS
IP4.ADDRESS[1]: 172.16.2.135/24

shows the address as 172.16.2.135 Note that this command shows all information about the connection and you could have
specified the UUID instead of the NAME as in:

$ nmcli con show 1c46bf37-2e4c-460d-8b20-421540f7d0e2



2. Add a new address that your machine can be seen by:

$ sudo nmcli con modify "Auto Ethernet" +ipv4.addresses 172.16.2.140/24



3. Activate it and test to see if it is there:

$ sudo nmcli con up "Auto Ethernet"

Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/6)

$ ping -c 3 172.16.2.140
PING 172.16.2.140 (172.16.2.140) 56(84) bytes of data.
64 bytes from 172.16.2.140: icmp_seq=1 ttl=64 time=0.038 ms
64 bytes from 172.16.2.140: icmp_seq=2 ttl=64 time=0.034 ms
64 bytes from 172.16.2.140: icmp_seq=3 ttl=64 time=0.032 ms

--- 172.16.2.140 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.032/0.034/0.038/0.007 ms



4. Clean up by removing the alias:

$ sudo nmcli con modify "Auto Ethernet" -ipv4.addresses 172.16.2.140/24
...
$ sudo nmcli con up "Auto Ethernet"
...

Exercise 4

Adding a Static Route using nmcli

We are going to add a static IPv4 route address to your system and make it persistent.
We will do this without editing files under '/dev' directly, using 'nmcli'.

1. Begin by examining your current routing tables, using both route and ip:

$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.16.2.2 0.0.0.0 UG 100 0 0 ens33
link-local * 255.255.0.0 U 1000 0 0 ens33
172.16.2.0 * 255.255.255.0 U 100 0 0 ens33
192.168.122.0 * 255.255.255.0 U 0 0 0 virbr0

$ ip route
default via 172.16.2.2 dev ens33 proto static metric 100
169.254.0.0/16 dev ens33 scope link metric 1000
172.16.2.0/24 dev ens33 proto kernel scope link src 172.16.2.135 metric 100
192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1 linkdown



2. Add a new route using nmcli:

$ sudo nmcli conn mod "Auto Ethernet" +ipv4.routes "192.168.100.0/24 172.16.2.1"



3. Note it has not yet taken effect:

$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.16.2.2 0.0.0.0 UG 100 0 0 ens33
link-local * 255.255.0.0 U 1000 0 0 ens33
172.16.2.0 * 255.255.255.0 U 100 0 0 ens33
192.168.122.0 * 255.255.255.0 U 0 0 0 virbr0



4. Reload the interface to have it take effect and show it has:
$ sudo nmcli conn up "Auto Ethernet"
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/25)
$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.16.2.2 0.0.0.0 UG 100 0 0 ens33
link-local * 255.255.0.0 U 1000 0 0 ens33
172.16.2.0 * 255.255.255.0 U 100 0 0 ens33
192.168.100.0 172.16.2.1 255.255.255.0 UG 100 0 0 ens33
192.168.122.0 * 255.255.255.0 U 0 0 0 virbr0



5. Reboot and verify the route has taken effect (i.e., it is persistent: If so remove it:

$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.16.2.2 0.0.0.0 UG 100 0 0 ens33
link-local * 255.255.0.0 U 1000 0 0 ens33
172.16.2.0 * 255.255.255.0 U 100 0 0 ens33
192.168.100.0 172.16.2.1 255.255.255.0 UG 100 0 0 ens33
192.168.122.0 * 255.255.255.0 U 0 0 0 virbr0

$ sudo nmcli conn mod "Auto Ethernet" -ipv4.routes "192.168.100.0/24 172.16.2.1"

$ sudo nmcli conn up "Auto Ethernet"
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/3)

$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.16.2.2 0.0.0.0 UG 100 0 0 ens33
link-local * 255.255.0.0 U 1000 0 0 ens33
172.16.2.0 * 255.255.255.0 U 100 0 0 ens33
192.168.122.0 * 255.255.255.0 U 0 0 0 virbr0



6. Note you can set a route with either route or ip from the command line but it won’t survive a reboot as in:

$ sudo ip route add 192.168.100.0/24 via 172.16.2.1

$ sudo route
....

You can verify that a route established this way is not persistent.

Firewall

Firewall

sudo apt update
sudo apt -y install firewalld
$ firewall-cmd --help

Exercise

Adding Services to a Zone

  • Add the http and https services to the public zone and verify that they are currently listed.

LDAP

OpenLDAP Workshop

OpenLDAP Docs

Simple setup

apt install slapd ldap-utils

dpkg-reconfigure slapd

ldapsearch -x -b dc=mniam,dc=com

# extended LDIF
#
# LDAPv3
# base <dc=mniam,dc=com> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#

# mniam.com
dn: dc=mniam,dc=com
objectClass: top
objectClass: dcObject
objectClass: organization
o: mniam ltd
dc: mniam

# admin, mniam.com
dn: cn=admin,dc=mniam,dc=com
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
description: LDAP administrator

# search result
search: 2
result: 0 Success

# numResponses: 3
# numEntries: 2

Filling in the Directory

Simple GUI example

apt install migrationtools jxplorer

nano /etc/migrationtools/migrate_common.ph

## enable
# IGNORE_UID_BELOW
# IGNORE_GID_BELOW 
#
## update
# DEFAULT_MAIL_DOMAIN
# DEFAULT_BASE 
#
# cd /usr/share/migrationtools
# LDAPADD="/usr/bin/ldapadd -c";
# ETC_ALIASES=/dev/null; 
# export PERL5LIB=$PERL5LIB:/usr/share/migrationtools;
# ./migrate_all_online.sh
#

### Question                  Answer
#
# X.500 naming context        dc=mniam,dc=com
# LDAP server hostname        localhost
# Manager DN                  cn=admin,dc=mniam,dc=com
# Bind credentials            the administrative password
# Create DUAConfigProfile     no

# to add also '/etc/aliases', extend standard schema with '/etc/ldap/schema/misc.schema'

PAM

apt install libpam-ldap

### Question                                              Answer
#
# LDAP server Uniform Resource Identifier                 ldap://ldap.mniam.com
# Distinguished name of the search base                   dc=mniam,dc=com
# LDAP version to use                                     3
# Allow LDAP admin account to behave like local root?     yes
## This allows using the usual passwd command for changing passwords stored in the LDAP database.
# Does the LDAP database require logging in?              no
# LDAP account for root                                   cn=admin,dc=mniam,dc=com
# LDAP root account password                              the LDAP database administrative password

Securing LDAP

Uses clear text by default, so extra encryption layer is recommended.

Server part

  • Create a key pair (comprising a public key and a private key) for the LDAP server
    • use 'openssl' to generate it (https://jamielinux.com/docs/openssl-certificate-authority/)
      • "common name" - must be the fully-qualified hostname for the LDAP server('ldap.mniam.com')
        mkdir keys; cd keys
        openssl genrsa -des3 -out ca.key 1024
        openssl req -new -x509 -days 3650 -key ca.key -out ca.crt
        openssl x509 -inform PEM -in ca.crt > public.pem
        
      • certificate goes 'keys/ca.crt'
      • private key goes 'keys/ca.key'
    • install keys in their standard location
      • make sure the private file is readable by the LDAP server which runs under the 'openldap' user identity:
        # adduser openldap ssl-cert
        Adding user ‘openldap’ to group ‘ssl-cert’ ...
        Adding user openldap to group ssl-cert
        Done.
        # cp keys/ca.key /etc/ssl/private/ldap.mniam.com.key
        # chown root:ssl-cert /etc/ssl/private/ldap.mniam.com.key
        # chmod 0640 /etc/ssl/private/ldap.mniam.com.key
        # cp public.pem /etc/ssl/certs/ldap.mniam.com.pem
        
  • The slapd daemon also needs to be told to use these keys for encryption
    # cat >ssl.ldif <<END
    dn: cn=config
    changetype: modify
    add: olcTLSCertificateFile
    olcTLSCertificateFile: /etc/ssl/certs/ldap.mniam.com.pem
    -
    add: olcTLSCertificateKeyFile
    olcTLSCertificateKeyFile: /etc/ssl/private/ldap.mniam.com.key
    -
    END
    # ldapmodify -Y EXTERNAL -H ldapi:/// -f ssl.ldif
    SASL/EXTERNAL authentication started
    SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
    SASL SSF: 0
    modifying entry "cn=config"
    
  • Change the SLAPD_SERVICES variable in the '/etc/default/slapd' file.
    • Play it safe and disable unsecured LDAP altogether
      # Default location of the slapd.conf file or slapd.d cn=config directory. If
      # empty, use the compiled-in default (/etc/ldap/slapd.d with a fallback to
      # /etc/ldap/slapd.conf).
      SLAPD_CONF=
      # System account to run the slapd server under. If empty the server
      # will run as root.
      SLAPD_USER="openldap"
      # System group to run the slapd server under. If empty the server will
      # run in the primary group of its user.
      SLAPD_GROUP="openldap"
      # Path to the pid file of the slapd server. If not set the init.d script
      # will try to figure it out from $SLAPD_CONF (/etc/ldap/slapd.conf by
      # default)
      SLAPD_PIDFILE=
      # slapd normally serves ldap only on all TCP-ports 389. slapd can also
      # service requests on TCP-port 636 (ldaps) and requests via unix
      # sockets.
      # Example usage:
      # SLAPD_SERVICES="ldap://127.0.0.1:389/ ldaps:/// ldapi:///"
      SLAPD_SERVICES="ldaps:/// ldapi:///"
      # If SLAPD_NO_START is set, the init script will not start or restart
      # slapd (but stop will still work). Uncomment this if you are
      # starting slapd via some other means or if you don’t want slapd normally
      # started at boot.
      #SLAPD_NO_START=1
      # If SLAPD_SENTINEL_FILE is set to path to a file and that file exists,
      # the init script will not start or restart slapd (but stop will still
      # work). Use this for temporarily disabling startup of slapd (when doing
      # maintenance, for example, or through a configuration management system)
      # when you don’t want to edit a configuration file.
      SLAPD_SENTINEL_FILE=/etc/ldap/noslapd
      # For Kerberos authentication (via SASL), slapd by default uses the system
      # keytab file (/etc/krb5.keytab). To use a different keytab file,
      # uncomment this line and change the path.
      #export KRB5_KTNAME=/etc/krb5.keytab
      # Additional options to pass to slapd
      SLAPD_OPTIONS=""
      

Client part

  • Put the CA certificate in '/usr/local/share/ca-certificates' and running 'update-ca-certificates'
    # cp keys/ca.crt /usr/local/share/ca-certificates/mniam.crt
    # update-ca-certificates
    Updating certificates in /etc/ssl/certs... 1 added, 0 removed; done.
    Running hooks in /etc/ca-certificates/update.d....
    Adding debian:mniam.pem
    done.
    done.
    
  • Modify the default LDAP URI and default base DN used by the various command line tools, do it in /etc/ldap/ldap.conf
    #
    # LDAP Defaults
    #
    # See ldap.conf(5) for details
    # This file should be world readable but not world writable.
    BASE dc=mniam,dc=com
    URI ldaps://ldap.mniam.com
    #SIZELIMIT 12
    #TIMELIMIT 15
    #DEREF never
    # TLS certificates (needed for GnuTLS)
    TLS_CACERT /etc/ssl/certs/ca-certificates.crt
    

X11

  • no longer needed file: '/etc/X11/xorg.conf'
  • log file '/var/log/Xorg.0.log'
  • keyboard '/etc/default/keyboard'
  • drivers
    • required packages in the non-free section
      • nvidia-glx for nVidia cards
      • fglrx-driver for some ATI cards
    • Both cases require matching kernel modules
    • Building these modules can be automated by installing
      • nvidia-kernel-dkms (for nVidia)
      • fglrx-modules-dkms (for ATI)
    • The free driver for ATI video cards "radeon" is much better
      • although it often requires a non-free firmware
  • display manager - gdm, kdm, lightdm
  • window manager - mutter, kwin, xfwm
  • desktop - gnome, kde, xfce, mate, etc
  • https://wiki.debian.org/Xorg#Configure_X

Exercise

1.
You will need to have X11 installed. This was likely already done by your distribution's installer. 
If you do not have it installed, you can build it from source using details on this website 
(http://www.linuxfromscratch.org/blfs/view/cvs/x/xorg7.html).


2.
Press the keys ctrl-alt-f1 and log in as root when the virtual terminal is open.


3.
Run the command "Xorg -configure"

4.
A new file has been created in /etc/X11/ called xorg.conf . 
This file has the configuration settings in it. They were automatically determined and may be satisfactory. 
To test this, use "startx" .

5.
If the XServer did not start, or you do not like the configuration, read on.

6.
Open the file "/etc/X11/xorg.conf"

7.
There are many sections, each controlling a different aspect of the XServer. If the XServer did not start, check the "Device" section. Here is a sample of this, but this will vary from system to system.

    Section "Device"
    Identifier "Device[0]"
    Driver "nvidia"
    VendorName "NVidia"
    BoardName "GeForce 6150 LE"
    EndSection

8.
To configure the "Device" section, you can use these options:

    Identifier -- The device's ID for the server.
    Driver -- What device driver to use for the device, some common ones are vesa (basic, no 3D support), nv (for NVidia cards, no 3D support), and NVidia (for NVidia cards, 3D support, must be downloaded and installed usually).
    VendorName -- Not very important, tells who made the driver.
    BoardName -- Tells what device your graphics card is.


9.
Also, you can configure the input devices such as mouse and keyboard.

10.
To configure the mouse, you will move to the "InputDevice" section with the "Identifier "Mouse[1]"" entry.

    Section "InputDevice"
    Identifier "Mouse[1]"
    Driver "mouse"
    Option "Buttons" "5"
    Option "Device" "/dev/input/mice"
    Option "Name" "ImPS/2 Generic Wheel Mouse"
    Option "Protocol" "explorerps/2"
    Option "Vendor" "Sysp"
    Option "ZAxisMapping" "4 5"
    EndSection
    The above entry controls the mouse. This section is likely to be correctly auto generated correctly.
    The "Driver" entry controls what driver to use. Unless you know otherwise, stick with "mouse".
    Various "Option" entries are provided to edit the protocols and other advanced things about the mouse. You should probably leave these alone.

11.
In addition, you can also configure the keyboard.

    Section "InputDevice"
    Identifier "Keyboard[0]"
    Driver "kbd"
    Option "Protocol" "Standard"
    Option "XkbLayout" "us"
    Option "XkbModel" "microsoftpro"
    Option "XkbRules" "xfree86"
    EndSection
    There are many options here, but you probably only care about "XkbLayout" and the Driver.
    "Option "XkbLayout" " controls the layout of your keyboard. You can specify a code to tell the computer what key you press means what.
    The driver should probably be left alone as kbd driver is able to operate virtually all keyboards, just as the mouse driver can run almost any mouse.

12.
You can also configure the monitor. Be careful as incorrect settings here can damage the monitor permanently.

    Section "Monitor"
    Identifier "Monitor[0]"
    VendorName "VSC"
    Model Name "VIEWSONIC A70"
    UseModes "Modes[0]"
    DisplaySize 310 232
    HorizSync 30.0 - 70.0
    VertRefresh 43.0 - 180.0
    Option "CalcAlgorithm" "XServerPool"
    Option "DPMS"
    EndSection

    Most of the configuration such as MonitorName is self-explanatory. You can also edit the DisplaySize, HorizSync, and VertRefresh settings, but these are the ones that can damage your system so leave them alone.


13.
Various modules can be loaded into the XServer at startup to facilitate things like fonts and 3D graphics. They will be specified in the "Module" entry.

    Section "Module"
    Load "dbe"
    Load "type1"
    Load "freetype"
    Load "extmod"
    Load "glx"
    EndSection
    The glx module controls 3D graphics.
    The free type module is vital for fonts.



14.
font is very important for a graphical program. You may want to edit the font paths, these tell the XServer where to look for fonts.

    Section "Files"
    InputDevices "/dev/gpmdata"
    InputDevices "/dev/input/mice"
    FontPath "/usr/share/fonts/misc:unscaled"
    FontPath "/usr/share/fonts/local"
    FontPath "/usr/share/fonts/75dpi:unscaled"
    FontPath "/usr/share/fonts/100dpi:unscaled"
    FontPath "/usr/share/fonts/Type1"
    FontPath "/usr/share/fonts/URW"
    FontPath "/usr/share/fonts/Speedo"
    FontPath "/usr/share/fonts/PEX"
    FontPath "/usr/share/fonts/cyrillic"
    FontPath "/usr/share/fonts/latin2/misc:unscaled"
    FontPath "/usr/share/fonts/latin2/75dpi:unscaled"
    FontPath "/usr/share/fonts/latin2/100dpi:unscaled"
    FontPath "/usr/share/fonts/latin2/Type1"
    FontPath "/usr/share/fonts/latin7/75dpi:unscaled"
    FontPath "/usr/share/fonts/baekmuk:unscaled"
    FontPath "/usr/share/fonts/japanese:unscaled"
    FontPath "/usr/share/fonts/kwintv"
    FontPath "/usr/share/fonts/truetype"
    FontPath "/usr/share/fonts/uni:unscaled"
    FontPath "/usr/share/fonts/CID"
    FontPath "/usr/share/fonts/ucs/misc:unscaled"
    FontPath "/usr/share/fonts/ucs/75dpi:unscaled"
    FontPath "/usr/share/fonts/ucs/100dpi:unscaled"
    FontPath "/usr/share/fonts/hellas/misc:unscaled"
    FontPath "/usr/share/fonts/hellas/75dpi:unscaled"
    FontPath "/usr/share/fonts/hellas/100dpi:unscaled"
    FontPath "/usr/share/fonts/hellas/Type1"
    FontPath "/usr/share/fonts/misc/sgi:unscaled"
    FontPath "/usr/share/fonts/xtest"
    FontPath "/opt/kde3/share/fonts"
    EndSection
    Note that fonts are usually autodetected by Xorg -configure, but if they were not you can add a new entry such as "FontPath wherethefontsare" to load them.

15.
The last section covered here is the "ServerLayout" section. It controls things such as multiple desktops and tells what devices to use.

    Section "ServerLayout"
    Identifier "Layout[all]"
    Screen "Screen[0]" 0 0
    InputDevice "Keyboard[0]" "CoreKeyboard"
    InputDevice "Mouse[1]" "CorePointer"
    Option "Clone" "off"
    Option "Xinerama" "off"
    EndSection
    There are many important options here. They are explained below.
    InputDevice -- Tells XServer to use a created device.
    Option "Clone" -- If multiple monitors or graphics cards are used, this tells whether or not to display the same thing on all of them.
    Option "Xinerama" -- If multiple graphics cards or monitors are used, this tells whether or not to let them behave like separate desktops.