-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenew.go
267 lines (234 loc) · 6.78 KB
/
renew.go
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strconv"
"time"
)
// It uses the acme.sh tool to automatically renew certificates for a domain
// and publishes the certificate files through an HTTP API to the APISIX control console.
// Step 1: Install acme.sh if not present
func InstallAcmeSh(acme string) {
if !checkAcmeShPresence(acme) &&
downloadAndInstall(acme) {
return
}
}
func checkAcmeShPresence(acme string) bool {
// Define the command to check if acme.sh is installed
fmt.Println(acme, "-v")
cmd := exec.Command("sh", "-c", acme+" -v")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Run the command
if err := cmd.Run(); err != nil {
// acme.sh is not installed or not found in PATH
fmt.Println("acme.sh is not installed or not found in PATH:", err)
return false
}
// acme.sh is installed
fmt.Println("acme.sh is installed")
return true
}
func downloadAndInstall(acme string) bool {
// Define the command to download and install acme.sh
cmd := exec.Command("curl", "https://get.acme.sh", "-o", "./install-acme.sh")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Run the command
err := cmd.Run()
if err != nil {
// Error occurred during download and installation
fmt.Println("Error downloading and installing acme.sh:", err)
return false
}
cmd = exec.Command("bash", "./install-acme.sh")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
// Error occurred during download and installation
fmt.Println("Error downloading and installing acme.sh:", err)
return false
}
// Print the output of the command (optional)
return true
}
// step 2: renew certificate
func RenewCert(acme, certPath, api_host, token, domain string, force, debug bool) bool {
// Define the command to renew the certificate using acme.sh
script := acme + " --issue -d \"" + domain + "\" --dns dns_cf "
if certPath != "" {
script = script + " -w \"" + certPath + "\""
}
if debug {
script = script + " --staging --debug"
}
if force {
script = script + " --force"
}
print(script)
cmd := exec.Command("sh", "-c", script)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Run the command
err := cmd.Run()
if err != nil {
// Error occurred during certificate renewal
fmt.Println("Error renewing certificate:", err)
return false
}
// Print the output of the command (optional)
return true
}
type SSLListContent struct {
Value struct {
ID string `json:"id"`
SNIs []string `json:"snis"`
Certificate string `json:"cert"`
Key string `json:"key"`
ValidityStart int64 `json:"validity_start"`
ValidityEnd int64 `json:"validity_end"`
} `json:"value"`
}
type SSLPostContent struct {
SNIs []string `json:"snis"`
Certificate string `json:"cert"`
Key string `json:"key"`
ValidityStart int64 `json:"validity_start,omitempty"`
ValidityEnd int64 `json:"validity_end,omitempty"`
}
type SSLList struct {
List []SSLListContent `json:"list"`
Total int `json:"total"`
}
// step 3: publish certificate
// step 5: Check if the certificate already exists in the APISIX SSL List
// 请求APISIX SSL 接口返回数据格式如下 :
//
// {
// "total": 1,
// "list": [
// {
// "createdIndex": 383691,
// "value": {
// "snis": [
// "*.home.qianxin.me"
// ],
// "update_time": 1713594846,
// "status": 1,
// "validity_end": 1721139220,
// "validity_start": 1713363221,
// "type": "server",
// "id": "0000000000199211",
// "create_time": 1713594842,
// "cert": "xxxxxxx",
// "key": "xxxxxxx"
// },
// "modifiedIndex": 383692,
// "key": "/apisix/ssls/0000000000199211"
// }
// ]
// }
func PublishCert(certPath, api_host, token, domain string, force, debug bool) error {
// step 4: Check if the certificate files already exists in the certPath
certFile := certPath + "/" + domain + ".cer"
keyFile := certPath + "/" + domain + ".key"
_, err := os.Stat(certFile)
if err != nil {
fmt.Println("Certificate files :" + certFile + " not exists, use --force to renew")
return err
}
fmt.Println("Certificate files: " + certFile + " already exists, use --force to renew")
reqURL := api_host + "/apisix/admin/ssls"
req, err := http.NewRequest("GET", reqURL, nil)
if err != nil {
return err
}
req.Header.Set("X-API-KEY", token)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("Error sending HTTP request: %v\n", err)
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode == 200 {
fmt.Println("ok")
} else {
fmt.Println(string(body))
os.Exit(1)
}
var sslList SSLList
err = json.Unmarshal(body, &sslList)
if err != nil {
return err
}
fmt.Println(sslList.List[0].Value.SNIs)
updateId := ""
for i := 0; i < len(sslList.List); i++ {
if domain == sslList.List[i].Value.SNIs[0] {
fmt.Println(sslList.List[i].Value.SNIs)
updateId = sslList.List[i].Value.ID
break
}
fmt.Println(sslList.List[i].Value.SNIs)
}
certContent := new(SSLPostContent)
certContent.SNIs = []string{domain}
certContent.Certificate = readFile(certFile)
certContent.Key = readFile(keyFile)
certContent.ValidityStart = getValidityTimestamp(certFile, "startdate")
certContent.ValidityEnd = getValidityTimestamp(certFile, "enddate")
if updateId == "" && force {
updateId = "199200" + strconv.FormatInt(time.Now().Unix(), 10)
}
UpdateSSLData(updateId, api_host, token, certContent)
return nil
}
func UpdateSSLData(id, api_host, token string, certContent *SSLPostContent) error {
if id == "" {
return errors.New("id cannot be empty")
}
reqURL := api_host + "/apisix/admin/ssls" + "/" + id
fmt.Println(reqURL)
// Convert SSL content struct to JSON
certJSON, err := json.Marshal(certContent)
fmt.Println(string(certJSON))
if err != nil {
fmt.Println("Error marshalling JSON:", err)
return err
}
// POST request to create SSL certificate on APISIX
reqBody := bytes.NewBuffer(certJSON)
req, err := http.NewRequest("PUT", reqURL, reqBody)
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return err
}
req.Header.Set("X-API-KEY", token)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("Error sending HTTP request:", err)
return err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading HTTP response body:", err)
return err
}
fmt.Println(string(respBody))
return nil
}