-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
333 lines (273 loc) · 7.7 KB
/
main.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"path"
"strings"
"time"
)
var (
SavePath = "data"
Addrss = "0.0.0.0"
Port = 8080
Token = ""
Cert = ""
Key = ""
Secret = ""
)
type BackupEntry struct {
Id string `json:"id"`
Tag string `json:"tag"`
Files map[string]string `json:"files"`
}
type DeployEntry struct {
ConfigPath string `json:"configPath"`
ServiceName string `json:"serviceName"`
Content string `json:"content"`
Timeout int `json:"timeout"`
}
func main() {
flag.StringVar(&Token, "token", "", "Authorization")
flag.StringVar(&Addrss, "address", "0.0.0.0", "Address to listen on")
flag.StringVar(&Cert, "cert", "", "Cert file path")
flag.StringVar(&Key, "key", "", "Key file path")
flag.StringVar(&Secret, "secret", "", "Secret")
flag.IntVar(&Port, "port", 8080, "Port to listen on")
flag.Parse()
if Token == "" {
fmt.Println("You need to specify a token that is the same as the client")
return
}
os.MkdirAll(SavePath, os.ModePerm)
http.HandleFunc("/backup", withAuth(handleBackup))
http.HandleFunc("/sync", withAuth(handleSync))
http.HandleFunc("/deploy", withAuth(handleDeploy))
var err error
if Cert != "" && Key != "" {
err = http.ListenAndServeTLS(fmt.Sprintf("%s:%d", Addrss, Port), Cert, Key, nil)
} else {
err = http.ListenAndServe(fmt.Sprintf("%s:%d", Addrss, Port), nil)
}
if err != nil {
log.Print(err.Error())
}
}
func withAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
uaHeader := r.Header.Get("User-Agent")
if uaHeader != "GUI.for.Cores" || authHeader != "Bearer "+Token {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next(w, r)
}
}
func handleBackup(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
tag := r.URL.Query().Get("tag")
p := path.Join(SavePath, tag)
log.Printf("List => where tag = %s\n", tag)
if !strings.HasPrefix(path.Clean(p), SavePath) {
http.Error(w, "403", http.StatusForbidden)
return
}
dirs, err := os.ReadDir(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
result := make([]string, 0)
for _, file := range dirs {
if !file.IsDir() {
result = append(result, file.Name())
}
}
response, err := json.Marshal(result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(response)
case http.MethodDelete:
tag := r.URL.Query().Get("tag")
ids := r.URL.Query().Get("ids")
p := path.Join(SavePath, tag)
idsToDelete := strings.Split(ids, ",")
log.Printf("Remove => where tag = %s and id in %s\n", tag, ids)
if !strings.HasPrefix(path.Clean(p), SavePath) {
http.Error(w, "403", http.StatusForbidden)
return
}
for _, id := range idsToDelete {
os.RemoveAll(path.Join(p, id))
}
w.WriteHeader(http.StatusOK)
case http.MethodPost:
var body BackupEntry
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
p := path.Join(SavePath, body.Tag, body.Id)
log.Printf("Backup : id = %s, tag = %s, files.length = %v\n", body.Id, body.Tag, len(body.Files))
if !strings.HasPrefix(path.Clean(p), SavePath) {
http.Error(w, "403", http.StatusForbidden)
return
}
b, err := json.Marshal(body)
if err != nil {
log.Printf("Backup err %v", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
os.MkdirAll(path.Join(SavePath, body.Tag), os.ModePerm)
os.WriteFile(p+".json", b, 0644)
w.WriteHeader(http.StatusCreated)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func handleSync(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
tag := r.URL.Query().Get("tag")
id := r.URL.Query().Get("id")
p := path.Join(SavePath, tag, id)
if !strings.HasPrefix(p, SavePath) {
http.Error(w, "403", http.StatusForbidden)
return
}
b, err := os.ReadFile(p)
if err != nil {
http.Error(w, "403", http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func handleDeploy(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
var body DeployEntry
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
configPath := body.ConfigPath
serviceName := body.ServiceName
content := body.Content
timeout := body.Timeout
log.Printf("Deploy : configPath = %s, serviceName = %s\n", configPath, serviceName)
if Secret == "" {
http.Error(w, "The secret parameter is missing on the server side", http.StatusInternalServerError)
return
}
config, err := AesDecrypt(content, Secret)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
backup, backupError := os.ReadFile(configPath)
os.WriteFile(configPath, config, 0644)
exec.Command("systemctl", "restart", serviceName).Run()
isTimeout := false
for {
time.Sleep(1 * time.Second)
output, _ := exec.Command("systemctl", "is-active", serviceName).CombinedOutput()
if strings.TrimSpace(string(output)) == "active" {
break
}
timeout--
if timeout < 0 {
isTimeout = true
break
}
}
if isTimeout && backupError == nil {
os.WriteFile(body.ConfigPath, backup, 0644)
exec.Command("systemctl", "restart", body.ServiceName).Run()
http.Error(w, "Restarting the service failed and has been restored", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func EvpBytesToKey(password []byte, salt []byte, keyLen, ivLen int) ([]byte, []byte) {
var result []byte
hash := md5.New()
var prev []byte
totalLen := keyLen + ivLen
for len(result) < totalLen {
hash.Reset()
hash.Write(prev)
hash.Write(password)
hash.Write(salt)
prev = hash.Sum(nil)
result = append(result, prev...)
}
return result[:keyLen], result[keyLen:totalLen]
}
func pkcs7Unpad(data []byte) ([]byte, error) {
if len(data) == 0 {
return nil, errors.New("pkcs7: data is empty")
}
padLength := int(data[len(data)-1])
if padLength > len(data) {
return nil, errors.New("pkcs7: invalid padding")
}
for i := 0; i < padLength; i++ {
if data[len(data)-1-i] != byte(padLength) {
return nil, errors.New("pkcs7: invalid padding")
}
}
return data[:len(data)-padLength], nil
}
func AesDecrypt(ciphertextBase64 string, passphrase string) ([]byte, error) {
ciphertext, err := base64.StdEncoding.DecodeString(ciphertextBase64)
if err != nil {
return nil, err
}
if len(ciphertext) < 16 || string(ciphertext[:8]) != "Salted__" {
return nil, errors.New("the ciphertext format is incorrect and salted__overseas is missing")
}
salt := ciphertext[8:16]
encryptedData := ciphertext[16:]
password := []byte(passphrase)
key, iv := EvpBytesToKey(password, salt, 32, 16)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(encryptedData)%aes.BlockSize != 0 {
return nil, errors.New("the ciphertext length is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(encryptedData, encryptedData)
unpadded, err := pkcs7Unpad(encryptedData)
if err != nil {
return nil, err
}
return unpadded, nil
}