/* Copyright 2022 CAcert Inc. SPDX-License-Identifier: Apache-2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "crypto" "crypto/x509" "encoding/pem" "errors" "flag" "fmt" "io/ioutil" "net/http" "os" "os/signal" "syscall" "time" "github.com/cloudflare/cfssl/ocsp" "github.com/knadh/koanf" "github.com/knadh/koanf/parsers/yaml" "github.com/knadh/koanf/providers/file" "github.com/sirupsen/logrus" "git.cacert.org/cacert-goocsp/pkg/ocspsource" ) /* constants for configuration keys */ const ( coIssuers = "issuers" issuerCaCert = "caCertificate" issuerReCert = "responderCertificate" issuerReKey = "responderKey" issuerCertList = "certificateList" ) func main() { var ( serverAddr = flag.String("serverAddr", ":8080", "Server ip addr and port") config = koanf.New(".") opts []ocspsource.Option ) err := config.Load(file.Provider("config.yaml"), yaml.Parser()) if err != nil { logrus.Panicf("could not load configuration: %v", err) } logrus.SetLevel(logrus.DebugLevel) issuerConfigs := config.Slices(coIssuers) opts = configureIssuers(issuerConfigs, opts) cacertSource, err := ocspsource.NewSource(opts...) if err != nil { logrus.Panicf("could not create OCSP source: %v", err) } http.Handle("/", withLogging(ocsp.NewResponder(cacertSource, nil).ServeHTTP)) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { cacertSource.BackgroundTasks(ctx) }() server := &http.Server{ Addr: *serverAddr, } setupCloseHandler(ctx, server) if err := server.ListenAndServe(); err != nil { if !errors.Is(err, http.ErrServerClosed) { logrus.Panicf("could not start the server process: %v", err) } logrus.Infof("server shutdown") } } func configureIssuers(issuerConfigs []*koanf.Koanf, opts []ocspsource.Option) []ocspsource.Option { for number, issuerConfig := range issuerConfigs { hasErrors := false for _, item := range []string{issuerCaCert, issuerReCert, issuerReKey, issuerCertList} { if v := issuerConfig.String(item); v == "" { logrus.Warnf("%s parameter for issuers entry %d is missing", item, number) hasErrors = true } } if hasErrors { logrus.Warnf("configuration for issuers entry %d had errors and has been skipped", number) continue } caCertificate, err := parseCertificate(issuerConfig.String(issuerCaCert)) if err != nil { logrus.Errorf("could not parse CA certificate for issuer %d: %v", number, err) continue } responderCertificate, err := parseCertificate(issuerConfig.String(issuerReCert)) if err != nil { logrus.Errorf("could not parse OCSP responder certificate for issuer %d: %v", number, err) continue } responderKey, err := parsePrivateKey(issuerConfig.String(issuerReKey)) if err != nil { logrus.Errorf("could not parse OCSP responder key for issuer %d: %v", number, err) continue } issuer, err := ocspsource.NewIssuer( caCertificate, responderCertificate, responderKey, issuerConfig.String(issuerCertList), ) if err != nil { logrus.Errorf("could not create issuer %d: %v", number, err) continue } opts = append(opts, ocspsource.WithIssuer(issuer)) } return opts } // The setupCloseHandler takes care of OS signal handling func setupCloseHandler(ctx context.Context, server *http.Server) { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func(ctx context.Context) { <-c logrus.Infof("program interrupted") err := server.Shutdown(ctx) if err != nil { logrus.Errorf("could not close server: %v", err) } }(ctx) } // The withLogging provides middleware to log incoming requests func withLogging(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now() next.ServeHTTP(w, r) logrus.Infof("GET %s FROM %s in %dms", r.URL.Path, r.RemoteAddr, time.Since(start).Milliseconds()) } } // parseCertificate is a helper to parse X.509 certificates from files func parseCertificate(certificateFile string) (*x509.Certificate, error) { pemData, err := ioutil.ReadFile(certificateFile) if err != nil { return nil, fmt.Errorf("could not read PEM data from %s: %w", certificateFile, err) } block, _ := pem.Decode(pemData) if block == nil { return nil, fmt.Errorf("could not find PEM data in %s", certificateFile) } certificate, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, fmt.Errorf("could not parse certificate in %s: %w", certificateFile, err) } return certificate, nil } // parsePrivateKey is a helper to parse PKCS#1 or PKCS#8 private keys from files func parsePrivateKey(keyFile string) (crypto.Signer, error) { pemData, err := ioutil.ReadFile(keyFile) if err != nil { return nil, fmt.Errorf("could not read PEM data from %s: %w", keyFile, err) } block, _ := pem.Decode(pemData) if block == nil { return nil, fmt.Errorf("could not find PEM data in %s", keyFile) } switch block.Type { case "PRIVATE KEY": key, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("no usable private key found in %s: %w", keyFile, err) } signer, ok := key.(crypto.Signer) if !ok { return nil, errors.New("key cannot be used as signer") } return signer, nil case "RSA PRIVATE KEY": rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("no usable private key found in %s: %w", keyFile, err) } return rsaKey, nil default: return nil, fmt.Errorf("unsupported PEM block type %s in %s", block.Type, keyFile) } }