Gin SSL 失效时间全量检测

随着业务越来越多,我们的 DNS 解析的记录是特别多的,而且从安全方面考虑,业务是全量 HTTPS 的,但会带来一个问题,就是有时候我们无法及时了解到 SSL 已过期,可能会照成业务直接无法访问的重大故障。

而能完成 SSL 过期检测,恰好需要依赖于 DNS 服务商提供的 API 接口,供我们查询某域名解析的全部记录,这里以阿里云为例。

第一步,我们要先拿到需要处理的记录。

1
$ go get github.com/alibabacloud-go/alidns-20150109/v2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main

import (
"crypto/tls"
"errors"
"fmt"
alidns20150109 "github.com/alibabacloud-go/alidns-20150109/v2/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/client"
"github.com/alibabacloud-go/tea/tea"
"github.com/gin-gonic/gin"
"net/http"
"strings"
"sync/atomic"
"time"
)

const (
AliyunAccessKeyId = "xx"
AliyunAccessKeySecret = "xx"
Domain = "hongfs.cn" // 域名
)

func main() {
r := gin.Default()

r.GET("/ssl", SSLHandle)

r.Run("127.0.0.1:9000")
}

func SSLHandle(c *gin.Context) {
dns, err := alidns20150109.NewClient(&openapi.Config{
AccessKeyId: tea.String(AliyunAccessKeyId),
AccessKeySecret: tea.String(AliyunAccessKeySecret),
Endpoint: tea.String("dns.aliyuncs.com"),
})

if err != nil {
c.String(http.StatusOK, "DNS 实例化失败:"+err.Error())

return
}

list, err := dnsRecords(dns)

if err != nil {
c.String(http.StatusOK, "DNS 记录获取失败:"+err.Error())

return
}

c.JSON(http.StatusOK, gin.H{
"list": list,
})
}

// dnsRecords 获取 DNS 记录
func dnsRecords(client *alidns20150109.Client) (data []string, err error) {
var tmp []*alidns20150109.DescribeDomainRecordsResponseBodyDomainRecordsRecord

// 页数
var page int64 = 1

// 页大小,500 是最大,减少请求
var size int64 = 500

for {
// 循环获取全部记录
list, err := client.DescribeDomainRecords(&alidns20150109.DescribeDomainRecordsRequest{
DomainName: tea.String(Domain),
PageNumber: tea.Int64(page),
PageSize: tea.Int64(size),
Status: tea.String("Enable"), // 启用状态
})

if err != nil {
return data, err
}

tmp = append(tmp, list.Body.DomainRecords.Record...)

if len(list.Body.DomainRecords.Record) != int(size) {
break
}

atomic.AddInt64(&page, 1)
}

// 筛选掉不需要处理的
for _, item := range tmp {
// 只保留类型是 A AAAA CNAME 的
if *item.Type != "A" &&
*item.Type != "AAAA" &&
*item.Type != "CNAME" {
continue
}

// RDS 的不需要 SSL
// 可能还有其他云产品也是不需要的,可以按需处理
if strings.HasSuffix(*item.Value, ".rds.aliyuncs.com") {
continue
}

// 拼接完成的记录值,主机名+域名
value := *item.DomainName

if *item.RR != "@" {
value = *item.RR + "." + value
}

data = append(data, value)
}

return
}

好的,我们已经筛选出需要处理的域名了。

接下来我们要检测已有的 SSL 还剩下多少时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// getSSLExpiredTime 获取 SSL 过期时间
func getSSLExpiredTime(domain string) (time.Time, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}

client := &http.Client{
Transport: tr,
CheckRedirect: func(req *http.Request, via []*http.Request) error { // 禁止重定向跳转
return http.ErrUseLastResponse
},
Timeout: 60 * time.Second, // 超时一分钟
}

resp, err := client.Get(fmt.Sprintf("https://%s", domain))

if err != nil {
return time.Time{}, err
}

defer resp.Body.Close()

if len(resp.TLS.PeerCertificates) == 0 {
return time.Time{}, errors.New("SSL 获取失败")
}

// 获取证书信息
cert := resp.TLS.PeerCertificates[0]

return cert.NotAfter, nil
}

已经实现了我们的获取函数,那接下来要循环 DNS 记录来看一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func SSLHandle(c *gin.Context) {
...

var result []string

for _, item := range list {
value, err := getSSLExpiredTime(item)

if err != nil {
result = append(result, fmt.Sprintf("%s 获取失败:%s", item, err.Error()))

continue
}

if value.Sub(time.Now()).Seconds() < 0.0 {
result = append(result, fmt.Sprintf("%s 已过期", item))

continue
}

// 计算剩余天数
surplus := value.Sub(time.Now()).Hours() / 24

result = append(result, fmt.Sprintf("%s 剩余:%1.0f天", item, surplus))
}

c.JSON(http.StatusOK, gin.H{
"list": result,
})
}

好的,到这来我们就已经完成了全部记录的检测。

但是,在实际检测中,发现了 ilovehuaweicloud.hongfs.cn 是没有开启 HTTPS 的,但为什么还会访问一个时间呢?

这个是浏览器访问的提示,所以找到了 PeerCertificates 里面有个参数是用来存储符合域名的,那就再加一步验证下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func getSSLExpiredTime(domain string) (time.Time, error) {
...

// 证书信息
cert := resp.TLS.PeerCertificates[0]

// 循环 SSL 支持的域名(包括通配符),下面配了个图片
for _, v := range cert.DNSNames {
if v == domain {
return cert.NotAfter, nil
} else if strings.HasPrefix(v, "*.") {
// 正则匹配通配符
if ok, _ := regexp.MatchString("^[\\w._-]{1,}."+strings.Replace(v, "*.", "", 1)+"$", domain); ok {
return cert.NotAfter, nil
}
}
}

return time.Time{}, errors.New("SSL 获取失败")
}

最终完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main

import (
"crypto/tls"
"errors"
"fmt"
alidns20150109 "github.com/alibabacloud-go/alidns-20150109/v2/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/client"
"github.com/alibabacloud-go/tea/tea"
"github.com/gin-gonic/gin"
"net/http"
"strings"
"sync/atomic"
"time"
)

const (
AliyunAccessKeyId = "xx"
AliyunAccessKeySecret = "xx"
Domain = "hongfs.cn" // 域名
)

func main() {
r := gin.Default()

r.GET("/ssl", SSLHandle)

r.Run("127.0.0.1:9000")
}

func SSLHandle(c *gin.Context) {
dns, err := alidns20150109.NewClient(&openapi.Config{
AccessKeyId: tea.String(AliyunAccessKeyId),
AccessKeySecret: tea.String(AliyunAccessKeySecret),
Endpoint: tea.String("dns.aliyuncs.com"),
})

if err != nil {
c.String(http.StatusOK, "DNS 实例化失败:"+err.Error())

return
}

list, err := dnsRecords(dns)

if err != nil {
c.String(http.StatusOK, "DNS 记录获取失败:"+err.Error())

return
}

var result []string

for _, item := range list {
value, err := getSSLExpiredTime(item)

if err != nil {
result = append(result, fmt.Sprintf("%s 获取失败:%s", item, err.Error()))

continue
}

if value.Sub(time.Now()).Seconds() < 0.0 {
result = append(result, fmt.Sprintf("%s 已过期", item))

continue
}

// 计算剩余天数
surplus := value.Sub(time.Now()).Hours() / 24

result = append(result, fmt.Sprintf("%s 剩余:%1.0f天", item, surplus))
}

c.JSON(http.StatusOK, gin.H{
"list": result,
})
}

// getSSLExpiredTime 获取 SSL 过期时间
func getSSLExpiredTime(domain string) (time.Time, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}

client := &http.Client{
Transport: tr,
CheckRedirect: func(req *http.Request, via []*http.Request) error { // 禁止重定向跳转
return http.ErrUseLastResponse
},
Timeout: 60 * time.Second, // 超时一分钟
}

resp, err := client.Get(fmt.Sprintf("https://%s", domain))

if err != nil {
return time.Time{}, err
}

defer resp.Body.Close()

if len(resp.TLS.PeerCertificates) == 0 {
return time.Time{}, errors.New("SSL 获取失败")
}

// 获取证书信息
cert := resp.TLS.PeerCertificates[0]

// 循环 SSL 支持的域名(包括通配符)
for _, v := range cert.DNSNames {
if v == domain {
return cert.NotAfter, nil
} else if strings.HasPrefix(v, "*.") {
// 正则匹配通配符
if ok, _ := regexp.MatchString("^[\\w._-]{1,}."+strings.Replace(v, "*.", "", 1)+"$", domain); ok {
return cert.NotAfter, nil
}

//if strings.Replace(v, "*.", "", 1) == domain {
// return cert.NotAfter, nil
//}
}
}

return time.Time{}, errors.New("SSL 获取失败")
}

// dnsRecords 获取 DNS 记录
func dnsRecords(client *alidns20150109.Client) (data []string, err error) {
var tmp []*alidns20150109.DescribeDomainRecordsResponseBodyDomainRecordsRecord

// 页数
var page int64 = 1

// 页大小,500 是最大,减少请求
var size int64 = 500

for {
// 循环获取全部记录
list, err := client.DescribeDomainRecords(&alidns20150109.DescribeDomainRecordsRequest{
DomainName: tea.String(Domain),
PageNumber: tea.Int64(page),
PageSize: tea.Int64(size),
Status: tea.String("Enable"), // 启用状态
})

if err != nil {
return data, err
}

tmp = append(tmp, list.Body.DomainRecords.Record...)

if len(list.Body.DomainRecords.Record) != int(size) {
break
}

atomic.AddInt64(&page, 1)
}

// 筛选掉不需要处理的
for _, item := range tmp {
// 只保留类型是 A AAAA CNAME 的
if *item.Type != "A" &&
*item.Type != "AAAA" &&
*item.Type != "CNAME" {
continue
}

// RDS 的不需要 SSL
// 可能还有其他云产品也是不需要的,可以按需处理
if strings.HasSuffix(*item.Value, ".rds.aliyuncs.com") {
continue
}

// 拼接完成的记录值,主机名+域名
value := *item.DomainName

if *item.RR != "@" {
value = *item.RR + "." + value
}

data = append(data, value)
}

return
}
往上