Presentation is loading. Please wait.

Presentation is loading. Please wait.

Guntis Barzdins Girts Folkmanis Juris Krūmiņš Artūrs Lavrenovs

Similar presentations


Presentation on theme: "Guntis Barzdins Girts Folkmanis Juris Krūmiņš Artūrs Lavrenovs"— Presentation transcript:

1 Guntis Barzdins Girts Folkmanis Juris Krūmiņš Artūrs Lavrenovs
Unix Server Tools Guntis Barzdins Girts Folkmanis Juris Krūmiņš Artūrs Lavrenovs

2 Unix Server Tools IP connectivity, routing Daemons Syslog Inetd etc.
Cron Security

3 “If it was hard to develop, it should be hard to install!”
Networking Software Good free implementations for: DNS BIND v8/9, djbdns SMTP sendmail, qmail, postfix, exim POP/IMAP qpopper, uwimapd, dovecot HTTP Apache, nginx PHP, MySQL Teiciens ir attiecināms uz pirmajām “lielajām” programmām, kā, piemēram, bind/sendmail, kas ir grūti konfigurējamas un ir dažādas problēmas, it īpaši drošības jomās. “If it was hard to develop, it should be hard to install!”

4 Two IP processing modes: host or router
Manual change # more /proc/sys/net/ipv4/ip_forward # echo 1 > /proc/sys/net/ipv4/ip_forward 1 # 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 Record changes in /etc/sysctl.conf (to activate after reboot) Host – nozīmē, ka dators ir paketes gala saņēmējs. Router – nozīmē, ka tiks veikta pakešu pārvietošana starp šī servera interfeisiem Visi pieminētie serveri darbojas host režīmā, router vajag, ja nav fiziska rūtera kastītes vai kaut kas pārāk netriviāls.

5 Sysctl izvads, unix kodola runtime iestatījumi.
unix sbin # sysctl -a abi.fake_utsname = 0 abi.trace = 0 abi.defhandler_libcso = abi.defhandler_lcall7 = abi.defhandler_elf = 0 abi.defhandler_coff = dev.rtc.max-user-freq = 64 net.unix.max_dgram_qlen = 10 net.ipv4.ip_conntrack_max = 8184 net.ipv4.netfilter.ip_conntrack_generic_timeout = 600 net.ipv4.netfilter.ip_conntrack_icmp_timeout = 30 net.ipv4.netfilter.ip_conntrack_udp_timeout_stream = 180 net.ipv4.netfilter.ip_conntrack_udp_timeout = 30 net.ipv4.netfilter.ip_conntrack_tcp_timeout_close = 10 net.ipv4.netfilter.ip_conntrack_tcp_timeout_time_wait = 120 net.ipv4.netfilter.ip_conntrack_tcp_timeout_last_ack = 30 net.ipv4.netfilter.ip_conntrack_tcp_timeout_close_wait = 60 net.ipv4.netfilter.ip_conntrack_tcp_timeout_fin_wait = 120 net.ipv4.netfilter.ip_conntrack_tcp_timeout_established = net.ipv4.netfilter.ip_conntrack_tcp_timeout_syn_recv = 60 net.ipv4.netfilter.ip_conntrack_tcp_timeout_syn_sent = 120 net.ipv4.netfilter.ip_conntrack_buckets = 1023 net.ipv4.netfilter.ip_conntrack_max = 8184 net.ipv4.conf.eth0.force_igmp_version = 0 net.ipv4.conf.eth0.arp_ignore = 0 net.ipv4.conf.eth0.arp_announce = 0 net.ipv4.conf.eth0.arp_filter = 0 net.ipv4.conf.eth0.tag = 0 net.ipv4.conf.eth0.log_martians = 0 net.ipv4.conf.eth0.bootp_relay = 0 net.ipv4.conf.eth0.medium_id = 0 net.ipv4.conf.eth0.proxy_arp = 0 net.ipv4.conf.eth0.accept_source_route = 1 net.ipv4.conf.eth0.send_redirects = 1 net.ipv4.conf.eth0.rp_filter = 1 net.ipv4.conf.eth0.shared_media = 1 net.ipv4.conf.eth0.secure_redirects = 1 net.ipv4.conf.eth0.accept_redirects = 1 net.ipv4.conf.eth0.mc_forwarding = 0 net.ipv4.conf.eth0.forwarding = 0 net.ipv4.conf.lo.force_igmp_version = 0 net.ipv4.conf.lo.arp_ignore = 0 net.ipv4.conf.lo.arp_announce = 0 net.ipv4.conf.lo.arp_filter = 0 net.ipv4.conf.lo.tag = 0 net.ipv4.conf.lo.log_martians = 0 net.ipv4.conf.lo.bootp_relay = 0 net.ipv4.conf.lo.medium_id = 0 net.ipv4.conf.lo.proxy_arp = 0 net.ipv4.conf.lo.accept_source_route = 1 net.ipv4.conf.lo.send_redirects = 1 net.ipv4.conf.lo.rp_filter = 0 net.ipv4.conf.lo.shared_media = 1 net.ipv4.conf.lo.secure_redirects = 1 net.ipv4.conf.lo.accept_redirects = 1 net.ipv4.conf.lo.mc_forwarding = 0 net.ipv4.conf.lo.forwarding = 0 net.ipv4.conf.default.force_igmp_version = 0 net.ipv4.conf.default.arp_ignore = 0 net.ipv4.conf.default.arp_announce = 0 net.ipv4.conf.default.arp_filter = 0 net.ipv4.conf.default.tag = 0 net.ipv4.conf.default.log_martians = 0 net.ipv4.conf.default.bootp_relay = 0 net.ipv4.conf.default.medium_id = 0 net.ipv4.conf.default.proxy_arp = 0 net.ipv4.conf.default.accept_source_route = 1 net.ipv4.conf.default.send_redirects = 1 net.ipv4.conf.default.rp_filter = 0 net.ipv4.conf.default.shared_media = 1 net.ipv4.conf.default.secure_redirects = 1 net.ipv4.conf.default.accept_redirects = 1 net.ipv4.conf.default.mc_forwarding = 0 net.ipv4.conf.default.forwarding = 0 net.ipv4.conf.all.force_igmp_version = 0 net.ipv4.conf.all.arp_ignore = 0 net.ipv4.conf.all.arp_announce = 0 net.ipv4.conf.all.arp_filter = 0 net.ipv4.conf.all.tag = 0 net.ipv4.conf.all.log_martians = 0 net.ipv4.conf.all.bootp_relay = 0 net.ipv4.conf.all.medium_id = 0 net.ipv4.conf.all.proxy_arp = 0 net.ipv4.conf.all.accept_source_route = 0 net.ipv4.conf.all.send_redirects = 1 net.ipv4.conf.all.rp_filter = 0 net.ipv4.conf.all.shared_media = 1 net.ipv4.conf.all.secure_redirects = 1 net.ipv4.conf.all.accept_redirects = 1 net.ipv4.conf.all.mc_forwarding = 0 net.ipv4.conf.all.forwarding = 0 net.ipv4.neigh.eth0.locktime = 100 net.ipv4.neigh.eth0.proxy_delay = 80 net.ipv4.neigh.eth0.anycast_delay = 100 net.ipv4.neigh.eth0.proxy_qlen = 64 net.ipv4.neigh.eth0.unres_qlen = 3 net.ipv4.neigh.eth0.gc_stale_time = 60 net.ipv4.neigh.eth0.delay_first_probe_time = 5 net.ipv4.neigh.eth0.base_reachable_time = 30 net.ipv4.neigh.eth0.retrans_time = 100 net.ipv4.neigh.eth0.app_solicit = 0 net.ipv4.neigh.eth0.ucast_solicit = 3 net.ipv4.neigh.eth0.mcast_solicit = 3 net.ipv4.neigh.lo.locktime = 100 net.ipv4.neigh.lo.proxy_delay = 80 net.ipv4.neigh.lo.anycast_delay = 100 net.ipv4.neigh.lo.proxy_qlen = 64 net.ipv4.neigh.lo.unres_qlen = 3 net.ipv4.neigh.lo.gc_stale_time = 60 net.ipv4.neigh.lo.delay_first_probe_time = 5 net.ipv4.neigh.lo.base_reachable_time = 30 net.ipv4.neigh.lo.retrans_time = 100 net.ipv4.neigh.lo.app_solicit = 0 net.ipv4.neigh.lo.ucast_solicit = 3 net.ipv4.neigh.lo.mcast_solicit = 3 net.ipv4.neigh.default.gc_thresh3 = 1024 net.ipv4.neigh.default.gc_thresh2 = 512 net.ipv4.neigh.default.gc_thresh1 = 128 net.ipv4.neigh.default.gc_interval = 30 net.ipv4.neigh.default.locktime = 100 net.ipv4.neigh.default.proxy_delay = 80 net.ipv4.neigh.default.anycast_delay = 100 net.ipv4.neigh.default.proxy_qlen = 64 net.ipv4.neigh.default.unres_qlen = 3 net.ipv4.neigh.default.gc_stale_time = 60 net.ipv4.neigh.default.delay_first_probe_time = 5 net.ipv4.neigh.default.base_reachable_time = 30 net.ipv4.neigh.default.retrans_time = 100 net.ipv4.neigh.default.app_solicit = 0 net.ipv4.neigh.default.ucast_solicit = 3 net.ipv4.neigh.default.mcast_solicit = 3 net.ipv4.tcp_westwood = 0 net.ipv4.ipfrag_secret_interval = 600 net.ipv4.tcp_low_latency = 0 net.ipv4.tcp_frto = 0 net.ipv4.tcp_tw_reuse = 0 net.ipv4.icmp_ratemask = 6168 net.ipv4.icmp_ratelimit = 100 net.ipv4.tcp_adv_win_scale = 2 net.ipv4.tcp_app_win = 31 net.ipv4.tcp_rmem = net.ipv4.tcp_wmem = net.ipv4.tcp_mem = net.ipv4.tcp_dsack = 1 net.ipv4.tcp_ecn = 0 net.ipv4.tcp_reordering = 3 net.ipv4.tcp_fack = 1 net.ipv4.tcp_orphan_retries = 0 net.ipv4.inet_peer_gc_maxtime = 120 net.ipv4.inet_peer_gc_mintime = 10 net.ipv4.inet_peer_maxttl = 600 net.ipv4.inet_peer_minttl = 120 net.ipv4.inet_peer_threshold = 65664 net.ipv4.igmp_max_msf = 10 net.ipv4.route.secret_interval = 600 net.ipv4.route.min_adv_mss = 256 net.ipv4.route.min_pmtu = 552 net.ipv4.route.mtu_expires = 600 net.ipv4.route.gc_elasticity = 8 net.ipv4.route.error_burst = 500 net.ipv4.route.error_cost = 100 net.ipv4.route.redirect_silence = 2048 net.ipv4.route.redirect_number = 9 net.ipv4.route.redirect_load = 2 net.ipv4.route.gc_interval = 60 net.ipv4.route.gc_timeout = 300 net.ipv4.route.gc_min_interval = 0 net.ipv4.route.max_size = 8192 net.ipv4.route.gc_thresh = 512 net.ipv4.route.max_delay = 10 net.ipv4.route.min_delay = 2 net.ipv4.icmp_ignore_bogus_error_responses = 0 net.ipv4.icmp_echo_ignore_broadcasts = 0 net.ipv4.icmp_echo_ignore_all = 0 net.ipv4.ip_local_port_range = net.ipv4.tcp_max_syn_backlog = 256 net.ipv4.tcp_rfc1337 = 0 net.ipv4.tcp_stdurg = 0 net.ipv4.tcp_abort_on_overflow = 0 net.ipv4.tcp_tw_recycle = 0 net.ipv4.tcp_syncookies = 0 net.ipv4.tcp_fin_timeout = 60 net.ipv4.tcp_retries2 = 15 net.ipv4.tcp_retries1 = 3 net.ipv4.tcp_keepalive_intvl = 75 net.ipv4.tcp_keepalive_probes = 9 net.ipv4.tcp_keepalive_time = 7200 net.ipv4.ipfrag_time = 30 net.ipv4.ip_dynaddr = 0 net.ipv4.ipfrag_low_thresh = net.ipv4.ipfrag_high_thresh = net.ipv4.tcp_max_tw_buckets = 16384 net.ipv4.tcp_max_orphans = 8192 net.ipv4.tcp_synack_retries = 5 net.ipv4.tcp_syn_retries = 5 net.ipv4.ip_nonlocal_bind = 0 net.ipv4.ip_no_pmtu_disc = 0 net.ipv4.ip_autoconfig = 0 net.ipv4.ip_default_ttl = 64 net.ipv4.ip_forward = 0 net.ipv4.tcp_retrans_collapse = 1 net.ipv4.tcp_sack = 1 net.ipv4.tcp_window_scaling = 1 net.ipv4.tcp_timestamps = 1 net.core.somaxconn = 128 net.core.hot_list_length = 128 net.core.optmem_max = 10240 net.core.message_burst = 50 net.core.message_cost = 5 net.core.mod_cong = 290 net.core.lo_cong = 100 net.core.no_cong = 20 net.core.no_cong_thresh = 10 net.core.netdev_max_backlog = 300 net.core.dev_weight = 64 net.core.rmem_default = net.core.wmem_default = net.core.rmem_max = net.core.wmem_max = vm.block_dump = 0 vm.laptop_mode = 0 vm.max_map_count = 65536 vm.max-readahead = 31 vm.min-readahead = 3 vm.page-cluster = 3 vm.pagetable_cache = 25 50 vm.kswapd = vm.overcommit_memory = 0 vm.bdflush = vm.vm_passes = 60 vm.vm_lru_balance_ratio = 2 vm.vm_mapped_ratio = 100 vm.vm_cache_scan_ratio = 6 vm.vm_vfs_scan_ratio = 6 vm.vm_gfp_debug = 0 kernel.lowlatency = 0 kernel.overflowgid = 65534 kernel.overflowuid = 65534 kernel.random.uuid = 5784cebf-b4c1-4e2d-b60c-c8ed66b10136 kernel.random.boot_id = 65fcbb7e-b4c3-452f-8d98-dc7ac3d67ea6 kernel.random.write_wakeup_threshold = 128 kernel.random.read_wakeup_threshold = 8 kernel.random.entropy_avail = 772 kernel.random.poolsize = 512 kernel.threads-max = 2047 kernel.cad_pid = 1 kernel.sysrq = 1 kernel.sem = kernel.msgmnb = 16384 kernel.msgmni = 16 kernel.msgmax = 8192 kernel.shmmni = 4096 kernel.shmall = kernel.shmmax = kernel.rtsig-max = 1024 kernel.rtsig-nr = 0 kernel.hotplug = /sbin/hotplug kernel.modprobe = /sbin/modprobe kernel.printk = kernel.ctrl-alt-del = 0 kernel.real-root-dev = 256 kernel.cap-bound = -257 kernel.tainted = 0 kernel.core_pattern = core kernel.core_setuid_ok = 0 kernel.core_uses_pid = 0 kernel.panic = 0 kernel.domainname = (none) kernel.hostname = unix kernel.version = #1 Thu Sep 23 14:41:14 EEST 2004 kernel.osrelease = gentoo-r9 kernel.ostype = Linux fs.lease-break-time = 45 fs.dir-notify-enable = 1 fs.leases-enable = 1 fs.overflowgid = 65534 fs.overflowuid = 65534 fs.dentry-state = fs.file-max = 13100 fs.file-nr = fs.inode-state = fs.inode-nr = unix sbin # Sysctl izvads, unix kodola runtime iestatījumi. Atkarībā no unix veida simtiem vai tūkštošiem Serveru gadījumā daudz network opcijas, kas ir jālabo. Vienmēr tās opcijas ir jāpielāgo ja ir netriviāls pielietojums vai nozīmīga slodze. Linux šīs opcija atbilst procfs un ir pieejamas /dev/sys virtuālajā failsistēmā. FreeBSD gadījumā ir tikai sysctl, profcs ir atmests kā novecojis.

6 ifconfig ifconfig eth0 192.168.99.35 netmask 255.255.255.0 up ifconfig
eth Link encap:Ethernet HWaddr 00:80:C8:F8:4A:51 inet addr: Bcast: Mask: UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets: 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: (29.2 Mb) TX bytes: (7.5 Mb) Interrupt:9 Base address:0x5000 Obsolete in Linux for many (10+) years but still heavily used everywhere because of muscle memory (and compatibility with other UNIX versions) Programmai ir saskarne ar kodolu, kas ļauj konfigurēt interfeisus. Visi skripti un viss pārējais izmanto šo programmu, lai konfigurētu startējot OS un pārkonfigurētu interfeisus kaut kādu izmaiņu gadījumā. Šo programmu vai arī aizvietotāju, atkarībā no UNIX veida.

7 ip – ifconfig replacement in Linux
Many new features Developed Replaces many networking commands – arp, iptunnel, nameif, netstat, route More cisco-ish syntax ip link set eth0 up ip addr add /24 dev eth0 ip addr show dev eth0 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether 00:12:33:44:55:66 brd ff:ff:ff:ff:ff:ff inet /24 brd scope global eth0 valid_lft forever preferred_lft forever Ifconfig jau sen netiek attīstīts, tikai krāj patchus, ko uztur Debian. Šōbrīd visi Linux atbalsta gan ifconfig, gan jauno ip, un atbalstīs ifconfig vēl daudzus gadus. Savietojamības jautājums, jo standarta komandas ir daudz maz vienkārši portējamas.

8 Netstat: routing, sockets
Routing table: netstat -rn Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface U eth0 U lo UG eth0 ip route default via dev eth0 proto static /24 dev eth0 proto kernel scope link src metric 1 IP socket status: netstat --inet -n Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp : : ESTABLISHED tcp : : ESTABLISHED tcp : : ESTABLISHED tcp : : ESTABLISHED tcp : : ESTABLISHED tcp : : ESTABLISHED tcp : : SYN_SENT tcp : : ESTABLISHED tcp : : TIME_WAIT ss -f inet -n -Uz visiem datoriem ir nepieciešama maršrutēšanas tabula, lai lietotu tīklu. Ja tīkls izslēgts, tad tabula ir tukša. Ja ir dīvains/lokāls pieslēgums, t.i., tikai LAN tad ir tikai direct connected tīkls. Visos standarta gadījumos vajag izeju uz ārpusi un tas ir default gateway. -TCP/IP protokolu stāvokļi redzami, kodols uztur stāvokļu tabulu, ko var izmantot monitorēšanai un atkļūdošanai. -SYN_SENT tātad syn pakete ir nosūtīta, bet nekāda atbilde nav saņemta. -Var pamanīt anomālijas, piemēram, pakalpojumatteices uzbrukumus.

9 route Galvenās route komandas ir maršutu pielikšana un noņemšana. Jaunajam ip funkcionalitāte ir analoģiska. ip route {add | del} /24 via

10 Security Hardening Recommended IP/ICMP Settings Disable Ping
# sysctl –w net.ipv4.icmp_echo_ignore_all=1 Disable ICMP Echo Requests # sysctl –w net.ipv4.icmp_echo_ignore_broadcasts=1 Disable IP Source Routing # sysctl –w net.ipv4.conf.all.accept_source_route=0 Disable ICMP Redirects # sysctl –w net.ipv4.conf.all.accept_redirects=0 Enable TCP SYN Cookie Protection # sysctl –w net.ipv4.tcp_syncookies=1 Disable Bogus Error Logging # sysctl –w net.ipv4.icmp_ignore_bogus_error_responses=1 Enable Bogus Packet Logging # sysctl –w net.ipv4.conf.all.log_martians=1 Create blackhole # sysctl net.inet.tcp.blackhole=1 # sysctl net.inet.udp.blackhole=1 - Tie ir idejiski piemēri, bet praktiski labā prakse ir tīkla lietas icmp, udp u.t.t paketes nogriezt ugunsmūra līmenī. Šāda pieeja tiek izmantota, ja nav ugunsmūra. Šīs dažas komandas nav universāls drošības risinājums. - syncookies metode kā aizsargāties pret SYNFLOOD, datus glabā pašā tcp komunikācijā. - Blackhole aizsargā no portu skenēšanas un dažiem pakalpojumatteices uzbrukumiem.

11 configure domain name resolver
In Linux resolver has 2 config files /etc/hosts specifies static mappings host1 host2 host3 host4 merlin host5 arthur king timeserver name1.xyz.aus.century.com name1 /etc/resolv.conf specifies the nameservers and the default domain domain abc.aus.century.com nameserver nameserver - Oriģinālais veids, kā mapot kādu viegli atceramu tekstu/nosaukumu pret IP adresēm. - Šobrīd tas pārraksta dns serveru atbildi, lai kaut ko testētu. - nameserver tie ir dns serveru ieraksti, tiem ir jābūt, lai dns lookup strādā - viss pārējais tās ir dažādas neobligātas opcijas

12 resolvconf – resolv.conf replacement
Some software dynamically manages network connections (in some of newer UNIX) cat /etc/resolv.conf # Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8) # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN Nameserver ps aux | grep dns nobody ? S Oct22 6:51 /usr/sbin/dnsmasq --no-resolv -- keep-in-foreground --no-hosts --bind-interfaces --pid- file=/var/run/NetworkManager/dnsmasq.pid --listen-address= conf- file=/var/run/NetworkManager/dnsmasq.conf --cache-size=0 --proxy-dnssec --enable- dbus=org.freedesktop.NetworkManager.dnsmasq --conf-dir=/etc/NetworkManager/dnsmasq.d - Sākotnēji visu ar roku darīja - Pēc tam automatizēja ar boot un līdzīgiem skriptiem - Pēc tam ar skriptiem, kas reaģē uz izmaiņām - Šobrīd unix uz portatīvām sistēmām (laptopi u.t.t) arī ar to nepietiek, konekcijas var strauji mainīties, piemēram, pieslēgšanās daudziem wifi tīkliem, tīkla parametri mainās - Un parasti arī DNS serveri, šāda pieeja ļauj dinamiski veikt izmaņas lokālā DNS proksī serverī, nemainot resolv.conf , kas var radīt problēmas (piemēram paliekas pēc shutdown)

13 Popular Routing Protocols
Routed – BSD dēmons, kas jau ir iebūvēts BSD sistēmās, Linux sistēmās parasti nav iebūvēts Gated – ir dažādi varianti arī komercprodukti, ko neiesaka lietot, jo ir brūvas alternatīuvas

14 Quagga (previously GNU Zebra)
- Ja UNIX serveris tiek izmantots kā rūteris, ko var darīt, kad dzelziska rūtera nav. Tad parasti ir pieņemts izmantot kādu no gatavām maršrutēšanas programmatūras pakām. - Labi servera dzelži + šis risinājums + labas unix zināšanas var izveidot alternatīvas cisco produktiem, kas maksā desmitiem reižu dārgāk.

15 Quagga Sintakse ļoti līdzīga (gan konfigurēšanai runtime, gan konfigurācijas fails) cisco ar domu, ka var vienkārši portēt konfigurāciju starp dažādiem rūteriem un programmatūrām. Tas ir viens no iemesliem, kādēļ atsevišķas maršrutēšanas programmas retāk tiek izmantotas.

16 Setting Up Network Interface Cards FreeBSD
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 options=40<POLLING> 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 " Mūsdienās visos standarta gadījumos BSD tīkla kartes, draiveri un interfeisi automātiski tiek nokonfigurēti.

17 Setting Up Network Interface Cards FreeBSD
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 xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx“ 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 number. ifconfig_fxp0_alias0="inet netmask " ifconfig_fxp0_alias1="inet netmask " ifconfig_fxp0_alias2="inet netmask " ifconfig_fxp0_alias3="inet netmask " Vēsturiski vajadzīgs bija priekš http/1.0 un ssl sertifikātiem. Šobrīd dažādām tehniskām vajadzībām.

18 Setting Up Network Interface Cards FreeBSD
Testing and Troubleshooting Testing the Ethernet Card 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. First test the local interface: juriskr >ping -c 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 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 ^C ping statistics --- round-trip min/avg/max/stddev = 0.178/0.249/0.381/0.093 ms You could also use the machine name instead of IP address if you have set up the /etc/hosts file.

19 Ifconfig output RHEL [juris@ns1 ~]$ ifconfig
eth Link encap:Ethernet HWaddr 00:0B:CD:41:F4:93 inet addr:81.xxx.xxx.xxx Bcast:81.xxx.xxx.xxx Mask: inet6 addr: fe80::20b:cdff:fe41:f493/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets: errors:0 dropped:0 overruns:0 frame:0 TX packets: errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes: (3.2 GiB) TX bytes: (3.7 GiB) Interrupt:193 eth0:1 Link encap:Ethernet HWaddr 00:0B:CD:41:F4:93 inet addr:10.xxx.xxx.xxx Bcast:10.xxx.xxx.xxx Mask: lo Link encap:Local Loopback inet addr: Mask: inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU: Metric:1 RX packets: errors:0 dropped:0 overruns:0 frame:0 TX packets: errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes: (615.5 MiB) TX bytes: (615.5 MiB) ~]$

20 Daemons A daemon is a process that: runs in the background
not associated with any terminal output doesn't end up in another session. terminal generated signals (^C) aren't received.

21 Unix and Daemons Unix systems typically have many daemon processes.
Most servers run as a daemon process.

22 Common Daemons Web server (httpd) Mail server (sendmail)
SuperServer (inetd) System logging (syslogd) Print server (lpd) router process (routed, gated)

23 Daemon Output No terminal - must use something else:
file system central logging facility Syslog is often used - provides central repository for system logging. Ja gribam izvadu, tad tas kaut kur ir jāliek - unixos visbiežāk ir /var/log glabāšanas vieta. - Ir arī citi varianti, piemēram, turēt atmiņā un atgriezt pēc tīkla pieprasījuma.

24 Syslog service syslogd daemon provides system logging services to "clients". Simple API for "clients" A library provided by O.S.

25 Sending a message to syslogd
Standard programming interface provided by syslog() function: #include <syslog.h> void syslog( int priority, const char *message, . . . ); Works like printf() Un atbilstoši tāpat kā jāver vaļā un ciet faili arī log ir jāver vaļā un ciet.

26 syslogd Filesystem Unix domain socket /var/log/messages /dev/log
UDP socket port 514 Console /dev/klog Syslog atkarībā no unix un konfigurācijas var ņemt informāciju gan no lokāliem avotiem, gan arī ļauj saņemt informāciju no citiem, sistēmai nav vietas, kur logot vai arī drošības apsvērumu dēļ. Parasti gala sistēmā rezultāti tiek glabāti iekš /var/log un glavenie faili ir messages vai syslog, bet citi arī tiek izmantoti. Remote syslogd

27 Syslog messages Think of syslog as a server that accepts messages.
Each message includes a number of fields, including: a level indicating the importance (8 levels) LOG_EMERG 0 kernel panic LOG ALERT 1 condition needing immediate attention LOG_CRIT 2 critical conditions LOG_ERR 3 errors LOG_WARNING 4 warning messages LOG_NOTICE 5 not an error, but may need attention LOG_INFO 6 informational messages LOG_DEBUG 7 when debugging a system Atbilstoši sistēmai šie līmeņi var tikt izmantoti, piemēram, lai kritiskus paziņojumus izvadītu arī uz ekrāna/konsoles.

28 Syslog message fields (cont.)
a facility that indicates the type of process that sent the message: LOG_MAIL, LOG_AUTH, LOG_USER, LOG_KERN, LOG_LPR, . . . Timestamp (added by syslogd) uname –n (added by syslogd) A text string. Šie parametri var tikt izmantoti, lai dalītu ziņojumus plūsmas, piemēram, LOG_AUTH saglabāt atsevišķā failā /var/log/auth.log, ko visi unixi mūsdienās arī dara, jo to ziņojumu skaits ir liels un parasti skatoties log failus vajag kaut ko konkrētu.

29 Logfile example Dec 27 02:45:00 moet.colorado.edu 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]: moose.cs.colorado.edu has not answered 34 times Dec 27 02:55:33 bruno sendmail [28040] : host name/address mismatch: != bull.bull..fr Mūsdienās auth.log ir interesanti, ja ir publisks serveris ar iespējotu attālinātu pārvaldību ssh. Var redzēt ķīniešus citus inficētās sistēmas, kas mēģina uzlauzt, minot lietotājvārdus un paroles.

30 Dec 28 17:23:49 moet.colorado.edu SA-BOOK [84]: Testing...
/ * c program: syslog using openlog and closelog */ #include <syslog.h> main ( ) { openlog ( “SA-BOOK”, LOG_PID, LOG_USER); syslog ( LOG_WARNING, “Testing …. “); closelog ( ); } LOG_PID – iekļaut pid LOG_USER facility (varbūt raksīs failā user.log) On the host, this code produce the following log entry: Dec 28 17:23:49 moet.colorado.edu SA-BOOK [84]: Testing...

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

32 rsyslog Replaces syslog in many newer Linux distros
Configuration and old input backwards compatible with syslog Anonymization, Encryption, Signatures Speed Rate-Limiting New inputs - systemd New outputs – DB, compressed files Aizvieto pašu serveri, visi syslog izsaukumi paliek tie paši.

33 Back to daemons To force a process to run in the background, just fork() and have the parent exit. There are a number of ways to disassociate a process from any controlling terminal. Call fork()and then setsid() -Unix signāliem mēs varam signalizēt vecākam nobeigties. -setsid izveido jaunu sesiju un padara procesu par vecāku

34 Daemon initialization
Daemons should close all unnecessary descriptors often including stdin, stdout, stderr. Get set up for using syslog Call openlog() Often change working directory. OR take a risk Many POSIX-based operating systems provide a function called daemon() which performs some or all of the steps listed above. Unfortunately it has three significant drawbacks: It is not available on all systems. Its behaviour is not standardised (or necessarily well-documented). Its behaviour is more difficult to customise. -Parasti unixiem ir /dev/null, tas tiek atvērts visu aizvērto stamdarta in/out/err plūsmu vietā. - Ja grib logus, tad tos jāatver. - direktoriju parasti nomaina, jo atvērta direktorija var radīt tehniskas problēmas, piemēram, failsistēmas atmontēšana

35 Too many daemons? There can be many servers running as daemons - and idle most of the time. Much of the startup code is the same for these servers. Most of the servers are asleep most of the time, but use up space in the process table. - Vēsturiski RAM bija visierobežotākais resurs. - Nevarēja atļauties turēt atmiņā visus dēmonus, kas šobrīd netiek izmantoti - Šāds stāvoklis mūsdienās ir tikai sekundāriem procesiem lietotāja sistēmās ne serveros.

36 Internet Daemon Daemon inetd started at boot time
Configuration file /etc/inetd.conf Name (service name=port), type, protocol, wait-status, uid, server, arguments # 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

37

38 Internet Daemon When to modify inetd.conf Disable a service
Add a # at the beginning of the entry Send hang-up to inetd kill –HUP processid Enable a service Change the path Modify arguments -HUP signāls tas ir pieņemtais veids, kā unix dēmonam pateikt, pārlāde konfigurācijas failu un izmanto jaunos iestatījumus

39 inetd The SuperServer is named inetd. This single daemon creates multiple sockets and waits for (multiple) incoming requests. inetd typically uses select to watch multiple sockets for input. When a request arrives, inetd will fork and the child process handles the client.

40 inetd children The child process closes all unnecessary sockets.
The child dup’s the client socket to descriptors 0,1 and 2 (stdin, stdout, stderr). The child exec’s the real server program, which handles the request and exits. -sokets deskriptors tiek pārveidots par stdin/out deskriptioriem. Visi inetd serveri strādā šādā režīmā, tātad var uzrakstīt jebkādu programmu ar std in/out un darbināt to kā serveri -Katrs exec atbilstoši izpilda īsto serveri no diska, kas ir lēni.

41 Output file descriptor used for default
standard input keyboard standard output screen standard error screen

42 inetd based servers Servers that are started by inetd assume that the socket holding the request is already established (descriptors 0,1 or 2). TCP servers started by inetd don’t call accept, so they must call getpeername if they need to know the address of the client.

43 /etc/inetd.conf inetd reads a configuration file that lists all the services it should handle. inetd creates a socket for each listed service, and adds the socket to a fd_set given to select().

44 inetd service specification
For each service, inetd needs to know: the port number and transport protocol wait/nowait flag. login name the process should run as. pathname of real server program. command line arguments to server program. Wait – apkalpot vienlaicīgi tikai vienu klientu

45 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 tftp dgram udp wait root /usr/sbin/tftpd tftpd -s /tftpboot

46 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

47 wait/nowait Specifying WAIT means that inetd should not look for new clients for the service until the child (the real server) has terminated. TCP servers usually specify nowait - this means inetd can start multiple copies of the TCP server program - providing concurrency!

48 UDP & wait/nowait Most UDP services run with inetd told to wait until the child server has died. Some UDP servers hang out for a while, handling multiple clients before exiting. inetd was told to wait – so it ignores the socket until the UDP server exits. Ar UDP bieži ir tā, ka serveris noforko atsevišķu procesu komunikācijai un iziet, un tad inetd var apkalpot nākamo klientu uzreiz.

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

50 Servers Servers that are expected to deal with frequent requests are typically not run from inetd: mail, web, NFS. Many servers are written so that a command line option can be used to run the server from inetd.

51 xinetd Some versions of Unix provide a service very similar to inetd called xinetd. configuration scheme is different basic idea (functionality) is the same…

52 example /etc/xinetd.d # typical xinetd.conf defaults { 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 = /24 Papildus inetd ļauj: Servera prioritātes Piekļuves kontrole Laika periodu, kurā pieejams Instanču skaitu Logošanu u.c.

53 The Superservers Superservers listen on multiple network ports and start the appropriate service when a client connection arrives for that port. xinetd is a superserver gaining popularity It is a revised version of inetd that creates a more secure environment Shipped with Red Hat Linux xinetd lately is the most widely used superserver Application level security is provided via TCP Wrappers - the tcpd program Bija doma, ka xinetd aizvietos xinetd un standalone darbosies tikai serveri. Bet atmiņa palika pietiekami lēta un pietiekami daudz, ka nav vajadzības.

54 Managing Services Network Services The Inetd Model
- Stand alone vs Inetd 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 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

55 Managing Services 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 Typical Services to be Blocked - Finger, rwho, rsh , rlogin, rexec, echo, ntalk - FTP, Telnet - Use ssh, scp, sftp

56 Ports There are 65535 ports available Services tend to use <1024
These are “priviledged” ports, only root may listen on them If you have something running under a port you don't recognise, Find out what it is Decide if you need it - Parasti >32k ir izejošo savienojumu porti - Daļa sekundāru/administratīvu lietu ir uz >1024 portiem - ja ir serveris, tad ir jāveic audits, kas no ārpuses ir pieejams un visu nevajadzīgo jāslēdz ārā

57 Useful Tools Netstat -an Netstat -lp ps -ef chkrootkit
tells you what connections are active Netstat -lp tells which ports are listening ps -ef lists the running process chkrootkit checks for signs of rootkits Common rootkits install trojaned tools - Paļauties uz chkrootkit un līdzīgiem nekad nevar, biežāk neatrod nekā atrod.

58 Scheduling processes - cron
Many aspects of system administration require things to be done on a routine basis Rotating logs building help files checking disk space checking permissions Remembering to do thing is error prone Unix provides scheduling mechanism refereed to as cron. Cron has two parts Daemon - crond table of actions /etc/crontab Uz serveriem anacron tiek ļoti reti lietots, parasti tikai, ja uzstādīts pēc noklusējuma.

59 Cron the crond Daemon is started at boot time
the daemon ‘wakes up’ every minute to check its table of actions if their is something to do -> run command if nothing to do --> go back to sleep for 1 min Cron table is a list (time,commnd) pairs. The format is minute hour day month dayofweek command

60 Crontab Commands can be scheduled by Example minute (0 59)
Hour ( 0 to 23) Day of the month ( ) Month ( 1 to 12) Day of the week (0=Sunday 6 = sat, or use mon,tues,wed) Example 01 * * * * commnd2 # hourly at 1 minute past * 1 * * * commnd2 # daily at 1 am 04 1 * * * commnd3 # run at 4 minute past 1 each day * means ‘check every’

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

62 Crontab Files Minute 0-59 Hour 0-23 Day 1-31 Month 1-12
Weekday 0-6 (0=Sunday) * Matches everything 1-3 Matches range 1,5 Matches Series Special strings (same as 0 * * * *), @daily, @weekly, etc. Most special of

63 Examples Output mailed to owner of crontab file
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 {} ‘;’ Output mailed to owner of crontab file

64 crontab commands User crontab crontab Replace ^C exit crontab –l List
crontab –e Edit crontab –l > cronfile crontab cronfile cron.allow - If this file exists, it must contain your username for you to use cron jobs. cron.deny - If the cron.allow file does not exist but this does then, you must not be listed here. System crontab Just edit /etc/crontab as root, nowadays it reloads automatically

65 The cron utility The cron utility runs in the background and constantly checks the /etc/crontab file. 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.

66 Common Uses for CRON Cleaning the filesystem
Distribution of config files Rotating log files Backups Heavy task offloading

67 The cron utility The cron utility uses two different types of configuration files, the system crontab and user crontabs. 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.

68 The cron utility # /etc/crontab - root's crontab for FreeBSD #
# $FreeBSD: src/etc/crontab,v /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

69 The cron utility 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. 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. 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. 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. 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. - PATH svarīgs mainīgais, dažādiem crontabiem/distro dažādi path un komandas var palikt neportēajamas, tad viens no risinājumiem ir izmantot pilnos ceļus - labā prakse likt vienu komandu, ja tā nav garāka par imznatotā temināla outputu, citos gadījumos veidot atsevišķu skriptus

70 The cron utility Installing a Crontab
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 version. 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. 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. If you later want to remove your user crontab completely, use crontab with the -r option.

71 Unix Security

72 Security Hardening : Access Control
TCP Wrappers Effective Access Control Mechanism Invisible Layer to Block or Permit Access to Services Hostname, IPAddresses, Logging /etc/hosts.allow /etc/hosts.deny - Oriģinālais veids kā nodrošināt piekļuves ierobežošanu programmām, kurām tādas funkcionalitātes nav, programmas netiek mainītas. Ja ugunsmūri nav pieejami. - Šobrīd nav nekādu ieguvumu un access control izmanto ugunsmūrus

73 TCP Wrappers TCP Wrappers - tcpd - is an application- level access control program TCP Wrappers is not a firewall and should be used with one if Linux security issues exist Configuration is done by two files: /etc/hosts.allow and /etc/hosts.deny Ensure proper and expected configuration by testing carefully before relying on it Use transparently with inetd OR link explicitly a daemon with the libwrap shared library Pastāvīgi funkcionējošiem dēmoniem ir iespēja pielinkot libwrap un jau programmas kodā izmantot definēto piekļuves kontroli.

74 TCP Wrappers

75 TCP Wrappers

76 Konfigurācijā redzams, ka izpildāmie faili aizvietoti ar tcpd, tātad vēl vairāk resursu tērēšana un, ja izmanto dns lookupus access controlēi, tad arī tie dubultojas.

77 Security Hardening : Access Control
Firewalls What is a Firewall? Access control policy Isolates networks Packet Filtering IPTables Chains (Input, Output, Forward) Targets (Accept, Drop, Reject, Log) Efficient Packet Filtering based on protocols, IP Address, state/stateless etc # iptables -A INPUT -s j DROP

78 Security tools Security tool (Bastille / Titan / JASS)
Host intrusion detection systems Monitor changes in filesystems/memory Record attributes and checksums in a secure location Compare later and report anomalies (Network) Intrusion detection or prevention systems Monitor host or whole network Signature-Based Detection Statistical anomaly-based detection Stateful Protocol Analysis Detection - Konfigurē sistēmu, dēmonus, ugunsmūrus pēc aktuālām drošības prasībām, kuras vidējs unix lietotājs var nepārzināt. - Vienīgais veids kā uzzināt par to, ka sistēma ir kompromitēta ir salīdzināt tās stāvokli ar kādu snapshot no pagātnes, kad sistēma nebija kompromitēta.

79 Linux Packet Filtering types
Ipfw (Linux 1.2 kernels) Ipfwadm (Linux 2.0 kernels) Ipchains (Linux 2.2 kernels) Iptables (Linux 2.4 kernels) Iptables (Linux 2.6 kernels) Iptables (Linux 3.* kernels)

80 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/ sport 1024:65535 –d localhost/32 - -dport domain –j ACCEPT #domain/udp (O) Allow DNS query from localhost to localhost (nothing useful) When a packet is logged, it shows up in /var/log/messages in the above format. The normal syslog fields of Date, time, machine name and the fact the kernel logged this show up first. IN= and OUT=lo show the respective interfaces that the packet comes from and goes to. Since this packet was created on the system and is heading out, only an outgoing interface is listed. SRC=and DST= show the source and destination IP address of the packet. LEN=73 is the length of the total packet. My best guess for the later LEN=53 is the length of the UDP headers and payload. TOS is for Type Of Service and PREC= is for precedence, I believe. They’re not currently used, although Mason made an attempt to correctly set these in ipchains. TTL is Time to live, ID is the IP ID, and DF means Don’t fragment. These are are also not needed in the rule creation process. PROTO= shows the protocol, and SPT and DPT=show the source and destination port. Mason looks for and 53 in /etc/services; when it finds 53 but not , it assumes that 53 is the server in this case. Mason reads this line and offers the rule on the next slide as a rule that would match this packet.

81 IPTables Plūsmas stāvokļi.

82 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 \ --state RELATED,ESTABLISHED –j ACCEPT iptables –A INPUT –i lo –j ACCEPT iptables –P INPUT DROP - Atļaujam visu tcp komunikāciju ar hosta 22 portu - Bet tas nav pietiekami, jo šis likums kontrolē tikai mūsu izejošās paketes un pēdējais likums izmet visas paketes - Otrais likums atļauj ienākošās paketes jau iniciētiem (šajā gadījumā mūsu tcp iniciētiem savienojumiem) - state machine, kas uztur tabulu ar visiem tcp savienojumu stāvokļiem

83 Iptables Rules: Allow TCP through the bridge, feed to Snort
iptables –A FORWARD –m state \ --state RELATED,ESTABLISHED –j QUEUE iptables –A FORWARD –p tcp –m state \ --state NEW,RELATED –j QUEUE - Pievienojama pakas rindai kodolā, no kuras pakešu analizators vai jebkāda cita programmatūra ar atbilstošām tiesībām tās var ielasīt un kaut kādā veidā apstrādāt

84 Masquerading Modem connections/DHCP
Doesn’t drop connections when address changes 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 Nat, viena reālā ip adrese un tīkls ar vairākām mašīnām, kurām ir privātas IP adreses. Visas mazās wifi rūtera kastītes izmanto šo.

85 Configuring NAT with iptable
First example: iptables –t nat –A POSTROUTING –s –j SNAT --to-source Pooling of IP addresses: iptables –t nat –A POSTROUTING –s / –j SNAT --to-source – ISP migration: iptables –t nat –R POSTROUTING –s / –j SNAT --to-source – IP masquerading: iptables –t nat –A POSTROUTING –s / –o eth1 –j MASQUERADE Load balancing: iptables -t nat -A PREROUTING -i eth1 -j DNAT --to- destination - viena privāta IP adrese uz vienu publisku, reti vajadzīgs - privāts tīkls uz nelielu skaitu publisku IP adrešu, ja ir liels privāts tīkls, tad ar 1 publisku IP adresi var nepietikt. - ja mainās IPS vai arī kādi skripti, kas detektē, ka savienojums ar pirmo IPS ir pazudis, tad pārliekam visu uz otro. Visi aktīvie tcp savienojumi tiks salauzti. - dinamiska IP adrese, kas var nomainīties - apgriezta pieeja, saņemam paketes un nododam tās dažādiem hostiem. TCP savienojumus nat uztur, līdz ar to nākamas savienojuma paketes nonāks tam pašam serverim.

86 Configuring NAT in Linux
Linux uses the Netfilter/iptable package to add filtering rules to the IP module - Likumi atbilstoši šiem stāvokļiem.

87 Source NAT 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 - Tiek uzturēta stāvokļu tabula, līdz ar to lielam tīklam vajag daudz IP adrešu un portu, citādi stāvokļu tabula pārpildās un aktīvie savienojumi tiek iznīcināti.

88 Destination NAT 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 \ --to-destination -d –dport 80 –j REDIRECT Ja ir nepieciešams piekļūt kāda iekšējā tīkla datora portam no ārpuses (veidojot jaunu savienojumu), tad izmanto destination nat, tādā veidā strādā port forwarding visos mazajos wifi rūterīšos.

89 Load Balancing Source Policy Routing: Make sure Person A, who pays the lower rate, gets routed over the house modem instead of the DSL Split Access for Multiple Uplinks: Packets coming in from ISP A go back out ISP A Load Balancing: default route becomes a multipath path route, balance routes over 2 providers iptables –t nat –A PREROUTING –i eth0 –d –p tcp –-dport 80 –j DNAT –-to-destination - Darbojas abos virzienos, pēdējais piemērs ir balansēšana no interneta uz mūsu serveriem. - NAT tabulas nodrošina, ka paketes iet pa izvēlēto linku vai nu speciāli balansētu vai arī iekonfigurētu. - Tā nav īsta interneta maršrutēšana serveru izpratnē, maršrutēšana tikai sava tīkla ietvaros.

90 -Unix ir vairāki dažādi populāri FW, dara vienu un to pašu definē stateless likumus,ja ir iespēja, tad tos precizē ar state likumiem. -Beigās aizliedz visu nedefinēto

91 - rootkit programmatūra, kas ļauj saglabāt root kontroli par sistēmu un noslēpt savu klātesamību. Aizvietot kādu programmatūru, piemēram, cron. Vai riebīgāki kodolu vai kodola moduļus, iekārtu draiverus.

92 Hacked WebServer

93 Queuing Disciplines First-In-First-Out (FIFO) Priority Queuing
no classes fast, easy to implement Priority Queuing all traffic in a high-priority class is sent before any in a lower priority one Class-based Queuing (CBQ) a number of bytes is sent from each class before going to the next class Internets tik ātrs, ka vienkāršos un mājas tīklu gadījumā nesaskaras ar šo. Lielos tīklos, šobrīd visbiežāk izmanto priority queuing, piemēram, reālā laika komunikācija VoIP augstākā prioritāte, tad iet web, tad citi standarta protokoli un tad p2p ar viszemāko klasi, ja tīkls tiek pārslogots, piemēram pīķa stundās, tad p2p strādā ļoti lēni.

94 Unix Traffic Shaping CBQ is an interface to the Linux tc command
tc (traffic control) Other queuing systems besides CBQ are available HBQ, TBF, SFQ

95 Link Sharing between CBQ Traffic Classes

96 Link Sharing Goal Over appropriate time-intervals,
each interior or leaf class should receive its allocated bandwidth (given sufficient demand)

97 CBQ – Class Based Queue Linux Bwmgr eth0 eth3 TRIUMF Internet 10Mpbs
2Mbps Linux Bwmgr /16 UBC 10Mbps /16 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 Šāda nav pārāk aktuāli.

98 QOS – Outgoing Packets (Classless)
pfifo_fast – first in first out – 3 bands, packets in Band 0 get handled, then Band 1, etc. Token Bucket Filter – Rate does not exceed some limit, but bursting is possible with enough tokens Allows uploading without killing interactive sessions: tc qdisc add dev ppp0 root tbf rate 220kbit latency 50ms burst 1540 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 red - Random Early Detection simulates physical congestion by randomly dropping packets when nearing configured bandwidth allocation. Well suited to very large bandwidth applications. Stochastic Fairness Queueing – no aktras rindas sūtam pa paketei Red – labi strādā ar tcp, tcp protokols pats palēnina komunikāciju

99 Bridging Linux 2.4 kernel (2.4.21)
bridging support built into 2.4 kernels If you also want iptables support on the bridge must also install the ebtables-brnf patch for your kernel Bridge is configured using tools from bridge-utils brctl addbr br0; brctl addif br0 eth0; brctl addif br0 eth3 iplink set br0 up; ifconfig eth0 up ifconfig eth3 up ip addr add /24 brd + dev br0 Iespējams savienot Layer 2 līmenī tīklus, mūsdienās fiziskiem interfeisiem maza jēga, bet tiek pielietots dažos virtualizācijas risinājumos nosimulējot L2 piekļuvi tīklam virtulizētajā mašīnā. Var strādāt arī kā L2 filtrētājs un šaperis.

100 Build the Bridge No Spanning Tree Protocol: Turn it on:
ifconfig eth up ifconfig eth up brctl addbr br0 brctl addif br0 eth0 brctl addif br0 eth1 No Spanning Tree Protocol: brctl stp br0 off Turn it on: ifconfig br up Or give the bridge an IP address and turn it on: ifconfig br netmask up route add default gw Tāpat kā switchos ir vajadzīgs STP protokols, lai neveidotu cilpas.

101 “If it was hard to develop, it should be hard to install!”
Networking Software Good free implementations for: DNS BIND v8/9, djbdns SMTP sendmail, qmail, postfix, exim POP/IMAP qpopper, uwimapd HTTP Apache, nginx PHP, mySQL “If it was hard to develop, it should be hard to install!”

102 Setting Up a Basic Name Server
Later versions of BIND use the configuration file /etc/named.conf This file is divided into five sections: options, controls, three different zones and an include line, which refers to the rndc security file A zone is a part of the DNS domain tree for which the DNS server has authority to provide information Zone information is contained in files referred to in named.conf BIND pirmā dns programmatūras serveris. Vēsturiski daudz dažādu bagu tika atklāts.

103 DNS Using DNS system Before Internet network started use DNS system there was hosts files. However there are one main disadvantage of using host file - search time increase exponentially. This is the main reason why Internet network started use DNS system. By the way, DNS system let you use distributed administrative model in order to delegate administrative rights to other people. Hosts failā, jo vairāk ierakstu jo lēnāka meklēšana. Plus lēna atjaunošana no kāda nezināma vai neuzticama avota.

104 DNS You can imagine DNS system structure using image below: net
"." (root) com edu au ru .ru domain msu wsu .wsu.ru domain gw gw1 host gw.wsu.ru gw1.wsu.ru wsu.ru Centrālā autoritāte, kas nodot kādu zonu zemāk administrēšanai un

105 DNS DNS zones terra flora www com edu gov … mfg ntserver
Terraflora.com domain mfg.terraflora.com zone terraflora.com zone servers

106 DNS DNS request: Required information for DNS requests
Making DNS requests DNS requests types: Recursive requests Iterative requests Nameserver1 ir rekursīvs DNS serveris, tie ir parasti IPS serveri vai tīkla serveri, apstrādā visus DNS pieprasījumus. 6. ir atbilstoši domēna autoritatīvais serveris, kurš atbild tikai uz šādu pieprasījumu, pieprasījums ir tāds pats kā 1 sūtītais

107 DNS ada.wsu.ru IP(crypt.iae.nsk.su) = ? Root servers
Authoritative server for nsk.su - ns.nsk.su server ns.nsk.su iaebox.iae.nsk.su IP(crypt.iae.nsk.su) = Authoritative server for iae.nsk.su - iaebox.iae.nsk.su ns.wsu.ru Domēnu vārda kokā nav iespējams ielekt vajadzīgā vietā, ejam atbilstoši pa koku līdz lapai - autoritatīvajam serverim.

108 DNS DNS system planning factors.
Number of servers and system platforms Server types: Primary server Secondary servers Cache servers Forward servers Stealth servers 13 klāsteri ar root serveriem, kas apkalpo visu internetu. Bieži uzbrucēju mēŗkis, bet vēl nav sanācis nogāzt šo sistēmu. DNS specifikācija paredz, ka domēnam jābūt 2 Ns serveriem primāram un sekundāram, drošībai. Uz primārā servera ir master zona un uz otro notiek zonas transfers. Cache serveri - ir tie, kurus IPS izvieto savā tīklā, lai samazinātu ārējā tīkla noslodzi un paātrinātu pieprasījumu apstrādi. Daži slikti Ips izvieto tādus cache, kas pārraksta TTL vērtības un salauž daļu domēna vārdu. Forwarder – saņem pieprasījumus no citiem DNS serveriem, kuri apkalpo tīklu un varbūt satur (slepenu) iekšējo zonu, un mēģina atgriezt atbildi veicot iterācijas Stealth – serveri uztur kontroli, bet autoritatīvi ir citi serveri, kuri darbojas kā slave

109 DNS DNS database resource records (RR) DNS database RR forms and types
Standard RR DNS database file structure IN-ADDR.ARPA zone for reverse address- to-name translation -Izmanto arī IP adrešu mapošanu, logošanai, antispama, drošības u.c. - uzbūvēts izmantojot domēnu IN-ADDR.arpa apgriežot 8 bitu porcijas otrādi, lai varētu funkcionēt tieši tāpat kā domēni un veikt lokupu iteratīvi.

110 DNS RR format TYPE contain RR type code CLASS contain RR class code
TTL contain Time to Live value RDLENGTH – data length RDATA – data NAME TYPE CLASS TTL RDLENGTH RDATA 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

111 DNS DNS CLASS types DNS RR types A IN NS CS MX CH MD HS MF CNAME SOA
WKS SRV TXT PTR Resource record tipi atbilstoši dažādām vajadzībām un protokoliem Class atbilst tiklam un internetā izmanto IN, citi ir cietiem tīkliem, bet mūsdienās tie ir tikai lieki izšķērdēti 2 baiti.

112 DNS 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.

113 DNS Split DNS example: … view "internal" {
match-clients { / 8 ; }; recursion yes; zone "example.com" { type master; file "example-internal.db"; }; view "external" { match-clients { any; }; recursion no; file "example-external.db"; …. Pareizi nokonfigurēts, ka tikai iekšējiem klientiem atļaujam veikt rekursīvus pieprasījumus, bet ārējiem tikai autoritatīvos savai zonai example.com.

114 DNS file "named.local"; allow-update { none; };
zone "test.lv" { type master; file "test.lv.zone"; view "external" { match-clients { any; }; recursion no; zone "." IN { type hint; file "named.ca"; file "test.lv.public.zone"; DNS configuration file example: logging { category lame-servers { null; }; }; options { directory "/var/named"; allow-transfer { ; ; ; }; recursive-clients 2000; notify yes; acl "internals" { ; /16; /24; /24; /24; view "internal" { match-clients { "internals"; }; recursion yes; zone "." IN { type hint; file "named.ca"; zone " in-addr.arpa" IN { type master; Hint fails ir vajadzīgs, jo serveris nekādā veidā nevar zināt par root serveriem. Autoritatīvajam serverim mums ir dažādas zonas iekšējā tīklā un ārējā.

115 DNS DNS server database file: ; ; test WWW on Lattelekom servers
$ORIGIN . $TTL ; 1 hour test.lv IN SOA ns1.test.lv. jurisk.test.lv. ( ; serial ; refresh (8 hours) ; retry (5 minutes) ; expire (2 weeks) ; minimum (1 hour) ) NS ns1.test.lv. A MX eproxy.test.lv. MX eproxy1.test.lv. MX eproxy2.test.lv. $ORIGIN test.lv. router A eproxy A eproxy A eproxy A ns A mail CNAME ns1 nais A ; ; test WWW on Lattelekom servers www A admin A editor A www A tavro A tekno A $ORIGIN it.test.lv. router A $ORIGIN test.lv. proxy A help A ssiahq A nw A Parasti izmanto atmiņas bakendus vai arī tranzakciju db, lai varētu ļaut vienlaicīgu redigēšanu, parasti domēnu reģistrētāji.

116 DNS Reverse DNS zone in-addr.arpa $ORIGIN . $TTL 3600 ; 1 hour
in-addr.arpa IN SOA ns1.test.lv. root.ns1.test.lv. ( ; serial ; refresh (1 hour) ; retry (5 minutes) ; expire (5 weeks 6 days 16 hours) ; minimum (1 hour) ) NS ns1.test.lv. $ORIGIN in-addr.arpa. PTR router.it.test.lv. PTR instructor.it2.test.lv. PTR proxy2.test.lv. PTR help.test.lv. PTR ssiahq01.test.lv. PTR nw1.test.lv. PTR sandbox.test.lv. PTR rs6000f50.test.lv. PTR risc6000f30.test.lv. Reversā mapošanā mazākā iedaļa tas ir viens 8 bitu /24 segments, ko var nodot citam serverim.

117 Restart named sudo /sbin/service named restart Password: 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, #53 Jan 28 22:36:22 womnibook named[11333]: listening on IPv4 interface eth0, #53 Jan 28 22:36:22 womnibook named[11333]: listening on IPv4 interface eth1, #53 Jan 28 22:36:22 womnibook named[11333]: command channel listening on #953 Jan 28 22:36:22 womnibook named[11333]: zone johannes.org/IN: loaded serial 142 Jan 28 22:36:22 womnibook named[11333]: running Jan 28 22:36:22 womnibook named[11333]: zone johannes.org/IN: sending notifies (serial 142) Jan 28 22:36:22 womnibook named: named startup succeeded

118 DNS Usefull utilities: Dig Host Nslookup Rndc Named-checkzone
Name-checkconfig -Tīkla debugošanai, serveru debugošanai u.t.t. - Salīdzināt rezultātu ar kādu citu rekursīvo serveri - Pārbaudīt vērtību autoritatīvā serverī

119 Using Command-line Utilities

120 Mailservers Maturity Security Features Performance qmail medium high
Sendmail low Postfix exim Courier Iemesls kādēļ ir daudz kvalitatīvu mail serveru. Šobrīd vairs nav aktuāla, bet tie ir iemesli kādēļ jauni serveri radās. Bron: Life with qmail, p. 5

121 Configuring a Basic Email Server
Sendmail is the most widely used server The sendmail package contains the sendmail daemon Sendmail is started using a script in /etc/rc.d/init.d Sendmail is configured using the file /etc/sendmail.cf Most administrators prefer to use the m4 program to configure sendmail Vēsturiski vismurgainākā un sarežģītākā konfigurācija.

122 Email basics MUA MUA Email database Email database SMTP MTA MDA MDA
Mail Server Mail Server database database SMTP MTA MDA MDA MTA POP3/IMAP SMTP Workstation Workstation MUA MUA

123 Simplified Mail Transactions
Mail User Agent Mail Transport Agent Mail Transport Agent Mail User Agent Mail Delivery Agent Mail Delivery Agent mbox mbox -Vēsturiski ir veids kā apmainīties ar ziņojumiem vienas sistēmas (maifreima) ietvaros -Pēc tam paplašināts uz vairākiem mainfeimiem tīklā - Un tad uz visu internetu, kas ir iemesls tam, ka ir problēmas - local mbox - jebkurš var sūtīt - caurumi un slikta konfigurācija - realitātē uzbūve ir briesmīga, bet visi lieto un lietos us Message composed using an MUA MUA gives message to MTA for delivery If local, the MTA gives it to the local MDA If remote, transfer to another MTA

124 Watching sendmail Work

125 Watching sendmail Work

126 Structure of qmail qmail-smtpd qmail-inject qmail-queue
Other incoming mail Incoming SMTP mail qmail-send qmail-rspawn qmail-lspawn qmail-remote qmail-local

127 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 &

128 Configuration of qmail
Configuration stored in /var/qmail/control/ Configure: Relaying Multiple host names Virtual domains Aliases qmail-users Blackhole lists Mailbox formaat

129 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. D.J.Bernstein On November 1, 2007, Bernstein raised the reward to US$1000.

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

131 Principles, sendmail vs qmail
Programs and files are not addresses sendmail treats programs and files as addresses “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” (DJB) qmail programs and files are not addresses “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.”

132 Keep it simple Parsing Libraries Limited parsing of strings
Minimizes risk of security holes from configuration errors Libraries Avoid standard C library, stdio “Write bug-free code” (DJB)

133 Webmail system (SquirreMail)
Web server Mail Server Workstation Webmail client (Squirre Mail) browser MUA database MTA Citi un labāki interfeisi piejami, lu jau sen pārgāja uz roundcube. Vienkārši klients, kas darbojas uz servera var funkcionēt pilnīgi vienādi ar desktop klientu, izmantojot pop/smtp protokolus

134

135

136

137 Apache what is Apache? Apache’s functionality installing Apache
directory structure configuration tools

138 Outline Apache Dynamic Content CGI PHP MySQL

139 If you request an HTML file
Browser Webserver HTML 1 2 3 4

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

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

142 Apache functionality DBM databases for authentication
customized responses to errors and problems unlimited flexible URL rewriting and aliasing Virtual Hosts Configurable Reliable Piped Logs

143 Apache modules (1) mod_access mod_alias mod_auth mod_autoindex mod_cgi
Access control based on client hostname or IP address mod_alias Mapping different parts of the host filesystem in the document tree, and URL redirection mod_auth User authentication using text files mod_autoindex Automatic directory listings mod_cgi Invoking CGI scripts

144 Apache modules (2) mod_include mod_mime mod_proxy mod_rewrite
Server-parsed documents mod_mime Determining document types using file extensions mod_proxy Caching proxy abilities mod_rewrite Powerful URI-to-filename mapping using regular expressions mod_usertrack User tracking using Cookies mod_vhost_alias Support for dynamically configured mass virtual hosting

145 Apache modules (3) mod_ssl
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. Requires Apache 1.3.x and OpenSSL 0.9.x Private and Public keys Thawte (www.thawte.com), Versisign (www.verisign.com)

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

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

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

149 Testing Apache installation
ps aux | grep apache root ? Ss Nov15 0:02 /usr/local/apache/bin/httpd root ? Ss Nov15 0:00 /usr/local/apache- ssl/bin/httpd -DSSL apache ? S Nov15 0:27 /usr/local/apache- ssl/bin/httpd -DSSL apache ? S Nov15 0:26 /usr/local/apache- ssl/bin/httpd -DSSL apache ? S Nov17 0:31 /usr/local/apache/bin/httpd apache ? S Nov18 8:54 /usr/local/apache/bin/httpd ....

150 Testing Apache installation

151 Apache directory layout
Debian /etc/init.d/apache Apache control script /etc/apache Apache configuration files /var/www Default Document Root /usr/lib/cgi-bin Default script directory

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

153 Apache directory layout (3)
Slackware /usr/local/apache /usr/local/apache/conf /usr/local/apache/htdocs /usr/local/apache/cgi-bin /var/log/apache /usr/local/apache/bin

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

155 Apache error log ErrorLog /usr/local/apache/logs/error_log
LogLevel warn [Sun Nov 21 09:13: ] [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: ] [error] [client ] File does not exist: /home/sms/public_html/favicon.ico [Sun Nov 21 13:02: ] [error] [client ] File does not exist: /home/code/public_html/robots.txt [Sun Nov 21 13:08: ] [error] [client ] File does not exist: /home/refuser2/public_html/_vti_bin/owssvr.dll [Sun Nov 21 13:08: ] [error] [client ] File does not exist: /home/refuser2/public_html/MSOffice/cltreq.asp [Sun Nov 21 13:09: ] [error] [client ] File does not exist: /home/refuser2/public_html/_vti_bin/owssvr.dll [Sun Nov 21 13:09: ] [error] [client ] File does not exist: /home/refuser2/public_html/MSOffice/cltreq.asp

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

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

158 Apache configuration .htaccess htpasswd AuthType Basic
AuthUserFile /home/someuser/passwd AuthName "Admin" require valid-user htpasswd htpasswd -c <password file> <username> user1:Y90u499mUj6xE user2:DOrWgcNwzaQUQ

159

160

161

162

163 Apache2 Unix Threading New Build System Multiprotocol Support
New Apache API IPv6 Support Filtering Multilanguage Error Responses Regular Expression Library Updated

164 Dynamic content Script Engine (PHP, Perl, ...) Browser Webserver 1 2 3
HTML & Scripts 1 2 3 4 5 6

165 Dynamic content Scripting engine CGI PHP Apache module vs. CGI

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

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

168 Dynamic content Two ways how to server dynamic content
CGI Apache module Many programming languages to use PHP, Perl, Python, C, C++, shell scripts ...

169 Common gateway interface (CGI)
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.

170 CGI example Shell script #!/bin/bash echo "Content-type: text/plain"
echo "Hello world!" echo "Today is:" `date`

171 CGI example (2) Perl script #!/usr/bin/perl
print "Content-type: text/plain\n\n"; print "Hello world!\n"; print "Today is: " . localtime() . "\n";

172 Apache modules mod_perl mod_php mod_python, OpenASP Module, ...
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 more. mod_php PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML mod_python, OpenASP Module, ...

173 PHP What is PHP? Installing PHP Configuring PHP

174 PHP: Hypertext Preprocessor (PHP)
<html>    <head>        <title>Example</title>    </head>    <body>        <?php        echo "Hi, I'm a PHP script!";        ?>    </body> </html>

175 PHP Pros Cons easy to learn ideal for small projects widely used
no strong typing Cons code maintenance interpreted language executes in the Web server process

176 Installing PHP Server-side scripting Command line scripting
Client-side GUI applications

177 Installing PHP 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

178 Installing PHP Source instalation Install PHP
./configure --with-mysql --with-apxs=/www/bin/apxs make make install cp php.ini-dist /usr/local/lib/php.ini Edit your httpd.conf to load the PHP module. LoadModule php4_module libexec/libphp4.so AddModule mod_php4.c AddType application/x-httpd-php .php .phtml Restart Apache

179 PHP Configuration 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"

180 PHP Configuration 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

181 PHP Configuration Apache configuration file
<VirtualHost > DocumentRoot /home/someuser/public_html ServerName <Directory /home/someuser/public_html/> php_admin_value open_basedir /home/someuser/:/tmp/:/usr/share/pear/ php_value auto_prepend_file /home/someuser/includes/default.inc php_value upload_max_filesize 10M </Directory> </VirtualHost>

182 PHP Configuration .htaccess file PHP scripts
AddType application/x-httpd-php .php3 php_value include_path .:/home/someuser/includes:/home/someuser/public_html php_flag register_globals Off PHP scripts <? ini_set("display_errors", "true"); ini_set("error_log","/home/someuser/log/php.log"); ...

183 Apache module vs. CGI Apache module CGI fastCGI Good performance
One user for all websites Other user’s source files can be accessed PHP safe_mode CGI New process each time suEXEC – each website under its own user fastCGI

184 Apache, PHP and MySQL PHP Engine Browser Webserver MySQL Database
HTML & PHP 1 2 3 4 5 6 7 8

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

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

187 MySQL 4.x Subqueries New client-server protocol with prepared statements Unicode and UTF-8 support Query cashing Much more...

188 Installing MySQL 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 &

189 Installing MySQL 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 &

190 Post-Instalation Procedures
Check instalation shell> bin/mysqladmin version Create system tables shell> bin/mysql_install_db --user=mysql Make nessesary databases and users CREATE DATABASE GRANT

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

192 MySQL binaries mysql mysqladmin mysqldump MySQL client
MySQL administration tool mysqldump Tool for creating database dumps

193 MySQL commands CREATE DATABASE <database name> DROP
GRANT ALL PRIVILEGES on database.* to IDENTIFIED BY ‘password’ Privilege type (ALL, ALTER, CREATE, DELETE, INSERT, SELECT, GRANT, ...) Privilege level (globa, database, table, column) User and host (localhost, IP address, network, %) REVOKE

194 PHP and database example
MySQL and SQLite Examples

195 PHPMyAdmin phpMyAdmin is a tool written in PHP intended to handle the administration of MySQL over the Web (http://www.phpmyadmin.net/) CREATE/DROP databases CREATE/DROP/ALTER tables Delete/add/edit/search information Execute SQL queries Manage privileges Export data

196

197

198 PHP and SQLite example <?php // create new database (OO interface) $db = new SQLiteDatabase("db.sqlite"); // create table foo and insert sample data $db->query("BEGIN;         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');         COMMIT;"); // execute a query     $result = $db->query("SELECT * FROM foo"); // iterate through the retrieved rows while ($result->valid()) {     // fetch current row     $row = $result->current();          print_r($row); // proceed to next row     $result->next(); } // not generally needed as PHP will destroy the connection unset($db); ?>

199 PHP and MySQL example <?php // 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 mysql_free_result($result); // Closing connection mysql_close($link); ?>


Download ppt "Guntis Barzdins Girts Folkmanis Juris Krūmiņš Artūrs Lavrenovs"

Similar presentations


Ads by Google