I. Review#
1.1 SSH#
SSH
secure shell
- Remote login connection, control host
- Data transmission is encrypted
- Based on asymmetric encryption technology
1.2 Encryption Technology#
Encryption Technology
Symmetric Encryption
-
Both parties share a key, one party encrypts, and the other decrypts
-
Disadvantage: This public key can easily be obtained by malicious individuals
Asymmetric Encryption
- Uses a key pair for encryption and decryption
- Generates a pair of keys, one as a private key and the other as a public key
- The private key is known only to oneself and is stored locally
- The public key is given to those who need to communicate, and the public key can be shared with others
- Use the public key for encryption and the private key for decryption, generally used for data encryption transmission
(For two people A and B, B transmits data to A using encryption, the private key is with A, and B uses A's public key to encrypt the data) - Use the private key for encryption and the public key for decryption, generally used for authentication
(A sends data to B, B confirms whether the data is sent by A, client A encrypts the data with A's private key, and server B decrypts it with A's public key. It only handles authentication, not encryption)
1.3 SSH Login#
SSH Login
Login Methods
- Password Login
Process
- Client sends login request
- Server sends the machine's public key to the client
- Client encrypts the password with the server's public key and sends it to the server
- Server receives the ciphertext and decrypts it with the private key, verifying against /etc/shadow
- Returns verification result
- Key Login, Public Key Authentication
- Client generates a public key pair
- Sends the client's user public key to the server, stored in the target user's ~/.ssh/authorized_keys
- Client sends a request, server returns a random string
- After the client receives the random string, it encrypts it with its private key and sends it to the server
- Server receives the ciphertext and decrypts it with the client's public key, compares the random string with the generated string. Returns authentication result (If the random string is obtained by others, it doesn't matter, because A's public key can be held by many people)
- Disadvantages
- Third-party attacks
- A cannot determine whether the received public key is B's
- To solve this problem
- Manual confirmation is done during the first login
- After confirmation, B's machine's public key is stored in ~/.ssh/known_hosts, and each subsequent login will compare it (If the system is reinstalled and cannot log in, it prompts known_hosts... and deletes known_hosts)
Public Key Authentication
- Generate a public key pair using the command
ssh-keygen
-t option specifies the encryption algorithm to be generated
Default is RSA algorithm encryption, just keep pressing enter during the process
- Client sends the public key to the server
It is stored in the target user's ~/.ssh/authorized_keys
- Check permissions
authorized_keys 600 permissions
.ssh and home directory should have permissions below 755
Or allow password verification login (prerequisite) # ssh-copy-id wy@192.168.0.39 -p 2233 to send the public key
[root@cPen_python ~]# ssh-copy-id wy@192.168.0.39 -p 2233 # Note: Password login must be supported
1.4 SSH Remote Operation Tool#
SSH Remote Operation Tool
- SSH
- Remote command execution, remote login
- Login methods
- ssh server IP address
- Log in using the current user and default port
- Using the client's current username, log in to the remote server under the same name user, default port 22
(If there is no same name user, login fails)- ssh username@server IP address
- Log in to the specified user on the remote server, using the default port 22
- ssh server address -l username -p port number
- Specify username and port to log in
- ssh -o some configuration options server IP address
# Input yes without order, automatically save host key
ssh -o StrictHostKeyChecking=no 192.168.0.132 -p 223- ssh -i /tmp/id_rsa specify private key authentication file
By default, it looks for the private key under ~/.ssh- ssh -vvv
Print detailed information of the login process
1.5 Service Configuration#
Service Configuration
- Service Installation Package
-
openssh#
[root@cPen_python ~]# which ssh
/usr/bin/ssh
[root@cPen_python ~]# rpm -qf /usr/bin/ssh
openssh-clients-7.4p1-21.el7.x86_64
-
- Configuration Files
- /etc/ssh/sshd_config Server configuration file
- /etc/ssh/ssh_config Client configuration
- Main Programs
Server /usr/sbin/sshd
Client /usr/bin/ssh - Reload configuration
Restart service service sshd restart/reload
kill -1 sshd's pid
kill -HUP sshd's pid number
1.6 Check SSH Service Startup Status#
Check SSH Service Startup Status
-
ps -aux/-ef
-
pidof sshd
-
netstat -autpln All interfaces (a) UDP TCP connections, showing all programs (p) listening status (l) n displays port number
# Note: Check network connection status
# ps -eo pid,uid,comm|grep sshd # Note: -eo view specific field information
- lsof -i:22 Print out the files required by the program
[root@localhost ~]# ps aux |grep sshd
root 1066 0.0 0.1 112924 4316 ? Ss 09:41 0:00 /usr/sbin/sshd -D
root 1608 0.0 0.1 158928 5608 ? Ss 09:43 0:00 sshd: root@pts/0
root 9546 0.0 0.0 112824 980 pts/0 S+ 11:26 0:00 grep --color=auto sshd
[root@localhost ~]# ps -ef |grep sshd
root 1066 1 0 09:41 ? 00:00:00 /usr/sbin/sshd -D
root 1608 1066 0 09:43 ? 00:00:00 sshd: root@pts/0
root 9550 1612 0 11:26 pts/0 00:00:00 grep --color=auto sshd
[root@localhost ~]# ps -eo pid,uid,comm|grep sshd # Note: -eo view specific field information
1066 0 sshd
1608 0 sshd
1.7 SSH-Agent#
SSH-Agent
Manage keys
Enable this service on your own machine
Configuration: xshell--> Host Properties--》SSH --》Check Use xagent for authentication; Check Use agent forwarding
Note: If your machine is Windows, enabling the ssh-agent service on Windows, now there are two machines A and B, both A and B have Windows public keys, in this case, enabling ssh-agent (in xshell), when A logs into B, by default, it will use Windows public key for encryption, and B machine will use Windows private key for decryption. This must be done in xshell, this is all xshell's behavior#
II. Jump Server#
Note: The jump server is used by office personnel. The jump server/bastion host is to protect the system's security#
Note: Use ssh-agent to access the jump server and the host you want to access#
Note: Usage scenario: Alibaba's business originally had 100,000 machines (in the local area network, no external network, cannot be accessed externally), I am at home, pulling one machine out of the hundred thousand, this one machine can access the external network (jump server/bastion host), the configuration of this one jump server is especially important#
Enable ssh-agent and add your machine's public key to the target host and bastion host (the permissions of the target host and bastion host)
Note: Connect to A, then jump to B, B may not have the current machine's public and private keys#
Jump Server Security Hardening:#
Cannot log in directly as root, use sudo to grant appropriate permissions
Cannot log in using the default port
Cannot log in using a password, all use public key login
Add firewall configuration
Summary:
Jump Server#
Security Hardening#
1. Cannot log in using a password
2. Cannot log in as root
3. Change the default port
4. Add firewall configuration
5. Use jump server to log in
Example 1: View routing ip r
--------------------------------------------------------------------------------------------
[root@cPen_python ~]# ip r # Note: View routing
default via 192.168.0.1 dev ens33 proto dhcp metric 100
192.168.0.0/24 dev ens33 proto kernel scope link src 192.168.0.32 metric 100
[root@cPen_python ~]# ip r delete default via 192.168.0.1 # Note: Delete gateway
[root@cPen_python ~]# ip r
192.168.0.0/24 dev ens33 proto kernel scope link src 192.168.0.32 metric 100
[root@cPen_python ~]# ping www.baidu.com # Note: After deletion, cannot ping the external network
connect: Network is unreachable
[root@cPen_python ~]# ping 8.8.8.8
connect: Network is unreachable
[root@cPen_python ~]# ip r add default via 192.168.0.1 # Note: Restore
============================================================================================
Example 2: Machine A logs into Machine B (simplified login) vim .ssh/config
# In the future, there will be many machines, and it is impossible to remember the IP addresses
--------------------------------------------------------------------------------------------
# Machine A logs into Machine B, before operating, you need to put Machine A's public key on Machine B for authorization
# Do not modify the global configuration, only modify personal configuration: create a hidden file in the user's home directory
# Configure on the client (configured on your own machine)
# Note: This means to take the machine root@192.168.0.31 -p 2233 and give it an alias called B
# ForwardAgent yes # Note: Forwarding enabled
# StrictHostKeyChecking no # Note: No need to input yes, directly save the key in known_hosts
# ServerAliveInterval 60 # Note: Alive status, check service alive status
# IdentityFile ~/.ssh/id_rsa # Note: Specify authentication private key
# Example as follows
[root@cPen_python ~]# vim .ssh/config
###############################################
ForwardAgent yes
StrictHostKeyChecking no
ServerAliveInterval 60
IdentityFile ~/.ssh/id_rsa
###############################################
Host B
HostName 192.168.0.31
User cPen
Port 2233
[root@cPen_python .ssh]# chmod 600 config # Note: Grant permissions. Not executing this command may cause errors
[root@cPen_python .ssh]# ssh B
Last login: Mon Nov 23 15:05:16 2020 from 192.168.0.32 # Note: Login successful
[root@cPen_centos8 ~]#
# Note: This simplifies # ssh 192.168.0.31 -l root -p 2233 operation (for example, logging into ftp server ssh ftp)
============================================================================================
Example 3: Check port connection status (client wants to access server using client telnet) telnet 192.168.0.31 2233
# Note: This command can only test TCP, cannot test UDP, but most services are TCP
# Check if the port is accessible (i.e., if the service is reachable) telnet 192.168.0.31 2233
--------------------------------------------------------------------------------------------
# The ping command is used to check whether the two machines are networked
# Use the telnet command to check if the service is reachable
# Example: Check if the port is reachable (if the service is reachable)
[root@cPen_python .ssh]# yum install telnet -y
[root@cPen_python .ssh]# telnet 192.168.0.31 2233
Trying 192.168.0.31...
Connected to 192.168.0.31. # Note: Service reachable
Escape character is '^]'.
SSH-2.0-OpenSSH_8.0
============================================================================================
Example 4: Prompt that the host is not trusted WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
--------------------------------------------------------------------------------------------
# Note: Prompt WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
Delete ~/.ssh/known_hosts
============================================================================================
Example 5: Permanently change hostname hostnamectl set-hostname "A"
--------------------------------------------------------------------------------------------
# Method 1
[root@cPen_python .ssh]# hostnamectl set-hostname "A"
# Note: Actually modifies /etc/hostname
[root@A ~]# less /etc/hostname
# Method 2
# Or directly modify /etc/hostname
# Temporarily change hostname
[root@B ~]# hostname cp
============================================================================================
Example 6: View process count pstree -p
--------------------------------------------------------------------------------------------
# Note: View the program tree structure pstree -p
[root@cPen_python .ssh]# pstree -p |grep sshd
|-sshd(1065)-+-sshd(3782)---bash(3784)
| |-sshd(3980)---bash(3982)-+-grep(4318)
| |-sshd(4059)---bash(4061)
| `-sshd(4288)---bash(4290)
# Note: The front is the parent program, the back is the child program created by the parent program, the child program allocates a new bash environment, and the bash environment operates the command grep
# Note: The parent process creates a child process, the child process creates a new child process, and the child process creates a new bash environment
#-------------------------------------------------------------------------------------------
# Note: After connecting to Machine B, the bash environment has an additional ssh child process to handle Machine B
[root@a ~]# ssh B
Last login: Mon Nov 23 15:52:16 2020 from 192.168.0.32
[root@a .ssh]# pstree -p |grep sshd
|-sshd(1065)-+-sshd(3782)---bash(3784)
| |-sshd(3980)---bash(3982)-+-grep(4325)
| |-sshd(4059)---bash(4061)---ssh(4323)
| `-sshd(4288)---bash(4290)
============================================================================================
Example 7: Modify client configuration ~/.ssh/config
# Configuration file: ~/.ssh/config
# Use jump server proxy login in work (client configuration, convenient for development configuration)
--------------------------------------------------------------------------------------------
# Note: Suppose there are three machines A, B, and C, B is the jump server, suppose A and C cannot communicate, A can communicate with B, B can communicate with C, B can communicate with D, B can communicate with E...
# Note: Machine B acts as a jump server, Machine A is your local machine, Machine A acts as a proxy, Machine B automatically forwards
# Note: Operate on the local machine A
[root@a ~]# vim ~/.ssh/config
###############################################
ForwardAgent yes
StrictHostKeyChecking no
ServerAliveInterval 60
IdentityFile ~/.ssh/id_rsa
###############################################
Host B
HostName 192.168.0.31
User sanchuang
Port 2233
Host 192.168.0.54
User sanchuang
Port 2233
ProxyCommand ssh 192.168.0.31 -W %h:%p -l sanchuang -p 2233
# Note: ProxyCommand means A logs into B through the jump server (192.168.0.31)
#-------------------------------------------------------------------------------------------
Host * /ftp* /10.* For IP addresses starting with the 10 network segment ssh 10.0.0.1 to execute this configuration
User sanchuang
Port 2233
ProxyCommand ssh B nc %h %p -w 10 2>/dev/null
# Note: In class, conflicts arise when writing Host * and ssh B
============================================================================================
Example 8: Remote execute command ssh B
--------------------------------------------------------------------------------------------
# Execute commands on Machine B without logging into B (generally used for scripts)
[root@a ~]# ssh B ifconfig # Note: Log into B to execute the ifconfig command
[root@a ~]# ssh B ip a # Note: Log into B to execute the command to view the IP address; the command's return is given by Machine B
[root@a ~]# ssh B "/usr/sbin/ip a" # Note: It is recommended to use the absolute path of the command in scripts
============================================================================================
Example 9: Remote transfer scp (Prerequisite: ssh can connect)
--------------------------------------------------------------------------------------------
# Note: Transfer files
[root@a ~]# touch ahost
[root@a ~]# scp ahost B:/tmp # Note: Copy the current path ahost file from Machine A to the /tmp path on Machine B
ahost 100% 0 0.0KB/s 00:00
[root@a ~]# scp B:/tmp/bhost ./ # Note: Copy the /tmp/bhost file from Machine B to the current path
bhost 100% 0 0.0KB/s 00:00
[root@a ~]# scp B:tmp/testhost ./ # Note: Copy the tmp/testhost file from the home directory of Machine B to the current path
# Note: Transfer directory
[root@a ~]# scp -r adir B: # Note: Copy the adir folder from the current path of Machine A to the home directory of Machine B
[root@a ~]# scp -r adir B:bdir # Note: Copy the folder and rename it
[root@a ~]# scp -r adir B:bdir/ # Note: No difference from the above
============================================================================================
Example 10: SFTP transfer files (Prerequisite: ssh can connect)
--------------------------------------------------------------------------------------------
# Note: FTP file transfer
# Note: SFTP transfer files between local and remote
# Note: Format sftp username@hostname
[sanchuang@a ~]$ sftp B
Connected to B.
sftp> ls # Note: Display remote directory list
2q aa adir bb bdir testdir testdir2 testhost
sftp> get bdir
Fetching /home/sanchuang/bdir/ to bdir
Cannot download non-regular file: /home/sanchuang/bdir/
sftp> mget bdir
Fetching /home/sanchuang/bdir/ to bdir
Cannot download non-regular file: /home/sanchuang/bdir/
sftp> get 2q # Note: get remote path Download file
Fetching /home/sanchuang/2q to 2q
/home/sanchuang/2q 100% 226 107.5KB/s 00:00
sftp> exit
============================================================================================
Example 11: PSSH PSCP command (Prerequisite: ssh can connect)
--------------------------------------------------------------------------------------------
# Batch processing
pssh
-h Specify the host file list, content format “[user@]host[:Port]”
-i Specify the processing information for each server
[root@a ~]# yum install pssh -y # Note: If not, you need to install the epel source
[root@a ~]# cat ip.txt
192.168.0.31:2233
192.168.0.54:22
[root@a ~]# pssh -h ip.txt -i "/usr/sbin/ip a"
[1] 17:18:13 [FAILURE] 192.168.0.54:22 Exited with error code 255、
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
…… # Note: Ensure that ssh can connect
[2] 17:18:13 [SUCCESS] 192.168.0.31:2233 # Note: Return SUCCESS indicates successful execution
……
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
……
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen
……
#-------------------------------------------------------------------------------------------
# The ip.txt file can be written like this
[root@a ~]# vim ip.txt
sanchuang@192.168.0.31:2233
sanchuang@192.168.0.54:2233
============================================================================================
Example 12: pscp.pssh batch transfer files (Prerequisite: ssh can connect)
--------------------------------------------------------------------------------------------
[root@a ~]# pscp.pssh -h ip.txt pscptest /tmp
# Note: Transfer the pscptest file from the current directory to the /tmp directory of the target host
[root@a ~]# vim ip.txt
sanchuang@192.168.0.31:2233
sanchuang@192.168.0.54:2233
[root@a ~]# pscp.pssh -h ip.txt pscptest /tmp
[1] 17:41:31 [FAILURE] sanchuang@192.168.0.54:2233 Exited with error code 1
[2] 17:41:31 [SUCCESS] sanchuang@192.168.0.31:2233
============================================================================================
Example 13: fping batch ping (Prerequisite: ssh can connect)
--------------------------------------------------------------------------------------------
# Note: Batch ping using fping command
[root@a ~]# yum install fping -y
[root@a ~]# fping -g 192.168.0.1/24 # Note: -g ping according to the network segment
192.168.0.1 is alive
……
192.168.0.254 is unreachable
[root@a ~]# fping -f ip.txt # Note: -f ping according to the file specified IP
192.168.0.31 is alive
192.168.0.54 is alive
III. SSH Service Supplement#
3.1 SSH#
SSH --> secure shell
Function: Remote login and operation of remote servers --> Information encryption --> Very secure remote login protocol
Note: Remote login and remote control save costs#
SSH protocol belongs to application layer protocol
Linux: openssh --> comes with centos7/8
Windows does not have SSH protocol
3.2 Commands#
Commands:
ssh
scp # Note: Remote copy
sftp
ssh-keygen
ssh-copy-id
3.3 Login Methods#
Login Methods:
Xshell # Note: Not open source
putty # Note: Open source
secureCRT # Note: Open source
- Username and password
/etc/passwd # Note: Stores usernames
/etc/shadow # Note: Stores passwords
- Keys
Public key and private key
Public key --> public # Note: Given to others
Private key # Note: Owned by oneself
3.4 Security Hardening Measures#
Security Hardening Measures:
Change port number 22
nmap # Note: Port scanning
nc # Note: Port scanning
Disable root
su # Note: su switch to root
Password complexity
Enable keys # Note: Disable password authentication
Patch or install the latest version of SSH software
iptables firewall
Note: Passwordless channel (key login)#
3.5 Passwordless Channel#
Passwordless Channel:
One-way trust # Note: Give the key to other hosts
Both-way trust # Note: Both parties give each other public keys
Note: Generally use root user, for security reasons use ordinary users#
3.6 Ansible#
Ansible: Automation operation and maintenance tool: batch management and operation
Note: Ansible batch management and batch deployment software; uses SSH protocol at the bottom, recommended to establish a passwordless channel#
Note: Ansible software is written in Python#
3.7 Log File: /var/log/secure#
Log file: /var/log/secure
[root@cPen_centos8 ssh]# vim /etc/ssh/sshd_config
# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV # Note: Log type authentication type AUTHPRIV setting
#LogLevel INFO
Log file:
/var/log/secure
[sanchuang@cPen_centos8 ~]$ ps aux|grep rsyslog # Note: External log process
SSH outsources its logging function to the rsyslog service to help it record logs
[sanchuang@cPen_centos8 ~]$ vim /etc/rsyslog.conf
# The authpriv file has restricted access.
authpriv.* /var/log/secure
3.8 How to Troubleshoot SSH Service Login Issues?#
How to troubleshoot SSH service login issues?
Check if the network is smooth
ping
Check if the SSH service is running, check the port, SELinux
SSH configuration: whether root is disabled, whether password authentication is disabled
Check the firewall iptables
service firewalled stop
Black and white list # Note: Used in centos6,7, not in 8
3.9 SSH Passwordless Channel#
SSH Passwordless Channel
Generate key pair
ssh-keygen
ssh-keygen -t ecdsa
Upload public key
ssh-copy-id -i id_ecdsa.pub root@192.168.0.35
ssh-copy-id -p 2299 -i id_ecdsa.pub root@192.168.0.35
Remote connection
ssh -p '2299' 'root@192.168.0.39'
Steps to establish a passwordless channel:
[root@localhost .ssh]# ssh-keygen -t ecdsa
[root@localhost .ssh]# ssh-copy-id -p 2299 -i id_ecdsa.pub root@192.168.0.39
[root@localhost .ssh]# ssh -p '2299' 'root@192.168.0.39'
known_hosts: Stores the public keys of the machines we have previously connected to via SSH
SCP is used to copy files or folders between two machines using the underlying SSH protocol
[root@cPen_centos8 ssh]# ssh root@192.168.0.24 # Note: Remote login
[root@cPen_centos8 ssh]# ssh root@192.168.0.24 df -Th # Note: Remote execute command
[root@cPen_python ssh]# scp echo.sh root@192.168.0.35:/root # Note: Transfer file (source file remote)
[root@cPen_python ssh]# scp -r /boot root@192.168.0.35:/root # Note: Transfer folder
[root@cPen_python ssh]# scp -r root@192.168.0.35:/etc/passwd # Note: Get folder
[root@cPen_python ssh]# ssh root@192.168.0.35 bash /root/echo.sh feng zhang wang
SCP is used to copy files or folders between two machines using the underlying SSH protocol
---------------------------------------------------------------------------------------------------------------------------------
[root@cPen_centos8 ssh]# getenforce # Note: Check SELinux
Disabled
[root@cPen_centos8 ssh]# setenforce 0 # Note: Temporarily disable SELinux
setenforce: SELinux is disabled
---------------------------------------------------------------------------------------------------------------------------------
[sanchuang@cPen_centos8 ~]$ ifdown ens33
[sanchuang@cPen_centos8 ~]$ ifup ens33
# Note: After disabling root user login, you can log in locally as root