package main import ( "bytes" "crypto/tls" "encoding/json" "fmt" "html/template" "io/ioutil" "log" "net/http" "os/exec" "strings" "time" "github.com/BurntSushi/toml" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) type signCertificate struct{} type requestData struct { Csr string `json:"csr"` CommonName string `json:"commonName"` } type responseData struct { Certificate string `json:"certificate"` } func (h *signCertificate) sign(csrPem string, commonName string) (certPem string, err error) { log.Printf("received CSR for %s:\n\n%s", commonName, csrPem) subjectDN := fmt.Sprintf("/CN=%s", commonName) err = ioutil.WriteFile("in.pem", []byte(csrPem), 0644) if err != nil { log.Print(err) return } opensslCommand := exec.Command( "openssl", "ca", "-config", "ca.cnf", "-days", "365", "-policy", "policy_match", "-extensions", "client_ext", "-batch", "-subj", subjectDN, "-utf8", "-rand_serial", "-in", "in.pem") var out, cmdErr bytes.Buffer opensslCommand.Stdout = &out opensslCommand.Stderr = &cmdErr err = opensslCommand.Run() if err != nil { log.Print(err) log.Print(cmdErr.String()) return } certPem = out.String() return } func (h *signCertificate) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "Only POST requests support", http.StatusMethodNotAllowed) return } if r.Header.Get("content-type") != "application/json" { http.Error(w, "Only JSON content is accepted", http.StatusNotAcceptable) return } var err error var requestBody requestData var certificate string if err = json.NewDecoder(r.Body).Decode(&requestBody); err != nil { log.Print(err) http.Error(w, err.Error(), http.StatusBadRequest) return } certificate, err = h.sign(requestBody.Csr, requestBody.CommonName) if err != nil { http.Error(w, "Could not sign certificate", http.StatusInternalServerError) return } var jsonBytes []byte if jsonBytes, err = json.Marshal(&responseData{Certificate: certificate}); err != nil { log.Print(err) } if _, err = w.Write(jsonBytes); err != nil { log.Print(err) } } type indexHandler struct { Bundle *i18n.Bundle } func (i *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { localizer := i18n.NewLocalizer(i.Bundle, r.Header.Get("Accept-Language")) csrGenTitle := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "CSRGenTitle", Other: "CSR generation in browser", }}) nameLabel := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "NameLabel", Other: "Your name", }}) nameHelpText := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "NameHelpText", Other: "Please input your name as it should be added to your certificate", }}) passwordLabel := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "PasswordLabel", Other: "Password for your client certificate", }}) rsaKeySizeLegend := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "RSAKeySizeLabel", Other: "RSA Key Size", }}) rsa3072Label := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "RSA3072Label", Other: "3072 Bit", }}) rsa2048Label := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "RSA2048Label", Other: "2048 Bit (not recommended)", }}) rsa4096Label := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "RSA4096Label", Other: "4096 Bit", }}) rsaHelpText := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "RSAHelpText", Other: "An RSA key pair will be generated in your browser. Longer key" + " sizes provide better security but take longer to generate.", }}) csrButtonLabel := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "CSRButtonLabel", Other: "Generate signing request", }}) statusLoading := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "StatusLoading", Other: "Loading ...", }}) sendCSRButtonLabel := localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "SendCSRButtonLabel", Other: "Send signing request", }}) t := template.Must(template.ParseFiles("templates/index.html")) err := t.Execute(w, map[string]interface{}{ "Title": csrGenTitle, "NameLabel": nameLabel, "NameHelpText": nameHelpText, "PasswordLabel": passwordLabel, "RSAKeySizeLegend": rsaKeySizeLegend, "RSA3072Label": rsa3072Label, "RSA2048Label": rsa2048Label, "RSA4096Label": rsa4096Label, "RSAHelpText": rsaHelpText, "CSRButtonLabel": csrButtonLabel, "StatusLoading": statusLoading, "SendCSRButtonLabel": sendCSRButtonLabel, }) if err != nil { log.Panic(err) } } type jsLocalesHandler struct { Bundle *i18n.Bundle } func (j *jsLocalesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { parts := strings.Split(r.URL.Path, "/") if len(parts) != 4 { http.Error(w, "Not found", http.StatusNotFound) return } lang := parts[2] localizer := i18n.NewLocalizer(j.Bundle, lang) type translationData struct { Keygen struct { Started string `json:"started"` Running string `json:"running"` Generated string `json:"generated"` } `json:"keygen"` } translations := &translationData{} translations.Keygen.Started = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "JavaScript.KeyGen.Started", Other: "started key generation", }}) translations.Keygen.Running = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "JavaScript.KeyGen.Running", Other: "key generation running for __seconds__ seconds", }}) translations.Keygen.Generated = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ ID: "JavaScript.KeyGen.Generated", Other: "key generated in __seconds__ seconds", }}) encoder := json.NewEncoder(w) if err := encoder.Encode(translations); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func main() { tlsConfig := &tls.Config{ CipherSuites: []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, }, NextProtos: []string{"h2"}, PreferServerCipherSuites: true, MinVersion: tls.VersionTLS12, } bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) for _, lang := range []string{"en-US", "de-DE"} { if _, err := bundle.LoadMessageFile(fmt.Sprintf("active.%s.toml", lang)); err != nil { log.Panic(err) } } mux := http.NewServeMux() mux.Handle("/sign/", &signCertificate{}) mux.Handle("/", &indexHandler{Bundle: bundle}) fileServer := http.FileServer(http.Dir("./public")) mux.Handle("/css/", fileServer) mux.Handle("/js/", fileServer) mux.Handle("/locales/", &jsLocalesHandler{Bundle: bundle}) server := http.Server{ Addr: ":8000", Handler: mux, TLSConfig: tlsConfig, ReadTimeout: 20 * time.Second, ReadHeaderTimeout: 5 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 30 * time.Second, } err := server.ListenAndServeTLS("server.crt.pem", "server.key.pem") if err != nil { log.Fatal(err) } }