This repository was archived by the owner on Mar 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
80 lines (74 loc) · 1.98 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
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/levenlabs/locksmith/cfssl"
"github.com/levenlabs/locksmith/config"
"github.com/levenlabs/locksmith/ovpn"
"io/ioutil"
"log"
"net/http"
)
type OVPNContents struct {
CA []byte
}
func main() {
log.Printf("Listening on %s", config.InternalAPIAddr)
http.HandleFunc("/generate", generateHandler)
log.Fatal(http.ListenAndServe(config.InternalAPIAddr, nil))
}
func generateHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s %s", r.Method, r.RemoteAddr, r.RequestURI)
if r.Method != "POST" {
http.Error(w, "Invalid HTTP Method", http.StatusMethodNotAllowed)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil || len(body) == 0 {
http.Error(w, "Invalid POST Body", http.StatusBadRequest)
return
}
if len(config.HMACKey) > 0 {
sig := r.URL.Query().Get("sig")
if sig == "" {
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
rawSig, err := hex.DecodeString(sig)
if err != nil {
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
if !verifyHMAC(body, rawSig) {
http.Error(w, "Invalid HMAC Sig", http.StatusBadRequest)
return
}
}
var c cfssl.GenerateRequest
err = json.Unmarshal(body, &c)
if err != nil {
http.Error(w, "Invalid POST Body", http.StatusBadRequest)
return
}
cert, key, err := cfssl.GenerateCert(&c, r.RemoteAddr)
if err != nil {
log.Printf("cfssl.GenerateCert(%#v) -> %s", c, err)
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
err = ovpn.CreateWrite(w, cert, key)
if err != nil {
log.Printf("ovpn.CreateWrite -> %s", err)
http.Error(w, "Error creating ovpn file", http.StatusInternalServerError)
return
}
log.Printf("Generated: %s %s", c.Hostname, r.RemoteAddr)
}
func verifyHMAC(body []byte, sentMac []byte) bool {
mac := hmac.New(sha256.New, config.HMACKey)
mac.Write(body)
expectedMAC := mac.Sum(nil)
return hmac.Equal(sentMac, expectedMAC)
}