目录
3.2.2 其它ssh客户端工具scp命令,rsync 命令,sftp命令,自动登录 ssh工具 sshpass
5.7.3 pam_google_authenticator 模块
1 安全机制
1.1 墨菲定律
墨菲定律:一种心理学效应,是由爱德华·墨菲(Edward A. Murphy)提出的,原话:如果有两种或两种以上的方式去做某件事情,而其中一种选择方式将导致灾难,则必定有人会做出这种选择
主要内容:
任何事都没有表面看起来那么简单
所有的事都会比你预计的时间长
会出错的事总会出错
如果你担心某种情况发生,那么它就更有可能发生
1.2 信息安全防护的目标
保密性 Confidentiality
完整性 Integrity
可用性 Usability
可控制性 Controlability
不可否认性 Non-repudiation
1.3 安全防护环节
物理安全:各种设备/主机、机房环境
系统安全:主机或设备的操作系统
应用安全:各种网络服务、应用程序
网络安全:对网络访问的控制、防火墙规则
数据安全:信息的备份与恢复、加密解密
管理安全:各种保障性的规范、流程、方法
1.4 常见的安全攻击 STRIDE
Spoofing 假冒
Tampering 篡改
Repudiation 否认
Information Disclosure 信息泄漏
Denial of Service 拒绝服务
Elevation of Privilege 提升权限
例: 钓鱼网站
http://eb.qeyfs.com/RWWPyv/wqcyp0.dll
1.5 安全设计基本原则
使用成熟的安全系统
以小人之心度输入数据
外部系统是不安全的
最小授权
减少外部接口
缺省使用安全模式
安全不是似是而非
从STRIDE思考
在入口处检查
从管理上保护好你的系统
1.6 常用安全技术
认证
授权
审计
安全通信
1.7 加密算法和协议
对称加密
非对称(公钥)加密
单向加密
认证协议
1.7.1 对称加密算法
对称加密:加密和解密使用同一个密钥
特性:
加密、解密使用同一个密钥,效率高
将原始数据分割成固定大小的块,逐个进行加密
缺陷:
密钥过多
密钥分发
数据来源无法确认
常见对称加密算法:
DES:Data Encryption Standard,56bits
3DES:
AES:Advanced (128, 192, 256bits)
Blowfish,Twofish
IDEA,RC6,CAST5
1.7.2 非对称加密算法
1.7.2.1 非对称加密算法介绍
非对称加密:密钥是成对出现
公钥:public key,公开给所有人,主要给别人加密使用
私钥:secret key,private key 自己留存,必须保证其私密性,用于自已加密签名
特点:用公钥加密数据,只能使用与之配对的私钥解密;反之亦然
功能:
数据加密:适合加密较小数据,比如: 加密对称密钥
数字签名:主要在于让接收方确认发送方身份
缺点:
密钥长,算法复杂
加密解密效率低下
常见算法:
RSA:由 RSA 公司发明,是一个支持变长密钥的公共密钥算法,需要加密的文件块的长度也是可变的,可实现加密和数字签名
DSA(Digital Signature Algorithm):数字签名算法,是一种标准的 DSS(数字签名标准)
ECC(Elliptic Curves Cryptography):椭圆曲线密码编码学,比RSA加密算法使用更小的密钥,提供相当的或更高等级的安全
1.7.2.2 非对称加密实现加密
接收者
生成公钥/密钥对:P和S
公开公钥P,保密密钥S
发送者
使用接收者的公钥来加密消息M
将P(M)发送给接收者
接收者
使用密钥S来解密:M=S(P(M))
1.7.2.3 非对称加密实现数字签名
发送者
生成公钥/密钥对:P和S
公开公钥P,保密密钥S
使用密钥S来加密消息M
发送给接收者S(M)
接收者
使用发送者的公钥来解密M=P(S(M))
1.7.2.4 RSA和DSA
RSA:公钥加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的,RSA取名来自开发他们三者的名字,后成立RSA数据安全有限公司。RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的所有密码攻击,已被ISO推荐为公钥数据加密标准。RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥
DSA (Digital Signature Algorithm):1991年7月26日提交,并归属于David W. Kravitz前NSA员工,
DSA是Schnorr和ElGamal签名算法的变种,被美国NIST作为SS(DigitalSignature Standard), DSA是基于整数有限域离散对数难题的,其安全性与RSA相比差不多。DSA只是一种算法,和RSA不同之处在于它不能用作加密和解密,也不能进行密钥交换,只用于签名,它比RSA要快很多
1.7.3 单向哈希算法
哈希算法:也称为散列算法,将任意数据缩小成固定大小的“指纹”,称为digest,即摘要
特性:
任意长度输入,固定长度输出
若修改数据,指纹也会改变,且有雪崩效应,数据的一点微小改变,生成的指纹值变化非常大。
无法从指纹中重新生成数据,即不要逆,具有单向性
功能:数据完整性
常见算法
md5: 128bits、sha1: 160bits、sha224 、sha256、sha384、sha512
常用工具
md5sum | sha1sum [ --check ] file
openssl、gpg
rpm -V
数字签名
RPM 文件完整性
rpm --verify package_name (or -V)
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat*
rpm --checksig pakage_file_name (or -K
1.7.4 综合应用多种加密算法
1.7.4.1 实现数据加密
实现数据加密,无法验证数据完整性和来源
Key(data)+Pb(key)
1.7.4.2 实现数字签名
不加密数据,可以保证数据来源的可靠性、数据的完整性和一致性
data+Sa(hash(data))
1.7.4.3 综合加密和签名
即实现数据加密,又可以保证数据来源的可靠性、数据的完整性和一致性
方法1:Pb{Sa[hash(data)]+data}
方法2:对称key{Sa[hash(data)]+data}+Pb(对称key)
1.7.5 密码交换
密钥交换:IKE( Internet Key Exchange )
公钥加密:用目标的公钥加密对称密钥
DH (Deffie-Hellman):生成对称(会话)密钥
参看:https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
DH 介绍
这个密钥交换方法,由惠特菲尔德·迪菲(Bailey Whitfield Diffie)和马丁·赫尔曼(Martin
Edward Hellman)在1976年发表
它是一种安全协议,让双方在完全没有对方任何预先信息的条件下通过不安全信道建立起一个密钥,这个密钥一般作为“对称加密”的密钥而被双方在后续数据传输中使用。
DH数学原理是base离散对数问题。做类似事情的还有非对称加密类算法,如:RSA。
其应用非常广泛,在SSH、VPN、Https...都有应用,勘称现代密码基石
DH 实现过程:
A: g,p 协商生成公开的整数g, 大素数p
B: g,p
A:生成隐私数据:a (a<p),计算得出 g^a%p,发送给B
B:生成隐私数据:b,(b<p),计算得出 g^b%p,发送给A
A:计算得出 [(g^b%p)^a]%p = g^ab%p,生成为密钥
B:计算得出 [(g^a%p)^b]%p = g^ab%p,生成为密钥
DH 特点
泄密风险:私密数据a,b在生成K后将被丢弃,因此不存在a,b过长时间存在导致增加泄密风险。
中间人攻击:由于DH在传输p,g时并无身份验证,所以有机会被实施中间人攻击,替换双方传输时的数据
#例:
g=23
p=5
A:a=6
g^a%p=23^6%5=4
[(g^b%p)^a]%p=2^6%5=4
B:b=15
g^b%p=23^15%5=2
[(g^a%p)^b]%p=4^15%5=4
[root@centos8 ~]#echo 23^15%5|bc
2
[root@centos8 ~]#echo 23^6%5|bc
4
[root@centos8 ~]#echo 2^6%5|bc
4
[root@centos8 ~]#echo 4^15%5|bc
4
1.8 CA和证书
1.8.1 中间人攻击
Man-in-the-middle,简称为 MITM,中间人
1.8.2 CA和证书
#PKI:Public Key Infrastructure 公共密钥加密体系
#签证机构:CA(Certificate Authority)
#注册机构:RA
#证书吊销列表:CRL
#证书存取库:
#X.509:定义了证书的结构以及认证协议标准
版本号
序列号
签名算法
颁发者
有效期限
主体名称
#证书类型:
证书授权机构的证书
服务器证书
用户证书
#获取证书两种方法:
自签名的证书: 自已签发自己的公钥
使用证书授权机构:
生成证书请求(csr)
将证书请求csr发送给CA
CA签名颁发证书
1.8.3 安全协议 SSL/TLS
1.8.3.1 TLS 介绍
SSL:Secure Socket Layer,TLS: Transport Layer Security
1994年,NetScape公司设计了SSL协议(Secure Sockets Layer)的1.0版,但是未发布
1995:SSL 2.0 Netscape 开发
1996:SSL 3.0
1999:TLS 1.0
2006:TLS 1.1 IETF(Internet工程任务组) RFC 4346,从2020年3月起,停止支持TLS 1.1及TLS 1.0版本
安全协议,谷歌(Chrome)、Mozilla(Firefox)、微软(IE和Edge) 、苹果(Safari) 都会发布新版
浏览器执行这个策略
2008:TLS 1.2 当前主要使用
2018:TLS 1.3
功能:
机密性
认证
完整性
重放保护
1.8.3.2 SSL/TLS组成
Handshake协议:包括协商安全参数和密码套件、服务器身份认证(客户端身份认证可选)、密钥
交换
ChangeCipherSpec 协议:一条消息表明握手协议已经完成
Alert 协议:对握手协议中一些异常的错误提醒,分为fatal和warning两个级别,fatal类型错误会
直接中断SSL链接,而warning级别的错误SSL链接仍可继续,只是会给出错误警告
Record 协议:包括对消息的分段、压缩、消息认证和完整性保护、加密等
1.8.4 HTTPS
HTTPS 协议:就是“HTTP 协议”和“SSL/TLS 协议”的组合。HTTP over SSL 或 HTTP over TLS ,对http协议的文本数据进行加密处理后,成为二进制形式传输
1.8.4.1 HTTPS 结构
1.8.4.2 HTTPS 工作的简化过程
1. 客户端发起HTTPS请求
用户在浏览器里输入一个https网址,然后连接到服务器的443端口
2. 服务端的配置
采用HTTPS协议的服务器必须要有一套数字证书,可以自己制作,也可以向组织申请。区别就是自己颁发的证书需要客户端验证通过,才可以继续访问,而使用受信任的公司申请的证书则不会弹出提示页面。这套证书其实就是一对公钥和私钥
3. 传送服务器的证书给客户端
证书里其实就是公钥,并且还包含了很多信息,如证书的颁发机构,过期时间等等
4. 客户端解析验证服务器证书
这部分工作是由客户端的TLS来完成的,首先会验证公钥是否有效,比如:颁发机构,过期时间等等,如果发现异常,则会弹出一个警告框,提示证书存在问题。如果证书没有问题,那么就生成一个随机值。然后用证书中公钥对该随机值进行非对称加密
5. 客户端将加密信息传送服务器
这部分传送的是用证书加密后的随机值,目的就是让服务端得到这个随机值,以后客户端和服务端的通信就可以通过这个随机值来进行加密解密了
6. 服务端解密信息
服务端将客户端发送过来的加密信息用服务器私钥解密后,得到了客户端传过来的随机值
7. 服务器加密信息并发送信息
服务器将数据利用随机值进行对称加密,再发送给客户端
8. 客户端接收并解密信息
客户端用之前生成的随机值解密服务段传过来的数据,于是获取了解密后的内容
2 OpenSSL
2.1 OpenSSL 介绍
官网:https://www.openssl.org/
OpenSSL计划在1998年开始,其目标是发明一套自由的加密工具,在互联网上使用。OpenSSL以Eric
Young以及Tim Hudson两人开发的SSLeay为基础,随着两人前往RSA公司任职,SSLeay在1998年12月停止开发。因此在1998年12月,社群另外分支出OpenSSL,继续开发下去
OpenSSL管理委员会当前由7人组成,有13个开发人员具有提交权限(其中许多人也是OpenSSL管理委员会的一部分)。只有两名全职员工(研究员),其余的是志愿者
该项目每年的预算不到100万美元,主要依靠捐款。 TLS 1.3 的开发由 Akamai 赞助
OpenSSL是一个开放源代码的软件库包,应用程序可以使用这个包来进行安全通信,避免窃听,同时确认另一端连线者的身份。这个包广泛被应用在互联网的网页服务器上
其主要库是以C语言所写成,实现了基本的加密功能,实现了SSL与TLS协议。OpenSSL可以运行在OpenVMS、 Microsoft Windows以及绝大多数类Unix操作系统上(包括Solaris,Linux,Mac OS X与各种版本的开放源代码BSD操作系统)
心脏出血漏洞:OpenSSL 1.0.1版本(不含1.0.1g)含有一个严重漏洞,可允许攻击者读取服务器的内存信息。该漏洞于2014年4月被公诸于世,影响三分之二的活跃网站
包括三个组件:
libcrypto:用于实现加密和解密的库
libssl:用于实现ssl通信协议的安全库
openssl:多用途命令行工具
2.2 Base64 编码
Base64是网络上最常见的用于传输 8Bit 字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法
base64的编码过程如下:
将每3个字节放入一个24位的缓冲区中,最后不足3个字节的,缓冲区的剩余部分用0来填补。然后每次取出6位(2的6次方为64,使用64个字符即可表示所有),将高2位用0来填充,组成一个新的字节,计算出这个新字节的十进制值,对应上面的编码表,输出相应的字符。这样不断地进行下去,就可完成对所有数据的编码工作。
按照以上规则对文本Man编码如下:
#例:
[root@centos8 ~]#echo -n Man | base64
TWFu
[root@centos8 ~]#echo TWFu | base64 -d
Man[root@centos8 ~]#
[root@centos8 ~]#echo -n ab | base64
YWI=
[root@centos8 ~]#echo -n ab | base64 | base64 -d
ab[root@centos8 ~]#
#例:破解下面密文
JXU0RjYwJXU1OTdEJXU2NzBCJXU1M0NCJXVGRjAxJXU2MjExJXU2NjJGJXU3MzhCJXU2NjUzJXU2NjI1
JXVGRjBDJXU2MjExJXU3Njg0UVEldUZGMUEyOTMwODYyMCV1RkYwQyV1NTNFRiV1NEVFNSV1NTJBMCV1
NEUyQSV1NTk3RCV1NTNDQiV1NTQxNyV1RkYxRiUwQQ==
2.3 openssl 命令
两种运行模式:
交互模式
批处理模式
三种子命令:
标准命令
消息摘要命令
加密命令
#例: openssl的交互和非交互式查看版本
root@ubuntu2004:~# openssl version
OpenSSL 1.1.1f 31 Mar 2020
[root@centos8 ~]#openssl version
OpenSSL 1.1.1c FIPS 28 May 2019
[root@ubuntu1804 ~]#openssl
OpenSSL> version
OpenSSL 1.1.1 11 Sep 2018
[root@centos7 ~]#openssl
OpenSSL> version
OpenSSL 1.0.2k-fips 26 Jan 2017
[root@centos8 ~]#openssl version
OpenSSL 1.1.1 FIPS 11 Sep 2018
[root@centos8 ~]#openssl help
Standard commands
asn1parse ca ciphers cms
crl crl2pkcs7 dgst dhparam
dsa dsaparam ec ecparam
enc engine errstr gendsa
genpkey genrsa help list
nseq ocsp passwd pkcs12
pkcs7 pkcs8 pkey pkeyparam
[root@centos8 ~]#openssl
OpenSSL> help
Standard commands
asn1parse ca ciphers cms
crl crl2pkcs7 dgst dhparam
......
OpenSSL> ca --help
Usage: ca [options]
Valid options are:
-help Display this summary
-verbose Verbose output during processing
-config val A config file
......
OpenSSL>q
[root@centos8 ~]#
2.3.1 openssl命令单向哈希加密
工具:openssl dgst
算法:md5sum, sha1sum, sha224sum,sha256sum…
#dgst 命令:帮助:man dgst
openssl dgst -md5 [-hex默认] /PATH/SOMEFILE
openssl dgst -md5 testfile
md5sum /PATH/TO/SOMEFILE
[root@centos8 data]#openssl md5 fstab
MD5(fstab)= 8f8e3b0d0c17f1b29d404544c7b310da
[root@centos8 data]#openssl sha512 fstab
SHA512(fstab)=
81f67107026a43bf60fff2cdd6ebe93f49ad3bf48e3645912aa0e8d27eec8d9647121f608c7b6ad1
94856318f0381db21f6961db862e99644126b64c38a5eeb6
[root@centos8 data]#sha512sum fstab
81f67107026a43bf60fff2cdd6ebe93f49ad3bf48e3645912aa0e8d27eec8d9647121f608c7b6ad1
94856318f0381db21f6961db862e99644126b64c38a5eeb6 fstab
#补充知识:
MAC: Message Authentication Code,单向加密的一种延伸应用,用于实现网络通信中保证所传输数据
的完整性机制
HMAC:hash-based MAC,使用哈希算法
2.3.2 openssl 命令生成用户密码
passwd命令:帮助:man sslpasswd
[root@centos8 ~]#openssl passwd --help
Usage: passwd [options]
Valid options are:
-help Display this summary
-in infile Read passwords from file
-noverify Never verify when reading password from terminal
-quiet No warnings
-table Format output as table
-reverse Switch table columns
-salt val Use provided salt
-stdin Read passwords from stdin
-6 SHA512-based password algorithm
-5 SHA256-based password algorithm
-apr1 MD5-based password algorithm, Apache variant
-1 MD5-based password algorithm
-aixmd5 AIX MD5-based password algorithm
-crypt Standard Unix password algorithm (default)
-rand val Load the file(s) into the random number generator
-writerand outfile Write random data to the specified file
[root@centos7 ~]# openssl passwd --help
Usage: passwd [options] [passwords]
where options are
-crypt standard Unix password algorithm (default)
-1 MD5-based password algorithm
-apr1 MD5-based password algorithm, Apache variant
-salt string use provided salt
-in file read passwords from file
-stdin read passwords from stdin
-noverify never verify when reading password from terminal
-quiet no warnings
-table format output as table
-reverse switch table columns
[root@centos8 ~]#getent shadow liang
liang:$6$Y16DiwuVQtL6XCQK$DAQO4BhVbfQmaUMFWKR61hVwFvxk7J9U4pZaFcwf6nBwERUN6bL3wAL
PonDRebk3CgooupeXHfRuFKRciUe6q.:18373:0:99999:7:::
[root@centos8 ~]#echo xinxin | openssl passwd -6 -salt Y16DiwuVQtL6XCQK -stdin
$6$Y16DiwuVQtL6XCQK$DAQO4BhVbfQmaUMFWKR61hVwFvxk7J9U4pZaFcwf6nBwERUN6bL3wALPonDR
ebk3CgooupeXHfRuFKRciUe6q.
[root@ubuntu ~]#openssl passwd -6 -salt Y16DiwuVQtL6XCQK xinxin
$6$Y16DiwuVQtL6XCQK$DAQO4BhVbfQmaUMFWKR61hVwFvxk7J9U4pZaFcwf6nBwERUN6bL3wALPonDR
ebk3CgooupeXHfRuFKRciUe6q.
#例: 利用Python程序在CentOS7 生成sha512加密密码
[root@centos7 ~]#python -c 'import
crypt,getpass;pw="xinxin";print(crypt.crypt(pw))'
$6$pt0SFMf6YqKea3mh$.7Hkslg17uI.Wu7BcMJStVVtkzrwktXrOC8DxcMFC4JO1igrqR7VAi87H5PH
OuLTUEjl7eJqKUhMT1e9ixojn1
例:创建新用户同时指定密码,在CentOS8和Ubuntu都通用
[root@centos8 ~]#useradd -p `echo xinxin | openssl passwd -6 -salt
Y16DiwuVQtL6XCQK -stdin` zhang
[root@centos8 ~]#getent shadow zhang
zhang:$6$Y16DiwuVQtL6XCQK$DAQO4BhVbfQmaUMFWKR61hVwFvxk7J9U4pZaFcwf6nBwERUN6bL3wA
LPonDRebk3CgooupeXHfRuFKRciUe6q.:18402:0:99999:7:::
[root@centos8 ~]#getent shadow zhang liang
zhang:$6$Y16DiwuVQtL6XCQK$DAQO4BhVbfQmaUMFWKR61hVwFvxk7J9U4pZaFcwf6nBwERUN6bL3wA
LPonDRebk3CgooupeXHfRuFKRciUe6q.:18402:0:99999:7:::
liang:$6$Y16DiwuVQtL6XCQK$DAQO4BhVbfQmaUMFWKR61hVwFvxk7J9U4pZaFcwf6nBwERUN6bL3wAL
PonDRebk3CgooupeXHfRuFKRciUe6q.:18373:0:99999:7:::
#例:
openssl passwd -1 -salt SALT(最多8位)
openssl passwd -1 -salt centos
2.3.2 openssl命令生成随机数
#随机数生成器:伪随机数字,利用键盘和鼠标,块设备中断生成随机数
/dev/random #仅从熵池返回随机数;随机数用尽,阻塞
/dev/urandom #从熵池返回随机数;随机数用尽,会利用软件生成伪随机数,非阻塞
#帮助:man sslrand
openssl rand -base64|-hex NUM
NUM: 表示字节数,使用-hex,每个字符为十六进制,相当于4位二进制,出现的字符数为NUM*2
#例:生成随机10位长度密码
[root@centos8 ~]#openssl rand -base64 9 |head -c10
ip97t6qQes[root@centos8 ~]#
[root@centos8 ~]#tr -dc '[:alnum:]' < /dev/urandom |head -c10
DO2mDp3eZu[root@centos8 ~]#
2.3.3 openssl命令实现 PKI
公钥加密:
算法:RSA, ELGamal
工具:gpg, openssl rsautl(man rsautl)
数字签名:
算法:RSA, DSA, ELGamal
密钥交换:
算法:dh
DSA:Digital Signature Algorithm
DSS:Digital Signature Standard
RSA:
openssl命令生成密钥对儿:man genrsa
#生成私钥
openssl genrsa -out /PATH/TO/PRIVATEKEY.FILE [-aes128] [-aes192] [-aes256] [-
des3] [NUM_BITS,默认2048]
#对称加密算法:man genrsa
-aes128, -aes192, -aes256, -aria128, -aria192, -aria256, -camellia128, -
camellia192, -camellia256, -des, -des3, -idea
#解密加密的私钥
openssl rsa -in /PATH/TO/PRIVATEKEY.FILE -out /PATH/TO/PRIVATEKEY2.FILE
#例: 生成的私钥设置权限保证安装
#对私钥通过设置严格的权限实现安全,应用更广泛
[root@centos8 ~]#(umask 077; openssl genrsa -out /data/app1.key 2048)
[root@centos8 ~]#cat /data/app1.key
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA4uAOqFCGYqJ6xh4VAjAtX8Jj35pXVpFgQb3N8G57RElN9X5R
RQNzaAIT7z+3vyar54WqQtT/PIPnWr9xXuUsyVb+MNV6Pbvx+bQzKeMjKtrXfe/o
FFon2d1YBF338QF1dH2NP5DUITN1jiUoMjyKyZlzzazTER9pTehdExL5xmu63n6y
qDXdmiYbgTGzjKub/3WwGYZi4WZ0Urn1DPq7mXQ2Las8xr8/nRFjtckYdXakggGS
YoRPRYKxFCU62tXtD6T1quxg96WwPeeyoXviSbhdwr1DPT/OFL6aFehjTNA2ytCG
FSbVhkz6TzBs3iLjcQGiMhG2stDoBO6gyFcL4QIDAQABAoIBADTp1uFQrpcQmBve
5j11aQ+9cbez8ozBKTcMAp0B14QMqL8J8ABtlpv6aBXTwZI2fb9owFYIAWNmzC2x
GsrsHm7y+CQBlhoR3JTFf21UiV40XjAEJReiE0tPwXh7RhmSoodBxRC/QYpgyxkU
93QIBMKSJJ0iorOKpO/DsvmA4npxM2ChXYLHHEmNkhcBw2vV5RJIlXK2QKC9vqyk
TmlOXPWBynEV68zbsRjVKSTmYh+48AJvDVJzqLSUF/Pyy6qXYnXUcBV1r683YxY4
bppuQtbFhpLoD0p6wQzwv0qdlEYKMuStO644lkf71qX3bQLwx4CGs8kY+ip2LF3q
hOM75yUCgYEA8Twueghbn99cxm4Nw++U62OpxSeVvbk8HU4tENKcz+G/NmQewjxV
gwCxxw8G+f6xZLBfiZP9UItURLw6gf/7pilfphK2FOJaJ7B52z4jCJpNNYwi5VHw
6M/s0S6Pr3w6fmFKqC/LKAVgesusrTD26GajI8oftkjHowDjZV724xMCgYEA8MLg
bEY0VHaBYxEZelBxRFxCO7fHFiilFRKaRctPzCHYm3MNvr55yFNySW1nG4f8pBGg
sthkeU4frPmYBlOkPt+W/pnOmut0y+ePfe/aIIfV/VjGpX41Qvb54G3fRyyK6zIR
Eun1nv1pu35BH7BsrCZz7TNKzCbV9Im7XK2cv7sCgYEAuDBCMEznYHcUCDIJcpwg
MWYkPvONgpHHU3zYLesRbiwoaigh0B5vEBpcoudXZVPRMFb2az5CgNgRHHY3mgDQ
rLsUW+IXgnSdb4ZwVDTqXOwrnYIFNuDMt4XihIkvjkalBs/UR/xN+p24X6nZi1dC
fom3cGEou25wd4X7GfBbQ18CgYEApU+5lr6RmdkQuDv6eXCYhS6vz589VKqtxw1R
3lBeRzSKLRpPusPAjNs3ItG6tT2nK+RqqcJJIr2QpE1wpA90PDN70u863EaFmKgz
b25sIGAEf4MgSmuhGIzKP95RK+aasCldbdY072ji23kyMBcMVxvEB39rgUe9Kr4T
ZuxSL5cCgYEAjPm5H6t4/FbeNIC26TrtI+af2liI3jMYsTVj4ReSOll+wblyWPuc
0TxCBGSJ7p9ZIaqz4ROp9yGu7XHeQ/f7Wfk9ouLhnicHVDIQk+2iLnll8QvHBuAW
BKfUkUuzdov1jy1FgojHLQcADJTW0H9+20gFgNaOJhZaVJtqoTFJg/k=
-----END RSA PRIVATE KEY-----
##用加密对称密钥加密私钥,此方式更安全,但是不方便
[root@centos8 ~]#openssl genrsa -out /data/app2.key -des3 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
................................................................................
..................................+++++
....................+++++
e is 65537 (0x010001)
Enter pass phrase for /data/app2.key:
Verifying - Enter pass phrase for /data/app2.key:
[root@centos8 ~]#cat /data/app2.key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,A153AEC7D2C38828
X6FESnpei3oqHGPXEyPnAVLo9pr5Ttd7PYi7lRQzS3jAOy+Z3iil7tv7Loa+F4jx
P6kHMiO+oxI2BFiRWTKUzVSI1Cale3r7lfpbFRRFAlx3rEOqdCAF8MB7M88F/z79
WVL7amGUzubMYERLKxPRuAbMe4jcDIbC2D82Pn0XWU8CGhILTMePm3KpPPTAxMdt
XjWBBryPXr9KTq2yavNW4MtwLqWVELK+As0NnD3TK0wgm+nCLJY2kVxneX2eiAC/
uLuWP5oKcDVml2k12itrOSdGv9zMH0uLtbMPCYxqEz9ETJe/PmutLTLFihLk3nZu
s/TTR8oYh0VaHrFQxxmHtV3Og2ZtETjVZ3jv0WjTVVi+R4AOY/6Pz1Dp/O0TJ87g
1ttoXe4bFN541GQvdnnPB1uLuDEUzbV4EcY33VXStvt7+QPPrLK2C/NLq7xrIxeq
XaYMIZifxPwrNmXrPEp66VuULoyc03r4Y7RGjMh7Asico9X1OkRe3xfpt1FBzd89
J3XNL1+Q83GBdZ+c93ar3vVorBtPoz6klq2F0WciNcC2RCzv8okk6UOi9VoMshhf
8xfCAyyowEmbMdFttFsSoKOFGpP5U08jPfqXam2e+fPTSaW/Z2yCNHuqynu7deeN
ra9VrGPHKrcH/K3C/LPAdgFo1P0MY0qntrgPHN9LSXmNrUONG1I7U5O14hgWC6sm
yqv2f9ygfv9g5ea3UZt/mLtZHnoFfdODHXMEUeeWd4VSxDyzaExwxFfi4OBvFX0b
Y2yghsLyhcoVkrVe8hkRSpgK7lQ+cjW686X6M99yWF6gNZxl/riK/e8eu1YZvPSA
I/YUEdeOKevmk71jOKMvnJkIAC+zIctoiiYYEm4TAmiAmRvqMHo1tiWhejU0vAPW
ECTubVuEzKr1mXIRnk6LxfMYwYhLbkfwV/GtqMIhLL6dEk25MbVVFe9ERMguRKNT
gS/BgYalVNXaIdlBHAtveM8wDtjqXhgFewdAo910VWemoQLwNLr0qZj5xBqevyfh
+y/NMQRz/7u3/8rUV0lgLYq3/NW1h7/HPkbG6piaQkMkoYfkQ+iq8W2q+CR09cqf
NkS+zpVldrKE/73iSUt07m65TrfSwA3epNR767b6KG2Umjdu0R4z8+LCf+0zB9Yo
IJA+G3x4gWpIc1FL1ZNyPoU+02KHh7FdGtkKyhRd1b3q1HzF3mg2tx2yT1F5dC55
mk+561m22cQZsZDuf0ps80rAMobAtu44VGdmnuGhW8U7s7sz3esa0mOBf57G7HKX
97uIp1mTvyu52oDbKfeTD/jjlyYI28svAFl49kGL3cG/4C6peh3qvgRLfF0dB4Gn
Ad5qIU1s0NXluIX02x74g1yAS+iw+PmC372DQedv1qLzJCM2TLKfhdVPvP4Ewo73
O6gMVjVabyUvmNBbQ3n7R8hY5LhCYLDfWFCInbDR673R7diucl90x+xl0+dsP7Nr
ZlvtHOA9mKTCDkX/iNfFUEKg87fY9qFs5TrZVzJm0q3PZciRrpG+hN7UShXL4KlB
/TecIedtaZV+8qPPG0URzDGASgqQinVYqh3qt9oAevb2hqAMrpM3zqAsSVowAwaE
-----END RSA PRIVATE KEY-----
[root@centos8 ~]#
#从私钥中提取出公钥
openssl rsa -in PRIVATEKEYFILE -pubout -out PUBLICKEYFILE
#例:
openssl rsa -in test.key -pubout -out test.key.pub
#例:
[root@centos7 ~]#(umask 066;openssl genrsa -out /data/app.key)
Generating RSA private key, 2048 bit long modulus
........................+++
.+++
e is 65537 (0x10001)
[root@centos7 ~]#ls -l /data/
total 4
-rw------- 1 root root 1679 Feb 3 15:26 app.key
[root@centos8 ~]#openssl genrsa -out /data/app.key 1024
Generating RSA private key, 1024 bit long modulus (2 primes)
.............................................................................+++
++
..........+++++
e is 65537 (0x010001)
[root@centos8 ~]#ll /data/app.key
-rw------- 1 root root 891 Feb 3 14:52 /data/app.key
#例:利用私钥提取公钥
[root@centos8 ~]#(umask 066;openssl genrsa -out /data/app.key)
[root@centos8 ~]#openssl rsa -in /data/app.key -pubout -out /data/app.key.pub
writing RSA key
[root@centos8 ~]#ls -l /data/
total 8
-rw------- 1 root root 887 Feb 3 15:28 app.key
-rw-r--r-- 1 root root 272 Feb 3 15:32 app.key.pub
[root@centos8 ~]#cat /data/app.key.pub
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvkS+Z4NWAMoXEwNUyn58J0oI+
ZjXotZUJLfbVHvGd3Ug6Rk52imHp1J629edUn0Cw7KoPfQLegmWsldG4v931HCdl
ELT2vj+QE7KJhc1tGFomzCnX8Q41tRrVVbHPxQYvNmMRXRqIdqXGxFpR758EngxF
zAGcnLTrDz/I2GocrQIDAQAB
-----END PUBLIC KEY-----
#例:利用加密的私钥提取公钥
[root@centos8 ~]#openssl genrsa -out /data/app2.key -des3 2048
[root@centos8 ~]#openssl rsa -in /data/app2.key -pubout -out /data/app2.pubkey
Enter pass phrase for /data/app2.key:
writing RSA key
[root@centos8 ~]#cat /data/app2.pubkey
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2VXLcmClBWiqL8u3f1vO
mjCEV+9c6S0qDXNiZrCRiYUyIMKLhyXnVLw+k6uGmC4bdATFgxDU2zjdJF3bptS6
dNZzMQJ5uAQOxQ1KHKm3O+s+Isg+H/LTHUDyc4szQZ3gjJCTKculS60qsWV7lcGP
PNSzXr3/F/TlLMRxv/9GrEjYXDgCAJt2lxWgvgXqX8Y1mc1FFkBRXVZr/CnXaij5
JIA89/OHIJoX+mQIuQEjmwFMCX/6cm64iks2obgmzluvm6fM6dkvlHDGpZicNZI1
5vaQcO7sJ4YTUGwJrDShC9R++vrAvfahvTDV3n/MLmfwS+8nhUA0Dr7M7I0GOYMp
EQIDAQAB
-----END PUBLIC KEY-----
#例:生成加密的私钥,并解密
[root@centos8 ~]#openssl genrsa -out /data/app.key -des3 1024
Generating RSA private key, 1024 bit long modulus (2 primes)
......+++++
...........+++++
e is 65537 (0x010001)
Enter pass phrase for /data/app.key:
Verifying - Enter pass phrase for /data/app.key:
[root@centos8 ~]#ls -l /data
total 4
-rw------- 1 root root 963 Feb 3 15:27 app.key
[root@centos8 ~]#cat /data/app.key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,577C3B861BAD86B6
VM8P7vx1UUcSJyXCB0pDO9xgmdNgsMOcl6NitdUvBA9Jx2oLyxsT6TYbbvZvlF55
aQB0bq43atECDBz2+v1ghacPp78S2wuGuTR1hdWwfFKJNr6d/5yXO4y1ZOt3RLvR
E4K6TCeSwZTIUNeQyuh+vstarQmaLQmdObb3lsMG+WipQj3hb0oGdZcWjuQ0gi1B
RKN1duhsWFQbdXZamBqWQqCbvigmqRwjk7S6GE3YwVhys1T4N0BFX/edNCMnzb79
6/mR+LJ2Wz/ecJXB5250rVby3h88ZNsgARg7jUM9zI6jf7G4t1etRlCJ8A9TvDe8
J/5lkDUSWEh1dnB+xw5uamDY7f3GanuKTEe54DxuBwmbBpphV1QTTefSJ01Q6l9K
wS0zV6WE+vCt99dE9J8+GXGD77twRcbmjDWfaoibvwMu00crB9K5dbxdSX50jlD9
Mj+bVr9tcwQW/WzA+V05Ndb74e8OE97pEFjTX8DeIxcZomDUcpNGpQ0eWvyE+A2x
Srux9nN8z9dUF963V4NjQGUg1owQPAlfO6zBGObXnynOqKDmBj+8FfWrnHnZUVt5
3HTV+uSkLuA+8lGoNoxH4/6ZLfvY0Y5+WSg3st2EvwGT74SNNrsNYD0qGt1LujQx
IiwfCI0uv8rqgtLtsYmJmYI0t7hWUVmb6QgX1Qh0Kvzc0A34IMDjY6dhXTKnxeF3
LGkrFAgl3+6tKXxMuQDLB6Jy9m3SOwW/JoXMVVcYHrSPzTgAl2sgAkgEq8nf4yfm
ZP9WHrDe10yXY+5K2h8UiFhvrnQ+YnH4BcTrKuEa9T7pxToo0cTdqg==
-----END RSA PRIVATE KEY-----
[root@centos8 ~]#openssl rsa -in /data/app.key -out /data/app.key
Enter pass phrase for /data/app.key:
writing RSA key
[root@centos8 ~]#ls -l /data
total 4
-rw------- 1 root root 887 Feb 3 15:28 app.key
[root@centos8 ~]#cat /data/app.key
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCvkS+Z4NWAMoXEwNUyn58J0oI+ZjXotZUJLfbVHvGd3Ug6Rk52
imHp1J629edUn0Cw7KoPfQLegmWsldG4v931HCdlELT2vj+QE7KJhc1tGFomzCnX
8Q41tRrVVbHPxQYvNmMRXRqIdqXGxFpR758EngxFzAGcnLTrDz/I2GocrQIDAQAB
AoGAQ/uDJCGkanSlya8lnumiKqqB1mm7nDWb1ScgOhw2UPubeT06Krqg+WtkXdJQ
VjsoUJoDq+WrU7/IYRDOWayp5Be3EXCdyldSrWu1+wqJ1Vnpk2oUAEyr+lzcHhW1
FNQ/5rb8kIUjR7DZpwnsYJxDygnaKaNKiUiF2FsMX8JcS8ECQQDoZt3zSsXYeR4t
Y9kPPA19npQXx9K4Wv2wsCR904pznzoaJ9Kj+6E/3AdxtXcTD0GiZe8vW+H6WCmW
gB1NpGiRAkEAwWTwO9ZncQnA+X2PYTkizBp/JdEdRjcL/D2g+g3rpL2nLChI56C5
zA4NsJFmblE2uY1OLIJBGExiZP/XS74gXQJBAISTOgYyH48P+OEX1plUPrXsorq2
KUU10wbaVNbauF6g9Lo7AXS+dQxC7pQ1Wsoqp9yGnd28Yrs3U/Ig/5ZtNaECQG+/
kKUy3bDOjwhbCjeGmVnQ0bmbXMwO0MkfH15+HrShtfBpEr9s+w8y66wkSEjkere7
M/m6Bj0xHgX4Y4JryS0CQQChBua8JXCCUGLle7+IEEcgQZSF4PdLrmnhrRG7Qrrg
yd6pPuvd2jAGv5fMhjROmf9MWc4DFiRK0B6dz7OyF9j/
-----END RSA PRIVATE KEY-----
2.4 建立私有CA实现证书申请颁发
建立私有CA:
OpenCA:OpenCA开源组织使用Perl对OpenSSL进行二次开发而成的一套完善的PKI免费软件
openssl:相关包 openssl和openssl-libs
证书申请及签署步骤:
1、生成证书申请请求
2、RA核验
3、CA签署
4、获取证书
#例:openssl-libs 包
[root@centos8 ~]#rpm -ql openssl-libs
/etc/pki/tls
/etc/pki/tls/certs
/etc/pki/tls/ct_log_list.cnf
/etc/pki/tls/misc
/etc/pki/tls/openssl.cnf
/etc/pki/tls/private
/usr/lib/.build-id
/usr/lib/.build-id/27
/usr/lib/.build-id/27/e3d5f8d63820f2fef5de2026878156fceceddb
#openssl的配置文件:
/etc/pki/tls/openssl.cnf
#三种策略:match匹配、optional可选、supplied提供
match:要求申请填写的信息跟CA设置信息必须一致
optional:可有可无,跟CA设置信息可不一致
supplied:必须填写这项申请信息
#例:
[root@centos8 ~]#cat /etc/pki/tls/openssl.cnf
#
......
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
####################################################################
[ CA_default ]
dir = /etc/pki/CA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
#unique_subject = no # Set to 'no' to allow creation of
# several certs with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem# The private key
x509_extensions = usr_cert # The extensions to add to the cert
# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = sha256 # use SHA-256 by default
preserve = no # keep passed DN ordering
policy = policy_match
# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
......
RANDFILE = $dir/private/.rand # private random number file
2.4.1 创建私有CA
#1、创建CA所需要的文件
#生成证书索引数据库文件
touch /etc/pki/CA/index.txt
#指定第一个颁发证书的序列号
echo 01 > /etc/pki/CA/serial
#2、 生成CA私钥
cd /etc/pki/CA/
(umask 066; openssl genrsa -out private/cakey.pem 2048)
#3、生成CA自签名证书
openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -days 3650 -out
/etc/pki/CA/cacert.pem
#选项说明:
-new:生成新证书签署请求
-x509:专用于CA生成自签证书
-key:生成请求时用到的私钥文件
-days n:证书的有效期限
-out /PATH/TO/SOMECERTFILE: 证书的保存路径
#国家代码:https://country-code.cl/
#例:生成自签名证书
[root@centos8 ~]#openssl req -utf8 -newkey rsa:1024 -subj "/CN=www.xinxin.org" -
keyout app.key -nodes -x509 -out app.crt
Generating a RSA private key
...........................+++++
...+++++
writing new private key to 'app.key'
-----
[root@centos8 ~]#openssl x509 -in app.crt -noout -text
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
39:9e:7c:e3:9a:0f:e3:d3:62:ea:8f:02:c9:cd:1e:f3:4a:77:cb:ff
Signature Algorithm: sha256WithRSAEncryption
Issuer: CN = www.xinxin.org
Validity
Not Before: Feb 4 15:51:39 2020 GMT
Not After : Mar 5 15:51:39 2020 GMT
Subject: CN = www.xinxin.org
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (1024 bit)
Modulus:
00:e1:7e:41:d5:50:03:07:73:13:b2:62:a6:cf:c0:
61:b1:25:1c:54:56:3e:8f:b3:aa:0e:97:49:50:de:
de:ed:7f:2f:0f:fd:17:22:72:f5:36:19:29:65:ff:
ad:ce:81:10:f3:23:8c:fb:af:32:7b:da:bc:3a:a5:
62:1c:8d:e3:f8:1b:a8:1d:82:86:e0:bc:d6:e1:28:
e0:37:33:16:6c:55:89:76:13:0e:50:37:65:39:da:
90:99:a0:d3:6f:af:4e:8d:34:6c:21:e1:ba:10:86:
8e:fd:fb:e2:83:fe:e7:8c:18:14:dc:f2:7d:6c:37:
fe:4e:e0:8d:99:65:d4:f6:9f
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
1F:67:31:48:D6:DA:6E:36:C9:6B:EC:3C:61:85:6A:52:C2:B2:06:17
X509v3 Authority Key Identifier:
keyid:1F:67:31:48:D6:DA:6E:36:C9:6B:EC:3C:61:85:6A:52:C2:B2:06:17
X509v3 Basic Constraints: critical
CA:TRUE
Signature Algorithm: sha256WithRSAEncryption
4f:75:d5:f8:99:ea:dc:4f:fd:57:05:ba:1e:ad:72:23:ae:b8:
ea:93:1d:43:21:f8:66:cb:85:49:6c:b8:8f:1e:f4:a0:e5:ac:
e5:2e:45:03:33:2f:6a:4a:28:97:30:f0:18:dd:c1:f7:46:0b:
3c:b0:b6:d6:bf:23:7d:3b:74:52:75:61:96:f9:b0:04:99:6c:
52:f4:5d:1c:76:33:52:48:4f:d4:1f:4e:5e:00:0c:18:75:c3:
ef:75:bc:c7:ea:37:6e:34:36:b2:a0:f6:6f:06:69:0a:c6:74:
d8:67:4c:16:81:2a:0b:ea:1c:16:ea:8e:48:dd:ba:0b:67:69:
19:1e
[root@centos8 ~]#
2.4.2 申请证书并颁发证书
#1、为需要使用证书的主机生成生成私钥
(umask 066; openssl genrsa -out /data/test.key 2048)
#2、为需要使用证书的主机生成证书申请文件
openssl req -new -key /data/test.key -out /data/test.csr
#3、在CA签署证书并将证书颁发给请求者
openssl ca -in /data/test.csr -out /etc/pki/CA/certs/test.crt -days 100
#注意:默认要求 国家,省,公司名称三项必须和CA一致
#4、查看证书中的信息:
openssl x509 -in /PATH/FROM/CERT_FILE -noout -text|issuer|subject|serial|dates
#查看指定编号的证书状态
openssl ca -status SERIAL
2.4.3 吊销证书
#在客户端获取要吊销的证书的serial
openssl x509 -in /PATH/FROM/CERT_FILE -noout -serial -subject
#在CA上,根据客户提交的serial与subject信息,对比检验是否与index.txt文件中的信息一致,吊销证
书:
openssl ca -revoke /etc/pki/CA/newcerts/SERIAL.pem
#指定第一个吊销证书的编号,注意:第一次更新证书吊销列表前,才需要执行
echo 01 > /etc/pki/CA/crlnumber
#更新证书吊销列表
openssl ca -gencrl -out /etc/pki/CA/crl.pem
#查看crl文件:
openssl crl -in /etc/pki/CA/crl.pem -noout -text
2.4.4 CentOS 7 创建自签名证书
[root@centos7 ~]#cd /etc/pki/tls/certs
[root@centos7 certs]#make
This makefile allows you to create:
o public/private key pairs
o SSL certificate signing requests (CSRs)
o self-signed SSL test certificates
To create a key pair, run "make SOMETHING.key".
To create a CSR, run "make SOMETHING.csr".
To create a test certificate, run "make SOMETHING.crt".
To create a key and a test certificate in one file, run "make SOMETHING.pem".
To create a key for use with Apache, run "make genkey".
To create a CSR for use with Apache, run "make certreq".
To create a test certificate for use with Apache, run "make testcert".
To create a test certificate with serial number other than random, add
SERIAL=num
You can also specify key length with KEYLEN=n and expiration in days with DAYS=n
Any additional options can be passed to openssl req via EXTRA_FLAGS
Examples:
make server.key
make server.csr
make server.crt
make stunnel.pem
make genkey
make certreq
make testcert
make server.crt SERIAL=1
make stunnel.pem EXTRA_FLAGS=-sha384
make testcert DAYS=600
[root@centos7 certs]#ls
ca-bundle.crt ca-bundle.trust.crt make-dummy-cert Makefile renew-dummy-cert
[root@centos7 certs]#cat Makefile
UTF8 := $(shell locale -c LC_CTYPE -k | grep -q charmap.*UTF-8 && echo -utf8)
DAYS=365
KEYLEN=2048
TYPE=rsa:$(KEYLEN)
EXTRA_FLAGS=
ifdef SERIAL
EXTRA_FLAGS+=-set_serial $(SERIAL)
endif
.PHONY: usage
.SUFFIXES: .key .csr .crt .pem
.PRECIOUS: %.key %.csr %.crt %.pem
usage:
@echo "This makefile allows you to create:"
@echo " o public/private key pairs"
@echo " o SSL certificate signing requests (CSRs)"
@echo " o self-signed SSL test certificates"
@echo
@echo "To create a key pair, run \"make SOMETHING.key\"."
@echo "To create a CSR, run \"make SOMETHING.csr\"."
@echo "To create a test certificate, run \"make SOMETHING.crt\"."
@echo "To create a key and a test certificate in one file, run \"make
SOMETHING.pem\"."
@echo
@echo "To create a key for use with Apache, run \"make genkey\"."
@echo "To create a CSR for use with Apache, run \"make certreq\"."
@echo "To create a test certificate for use with Apache, run \"make
testcert\"."
@echo
@echo "To create a test certificate with serial number other than random,
add SERIAL=num"
@echo "You can also specify key length with KEYLEN=n and expiration in days
with DAYS=n"
@echo "Any additional options can be passed to openssl req via EXTRA_FLAGS"
@echo
@echo Examples:
@echo " make server.key"
@echo " make server.csr"
@echo " make server.crt"
@echo " make stunnel.pem"
@echo " make genkey"
@echo " make certreq"
@echo " make testcert"
@echo " make server.crt SERIAL=1"
@echo " make stunnel.pem EXTRA_FLAGS=-sha384"
@echo " make testcert DAYS=600"
%.pem:
umask 77 ; \
PEM1=`/bin/mktemp /tmp/openssl.XXXXXX` ; \
PEM2=`/bin/mktemp /tmp/openssl.XXXXXX` ; \
/usr/bin/openssl req $(UTF8) -newkey $(TYPE) -keyout $$PEM1 -nodes -x509 -
days $(DAYS) -out $$PEM2 $(EXTRA_FLAGS) ; \
cat $$PEM1 > $@ ; \
echo "" >> $@ ; \
cat $$PEM2 >> $@ ; \
$(RM) $$PEM1 $$PEM2
%.key:
umask 77 ; \
/usr/bin/openssl genrsa -aes128 $(KEYLEN) > $@
%.csr: %.key
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $^ -out $@
%.crt: %.key
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $^ -x509 -days $(DAYS) -out $@
$(EXTRA_FLAGS)
TLSROOT=/etc/pki/tls
KEY=$(TLSROOT)/private/localhost.key
CSR=$(TLSROOT)/certs/localhost.csr
CRT=$(TLSROOT)/certs/localhost.crt
genkey: $(KEY)
certreq: $(CSR)
testcert: $(CRT)
$(CSR): $(KEY)
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $(KEY) -out $(CSR)
$(CRT): $(KEY)
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $(KEY) -x509 -days $(DAYS) -out
$(CRT) $(EXTRA_FLAGS)
[root@centos7 certs]#
[root@centos7 certs]#make app.crt
umask 77 ; \
/usr/bin/openssl genrsa -aes128 2048 > app.key
Generating RSA private key, 2048 bit long modulus
...............+++
............................................+++
e is 65537 (0x10001)
Enter pass phrase:
Verifying - Enter pass phrase:
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key app.key -x509 -days 365 -out app.crt
Enter pass phrase for app.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:hubei
Locality Name (eg, city) [Default City]:wuhan
Organization Name (eg, company) [Default Company Ltd]:xinxin
Organizational Unit Name (eg, section) []:it
Common Name (eg, your name or your server's hostname) []:www.xinxin.org
Email Address []:admin@xinxin.org
[root@centos7 certs]#ls
app.crt app.key ca-bundle.crt ca-bundle.trust.crt make-dummy-cert Makefile
renew-dummy-cert
[root@centos7 certs]#openssl x509 -in app.crt -noout -text
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
90:d7:97:6a:21:21:f8:5e
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=CN, ST=hubei, L=wuhan, O=xinxin, OU=it,
CN=www.xinxin.org/emailAddress=admin@xinxin.org
Validity
Not Before: Feb 5 00:28:31 2020 GMT
Not After : Feb 4 00:28:31 2021 GMT
Subject: C=CN, ST=hubei, L=wuhan, O=xinxin, OU=it,
CN=www.xinxin.org/emailAddress=admin@xinxin.org
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:f8:dd:d3:ea:0b:f1:97:0f:27:de:44:a2:32:77:
fb:5c:73:74:17:7b:5f:a4:9c:a2:d4:3b:d4:49:4c:
da:e0:a2:6a:41:05:6e:10:1e:96:dc:95:34:ed:08:
05:18:ba:27:c5:e5:f0:7c:65:15:78:f8:9b:bf:ee:
41:ef:1c:6f:7f:35:29:fd:f5:cf:4a:f1:36:7e:0c:
37:96:b1:01:e5:aa:7f:6e:a0:56:b0:33:28:ed:db:
7a:56:34:67:83:be:bd:ad:3d:e7:80:d9:cf:6a:c7:
c9:7f:d1:83:73:33:7f:77:27:a5:2e:17:84:82:c7:
50:3d:20:d8:20:f1:5e:61:d2:69:07:8f:0e:cd:ea:
c2:51:bd:aa:a0:ce:61:18:6f:00:43:13:21:8d:6d:
3b:85:13:d8:93:ed:fc:65:28:ec:12:d1:67:40:d0:
98:54:9a:59:1e:10:4f:c5:8c:b5:b1:26:55:2f:e1:
53:1d:6b:71:88:64:e2:b1:21:28:8c:c7:04:3a:70:
87:c7:48:41:44:95:43:2f:e8:da:5f:f8:93:1a:9a:
de:e4:e3:82:57:60:6a:49:08:2e:5f:57:f7:62:b2:
bb:8a:1f:8b:2b:dc:40:dd:35:30:42:c1:f4:c6:1a:
0b:61:df:37:ed:bd:25:39:4c:5f:27:32:57:9e:d0:
11:9d
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
28:48:D7:B5:02:7E:D7:4B:A1:74:A7:86:4B:3C:E5:FC:39:7B:F4:2E
X509v3 Authority Key Identifier:
keyid:28:48:D7:B5:02:7E:D7:4B:A1:74:A7:86:4B:3C:E5:FC:39:7B:F4:2E
X509v3 Basic Constraints:
CA:TRUE
Signature Algorithm: sha256WithRSAEncryption
a3:66:1b:85:dc:9e:1b:c7:c8:e4:29:3c:32:b2:fc:71:c9:79:
9e:ad:db:78:bd:a4:42:1a:ef:d7:7f:4a:84:d9:46:e1:60:fa:
9f:04:83:67:88:74:fd:99:d2:e3:7b:34:86:27:a1:d0:3c:be:
5f:93:d0:17:e9:d1:f6:19:2b:d5:e7:48:1f:56:ac:65:22:ec:
64:6f:a3:05:0c:83:2f:29:a8:ef:cc:25:51:d0:16:21:93:9e:
85:fc:82:d4:8c:ba:14:47:6e:fd:33:44:71:a7:c4:7f:92:2a:
01:40:f9:69:70:73:27:89:73:82:ea:21:95:48:e2:c1:5d:b8:
ed:e7:61:49:88:1c:b6:8a:a6:bd:cc:83:6b:2c:19:b9:07:21:
46:f8:1f:dc:cb:3c:9c:6d:b9:b1:dc:03:b0:5a:00:de:41:7c:
96:d8:3a:f3:06:fc:24:03:60:54:35:85:a2:1e:79:fc:cb:6e:
fd:e2:c3:7b:16:6e:7c:56:17:d4:64:c9:15:e9:a4:b0:9a:a7:
c5:d6:f8:c8:e4:99:b1:b0:f0:8b:b4:ea:8e:a9:29:c1:4a:19:
69:7a:d7:51:93:23:51:b6:0b:63:e1:45:a7:3f:65:4d:89:55:
e8:52:29:0a:41:d2:fb:76:20:7e:14:da:a8:ad:e6:fc:b0:a9:
5f:10:b0:d3
[root@centos7 certs]#
2.4.5 例:在CentOS8上实现私有CA和证书申请
2.4.5.1 创建CA相关目录和文件
[root@centos8 ~]#mkdir -pv /etc/pki/CA/{certs,crl,newcerts,private}
mkdir: created directory '/etc/pki/CA'
mkdir: created directory '/etc/pki/CA/certs'
mkdir: created directory '/etc/pki/CA/crl'
mkdir: created directory '/etc/pki/CA/newcerts'
mkdir: created directory '/etc/pki/CA/private'
[root@centos8 ~]#tree /etc/pki/CA/
/etc/pki/CA/
├── certs
├── crl
├── newcerts
└── private
4 directories, 0 files
[root@centos8 ~]#touch /etc/pki/CA/index.txt
[root@centos8 ~]#echo 0F > /etc/pki/CA/serial
#index.txt和serial文件在颁发证书时需要使用,如果不存在,会出现以下错误提示
[root@centos8 ~]#openssl ca -in /data/app1/app1.csr -out
/etc/pki/CA/certs/app1.crt -days 1000
Using configuration from /etc/pki/tls/openssl.cnf
140040142845760:error:02001002:system library:fopen:No such file or
directory:crypto/bio/bss_file.c:72:fopen('/etc/pki/CA/index.txt','r')
140040142845760:error:2006D080:BIO routines:BIO_new_file:no such
file:crypto/bio/bss_file.c:79:
[root@centos8 ~]#openssl ca -in /data/app1/app1.csr -out
/etc/pki/CA/certs/app1.crt -days 1000
Using configuration from /etc/pki/tls/openssl.cnf
/etc/pki/CA/serial: No such file or directory
error while loading serial number
140240559408960:error:02001002:system library:fopen:No such file or
directory:crypto/bio/bss_file.c:72:fopen('/etc/pki/CA/serial','r')
140240559408960:error:2006D080:BIO routines:BIO_new_file:no such
file:crypto/bio/bss_file.c:79:
2.4.5.2 创建CA的私钥
[root@centos8 ~]#cd /etc/pki/CA/
[root@centos8 CA]#(umask 066; openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
..........................................................................+++++
.............................+++++
e is 65537 (0x010001)
[root@centos8 CA]#tree
.
├── certs
├── crl
├── newcerts
└── private
└── cakey.pem
4 directories, 1 file
[root@centos8 CA]#ll private/
total 4
-rw------- 1 root root 1679 May 20 11:55 cakey.pem
[root@centos8 CA]#cat private/cakey.pem
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAujCIyGTEHfRk1RBfoFacalTuyulhL05LK7fhZhcuDafdNOPz
YLVKn2wPwmtaga5jZUOs2K6Bz1xGYFYjz092kbQhr8D290M4AvswYRr9dE0e6StP
i/GeNT9HxiJlR38Q5Enw+rt+ek4i408R30VnwO2RDzRSQ5TaGOHBzOMrxsdKHuMc
TSdekUH/jel3Xp9hngUB/+76BL8TL/uRbgU/fc0v4/V+tH17c1S+XF28YEt1t6Rp
OOEVtFJQZtwDBRQYvaApnduHNDJD4sdCi99Hi5shdsexbt9IQHWQnrO3oVxMpbKL
4UU1E/QphCfKBQe+uraxpmZ82deM8fRJbe/3/wIDAQABAoIBAGCFvrNcgcshopBO
L7TYkbgSFcU9nbM/fHrKleAuDiLoLiY4MjilY20oQTdCHiZyeHbL0bR3KzaLmLRi
k6fqgwZgAsKxX5ap00TAYcFFk7WSMX8hg9iBxsnF53iQ5j5dYi1nI7VoM9ZF4ZJD
sHk16ua6geQG9MqyRSp3BtgnwM8IJ3y9U/a5srXKa3qlyD56EJMDP1noiKEsD6lz
H15c+nSC+pk/NBRqRd2fPDiM4rF7Lj0MZ8ikW6e6igpZet8hYLAki4ChicFaCSve
Z0r1IUU5b8k0lXtCcaeLD99kneP6vkES8RbPnlM4JXxWj4cSomvx31tgDyRCBiB1
EsSLoKECgYEA95z/PHqjYu2En40xodmB9PN27UCdlzm58z8Y2+yD5cf16sU5adWy
r9fxDo3eSi1UTW3nQTYjgzZXx0bsrnSi8106SOZ7oRl3LI6FvH3zheCUcrS3WSSx
Mboxyvv7XrzTEJGPuTq8ZgG8TsBM+vDIo+ZBPXEMVzsIaHJPTxADAlECgYEAwH7y
Axm++nXhjFxNsKRYUTktjEuz1WMGYmU4JjHpNL9oMknb1NN41eaI41MglEbjidlQ
A4avGlbPfX3aqQiyq9tA6+lzm3yS4XR2qpx6oe+LK20x5JGzzcwV8ub14g/hP6qq
9pBgVm4mCV9kDx8Unnf81vWp4L+ddjQ5wQGU8U8CgYEAhGOMk+l+MgaMQkJbpw2E
TlNd4rwJhjF3GndB81QhsVmYQk3wxIVdZGcwm3d+wmo6CKwaWON5WU5U4FcrdJso
BLZz00ZoE1pqPYh2OLGe4pWQyUOWRDM6CjxjIwRXAfAzaUhqb77XvDJxXCm0/vZ+
UCNr/k3TK1CEzlNP1BXbhgECgYEAg0ROHsUo0b0fQMsVA5cezsyx/dEF4kbz7Jdf
sdQpVpoMIPby3PAUn7DkujhOqC6rLa6ufKkUsV5vggEX4lsXFFCgtf9toaNSukHk
RjYM/m7OtZ9x/Y9KUNWSRiEvnaf8j6D/ksIjn+zfLVcKcbFdKy9hkOjXnnaslxXI
KJC+k8sCgYEAuTFCw2XTAaVHUlbzibF275Fu1ctsBC/OQx+v+ay1O6vTQ8f8AjVO
DccPsLQUW8w9Sxt8WHSs5l2jxrj5QyeUQI3NxIVN7n5vY1jJ3tSEnPW9yxlZebb4
3FN2AINcDBOVHZSI9p71NQvpzr2D11iwWhCYeIkZtlvXBBQA9ewgAWQ=
-----END RSA PRIVATE KEY-----
2.4.5.3 给CA颁发自签名证书
[root@centos8 ~]#openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -days
3650 -out /etc/pki/CA/cacert.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:beijing
Locality Name (eg, city) [Default City]:beijing
Organization Name (eg, company) [Default Company Ltd]:xinxin
Organizational Unit Name (eg, section) []:devops
Common Name (eg, your name or your server's hostname) []:ca.xinxin.org
Email Address []:admin@xinxin.org
[root@centos8 ~]#tree /etc/pki/CA
/etc/pki/CA
├── cacert.pem
├── certs
├── crl
├── newcerts
└── private
└── cakey.pem
4 directories, 2 files
[root@centos8 ~]#cat /etc/pki/CA/cacert.pem
-----BEGIN CERTIFICATE-----
MIID+zCCAuOgAwIBAgIUOgPr416WnD8XXPst9HsDrXxCU+swDQYJKoZIhvcNAQEL
BQAwgYwxCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdiZWlqaW5nMRAwDgYDVQQHDAdi
ZWlqaW5nMQ8wDQYDVQQKDAZtYWdlZHUxDzANBgNVBAsMBmRldm9wczEWMBQGA1UE
AwwNY2EubWFnZWR1Lm9yZzEfMB0GCSqGSIb3DQEJARYQYWRtaW5AbWFnZWR1Lm9y
ZzAeFw0yMDA1MjAwNDAxNTFaFw0zMDA1MTgwNDAxNTFaMIGMMQswCQYDVQQGEwJD
TjEQMA4GA1UECAwHYmVpamluZzEQMA4GA1UEBwwHYmVpamluZzEPMA0GA1UECgwG
bWFnZWR1MQ8wDQYDVQQLDAZkZXZvcHMxFjAUBgNVBAMMDWNhLm1hZ2VkdS5vcmcx
HzAdBgkqhkiG9w0BCQEWEGFkbWluQG1hZ2VkdS5vcmcwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQC6MIjIZMQd9GTVEF+gVpxqVO7K6WEvTksrt+FmFy4N
p9004/NgtUqfbA/Ca1qBrmNlQ6zYroHPXEZgViPPT3aRtCGvwPb3QzgC+zBhGv10
TR7pK0+L8Z41P0fGImVHfxDkSfD6u356TiLjTxHfRWfA7ZEPNFJDlNoY4cHM4yvG
x0oe4xxNJ16RQf+N6Xden2GeBQH/7voEvxMv+5FuBT99zS/j9X60fXtzVL5cXbxg
S3W3pGk44RW0UlBm3AMFFBi9oCmd24c0MkPix0KL30eLmyF2x7Fu30hAdZCes7eh
XEylsovhRTUT9CmEJ8oFB766trGmZnzZ14zx9Elt7/f/AgMBAAGjUzBRMB0GA1Ud
DgQWBBQS4XEOvZ59bJQCyfEuZrNeErP+XzAfBgNVHSMEGDAWgBQS4XEOvZ59bJQC
yfEuZrNeErP+XzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBs
mnrHuGBiM80FL3vKs3+WoSSvjLRftjweQGGijJ685O9mDFqz+OBcFtQtklRGtVQ3
SPtadO2j70vGmmoZaiW9zXyOBlQc8CzTxL9BJcykJHWDihYYWeixorfKjzkJ9C4y
poG/bIIj+JN3bD76BzQomYeUMzKv20cB7UvFYbg+Y01RuV62+BAM4qZP6W1ROi3e
/ZrC5ODgwkcOVo56Fg6vLWeLwcPKN6+fGkWYXUsPMXhb43icQcUHZwKup0fKcLdT
vx8uKwI8pfWfTK0Rie+igUSyIrvVGa6cvA6e2uBIk4SoAlNp+OElijY+3mE+jiqO
6AWx/63jzwWKe2YvL8at
-----END CERTIFICATE-----
[root@centos8 ~]#openssl x509 -in /etc/pki/CA/cacert.pem -noout -text
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
3a:03:eb:e3:5e:96:9c:3f:17:5c:fb:2d:f4:7b:03:ad:7c:42:53:eb
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = CN, ST = beijing, L = beijing, O = xinxin, OU = devops, CN =
ca.xinxin.org, emailAddress = admin@xinxin.org
Validity
Not Before: May 20 04:01:51 2020 GMT
Not After : May 18 04:01:51 2030 GMT
Subject: C = CN, ST = beijing, L = beijing, O = xinxin, OU = devops, CN
= ca.xinxin.org, emailAddress = admin@xinxin.org
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:ba:30:88:c8:64:c4:1d:f4:64:d5:10:5f:a0:56:
9c:6a:54:ee:ca:e9:61:2f:4e:4b:2b:b7:e1:66:17:
2e:0d:a7:dd:34:e3:f3:60:b5:4a:9f:6c:0f:c2:6b:
5a:81:ae:63:65:43:ac:d8:ae:81:cf:5c:46:60:56:
23:cf:4f:76:91:b4:21:af:c0:f6:f7:43:38:02:fb:
30:61:1a:fd:74:4d:1e:e9:2b:4f:8b:f1:9e:35:3f:
47:c6:22:65:47:7f:10:e4:49:f0:fa:bb:7e:7a:4e:
22:e3:4f:11:df:45:67:c0:ed:91:0f:34:52:43:94:
da:18:e1:c1:cc:e3:2b:c6:c7:4a:1e:e3:1c:4d:27:
5e:91:41:ff:8d:e9:77:5e:9f:61:9e:05:01:ff:ee:
fa:04:bf:13:2f:fb:91:6e:05:3f:7d:cd:2f:e3:f5:
7e:b4:7d:7b:73:54:be:5c:5d:bc:60:4b:75:b7:a4:
69:38:e1:15:b4:52:50:66:dc:03:05:14:18:bd:a0:
29:9d:db:87:34:32:43:e2:c7:42:8b:df:47:8b:9b:
21:76:c7:b1:6e:df:48:40:75:90:9e:b3:b7:a1:5c:
4c:a5:b2:8b:e1:45:35:13:f4:29:84:27:ca:05:07:
be:ba:b6:b1:a6:66:7c:d9:d7:8c:f1:f4:49:6d:ef:
f7:ff
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
12:E1:71:0E:BD:9E:7D:6C:94:02:C9:F1:2E:66:B3:5E:12:B3:FE:5F
X509v3 Authority Key Identifier:
keyid:12:E1:71:0E:BD:9E:7D:6C:94:02:C9:F1:2E:66:B3:5E:12:B3:FE:5F
X509v3 Basic Constraints: critical
CA:TRUE
Signature Algorithm: sha256WithRSAEncryption
6c:9a:7a:c7:b8:60:62:33:cd:05:2f:7b:ca:b3:7f:96:a1:24:
af:8c:b4:5f:b6:3c:1e:40:61:a2:8c:9e:bc:e4:ef:66:0c:5a:
b3:f8:e0:5c:16:d4:2d:92:54:46:b5:54:37:48:fb:5a:74:ed:
a3:ef:4b:c6:9a:6a:19:6a:25:bd:cd:7c:8e:06:54:1c:f0:2c:
d3:c4:bf:41:25:cc:a4:24:75:83:8a:16:18:59:e8:b1:a2:b7:
ca:8f:39:09:f4:2e:32:a6:81:bf:6c:82:23:f8:93:77:6c:3e:
fa:07:34:28:99:87:94:33:32:af:db:47:01:ed:4b:c5:61:b8:
3e:63:4d:51:b9:5e:b6:f8:10:0c:e2:a6:4f:e9:6d:51:3a:2d:
de:fd:9a:c2:e4:e0:e0:c2:47:0e:56:8e:7a:16:0e:af:2d:67:
8b:c1:c3:ca:37:af:9f:1a:45:98:5d:4b:0f:31:78:5b:e3:78:
9c:41:c5:07:67:02:ae:a7:47:ca:70:b7:53:bf:1f:2e:2b:02:
3c:a5:f5:9f:4c:ad:11:89:ef:a2:81:44:b2:22:bb:d5:19:ae:
9c:bc:0e:9e:da:e0:48:93:84:a8:02:53:69:f8:e1:25:8a:36:
3e:de:61:3e:8e:2a:8e:e8:05:b1:ff:ad:e3:cf:05:8a:7b:66:
2f:2f:c6:ad
[root@centos8 ~]#sz /etc/pki/CA/cacert.pem
#将文件cacert.pem传到windows上,修改文件名为cacert.pem.crt,双击可以看到
2.4.5.4 用户生成私钥和证书申请
[root@centos8 ~]#mkdir /data/app1
#生成私钥文件
[root@centos8 ~]#(umask 066; openssl genrsa -out /data/app1/app1.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
....................+++++
....................................+++++
e is 65537 (0x010001)
[root@centos8 ~]#cat /data/app1/app1.key
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAuTpb5UtXhCa4jMN3gMv8a0uHmmTWMqYip4WULOnDYK2J7QCI
EWIf7HPgZTvL1TiHVqMRaJHxwNH5IdEO6qzrqequI3pD+7M3iCtRowpD9y9Mennd
YLzEgIepUboJtn4xG/LP9e89bC00StgDFJsEl19suaSUZCbwKR9QU/RiWOLZfqLm
b5xEaUO37+eCio01wWi2TSxHu+CUVpyf915Ogg4jOoYGGLS80YknO6qe8HRwCJg6
w0n3s9BkqFgeYsZBZb2J27rzhGpPvE6ECuxaRwqdvkcZlxZnibsBP1VeDi4Vno4q
bQ+vjxTFLlTcDko8Xe6Nct+Q/Z3vQA+YNoH/XQIDAQABAoIBAQCK9s2a6TtvWd17
PeqaJm/pz3Cc1KoetaWqKP1R9M8v6QJhXNS4tfVdYFIpoQL7pL1kslKNMXE+SEmw
pTebuL/Vasvasg/u9jXjYxyMRVdYS5QFDwiXWwfRpfXR6tD+qQ4O+cwrpqFeV0u0
Gvu0qdh3+I+Jd4Ac41mqgGOzmNVv+Piw/kTKv9iSNdcTOkhIRaHqI98xoYXAON9/
22axpb+chtoUzqmfUwEDyA7pD0MZApbX0q8ikuHGWHl/I+5mXSWARIyxrMjwSVw2
oM8TbwvTrKEq8UZ16GY42J8GfW7qo2T9EjdaSKirGT+4HsV4Dqs0zeYbu9xSwSXY
GjFtXqYBAoGBAPJ9Y1ElMeH4qzahYV1/WbdEDrXtEXqsL2tZ1BGF2q2ZPG9D+e6z
nNWb0Tv9tcijbK/9FvH2mlygHDXcJGhvfo6jD3+JQztjV95uycgNPfVEoaNF9wQc
Xgf7Qg1ejbCY9Qh2b9SnbQUPQLUzJx+R9AjNCq/kP4qYOA9yHXDW5OXZAoGBAMOM
QA2JtEKF2No7BfW2aAHdX54g9HEVB+IhtvHX1S3EtsK7GrhFCb1Ff9b+J0Hjs5yV
6Qw1ZDDllQbwCXy/p0WkjdEO8LU6jUERjbOjYxbv9JMMKywEmRH98TSx5aPAmlrh
BVH1SVisTcy+9MRykX+bQYczpPs9gedWUWgQI58lAoGBALk3gQbYDDP4Bn7h4UbT
ISnUeBAJlhJHNqkeodcIkLGMnBa4q0ziMGcQb08NSS6JdVkvTblfjSQ2v5V8IusK
TnaQoiPeKlZQWStzH/kH9E1FMNlPdY/UQxaBmkAv+rXq/y6JmH2rrJ/yuJAvFDEP
AIFAbGtRQh+QiTFzDn3EBm5xAoGASqIbzE7zWrRlGJ2QX8B3n8aS+PJQ+Vvyf08o
2NLsjSRYMKhiwVOwLOn6qd6ksxQp+CiLItq526O0Jkq1BETNndn5OoI+Qp0PTndZ
oudIKXf526m4THuQxHosdlUzdTVMdEUP18ELdmmE5BE5sESd3Zsu/mAqpq1KCDY8
qcAHKHUCgYEAmSZtkSQcu4P3QjNDAIUPWJIJbjrv/HopqJGkbYyu0RKbRuE+qX4S
3fkbpJAzLDtyrD4/UOqYXx7mMwYxslqejNdFiEaIE7TvA7AGp82npakZA+p5Xqm4
UXBg6HuyDrYOQ15j+uaMW/FaIlK1fViGn0LiOMNpqDAKlYpkzlbvCU0=
-----END RSA PRIVATE KEY-----
#生成证书申请文件
[root@centos8 ~]#openssl req -new -key /data/app1/app1.key -out
/data/app1/app1.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:beijing
Locality Name (eg, city) [Default City]:bj
Organization Name (eg, company) [Default Company Ltd]:xinxin
Organizational Unit Name (eg, section) []:it
Common Name (eg, your name or your server's hostname) []:app1.xinxin.org
Email Address []:root@xinxin.org
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@centos8 ~]#ll /data/app1/
total 8
-rw-r--r-- 1 root root 1045 May 20 14:11 app1.csr
-rw------- 1 root root 1679 May 20 14:06 app1.key
#默认有三项内容必须和CA一致:国家,省份,组织,如果不同,会出现下面的提示
[root@centos8 ~]#openssl ca -in /data/app2/app2.csr -out
/etc/pki/CA/certs/app2.crt
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
The stateOrProvinceName field is different between
CA certificate (beijing) and the request (hubei)
2.4.5.5 CA颁发证书
[root@centos8 ~]#openssl ca -in /data/app1/app1.csr -out
/etc/pki/CA/certs/app1.crt -days 1000
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
Serial Number: 15 (0xf)
Validity
Not Before: May 20 06:21:01 2020 GMT
Not After : Feb 14 06:21:01 2023 GMT
Subject:
countryName = CN
stateOrProvinceName = beijing
organizationName = xinxin
organizationalUnitName = it
commonName = app1.xinxin.org
emailAddress = root@xinxin.org
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
BC:C0:D3:08:AE:E3:2C:0C:DB:2E:DC:B9:5F:65:E2:49:6A:D7:C9:30
X509v3 Authority Key Identifier:
keyid:12:E1:71:0E:BD:9E:7D:6C:94:02:C9:F1:2E:66:B3:5E:12:B3:FE:5F
Certificate is to be certified until Feb 14 06:21:01 2023 GMT (1000 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@centos8 ~]#tree /etc/pki/CA
/etc/pki/CA
├── cacert.pem
├── certs
│ └── app1.crt
├── crl
├── index.txt
├── index.txt.attr
├── index.txt.old
├── newcerts
│ └── 0F.pem
├── private
│ └── cakey.pem
├── serial
└── serial.old
4 directories, 9 files
2.4.5.6 查看证书
[root@centos8 ~]#cat /etc/pki/CA/certs/app1.crt
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 15 (0xf)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=CN, ST=beijing, L=beijing, O=liang, OU=devops,
CN=ca.liang.org/emailAddress=admin@liang.org
Validity
Not Before: May 20 06:21:01 2020 GMT
Not After : Feb 14 06:21:01 2023 GMT
Subject: C=CN, ST=beijing, O=xinxin, OU=it,
CN=app1.xinxin.org/emailAddress=root@xinxin.org
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:b9:3a:5b:e5:4b:57:84:26:b8:8c:c3:77:80:cb:
fc:6b:4b:87:9a:64:d6:32:a6:22:a7:85:94:2c:e9:
c3:60:
。。。。。。
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
BC:C0:D3:08:AE:E3:2C:0C:DB:2E:DC:B9:5F:65:E2:49:6A:D7:C9:30
X509v3 Authority Key Identifier:
keyid:12:E1:71:0E:BD:9E:7D:6C:94:02:C9:F1:2E:66:B3:5E:12:B3:FE:5F
Signature Algorithm: sha256WithRSAEncryption
28:64:7c:ac:58:b2:07:58:5e:91:58:53:45:64:82:92:65:bd:
7b:8c:3a:20:b7:23:ed:5f:11:22:de:44:c6:8b:2a:3c:83:f2:
a。。。。。。
-----BEGIN CERTIFICATE-----
MIID+jCCAuKgAwIBAgIBDzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCQ04x
EDAOBgNVBAgMB2JlaWppbmcxEDAOBgNVBAcMB2JlaWppbmcxDzANBgNVBAoMBm1h
Z2VkdTEPMA0GA1UECwwGZGV2b3BzMRYwFAYDVQQDDA1jYS5tYWdlZHUub3JnMR8w
。。。。。。
-----END CERTIFICATE-----
[root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -text
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 15 (0xf)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = CN, ST = beijing, L = beijing, O = liang, OU = devops, CN =
ca.liang.org, emailAddress = admin@liang.org
Validity
Not Before: May 20 06:21:01 2020 GMT
Not After : Feb 14 06:21:01 2023 GMT
Subject: C = CN, ST = beijing, O = liang, OU = it, CN =
app1.liang.org, emailAddress = root@liang.org
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:b9:3a:5b:e5:4b:57:84:26:b8:8c:c3:77:80:cb:
fc:6b:4b:87:9a:64:d6:32:a6:22:a7:85:94:2c:e9:
c3:60:ad:89:ed:00:88:11:62:1f:ec:73:e0:65:3b:
。。。。。。
[root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -issuer
issuer=C = CN, ST = beijing, L = beijing, O = liang, OU = devops, CN =
ca.liang.org, emailAddress = admin@liang.org
[root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -subject
subject=C = CN, ST = beijing, O = liang, OU = it, CN = app1.liang.org,
emailAddress = root@liang.org
[root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -dates
notBefore=May 20 06:21:01 2020 GMT
notAfter=Feb 14 06:21:01 2023 GMT
[root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -serial
serial=0F
#验证指定编号对应证书的有效性
[root@centos8 ~]#openssl ca -status 0F
Using configuration from /etc/pki/tls/openssl.cnf
0F=Valid (V)
[root@centos8 ~]#cat /etc/pki/CA/index.txt
V 230214062101Z 0F unknown
/C=CN/ST=beijing/O=xinxin/OU=it/CN=app1.xinxin.org/emailAddress=root@xinxin.org
[root@centos8 ~]#cat /etc/pki/CA/index.txt.old
[root@centos8 ~]#cat /etc/pki/CA/serial
10
[root@centos8 ~]#cat /etc/pki/CA/serial.old
0F
2.4.5.7 将证书相关文件发送到用户端使用
[root@centos8 ~]#cp /etc/pki/CA/certs/app1.crt /data/app1/
[root@centos8 ~]#tree /data/app1/
/data/app1/
├── app1.crt
├── app1.csr
└── app1.key
0 directories, 3 files
2.4.5.8 证书的信任
默认生成的证书,在windows上是不被信任的,可以通过下面的操作实现信任
打开internet属性
2.4.5.9 证书的吊销
[root@centos8 ~]#openssl ca -revoke /etc/pki/CA/newcerts/11.pem
Using configuration from /etc/pki/tls/openssl.cnf
Revoking Certificate 11.
Data Base Updated
[root@centos8 ~]#openssl ca -status 11
Using configuration from /etc/pki/tls/openssl.cnf
11=Revoked (R)
[root@centos8 ~]#cat /etc/pki/CA/index.txt
V 230214062101Z 0F unknown
/C=CN/ST=beijing/O=liang/OU=it/CN=app1.liang.org/emailAddress=root@liang.org
V 210520064452Z 10 unknown
/C=CN/ST=hubei/L=wuhan/O=liang/OU=sales/CN=app2.liang.org/emailAddress=admin
@liang.org
R 210520065000Z 200520065821Z 11 unknown
/C=CN/ST=hubei/L=wuhan/O=liang/OU=sales/CN=app2.liang.org/emailAddress=admin
@liang.org
2.4.5.10 生成证书吊销列表文件
[root@centos8 ~]#openssl ca -gencrl -out /etc/pki/CA/crl.pem
Using configuration from /etc/pki/tls/openssl.cnf
/etc/pki/CA/crlnumber: No such file or directory
error while loading CRL number
140511895181120:error:02001002:system library:fopen:No such file or
directory:crypto/bio/bss_file.c:72:fopen('/etc/pki/CA/crlnumber','r')
140511895181120:error:2006D080:BIO routines:BIO_new_file:no such
file:crypto/bio/bss_file.c:79:
[root@centos8 ~]#echo 01 > /etc/pki/CA/crlnumber
[root@centos8 ~]#openssl ca -gencrl -out /etc/pki/CA/crl.pem
Using configuration from /etc/pki/tls/openssl.cnf
[root@centos8 ~]#cat /etc/pki/CA/crlnumber
02
[root@centos8 ~]#cat /etc/pki/CA/crl.pem
-----BEGIN X509 CRL-----
MIIB/DCB5QIBATANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCQ04xEDAOBgNV
BAgMB2JlaWppbmcxEDAOBgNVBAcMB2JlaWppbmcxDzANBgNVBAoMBm1hZ2VkdTEP
MA0GA1UECwwGZGV2b3BzMRYwFAYDVQQDDA1jYS5tYWdlZHUub3JnMR8wHQYJKoZI
。。。。。。
[root@centos8 ~]#openssl crl -in /etc/pki/CA/crl.pem -noout -text
Certificate Revocation List (CRL):
Version 2 (0x1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = CN, ST = beijing, L = beijing, O = xinxin, OU = devops, CN =
ca.xinxin.org, emailAddress = admin@xinxin.org
Last Update: May 20 07:03:57 2020 GMT
Next Update: Jun 19 07:03:57 2020 GMT
CRL extensions:
X509v3 CRL Number:
1
Revoked Certificates:
Serial Number: 11
Revocation Date: May 20 06:58:21 2020 GMT
Signature Algorithm: sha256WithRSAEncryption
95:11:5f:6b:73:9f:4e:67:3e:4c:72:9c:dc:18:2e:29:96:50:
87:60:42:7f:54:67:16:5a:0e:66:d0:83:d8:f9:e7:19:a1:5d:
5f:b9:4f:3e:aa:57:c8:08:e3:eb:0f:c3:25:06:5d:17:14:44:
31:c3:11:6d:92:08:82:ba:b3:f0:a6:c7:db:18:35:94:6c:36:
9a:77:b1:02:98:04:ce:9e:35:bb:48:87:57:c8:1b:1d:fd:db:
b6:f1:3f:03:5c:ec:b6:ea:e9:f1:d8:2f:7e:3d:45:43:a0:72:
32:3d:a0:a4:bc:4d:4f:cb:74:8c:e5:a1:f5:55:41:dc:c5:a8:
47:5a:15:bf:c7:2c:73:a9:df:f9:e1:ba:e1:f6:58:74:7d:9d:
be:a3:34:25:fa:6b:ca:8b:50:0f:8c:d1:e1:06:31:2a:ac:2e:
ff:b7:96:a9:b2:67:d1:7b:18:4f:7b:23:59:46:29:6f:e2:c8:
95:a5:bb:93:a0:8e:e9:a6:a7:6e:35:27:e6:e6:bb:1c:99:2d:
5a:ac:77:97:4e:cb:02:0f:f2:46:69:19:02:6a:f8:66:b8:b9:
43:06:63:d0:af:47:5e:4c:cb:b2:56:ea:d6:67:25:54:27:c3:
fd:bd:8c:d5:a1:20:4b:2b:72:7d:cd:12:b5:af:83:54:7b:96:
38:d6:e6:0d
[root@centos8 ~]#sz /etc/pki/CA/crl.pem
#将此文件crl.pem传到windows上并改后缀为crl.pem.crl,双击可以查看以下显示
3 ssh服务
3.1 ssh服务介绍
ssh: secure shell protocol, 22/tcp, 安全的远程登录,实现加密通信,代替传统的 telnet 协议
具体的软件实现:
OpenSSH:ssh协议的开源实现,CentOS 默认安装
dropbear:另一个ssh协议的开源项目的实现
SSH 协议版本
v1:基于CRC-32做MAC,不安全;man-in-middle
v2:双方主机协议选择安全的MAC方式,基于DH算法做密钥交换,基于RSA或DSA实现身份认证
3.1.1 公钥交换原理
客户端发起链接请求
服务端返回自己的公钥,以及一个会话ID(这一步客户端得到服务端公钥)
客户端生成密钥对
客户端用自己的公钥异或会话ID,计算出一个值Res,并用服务端的公钥加密
客户端发送加密后的值到服务端,服务端用私钥解密,得到Res
服务端用解密后的值Res异或会话ID,计算出客户端的公钥(这一步服务端得到客户端公钥)
最终:双方各自持有三个秘钥,分别为自己的一对公、私钥,以及对方的公钥,之后的所有通讯都
会被加密
3.1.2 ssh加密通讯原理
3.2 openssh 服务
OpenSSH是SSH (Secure SHell) 协议的免费开源实现,一般在各种Linux版本中会默认安装,基于C/S
结构
Openssh软件相关包:
openssh
openssh-clients
openssh-server
服务器端程序:/usr/sbin/sshd
Unit 文件:/usr/lib/systemd/system/sshd.service
客户端:
Linux Client: ssh, scp, sftp,slogin
Windows Client:xshell, MobaXterm,putty, securecrt, sshsecureshellclient
#例:openssh 相关包
[root@centos8 ~]#rpm -qa openssh*
openssh-8.0p1-3.el8.x86_64
openssh-server-8.0p1-3.el8.x86_64
openssh-clients-8.0p1-3.el8.x86_64
[root@centos8 ~]#rpm -ql openssh-server
/etc/pam.d/sshd
/etc/ssh/sshd_config
/etc/sysconfig/sshd
/usr/lib/.build-id
/usr/lib/.build-id/19
/usr/lib/.build-id/19/f94eb99dad442636475226c458fcc3f38a502a
/usr/lib/.build-id/3b
/usr/lib/.build-id/3b/ede10e34358c9dbff9c6ffda41a835b95302bb
/usr/lib/systemd/system/sshd-keygen.target
/usr/lib/systemd/system/sshd-keygen@.service
/usr/lib/systemd/system/sshd.service
/usr/lib/systemd/system/sshd.socket
/usr/lib/systemd/system/sshd@.service
/usr/lib/tmpfiles.d/openssh.conf
/usr/lib64/fipscheck/sshd.hmac
/usr/libexec/openssh/sftp-server
/usr/libexec/openssh/sshd-keygen
/usr/sbin/sshd
/usr/share/man/man5/moduli.5.gz
/usr/share/man/man5/sshd_config.5.gz
/usr/share/man/man8/sftp-server.8.gz
/usr/share/man/man8/sshd.8.gz
/var/empty/sshd
root@centos8 ~]#rpm -ql openssh-clients
/etc/ssh/ssh_config
/etc/ssh/ssh_config.d
/etc/ssh/ssh_config.d/05-redhat.conf
/usr/bin/scp
/usr/bin/sftp
/usr/bin/ssh
/usr/bin/ssh-add
/usr/bin/ssh-agent
/usr/bin/ssh-copy-id
/usr/bin/ssh-keyscan
/usr/lib/.build-id
/usr/lib/.build-id/3c
/usr/lib/.build-id/3c/88e491c910bc9079723a9184cbdf8bc4028624
/usr/lib/.build-id/53
/usr/lib/.build-id/53/8a62712c0e39ace0bc551706c885fa581fbaa3
/usr/lib/.build-id/92
/usr/lib/.build-id/92/bc7c07428eff615cf3b8c2a641439b1d698cda
/usr/lib/.build-id/ab
/usr/lib/.build-id/ab/a40d567f2828ad156be12ad64b50d4c000d6d1
/usr/lib/.build-id/b3
/usr/lib/.build-id/b3/a9d47e23c41b6f51d877d44ca3a2ffdc6e65f1
/usr/lib/.build-id/bb
/usr/lib/.build-id/bb/6bb2e70b69036d05be006ceaeafce21442f4ed
/usr/lib/.build-id/e6
/usr/lib/.build-id/e6/c028d0606c0fecced8250d7ff5dec5f60c9702
/usr/lib64/fipscheck/ssh.hmac
/usr/libexec/openssh/ssh-pkcs11-helper
/usr/share/man/man1/scp.1.gz
/usr/share/man/man1/sftp.1.gz
/usr/share/man/man1/ssh-add.1.gz
/usr/share/man/man1/ssh-agent.1.gz
/usr/share/man/man1/ssh-copy-id.1.gz
/usr/share/man/man1/ssh-keyscan.1.gz
/usr/share/man/man1/ssh.1.gz
/usr/share/man/man5/ssh_config.5.gz
/usr/share/man/man8/ssh-pkcs11-helper.8.gz
[root@centos8 ~]#rpm -ql openssh
/etc/ssh
/etc/ssh/moduli
/usr/bin/ssh-keygen
/usr/lib/.build-id
/usr/lib/.build-id/27
/usr/lib/.build-id/27/31b9e5af80b6b09382aaca926840eecb95b4c1
/usr/lib/.build-id/7f
/usr/lib/.build-id/7f/34cc076efad8d4e0babfd0bfe951ba140f2877
/usr/libexec/openssh
/usr/libexec/openssh/ssh-keysign
/usr/share/doc/openssh
/usr/share/doc/openssh/CREDITS
/usr/share/doc/openssh/ChangeLog
/usr/share/doc/openssh/INSTALL
/usr/share/doc/openssh/OVERVIEW
。。。。。
3.2.1 客户端 ssh命令
ssh命令是ssh客户端,允许实现对远程系统经验证地加密安全访问
当用户远程连接ssh服务器时,会复制ssh服务器/etc/ssh/ssh_host*key.pub文件中的公钥到客户机的~/.ssh/know_hosts中。下次连接时,会自动匹配相对应的私钥,不能匹配,将拒绝连接
ssh客户端配置文件: /etc/ssh/ssh_config
#主要配置
#StrictHostKeyChecking ask
#首次登录不显示检查提示
StrictHostKeyChecking no
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# IdentityFile ~/.ssh/id_ecdsa
# IdentityFile ~/.ssh/id_ed25519
# Port 22
#格式:
ssh [user@]host [COMMAND]
ssh [-l user] host [COMMAND]
#常见选项
-p port #远程服务器监听的端口
-b #指定连接的源IP
-v #调试模式
-C #压缩方式
-X #支持x11转发
-t #强制伪tty分配,如:ssh -t remoteserver1 ssh -t remoteserver2 ssh
remoteserver3
-o option 如:-o StrictHostKeyChecking=no
-i <file> #指定私钥文件路径,实现基于key验证,默认使用文件: ~/.ssh/id_dsa,
~/.ssh/id_ecdsa, ~/.ssh/id_ed25519,~/.ssh/id_rsa等
#例:禁止首次连接的询问过程
[root@centos7 ~]#sed -i.bak '/StrictHostKeyChecking/s/.*/StrictHostKeyChecking
no/' /etc/ssh/ssh_config
#例:通过多个跳板登录远程主机10.0.0.6
[root@centos8 ~]#ssh -t 10.0.0.8 ssh -t 10.0.0.7 ssh 10.0.0.6
root@10.0.0.8's password:
root@10.0.0.7's password:
root@10.0.0.6's password:
Last login: Fri May 22 09:10:28 2020 from 10.0.0.7
[root@centos6 ~]#
#例:远程执行命令
[root@centos6 ~]#ssh 10.0.0.8 "sed -i.bak
'/StrictHostKeyChecking/s/.*/StrictHostKeyChecking no/' /etc/ssh/ssh_config"
root@10.0.0.8's password:
[root@centos6 ~]#
#例:在远程主机运行本地shell脚本
[root@centos8 ~]#hostname -I
10.0.0.8
[root@centos8 ~]#cat test.sh
#!/bin/bash
hostname -I
[root@centos8 ~]#ssh 10.0.0.18 /bin/bash < test.sh
root@10.0.0.18's password:
10.0.0.18
#例:统计ssh登录失败次数最多的前十个远程IP
[root@centos8 ~]#lastb -f btmp-test | awk '{print $3}'|sort |uniq -c|sort -
nr|head
86294 58.218.92.37
43148 58.218.92.26
18036 112.85.42.201
10501 111.26.195.101
10501 111.231.235.49
10501 111.204.186.207
10501 111.11.29.199
10499 118.26.23.225
6288 42.7.26.142
4236 58.218.92.30
[root@centos8 ~]#lastb -f btmp-test | awk '{ip[$3]++}END{for(i in ip){print
ip[i],i}}'|sort -nr|head
86294 58.218.92.37
43148 58.218.92.26
18036 112.85.42.201
10501 111.26.195.101
10501 111.231.235.49
10501 111.204.186.207
10501 111.11.29.199
10499 118.26.23.225
6288 42.7.26.142
4236 58.218.92.30
#例: 利用windows 显示 Linux 的图形工具
#在windows 开启X Server的软件,如:Xmanager,观察的窗口的编号,如:0.0
[root@centos8 ~]#yum -y install firefox
[root@centos8 ~]#export DISPLAY=10.0.0.1:0.0
[root@centos8 ~]#firefox
C:\Users\Administrator>netstat -no | findstr 13520
TCP 10.0.0.1:6000 10.0.0.8:42806 ESTABLISHED 13520
TCP 10.0.0.1:6000 10.0.0.8:42812 ESTABLISHED 13520
TCP 10.0.0.1:6000 10.0.0.8:42814 ESTABLISHED 13520
TCP 10.0.0.1:6000 10.0.0.8:42846 ESTABLISHED 13520
TCP 10.0.0.1:6000 10.0.0.8:42878 ESTABLISHED 13520
3.2.2 其它ssh客户端工具scp命令,rsync 命令,sftp命令,自动登录 ssh工具 sshpass
3.2.2.1 scp命令
#格式:
scp [options] SRC... DEST/
#方式:
scp [options] [user@]host:/sourcefile /destpath
scp [options] /sourcefile [user@]host:/destpath
scp [options] [user@]host1:/sourcetpath [user@]host2:/destpath
#常用选项:
-C 压缩数据流
-r 递归复制
-p 保持原文件的属性信息
-q 静默模式
-P PORT 指明remote host的监听的端口
3.2.2.2 rsync 命令
rsync工具可以基于ssh和rsync协议实现高效率的远程系统之间复制文件,使用安全的shell连接做为传输方式,比scp更快,基于增量数据同步,即只复制两方不同的文件,此工具来自于rsync包
注意:通信两端主机都需要安装 rsync 软件
rsync -av /etc server1:/tmp/ #复制目录和目录下文件
rsync -av /etc/ server1:/tmp/ #只复制目录下文件
#常用选项:
-n 模拟复制过程
-v 显示详细过程
-r 递归复制目录树
-p 保留权限
-t 保留修改时间戳
-g 保留组信息
-o 保留所有者信息
-l 将软链接文件本身进行复制(默认)
-L 将软链接文件指向的文件复制
-u 如果接收者的文件比发送者的文件较新,将忽略同步
-z 压缩,节约网络带宽
-a 存档,相当于-rlptgoD,但不保留ACL(-A)和SELinux属性(-X)
--delete 源数据删除,目标数据也自动同步删除
--progress 显示进度
--bwlimit=5120 #限速以KB为单位,5120表示5MB
#例:
[root@centos8 ~]#rsync -auv --delete /data/test 10.0.0.7:/data
#例:
[root@centos8 ~]#rsync -auv --progress --bwlimit=5120 --delete /data/test
10.0.0.7:/data
sending incremental file list
test/
test/a.img
104,857,600 100% 5.01MB/s 0:00:19 (xfr#1, to-chk=0/2)
sent 104,883,319 bytes received 39 bytes 4,463,121.62 bytes/sec
total size is 104,857,600 speedup is 1.00
[root@rocky8 ~]#
3.2.2.3 sftp命令
交互式文件传输工具,用法和传统的ftp工具相似,利用ssh服务实现安全的文件上传和下载
使用ls cd mkdir rmdir pwd get put等指令,可用?或help获取帮助信息
sftp [user@]host
sftp> help
3.2.2.4 自动登录 ssh工具 sshpass
由EPEL源提供,ssh登陆不能在命令行中指定密码。sshpass的出现,解决了这一问题。sshpass用于非交互SSH的密码验证,一般用在sh脚本中,无须再次输入密码(本机known_hosts文件中有的主机才能生效)。它允许你用 -p 参数指定明文密码,然后直接登录远程服务器,它支持密码从命令行、文件、环境变量中读取。
#格式:
sshpass [option] command parameters
#常见选项:
-p password #后跟密码它允许你用 -p 参数指定明文密码,然后直接登录远程服务器
-f filename #后跟保存密码的文件名,密码是文件内容的第一行
-e #将环境变量SSHPASS作为密码
#例:
[root@centos8 ~]#yum -y install sshpass
[root@centos8 ~]#rpm -ql sshpass
/usr/bin/sshpass
/usr/lib/.build-id
/usr/lib/.build-id/1f
/usr/lib/.build-id/1f/c5d6cf03500df846a1a801aab749f478845a4d
/usr/share/doc/sshpass
/usr/share/doc/sshpass/AUTHORS
/usr/share/doc/sshpass/COPYING
/usr/share/doc/sshpass/ChangeLog
/usr/share/doc/sshpass/NEWS
/usr/share/man/man1/sshpass.1.gz
[root@centos8 ~]#sshpass -p 123456 ssh -o StrictHostKeyChecking=no 10.0.0.7
hostname -I
Warning: Permanently added '10.0.0.7' (ECDSA) to the list of known hosts.
10.0.0.7
[root@centos8 ~]#sshpass -p 123456 scp -o StrictHostKeyChecking=no /data/*
10.0.0.8:/data
[root@centos8 ~]# cat pass.txt
123456
[root@centos8 ~]# sshpass -f pass.txt ssh root@10.0.0.8
[root@centos8 ~]# export SSHPASS=123456
[root@centos8 ~]# sshpass -e ssh root@10.0.0.8
#例:批量修改多台主机的root密码为随机密码
cat change_root_password.sh
#!/bin/bash
rpm -q sshpass &> /dev/null || yum -y install sshpass
export SSHPASS=123456
NET=10.0.0
for i in {1..254};do
{
PASS=`openssl rand -base64 9`
sshpass -e ssh -o StrictHostKeyChecking=no $NET.$i "echo $PASS|passwd --
stdin root &> /dev/null"
echo $NET.$i:$PASS >> host.txt
}&
done
wait
#例:批量部署多台主机基于key验证脚本1
#!/bin/bash
NET=10.0.0
PASS=xinxin
ssh-keygen -P "" -f /root/.ssh/id_rsa &> /dev/null
rpm -q sshpass &> /dev/null || yum -y install sshpass &> /dev/null
for i in {1..100};do
{
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no -i
/root/.ssh/id_rsa.pub $NET.$i &> /dev/null
}&
done
wait
#例:批量部署多台主机基于key验证脚本2
[root@centos8 ~]#cat sshpass.sh
#!/bin/bash
HOSTS="
10.0.0.6
10.0.0.7
10.0.0.18
10.0.0.28
"
PASS=xinxin
ssh-keygen -P "" -f /root/.ssh/id_rsa &> /dev/null
rpm -q sshpass &> /dev/null || yum -y install sshpass &> /dev/null
for i in $HOSTS;do
{
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no -i
/root/.ssh/id_rsa.pub $i &> /dev/null
}&
done
wait
3.2.3 ssh登录验证方式介绍
ssh服务登录的常用验证方式
用户/口令
基于密钥
基于用户和口令登录验证
1. 客户端发起ssh请求,服务器会把自己的公钥发送给用户
2. 用户会根据服务器发来的公钥对密码进行加密
3. 加密后的信息回传给服务器,服务器用自己的私钥解密,如果密码正确,则用户登录成功
基于密钥的登录方式
1. 首先在客户端生成一对密钥(ssh-keygen)
2. 并将客户端的公钥ssh-copy-id 拷贝到服务端
3. 当客户端再次发送一个连接请求,包括ip、用户名
4. 服务端得到客户端的请求后,会到authorized_keys中查找,如果有响应的IP和用户,就会随机生
成一个字符串,例如:xinxin
5. 服务端将使用客户端拷贝过来的公钥进行加密,然后发送给客户端
6. 得到服务端发来的消息后,客户端会使用私钥进行解密,然后将解密后的字符串发送给服务端
7. 服务端接受到客户端发来的字符串后,跟之前的字符串进行对比,如果一致,就允许免密码登录
3.2.4 实现基于密钥的登录方式
#在客户端生成密钥对
ssh-keygen -t rsa [-P 'password'] [-f “~/.ssh/id_rsa"]
#把公钥文件传输至远程服务器对应用户的家目录
ssh-copy-id [-i [identity_file]] [user@]host
#重设私钥口令:
ssh-keygen -p
#验证代理(authentication agent)保密解密后的密钥,口令就只需要输入一次,在GNOME中,代理被
自动提供给root用户
#启用代理
ssh-agent bash
#钥匙通过命令添加给代理
ssh-add
在SecureCRT或Xshell实现基于key验证
在SecureCRT工具—>创建公钥—>生成Identity.pub文件
转化为openssh兼容格式(适合SecureCRT,Xshell不需要转化格式),并复制到需登录主机上相应文
件authorized_keys中,注意权限必须为600,在需登录的ssh主机上执行:
ssh-keygen -i -f Identity.pub >> .ssh/authorized_keys
#例:实现基于 key 验证
[root@centos8 ~]#ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): #回车,接受默认值
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:vpPtmqRv1llmoSvqT2Lx5C0LPGTE0pvdAqhDqlR5jLY root@centos8.baidu.com
The key's randomart image is:
+---[RSA 3072]----+
| |
| ++ |
| .=oo= |
| oo.oo = . . |
|..oE * S .. . |
|o . + * o. + |
|. * B+.* |
| . B*== |
| .+*B=. |
+----[SHA256]-----+
[root@centos8 ~]#ll .ssh/
total 8
-rw------- 1 root root 2622 May 22 09:51 id_rsa
-rw-r--r-- 1 root root 583 May 22 09:51 id_rsa.pub
[root@centos8 ~]#cat .ssh/id_rsa.pub
ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABgQDEIP+dPPpgsvL+RdPbHvv5w88jOiRTO8Jz2aMcnRDE5UCbBjjg
b/qqOuNEaQDk+RFfCRtxdm4o+B1NqBmFBCXVDJIy/dNzF/XyoQC1JzyBo9/sfggpeE5w3tQpJKQAIeQK
rBZ6VD/otAHB/MO9NfQP21yZsgB1qXyY+3vvM8Hrk6mJf+J4+shyLnLYfDH6m93f7fMXcgiz2h0IuG5W
85vuMUK5XQKQNnB1Ev9QSkQWtRbhzJ2LRgyBPLeifGzeO9fsiNz9k9TWVPgx6WxaW3xZe/byipEBBs49
tMRFw/5E73H90g0lzBBzw5hUmDK1uieG6wU4/b/alJzqRsXSvm7s8ompfv9Cqigvy14H4ev79Ywi2aSe
YacJ25MCmAHtwYMS5/Q25aTobpQF2DM57nlRxHF+biVjYgaJzZ+6eOIUjLzobFLqBzPsMC7DggJWjzRY
y2MY1NJX97xjrkTP6zNPdWTnRieTo6d+BaHzj92uVJp3FfbkTg5pNqlguXdEMYU=
root@centos8.baidu.com
[root@centos8 ~]#cat .ssh/id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAxCD/nTz6YLLy/kXT2x77+cPPIzokUzvCc9mjHJ0QxOVAmwY44G/6
qjrjRGkA5PkRXwkbcXZuKPgdTagZhQQl1QySMv3Tcxf18qEAtSc8gaPf7H4IKXhOcN7UKS
SkACHkCqwWelQ/6LQBwfzDvTX0D9tcmbIAdal8mPt77zPB65OpiX/iePrIci5y2Hwx+pvd
3+3zF3IIs9odCLhuVvOb7jFCuV0CkDZwdRL/UEpEFrUW4cydi0YMgTy3onxs3jvX7Ijc/Z
PU1lT4MelsWlt8WXv28oqRAQbOPbTERcP+RO9x/dINJcwQc8OYVJgytbonhusFOP2/2pSc
6kbF0r5u7PKJqX7/QqooL8teB+Hr+/WMItmknmGnCduTApgB7cGDEuf0NuWk6G6UBdgzOe
55UcRxfm4lY2IGic2funjiFIy86GxS6gcz7DAuw4ICVo80WMtjGNTSV/e8Y65Ez+szT3Vk
50Ynk6OnfgWh84/drlSadxX25E4OaTapYLl3RDGFAAAFmGG46gFhuOoBAAAAB3NzaC1yc2
EAAAGBAMQg/508+mCy8v5F09se+/nDzyM6JFM7wnPZoxydEMTlQJsGOOBv+qo640RpAOT5
EV8JG3F2bij4HU2oGYUEJdUMkjL903MX9fKhALUnPIGj3+x+CCl4TnDe1CkkpAAh5AqsFn
pUP+i0AcH8w7019A/bXJmyAHWpfJj7e+8zweuTqYl/4nj6yHIucth8Mfqb3d/t8xdyCLPa
HQi4blbzm+4xQrldApA2cHUS/1BKRBa1FuHMnYtGDIE8t6J8bN471+yI3P2T1NZU+DHpbF
pbfFl79vKKkQEGzj20xEXD/kTvcf3SDSXMEHPDmFSYMrW6J4brBTj9v9qUnOpGxdK+buzy
ial+/0KqKC/LXgfh6/v1jCLZpJ5hpwnbkwKYAe3BgxLn9DblpOhulAXYMznueVHEcX5uJW
NiBonNn7p44hSMvOhsUuoHM+wwLsOCAlaPNFjLYxjU0lf3vGOuRM/rM091ZOdGJ5Ojp34F
ofOP3a5UmncV9uRODmk2qWC5d0QxhQAAAAMBAAEAAAGAYMFSuPRbJJdDbxNtp3zKm/XwWx
WU1Ab4MATfBf+qRSg/zfqs1nQHujEg6x/OFCeXXUX15uyg/c8hTa0vIcLhExCHk2ZLCU15
xP+OhM/ddqssjdPDHQo/0Ejta3qq+XG+uVEaKbEkch1TfKrAubhDNgtmzF/XADTjxejSxD
fJY/lNuwp+5GX7uvCVMZ1bXqHEPHN76EYWavugNSwfKwA1HbXpj96FpDVnFyqPD8IDgxxF
NJGn6wxcoOkeQqeVYbEtQCPF1htWwLBl1v4WauR8FW47FDkV8kff3INGevbfiNe403DGnp
VtYKesuNA6eJ3u4i+ZugBFHq0w0exLolF4ViTlLlErLwa2D6LYozuPS3mwnEGt+eg1Md8p
aWJh0ebElnZMF3xx1zLJ6/RdeKU6/9Cb23zW4PFaDiEK//do9MC8gtN6Rdube0Ze+tfSGl
flXwDpcbcOvHN8paCMVHoW7hOm6mwlg0DKyW3ot1HKiYij0Fy5lKkN2iROeE4IxfGlAAAA
wBkFn8GcN01jNrwev6HtRd4Cv9XJow0VpXW8JdqN11xtq90h4Hm3SSOk2HuChzgCrah+Om
tofhG89QvyL6IyNU+AA4wb0EfBgc/xtFoyFNQN/WevQwIiJsEiHrCMick+Yk0gElVYxbD5
vX4tqGkNoq5ZUEI+Q8u4LbATFpCm8CGPzrTVLEXyTWC1hMwi2EK6ZH0tWLKr+WdDGnVP2g
nBxrbtJ8Thc1s9RK8tsnqHano6nZExJXspAFcvWgJjdO2wUgAAAMEA65BjaYXw1HKYdlqF
mR5b5S+NfRahOBJv3fP80XdxTtdBQ5kdFJHlu1XW5Jh8DbySjSi6nKgsd9IVHoDIw4eVnS
Z7umx1vTu03TdK9ZX98IDpeP75QkYB3xz9TjReY3H8WA9piBQVDdqcIIApUmvKhyxLNQOc
weHZ0Nj8ZiaY9wfMz34kWYhv5ngSuMBG9ThE6XyvB8GGHUXU2wIwv/DlNllRYWO6CO0C7Z
Q0vOUI3fcWb4oAunlrKOZDKMJhhQEHAAAAwQDVJMz09F0jYGr/PBk9pAnZSpQuZwlnsKjt
gni/Gz2dxiVI1JtpfWhctoch92e40DUQEX0rvzPCZGdzHRE84IlTfjWDx4hzYw4+zLv2v3
t+TMBTOleGuMNftrZCcQbWwVZPEtSTh1G7M5abthQcVZ+q3p+LM7zSHbB93LFSEccJF9EF
tpiXz/yjPjNT05h52Jq0O3NxMG7LsHp4FxNx0X/5DXepnk0VGHqAZT9XmkKGRjXEWXfj9N
AS8zTUHzSQchMAAAAdcm9vdEBjZW50b3M4Lndhbmd4aWFvY2h1bi5jb20BAgMEBQY=
-----END OPENSSH PRIVATE KEY-----
[root@centos8 ~]#ssh-copy-id root@10.0.0.7
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed:
"/root/.ssh/id_rsa.pub"
The authenticity of host '10.0.0.7 (10.0.0.7)' can't be established.
ECDSA key fingerprint is SHA256:s//WMgPVXmOjqfOg3f3X0nmaPZF+Fj5vPdWCnAzDcpU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter
out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are
prompted now it is to install the new keys
root@10.0.0.7's password: #输入远程用户的密码
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '10.0.0.7'"
and check to make sure that only the key(s) you wanted were added.
[root@centos7 ~]#ll .ssh
total 4
-rw------- 1 root root 583 May 22 09:52 authorized_keys
[root@centos7 ~]#cat .ssh/authorized_keys
ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABgQDEIP+dPPpgsvL+RdPbHvv5w88jOiRTO8Jz2aMcnRDE5UCbBjjg
b/qqOuNEaQDk+RFfCRtxdm4o+B1NqBmFBCXVDJIy/dNzF/XyoQC1JzyBo9/sfggpeE5w3tQpJKQAIeQK
rBZ6VD/otAHB/MO9NfQP21yZsgB1qXyY+3vvM8Hrk6mJf+J4+shyLnLYfDH6m93f7fMXcgiz2h0IuG5W
85vuMUK5XQKQNnB1Ev9QSkQWtRbhzJ2LRgyBPLeifGzeO9fsiNz9k9TWVPgx6WxaW3xZe/byipEBBs49
tMRFw/5E73H90g0lzBBzw5hUmDK1uieG6wU4/b/alJzqRsXSvm7s8ompfv9Cqigvy14H4ev79Ywi2aSe
YacJ25MCmAHtwYMS5/Q25aTobpQF2DM57nlRxHF+biVjYgaJzZ+6eOIUjLzobFLqBzPsMC7DggJWjzRY
y2MY1NJX97xjrkTP6zNPdWTnRieTo6d+BaHzj92uVJp3FfbkTg5pNqlguXdEMYU=
root@centos8.baidu.com
[root@centos8 ~]#ssh 10.0.0.7
Last login: Fri May 22 08:43:50 2020 from 10.0.0.1
[root@centos7 ~]#exit
logout
Connection to 10.0.0.7 closed.
[root@centos8 ~]#scp /etc/fstab 10.0.0.7:/data
fstab
#对私钥加密
[root@centos8 ~]#ssh-keygen -p
Enter file in which the key is (/root/.ssh/id_rsa):
Key has comment 'root@centos8.baidu.com'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.
[root@centos8 ~]#ssh 10.0.0.7
Enter passphrase for key '/root/.ssh/id_rsa': #输入私钥的密码
Last login: Fri May 22 08:47:50 2020 from 10.0.0.8
[root@centos7 ~]#exit
logout
Connection to 10.0.0.7 closed.
#启用ssh代理
[root@centos8 ~]#ssh-agent bash
[root@centos8 ~]#ps aux|grep agent
root 1972 0.0 0.0 29440 548 ? Ss 10:18 0:00 ssh-agent bash
root 1992 0.0 0.1 12108 964 pts/0 S+ 10:18 0:00 grep --
color=auto agent
[root@centos8 ~]#ssh-add
Enter passphrase for /root/.ssh/id_rsa:
Identity added: /root/.ssh/id_rsa (root@centos8.baidu.com)
[root@centos8 ~]#ssh 10.0.0.7
Last login: Fri May 22 08:48:55 2020 from 10.0.0.8
#例: 利用expect实现ssh key的批量部署
#!/bin/bash
COLOR="echo -e \E[1;32m"
END="\E[0m"
PASSWORD=123456
IPLIST="
10.0.0.7
10.0.0.17
"
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -P "" -f ~/.ssh/id_rsa &>/dev/null
rpm -q expect &> /dev/null || yum -y -q install expect &>/dev/null
for ip in $IPLIST ;do
{
expect <<EOF
set timeout 60
spawn ssh-copy-id $ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$PASSWORD\r" }
}
expect eof
EOF
$COLOR"$ip is ready"$END
}&
done
wait
$COLOR"Push ssh key is finished!"$END
#例:expect实现批量基于ssh的key部署
[root@centos8 ~]#cat push_ssh_key.sh
#!/bin/bash
PASS=xinxin
rpm -q expect &> /dev/null || yum -y install expect &> /dev/null
if [ ! -e /root/.ssh/id_rsa ];then
ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa &> /dev/null
echo "ssh key is created"
fi
while read IP ;do
expect &> /dev/null <<EOF #或者expect <<EOF &> /dev/null
set timeout 20
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$IP
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$PASS\n" }
}
expect eof
EOF
echo $IP is ready
done < hosts.txt
[root@centos8 ~]#cat hosts.txt
10.0.0.7
10.0.0.6
[root@centos8 ~]#bash push_ssh_key.sh
ssh key is created
10.0.0.7 is ready
10.0.0.6 is ready
[root@centos8 ~]#ssh 10.0.0.7
Last login: Fri May 22 10:19:35 2020 from 10.0.0.8
[root@centos7 ~]#exit
logout
Connection to 10.0.0.7 closed.
[root@centos8 ~]#ssh 10.0.0.6
Last login: Fri May 22 10:19:39 2020 from 10.0.0.8
[root@centos6 ~]#exit
logout
Connection to 10.0.0.6 closed.
#例:基于key验证实现批量主机管理
[root@centos8 ~]#cat hosts.txt
10.0.0.7
10.0.0.6
[root@centos8 ~]#for i in `cat hosts.txt`;do ssh $i hostname -I ;done
10.0.0.7
10.0.0.6
3.2.5 ssh服务器配置
服务器端:sshd
服务器端的配置文件: /etc/ssh/sshd_config
服务器端的配置文件帮助:man 5 sshd_config
常用参数:
Port 22 #生产建议修改
ListenAddress ip
LoginGraceTime 2m
PermitRootLogin yes #默认ubuntu不允许root远程ssh登录
StrictModes yes #检查.ssh/文件的所有者,权限等
MaxAuthTries 6 #pecifies the maximum number of authentication
attempts permitted per connection. Once the number of failures reaches half this
value, additional failures are logged. The default is 6.
MaxSessions 10 #同一个连接最大会话
PubkeyAuthentication yes #基于key验证
PermitEmptyPasswords no #空密码连接
PasswordAuthentication yes #基于用户名和密码连接
GatewayPorts no
ClientAliveInterval 10 #单位:秒
ClientAliveCountMax 3 #默认3
UseDNS yes #提高速度可改为no
GSSAPIAuthentication yes #提高速度可改为no
MaxStartups #未认证连接最大值,默认值10
Banner /path/file
#以下可以限制可登录用户的办法:
AllowUsers user1 user2 user3
DenyUsers user1 user2 user3
AllowGroups g1 g2
DenyGroups g1 g2
#例:设置 ssh 空闲60s 自动注销
Vim /etc/ssh/sshd_config
ClientAliveInterval 60
ClientAliveCountMax 0
Service sshd restart
#注意:新开一个连接才有效
#例:解决ssh登录缓慢的问题
vim /etc/ssh/sshd_config
UseDNS no
GSSAPIAuthentication no
systemctl restart sshd
#例:在 ubuntu 上启用 root 远程ssh登录
#修改sshd服务配置文件
vim /etc/ssh/sshd_config
#PermitRootLogin prohibit-password 注释掉此行
PermitRootLogin yes 修改为下面形式
systemctl restart sshd
#ssh 服务的最佳实践
建议使用非默认端口
禁止使用protocol version 1
限制可登录用户
设定空闲会话超时时长
利用防火墙设置ssh访问策略
仅监听特定的IP地址
基于口令认证时,使用强密码策略,比如:tr -dc A-Za-z0-9_ < /dev/urandom | head -c 12|
xargs
使用基于密钥的认证
禁止使用空密码
禁止root用户直接登录
限制ssh的访问频度和并发在线数
经常分析日志
4 利用 sudo 实现授权
4.1 sudo 介绍
sudo 即superuser do,允许系统管理员让普通用户执行一些或者全部的root命令的一个工具,如halt,reboot,su等等。这样不仅减少了root用户的登录 和管理时间,同样也提高了安全性
在最早之前,一般用户管理系统的方式是利用su切换为超级用户。但是使用su的缺点之一在于必须要先告知超级用户的密码。sudo于1980年前后推出,sudo使一般用户不需要知道超级用户的密码即可获得权限。首先超级用户将普通用户的名字、可以执行的特定命令、按照哪种用户或用户组的身份执行等信息,登记在特殊的文件中(通常是/etc/sudoers),即完成对该用户的授权(此时该用户称为“sudoer”);在一般用户需要取得特殊权限时,其可在命令前加上“sudo”,此时sudo将会询问该用户自己的密码(以确认终端机前的是该用户本人),回答后系统即会将该命令的进程以超级用户的权限运行。之后的一段时间内(默认为5分钟,可在/etc/sudoers自定义),使用sudo不需要再次输入密码。
由于不需要超级用户的密码,部分Unix系统甚至利用sudo使一般用户取代超级用户作为管理帐号,例如Ubuntu、Mac OS X等。
sudo特性:
sudo能够授权指定用户在指定主机上运行某些命令。如果未授权用户尝试使用 sudo,会提示联系管理员
sudo提供了丰富的日志,详细地记录了每个用户干了什么。它能够将日志传到中心主机或者日志服务器
sudo使用时间戳文件来执行类似的“检票”系统。当用户调用sudo并且输入它的密码时,用户获得了一张存活期为5分钟的票
sudo的配置文件是sudoers文件,它允许系统管理员集中的管理用户的使用权限和使用的主机。它所存放的位置默认是在/etc/sudoers,属性必须为0440
4.2 sudo 组成
#包:sudo
#配置文件:/etc/sudo.conf
#授权规则配置文件:
/etc/sudoers
/etc/sudoers.d
#安全编辑授权规则文件和语法检查工具
/usr/sbin/visudo
#例:
#检查语法
visudo -c
#检查指定配置文件语法
visudo -f /etc/sudoers.d/test
#授权编辑规则文件的工具:/usr/bin/sudoedit
#执行授权命令:/usr/bin/sudo
#时间戳文件:/var/db/sudo
#日志文件:/var/log/secure
4.3 sudo 命令
sudo命令
ls -l /usr/bin/sudo
sudo -i -u liang 切换身份功能和 su 相似,但不一样,sudo必须提前授权,而且要输入自已的密码
sudo [-u user] COMMAND
-V 显示版本信息等配置信息
-u user 默认为root
-l,ll 列出用户在主机上可用的和被禁止的命令
-v 再延长密码有效期限5分钟,更新时间戳
-k 清除时间戳(1970-01-01),下次需要重新输密码
-K 与-k类似,还要删除时间戳文件
-b 在后台执行指令
-p 改变询问密码的提示符号
示例:-p "password on %h for user %p: "
4.4 sudo 授权规则配置
配置文件格式说明:/etc/sudoers, /etc/sudoers.d/
配置文件中支持使用通配符 glob
? 任意单一字符
* 匹配任意长度字符
[wxc] 匹配其中一个字符
[!wxc] 除了这三个字符的其它字符
\x 转义
[[alpha]] 字母
#例:
/bin/ls [[alpha]]*
#配置文件规则有两类
1、别名定义:不是必须的
2、授权规则:必须的
sudoers 授权规则格式:
用户 登入主机=(代表用户) 命令
user host=(runas) command
#例:
root ALL=(ALL) ALL
#格式说明:
user: 运行命令者的身份
host: 通过哪些主机
(runas):以哪个用户的身份
command: 运行哪些命令
#sudoers的别名
User和runas:
username
#uid
%group_name
%#gid
user_alias|runas_alias
host:
ip或hostname
network(/netmask)
host_alias
command:
command name
directory
sudoedit
Cmnd_Alias
#sudo别名有四种类型:
User_Alias
Runas_Alias
Host_Alias
Cmnd_Alias
#别名格式:
[A-Z]([A-Z][0-9]_)*
#别名定义:
Alias_Type NAME1 = item1,item2,item3 : NAME2 = item4, item5
4.5 案例
#例:
Student ALL=(ALL) ALL
%wheel ALL=(ALL) ALL
#例:
student ALL=(root) /sbin/pidof,/sbin/ifconfig
%wheel ALL=(ALL) NOPASSWD: ALL
#例:
[root@centos7 ~]#groupmems -a liang -g wheel
[root@centos7 ~]#id liang
uid=1000(liang ) gid=1000(liang ) groups=1000(liang ),10(wheel)
[root@centos7 ~]#su - liang
Last login: Fri Jan 29 19:32:37 CST 2021 on pts/0
#下面方式失败
[liang @centos7 ~]$sudo echo 1.2.3.4 www.test.com >> /etc/hosts
-bash: /etc/hosts: Permission denied
#用下面方式可以实现
#bash -c 将后面所有信字符串作为整体进行sudo
#注意""必须加,否则只授权 >> 前面的命令sudo
[liang @centos7 ~]$sudo bash -c "echo 1.2.3.4 www.test.com >> /etc/hosts"
[liang @centos7 ~]$cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
centos7.baidu.com
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
1.2.3.4 www.test.com
#例:
User_Alias NETADMIN= netuser1,netuser2
Cmnd_Alias NETCMD = /usr/sbin/ip,/usr/sbin/ifconfig
NETADMIN ALL=(root) NETCMD
#例:
User_Alias SYSADER=liang,xin,%admins
User_Alias DISKADER=tom
Host_Alias SERS=www.xinxin.com,172.16.0.0/24
Runas_Alias OP=root
Cmnd_Alias SYDCMD=/bin/chown,/bin/chmod
Cmnd_Alias DSKCMD=/sbin/parted,/sbin/fdisk
SYSADER SERS= SYDCMD,DSKCMD
DISKADER ALL=(OP) DSKCMD
#例:
User_Alias ADMINUSER = adminuser1,adminuser2
Cmnd_Alias ADMINCMD = /usr/sbin/useradd,/usr/sbin/usermod, /usr/bin/passwd [a-
zA-Z]*, !/usr/bin/passwd root
ADMINUSER ALL=(root) NOPASSWD:ADMINCMD,PASSWD:/usr/sbin/userdel
#例:
Defaults:liang runas_default=tom
liang ALL=(tom,jerry) ALL
liang $ sudo cmd #默认代表tom执行cmd
liang $ sudo -u jerry cmd
#例:
liang 192.168.1.6,192.168.1.8=(root) /usr/sbin/,!/usr/sbin/useradd
#例:如何解决?
liang ALL=(ALL) /bin/cat /var/log/messages*
[root@centos8 ~]#man sudoers
will allow command like:
$ sudo cat /var/log/messages.1
It will also allow:
$ sudo cat /var/log/messages /etc/shadow
#例:
[root@centos8 ~]#vim /etc/sudoers.d/test
liang ALL=(ALL) sudoedit
#liang 可以执行下面命令
[root@centos8 ~]#sudoedit /etc/sudoers
[root@centos8 ~]#sudoedit /etc/sudoers.d/test
#例:修改验证密码间隔为2分钟
[root@centos8 ~]#vim /etc/sudoers
Defaults env_reset , timestamp_timeout=2
[root@centos8 ~]#sudo -V
......
Authentication timestamp timeout: 2.0 minutes......
#例:ubuntu 默认用户具有sudo权限
root@ubuntu1804:~# grep %sudo /etc/sudoers
%sudo ALL=(ALL:ALL) ALL
root@ubuntu1804:~# id liang
uid=1000(liang) gid=1000(liang)
groups=1000(liang),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),108(lxd),113(lpa
dmin),114(sambashare)
#默认的用户liang 属于此sudo组,所以liang 有所有权限
#例: 修改ubuntu的visudo的默认编辑器
root@ubuntu1804:~# export EDITOR=vim
root@ubuntu1804:~# visudo
#例:删除时间戳文件
[root@centos8 ~]#su - liang
Last login: Mon May 25 10:28:14 CST 2020 on pts/1
[liang@centos8 ~]$sudo -K
[liang@centos8 ~]$exit
logout
[root@centos8 ~]#ll /run/sudo/ts
total 4
-rw------- 1 root xin 112 May 25 10:11 xin
[root@centos8 ~]#file /run/sudo/ts/xin
/run/sudo/ts/xin: data
#例:修改sudo 提示符格式
[liang@centos8 ~]$sudo cat /var/log/messages
[sudo] password for liang:
[liang@centos8 ~]$sudo -p "password on %h for user %p: " cat /var/log/messages
password on centos8 for user liang:
5 PAM认证机制
5.1 PAM 介绍
认证库:文本文件,MySQL,NIS,LDAP等
PAM:Pluggable Authentication Modules,插件式的验证模块,Sun公司于1995 年开发的一种与认证相关的通用框架机制。PAM 只关注如何为服务验证用户的 API,通过提供一些动态链接库和一套统一的API,将系统提供的服务和该服务的认证方式分开,使得系统管理员可以灵活地根据需要给不同的服务配置不同的认证方式而无需更改服务程序一种认证框架,自身不做认证
5.2 PAM架构
PAM提供了对所有服务进行认证的中央机制,适用于本地登录,远程登录,如:telnet,rlogin,fsh,ftp,点对点协议PPP,su等应用程序中,系统管理员通过PAM配置文件来制定不同应用程序的不同认证策略;应用程序开发者通过在服务程序中使用PAM API(pam_xxxx( ))来实现对认证方法的调用;而PAM服务模块的开发者则利用PAM SPI来编写模块(主要调用函数pam_sm_xxxx( )供PAM接口库调用,将不同的认证机制加入到系统中;PAM接口库(libpam)则读取配置文件,将应用程序和相应的PAM服务模块联系起来
5.3 PAM相关文件
包名: pam
模块文件目录:/lib64/security/*.so
特定模块相关的设置文件:/etc/security/
应用程序调用PAM模块的配置文件
主配置文件:/etc/pam.conf,默认不存在,一般不使用主配置
为每种应用模块提供一个专用的配置文件:/etc/pam.d/APP_NAME
注意:如/etc/pam.d存在,/etc/pam.conf将失效
#例:查看程序是否支持PAM
[root@centos8 ~]#ldd `which sshd` |grep libpam
libpam.so.0 => /lib64/libpam.so.0 (0x00007fea8e70d000)
[root@centos8 ~]#ldd `which passwd` |grep pam
libpam.so.0 => /lib64/libpam.so.0 (0x00007f045b805000)
libpam_misc.so.0 => /lib64/libpam_misc.so.0 (0x00007f045b601000)
#不支持PAM
[root@centos6 ~]#ldd /usr/sbin/httpd |grep pam
[root@centos6 ~]#
5.4 PAM工作原理
PAM认证一般遵循这样的顺序:Service(服务)→PAM(配置文件)→pam_*.so
PAM认证首先要确定那一项服务,然后加载相应的PAM的配置文件(位于/etc/pam.d下),最后调用认证文件(位于/lib64/security下)进行安全认证
PAM认证过程示例:
1.使用者执行/usr/bin/passwd 程序,并输入密码
2.passwd开始调用PAM模块,PAM模块会搜寻passwd程序的PAM相关设置文件,这个设置文件一般是
在/etc/pam.d/里边的与程序同名的文件,即PAM会搜寻/etc/pam.d/passwd此设置文件
3.经由/etc/pam.d/passwd设定文件的数据,取用PAM所提供的相关模块来进行验证
4.将验证结果回传给passwd这个程序,而passwd这个程序会根据PAM回传的结果决定下一个动作(重新输入
密码或者通过验证)
5.5 PAM 配置文件格式说明
#通用配置文件/etc/pam.conf格式,此格式不使用
application type control module-path arguments
#专用配置文件/etc/pam.d/ 格式
type control module-path arguments
application:指服务名,如:telnet、login、ftp等,服务名字“OTHER”代表所有没有在该文件中明确
配置的其它服务
type:指模块类型,即功能
control :PAM库该如何处理与该服务相关的PAM模块的成功或失败情况,一个关健词实现
module-path: 用来指明本模块对应的程序文件的路径名
Arguments: 用来传递给该模块的参数
模块类型(module-type)
Auth 账号的认证和授权
Account 帐户的有效性,与账号管理相关的非认证类的功能,如:用来限制/允许用户对某个服务的访问时间,限制用户的位置(例如:root用户只能从控制台登录)
Password 用户修改密码时密码复杂度检查机制等功能
Session 用户会话期间的控制,如:最多打开的文件数,最多的进程数等
-type 表示因为缺失而不能加载的模块将不记录到系统日志,对于那些不总是安装在系统上的模块有用
Control:
required :一票否决,表示本模块必须返回成功才能通过认证,但是如果该模块返回失败,失败结果也不会立即通知用户,而是要等到同一type中的所有模块全部执行完毕,再将失败结果返回给应用程序,即为必要条件
requisite :一票否决,该模块必须返回成功才能通过认证,但是一旦该模块返回失败,将不再执行同一type内的任何模块,而是直接将控制权返回给应用程序。是一个必要条件
sufficient :一票通过,表明本模块返回成功则通过身份认证的要求,不必再执行同一type内的其它模块,但如果本模块返回失败可忽略,即为充分条件,优先于前面的required和requisite
optional :表明本模块是可选的,它的成功与否不会对身份认证起关键作用,其返回值一般被忽略
include: 调用其他的配置文件中定义的配置信息
module-path:
模块文件所在绝对路径:
模块文件所在相对路径:/lib64/security目录下的模块可使用相对路径,如:pam_shells.so、
pam_limits.so
有些模块有自已的专有配置文件,在/etc/security/*.conf目 录下
Arguments
debug :该模块应当用syslog( )将调试信息写入到系统日志文件中
no_warn :表明该模块不应把警告信息发送给应用程序
use_first_pass :该模块不能提示用户输入密码,只能从前一个模块得到输入密码
try_first_pass :该模块首先用前一个模块从用户得到密码,如果该密码验证不通过,再提示用户输入新密码
use_mapped_pass 该模块不能提示用户输入密码,而是使用映射过的密码
expose_account 允许该模块显示用户的帐号名等信息,一般只能在安全的环境下使用,因为泄漏用户名会对安全造成一定程度的威胁
注意:修改PAM配置文件将马上生效
建议:编辑pam规则时,保持至少打开一个root会话,以防止root身份验证错误
5.6 PAM模块帮助
pam模块文档说明:/user/share/doc/pam-*
rpm -qd pam
man -k pam_
man 模块名 如:man 8 rootok
5.7 常用PAM模块
5.7.1 pam_nologin.so 模块
功能:如果/etc/nologin文件存在,将导致非root用户不能登陆,当该用户登陆时,会显示/etc/nologin文件内容,并拒绝登陆
#例: 默认此模块可以对ssh等登录有效,但不影响su登录
[root@centos8 pam.d]#grep pam_nologin *
login:account required pam_nologin.so
remote:account required pam_nologin.so
sshd:account required pam_nologin.so
5.7.2 pam_limits.so 模块
功能:在用户级别实现对其可使用的资源的限制,例如:可打开的文件数量,可运行的进程数量,可用内存空间
修改限制的实现方式:
(1) ulimit命令
ulimit是linux shell的内置命令,它具有一套参数集,用于对shell进程及其子进程进行资源限制。
ulimit的设定值是 per-process 的,也就是说,每个进程有自己的limits值。
使用ulimit进行修改,立即生效。
ulimit只影响shell进程及其子进程,用户登出后失效。
可以在profile中加入ulimit的设置,变相的做到永久生效。
#修改限制的实现方式:
(1) ulimit命令
ulimit是linux shell的内置命令,它具有一套参数集,用于对shell进程及其子进程进行资源限制。
ulimit的设定值是 per-process 的,也就是说,每个进程有自己的limits值。
使用ulimit进行修改,立即生效。
ulimit只影响shell进程及其子进程,用户登出后失效。
可以在profile中加入ulimit的设置,变相的做到永久生效。
#常用选项:
-H 设置硬件资源限制.
-S 设置软件资源限制.
-a 显示当前所有的资源限制.
-c size:设置core文件的最大值.单位:blocks
-d size:设置数据段的最大值.单位:kbytes
-f size:设置创建文件的最大值.单位:blocks
-l size:设置在内存中锁定进程的最大值.单位:kbytes
-m size:设置可以使用的常驻内存的最大值.单位:kbytes
-n size:设置内核可以同时打开的文件描述符的最大值.单位:n
-p size:设置管道缓冲区的最大值.单位:kbytes
-s size:设置堆栈的最大值.单位:kbytes
-t size:设置CPU使用时间的最大上限.单位:seconds
-u size:最大用户进程数
-v size:设置虚拟内存的最大值.单位:kbytes
unlimited 是一个特殊值,用于表示不限制
##说明
查询时,若不加H或S参数,默认显示的是软限制
修改时,若不加H或S参数,两个参数一起改变
(2) 配置文件:
pam_limits的设定值是基于 per-process 的
/etc/security/limits.conf
/etc/security/limits.d/*.conf
#配置文件格式:
#每行一个定义
<domain> <type> <item> <value>
#格式说明:
应用于哪些对象
Username 单个用户
@group 组内所有用户
* 所有用户
% 仅用于限制 maxlogins limit , 可以使用 %group 语法. 只用 % 相当于 * 对所有用户
maxsyslogins limit限制. %group 表示限制此组中的所有用户总的最大登录数
#限制的类型
Soft 软限制,普通用户自己可以修改
Hard 硬限制,由root用户设定,且通过kernel强制生效
- 二者同时限定
#限制的资源
nofile 所能够同时打开的最大文件数量,默认为1024
nproc 所能够同时运行的进程的最大数量,默认为1024
#指定具体值
注意:systemd 的service 资源设置需要单独配置
# /etc/security/limits.conf
#
#This file sets the resource limits for the users logged in via PAM.
#It does not affect resource limits of the system services.
在Centos7以上版本中,使用Systemd替代了之前的SysV。/etc/security/limits.conf文件的配置作
用域缩小了。/etc/security/limits.conf的配置,只适用于通过PAM认证登录用户的资源限制,它对
systemd的service的资源限制不生效。因此登录用户的限制,通过/etc/security/limits.conf
与/etc/security/limits.d下的文件设置即可。
对于systemd service的资源设置,则需修改全局配置,全局配置文件放在/etc/systemd/system.conf
和/etc/systemd/user.conf,同时也会加载两个对应目录中的所有.conf文
件/etc/systemd/system.conf.d/*.conf和/etc/systemd/user.conf.d/*.conf。system.conf
是系统实例使用的,user.conf是用户实例使用的。
vim /etc/systemd/system.conf
DefaultLimitNOFILE=100000
DefaultLimitNPROC=65535
或者针对指定的service添加下面行
[Service]
LimitNOFILE=100000
LimitNPROC=65535
#例:系统的各种资源的默认值
[root@centos8 ~]#ulimit -a
core file size (blocks, -c) unlimited
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 3059
max locked memory (kbytes, -l) 16384
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 3059
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
#例: 查看指定进程的资源限制
#cat /proc/PID/limits
[root@liang-liyun-pc ~]# cat /proc/`pidof nginx | xargs -n1 | sort -n|head
-1`/limits
Limit Soft Limit Hard Limit Units
Max cpu time unlimited unlimited seconds
Max file size unlimited unlimited bytes
Max data size unlimited unlimited bytes
Max stack size 8388608 unlimited bytes
Max core file size 0 unlimited bytes
Max resident set unlimited unlimited bytes
Max processes 7270 7270 processes
Max open files 65535 65535 files
Max locked memory 65536 65536 bytes
Max address space unlimited unlimited bytes
Max file locks unlimited unlimited locks
Max pending signals 7270 7270 signals
Max msgqueue size 819200 819200 bytes
Max nice priority 0 0
Max realtime priority 0 0
Max realtime timeout unlimited unlimited us
#例:ulimit 命令修改用户打开的文件个数
[root@centos8 ~]#ulimit -n
1024
[root@centos8 ~]#ulimit -n 1048577
-bash: ulimit: open files: cannot modify limit: Operation not permitted
[root@centos8 ~]#ulimit -n 1048576
[root@centos8 ~]#ulimit -a
core file size (blocks, -c) unlimited
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 7111
max locked memory (kbytes, -l) 16384
max memory size (kbytes, -m) unlimited
open files (-n) 1048576
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 7111
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
[root@centos8 ~]#echo 2^20|bc
1048576
#例:限制用户最多打开的文件数和运行进程数,并持久保存
cat /etc/pam.d/system-auth
session required pam_limits.so
vim /etc/security/limits.conf
#用户apache可打开10240个文件
apache - nofile 10240
#用户student不能运行超过20个进程
student hard nproc 10
#用student登录多次运行bash,观察结果
[root@centos8 ~]#vim /etc/security/limits.conf
liang - nofile 66666
liang - nproc 5
xin - nofile 88888
[root@centos8 ~]#su - liang
Last login: Mon May 25 14:40:38 CST 2020 on pts/0
[liang@centos8 ~]$ulimit -n
66666
#案例
vim /etc/security/limits.conf
* - core unlimited
* - nproc 1000000
* - nofile 1000000
* - memlock 32000
* - msgqueue 8192000
5.7.3 pam_google_authenticator 模块
什么是 MFA ?
Multi-Factor Authentication (MFA) 是一种简单有效的最佳安全实践方法,它能够在用户名和密码之
外再额外增加一层安全保护
#功能:实现SSH登录的两次身份验证,先验证APP的数字码,再验证root用户的密码,都通过才可以登
录。
#官方网站:https://github.com/google/google-authenticator-android
例:
1. 在手机应用市场搜索:身份验证器或authenticator,并安装APP或者也可以使用微信小程序
MinaOTP
2. 运行脚本(需要联网EPEL源),本质是修改了/etc/pam.d/sshd文件,将google的PAM模块加入进去实
现
[root@centos8 ~]#dnf info google-authenticator
BaseOS
3.3 MB/s | 3.9 kB 00:00
AppStream
2.9 MB/s | 4.3 kB 00:00
EPEL
34 kB/s | 4.7 kB 00:00
extras
7.3 kB/s | 1.5 kB 00:00
Available Packages
Name : google-authenticator
Version : 1.07
Release : 1.el8
Architecture : x86_64
Size : 57 k
Source : google-authenticator-1.07-1.el8.src.rpm
Repository : epel
Summary : One-time pass-code support using open standards
URL : https://github.com/google/google-authenticator-libpam/
License : ASL 2.0
Description : The Google Authenticator package contains a plug-able
authentication
: module (PAM) which allows login using one-time pass-codes
conforming to
: the open standards developed by the Initiative for Open
Authentication
: (OATH) (which is unrelated to OAuth).
:
: Pass-code generators are available (separately) for several
mobile
: platforms.
:
: These implementations support the HMAC-Based One-time
Password (HOTP)
: algorithm specified in RFC 4226 and the Time-based One-time
Password
: (TOTP) algorithm currently in draft.
[root@centos8 ~]#bash google-authenticator.sh
Installed:
google-authenticator-1.07-1.el8.x86_64
Complete!
Do you want me to update your /root/.google_authenticator file? (y/n) y
你希望我更新你的“/root/.google_authenticator”文件吗(y/n)?
Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y
你希望禁止多次使用同一个验证令牌吗?这限制你每次登录的时间大约是30秒, 但是这加大了发现或甚
至防止中间人攻击的可能性(y/n)?
By default, a new token is generated every 30 seconds by the mobile app.
In order to compensate for possible time-skew between the client and the
server,
we allow an extra token before and after the current time. This allows for a
time skew of up to 30 seconds between authentication server and client. If
you
experience problems with poor time synchronization, you can increase the
window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the
current
code, and the 8 next codes). This will permit for a time skew of up to 4
minutes
between client and server.
Do you want to do so? (y/n) y
默认情况下,令牌保持30秒有效;为了补偿客户机与服务器之间可能存在的时滞,
我们允许在当前时间前后有一个额外令牌。如果你在时间同步方面遇到了问题, 可以增加窗口从默认的3
个可通过验证码增加到17个可通过验证码,
这将允许客户机与服务器之间的时差增加到4分钟。你希望这么做吗(y/n)?
If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every
30s.
Do you want to enable rate-limiting? (y/n) y
如果你登录的那台计算机没有经过固化,以防范运用蛮力的登录企图,可以对验证模块
启用尝试次数限制。默认情况下,这限制攻击者每30秒试图登录的次数只有3次。 你希望启用尝试次数
限制吗(y/n)?
在App Store 搜索Google Authenticator 进行App安装
Do you want authentication tokens to be time-based (y/n) y
Warning: pasting the following URL into your browser exposes the OTP secret
to Google:
https://www.google.com/chart?
chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/root@centos8.localdomain%3Fse
cret%3D7YTAL4GW3TND7BICUMJGJLIFVE%26issuer%3Dcentos8.localdomain #浏览器打开
此地址
Failed to use libqrencode to show QR code visually for scanning.
Consider typing the OTP secret into your app manually.
Your new secret key is: 7YTAL4GW3TND7BICUMJGJLIFVE
Enter code from app (-1 to skip):
访问生成的url(需要科学上网):
打开用身份验证器APP,扫网页上的二维码,进行绑定手机
继续上面的安装配置向导,输入手机APP上的数字,后续都回答 y 即可
Failed to use libqrencode to show QR code visually for scanning.
Consider typing the OTP secret into your app manually.
Your new secret key is: 7YTAL4GW3TND7BICUMJGJLIFVE
Enter code from app (-1 to skip): 224421 #手机APP上的数字
Code confirmed
Your emergency scratch codes are:
68820657
77385307
50928320
41000243
54628309
Do you want me to update your "/root/.google_authenticator" file? (y/n) y
Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y
By default, a new token is generated every 30 seconds by the mobile app.
In order to compensate for possible time-skew between the client and the
server,
we allow an extra token before and after the current time. This allows for a
time skew of up to 30 seconds between authentication server and client. If
you
experience problems with poor time synchronization, you can increase the
window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the
current
code, and the 8 next codes). This will permit for a time skew of up to 4
minutes
between client and server.
Do you want to do so? (y/n) y
If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every
30s.
Do you want to enable rate-limiting? (y/n) y
Redirecting to /bin/systemctl restart sshd.service
[root@centos8 ~]#
ssh 当前主机,可看到提示,输入手机APP上显示的数字码和root密码,可以登录,否则失败
[root@centos7 ~]#ssh 10.0.0.8
Verification code:
Password:
Last failed login: Fri Feb 7 12:11:12 CST 2020 from 10.0.0.7 on ssh:notty
There were 6 failed login attempts since the last successful login.
Last login: Fri Feb 7 12:09:47 2020 from 10.0.0.7
[root@centos8 ~]#
临时口令存放在/root/.google_authenticator中,用一次删除一个,可手动加入使用
[root@centos8 ~]#cat .google_authenticator
7YTAL4GW3TND7BICUMJGJLIFVE
" RATE_LIMIT 3 30
" WINDOW_SIZE 17
" DISALLOW_REUSE
" TOTP_AUTH
68820657
77385307
50928320
41000243
54628309
[root@centos8 ~]#
支持 ssh key 验证
[root@centos8 ~]#vim /etc/ssh/sshd_config
#在最后一行加下面内容
AuthenticationMethods publickey,keyboard-interactive
[root@centos8 ~]#vim /etc/pam.d/sshd
#注释此行
#auth substack password-auth
[root@centos8 ~]#systemctl restart sshd
#例:安装配置脚本
cat google-authenticator.sh
#安装epel
yum install -y epel-release.noarch
yum makecache
#安装google authenticator
yum install -y google-authenticator.x86_64
echo -e "\033[31mDo you want me to update your "/root/.google_authenticator"
file? (y/n) y"
echo -e "\033[31m你希望我更新你的“/root/.google_authenticator”文件吗(y/n)?\033[0m"
echo -e "\033[31mDo you want to disallow multiple uses of the same
authentication"
echo -e "\033[31mtoken? This restricts you to one login about every 30s, but it
increases"
echo -e "\033[31myour chances to notice or even prevent man-in-the-middle
attacks (y/n) y"
echo -e "\033[31m你希望禁止多次使用同一个验证令牌吗?这限制你每次登录的时间大约是30秒, 但是这
加大了发现或甚至防止中间人攻击的可能性(y/n)?\033[0m"
echo -e "\033[31mBy default, a new token is generated every 30 seconds by the
mobile app."
echo -e "\033[31mIn order to compensate for possible time-skew between the
client and the server,"
echo -e "\033[31mwe allow an extra token before and after the current time. This
allows for a"
echo -e "\033[31mtime skew of up to 30 seconds between authentication server and
client. If you"
echo -e "\033[31mexperience problems with poor time synchronization, you can
increase the window"
echo -e "\033[31mfrom its default size of 3 permitted codes (one previous code,
the current"
echo -e "\033[31mcode, the next code) to 17 permitted codes (the 8 previous
codes, the current"
echo -e "\033[31mcode, and the 8 next codes). This will permit for a time skew
of up to 4 minutes"
echo -e "\033[31mbetween client and server."
echo -e "\033[31mDo you want to do so? (y/n) y"
echo -e "\033[31m默认情况下,令牌保持30秒有效;为了补偿客户机与服务器之间可能存在的时滞,
\033[0m"
echo -e "\033[31m我们允许在当前时间前后有一个额外令牌。如果你在时间同步方面遇到了问题, 可以
增加窗口从默认的3个可通过验证码增加到17个可通过验证码,\033[0m"
echo -e "\033[31m这将允许客户机与服务器之间的时差增加到4分钟。你希望这么做吗(y/n)?\033[0m"
echo -e "\033[31mIf the computer that you are logging into isn't hardened
against brute-force"
echo -e "\033[31mlogin attempts, you can enable rate-limiting for the
authentication module."
echo -e "\033[31mBy default, this limits attackers to no more than 3 login
attempts every 30s."
echo -e "\033[31mDo you want to enable rate-limiting? (y/n) y"
echo -e "\033[31m如果你登录的那台计算机没有经过固化,以防范运用蛮力的登录企图,可以对验证模块
\033[0m"
echo -e "\033[31m启用尝试次数限制。默认情况下,这限制攻击者每30秒试图登录的次数只有3次。 你希
望启用尝试次数限制吗(y/n)?\033[0m"
echo -e "\033[32m 在App Store 搜索Google Authenticator 进行App安装 \033[0m"
google-authenticator
#/etc/pam.d/sshd文件,修改或添加下行保存
#auth required pam_google_authenticator.so
sed -i '1a\auth required pam_google_authenticator.so' /etc/pam.d/sshd
#编辑/etc/ssh/sshd_config找到下行
#ChallengeResponseAuthentication no
#更改为
#ChallengeResponseAuthentication yes
sed -i 's/.*ChallengeResponseAuthentication.*/ChallengeResponseAuthentication
yes/' /etc/ssh/sshd_config
#重启SSH服务
service sshd restart
6 时间同步服务
加密和安全当前都离不开时间的同步,否则各种网络服务可能不能正常运行
例: 时间错误导致证书应用出错
6.1 计时方式
6.1.1 古代计时方式
在远古时期,人类用来确定时间的方式是一些自然界“相对”亘古不变的周期。如:地球的公转是为一年,月球的公转是为一月,地球的自转是为一天等,最早的计时可以追溯到公元前大约2000年,古埃及人利用光线留下的影子用作计时的工具。影子拉得越长,计时越精确。古埃及人修建高耸入云的大型方尖碑,来追踪太阳的移动,随后人们又利用了沙漏、日晷、钟摆等工具,巧妙地利用一些相对固定而准确的周期来计时商朝人开发并使用了一种泄水型水钟——漏壶。后来又有用蜡烛和线香计时的北宋元祐元年(1086年),天文学家苏颂将浑仪、浑象和报时装置结合,建造一个划时代的计时工具——“水运仪象台”
14世纪时,西方国家广泛使用机械钟。在十六世纪,奥斯曼帝国的科学家达兹·艾-丁(Taqi al-Din)发明出了机械闹钟
1583年,伽利略提出了著名的等时性理论,即不论摆动幅度的大小,完成一次摆动的时间是相同的。1656年,荷兰科学家克里斯蒂安·惠更斯(Christiaan Huygens)应用他的理论,设计出了世界第一只钟摆
1868年,百达翡丽(Patek Philippe)发明了手表
6.1.2 现代计时方式
石英晶体受到电池的电力影响时,会产生规律的振动。每秒的振动次数是32768次,可以设计电路来计算振动次数,当计数到32768次时,即计时1秒。1967年,瑞士人发布了世界上首款石英表
当原子从一个相对高的“能量态”迁至低的“能量态”时,会释放出电磁波,产生共振频率。依据此原理,拉比构想出了一种全新的计时仪器——原子钟(Atomic clock)
因为原子的共振频率是固定的。如:铯原子(Caesium133)的固有频率是9192631770赫兹,约合92亿赫兹,对铯原子钟计数9192631770次,即可测量出一秒钟。很多国家(包括我国和美国NIST)的标准局,就是用铯原子钟来作为时间精度标准的。GPS系统也是用铯原子钟来计时
2008年诞生的锶(Strontium87)原子钟,固有频率为429228004229873,约合430万亿赫兹,将精度提高到了10的17次方
2013年镱元素(ytterbium)制成的原子钟问世,镱原子钟的固有频率约合518万亿赫兹,精度高达10的18次方。宇宙的年龄为138亿年。如果这台镱原子钟从宇宙诞生之初就开始计时,直到今天也不会发生1秒的误差
#例: ntpdate 一次性同步时间
[root@centos7 ~]#date -s '-1 year'
Sat May 25 16:26:13 CST 2019
[root@centos7 ~]#date
Sat May 25 16:26:14 CST 2019
[root@centos7 ~]#ping ntp.aliyun.com
PING ntp.aliyun.com (203.107.6.88) 56(84) bytes of data.
64 bytes from 203.107.6.88 (203.107.6.88): icmp_seq=1 ttl=128 time=16.6 ms
64 bytes from 203.107.6.88 (203.107.6.88): icmp_seq=2 ttl=128 time=16.8 ms
^C
--- ntp.aliyun.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 16.607/16.706/16.806/0.163 ms
[root@centos7 ~]#ntpdate ntp.aliyun.com
25 May 16:26:30 ntpdate[24545]: step time server 203.107.6.88 offset
31622399.992886 sec
[root@centos7 ~]#date
Mon May 25 16:26:34 CST 2020
[root@centos7 ~]#ntpdate time.windows.com
25 May 16:32:34 ntpdate[24565]: step time server 52.231.114.183 offset
31622399.981666 sec
[root@centos7 ~]#date
Mon May 25 16:32:39 CST 2020
#例: rdate 一次性同步时间
[root@centos7 ~]#yum -y install rdate
[root@centos7 ~]#date -s '1 year'
Tue Jan 18 21:33:13 CST 2022
[root@centos7 ~]#rdate -s -u time.nist.gov
[root@centos7 ~]#date
Mon Jan 18 21:33:22 CST 2021
6.2 时间同步服务
时间同步服务
多主机协作工作时,各个主机的时间同步很重要,时间不一致会造成很多重要应用的故障,如:加密协议,日志,集群等, 利用NTP(Network Time Protocol) 协议使网络中的各个计算机时间达到同步。目前NTP协议属于运维基础架构中必备的基本服务之一
时间同步软件实现:
ntp
chrony
ntp:
将系统时钟和世界协调时UTC同步,精度在局域网内可达0.1ms,在互联网上绝大多数的地方精度可以达到1-50ms
官网:http://www.ntp.org
chrony:
实现NTP协议的的自由软件。可使系统时钟与NTP服务器,参考时钟(例如GPS接收器)以及使用手表和键盘的手动输入进行同步。还可以作为NTPv4(RFC 5905)服务器和对等体运行,为网络中的计算机提供时间服务。设计用于在各种条件下良好运行,包括间歇性和高度拥挤的网络连接,温度变化(计算机时钟对温度敏感),以及不能连续运行或在虚拟机上运行的系统。
通过Internet同步的两台机器之间的典型精度在几毫秒之内,在LAN上,精度通常为几十微秒。利用硬件时间戳或硬件参考时钟,可实现亚微秒的精度
6.3 chrony
6.3.1 chrony介绍
chrony 的优势:
更快的同步只需要数分钟而非数小时时间,从而最大程度减少了时间和频率误差,对于并非全天24 小时运行的虚拟计算机而言非常有用
能够更好地响应时钟频率的快速变化,对于具备不稳定时钟的虚拟机或导致时钟频率发生变化的节能技术而言非常有用
在初始同步后,它不会停止时钟,以防对需要系统时间保持单调的应用程序造成影响
在应对临时非对称延迟时(例如,在大规模下载造成链接饱和时)提供了更好的稳定性
无需对服务器进行定期轮询,因此具备间歇性网络连接的系统仍然可以快速同步时钟
chrony官网:https://chrony.tuxfamily.org
chrony官方文档:https://chrony.tuxfamily.org/documentation.html
6.3.2 chrony 文件组成
包:chrony
两个主要程序:chronyd和chronyc
chronyd:后台运行的守护进程,用于调整内核中运行的系统时钟和时钟服务器同步。它确定计算机增减时间的比率,并对此进行补偿
chronyc:命令行用户工具,用于监控性能并进行多样化的配置。它可以在chronyd实例控制的计算机上工作,也可在一台不同的远程计算机上工作
服务unit 文件: /usr/lib/systemd/system/chronyd.service
监听端口: 服务端: 123/udp,客户端: 323/udp
配置文件: /etc/chrony.conf
6.3.3 配置文件chrony.conf
server #可用于时钟服务器,iburst 选项当服务器可达时,发送一个八个数据包而不是通常的一个数据
包。 包间隔通常为2秒,可加快初始同步速度
pool #该指令的语法与server 指令的语法相似,不同之处在于它用于指定NTP服务器池而不是单个
NTP服务器。池名称应解析为随时间可能会变化的多个地址
driftfile #根据实际时间计算出计算机增减时间的比率,将它记录到一个文件中,会在重启后为系统时钟作
出补偿
rtcsync #启用内核模式,系统时间每11分钟会拷贝到实时时钟(RTC)
allow / deny #指定一台主机、子网,或者网络以允许或拒绝访问本服务器
cmdallow / cmddeny #可以指定哪台主机可以通过chronyd使用控制命令
bindcmdaddress #允许chronyd监听哪个接口来接收由chronyc执行的命令
makestep # 通常chronyd将根据需求通过减慢或加速时钟,使得系统逐步纠正所有时间偏差。在某些特定
情况下,系统时钟可能会漂移过快,导致该调整过程消耗很长的时间来纠正系统时钟。该指令强制chronyd在
调整期大于某个阀值时调整系统时钟
local stratum 10 #即使server指令中时间服务器不可用,也允许将本地时间作为标准时间授时给其它
客户端
6.3.4 NTP 客户端工具
chronyc 可以运行在交互式和非交互式两种方式,支持以下子命令
help 命令可以查看更多chronyc的交互命令
accheck 检查是否对特定主机可访问当前服务器
activity 显示有多少NTP源在线/离线
sources [-v] 显示当前时间源的同步信息
sourcestats [-v]显示当前时间源的同步统计信息
add server 手动添加一台新的NTP服务器
clients 报告已访问本服务器的客户端列表
delete 手动移除NTP服务器或对等服务器
settime 手动设置守护进程时间
tracking 显示系统时间信息
[root@centos7 ~]#chronyc
chrony version 3.2
Copyright (C) 1997-2003, 2007, 2009-2017 Richard P. Curnow and others
chrony comes with ABSOLUTELY NO WARRANTY. This is free software, and
you are welcome to redistribute it under certain conditions. See the
GNU General Public License version 2 for details.
chronyc> clients
Hostname NTP Drop Int IntL Last Cmd Drop Int Last
===============================================================================
192.168.8.7 18 0 6 - 17 0 0 - -
192.168.8.6 14 0 6 - 56 0 0 - -
chronyc> activity
200 OK
1 sources online
0 sources offline
0 sources doing burst (return to online)
0 sources doing burst (return to offline)
0 sources with unknown address
chronyc> sources -v
210 Number of sources = 1
.-- Source mode '^' = server, '=' = peer, '#' = local clock.
/ .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| / '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
|| .- xxxx [ yyyy ] +/- zzzz
|| Reachability register (octal) -. | xxxx = adjusted offset,
|| Log2(Polling interval) --. | | yyyy = measured offset,
|| \ | | zzzz = estimated error.
|| | | \
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^? 192.168.8.100 3 8 1 338 -40ms[ -40ms]
+/- 237ms
#例: CentOS6 ntp客户端同步检查
[root@centos6 ~]#ntpq -p
remote refid st t when poll reach delay offset jitter
==============================================================================
*10.0.0.8 202.112.29.82 3 u 16 64 1 0.424 1.956 1.771
6.3.5 公共NTP服务
pool.ntp.org:项目是一个提供可靠易用的NTP服务的虚拟集群cn.pool.ntp.org,0-
3.cn.pool.ntp.org
阿里云公共NTP服务器
Unix/linux类:ntp.aliyun.com,ntp1-7.aliyun.com
windows类: time.pool.aliyun.com
腾讯公共NTP
time1-5.cloud.tencent.com
大学ntp服务
s1a.time.edu.cn 北京邮电大学
s1b.time.edu.cn 清华大学
s1c.time.edu.cn 北京大学
国家授时中心服务器:210.72.145.44
美国标准技术院: time.nist.gov
6.3.6 时间工具
#timedatectl 时间和时区管理
#查看日期时间、时区及NTP状态:
timedatectl
#查看时区列表:
timedatectl list-timezones
#修改时区:
timedatectl set-timezone Asia/Shanghai
#修改时区
root@ubuntu2004:~# rm -f /etc/localtime
root@ubuntu2004:~# ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
#修改日期时间:
timedatectl set-time "2017-01-23 10:30:00"
#开启NTP:
timedatectl set-ntp true/false
ntpdate 时间同步命令,CentOS8版本此命令已淘汰
system-config-date:图形化配置chrony服务的工具
6.3.7例: 实现私有的时间服务器
#服务器端配置
[root@centos8 ~]#hostname -I
10.0.0.8
[root@centos8 ~]#yum -y install chrony
[root@centos8 ~]#vim /etc/chrony.conf
server ntp.aliyun.com iburst
server ntp1.aliyun.com iburst
server ntp2.aliyun.com iburst
#allow 192.168.0.0/16
allow 0.0.0.0/0 #加此行,指定允许同步的网段
# Serve time even if not synchronized to a time source.
local stratum 10 #删除此行注释,当互联网无法连接,仍然可以为客户端提供时间同步服务
[root@centos8 ~]#systemctl restart chronyd
#服务启动后会打开端口123/udp
[root@centos8 ~]#ss -ntlu
Netid State Recv-Q Send-Q
Local Address:Port Peer Address:Port
udp UNCONN 0 0
0.0.0.0:123 0.0.0.0:*
udp UNCONN 0 0
127.0.0.1:323 0.0.0.0:*
udp UNCONN 0 0
[::1]:323 [::]:*
tcp LISTEN 0 128
0.0.0.0:22 0.0.0.0:*
tcp LISTEN 0 100
127.0.0.1:25 0.0.0.0:*
tcp LISTEN 0 128
[::]:22 [::]:*
tcp LISTEN 0 100
[::1]:25 [::]:*
#客户端配置
[root@centos7 ~]#vim /etc/chrony.conf
server 10.0.0.8 iburst
[root@centos7 ~]#systemctl restart chronyd.service
#确认同步成功
[root@centos7 ~]#chronyc sources -v
210 Number of sources = 1
.-- Source mode '^' = server, '=' = peer, '#' = local clock.
/ .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| / '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
|| .- xxxx [ yyyy ] +/- zzzz
|| Reachability register (octal) -. | xxxx = adjusted offset,
|| Log2(Polling interval) --. | | yyyy = measured offset,
|| \ | | zzzz = estimated error.
|| | | \
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^* 10.0.0.8 3 6 77 29 -229us[-1154us] +/- 17ms