goocsp/cmd/cacertocsp/main.go

260 lines
6.5 KiB
Go

/*
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"
"code.cacert.org/cacert/goocsp/pkg/crlcertdb"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/file"
"github.com/sirupsen/logrus"
"code.cacert.org/cacert/goocsp/pkg/opensslcertdb"
"code.cacert.org/cacert/goocsp/pkg/ocsp"
"code.cacert.org/cacert/goocsp/pkg/ocspsource"
)
/* constants for configuration keys */
const (
coIssuers = "issuers"
issuerCaCert = "caCertificate"
issuerReCert = "responderCertificate"
issuerReKey = "responderKey"
issuerDbType = "dbType"
issuerDbFile = "dbFile"
)
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)
ctx, cancel := context.WithCancel(context.Background())
opts = configureIssuers(ctx, 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))
defer cancel()
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")
}
}
var ErrUnknownDBType = errors.New("unknown certificate db type")
const (
dbTypeCRL = "crl"
dbTypeOpenSSL = "openssl"
)
func configureIssuers(ctx context.Context, issuerConfigs []*koanf.Koanf, opts []ocspsource.Option) []ocspsource.Option {
for number, issuerConfig := range issuerConfigs {
hasErrors := false
for _, item := range []string{issuerCaCert, issuerReCert, issuerReKey, issuerDbType, issuerDbFile} {
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
}
var certDb ocspsource.CertificateDatabase
switch issuerConfig.String(issuerDbType) {
case dbTypeOpenSSL:
certDb, err = opensslcertdb.NewCertDB(ctx, issuerConfig.String(issuerDbFile))
case dbTypeCRL:
certDb, err = crlcertdb.NewCertDB(ctx, issuerConfig.String(issuerDbFile))
default:
err = ErrUnknownDBType
}
if err != nil {
logrus.Errorf("could not create certificate db %d: %v", number, err)
continue
}
issuer := ocspsource.NewIssuer(
caCertificate,
responderCertificate,
responderKey,
certDb,
)
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)
}
}