Document Sample
UNIX Powered By Docstoc
					Unix Server Tools

    Guntis Barzdins
    Girts Folkmanis
     Juris Krūmiņš
              Unix Server Tools

w IP connectivity, routing
w Deamons
w Syslog
w Inetd etc.
w Cron
w Security
                   Networking Software
w Good free implementations for:
   n   DNS
         l   BIND v8/9, djbdns
   n   SMTP
         l   sendmail, qmail, postfix, exim
   n   POP/IMAP
         l   qpopper, uwimapd
   n   HTTP
         l   Apache
         l   PHP, mySQL

       “If it was hard to develop, it should be hard to install!”
         Two IP processing modes: host or router

w Manual change
         # more /proc/sys/net/ipv4/ip_forward
         # echo 1 > /proc/sys/net/ipv4/ip_forward
         # more /proc/sys/net/ipv4/ip_forward

w Use of sysctl (modify kernel parameters /proc/sys/ at runtime)
     Eg: #/sbin/sysctl net.ipv4.ip_forward
           net.ipv4.ip_forward = 1

     Eg: #/sbin/sysctl -w net.ipv4.ip_forward=0
           net.ipv4.ip_forward = 0

w Record changes in /etc/sysctl.conf (to activate after reboot)
unix sbin # sysctl -a                                              net.ipv4.conf.default.tag = 0                    net.ipv4.neigh.default.unres_qlen = 3               net.ipv4.tcp_keepalive_probes = 9           kernel.sem = 250          32000 32 128
abi.fake_utsname = 0                                               net.ipv4.conf.default.log_martians = 0           net.ipv4.neigh.default.gc_stale_time = 60           net.ipv4.tcp_keepalive_time = 7200          kernel.msgmnb = 16384
abi.trace = 0                                                      net.ipv4.conf.default.bootp_relay = 0            net.ipv4.neigh.default.delay_first_probe_time = 5   net.ipv4.ipfrag_time = 30                   kernel.msgmni = 16
abi.defhandler_libcso = 68157441                                   net.ipv4.conf.default.medium_id = 0              net.ipv4.neigh.default.base_reachable_time = 30     net.ipv4.ip_dynaddr = 0                     kernel.msgmax = 8192
abi.defhandler_lcall7 = 68157441                                   net.ipv4.conf.default.proxy_arp = 0              net.ipv4.neigh.default.retrans_time = 100           net.ipv4.ipfrag_low_thresh = 196608         kernel.shmmni = 4096
abi.defhandler_elf = 0                                             net.ipv4.conf.default.accept_source_route = 1    net.ipv4.neigh.default.app_solicit = 0              net.ipv4.ipfrag_high_thresh = 262144        kernel.shmall = 2097152
abi.defhandler_coff = 117440515                                    net.ipv4.conf.default.send_redirects = 1         net.ipv4.neigh.default.ucast_solicit = 3            net.ipv4.tcp_max_tw_buckets = 16384         kernel.shmmax = 33554432
dev.rtc.max-user-freq = 64                                         net.ipv4.conf.default.rp_filter = 0              net.ipv4.neigh.default.mcast_solicit = 3            net.ipv4.tcp_max_orphans = 8192             kernel.rtsig-max = 1024
net.unix.max_dgram_qlen = 10                                       net.ipv4.conf.default.shared_media = 1           net.ipv4.tcp_westwood = 0                           net.ipv4.tcp_synack_retries = 5             kernel.rtsig-nr = 0
net.ipv4.ip_conntrack_max = 8184                                   net.ipv4.conf.default.secure_redirects = 1       net.ipv4.ipfrag_secret_interval = 600               net.ipv4.tcp_syn_retries = 5                kernel.hotplug = /sbin/hotplug
net.ipv4.netfilter.ip_conntrack_generic_timeout = 600              net.ipv4.conf.default.accept_redirects = 1       net.ipv4.tcp_low_latency = 0                        net.ipv4.ip_nonlocal_bind = 0               kernel.modprobe = /sbin/modprobe
net.ipv4.netfilter.ip_conntrack_icmp_timeout = 30                  net.ipv4.conf.default.mc_forwarding = 0          net.ipv4.tcp_frto = 0                               net.ipv4.ip_no_pmtu_disc = 0                kernel.printk = 1       4    1   7
net.ipv4.netfilter.ip_conntrack_udp_timeout_stream = 180           net.ipv4.conf.default.forwarding = 0             net.ipv4.tcp_tw_reuse = 0                           net.ipv4.ip_autoconfig = 0                  kernel.ctrl-alt-del = 0
net.ipv4.netfilter.ip_conntrack_udp_timeout = 30                   net.ipv4.conf.all.force_igmp_version = 0         net.ipv4.icmp_ratemask = 6168                       net.ipv4.ip_default_ttl = 64                kernel.real-root-dev = 256
net.ipv4.netfilter.ip_conntrack_tcp_timeout_close = 10             net.ipv4.conf.all.arp_ignore = 0                 net.ipv4.icmp_ratelimit = 100                       net.ipv4.ip_forward = 0                     kernel.cap-bound = -257
net.ipv4.netfilter.ip_conntrack_tcp_timeout_time_wait = 120        net.ipv4.conf.all.arp_announce = 0               net.ipv4.tcp_adv_win_scale = 2                      net.ipv4.tcp_retrans_collapse = 1           kernel.tainted = 0
net.ipv4.netfilter.ip_conntrack_tcp_timeout_last_ack = 30          net.ipv4.conf.all.arp_filter = 0                 net.ipv4.tcp_app_win = 31                           net.ipv4.tcp_sack = 1                       kernel.core_pattern = core
net.ipv4.netfilter.ip_conntrack_tcp_timeout_close_wait = 60        net.ipv4.conf.all.tag = 0                        net.ipv4.tcp_rmem = 4096         87380 174760       net.ipv4.tcp_window_scaling = 1             kernel.core_setuid_ok = 0
net.ipv4.netfilter.ip_conntrack_tcp_timeout_fin_wait = 120         net.ipv4.conf.all.log_martians = 0               net.ipv4.tcp_wmem = 4096          16384 131072      net.ipv4.tcp_timestamps = 1                 kernel.core_uses_pid = 0
net.ipv4.netfilter.ip_conntrack_tcp_timeout_established = 432000   net.ipv4.conf.all.bootp_relay = 0                net.ipv4.tcp_mem = 23552         24064 24576        net.core.somaxconn = 128                    kernel.panic = 0
net.ipv4.netfilter.ip_conntrack_tcp_timeout_syn_recv = 60          net.ipv4.conf.all.medium_id = 0                  net.ipv4.tcp_dsack = 1                              net.core.hot_list_length = 128              kernel.domainname = (none)
net.ipv4.netfilter.ip_conntrack_tcp_timeout_syn_sent = 120         net.ipv4.conf.all.proxy_arp = 0                  net.ipv4.tcp_ecn = 0                                net.core.optmem_max = 10240                 kernel.hostname = unix
net.ipv4.netfilter.ip_conntrack_buckets = 1023                     net.ipv4.conf.all.accept_source_route = 0        net.ipv4.tcp_reordering = 3                         net.core.message_burst = 50                 kernel.version = #1 Thu Sep 23 14:41:14 EEST 2004
net.ipv4.netfilter.ip_conntrack_max = 8184                         net.ipv4.conf.all.send_redirects = 1             net.ipv4.tcp_fack = 1                               net.core.message_cost = 5                   kernel.osrelease = 2.4.26-gentoo-r9
net.ipv4.conf.eth0.force_igmp_version = 0                          net.ipv4.conf.all.rp_filter = 0                  net.ipv4.tcp_orphan_retries = 0                     net.core.mod_cong = 290                     kernel.ostype = Linux
net.ipv4.conf.eth0.arp_ignore = 0                                  net.ipv4.conf.all.shared_media = 1               net.ipv4.inet_peer_gc_maxtime = 120                 net.core.lo_cong = 100             = 45
net.ipv4.conf.eth0.arp_announce = 0                                net.ipv4.conf.all.secure_redirects = 1           net.ipv4.inet_peer_gc_mintime = 10                  net.core.no_cong = 20                       fs.dir-notify-enable = 1
net.ipv4.conf.eth0.arp_filter = 0                                  net.ipv4.conf.all.accept_redirects = 1           net.ipv4.inet_peer_maxttl = 600                     net.core.no_cong_thresh = 10                fs.leases-enable = 1
net.ipv4.conf.eth0.tag = 0                                         net.ipv4.conf.all.mc_forwarding = 0              net.ipv4.inet_peer_minttl = 120                     net.core.netdev_max_backlog = 300           fs.overflowgid = 65534
net.ipv4.conf.eth0.log_martians = 0                                net.ipv4.conf.all.forwarding = 0                 net.ipv4.inet_peer_threshold = 65664                net.core.dev_weight = 64                    fs.overflowuid = 65534
net.ipv4.conf.eth0.bootp_relay = 0                                 net.ipv4.neigh.eth0.locktime = 100               net.ipv4.igmp_max_msf = 10                          net.core.rmem_default = 106496              fs.dentry-state = 1640 1438 45 0         0   0
net.ipv4.conf.eth0.medium_id = 0                                   net.ipv4.neigh.eth0.proxy_delay = 80             net.ipv4.route.secret_interval = 600                net.core.wmem_default = 106496              fs.file-max = 13100
net.ipv4.conf.eth0.proxy_arp = 0                                   net.ipv4.neigh.eth0.anycast_delay = 100          net.ipv4.route.min_adv_mss = 256                    net.core.rmem_max = 106496                  fs.file-nr = 140      37 13100
net.ipv4.conf.eth0.accept_source_route = 1                         net.ipv4.neigh.eth0.proxy_qlen = 64              net.ipv4.route.min_pmtu = 552                       net.core.wmem_max = 106496                  fs.inode-state = 1443 18 0         0   0   0    0
net.ipv4.conf.eth0.send_redirects = 1                              net.ipv4.neigh.eth0.unres_qlen = 3               net.ipv4.route.mtu_expires = 600                    vm.block_dump = 0                           fs.inode-nr = 1443 18
net.ipv4.conf.eth0.rp_filter = 1                                   net.ipv4.neigh.eth0.gc_stale_time = 60           net.ipv4.route.gc_elasticity = 8                    vm.laptop_mode = 0                          unix sbin #
net.ipv4.conf.eth0.shared_media = 1                                net.ipv4.neigh.eth0.delay_first_probe_time = 5   net.ipv4.route.error_burst = 500                    vm.max_map_count = 65536
net.ipv4.conf.eth0.secure_redirects = 1                            net.ipv4.neigh.eth0.base_reachable_time = 30     net.ipv4.route.error_cost = 100                     vm.max-readahead = 31
net.ipv4.conf.eth0.accept_redirects = 1                            net.ipv4.neigh.eth0.retrans_time = 100           net.ipv4.route.redirect_silence = 2048              vm.min-readahead = 3
net.ipv4.conf.eth0.mc_forwarding = 0                               net.ipv4.neigh.eth0.app_solicit = 0              net.ipv4.route.redirect_number = 9         = 3
net.ipv4.conf.eth0.forwarding = 0                                  net.ipv4.neigh.eth0.ucast_solicit = 3            net.ipv4.route.redirect_load = 2                    vm.pagetable_cache = 25 50
net.ipv4.conf.lo.force_igmp_version = 0                            net.ipv4.neigh.eth0.mcast_solicit = 3            net.ipv4.route.gc_interval = 60                     vm.kswapd = 512 32 8
net.ipv4.conf.lo.arp_ignore = 0                                    net.ipv4.neigh.lo.locktime = 100                 net.ipv4.route.gc_timeout = 300                     vm.overcommit_memory = 0
net.ipv4.conf.lo.arp_announce = 0                                  net.ipv4.neigh.lo.proxy_delay = 80               net.ipv4.route.gc_min_interval = 0                  vm.bdflush = 50 500 0         0   500 3000 60 20 0
net.ipv4.conf.lo.arp_filter = 0                                    net.ipv4.neigh.lo.anycast_delay = 100            net.ipv4.route.max_size = 8192                      vm.vm_passes = 60
net.ipv4.conf.lo.tag = 0                                           net.ipv4.neigh.lo.proxy_qlen = 64                net.ipv4.route.gc_thresh = 512                      vm.vm_lru_balance_ratio = 2
net.ipv4.conf.lo.log_martians = 0                                  net.ipv4.neigh.lo.unres_qlen = 3                 net.ipv4.route.max_delay = 10                       vm.vm_mapped_ratio = 100
net.ipv4.conf.lo.bootp_relay = 0                                   net.ipv4.neigh.lo.gc_stale_time = 60             net.ipv4.route.min_delay = 2                        vm.vm_cache_scan_ratio = 6
net.ipv4.conf.lo.medium_id = 0                                     net.ipv4.neigh.lo.delay_first_probe_time = 5     net.ipv4.icmp_ignore_bogus_error_responses = 0      vm.vm_vfs_scan_ratio = 6
net.ipv4.conf.lo.proxy_arp = 0                                     net.ipv4.neigh.lo.base_reachable_time = 30       net.ipv4.icmp_echo_ignore_broadcasts = 0            vm.vm_gfp_debug = 0
net.ipv4.conf.lo.accept_source_route = 1                           net.ipv4.neigh.lo.retrans_time = 100             net.ipv4.icmp_echo_ignore_all = 0                   kernel.lowlatency = 0
net.ipv4.conf.lo.send_redirects = 1                                net.ipv4.neigh.lo.app_solicit = 0                net.ipv4.ip_local_port_range = 1024 4999            kernel.overflowgid = 65534
net.ipv4.conf.lo.rp_filter = 0                                     net.ipv4.neigh.lo.ucast_solicit = 3              net.ipv4.tcp_max_syn_backlog = 256                  kernel.overflowuid = 65534
net.ipv4.conf.lo.shared_media = 1                                  net.ipv4.neigh.lo.mcast_solicit = 3              net.ipv4.tcp_rfc1337 = 0                            kernel.random.uuid = 5784cebf-b4c1-4e2d-b60c-c8ed66b10136
net.ipv4.conf.lo.secure_redirects = 1                              net.ipv4.neigh.default.gc_thresh3 = 1024         net.ipv4.tcp_stdurg = 0                             kernel.random.boot_id = 65fcbb7e-b4c3-452f-8d98-dc7ac3d67ea6
net.ipv4.conf.lo.accept_redirects = 1                              net.ipv4.neigh.default.gc_thresh2 = 512          net.ipv4.tcp_abort_on_overflow = 0                  kernel.random.write_wakeup_threshold = 128
net.ipv4.conf.lo.mc_forwarding = 0                                 net.ipv4.neigh.default.gc_thresh1 = 128          net.ipv4.tcp_tw_recycle = 0                         kernel.random.read_wakeup_threshold = 8
net.ipv4.conf.lo.forwarding = 0                                    net.ipv4.neigh.default.gc_interval = 30          net.ipv4.tcp_syncookies = 0                         kernel.random.entropy_avail = 772
net.ipv4.conf.default.force_igmp_version = 0                       net.ipv4.neigh.default.locktime = 100            net.ipv4.tcp_fin_timeout = 60                       kernel.random.poolsize = 512
net.ipv4.conf.default.arp_ignore = 0                               net.ipv4.neigh.default.proxy_delay = 80          net.ipv4.tcp_retries2 = 15                          kernel.threads-max = 2047
net.ipv4.conf.default.arp_announce = 0                             net.ipv4.neigh.default.anycast_delay = 100       net.ipv4.tcp_retries1 = 3                           kernel.cad_pid = 1
net.ipv4.conf.default.arp_filter = 0                               net.ipv4.neigh.default.proxy_qlen = 64           net.ipv4.tcp_keepalive_intvl = 75                   kernel.sysrq = 1

w ifconfig eth0 netmask up
w ifconfig
eth0      Link encap:Ethernet  HWaddr 00:80:C8:F8:4A:51
          inet addr:  Bcast:  
          RX packets:190312 errors:0 dropped:0 overruns:0 frame:0
          TX packets:86955 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100 
          RX bytes:30701229 (29.2 Mb)  TX bytes:7878951 (7.5 Mb)
          Interrupt:9 Base address:0x5000
               Netstat: routing, sockets
Routing table:
     [root@morgan]# netstat -rn
     Kernel IP routing table
     Destination     Gateway          Genmask         Flags   MSS   Window   irtt   Iface   U        40   0           0   eth0       U        40   0           0   lo         UG       40   0           0   eth0

IP socket status:
     [root@morgan]# netstat --inet -n
     Active Internet connections (w/o servers)
     Proto Recv-Q Send-Q Local Address            Foreign Address            State
     tcp        0    192        ESTABLISHED
     tcp        0      0         ESTABLISHED
     tcp       96      0             ESTABLISHED
     tcp        0      0             ESTABLISHED
     tcp        0      0             ESTABLISHED
     tcp        0      0             ESTABLISHED
     tcp        0      0            SYN_SENT
     tcp        0      0         ESTABLISHED
     tcp        0      0         TIME_WAIT
                                           Security Hardening

Recommended IP/ICMP Settings
w Disable Ping
      # sysctl –w net.ipv4.icmp_echo_ignore_all=1
w Disable ICMP Echo Requests
   # sysctl –w net.ipv4.icmp_echo_ignore_broadcasts=1
w Disable IP Source Routing
   # sysctl –w net.ipv4.conf.all.accept_source_route=0
w Disable ICMP Redirects
   # sysctl –w net.ipv4.conf.all.accept_redirects=0
w Enable TCP SYN Cookie Protection
   # sysctl –w net.ipv4.tcp_syncookies=1
w Disable Bogus Error Logging
   # sysctl –w net.ipv4.icmp_ignore_bogus_error_responses=1
w Enable Packet Logging
   # sysctl –w net.ipv4.conf.all.log_martians=1
                configure domain name
wIn Linux resolver has 2 config files
  n   /etc/hosts   specifies static mappings
      185.300.10.1    host1
      185.300.10.2    host2
      185.300.10.3    host3
      185.300.10.4    host4 merlin
      185.300.10.5    host5 arthur king
      185.300.10.5    timeserver       name1
  n   /etc/resolv.conf     specifies the nameservers and the default domain
Popular Routing Protocols
   Setting Up Network Interface Cards FreeBSD
w Configuring the Network Card
   Once the right driver is loaded for the network card, the card needs to be configured. As with many
   other things, the network card may have been configured at installation time by sysinstall. To
   display the configuration for the network interfaces on your system, enter the following command:
    juriskr >ifconfig
    fxp0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
           inet netmask 0xffffff00 broadcast
           inet netmask 0xffffffff broadcast
           inet netmask 0xffffffff broadcast
           inet netmask 0xffffffff broadcast
           inet netmask 0xffffffff broadcast
           ether 00:02:55:c8:45:aa
           media: Ethernet autoselect (100baseTX <full-duplex>)
           status: active
    ppp0: flags=8010<POINTOPOINT,MULTICAST> mtu 1500
    sl0: flags=c010<POINTOPOINT,LINK2,MULTICAST> mtu 552
    lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
           inet netmask 0xff000000
   To configure your card, you need root privileges. The network card configuration can be done from
   the command line with ifconfig(8) but you would have to do it after each reboot of the system. The
   file /etc/rc.conf is where to add the network card's configuration.
     juriskr >cat /etc/rc.conf | grep ifconfig
    ifconfig_fxp0="inet netmask"
    ifconfig_fxp0_alias0="inet netmask"
    ifconfig_fxp0_alias1="inet netmask"
    ifconfig_fxp0_alias2="inet netmask"
    ifconfig_fxp0_alias3="inet netmask"
    Setting Up Network Interface Cards FreeBSD
w Virtual Hosts
  A very common use of FreeBSD is virtual site hosting, where one server appears to the
  network as many servers. This is achieved by assigning multiple network addresses to a
  single interface. A given network interface has one “real” address, and may have any
  number of “alias” addresses. These aliases are normally added by placing alias entries in
  /etc/rc.conf. An alias entry for the interface fxp0 looks like:

    ifconfig_fxp0_alias0="inet netmask“

    Note that alias entries must start with alias0 and proceed upwards in order, (for example,
    _alias1, _alias2, and so on). The configuration process will stop at the first missing

     ifconfig_fxp0_alias0="inet netmask"
     ifconfig_fxp0_alias1="inet netmask"
     ifconfig_fxp0_alias2="inet netmask"
     ifconfig_fxp0_alias3="inet netmask"
    Setting Up Network Interface Cards FreeBSD
w   Testing and Troubleshooting
     n    Testing the Ethernet Card
            l   To verify that an Ethernet card is configured correctly, you have to try two things. First, ping the interface
                itself, and then ping another machine on the LAN.
            l   First test the local interface:
                    juriskr >ping -c 3
                   PING ( 56 data bytes
                   64 bytes from icmp_seq=0 ttl=64 time=0.054 ms
                   64 bytes from icmp_seq=1 ttl=64 time=0.050 ms
                   64 bytes from icmp_seq=2 ttl=64 time=0.066 ms

                 --- ping statistics ---
                 3 packets transmitted, 3 packets received, 0% packet loss
                 round-trip min/avg/max/stddev = 0.050/0.057/0.066/0.007 ms
            l   Now we have to ping another machine on the LAN:
                 juriskr >ping
                 PING ( 56 data bytes
                 64 bytes from icmp_seq=0 ttl=64 time=0.381 ms
                 64 bytes from icmp_seq=1 ttl=64 time=0.188 ms
                 64 bytes from icmp_seq=2 ttl=64 time=0.178 ms
                 --- ping statistics ---
                 3 packets transmitted, 3 packets received, 0% packet loss
                 round-trip min/avg/max/stddev = 0.178/0.249/0.381/0.093 ms
            l   You could also use the machine name instead of IP address if you have set up the /etc/hosts file.
                        Ifconfig output RHEL
[juris@ns1 ~]$ ifconfig
eth0 Link encap:Ethernet HWaddr 00:0B:CD:41:F4:93
       inet Mask:
       inet6 addr: fe80::20b:cdff:fe41:f493/64 Scope:Link
       RX packets:473091457 errors:0 dropped:0 overruns:0 frame:0
       TX packets:488547237 errors:0 dropped:0 overruns:0 carrier:0
       collisions:0 txqueuelen:1000
       RX bytes:3458689275 (3.2 GiB) TX bytes:3985927941 (3.7 GiB)

eth0:1 Link encap:Ethernet HWaddr 00:0B:CD:41:F4:93
      inet Mask:

lo     Link encap:Local Loopback
      inet addr: Mask:
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING MTU:16436 Metric:1
      RX packets:6004400 errors:0 dropped:0 overruns:0 frame:0
      TX packets:6004400 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0
      RX bytes:645400309 (615.5 MiB) TX bytes:645400309 (615.5 MiB)

[juris@ns1 ~]$

A daemon is a process that:
  n runs in the background
  n not associated with any terminal

      l output doesn't end up in another session.
      l terminal generated signals (^C) aren't
           Unix and Daemons

w Unix systems typically have many daemon

w Most servers run as a daemon process.
             Common Daemons

w Web server (httpd)
w Mail server (sendmail)
w SuperServer (inetd)
w System logging (syslogd)
w Print server (lpd)
w router process (routed, gated)
                     Daemon Output

w No terminal - must use something else:
   n   file system
   n   central logging facility

w Syslog is often used - provides central repository
  for system logging.
                     Syslog service

w syslogd daemon provides system logging
  services to "clients".

w Simple API for "clients"
   n   A library provided by O.S.
     Sending a message to syslogd

w Standard programming interface provided by
  syslog() function:

#include <syslog.h>
void syslog( int priority, 
             const char *message,
             . . . );

w Works like printf()
Unix domain socket

 UDP socket
  port 514            syslogd
                      syslogd        Console

                                Remote syslogd
                  Syslog messages
w Think of syslog as a server that accepts messages.
w Each message includes a number of fields, including:
   n   a level indicating the importance (8 levels)
        l   LOG_EMERG  0          kernel panic
        l   LOG ALERT  1          condition needing immediate attention
        l   LOG_CRIT  2           critical conditions
        l   LOG_ERR    3          errors
        l   LOG_WARNING 4         warning messages
        l   LOG_NOTICE 5          not an error, but may need attention
        l   LOG_INFO  6           informational messages
        l   LOG_DEBUG  7          when debugging a system
       Syslog message fields (cont.)

w a facility that indicates the type of process that sent the
       LOG_KERN, LOG_LPR, . . .

w Timestamp (added by syslogd)
w uname –n (added by syslogd)
w A text string.
                               Logfile example

Dec 27 02:45:00 netinfod [71]: cann’t lookup child
Dec 27 02:50:00    bruno ftpd [27876]: open of pid file failed: not a directory
Dec 27 02:50:47    anchor vmunix: spurious VME interrupt at processor level 5
Dec 27 02:52:17    bruno pingem[107]: has not answered 34 times
Dec 27 02:55:33    bruno sendmail [28040] : host name/address mismatch: !=
    / * c program: syslog using openlog and closelog */

    #include <syslog.h>
    main ( )
           openlog ( “SA-BOOK”, LOG_PID, LOG_USER);
           syslog ( LOG_WARNING, “Testing …. “);
           closelog ( );

On the host, this code produce the following log entry:

Dec 28 17:23:49 SA-BOOK [84]: Testing...
                            Log files

w Log files are normally kept in /var/log
  (setings in /etc/syslog.conf “/etc/init.d/syslog restart”)
w Read them
w Syslog logs the system and what is happening on it
w Logcheck is a handy utility which checks the contents of
  logs and mails anything unusual
               Back to daemons

w To force a process to run in the background, just
  fork() and have the parent exit.
w There are a number of ways to disassociate a
  process from any controlling terminal.
   n Call setsid() and then fork() again.
            Daemon initialization

w Daemons should close all unnecessary
   n   often including stdin, stdout, stderr.
w Get set up for using syslog
   n   Call openlog()

• Often change working directory.
           Too many daemons?

w There can be many servers running as daemons -
  and idle most of the time.
w Much of the startup code is the same for these
w Most of the servers are asleep most of the time,
  but use up space in the process table.
                       Internet Daemon
    w Daemon inetd started at boot time
    w Configuration file /etc/inetd.conf
       n   Name, type, protocol, wait-status, uid, server,
ftp     stream  tcp6    nowait  root    /usr/sbin/tcpd  in.ftpd
telnet  stream  tcp6    nowait  root    /usr/sbin/tcpd  in.telnetd
# Mail is a useful thing...
pop3    stream  tcp     nowait  root    /etc/mail/popper        popper -s
imap    stream  tcp     nowait  root    /etc/mail/imapd         imapd
                   Internet Daemon

w When to modify inetd.conf
  n   Disable a service
      l Add a # at the beginning of the entry
      l Send hang-up to inetd
          kill –HUP processid
  n   Enable a service
  n   Change the path
  n   Modify arguments
w The SuperServer is named inetd. This single
  daemon creates multiple sockets and waits for
  (multiple) incoming requests.
w inetd typically uses select to watch
  multiple sockets for input.
w When a request arrives, inetd will fork and
  the child process handles the client.
             inetd children
w The child process closes all unnecessary

w The child dup’s the client socket to descriptors
  0,1 and 2 (stdin, stdout, stderr).

w The child exec’s the real server program, which
  handles the request and exits.

descriptor    used for     default
       0   standard input  keyboard
       1   standard output screen
       2   standard error   screen
        inetd based servers
w Servers that are started by inetd assume that
  the socket holding the request is already
  established (descriptors 0,1 or 2).

w TCP servers started by inetd don’t call
  accept, so they must call getpeername if
  they need to know the address of the client.
w inetd reads a configuration file that lists all
  the services it should handle.

w inetd creates a socket for each listed
  service, and adds the socket to a fd_set
  given to select().
       inetd service specification

w For each service, inetd needs to know:
  n   the port number and transport protocol
  n   wait/nowait flag.
  n   login name the process should run as.
  n   pathname of real server program.
  n   command line arguments to server program.
       example /etc/inetd.conf
# comments start with #
echo     stream  tcp  nowait  root  internal
echo     dgram   udp        wait    root  internal
chargen  stream  tcp        nowait  root  internal
chargen  dgram   udp        wait    root  internal
ftp      stream  tcp        nowait  root  /usr/sbin/ftpd ftpd -l
telnet   stream  tcp  nowait  root  /usr/sbin/telnetd telnetd
finger   stream  tcp        nowait  root  /usr/sbin/fingerd fingerd
# Authentication
auth     stream  tcp  nowait  nobody  /usr/sbin/in.identd in.identd -l -e -o
tftp       dgram   udp      wait    root   /usr/sbin/tftpd tftpd -s /tftpboot
          example /etc/services
ftp 21/tcp # File Transfer Protocol
telnet 23/tcp # Telnet
smtp 25/tcp # Simple Mail Transfer Protocol
tftp 69/udp # Trivial File Transfer Protocol
www 80/tcp # World Wide Web
ntp 123/tcp # Network Time Protocol
ntp 123/udp # Network Time Protocol

w Specifying WAIT means that inetd should not
  look for new clients for the service until the child
  (the real server) has terminated.
w TCP servers usually specify nowait - this means
  inetd can start multiple copies of the TCP server
  program - providing concurrency!
          UDP & wait/nowait
w Most UDP services run with inetd told to wait
  until the child server has died.

w Some UDP servers hang out for a while, handling
  multiple clients before exiting.

w inetd was told to wait – so it ignores the socket
  until the UDP server exits.
                  Super inetd

w Some versions of inetd have server code to
  handle simple services such as
     echo server,
     daytime server,

w Servers that are expected to deal with frequent
  requests are typically not run from inetd: mail,
  web, NFS.

w Many servers are written so that a command line
  option can be used to run the server from inetd.

w Some versions of Unix provide a service very
  similar to inetd called xinetd.
   n   configuration scheme is different
   n   basic idea (functionality) is the same…
            example /etc/xinetd.d
# typical xinetd.conf
        instances               = 60
        log_type                = SYSLOG daemon
        log_on_success          = HOST PID
        log_on_failure          = HOST
        cps                     = 25 30
includedir /etc/xinetd.d

root# ls /etc/xinetd.d
chargen      daytime-udp  finger       shell        time-udp
chargen-udp  echo         ftp          telnet

root# cat /etc/xinetd.d/telnet
service telnet
        disable         = yes
        socket_type     = stream
        wait            = no
        user            = root
        server          = /usr/libexec/telnetd
        groups          = yes
        flags           = REUSE
        access_times    = 8:00-18:00
        only_from       =
                    The Superservers

w Superservers listen on multiple network ports and start
  the appropriate service when a client connection arrives
  for that port.
w xinetd is a superserver gaining popularity
   n   It is a revised version of inetd that creates a more secure
   n   Shipped with Red Hat Linux
w xinetd lately is the most widely used superserver
   n   Application level security is provided via TCP Wrappers - the
       tcpd program
                                               Managing Services

w Network Services
    - Stand alone vs Inetd

w The Inetd Model
    - Network Super Daemon
    - /etc/services : Maps the name of the service to a port number.
   eg: ulistserv 372/tcp ulistproc
    - /etc/inetd.conf : Main Configuration file for inetd.
   eg: ftp stream tcp nowait root /usr/sbin/tcpd proftpd

w The Xinetd Model
    - Advanced Replacement for inetd
    - More Secure and flexible with Advanced Access Control Mechanisms
    - /etc/xinetd.conf : Main Configuration file for xinetd
    - /etc/xinetd.d/ : Contains files for services managed by xinetd
                                          Managing Services

w Managing Services in Inetd and Xinetd
     - For Inetd : Comment out corresponding service from inetd.conf
     - Restart Inetd
        # pkill –HUP inetd
    - For Xinetd : Make changes in xinetd.conf and xinetd.d
      - Access control Mechanisms for services can be specified
        # /etc/rc.d/init.d/xinetd restart

w Typical Services to be Blocked
     - Finger, rwho, rsh , rlogin, rexec, echo, ntalk
     - FTP, Telnet
     - Use ssh, scp, sftp

w There are 65535 ports available
w Services tend to use <1024
   n   These are “priviledged” ports, only root may listen on them
w If you have something running under a port you don't
   n   Find out what it is
   n   Decide if you need it
                          Useful Tools

w Netstat -an
   n   tells you what connections are active
w Netstat -lp
   n   tells which ports are listening
w ps -ef
   n   lists the running process
w chkrootkit
   n   checks for signs of rootkits
   n   Common rootkits install trojaned tools
      Scheduling processes - cron

n   Many aspects of system administration require things to be
    done on a routine basis
     l   Rotating logs
     l   building help files
     l   checking disk space
     l   checking permissions
n   Remembering to do thing is error prone
n   Unix provides scheduling mechanism refereed to as cron.
n   Cron has two parts
     l   Daemon - crond
     l   table of actions /etc/crontab

w the crond Daemon is started at boot time
w the daemon ‘wakes up’ every minute to check its
  table of actions
   n   if their is something to do -> run command
   n   if nothing to do --> go back to sleep for 1 min
w Cron table is a list (time,commnd) pairs. The
  format is
w minute hour day month dayofweek command
w Commands can be scheduled by
      l   minute (0 59)
      l   Hour ( 0 to 23)
      l   Day of the month (1 - 31)
      l   Month ( 1 to 12)
      l   Day of the week (0=Sunday 6 = sat, or use mon,tues,wed)
w Example
      01 * * * *          commnd2   # hourly at 1 minute past
      * 1 * * *           commnd2   # daily at 1 am
      04 1 * * *          commands 3 - run at 4 minute past
                                      1 each day
  * means ‘check every’

w Under Redhat Linux the cron table is used to execute a
  set of commands in some special directories
   n   /etc/cron.hourly
   n   /etc/cron.daily
        l   contains logrotate, makewhatis,slocate,tmpwatch
   n   /etc/cron.weekly
   n   /etc/cron.monthly
        l   You can add you own commands to the appropriate directory,
            but remember they need to be ‘batch’ commands as they will run
                        Crontab Files

w   Minute 0-59
w   Hour 0-23
w   Day 1-31
w   Month 1-12
w   Weekday 0-6 (0=Sunday)
    n   * Matches everything
    n   1-3 Matches range
    n   1,5 Matches Series
15,45 10 * * 1-5 write garth % Hi Garth % get a job
30 2 * * 1 (cd /user/joe/p; make)
find /tmp –atime +3 –exec rm –f {} ‘;’

w Output mailed to owner of crontab file
            crontab commands

w crontab        Replace ^C exit
w crontab    –l List
w crontab    –e Edit
w crontab    –l > cronfile
w crontab    cronfile
  n   cron.allow
  n   cron.deny
         Common Uses for CRON

w Cleaning the filesystem
w Distribution of config files
w Rotating log files
w Backups
                The cron utility

w The cron utility runs in the background and
  constantly checks the /etc/crontab file.
w The cron utility also checks the /var/cron/tabs
  directory, in search of new crontab files. These
  crontab files store information about specific
  functions which cron is supposed to perform at
  certain times.
                  The cron utility

w The cron utility uses two different types of configuration
  files, the system crontab and user crontabs.
w The only difference between these two formats is the
  sixth field. In the system crontab, the sixth field is the
  name of a user for the command to run as. This gives the
  system crontab the ability to run commands as any user.
  In a user crontab, the sixth field is the command to run,
  and all commands run as the user who created the
  crontab; this is an important security feature.
                     The cron utility
# /etc/crontab - root's crontab for FreeBSD #
# $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $
SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/var/log
#minute hour mday month wday who command
*/5 * * * * root /usr/libexec/atrun
                              The cron utility
n   Like most FreeBSD configuration files, the # character represents a comment. A comment can
    be placed in the file as a reminder of what and why a desired action is performed. Comments
    cannot be on the same line as a command or else they will be interpreted as part of the
    command; they must be on a new line. Blank lines are ignored.
n   First, the environment must be defined. The equals (=) character is used to define any
    environment settings, as with this example where it is used for the SHELL, PATH, and HOME
    options. If the shell line is omitted, cron will use the default, which is sh. If the PATH variable is
    omitted, no default will be used and file locations will need to be absolute. If HOME is omitted,
    cron will use the invoking users home directory.
n   This line defines a total of seven fields. Listed here are the values minute, hour, mday, month,
    wday, who, and command. These are almost all self explanatory. minute is the time in minutes
    the command will be run. hour is similar to the minute option, just in hours. mday stands for day
    of the month. month is similar to hour and minute, as it designates the month. The wday option
    stands for day of the week. All these fields must be numeric values, and follow the twenty-four
    hour clock. The who field is special, and only exists in the /etc/crontab file. This field specifies
    which user the command should be run as. When a user installs his or her crontab file, they will
    not have this option. Finally, the command option is listed. This is the last field, so naturally it
    should designate the command to be executed.
n   This last line will define the values discussed above. Notice here we have a */5 listing, followed
    by several more * characters. These * characters mean “first-last”, and can be interpreted as
    every time. So, judging by this line, it is apparent that the atrun command is to be invoked by
    root every five minutes regardless of what day or month it is. For more information on the atrun
    command, see the atrun(8) manual page.
n   Commands can have any number of flags passed to them; however, commands which extend
    to multiple lines need to be broken with the backslash “\” continuation character.
                          The cron utility

w Installing a Crontab
    n   Important: You must not use the procedure described here to edit/install
        the system crontab. Simply use your favorite editor: the cron utility will
        notice that the file has changed and immediately begin using the updated
    n   To install a freshly written user crontab, first use your favorite editor to
        create a file in the proper format, and then use the crontab utility.
    n   For users who wish to begin their own crontab file from scratch, without the
        use of a template, the crontab -e option is available. This will invoke the
        selected editor with an empty file. When the file is saved, it will be
        automatically installed by the crontab command.
    n   If you later want to remove your user crontab completely, use crontab with
        the -r option.
Unix Security
                Security Hardening : Access Control

TCP Wrappers

w   Effective Access Control Mechanism
w   Invisible Layer to Block or Permit Access to Services
w   Hostname, IPAddresses, Logging
w   /etc/hosts.allow
w   /etc/hosts.deny
                    TCP Wrappers

w TCP Wrappers - tcpd - is an application-level
  access control program
   n   TCP Wrappers is not a firewall and should be used
       with one if Linux security issues exist
   n   Configuration is done by two files: /etc/hosts.allow and
   n   Ensure proper and expected configuration by testing
       carefully before relying on it

TCP Wrappers

TCP Wrappers

             Security Hardening : Access Control
w   What is a Firewall?
w   Access control policy
w   Isolates networks
w   Packet Filtering

w Chains (Input, Output, Forward)
w Targets (Accept, Drop, Reject, Log)
w Efficient Packet Filtering based on protocols, IP Address,
  state/stateless etc
    # iptables -A INPUT -s -j DROP
                 Security tools

w Security tool (Bastille / Titan / JASS)
w Host intrusion detection system (LIDS / Tripwire)
      Linux Packet Filtering types

w Ipfw (Linux 1.2 kernels)
w Ipfwadm (Linux 2.0 kernels)
w Ipchains (Linux 2.2 kernels)
w Iptables (Linux 2.4 kernels)
w Iptables (Linux 2.6 kernels)
       Iptables log and rule format
Apr 30 21:04:10 sparrow kernel: IN= OUT=lo
  SRC= DST= LEN=73 TOS=0x00
  PREC=0x00 TTL=64 ID=11339 DF PROTO=UDP
  SPT=33272 DPT=53 LEN=53

/sbin/iptables –A OUTPUT –o lo –p udp –s localhost/32 - -
   sport 1024:65535 –d localhost/32 - -dport domain –j
   ACCEPT #domain/udp (O)
              Iptables Rules:
    Allow SSH to the bridge machine itself

iptables –A INPUT –p tcp –d \
-–dport 22 –j ACCEPT

iptables –A INPUT –i eth0 –m state \

iptables –A INPUT –i lo –j ACCEPT

iptables –P INPUT DROP
           Iptables Rules:
Allow TCP through the bridge, feed to Snort

iptables –A FORWARD –m state \

iptables –A FORWARD –p tcp –m state \
w Modem connections/DHCP
w Doesn’t drop connections when address changes
w Makes all packets from internal look like they are
  coming from the modem machine/DHCP address
  (outgoing interface’s address):

  echo 1 > /proc/sys/net/ipv4/ip_forward
  modprobe iptable_nat
  iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
      Configuring NAT with iptable
w First example:
  iptables –t nat –A POSTROUTING –s
                –j SNAT --to-source
w Pooling of IP addresses:
  iptables –t nat –A POSTROUTING –s
                –j SNAT --to-source–
w ISP migration:
  iptables –t nat –R POSTROUTING –s
                –j SNAT --to-source–
w IP masquerading:
  iptables –t nat –A POSTROUTING –s
                –o eth1 –j MASQUERADE
w Load balancing:
  iptables -t nat -A PREROUTING -i eth1 -j DNAT --to-
          Configuring NAT in Linux
w Linux uses the Netfilter/iptable package to add filtering rules to the
  IP module
                 Source NAT

w Translate source address

  iptables –t nat –A POSTROUTING \
  –o <outgoing-interface> -j SNAT \
  –-to-source <address>[-<address>][:port-port]

  iptables –t nat –A POSTROUTING –o eth1 \
  -J SNAT –-to-source
               Destination NAT
w Translate destination address

  iptables –t nat –A PREROUTING \
  –i <incoming-interface> -j DNAT \
  --to-destination <address>[-<address>][:port-port]

  iptables –t nat –A PREROUTING -i eth0 –p tcp \
  -d –dport 80 –j DNAT \

  iptables –t nat –A PREROUTING -i eth0 –p tcp \
  -d –dport 80 –j REDIRECT
            Load Balancing
w Source Policy Routing: Make sure Person A,
  who pays the lower rate, gets routed over the
  house modem instead of the DSL
w Split Access for Multiple Uplinks: Packets
  coming in from ISP A go back out ISP A
w Load Balancing: default route becomes a
  multipath path route, balance routes over 2
  iptables –t nat –A PREROUTING –i eth0
  –d –p tcp –-dport 80 –j DNAT
Hacked WebServer
                  Queuing Disciplines

w First-In-First-Out (FIFO)
   n   no classes
   n   fast, easy to implement
w Priority Queuing
   n   all traffic in a high-priority class is sent before any in a lower
       priority one
w Class-based Queuing (CBQ)
   n   a number of bytes is sent from each class before going to the
       next class
                 Unix Traffic Shaping

w Documentation on Linux traffic shaping is sparse
w CBQ is an interface to the Linux tc command
   n   tc (traffic control) man tc gives nothing
w Other queuing systems besides CBQ are available
        l   HBQ, TBF, SFQ
Link Sharing between CBQ
      Traffic Classes
      Link Sharing Goal

Over appropriate time-intervals,
each interior or leaf class should
 receive its allocated bandwidth
    (given sufficient demand)
                CBQ – Class Based Queue
     eth0                                    eth3
   TRIUMF                                  Internet
   10Mpbs                                   2Mbps
                  Linux Bwmgr                            UBC 10Mbps

•If you want to control traffic in both directions, you
must set up CBQ for both interfaces
•Imagine you want to shape traffic from Internet to the
TRIUMF to 10Mbit and traffic in the opposite direction
to 2Mbit. You need to setup CBQ on both eth0 and
eth3 interfaces, thus you need two config files
         QOS – Outgoing Packets
w pfifo_fast – first in first out – 3 bands, packets in Band 0
  get handled, then Band 1, etc.
w Token Bucket Filter – Rate does not exceed some limit,
  but bursting is possible with enough tokens
   n   Allows uploading without killing interactive sessions:
        tc qdisc add dev ppp0 root tbf rate 220kbit
        latency 50ms burst 1540

w Stochastic Fairness Queueing – less accurate
  but promotes fairness so no one conversation
  drowns out the others
        tc qdisc add dev ppp0 root sfq perturb 10
w Linux 2.4 kernel (2.4.21)
   n   bridging support built into 2.4 kernels

   n   If you also want iptables support on the bridge must also
       install the ebtables-brnf patch for your kernel

   n   Bridge is configured using tools from bridge-utils
        l   brctl addbr br0; brctl addif br0 eth0; brctl addif br0 eth3
        l   iplink set br0 up; ifconfig eth0 up ifconfig eth3 up
        l   ip addr add brd + dev br0
                   Build the Bridge
   ifconfig eth0 up
   ifconfig eth1 up
   brctl addbr br0
   brctl addif br0 eth0
   brctl addif br0 eth1
No Spanning Tree Protocol:
   brctl stp br0 off
Turn it on:
   ifconfig br0 up
Or give the bridge an IP address and turn it on:
   ifconfig br0 netmask up
   route add default gw
                   Networking Software
w Good free implementations for:
   n   DNS
         l   BIND v8/9, djbdns
   n   SMTP
         l   sendmail, qmail, postfix, exim
   n   POP/IMAP
         l   qpopper, uwimapd
   n   HTTP
         l   Apache
         l   PHP, mySQL

       “If it was hard to develop, it should be hard to install!”
 Setting Up a Basic Name Server

w Later versions of BIND use the configuration file
w This file is divided into five sections: options, controls,
  three different zones and an include line, which refers to
  the rndc security file
w A zone is a part of the DNS domain tree for which the
  DNS server has authority to provide information
w Zone information is contained in files referred to in
w Using DNS system
  n   Before Internet network started use DNS system there
      was hosts files.
  n   However there are one main disadvantage of using
      host file - search time increase exponentially.
  n   This is the main reason why Internet network started
      use DNS system.
  n   By the way, DNS system let you use distributed
      administrative model in order to delegate
      administrative rights to other people.
n   You can imagine DNS system structure using image below:
                                                "." (root)

                                        net   com       edu         au
      host                  ru
                                                              .ru domain
     host                         msu              wsu

     host                   gw1                                     
w DNS zones
                  com                           …

                    terra flora

                                    ntserver                   servers


w DNS request:
  n   Requred information for DNS requests
  n   Making DNS requests
  n   DNS requests types:
      l Recursive reuqets
      l Iterative requests
                   IP( = ?

                IP( = ?
                                                        Root servers
                 Authoritative server for
        - server

                 IP( = ?
                 Authoritative server for
        -      IP( = ?      
                 IP( =

                IP( =
w DNS system planning factors.
w Number of servers and system platforms
w Server types:
  n   Primary server
  n   Secondary servers
  n   Cache servers
  n   Forward servers
  n   Stealth servers
w DNS database resurce records (RR)
w DNS database RR forms and types
w Standart RR
w DNS database file structure
w IN-ADDR.ARPA zone for reverse address-to-
  name translation
w RR format
  n   TYPE contain RR type code
  n   CLASS contain RR class code
  n   TTL contain Time to Live value
  n   RDLENGTH – data length           0   1   2   3   4   5   6   7     8   9   10 11 12 13 14 15

  n   RDATA – data                                                 NAME





w DNS RR types   • DNS CLASS
  n   A            types
  n   NS           –   IN
  n   MX           –   CS
  n   MD           –   CH
  n   MF           –   HS
  n   CNAME
  n   SOA
  n   WKS
  n   SRV
  n   TXT
  n   PTR
  n   …
w BIND server configuration
 acl – define access control list in order to control access to server resources
Controls – define control channel for rndc control utility.
Include - can be used to merge a lot of configuration file in one.
Key – use information to check identity using TSIG technology.
Logging – use to control logging options of DNS server.
Options - different DNS server options. Use mainly for global server configuration.
Server - certain server configuration options.
trusted-keys - used for DNSSEC protocol to hold trusted keys.
View - define view options.
Zone – define zone option.
Split DNS example:
view "internal" {
      match-clients { / 8 ; };
      recursion yes;
      zone "" {
               type master;
               file "example-internal.db";
view "external" {
      match-clients { any; };
      recursion no;
      zone "" {
               type master;
               file "example-external.db";
                                                       DNS   file "named.local";
DNS configuration file example:
logging {                                                    allow-update { none; };
      category lame-servers { null; };                  };
};                                                      zone "" {
options {                                                    type master;
      directory "/var/named";                                file "";
      allow-transfer {;;; };                                  };
      recursive-clients 2000;                           };
      notify yes;                                       view "external" {
};                                                           match-clients { any; };
acl "internals" {;;;                recursion no;;;                   zone "." IN {
};                                                           type hint;
view "internal" {                                            file "";
      match-clients { "internals"; };
      recursion yes;                                    };
                                                        zone "" {
zone "." IN {                                                type master;
    type hint;                                               file "";
    file "";                                    };
zone "" IN {                        };
    type master;                                                                           2
DNS server database file:                                ;
$ORIGIN .                                                ; test WWW on Lattelekom servers
$TTL 3600      ; 1 hour                                  ;          IN SOA (   www                A
                     2006040301 ; serial                 admin              A
                     28800 ; refresh (8 hours)           editor           A
                     1800      ; retry (5 minutes)       www                A
                     1209600 ; expire (2 weeks)          tavro            A
                     28800 ; minimum (1 hour)            tekno             A
                     )                                   $ORIGIN
              NS                            router            A
              A                      $ORIGIN
              MX 10                      proxy2             A
              MX 20                     help             A
              MX 30                     ssiahq01            A
$ORIGIN                                         nw1               A
router            A
eproxy             A
eproxy1             A
eproxy2             A
ns1              A
mail             CNAME ns1
nais             A
Reverse DNS zone
$TTL 3600      ; 1 hour IN SOA (
                    2006012401 ; serial
                    3600    ; refresh (1 hour)
                    300    ; retry (5 minutes)
                    3600000 ; expire (5 weeks 6 days 16 hours)
                    3600    ; minimum (1 hour)

1            PTR
7            PTR
8            PTR
10            PTR
31            PTR
58            PTR
60            PTR
77            PTR
119            PTR
                                           Restart named
           w sudo /sbin/service named restart
             Stopping named:
             Starting named:       [ OK ]

$ sudo tail /var/log/messages
Jan 28 22:36:22 womnibook named[11333]: loading configuration from '/etc/named.conf'
Jan 28 22:36:22 womnibook named[11333]: no IPv6 interfaces found
Jan 28 22:36:22 womnibook named[11333]: listening on IPv4 interface lo,
Jan 28 22:36:22 womnibook named[11333]: listening on IPv4 interface eth0,
Jan 28 22:36:22 womnibook named[11333]: listening on IPv4 interface eth1,
Jan 28 22:36:22 womnibook named[11333]: command channel listening on
Jan 28 22:36:22 womnibook named[11333]: zone loaded serial 142
Jan 28 22:36:22 womnibook named[11333]: running
Jan 28 22:36:22 womnibook named[11333]: zone sending notifies (serial 142)
Jan 28 22:36:22 womnibook named: named startup succeeded
w Usefull utilities:
   n   Dig
   n   Host
   n   Nslookup
   n   Rndc
   n   Named-checkzone
   n   Name-checkconfig
Using Command-line Utilities

           Maturity    Security   Features      Performance

qmail      medium      high       high          high

Sendmail   high        low        high          low

Postfix    medium      high       medium        high

exim       medium      low        high          medium

Courier    low         medium     high          medium

                                             Bron: Life with qmail, p. 5
         Configuring a Basic Email
w Sendmail is the most widely used email server
  n   The sendmail package contains the sendmail daemon
  n   Sendmail is started using a script in /etc/rc.d/init.d
  n   Sendmail is configured using the file /etc/
  n   Most email administrators prefer to use the m4
      program to configure sendmail
                     Email basics

Mail Server                  Mail Server
          Email                        database
  MDA         MTA                          MDA

  Workstation                     Workstation

        MUA                                MUA
           Simplified Mail Transactions
                         Mail                           Mail
 Mail User                                                       Mail User
                      Transport                      Transport
  Agent                                                           Agent
                        Agent                          Agent

                         Mail                          Mail
  mbox                 Delivery                      Delivery    mbox
                        Agent                         Agent

w Message composed using an MUA
w MUA gives message to MTA for delivery
   n   If local, the MTA gives it to the local MDA
   n   If remote, transfer to another MTA
Watching sendmail Work
Watching sendmail Work
                Structure of qmail
qmail-smtpd                              qmail-inject

Incoming SMTP mail                 Other incoming mail


     qmail-rspawn                  qmail-lspawn

      qmail-remote                  qmail-local
Installation qmail and qmail-pop3d

tux:~# apt-get update
tux:~# apt-get install qmail

 sh -c "start-stop-daemon --start --quiet --user root \
    --exec /usr/bin/tcpserver -- \
    0 pop-3 /usr/sbin/qmail-popup `hostname`.`dnsdomainname` \
    /usr/bin/checkpassword /usr/sbin/qmail-pop3d Maildir &
              Configuration of qmail

w Configuration stored in
w Configure:
   n   Relaying
   n   Multiple host names
   n   Virtual domains
   n   Aliases
   n   qmail-users
   n   Blackhole lists
   n   Mailbox formaat
            The qmail security guarantee

In March 1997, I offered $500 to the first person to publish a
verifiable security hole in the latest version of qmail: for example, a
way for a user to exploit qmail to take over another account.

My offer still stands. Nobody has found any security holes in qmail.

       Principles, sendmail vs qmail

w Do as little as possible in setuid programs
   n   Of 20 recent sendmail security holes, 11 worked only because
       the entire sendmail system is setuid
   n   Only qmail-queue is setuid
        l   Its only function is add a new message to the queue
w Do as little as possible as root
   n   The entire sendmail system runs as root
        l   Operating system protection has no effect
   n   Only qmail-start and qmail-lspawn run as root.
       Principles, sendmail vs qmail

w Programs and files are not addresses
   n   sendmail treats programs and files as addresses
        l   “sendmail goes through horrendous contortions trying to keep
            track of whether a local user was responsible for an address. This
            has proven to be an unmitigated disaster”
   n   qmail programs and files are not addresses
        l   “The local delivery agent, qmail-local, can run programs or write
            to files as directed by ~user/.qmail, but it's always running as that
            user. Security impact: .qmail, like .cshrc and .exrc and various
            other files, means that anyone who can write arbitrary files as a
            user can execute arbitrary programs as that user. That's it.”
                      Keep it simple

w Parsing
   n   Limited parsing of strings
       l   Minimizes risk of security holes from configuration
w Libraries
   n   Avoid standard C library, stdio
       l   “Write bug-free code” (DJB)
                  Webmail system (SquirreMail)
                           Mail Server
Web server
                              MUA        database
 Mail)                         MTA



w what is Apache?
w Apache’s functionality
w installing Apache
w directory structure
w configuration
w tools
w Apache
w Dynamic Content
  n   CGI
  n   PHP
     If you request an HTML file


          1                           2
                    Webserver   3
                         Web server

w a software program that does the following
   n   Accepts requests for web pages from a browser.
   n   Looks for the requested pages on the server hard drive.
   n   Sends a copy of the the requested web page to the browser.
   n   A web server can only serve HTML and jpg/gif files
w In our case, we use a very popular web server called

w open-source
w very popular (more than 67% of the web sites)
w highly configurable and extensible with third-party
w runs on many operating systems (most of the
w is actively being developed
           Apache functionality

w DBM databases for authentication
w customized responses to errors and problems
w unlimited flexible URL rewriting and aliasing
w Virtual Hosts
w Configurable Reliable Piped Logs
                    Apache modules (1)
w mod_access
   n   Access control based on client hostname or IP address
w mod_alias
   n   Mapping different parts of the host filesystem in the document tree, and
       URL redirection
w mod_auth
   n   User authentication using text files
w mod_autoindex
   n   Automatic directory listings
w mod_cgi
   n   Invoking CGI scripts
                   Apache modules (2)
w mod_include
   n   Server-parsed documents
w mod_mime
   n   Determining document types using file extensions
w mod_proxy
   n   Caching proxy abilities
w mod_rewrite
   n   Powerful URI-to-filename mapping using regular expressions
w mod_usertrack
   n   User tracking using Cookies
w mod_vhost_alias
   n   Support for dynamically configured mass virtual hosting
                Apache modules (3)

w mod_ssl
  n   This module provides strong cryptography for the Apache 1.3
      webserver via the Secure Sockets Layer (SSL) and Transport
      Layer Security (TLS) protocols by the help of the Open Source
      SSL/TLS toolkit OpenSSL.
  n   Requires Apache 1.3.x and OpenSSL 0.9.x
  n   Private and Public keys
  n   Thawte (, Versisign (
              Installing Apache

w Unix binary package
  n   RPM
  n   DEB
w Source
w Windows (MSI Installer)
            Installing Apache

$ ./configure --prefix=/usr/local/apache
$ make
$ make install
$ /usr/local/apache/bin/apachectl start
                    Installing Apache

w ./configure –help
  n   --show-layout
      l   show GNU style directory layout
  n   --with-layout=GNU
      l   Use GNU style directory layout
  n   --enable-suexec
      l   Enable suEXEC support for CGI and SSI
  n   --add-module=/path/to/mod_foo.c
      l   compiles, installs and adds module as a Dynamic Shared Object
             Testing Apache installation

arnis@perkons:~$ ps aux | grep apache
root   289 0.0 0.2 8400 2564 ?       Ss Nov15 0:02 /usr/local/apache/bin/httpd
root   307 0.0 0.1 8764 1480 ?       Ss Nov15 0:00 /usr/local/apache-ssl/bin/httpd -DSSL
apache- 315 0.0 0.1 14768 1580 ?       S Nov15 0:27 /usr/local/apache-ssl/bin/httpd -DSSL
apache- 13822 0.0 0.2 15224 2644 ?      S Nov15 0:26 /usr/local/apache-ssl/bin/httpd -DSSL
apache 11290 0.0 0.3 16856 3112 ?       S Nov17 0:31 /usr/local/apache/bin/httpd
apache 498 0.2 0.8 12596 8484 ?        S Nov18 8:54 /usr/local/apache/bin/httpd
Testing Apache installation
              Apache directory layout

w Debian
  n   /etc/init.d/apache
       l   Apache control script
  n   /etc/apache
       l   Apache configuration files
  n   /var/www
       l   Default Document Root
  n   /usr/lib/cgi-bin
       l   Default script directory
         Apache directory layout (2)

n   /var/log/apache
     l   log files (access.log, error.log)
n   /usr/sbin
     l   rotatelogs, ab (Apache Benchmark)
n   /usr/bin
     l   htpasswd, htdigest, dbmmanage
n   /usr/lib/apache/1.3
     l   Apache modules
n   /usr/lib/apache/suexec
        Apache directory layout (3)

w Slackware
  n   /usr/local/apache
  n   /usr/local/apache/conf
  n   /usr/local/apache/htdocs
  n   /usr/local/apache/cgi-bin
  n   /var/log/apache
  n   /usr/local/apache/bin
                     Apache access log

LogFormat "%v %h %l %u %t \"%r\" %>s %b" common
CustomLog /usr/local/apache/logs/access_log common
    n   %v – virtual host
    n   %h – remote host
    n   %u – user
    n   %t - time
    n   %r – HTTP request
    n   %>s – status code
    n   %b – size - - [21/Nov/2004:17:23:36 +0200]
"GET /index.php?m=5 HTTP/1.1" 200 32257
                                       Apache error log

ErrorLog /usr/local/apache/logs/error_log
LogLevel warn

[Sun Nov 21 09:13:42 2004] [error] PHP Fatal error: Call to undefined function PN_DBMsgError() in /home/msaule/public_html/referer.
php on line 85
[Sun Nov 21 12:41:09 2004] [error] [client] File does not exist: /home/sms/public_html/favicon.ico
php on line 85
[Sun Nov 21 13:02:50 2004] [error] [client] File does not exist: /home/code/public_html/robots.txt
[Sun Nov 21 13:08:26 2004] [error] [client] File does not exist: /home/refuser2/public_html/_vti_bin/owssvr.dll
[Sun Nov 21 13:08:26 2004] [error] [client] File does not exist: /home/refuser2/public_html/MSOffice/cltreq.asp
[Sun Nov 21 13:09:07 2004] [error] [client] File does not exist: /home/refuser2/public_html/_vti_bin/owssvr.dll
[Sun Nov 21 13:09:07 2004] [error] [client] File does not exist: /home/refuser2/public_html/MSOffice/cltreq.asp
           Apache configuration

w Edit httpd.conf
w Check configuration “apachectl configtest”
w Restart Apache
w Check changes
                 Apache configuration

w Virtual host
<VirtualHost *>
  CustomLog /usr/local/apache/logs/jrt_access_log common
  ErrorLog /usr/local/apache/logs/jrt_error_log
  DocumentRoot /home/jrt/public_html
                  Apache configuration

w .htaccess
AuthType Basic
AuthUserFile /home/someuser/passwd
AuthName "Admin"
require valid-user
w htpasswd
htpasswd -c <password file> <username>


w   Unix Threading
w   New Build System
w   Multiprotocol Support
w   New Apache API
w   IPv6 Support
w   Filtering
w   Multilanguage Error Responses
w   Regular Expression Library Updated
              Dynamic content

          1                                       2
                   6     Webserver        3
                       Script Engine
                       (PHP, Perl, ...)
             Dynamic content

w Scripting engine
w Apache module vs. CGI
                    Dynamic content

w Apache only sends content to the user
w What if I need some resources/information from server
   n   Send e-mail
   n   Store some information in file (guestbook)
   n   Execute unix applications
   n   And much more...
w We need programming language
                  Dynamic content

w Script engine is a software program that does the
   n   Accepts scripts passed along from the web server that
       are of the non-HTML type.
   n   Processes these scripts.
   n   Returns the result of this processing to the web
                  Dynamic content

w Two ways how to server dynamic content
  n   CGI
  n   Apache module
w Many programming languages to use
  n   PHP, Perl, Python, C, C++, shell scripts ...
         Common gateway interface
A standard for running external programs from a World-Wide Web
   HTTP server. CGI specifies how to pass arguments to the
   executing program as part of the HTTP request. It also defines a
   set of environment variables. Commonly, the program will generate
   some HTML which will be passed back to the browser but it can
   also request URL redirection.
                             CGI example

w Shell script
echo "Content-type: text/plain"
echo ""
echo "Hello world!"
echo "Today is:" `date`
                            CGI example (2)

w Perl script
print "Content-type: text/plain\n\n";
print "Hello world!\n";
print "Today is: " . localtime() . "\n";
                   Apache modules

w mod_perl
   mod_perl brings together the full power of the Perl programming
     language and the Apache HTTP server. You can use Perl to
     manage Apache, respond to requests for web pages and much
w mod_php
   PHP is a widely-used general-purpose scripting language that is
     especially suited for Web development and can be embedded
     into HTML
w mod_python, OpenASP Module, ...

w What is PHP?
w Installing PHP
w Configuring PHP
    PHP: Hypertext Preprocessor


       echo "Hi, I'm a PHP script!";

w Pros
    n easy to learn
    n ideal for small projects

    n widely used

    n no strong typing

w Cons
    n no strong typing
    n code maintenance

    n interpreted language

    n executes in the Web server process
                 Installing PHP

w Server-side scripting

w Command line scripting

w Client-side GUI applications
                    Installing PHP

w Gentoo
# emerge \<apache-2
# USE="-*" emerge php mod_php
# ebuild /var/db/pkg/dev-php/mod_php-<your PHP
   version>/mod_php-<your PHP version>.ebuild config
# nano /etc/conf.d/apache Add "-D PHP4" to APACHE_OPTS # rc-
   update add apache default
# /etc/init.d/apache start
                         Installing PHP

w Source instalation
   n   Install PHP
   ./configure --with-mysql --with-apxs=/www/bin/apxs
   make install
   cp php.ini-dist /usr/local/lib/php.ini
   n Edit your httpd.conf to load the PHP module.

     LoadModule php4_module libexec/
     AddModule mod_php4.c
     AddType application/x-httpd-php .php .phtml
   n Restart Apache
                  PHP Configuration

w php.ini read once at web server startup
; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either: ; true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes
; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"
                      PHP Configuration

w php.ini directives
max_execution_time = 30 ; Maximum execution time of each script, in seconds
max_input_time = 60 ; Maximum amount of time each script may spend parsing
   request data
memory_limit = 8M ; Maximum amount of memory a script may consume (8MB)

; - Show all errors except for notices and coding standards warnings
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT
display_errors = Off
log_errors = On
error_log = filename
                    PHP Configuration

w Apache configuration file
    DocumentRoot /home/someuser/public_html
    <Directory /home/someuser/public_html/>
     php_admin_value open_basedir /home/someuser/:/tmp/:/usr/share/pear/
     php_value auto_prepend_file /home/someuser/includes/
     php_value upload_max_filesize 10M
                     PHP Configuration

w .htaccess file
AddType application/x-httpd-php .php3
php_value include_path .:/home/someuser/includes:/home/someuser/public_html
php_flag register_globals Off

w PHP scripts
ini_set("display_errors", "true");
               Apache module vs. CGI

w Apache module
   n   Good performance
   n   One user for all websites
        l   Other user’s source files can be accessed
        l   PHP safe_mode
   n   New process each time
   n   suEXEC – each website under its own user
w fastCGI
          Apache, PHP and MySQL

          1                                  2
                       Webserver       3
                  8      7
                       PHP Engine
                      MySQL Database

w About MySQL
w Installing MySQL
w MySQL directory structure
w MySQL commands
w Some examples
w PHPMyAdmin

w   Open source
w   Very fast
w   Stable
w   Easy to use
w   Independant storage engines
    n   Can be run with or without transaction control
w Security
    n   SSL support
    n   Resources configurable per user basis
                  MySQL 4.x

w Subqueries
w New client-server protocol with prepared
w Unicode and UTF-8 support
w Query cashing
w Much more...
                         Installing MySQL

w Binary distribution
shell> groupadd mysql
shell> useradd -g mysql mysql
shell> cd /usr/local
shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf -
shell> ln -s full-path-to-mysql-VERSION-OS mysql
shell> cd mysql
shell> scripts/mysql_install_db --user=mysql
shell> chown -R root .
shell> chown -R mysql data
shell> chgrp -R mysql .
shell> bin/mysqld_safe --user=mysql &
                             Installing MySQL
w Source distribution
shell> groupadd mysql
shell> useradd -g mysql mysql
shell> gunzip < mysql-VERSION.tar.gz | tar -xvf -
shell> cd mysql-VERSION
shell> ./configure --prefix=/usr/local/mysql
shell> make
shell> make install
shell> cp support-files/my-medium.cnf /etc/my.cnf
shell> cd /usr/local/mysql
shell> bin/mysql_install_db --user=mysql
shell> chown -R root .
shell> chown -R mysql var
shell> chgrp -R mysql .
shell> bin/mysqld_safe --user=mysql &
      Post-Instalation Procedures

w Check instalation
  n   shell> bin/mysqladmin version
w Create system tables
  n   shell> bin/mysql_install_db --user=mysql
w Make nessesary databases and users
  n   GRANT
          MySQL directory structure

w ./
   n   MySQL server control scripts
w bin/
   n   MySQL server, MySQL client and commandline tools
w data/
   n   Databases – directories
   n   Tables – files (MYD, MYI,FRM)
w var/log
   n   Log files
                 MySQL binaries

w mysql
  n   MySQL client
w mysqladmin
  n   MySQL administration tool
w mysqldump
  n   Tool for creating database dumps
                MySQL commands

w CREATE DATABASE <database name>
w GRANT ALL PRIVILEGES on database.* to
  user@localhost IDENTIFIED BY ‘password’
   n   Privilege type (ALL, ALTER, CREATE, DELETE, INSERT,
       SELECT, GRANT, ...)
   n   Privilege level (globa, database, table, column)
   n   User and host (localhost, IP address, network, %)
         PHP and database example

MySQL and SQLite Examples

phpMyAdmin is a tool written in PHP intended to handle the
  administration of MySQL over the Web

w   CREATE/DROP databases
w   Delete/add/edit/search information
w   Execute SQL queries
w   Manage privileges
w   Export data
                 PHP and SQLite example

// create new database (OO interface) 
$db = new SQLiteDatabase("db.sqlite"); 

// create table foo and insert sample data 
         CREATE TABLE foo(id INTEGER PRIMARY KEY, name CHAR(255)); 
         INSERT INTO foo (name) VALUES('Ilia'); 
         INSERT INTO foo (name) VALUES('Ilia2'); 
         INSERT INTO foo (name) VALUES('Ilia3'); 

// execute a query     
$result = $db->query("SELECT * FROM foo"); 
// iterate through the retrieved rows 
while ($result->valid()) { 
    // fetch current row 
    $row = $result->current();      
// proceed to next row 

// not generally needed as PHP will destroy the connection 

               PHP and MySQL example
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
   or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');

// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
   echo "\t<tr>\n";
   foreach ($line as $col_value) {
       echo "\t\t<td>$col_value</td>\n";
   echo "\t</tr>\n";
echo "</table>\n";

// Free resultset

// Closing connection

Shared By: