Skip to content

Instantly share code, notes, and snippets.

@mbodo
Last active June 28, 2020 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbodo/94718532ca15559269d8042450fc7890 to your computer and use it in GitHub Desktop.
Save mbodo/94718532ca15559269d8042450fc7890 to your computer and use it in GitHub Desktop.
lpi202.md

LPI-2 202 Notices

Topic 207: Domain Name Server

Topic 208: Web Services

Topic 209: File Sharing

Topic 210: Network Client Management

Topic 211: E-Mail Services

Topic 212: System Security

207.1 Basic DNS server configuration

Basics:

  • Host
  • Domain name
  • Top-level domain
  • FQDN
  • Subdomain
  • Name server
  • Authoritative name server
  • Zone file
  • Record
  • Caching name server
  • TTL
  • DNS forwarder
  • Forward lookup
  • Reverse lookup
  • BIND, dnsmasq, bjbdns, PowerDNS

Name resolution:

cat  /etc/resolv.conf
nameserver 192.168.1.1
  • 13 root servers (a-m).root-servers.net.

BIND configuration:

options {
        // listen to incoming requests on port 53 for the localhost
        // multiple listen on listen-on port 53 { 127.0.0.1; 192.168.1.1; };
        listen-on port 53 { 127.0.0.1; };
        
        // IPv6
        listen-on-v6 port 53 { ::1; };
        
        // Working directory, location for additional information, including zone files
        directory       "/var/named";
        
        // Dump-file generated by rndc dumpdb
        dump-file       "/var/named/data/cache_dump.db";
        
        statistics-file "/var/named/data/named_stats.txt";
        
        // stats info from memory when server exits
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        
        recursing-file  "/var/named/data/named.recursing";
        
        secroots-file   "/var/named/data/named.secroots";
        
        /* 
           limits which systems can query DNS server
           accepts arguments in form { address_match_list; address_match_list; .. }
           address_match_list:
           - IPv4, IPv6
           - network 192.168.1/24
           - acl, a nickname assigned to multiple IP addresses or networks
                  acl "permit" { localhost; !192.168.3.1; 192.168.3/24 };
                  allow-query  { "permit" }
           - predefined address:
             - none, match no IP addr
             - any, match any IP addr
             - localhost, IP addr of the DNS itself
             - localnets, all IP addr of the network the DNS is on
           - negate with ! e.g allow-query { localhost; !192.168.3.1; 192.168.3/24 } - every machine 192.168.3/24
        */
        allow-query     { localhost; };
        
        // yes - perform all neccessary DNS queries, no - referral data response, e.g. a DNS server to query next
        recursion yes;
        
        // DNSSEC - Domain Name System Security Extensions, it authenticating DNS data
        dnssec-enable yes;
        
        // yes - use of trusted or managed keys
        dnssec-validation yes;
        
        // auto - alter. repository of trusted keys defined in bindkeys-file
        dnssec-lookaside auto;
        
        /* Path to ISC DLV key - when dnssec-lookaside is auto */ 
        bindkeys-file "/etc/named.root.key";
        
        // directory used to store list od DNSSEC trusted keys
        managed-keys-directory "/var/named/dynamic";
        
        // process ID of the DNS server
        pid-file "/run/named/named.pid";
        
        // TSIG (Transaction SIGnature) session key to allow authenticated updates of the DNS database, used by nsupdate cmd
        session-keyfile "/run/named/session.key";

...

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
        type hint;
        file "named.ca";
};

// additional DNS settings in a separate file
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

BIND commands:

$ rndc reload - reload all the configuration, including the zone files

Alt. to reload:
---------------

$ ps -ef | grep named
78868

$ kill -1 78868

Reload specific zone:
---------------------

$ rndc reload <zone>

Troubleshooting the rndc reload:
--------------------------------

$ rndc reload
rndc: neither /etc/rndc.conf nor /etc/rndc.key was found

$ rndc-confgen > /etc/rndc.conf
$ vim /etc/rndc.conf /etc/named.conf
  
  copy from rndc.conf to named.conf
  
  # Use with the following in named.conf, adjusting the allow list as needed:
  # key "rndc-key" {
  #       algorithm hmac-md5;
  ...
  
  # End of named.conf

  remove #
  
  :wqa

$systemctl restart named.service - in older systems kill -1 named

$rndc reload
server reload successful

Setting up permissions:
-----------------------

$ ls -l /etc/rndc.conf
-rw-r--r-- 1 root root 479 Jun 21 13:14 /etc/rndc.conf

$ chgrp named /etc/rndc.conf
$ chown 640 /etc/rndc.conf

Other
$ rndc dumpdb - dump of named server cache, default in /etc/named.conf is /var/named/data/cache_dump.d
$ rndc flush - flush named cache
$ rndc flushname - flush specifics domain
$ rndc flushtree - flush entire subdomain
$ rndc reconfig - reloads /etc/named.conf and any new zone files, doesn't reload any existing zone file 
$ rndc status - status of named server
$ rndc stop - stops named server

207.2 Create and maintain DNS zones

Zone File Basic:

/var/named - direcory for zone files
/var/named/named.ca - list of the root servers
/var/named/named.localhost - file defines the localhost

Zone File Entries:

/etc/named.conf - every zone file 

Primary master DNS server:
--------------------------

zone "zoneone.com" {
type master;
file "named.zoneone.com";
};

Notes:
type master, - this is the machine where changes to zone file are made
file "named.zoneone.com"; - relative to /var/named

2nd DNS server slave at /etc/named.conf
---------------------------------------

zone "zoneone.com" {
type slave;
file "named.zoneone.com";
masters { 10.20.30.1; }
};

Notes:
type slave; - holds a copy of of the master name server zone files

Reverse lookup:
---------------

zone "10.20.30.in-addr.arpa" {
     type master;
     file "db.30.20.10";
};


Authoritative name server:
--------------------------
- has authority to respond to DNS queries, this could be both master and slave name servers

Additional zone settings:
allow-query - same as in /etc/named.conf global option, just for specific zone
allow-transfer - limit DNS servers which can transfer zonefile
allow-update - Dynamic DNS feature, allows DHCP to update records in master DNS's zone file

Zone file syntax:

; - comment lines
line - end of a line is end of record, multiple SOA
record - field of data separated by spaces or tabs
       - name, domain name
       - ttl, time to live
       - record class, e.g. IN internet class
       - record type
       - record data, single or multiple values
@ - the current origin, for the zoneone.com, this means zoneone.com
ttl - zone file should start with $TTL setting, how long caching DNS servers store info from this DNS server, 
      in seconds, default $TTL 86400(s) - (1d), also valid (1m, 1h, 1d, 1w), not case sensitive

Zone Record Type:

  • SOA (Start of Authority)
Multiline
@   IN SOA ns.zoneone.com root.zoneone.com. (
                          0    ; serial
                          1D   ; refresh
                          1H   ; retry
                          1W   ; expire
                          3H ) ; minimum

Oneline
@   IN SOA ns.zoneone.com root.zoneone.com. 0 1D 1H 1W 3H

ns.zoneone.com   - name server
root.zoneone.com - email of DNS admin, equvivalent to root@zoneone.com
0                - serial, slave servers query master regulary wheter the serial num. has been updated,
                   ser. num is limited to 10 digits,
                   common format YEARmonthDAYrev, e.g June 22, 2020, rev 01 is 2020062201, this format allows 0-99 changes per
                   day
1D               - refresh, how often should slave DNS server query the master, typicaly one day, or freq. cahnges 6H
1H               - retry, tell when the slave DNS should repeat the request to master again, if master not responded
1W               - expiry, if master unreachable for longer than 1W e.g, than the slave servers should no longer respond to DNS
                   client, DNS entries are no longer valid
3H               - minimum, lenght of time to cache negative DNS responses, if domain is updated frequently 1H, rarly changed 1D

Address Record Type:

Relative to $ORIGIN
-------------------
www          IN          A           10.20.30.40

FQDN:
-----
www.zoneone.com          IN          A           10.20.30.40

Canonical Name Type:

- beacuse only one address record per IP address

www.zoneone.com          IN          A           10.20.30.40
ftp                      IN          CNAME       www 

ftp.zoneone.com -> www.zoneone.com -> 10.20.30.40

Name Server Record Type:

@          IN          NS          ns.samplezone.com.
@          IN          NS          ns2.samplezone.com.

Mail eXchnage Record Type

@          IN          MX          10          mail1.samplezone.com.
@          IN          MX          20          mail2.samplezone.com.

10,20 - priority values, lower number means higher priority, 
        common is to use with same priority, because of load balancing

PoinTeR Record Type:

- translate domain names into IP addresses

40.30.20.10.in-addr.arpa          IN          PTR          www.zoneone.com.

- valid is also only a portion of IP address

40         IN          PTR          www.zoneone.com.

Testing the DNS Server:

named-checkconf - verify the syntax of /etc/named.conf

named-checkzone zoneone.com /var/named/named.zoneone.com
named-checkzone 30.20.10.in-addr.arpa /var/named/db.10.20.30

dig www.zoneone.com @localhost
nslookup wwzoneone.com localhost
host ww.zoneone.com localhost

207.3 Securing a DNS server

Run BIND to chroot jail:

Older distibutions:

$ mkdir -p /chroot/named
$ mkdir -p /chroot/named/dev
$ mkdir -p /chroot/named/etc
$ mkdir -p /chroot/named/var/named
$ mkdir -p /croot/named/var/run

$ cp -p /etc/named.conf /chroot/named/etc
$ cp -a /var/named/* /chroot/named/var/named
$ cp  /etc/localtime /chroot/named/etc

$ chown -R named:named /chroot/named
$ mknod /chroot/named/dev/null c 1 3
$ mknod /chroot/named/dev/random c 1 8
$ chmod 666 /chroot/named/dev/*

$ cat /etc/sysconfig/named
# BIND named process options
-t /chroot/named

Modern distribution with systemd:

$ yum install bind-chroot
$ systemctl start named-chroot.service

Split BIND Configuration:

  • DNS Views
  • 2 DNS Severs (more secure)

Transaction Signatures (TSIG):

/etc/named.conf

allow-transfer { address_match_list }

DNSSEC ( Domain Name System SEcurity Extensions)

Generate public/private key
---------------------------

$ cd /var/named
$ dnssec-keygen -a RSASHA1 -b 512 -n ZONE zoneone.com

genereate 2 files

/var/named/Kzone.com+005+06542.key      - public key
/var/named/Kzone.com+005+06542.private  - private key

Sign off the zone file with zone private key
--------------------------------------------

$ dnssec-sigzone -o zoneone.com named.zoneone.com
$ ls
...
named.zoneone.com.signed
...


Links:

208.1 Implementing a web server

Basic Apache Web Server Conf:

ServerRoot - top of directory tree, e.g /etc/httpd
Listen - allows bind spec. IP addrs and port, e.g Listen 10.20.30.40:80
DocumentRoot - directory to serve documents, e.g /var/www/html
LogLevel - info, warn, debug .etc

Starting Apache:

httpd - apache web server process
apachectl (apache2ctl) - server control interface

Apache Log Files:

/var/log/httpd/access_log - logs attempts to access content from web server
/var/log/httpd/error_log  - logs error messages on web server

Enable scripting:

PHP

1. $ yum install php
2. check at /etc/httpd/modules -> /usr/lib64/httpd/modules for libphp5.so
3. check directive, grep Include /etc/httpd/conf/httpd.conf
4. check that exists or configure, ls -l /etc/httpd/conf.modules.d/10-php.conf
   <IfModule prefork.c>  
     LoadModule php5_module modules/libphp5.so
   </IfModule>
5. restart httpd, systemctl restart httpd
6. Test, create /var/www/html/index.php
   <html> <head>  <title>PHP Test</title> </head> <body> <?php echo '<p>Hello World from PHP</p>'; ?> </body></html>
7. In browser http://<IP address>:<port>/index.php

Perl

1. $ yum install mod_perl
2. check at /etc/httpd/modules -> /usr/lib64/httpd/modules for mod_perl.so
3. check that exists or configure, ls -l /etc/httpd/conf.modules.d/02-perl.conf
   LoadModule perl_module modules/mod_perl.so
4. configure, /etc/httpd/conf/httpd.conf
   <Directory /var/www/html/perl>
     AllowOverride All
     SetHandler perl-script
     PerlHandler ModPerl::Registry
     PerlOptions +ParseHeaders
     Options ExecCGI
     Order allow,deny
     Allow from all
   </Directory>
5. create, mkdir -p /var/www/html/perl
6. create, vim /var/www/html/perl/index.pl
   print "Content-type: text/plain\r\n\r\n";
   print "Hello world from Perl\n"
7. restart, systemctl restart httpd
8. test, http://<IP addr>:<port>/perl/index.pl

Apache Web Server Security:

System
------

- limit the user accounts
- min. packages
- limit which processes running on the system
- permissions, selinux
- firewall

Apache settings
---------------
StartServers        - Apache start as single process owned by root user. e.g. 10 
                      This process never handle client requests.
                      Start multiple processes under non-root user to handle client requests.
MinSpareServers     - number how many httpd processes are always available e.g. 5
MaxSpareServers     - number how many httpd process can be killed when not used e.g. 15
MaxClients          - number of max 150 servers will be started e.g. 100
MaxRequestsPerChild - help to mitigate DOS - Denial of Service e.g. 2500
           

User Authentification:

httpd <= 2.0 - Module mod_auth must be loaded, to perform basic authenication
httpd >= 2.1 - Module mod_auth_basic must be loaded, to perform basic authenication

To secure with basic user authentication:
$htpasswd -c /etc/httpd/conf/password userone

-c is location of password file

To secure specifics directory:

vim /etc/httpd/conf/httpd.conf

<Directory /var/www/html/secured>
  AuthName "Basic Auth Folder"     
  AuthType Basic
  AuthUserFile /etc/httpd/conf/password
  Require valid-user
 </Directory>

or place the /var/www/html/secured/.htaccess

  AuthName "Basic Auth Folder"     
  AuthType Basic
  AuthUserFile /etc/httpd/conf/password
  Require valid-user

Virtual Hosts:

IP-Based virtual hosts
----------------------
1. IP aliasing (see Links below)
2. Multiple network interfaces

Configuration:

<VirtualHost www.virtualone.com>     
  ServerAdmin admin@mail.virtualone.com     
  DocumentRoot /var/www/virtualone/html     
  ServerName www.virtualone.com     
  ErrorLog /var/log/virtualone/error_log
</VirtualHost>

<VirtualHost www.virtualtwo.com>     
  ServerAdmin admin@mail.virtualtwo.com     
  DocumentRoot /var/www/virtualtwo/html     
  ServerName www.virtualtwo.com     
  ErrorLog /var/log/virtualtwo/error_log
</VirtualHost>


- Name-Based wirtual hosts

<VirtualHost 10.20.30.40>
 ServerName www.virtualone.com
 DocumentRoot /var/www/virtualone/html
</VirtualHost>

<VirtualHost 10.20.30.40>
 ServerName www.virtualtwo.com
 DocumentRoot /var/www/virtualtwo/html
</VirtualHost>

208.2 Apache configuration for HTTPS

SSL:

Asymmetric cryptography - public, private key
Public key - encrypt, contains digital signature
Private key - decrypt
CA(Certificate Authority) - verify the digital signature

Issues:

  • Large number of CA servers increase chance that one could be compromised
  • Trust because the root CA
  • Man in the middle attacks
  • Each virtual host must have its own digital signature
  • Private key security

CA Signed(example, uses only weak ciphers!):

1. verify openssl is installed
   $ yum list openssl
   Installed Packages
   openssl.x86_64
2. create private key (.key)
   $ openssl genrsa -des3 -out server.key 1024
3. create signing request (.csr)
   openssl req -new -key server.key -out server.csr

Self Signed:

1. install openssl-perl
2. mkdir /tmp/ssltest
3. cd /tmp/ssltest
4. setup CA
   $ /etc/pki/tls/misc/CA.pl -newca
     ...
   $ ls -l /etc/pki/CA/private/cakey.pem
5. create signing request
   $ /etc/pki/tls/misc/CA.pl -newreq
   $ ls -l newkey.pem
   $ ls -l newreq.pem
6. sign the certificate
   $ /etc/pki/tls/misc/CA.pl -signreq
   $ ls -l newcert.pem
7. copy certificate and key
   $ mv newcert.pem /etc/ssl/vm.com_cert.pem
   $ mv newkey.pem /etc/ssl/vm.com_priv.pem
   $ rm newreq.pem

Apache SSL:

1. install yum install mod_ssl
2. check
   $ cat /etc/httpd/conf.modules.d/00-ssl.conf
     LoadModule ssl_module modules/mod_ssl.so
3. check
   $ ls -l /etc/httpd/modules/mod_ssl.so
4. $ vim /etc/httpd/conf.d/ssl.conf
     SSLCertificateFile /etc/ssl/vm.com_cert.pem
     SSLCertificateKeyFile /etc/ssl/vm.com_priv.pem
5. $ systemctl restart httpd
6. browser https://<ip addr>:<port>:443/

Apache SSL Directives:

  • SSL Engine - On/Off virtual hosts
  • SSLCertificateChainFile - full chain inc root CA, could be used instead of SSLCertificateFile
  • SSLCACertificateFile - file on server, to authenticate client
  • SSLCACertificatePath -
  • SSLProtocol - TLSv1, TLSv1.2 .tec
  • SSLCipherSuite - cipher used to create public/private key
  • ServerTokens - limit the info about the server, which recieve the client
  • ServerSignature - create footer with debug info
  • TraceEnable - SSL trace for debugging

208.3 Implementing a proxy server

  • Tunneling proxy - Net-A <-> tunneling proxy <-> Net-B
    • Gateway between two networks
  • Forward proxy - Client <-> Forward proxy <-> Internet <-> Destination Server
    • filter
    • annonymizer
    • cache
    • log client activity
  • Reverse proxy - Client <-> Internet <-> Reverse proxy <-> Destination Server
    • load balancer
    • cache static data
    • ssl proxy
    • hide destination server
    • optimize, compressing

Squid:

Configuration: 
--------------
/etc/squid/squid.conf

Parameters:
-----------
cache_dir   - e.g cache_dir ufs /var/spool/squid 100 16 256
              ufs - type of storage
              /var/spool/squid - cache directory
              100 - max. size of cached files
              16 - first-level directory size in cache dir
              256 - second level directory size in cache dir
http_port   - listen incoming http requests e.g 3128
auth_param  - authenticate, with e.g LDAP, Samba severs
acl         - access control list
http_access - set acl to use Squid as HTTP forward server

Squid Access Rules:
-------------------
grep -v '^#' /etc/squid/squid.conf | grep -v '^$'

acl localnet src 10.0.0.0/8 - source to request connection
acl SSL_ports port 443      - SSL connection is permitted
...
acl Safe_ports port 80      - HTTP connection is permitted

- default acls in Squid configuration: all, manager, localhost, to_localhost

http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager - - order is important !
http_access deny manager - order is important !
http_access allow localnet
http_access allow localhost
http_access deny all - order is important !

208.4 Implementing Nginx as a web server and a reverse proxy

Nginx:

Provides:
---------
- loadbalancing
- web acceleration
- multiple protocols (TCP,IMAP,SMTP)
- authentication

Reverse Proxy:
--------------
server {        
        listen 80;        
        location / {             
          proxy_pass http://192.168.1.5;
        }
}

Links:

209.1 SAMBA Server Configuration

  • SMB (Server Message Block) Protocol
  • CIFS (Common Internet File System), SMB-based protocoll from Microsoft
Installation:
-------------
yum install samba samba-client samba-common

Configuration:
--------------
/etc/samba/smb.conf
# - regular comments
; - comment actual config. settings

[global]
        # NetBIOS - Network Basic Input/Output System
        workgroup = SAMBA
        # useful when remote system is attempting to connect
        # %v - SAMBA version
        # %h - hostname
        server string = SAMBA Server Version %v
        # Authentication method:
        # user - SAMBA user accounts
        # domain - Windows Domain controller
        # ads - Active Directory
        security = user

        # type of SAMBA account data store
        passdb backend = tdbsam

        printing = cups
        printcap name = cups
        
        # yes - SAMBA will load al CUPS printers
        load printers = yes
        # CUPS options
        cups options = raw

[homes]
        # for sharing SAMBA users home directories
        comment = Home Directories
        valid users = %S, %D%w%S
        # yes - share will be visible with client utilities
        # no  - share is available but not listed with client utilities 
        browseable = No
        # SAMBA 4
        read only = No
        #SAMBA 3
        writable = Yes
        inherit acls = Yes

[printers]
        comment = All Printers
        # location to CUPS spool directory
        path = /var/tmp
        printable = Yes
        create mask = 0600
        browseable = No
        # permits access to CUPS printers from guest account
        guest ok - no

[print$]
        comment = Printer Drivers
        path = /var/lib/samba/drivers
        # list of users which have r-w access to service 
        write list = @printadmin root
        force group = @printadmin
        # when file created necessary permissions are calculated 
        create mask = 0664
        directory mask = 0775
        
# Custom share
[share]
comment = Shared
path = /usr/share
guest ok = no
browsable = yes
read only = yes
# users which can access share
valid users = smbuser1, smbuser2
# users which cannot access share
invalid users = smbuser3
# users with access and read only
read list = smbuser1
# users with access and read-write
write list = smbuser2

Validation of configuration:
----------------------------
$testparm 
Load smb config files from /etc/samba/smb.conf
Loaded services file OK.
Server role: ROLE_STANDALONE

Press enter to see a dump of your service definitions
...

Start SAMBA:
------------
# NetBios name server
systemctl start nmb.service

# Samba Server
systemctl start smb.service

Samba Accounts:
---------------
- The simplier option is to map smb user accounts to linux user accounts

$ grep -i localuser1 /etc/passwd
localuser1:x:500:500::/home/localuser1:/bin/bash

$ smbpasswd -a localuser1
New SMB password:
...

- Using a account mapping (if account doesn't match system user account)

$ touch /etc/samba/usermap.txt
$ smbpasswd -a smbuser1
$ vim /etc/samba/usermap.txt
# (system acc.) = (smb acc.)
localuser1 = smbuser1

- if Active Directory, or Domain server
# (windows acc.) = (smb acc.)
winuser1 = smbuser1

- create guest account
$smbpasswd guest
...

Accessing SAMBA Servers:
------------------------
# Discover SAMBA servers
$ nmblookup SAMBA
192.168.XXX.XXX SAMBA<00>

# Client connect and list the shares
$ smbclient -U testone -L 192.168.XXX.XXX
Enter SAMBA\testone's password: 

        Sharename       Type      Comment
        ---------       ----      -------
        print$          Disk      Printer Drivers
        ...
        testone         Disk      Home Directories

...

# Client connect and access specifcs share
$ smbclient -U testone //192.168.XXX.XXX/testone
Password:
...
smb: \>ls
.
..
.bashrc
...

# View which machines are connected to SAMBA
$ smbstatus

Samba version 4.10.4
PID     Username     Group        Machine                                   Protocol Version  Encryption           Signing              
----------------------------------------------------------------------------------------------------------------------------------------
6842    testone      users     192.168.XXX.XXX (ipv4:192.168.XXX.XXX:46164) SMB3_11           -                    partial(AES-128-CMAC)
...

# Mounting SAMBA shares
- Manually
$ mkdir /share/testone
$ mount -t cifs -o user=student //192.168.XXX.XXX/testone /share/testone

- Boot /etc/fstab
$ vim /etc/fstab
# Directly with user, password
//10.0.2.15/doc   /doc   cifs   user=testone,password=mypassword   0    0
# With credentials
//10.0.2.15/doc   /doc   cifs   credentials=/etc/samba/testone   0    0

$ vim /etc/samba/testone
  user=testone
  password=mypassword

209.2 NFS Server Configuration

Installation:
-------------

$ yum install nfs-utils
$ systemctl start rpcbind && sleep 5 && systemctl start nfs-server && sleep 5 && systemctl start nfs-lock && sleep 5 && systemctl start nfs-idmap
$ systemctl status rpcbind nfs-server nfs-lock nfs-idmap

Configuration:
--------------
/etc/exports

hostname - resolvable as IP addr
netgroup - NIS netgroup, @groupname
domain - with wildcards *, e.g *.zoneone.com
network - VLSM, CIDR
rw - share read-write
ro - read-only
sync - file changes immediately, lower performance
async - file changes scheduled, in memory, higher perf., data loss
root_squash - map root account from NFS Client to anonymous account (nobody, nfsnobody)
no_root_squash - map root account from NFS Client to local root and group account

Notice: if user account  on NFS Client doesn't exists it map to user with equal UID, GID

Setup:
------
 - 2 VMs on one LAN

Both VMs
1. $ groupadd -g 54332 nfsuser
2. $ useradd -m -s /bin/bash -g nfsuser -u 54325 nfsuser

VM NFS Server:
3. $ mkdir -p /share
4. $ chown -vR nfsuser:nfsuser /share
5. $ touch /share/example1.txt
6. $ chmod -vR 0744 /share/example1.txt
7. $ systemctl stop nfs-idmap && systemctl stop nfs-lock && systemctl stop nfs-server && systemctl start rpcbind
8. $ systemctl start rpcbind && sleep 5 && systemctl start nfs-server && sleep 5 && systemctl start nfs-lock && sleep 5 && systemctl start nfs-idmap
9. $ exportfs -a

VM NFS Client:
10. 192.168.xxx.xxx is NFS Server IP addr
    $ mount -t nfs 192.168.xxx.xxx:/share /mnt
11. as root
    $ su - nfsuser
12. echo "Hello world from NFS client" > /mnt/example1.txt
13. cat /mnt/example1.txt
    Hello world from NFS client

VM NFS Server
14. $ cat /mnt/example1.txt
    Hello world from NFS client
15. $ echo "Hello from NFS Server" >> /share/example1.txt

VM NFS Client:
16. cat /mnt/example1.txt
    Hello world from NFS client
    Hello from NFS Server

NFS Server Processes:
---------------------
- RPC

$  ps -ef | grep -i 'rpc\.'
rpcuser  18972     1  0 10:49 ?        00:00:00 /usr/sbin/rpc.statd
...

- RPC systemd

$ systemctl list-units rpc*
UNIT              LOAD   ACTIVE SUB     DESCRIPTION
rpc-statd.service loaded active running NFS status monitor for NFSv2/3 locking.
rpcbind.service   loaded active running RPC bind service
rpcbind.socket    loaded active running RPCbind Server Activation Socket
rpc_pipefs.target loaded active active  rpc_pipefs.target
rpcbind.target    loaded active active  RPC Port Mapper

- NFS

$ ps -ef | grep -i --color nfs
root     18978     2  0 10:49 ?        00:00:00 [nfsd4_callbacks]
root     18984     2  0 10:49 ?        00:00:00 [nfsd]
...

- NFS systemd

$ systemctl list-units -all nfs*
  UNIT                      LOAD      ACTIVE   SUB     DESCRIPTION
  nfs-config.service        loaded    inactive dead    Preprocess NFS configuration
  nfs-idmapd.service        loaded    active   running NFSv4 ID-name mapping service
  nfs-mountd.service        loaded    active   running NFS Mount Daemon
● nfs-secure-server.service not-found inactive dead    nfs-secure-server.service
  nfs-server.service        loaded    active   exited  NFS server and services
  nfs-utils.service         loaded    inactive dead    NFS server and client services
  nfs-client.target         loaded    active   active  NFS client services

rpc.statd   - handle recovery, if NFS Server is rebboted whil NFS Client is using the NFS Server
rpc.rquotad - filesystem qouta
rpc.mountd  - handle initial NFS Client mout request
rpc.idmapd  - only NFSv4, mapping of user and groups
nfsd        - handle client/server NFS

Portmap:
--------
- when NFS client connect it query the portmap which port NFS Server is using

$ rpcinfo -p
   program vers proto   port  service
    100000    4   tcp    111  portmapper
    100000    3   tcp    111  portmapper

also from remote system (client vm), 

$ rpcinfo -p 192.168.122.21
   program vers proto   port  service
    100000    4   tcp    111  portmapper
    100000    3   tcp    111  portmapper

TCP wrappers:
$ vim /etc/hosts.allow
portmap: 192.168.XXX.XXX

$ vim /etc/hosts.deny
portmap: 192.168.XXX.XXX/24

NFS Server Commands:
--------------------
- display what is shared
$ exportfs
/share          <world>

- share temporary NFS server
$ exportfs -o ro 192.168.XXX.XXX:/usr/share/doc
$ exportfs
/usr/share/doc  192.168.122.189
/share          <world>

- enable changes after edit of /etc/export
$ exportfs -a

- show nfs mounts
$ nfsstat -m

/mnt from 192.168.XXX.XXX:/usr/share/doc
 Flags: rw,relatime,vers=4.1,rsize=1048576,wsize=1048576,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=192.168.XXX.XXX,local_lock=none,addr=192.168.XXX.XXX

NFS Client Commands:
--------------------
- mount
$ mount -t nfs 192.168.XXX.XXX:/share /mnt

Permanent Mount /etc/fstab:
---------------------------
- VM Client 

$ vim /etc/fstab
192.168.XXX.XXX:/share      /access                nfs      defaults     0    0
                                                            (rw,soft)
Options:

soft | hard - soft try to mount for a specific period of time and than stops, hard ties to mount indefinitely 
fb | bg     - foregorund mount | backgroud mount + if with combination with hard
timeo=      - 600, means 600/10 = 60s
retrans=    - retry to mount NFS share, 3xUDP and 2xTCP apttempts by default
retry=      - how many attempts to try before timeout
rsize       - max. byte size of each READ request
wsize       - max. byte size of each WRITE request
rw | ro     - read-write | read-only attempt to mount, if NFS is read-only configured, rw is not used

210.1 DHCP configuration

210.2 PAM authentication

PAM Configuration Basic:

Configuration files:
--------------------
- old:
$ ls -l /etc/pam.conf

- new:
$ ls -l /etc/pam.d/
chfn chsh config-util

e.g SSH PAM configuration
#%PAM-1.0
auth       required     pam_sepermit.so
auth       substack     password-auth
auth       include      postlogin
# Used with polkit to reauthorize users in remote sessions

PAM Types:
----------
- PAM modules are executed in order they are written
- Each module return successful or unsuccessful result
- usuccessful doesn't always mean user can't log in

Control values:
---------------
required   - Successful  : if succ. go to next rule, if final rule stack return with succ.
             Unsuccessful: if unsucc. no next rule is executed, stack return as unsucc.
requisite  - Successful  : if succ. go to next rule, if final rule stack return with succ.
             Unsuccessful: if unsucc. next rule is executed, but the stack return as unsucc.
optional   - Successful  : if succ. go to next rule, if final rule stack return with succ.
             Unsuccessful: if unsucc. next rule is executed, if final stack return succ.
sufficient - Successful  : if succ. no next rule and the stack return with succ.
             Unsuccessful: if unsucc. next rule is executed, if final stack return succ.
include    - PAM use all rules from included file, but only rules for type e.g auth, account .etc

PAM Modules:
------------
pam_unix.so - for setting a passwords
              Options:
              md5        - encrypt md5
              sha256     - encryt sha256
              shadow     - store in /etc/shadow
              nullok     - allow root to provide users with null passwords
              remember=x - remeber old passwords, password rotate
             
pam_cracklib.so - use for password format, e.g min. length
pam_limits.so - limit access resources /etc/security/limits.conf
pam_listfile - grant or deny access to content
               auth    required pam_listfile.so item=user sense=deny file=/etc/sshfs/ sshfsusers onerr=succeed
...

210.3 LDAP client usage

ldapdelete:
-----------

$ ldapdelete "uid=named,ou=People,dc=my-domain,dc=com" -x -D  "cn=root,dc=my-domain,dc=com" -W

"uid=named,ou=People,dc=my-domain,dc=com", object to be deleted
-x, simple authentication
-D, ldap account
-W, prompt the user for password

ldapsearch:
-----------

$ ldapsearch -x -b 'ou=People,dc=my-domain,dc=com' '(objectclass=account)' uid
-x, simple authentication
-b, base to search from e.g. "dc=my-domain,dc=com"
'(objectclass=account)' - filter
uid - attribute to search for

# With common name (cn) searching
$ ldapsearch -x -b 'ou=People,dc=mydomain,dc=com' '(cn=bin)' uid

# With common name (cn) searching and display options
$ ldapsearch -LLL -x -b 'ou=People,dc=my-domain,dc=com' '(cn=bin)' uid
- L,  display output in LDAP,version1
- LL, display output only results and LDAP version
- LLL,display output only results

# With common name (cn) searching and logical operators
$ ldapsearch -x -b 'ou=People,dc=my-domain,dc=com' '(|(cn=bin)(cn=root))' uid 
- |, OR
- &, AND
- !, NOT

# With common name (cn) searching and filter operators
ldapsearch -x -b 'ou=People,dc=,dc=com' '(cn=*bo*)' uid
=   , match exactly
=*.*, match expression with wild card
>=  , gt or eq
<=  , lt or eq
~=  , approx. match

ldappassword:
-------------

# Change ldap password with specifying password at cmd
$ ldappasswd -x -D "cn=root,dc=my-domain,dc=com" -s newpassword -W  uid=bin,ou=People,dc=my-domain,dc=com
-x, simple authentication
-D, ldap account
-s, new pasword specification
-W, propmt for password
uid=bin,ou=People,dc=my-domain,dc=com, 

# Change ldap password without specifying password at cmd
$ ldappasswd -x -D "cn=root,dc=my-domain,dc=com" -S -W  uid=bin,ou=People,dc=my-domain,dc=com
-S, prompt for new password

210.4 Configuring an OpenLDAP server

Installation:

$ yum install openldap openldap-clients openldap-servers

LDAP Terms:

Object    - entry or record, describe user accounts .etc, definition of object is object class, defined in schema
Attribute - component of object, data types defined in schema
Schema    - define attributes and objects, what attributes has object and what should contains the attributes
LDIF      - LDAP DATA Interchange Format
DN        - distinguished name,must be unique name in server directory, represented as containers, 
            e.g top level container  "com", secondary level "my-domain"
CN        - common name, cn=user1,dc=my-domain,dc-com - think as directory and file analogy
SSSD      - system security services daemon

Configuration:

slapd.conf
----------

include         /etc/openldap/schema/core.schema
include         /etc/openldap/schema/cosine.schema
include         /etc/openldap/schema/inetorgperson.schema
include         /etc/openldap/schema/nis.schema

# Top level structure
suffix          "dc=my-domain,cd=com"
# Root account of LDAP server
rootdn          "cn=Manager,dc=my-domain,dc=com"
# plain text password for the rootdn LDAP account
rootpw          secret
# encrypted rootdn password, created with slappasswd
rootpw          {crypt}ojksnnJJmn

loglevel 2048
loglevel 0x800
loglevel parse

loglevel 4096
loglevel 0x1000
loglevel cache

# Mode 700 recomended
# If this directory does not exist, slapd will not start
directory /var/lib/ldap

LDAP verify/startup

Verify the slapd.conf
---------------------
$ slaptest -u -v

Startup SysV:
-------------
$ /etc/init.d/ldap start

Startup systemd:
----------------
$ systemctl start slapd.service

OpenLDAP Objects:

dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootPW
olcRootPW: {SSHA}OPx7WkATKHSUKHOIKGqfTQOtRN6B9ohd

OpenLDAP Schemas:

Example:

objectClass: organization
o: ExampleOrg

$ vim /etc/openldap/schema/core.schema

# Object ID (2.5.4.10) each objectclass has a unique
# DESC determine object usage
# MUST for required attributes
# MAY for allowed attributes
attributetype ( 2.5.4.10 NAME ( 'o' 'organizationName' )
        DESC 'RFC2256: organization this object belongs to'
        SUP name )

OpenLDAP Database Commands:

ldapadd
-------

$ vim ldif.txt 
dn: dc=my-domain,dc=com
dc: olcDatabase={2}hdb
description: A example organization
objectClass: dcObject
objectClass: organization
o: ExampleOrg

ldapadd -x -D "cn=Manager,dc=my-domain,dc=com" -W -f ldif.txt

-x, simple authentication
-D, DN of OpenLDAP authorized to administer the server
-W, query for rootdn password
-f , LDIF file name

ldapmodify
----------
- change and existing object with LDIF file

ldapdelete
----------
- delete existing object, no LDIF is required, delete speciefied from cmd

slapindex
---------
- add index for data

slapcat
-------
$ slapcat
dn: dc=my-domain,dc=com
dc: olcDatabase={2}hdb

Access Control:

olcAccess: <access directive>
<access directive> ::= to <what>
...

Links:

211.1 Using e-mail servers

SMTP - Simple Mail Transfer Protocol

SMTP Components:
----------------
MUA  - Mail User Agent
MSA  - Mail Submission Agent
MTA  - Mail Transfer Agent
MDA  - Mail Delivery Agent
POP  - Post Office Protocol
IMAP - Internet Message Access Protocol

Configuration:
--------------
- directly:
$ vim /etc/postfix/main.cf

- command:
$ postconf
2bounce_notice_recipient = postmaster
access_map_defer_code = 450
access_map_reject_code = 554
...

- only custom settings:
$ postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
...

- only one setting:
$ postconf inet_interfaces
inet_interfaces = localhost

- make changes to settings:
$ postconf -e inet_interfaces=all

Important Settings:
-------------------
myhostname           - fqdn, hostanme
disable_vrfy_command - default yes for public acc. posftix servert, to disable harvest emails
mydomain             - domain part of system's hostname
myorigin             - outgoing hostname, MUA conf. feature, if not set $myhostname
inet_interfaces      - localhost, all, if: define which hosts or domains accepts postfix inbound email for
mydestination        - default $myhostname, list of the domains that postix accepts email for
relay_domains        - if postfix is used as relay, send email to other domains
relayhost            - define relayhost option accepts the value of outbou8nd SMTP server

Aliases:
--------
- Configuration:
$ vim /etc/aliases

# Basic system aliases -- these MUST be present.
mailer-daemon:  postmaster
postmaster:     root
...
ldap:           root

# multiple system users to alias 
ldapsupport:    user1,user2,user3,user4

- Treansformation to binary db file /etc/aliases.db
$ newaliases

Postfix Virtual Domains:
------------------------
- Configuration:
$ vim /etc/postfix/virtual

# postfix inbound email for two domains
corp@sales.com   corpsales
corp@support.com corpsupport

# forward inbound email from corp@sales.com to corp@support.com
corp@sales.com   corp@support.com

$ vim /etc/postfix/main.cf
virtual_alias_maps = hash:/etc/postfix/virtual

# convert to binary form
$ postmap /etc/postfix/virtual

$ systemctl restart postfix

Sendmail:

Configure:
----------
/etc/mail/sendmail.cf
# m4 templates
/rtc/mail/sendmail.mc

Exim:

/etc/exim/exim.conf

211.2 Managing E-Mail Delivery

211.3 Managing Remote E-Mail Delivery

212.1 Configuring a router

Configuring:
------------
- IPv4 temporary set ip_forwarding

$ cat /proc/sys/net/ipv4/ip_forward
0

$ echo 1 > /proc/sys/net/ipv4/ip_forward
1

$ sysctl  -a | grep -i --color ip_forward
net.ipv4.ip_forward = 1

- IPv4 permanent set ip_forwarding

$ vim /etc/sysctl.conf
  net.ipv4.ip_forward = 1

- IPv6 temporary set forwarding
$ cat /proc/sys/net/ipv6/conf/all/forwarding
0

$ echo 1 > /proc/sys/net/ipv6/conf/all/forwarding

- IPv6 permanent set forwarding
net.ipv6.conf.default.forwarding = 0

Firewall essentials:

IP Tables:
----------

incoming packet                           outgoing packet
     ^                                           ^
     |                                           |
prerouting -> routing decision -> forward -> postrouting
                     |
                     v
                   input -> process on local host -> output

IP Tables filtering points:
---------------------------
Filtering point  -  Table
- PREROUTING     |  NAT, MANGLE 
- INPUT          |  FILTER, MANGLE 
- FORWARD        |  FILTER, MANGLE 
- OUTPUT         |  FILTER, NAT, MANGLE 
- POSTROUTING    |  NAT, MANGLE 

Targets:
--------
DROP   - built-in, drop packed without any message
ACCEPT - built-in
LOG    - extension
REJECT - extension, drop packed with icmp message, e.g "Destination Port unreachable"

Basic iptables commands:

List all chains in all tables:
------------------------------
$ iptables -L --line-numbers

List all chains in table:
-------------------------
$ iptables -t filter -L --line-numbers

Add rule to chain:
------------------
Drop all packets from IP address

$ iptables -t filter -A INPUT -s 192.168.XXX.XXX -j DROP

-t, table
-A, add to chain
-s, source 
-j, jump target

Replace rule by line number:
----------------------------
$ iptables -t filter -R INPUT 1 -s 172.17.XXX.XXX -j DROP

-R, replace rule in chain INPUT, table filter
1,  rule number to replace

Delete rule by line number:
----------------------------
$ iptables -t filter -D INPUT 1

Flush all rules in chain:
-------------------------
$ iptables -t filter -F INPUT

Saving the iptables rules:
--------------------------
$ iptables-save > /etc/sysconfig/iptables

Restore iptable rules:
----------------------
$ iptables -t filter -F INPUT
$ iptables-restore < /etc/sysconfig/iptables

Redirect incoming packet to another hosts:
------------------------------------------
$ iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination  192.168.XXX.XXX:22

-j DNAT, Destination NAT

NAT:
----
$ iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Note: eth0 is connected to the internal network

Links:

212.2 Securing FTP servers

212.3 Secure shell (SSH)

SSH Server:
-----------
$ /etc/ssh/sshd_config

Configuration /etc/ssh/ssh_config:
----------------------------------
# Both
Protocol 1,2

# Multiple IF
ListenAddress 192.168.1.100:192.168.1.101

# QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG = DEBUG1, DEBUG2, DEBUG3
LogLevel INFO

# Disable Login as root
PermitRootLogin no

# Allow only
AllowUsers user1 user2 user3

# Allow everybody, deny specific users
DenyUsers user3 user4

# Deny with wildcards, all users started with lock..
DenyUsers lock*

# Allow authentication with password
PasswordAuthentication yes

# Public key authentication
PubkeyAuthentication yes

# Others

# XServer from ssh
X11Forwarding yes

# How many attemps user has to enter correct password
MaxAuthTries 6

# Skip loging for users which have empty passwords
PermitEmptyPasswords no

SSH Client utils:
-----------
# System wide configuration
$ /etc/ssh/ssh_config

# User specific
~/.ssh/config

# Fingerprint 
~/.ssh/knowing_hosts

# Log as different user
ssh -l username ssh_server
ssh username@ssh_server

Passwordless Login:
-------------------
# Generate key
$ ssh-keygen -t rsa

# Copy public key to server
$ cat ~/.ssh/id_rsa.pub | ssh user1@192.168.XXX.XXX 'cat >> /user1/.ssh/authorized_keys'
$ ssh user1@192.168.XXX.XXX 'chmod 640 /user1/.ssh/authorized_keys'
$ eval $(ssh-agent)
$ ssh-add ~/.ssh/id_rsa

212.4 Security tasks

fail2ban:
---------
- configuration
$ /etc/fail2ban/jail.conf

- custom configuration
$ touch /etc/fail2ban/jail.local
$ touch /etc/fail2ban/jail.d/01_policy.local

- parameters
bantime
maxretry
findtime
enabled
ignoreip

OpenVAS
-------

Snort
-----
modes: IDS, sniffer, packet logging

Links:

212.5 OpenVPN

$ yum install openvpn easy-rsa

Links: -wireguard

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment