[安全運維向]模擬搭建小型企業內網

實驗目的
根據小型企業實際情況,模擬搭建小型局域網,針對常見內網滲透攻擊手段(如ddos、ssh爆破等)做相應配置。實驗目標是提高運維新手的安全運維能力。
網絡拓撲

場景介紹
局域網下含有物理機、proxy server主機。物理機即普通客戶主機,proxy server即企業提供的代理,此網絡模擬的是公網環境。
Nat網絡下含有HTTP server、Backup server、nis server、Client主機。此網絡模擬的是公司內網環境。
主機介紹
物理機:設置瀏覽器代理為同一網段下的192.168.1.10,可訪問192.168.56.102門戶網站。
Proxy server:關停一切不必要的端口,偽裝ssh端口為1022,需要重點考慮防火墻的設置,檢測日志信息,短時間內登錄ssh超過一定失敗次數則給root用戶發郵件提醒,提供squid代理服務。
Http server:架設由https協議保護的門戶網站,并提供rsync服務,需要考慮防火墻的設置,設置iptables,僅僅讓proxy server訪問80、443端口。
Backup server:rsync保存http server的日志信息。
Nis server:為client、backup server這兩個服務器提供賬號管理服務。
client:配置簡易防火墻。
詳細配置
特殊配置
在192.168.56.0/24這個網段下,除了proxy server這個服務器可以被物理機訪問,其他主機需要設置不能被局域網以外的其他ip訪問。這個可以通過設置iptables實現:
# ban 物理機iptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.1 -j DROP# 只允許同網段的ip連接iptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.0/24 -j ACCEPT
Proxy server
1.防火墻配置
# 清空原有配置iptables -Fiptables -Xiptables -Z # input 表默認策略 丟棄iptables -P INPUT DROPiptables -P OUTPUT ACCEPTiptables -P FORWARD ACCEPT # -A 增加規則,-i 指定網卡,-j 指示動作,-m 模組,-p 協議# --dport 目標端口,--sport 源端口#-m state --state RELATED,ESTABLISHED 指定要匹配包的的狀態,當前有4種狀態可用:INVALID,ESTABLISHED,NEW和RELATED。 INVALID意味著這個包沒有已知的流或連接與之關聯,也可能是它包含的數據或包頭有問題。ESTABLISHED意思是包是完全有效的,而且屬于一個已建立的連接,這個連接的兩端都已經有數據發送。NEW表示包將要或已經開始建立一個新的連接,或者是這個包和一個還沒有在兩端都有數據發送的連接有關。RELATED說明包正在建立一個新的連接,這個連接是和一個已建立的連接相關的。iptables -A INPUT -i lo -j ACCEPTiptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -A INPUT -p TCP -i enp0s3 --dport 111 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s3 --dport 1022 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s3 --dport 3128 --sport 1024:65534 -j ACCEPTiptables-save > /home/dc/iptables.mysettings
并設置/etc/crontab文件
ELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root # For details see man 4 crontabs # Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed# apply my iptables from file per minute. * * * * * root /sbin/iptables-restore /home/dc/iptables.mysettings
開啟內核管理功能:
[root@localhost dc]# vim /etc/sysctl.conf[root@localhost dc]# cat /etc/sysctl.conf# sysctl settings are defined through files in# /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.## Vendors settings live in /usr/lib/sysctl.d/.# To override a whole file, create a new file with the same in# /etc/sysctl.d/ and put new settings there. To override# only specific settings, add a file with a lexically later# name in /etc/sysctl.d/ and put new settings there.## For more information, see sysctl.conf(5) and sysctl.d(5). # Turn on syncookies for SYN flood attack protection#net.ipv4.tcp_syncookies = 1 # Avoid a smurf attack#net.ipv4.icmp_echo_ignore_broadcasts = 1 # Turn on reverse path filtering#net.ipv4.conf.all.rp_filter = 1net.ipv4.conf.default.rp_filter = 1net.ipv4.conf.enp0s8.rp_filter = 1net.ipv4.conf.lo.rp_filter = 1# Turn on and log spoofed, source routed, and redirect packetsnet.ipv4.conf.all.log_martians = 1net.ipv4.conf.default.log_martians = 1net.ipv4.conf.enp0s8.log_martians = 1net.ipv4.conf.lo.log_martians = 1 # Make sure no one can alter the routing tables#net.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.default.accept_redirects = 0net.ipv4.conf.enp0s8.accept_redirects = 0net.ipv4.conf.lo.accept_redirects = 0 # redirects projectnet.ipv4.conf.all.send_redirects = 0net.ipv4.conf.default.send_redirects = 0net.ipv4.conf.enp0s8.send_redirects = 0net.ipv4.conf.lo.send_redirects = 0[root@localhost dc]# sysctl -p
設置完畢之后可以重啟查看防火墻設置是否生效。
2.關停一切不必要的端口
查看開啟的端口發現這一項:
[root@localhost dc]# netstat -tulnptcp6 0 0 ::1:631 :::* LISTEN 1267/cupsd
根據鳥哥的書中提示,我利用systemctl命令關閉了cups服務。systemctl disable cups.service,也可以使用ntsysv命令查看、關閉不必要的服務。
3.偽裝ssh端口為1022
/etc/ssh/sshd_config:
```Port 1022#AddressFamily any#ListenAddress 0.0.0.0#ListenAddress :: HostKey /etc/ssh/ssh_host_rsa_key#HostKey /etc/ssh/ssh_host_dsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyHostKey /etc/ssh/ssh_host_ed25519_key # Ciphers and keying#RekeyLimit default none # Logging#SyslogFacility AUTHSyslogFacility AUTHPRIV#LogLevel INFO # Authentication: #LoginGraceTime 2mPermitRootLogin no#StrictModes yes#MaxAuthTries 6#MaxSessions 10```
在selinux中添加 1022端口作為ssh服務端口的權限。
[root@localhost dc]# semanage port -a -t ssh_port_t -p tcp 1022[root@localhost dc]#[root@localhost dc]# semanage port -l | grep sshssh_port_t tcp 1022, 22
4.檢測日志信息,短時間內超過一定失敗測試則給root用戶發郵件提醒
使用kali測試爆破ssh端口
date ; hydra -l dc -P /usr/share/wordlists/fasttrack.txt -v ssh://192.168.1.10:1022 ; date
2022年 07月 29日 星期五 22:23:15 CST [WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4 [ERROR] could not connect to target port 1022: Socket error: Connection reset by peer [ERROR] ssh protocol error [ERROR] could not connect to target port 1022: Socket error: Connection reset by peer [ERROR] ssh protocol error 2022年 07月 29日 星期五 22:25:26 CST
cat /usr/share/wordlists/fasttrack.txt | wc -l 222
>>> (222/(2*60+10)) 1.7076923076923076
平均每秒1.7個失敗登錄。可以看出一分鐘內ssh登錄次數超過60次,說明極有可能正在被黑客暴力破解賬戶密碼。
編寫自動化工具智能探測是否被爆破ssh密碼,立即封禁可疑ip、發郵件給系統管理員。
具體功能:定時檢測lastb命令的輸出,如果發現1分鐘內某ip登錄失敗次數超過60次則用mail命令通知root用戶,并將立即使用iptables封禁該ip。(將封禁嫌疑ip的命令加入/home/dc/iptables.mysettings)
腳本內容:
import os,datetime
def is_this_ip_in_field(ip,field): in_field = False for element in field: if element[0] == ip: in_field = True return in_field
return in_field
def compose_time_str(date_time_t): month_str = date_time_t.strftime("%b") day_str = date_time_t.strftime("%d").replace('0','') time_str = date_time_t.strftime("%H:%M") date_str = month_str+'-'+day_str+'-'+time_str return date_str
now_time = datetime.datetime.now()month_str = now_time.strftime("%b")
current_time_1_min_ago = now_time-datetime.timedelta(minutes=1)current_time_2_min_ago = now_time-datetime.timedelta(minutes=2)current_time_3_min_ago = now_time-datetime.timedelta(minutes=3)
current_time_1_min_ago_str = compose_time_str(current_time_1_min_ago)current_time_2_min_ago_str = compose_time_str(current_time_2_min_ago)current_time_3_min_ago_str = compose_time_str(current_time_3_min_ago)
time_str_list = [current_time_1_min_ago_str,current_time_2_min_ago_str,current_time_3_min_ago_str]#print(time_str_list)
cmdline = "lastb | awk \'{printf \"%s-%s-%s %s\\",$5,$6,$7,$3}\' | less"
a = os.popen(cmdline)login_failed_infomation = a.read().split('')suspect_ip_and_attack_time_dict = {}
# { time:{ip:number,ip2:number},time2:{ip:number} }for line in login_failed_infomation: if not line.startswith(month_str): continue
detail_time,ip = line.split(' ')
#print(detail_time)
if detail_time in time_str_list: # has detail time segemnt. if suspect_ip_and_attack_time_dict.has_key(detail_time): time_dict = suspect_ip_and_attack_time_dict[detail_time] if time_dict.has_key(ip): time_dict[ip] += 1 else: time_dict[ip] = 1 else: # add ip tmp_dict = {} tmp_dict[ip] = 1 suspect_ip_and_attack_time_dict[detail_time] = tmp_dict
report_message = ""black_list = []message = ""
for keys,values in suspect_ip_and_attack_time_dict.items(): for ip,failed_times in values.items(): if failed_times > 60: black_list.append(ip) format_str = "{} attacked {} times at {}" message += format_str.format(ip,failed_times,keys) #print(message)
black_list = list(set(black_list))ban_ip_list = []tmp_list = []
f = open("black_list.txt","r")for line in f: ban_ip_list.append(line)f.close()
for element in black_list: if element not in ban_ip_list: tmp_list.append(element)
black_list = tmp_listf = open("black_list.txt","a")
#iptables -I INPUT 3 -i enp0s3 -s 192.168.1.1 -j DROPfor ip in black_list: ban_cmd = "iptables -I INPUT 3 -i enp0s3 -s " + ip + " -j DROP" f.write(ip+'') os.popen(ban_cmd)f.close()
os.popen("iptables-save > /home/dc/iptables.mysettings")
if message != "": mail_cmd = "echo \"" + message + "\" | mail -s \"security report\" root@localhost" os.system(mail_cmd)
/etc/crontab 文件的內容:
ELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root # For details see man 4 crontabs # Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed# apply my iptables from file per minute. * * * * * root /sbin/iptables-restore /home/dc/iptables.mysettings# detect attack beheviour every 3 minutes. */3 * * * * root /usr/bin/python /root/detect_ssh_port_hacking.py
分別在兩臺主機上使用hydra爆破1022端口
date ; hydra -l dc -P /usr/share/nmap/nselib/data/passwords.lst -v ssh://192.168.1.10:1022 ; date
完成后在本機查看root郵箱
[root@localhost ~]# cat /var/spool/mail/root From root@localhost.localdomain Thu Aug 4 10:33:02 2022Return-Path: X-Original-To: root@localhostDelivered-To: root@localhost.localdomainReceived: by localhost.localdomain (Postfix, from userid 0) id 130BE12010FD; Thu, 4 Aug 2022 10:33:02 -0400 (EDT)Date: Thu, 04 Aug 2022 10:33:02 -0400To: root@localhost.localdomainSubject: security reportUser-Agent: Heirloom mailx 12.5 7/5/10MIME-Version: 1.0Content-Type: text/plain; charset=us-asciiContent-Transfer-Encoding: 7bitMessage-Id: <20220804143302.130BE12010FD@localhost.localdomain>From: root@localhost.localdomain (root) 192.168.1.3 attacked 142 times at Aug-4-10:30192.168.1.16 attacked 142 times at Aug-4-10:30192.168.1.3 attacked 146 times at Aug-4-10:31192.168.1.16 attacked 96 times at Aug-4-10:31192.168.1.3 attacked 64 times at Aug-4-10:32
腳本發現了攻擊行為之后,馬上拉黑了兩臺正在攻擊的主機。
再看看攻擊機的輸出:
┌──(root?kali)-[/usr/share/nmap/nselib/data]└─# date ; hydra -l dc -P /usr/share/nmap/nselib/data/passwords.lst -v ssh://192.168.1.10:1022 ; date2022年 08月 04日 星期四 22:32:55 CSTHydra v9.2 (c) 2021 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-08-04 22:32:55[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4[WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore[DATA] max 16 tasks per 1 server, overall 16 tasks, 5010 login tries (l:1/p:5010), ~314 tries per task[DATA] attacking ssh://192.168.1.10:1022/[VERBOSE] Resolving addresses ... [VERBOSE] resolving done[INFO] Testing if password authentication is supported by ssh://dc@192.168.1.10:1022[ERROR] could not connect to ssh://192.168.1.10:1022 - Timeout connecting to 192.168.1.102022年 08月 04日 星期四 22:33:37 CST
本來是要測試完五千條密碼,由于腳本的存在,只測試了不到三四百條條就被ban了:
dc@LAPTOP-J3UJRUOC:/usr/share/nmap/nselib/data$ wc -l /usr/share/nmap/nselib/data/passwords.lst5084 /usr/share/nmap/nselib/data/passwords.lst
再查看本機iptables配置:
[root@localhost ~]# iptables -L --line-numberChain INPUT (policy DROP)num target prot opt source destination 1 ACCEPT all -- anywhere anywhere 2 ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED3 DROP all -- 192.168.1.16 anywhere 4 DROP all -- 192.168.1.3 anywhere 5 ACCEPT tcp -- anywhere anywhere tcp spts:1024:65534 dpt:sunrpc6 ACCEPT tcp -- anywhere anywhere tcp spts:1024:65534 dpt:exp27 ACCEPT tcp -- anywhere anywhere tcp spts:1024:65534 dpt:squid Chain FORWARD (policy ACCEPT)num target prot opt source destination Chain OUTPUT (policy ACCEPT)num target prot opt source destination [root@localhost ~]#
5.搭建squid代理
安裝squid:
yum install squid
取消配置文件中一行注釋:
vim /etc/squid/squid.conf: Uncomment and adjust the following to add a disk cache directory.cache_dir ufs /var/spool/squid 100 16 256
啟動服務并設置開機自啟:
[root@localhost ~]# systemctl start squid.service[root@localhost ~]# systemctl enable squid.service
最后別忘了重新設置一下防火墻,因為物理機還需要訪問proxy server:
iptables -Fiptables -Xiptables -Ziptables -P INPUT DROPiptables -P OUTPUT ACCEPTiptables -P FORWARD ACCEPTiptables -A INPUT -i lo -j ACCEPTiptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -A INPUT -p TCP -i enp0s3 --dport 111 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s3 --dport 1022 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s3 --dport 3128 --sport 1024:65534 -j ACCEPTiptables-save > /home/dc/iptables.mysettingsiptables -L --line-number
client
配置防火墻:
iptables -Fiptables -Xiptables -Ziptables -P INPUT DROPiptables -P OUTPUT ACCEPTiptables -P FORWARD ACCEPTiptables -A INPUT -i lo -j ACCEPTiptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.1 -j DROPiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.0/24 -j ACCEPTiptables-save > /home/dc/iptables.mysettings
允許接受來自lo網卡的數據包,允許接受來自56網段、以及和自身發出的數據包相關的數據包。ban掉56.1這個ip(物理機),以及其他所有數據包。
寫入計劃任務:
[root@localhost dc]# vim /etc/crontab[root@localhost dc]# cat /etc/crontabSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root # For details see man 4 crontabs # Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed * * * * * root /sbin/iptables-restore /home/dc/iptables.mysettings
http server
1.防火墻配置
iptables -Fiptables -Xiptables -Ziptables -P INPUT DROPiptables -P OUTPUT ACCEPTiptables -P FORWARD ACCEPTiptables -A INPUT -i lo -j ACCEPTiptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.1 -j DROPiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.106 --dport 80 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.106 --dport 443 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 --dport 80 -j DROPiptables -A INPUT -p TCP -i enp0s8 --dport 443 -j DROPiptables -A INPUT -p TCP -i enp0s8 --dport 111 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 --dport 22 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 --dport 631 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 --dport 25 --sport 1024:65534 -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.0/24 -j ACCEPT
保存配置并且安排上定時任務:
iptables-save > /root/my_iptables_seetings.rule/usr/sbin/iptables-restore < /root/my_iptables_seetings.rule[root@localhost html]# cat /etc/crontabSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root # For details see man 4 crontabs # Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed * * * * * root /usr/sbin/iptables-restore < /root/my_iptables_seetings.rule
2.安裝httpd服務,啟動該服務,并設置開機啟動:
yum install httpdsystemctl start httpdsystemctl enable httpdsystemctl status httpd
簡單設置網站首頁:
cd /var/www/html/cat index.htmlThis is my first page.
安排上https:
yum install mod_sslsystemctl restart httpd
備份服務器
在這個服務器上設置定時備份http服務器的網站內容。
1.首先做免密登錄http服務器的設置:
[dc@localhost ~]$ suPassword:[root@localhost dc]# ssh-keygenGenerating public/private rsa key pair.Enter file in which to save the key (/root/.ssh/id_rsa):Created directory '/root/.ssh'.Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /root/.ssh/id_rsa.Your public key has been saved in /root/.ssh/id_rsa.pub.The key fingerprint is:SHA256:iQiHtrt1CpVCi/9tUepSWVziMnhw/Zk9CASepiHvr2s root@localhost.localdomainThe key's randomart image is:+---[RSA 2048]----+| .+. || .....+ . || * o++o = = || + B.*+.=.= o ||. + *..BS . || . = = || + oo.. || =E=o || ..==o |+----[SHA256]-----+[root@localhost dc]# scp ~/.ssh/id_rsa.pub root@192.168.56.102:~The authenticity of host '192.168.56.102 (192.168.56.102)' can't be established.ECDSA key fingerprint is SHA256:fXKVGvaS/isxJ+u6655e5dyTap2YDAgEgdrbs96gcoU.ECDSA key fingerprint is MD5:6d:28:85:28:3a:2d:2e:be:cb:e9:cd:87:ad:9a:ea:22.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added '192.168.56.102' (ECDSA) to the list of known hosts.root@192.168.56.102's password:id_rsa.pub 100% 408 489.5KB/s 00:00
在http server上添加相關公鑰信息:
[root@localhost ~]# ls -ld id_rsa.pub .ssh/-rw-r--r--. 1 root root 406 Aug 3 01:38 id_rsa.pubdrwx------. 2 root root 25 Aug 1 03:17 .ssh/[root@localhost ~]# cat id_rsa.pub >> ~/.ssh/known_hosts123.txt .bash_profile .cshrc original-ks.cfg .viminfo anaconda-ks.cfg .bashrc id_rsa.pub .rnd .wireshark/ .bash_history .cache/ .lesshst .ssh/ .xauthTIyBog .bash_logout .config/ .local/ .tcshrc [root@localhost ~]# cat id_rsa.pub >> ~/.ssh/authorized_keys[root@localhost ~]# chmod 644 ~/.ssh/authorized_keys
回到備份服務器測試下:
[dc@localhost ~]$ ssh root@192.168.32.146Last login: Sat Jul 30 06:48:47 2022[root@localhost ~]# exitlogoutConnection to 192.168.32.146 closed.
2.做完免密登錄后,直接以root身份添加系統定時任務,每隔一小時同步備份http server的網站內容到本地/tmp下。
[root@localhost .ssh]# /usr/bin/rsync -av -e ssh root@192.168.56.102:/var/www/html /tmpreceiving incremental file listhtml/html/index.html sent 47 bytes received 151 bytes 132.00 bytes/sectotal size is 23 speedup is 0.12
添加計劃任務:
[root@localhost ~]# cat /etc/crontabSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root # For details see man 4 crontabs # Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed* * * * * root /usr/bin/rsync -av -e ssh root@192.168.56.102:/var/www/html /tmp &> /root/rsync_res.txt
可以監視腳本的輸出、以及crontab的日志文件來觀察運行情況。主要是這兩個日志文件:
/root/rsync_res.txt/var/log/cron
nis server
1.安裝nis
yum install yp-toolsyum install ypbindyum install ypservyum install rpcbind
2.設置nis域名。
這里參考鳥哥的書,配置如下:
nis 域名 vbirdnis整個內部的信任網絡為 192.168.56.0/24nis master server 的ip 為 192.168.56.103,主機名為 www.centos.vbirdnis client 的ip為192.168.56.105,主機名為client.centos.vbirdnis client 2 的ip為192.168.56.104,主機名為backup.centos.vbird
編輯/etc/sysconfig/network,設置域名,并配置nis啟動在固定的端口上:
[root@localhost ~]# cat /etc/sysconfig/network# Created by anacondaNISDOMAIN=vbirdnisYPSERV_ARGS="-p 1011"
在兩臺客戶機上也做同樣的設置。
3.設置主要配置文件:
[root@localhost dc]# cat /etc/ypserv.conf## ypserv.conf In this file you can set certain options for the NIS server,# and you can deny or restrict access to certain maps based# on the originating host.## See ypserv.conf(5) for a description of the syntax.# # Some options for ypserv. This things are all not needed, if# you have a Linux net. # How many map file handles should be cached ?files: 30 # Should we register ypserv with SLP ?# slp: no# After how many seconds we should re-register ypserv with SLP ?# slp_timeout: 3600 # xfr requests are only allowed from ports < 1024xfr_check_port: yes # The following, when uncommented, will give you shadow like passwords.# Note that it will not work if you have slave NIS servers in your# network that do not run the same server as you. # Host : Domain : Map : Security## * : * : passwd.byname : port# * : * : passwd.byuid : port # Not everybody should see the shadow passwords, not secure, since# under MSDOG everbody is root and can access ports < 1024 !!!* : * : shadow.byname : port* : * : passwd.adjunct.byname : port # If you comment out the next rule, ypserv and rpc.ypxfrd will# look for YP_SECURE and YP_AUTHDES in the maps. This will make# the security check a little bit slower, but you only have to# change the keys on the master server, not the configuration files# on each NIS server.# If you have maps with YP_SECURE or YP_AUTHDES, you should create# a rule for them above, that's much faster. * : * : * : none
4.設置主機名與ip的對應
配置對應文件:
[root@localhost dc]# cat /etc/hosts127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4::1 localhost localhost.localdomain localhost6 localhost6.localdomain6192.168.56.103 www.centos.vbird192.168.56.105 client.centos.vbird192.168.56.104 backup.centos.vbird
使用hostname查看主機名,發現沒有設置成功,用hostnamectl命令重新設置:
[root@localhost dc]# hostnamelocalhost.localdomain[root@localhost dc]# hostnamectl set-hostname www.centos.vbird[root@localhost dc]# hostnamewww.centos.vbird
5.啟動所有相關服務
[root@localhost dc]# cat /etc/sysconfig/yppasswdd# The passwd and shadow files are located under the specified# directory path. rpc.yppasswdd will use these files, not /etc/passwd# and /etc/shadow.#ETCDIR=/etc # This option tells rpc.yppasswdd to use a different source file# instead of /etc/passwd# You can't mix usage of this with ETCDIR#PASSWDFILE=/etc/passwd # This option tells rpc.yppasswdd to use a different source file# instead of /etc/passwd.# You can't mix usage of this with ETCDIR#SHADOWFILE=/etc/shadow # Additional arguments passed to yppasswdYPPASSWDD_ARGS="--port 1012"[root@localhost dc]# systemctl status ypserv.service● ypserv.service - NIS/YP (Network Information Service) Server Loaded: loaded (/usr/lib/systemd/system/ypserv.service; disabled; vendor preset: disabled) Active: inactive (dead)[root@localhost dc]# systemctl start ypserv.service[root@localhost dc]# systemctl enable ypserv.serviceCreated symlink from /etc/systemd/system/multi-user.target.wants/ypserv.service to /usr/lib/systemd/system/ypserv.service.[root@localhost dc]# systemctl status ypserv.service● ypserv.service - NIS/YP (Network Information Service) Server Loaded: loaded (/usr/lib/systemd/system/ypserv.service; enabled; vendor preset: disabled) Active: active (running) since Fri 2022-08-05 08:07:36 EDT; 13s ago Main PID: 32494 (ypserv) Status: "Processing requests..." CGroup: /system.slice/ypserv.service └─32494 /usr/sbin/ypserv -f -p 1011 Aug 05 08:07:36 www.centos.vbird systemd[1]: Starting NIS/YP (Network Information Service) Server...Aug 05 08:07:36 www.centos.vbird ypserv[32494]: WARNING: no securenets file found!Aug 05 08:07:36 www.centos.vbird systemd[1]: Started NIS/YP (Network Information Service) Server.[root@localhost dc]# systemctl status yppasswdd.service● yppasswdd.service - NIS/YP (Network Information Service) Users Passwords Change Server Loaded: loaded (/usr/lib/systemd/system/yppasswdd.service; disabled; vendor preset: disabled) Active: inactive (dead)[root@localhost dc]# systemctl start yppasswdd.service[root@localhost dc]# systemctl enable yppasswdd.serviceCreated symlink from /etc/systemd/system/multi-user.target.wants/yppasswdd.service to /usr/lib/systemd/system/yppasswdd.service.[root@localhost dc]# systemctl status yppasswdd.service● yppasswdd.service - NIS/YP (Network Information Service) Users Passwords Change Server Loaded: loaded (/usr/lib/systemd/system/yppasswdd.service; enabled; vendor preset: disabled) Active: active (running) since Fri 2022-08-05 08:08:06 EDT; 9s ago Main PID: 32611 (rpc.yppasswdd) Status: "Processing requests..." CGroup: /system.slice/yppasswdd.service └─32611 /usr/sbin/rpc.yppasswdd -f --port 1012 Aug 05 08:08:06 www.centos.vbird systemd[1]: Starting NIS/YP (Network Information Service) Users Passwords Change Server...Aug 05 08:08:06 www.centos.vbird yppasswdd-pre-setdomain[32606]: Setting NIS domain: 'vbirdnis' (environment variable)Aug 05 08:08:06 www.centos.vbird systemd[1]: Started NIS/YP (Network Information Service) Users Passwords Change Server.
檢查看看是否有異常:
[root@localhost dc]# rpcinfo -p localhost program vers proto port service 100000 4 tcp 111 portmapper 100000 3 tcp 111 portmapper 100000 2 tcp 111 portmapper 100000 4 udp 111 portmapper 100000 3 udp 111 portmapper 100000 2 udp 111 portmapper 100004 2 udp 1011 ypserv 100004 1 udp 1011 ypserv 100004 2 tcp 1011 ypserv 100004 1 tcp 1011 ypserv 100009 1 udp 1012 yppasswdd[root@localhost dc]# rpcinfo -u localhost ypservprogram 100004 version 1 ready and waitingprogram 100004 version 2 ready and waiting
6.處理賬號并建立數據庫
[root@localhost dc]# useradd -u 1001 nisuser1[root@localhost dc]# useradd -u 1002 nisuser2[root@localhost dc]# useradd -u 1003 nisuser3[root@localhost dc]# vim /etc/passwd[root@localhost dc]# echo password | passwd --stdin nisuser1Changing password for user nisuser1.passwd: all authentication tokens updated successfully.[root@localhost dc]# echo password | passwd --stdin nisuser2Changing password for user nisuser2.passwd: all authentication tokens updated successfully.[root@localhost dc]# echo password | passwd --stdin nisuser3Changing password for user nisuser3.passwd: all authentication tokens updated successfully.[root@localhost dc]# /usr/lib64/yp/ypinit -m At this point, we have to construct a list of the hosts which will run NISservers. www.centos.vbird is in the list of NIS server hosts. Please continue to addthe names for the other hosts, one per line. When you are done with thelist, type a . next host to add: www.centos.vbird next host to add: The current list of NIS servers looks like this: www.centos.vbird Is this correct? [y/n: y] yWe need a few minutes to build the databases...Building /var/yp/vbirdnis/ypservers...Running /var/yp/Makefile...gmake[1]: Entering directory `/var/yp/vbirdnis'Updating passwd.byname...Updating passwd.byuid...Updating group.byname...Updating group.bygid...Updating hosts.byname...Updating hosts.byaddr...Updating rpc.byname...Updating rpc.bynumber...Updating services.byname...Updating services.byservicename...Updating netid.byname...Updating protocols.bynumber...Updating protocols.byname...Updating mail.aliases...gmake[1]: Leaving directory `/var/yp/vbirdnis' www.centos.vbird has been set up as a NIS master server. Now you can run ypinit -s www.centos.vbird on all slave server.
7.防火墻設置
iptables -Fiptables -Xiptables -Ziptables -P INPUT DROPiptables -P OUTPUT ACCEPTiptables -P FORWARD ACCEPTiptables -A INPUT -i lo -j ACCEPTiptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.1 -j DROPiptables -A INPUT -p TCP -i enp0s8 -s 192.168.56.0/24 -j ACCEPTiptables -A INPUT -p UDP -i enp0s8 -s 192.168.56.0/24 -j ACCEPT
保存配置并且安排上定時任務:
iptables-save > /root/my_iptables_seetings.rule/usr/sbin/iptables-restore < /root/my_iptables_seetings.rule[root@localhost html]# cat /etc/crontabSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root # For details see man 4 crontabs # Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed * * * * * root /usr/sbin/iptables-restore < /root/my_iptables_seetings.rule
8.客戶端配置
安裝必須軟件:
[root@localhost dc]# yum install ypbindLoaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfile * base: mirrors.nju.edu.cn * extras: mirrors.ustc.edu.cn * updates: mirrors.ustc.edu.cnbase | 3.6 kB 00:00:00 extras | 2.9 kB 00:00:00 updates | 2.9 kB 00:00:00 updates/7/x86_64/primary_db | 16 MB 00:00:03 Resolving Dependencies--> Running transaction check---> Package ypbind.x86_64 3:1.37.1-9.el7 will be installed--> Processing Dependency: yp-tools for package: 3:ypbind-1.37.1-9.el7.x86_64--> Running transaction check---> Package yp-tools.x86_64 0:2.14-5.el7 will be installed--> Finished Dependency Resolution Dependencies Resolved ======================================================================================= Package Arch Version Repository Size=======================================================================================Installing: ypbind x86_64 3:1.37.1-9.el7 base 62 kInstalling for dependencies: yp-tools x86_64 2.14-5.el7 base 79 k Transaction Summary=======================================================================================Install 1 Package (+1 Dependent package) Total download size: 142 kInstalled size: 299 kIs this ok [y/d/N]: yDownloading packages:warning: /var/cache/yum/x86_64/7/base/packages/ypbind-1.37.1-9.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEYPublic key for ypbind-1.37.1-9.el7.x86_64.rpm is not installed(1/2): ypbind-1.37.1-9.el7.x86_64.rpm | 62 kB 00:00:00 (2/2): yp-tools-2.14-5.el7.x86_64.rpm | 79 kB 00:00:00 ---------------------------------------------------------------------------------------Total 209 kB/s | 142 kB 00:00 Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7Importing GPG key 0xF4A80EB5: Userid : "CentOS-7 Key (CentOS 7 Official Signing Key) " Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5 Package : centos-release-7-9.2009.0.el7.centos.x86_64 (@anaconda) From : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7Is this ok [y/N]: yRunning transaction checkRunning transaction testTransaction test succeededRunning transaction Installing : yp-tools-2.14-5.el7.x86_64 1/2 Installing : 3:ypbind-1.37.1-9.el7.x86_64 2/2 Verifying : 3:ypbind-1.37.1-9.el7.x86_64 1/2 Verifying : yp-tools-2.14-5.el7.x86_64 2/2 Installed: ypbind.x86_64 3:1.37.1-9.el7 Dependency Installed: yp-tools.x86_64 0:2.14-5.el7 Complete![root@localhost dc]# yum install yp-toolsLoaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfile * base: mirrors.nju.edu.cn * extras: mirrors.ustc.edu.cn * updates: mirrors.ustc.edu.cnPackage yp-tools-2.14-5.el7.x86_64 already installed and latest versionNothing to do
可以使用setup命令快速設置配置文件。
使用yptest命令驗證數據庫。
使用ypwhich檢查數據庫數量。
使用su - nisuser1 切換身份。