-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsave.go
More file actions
75 lines (69 loc) · 1.75 KB
/
save.go
File metadata and controls
75 lines (69 loc) · 1.75 KB
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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strings"
"time"
auth "github.com/abbot/go-http-auth"
)
// GET /save/
func saveRules(w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
err := os.MkdirAll("/etc/iptables/", 0755)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
stdout, err := exec.Command("iptables-save").Output()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
err = ioutil.WriteFile("/etc/iptables/rules.v4", stdout, 0644)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
err = os.MkdirAll(*savePath, 0755)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
currentTime := time.Now().Local()
dstFile := []string{*savePath, "rules.v4.", currentTime.Format("2006-01-02"), ".", currentTime.Format("15-04-05")}
cmd := exec.Command("cp", "/etc/iptables/rules.v4", strings.Join(dstFile, ""))
err = cmd.Run()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fmt.Fprintln(w, strings.Join(dstFile, ""))
}
// GET /restore/{file}
func restoreRules(w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
err := exec.Command("iptables-restore", r.URL.Query().Get("file")).Run()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}