2 tofuproxy -- HTTP proxy with TLS certificates management
3 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
36 cn := flag.String("cn", "tofuproxy.localhost", "CommonName")
37 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
38 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
40 log.SetFlags(log.Lshortfile)
42 prv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
47 notBefore := time.Now()
48 notAfter := notBefore.Add(365 * 24 * time.Hour)
50 serialRaw := make([]byte, 16)
51 if _, err = io.ReadFull(rand.Reader, serialRaw); err != nil {
54 serial := big.NewInt(0)
55 serial = serial.SetBytes(serialRaw)
57 template := x509.Certificate{
59 Subject: pkix.Name{CommonName: *cn},
60 DNSNames: []string{*cn},
63 BasicConstraintsValid: true,
66 certRaw, err := x509.CreateCertificate(
67 rand.Reader, &template, &template, pub, prv,
72 if _, err = x509.ParseCertificate(certRaw); err != nil {
75 pkcs8, err := x509.MarshalPKCS8PrivateKey(prv)
80 fd, err := os.OpenFile(*prvPath, os.O_WRONLY|os.O_CREATE, 0600)
84 err = pem.Encode(fd, &pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8})
90 fd, err = os.OpenFile(*crtPath, os.O_WRONLY|os.O_CREATE, 0600)
91 err = pem.Encode(fd, &pem.Block{Type: "CERTIFICATE", Bytes: certRaw})