diff options
author | Steve Manuel <nilslice@gmail.com> | 2016-10-21 12:46:51 -0700 |
---|---|---|
committer | Steve Manuel <nilslice@gmail.com> | 2016-10-21 12:46:51 -0700 |
commit | 5774f56b2ba029b0401a6c1b3956d9f1b6017356 (patch) | |
tree | 3b733cc067a0d7f8c69f654622c1a158952f8971 /system/tls | |
parent | aa97af279e0ad3fdda3e2ee7cf22e90d63b268c4 (diff) |
adding initial support for TLS encryption via Lets Encrypt
Diffstat (limited to 'system/tls')
-rw-r--r-- | system/tls/init.go | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/system/tls/init.go b/system/tls/init.go new file mode 100644 index 0000000..557f072 --- /dev/null +++ b/system/tls/init.go @@ -0,0 +1,63 @@ +package tls + +import ( + "crypto/tls" + "log" + "net/http" + "os" + "path/filepath" + "time" + + "github.com/bosssauce/ponzu/system/db" + + "golang.org/x/crypto/acme/autocert" +) + +var m autocert.Manager + +// setup attempts to locate or create the cert cache directory and the certs for TLS encryption +func setup() { + pwd, err := os.Getwd() + if err != nil { + log.Fatalln("Couldn't find working directory to locate or save certs.") + } + + cache := autocert.DirCache(filepath.Join(pwd, "system", "tls", "certs")) + if _, err := os.Stat(string(cache)); os.IsNotExist(err) { + err := os.MkdirAll(string(cache), os.ModePerm|os.ModeDir) + if err != nil { + log.Fatalln("Couldn't create cert directory at", cache) + } + } + + host, err := db.Config("domain") + if err != nil { + log.Fatalln("No 'domain' field set in Configuration. Please add a domain before attempting to make certificates.") + } + + email, err := db.Config("admin_email") + if err != nil { + log.Fatalln("No 'admin_email' field set in Configuration. Please add an admin email before attempting to make certificates.") + } + + m = autocert.Manager{ + Prompt: autocert.AcceptTOS, + Cache: cache, + HostPolicy: autocert.HostWhitelist(string(host)), + RenewBefore: time.Hour * 24 * 30, + Email: string(email), + } + +} + +// Enable runs the setup for creating or locating certificates and starts the TLS server +func Enable() { + setup() + + server := &http.Server{ + Addr: ":https", + TLSConfig: &tls.Config{GetCertificate: m.GetCertificate}, + } + + go server.ListenAndServeTLS("", "") +} |