Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 11, 01:00 UTC
| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package caddypki |
| 16 | |
| 17 | import ( |
| 18 | "crypto" |
| 19 | "crypto/x509" |
| 20 | "time" |
| 21 | |
| 22 | "go.step.sm/crypto/keyutil" |
| 23 | "go.step.sm/crypto/x509util" |
| 24 | ) |
| 25 | |
| 26 | func generateRoot(commonName string) (*x509.Certificate, crypto.Signer, error) { |
| 27 | template, signer, err := newCert(commonName, x509util.DefaultRootTemplate, defaultRootLifetime) |
| 28 | if err != nil { |
| 29 | return nil, nil, err |
| 30 | } |
| 31 | root, err := x509util.CreateCertificate(template, template, signer.Public(), signer) |
| 32 | if err != nil { |
| 33 | return nil, nil, err |
| 34 | } |
| 35 | return root, signer, nil |
| 36 | } |
| 37 | |
| 38 | func generateIntermediate(commonName string, rootCrt *x509.Certificate, rootKey crypto.Signer, lifetime time.Duration) (*x509.Certificate, crypto.Signer, error) { |
| 39 | template, signer, err := newCert(commonName, x509util.DefaultIntermediateTemplate, lifetime) |
| 40 | if err != nil { |
| 41 | return nil, nil, err |
| 42 | } |
| 43 | intermediate, err := x509util.CreateCertificate(template, rootCrt, signer.Public(), rootKey) |
| 44 | if err != nil { |
| 45 | return nil, nil, err |
| 46 | } |
| 47 | return intermediate, signer, nil |
| 48 | } |
| 49 | |
| 50 | func newCert(commonName, templateName string, lifetime time.Duration) (cert *x509.Certificate, signer crypto.Signer, err error) { |
| 51 | signer, err = keyutil.GenerateDefaultSigner() |
| 52 | if err != nil { |
| 53 | return nil, nil, err |
| 54 | } |
| 55 | csr, err := x509util.CreateCertificateRequest(commonName, []string{}, signer) |
| 56 | if err != nil { |
| 57 | return nil, nil, err |
| 58 | } |
| 59 | template, err := x509util.NewCertificate(csr, x509util.WithTemplate(templateName, x509util.CreateTemplateData(commonName, []string{}))) |
| 60 | if err != nil { |
| 61 | return nil, nil, err |
| 62 | } |
| 63 | |
| 64 | cert = template.GetCertificate() |
| 65 | cert.NotBefore = time.Now().Truncate(time.Second) |
| 66 | cert.NotAfter = cert.NotBefore.Add(lifetime) |
| 67 | return cert, signer, nil |
| 68 | } |