cacert-gosigner/cmd/signer/main.go
Jan Dittberner ad6b987c91 Implement sign certificate command
- decouple config and messages
- cainfo maps from config.Profile to messages.CAProfile
- config parses profile usage
- validity can be configured per certificate profile, defaults are defined in
  a defaultValidity method of the profile usage
- the client simulator emits certificate signing requests at random intervals
- add implementation of SingCertificateCommand to MsgPackHandler
- remove indirection signing.RequestSignature
2022-12-11 13:32:05 +01:00

277 lines
6.9 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"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/sirupsen/logrus"
"git.cacert.org/cacert-gosigner/pkg/protocol"
"git.cacert.org/cacert-gosigner/internal/config"
"git.cacert.org/cacert-gosigner/internal/handler"
"git.cacert.org/cacert-gosigner/internal/health"
"git.cacert.org/cacert-gosigner/internal/hsm"
"git.cacert.org/cacert-gosigner/internal/serial"
"git.cacert.org/cacert-gosigner/internal/x509/revoking"
"git.cacert.org/cacert-gosigner/internal/x509/signing"
)
var (
commit = "dev"
date = "unknown"
version = "unknown"
)
const (
defaultSignerConfigFile = "config.yaml"
)
func main() {
var (
showVersion, setupMode, verbose bool
signerConfigFile, logLevel string
logger *logrus.Logger
)
logger = logrus.New()
logger.SetOutput(os.Stdout)
logger.SetLevel(logrus.InfoLevel)
logger.Infof("cacert-gosigner %s (%s) - built %s", version, commit, date)
flag.StringVar(&signerConfigFile, "config", defaultSignerConfigFile, "signer configuration file")
flag.BoolVar(&showVersion, "version", false, "show version")
flag.BoolVar(&setupMode, "setup", false, "setup mode")
flag.BoolVar(&verbose, "verbose", false, "verbose output")
flag.StringVar(&logLevel, "loglevel", "INFO", "log level")
flag.Parse()
if showVersion {
return
}
parsedLevel, err := logrus.ParseLevel(logLevel)
if err != nil {
logger.WithError(err).Fatal("could not parse log level")
}
logger.SetLevel(parsedLevel)
caConfig := loadConfig(signerConfigFile, logger)
access := initializeHSM(caConfig, setupMode, verbose, logger)
if setupMode {
return
}
framer, err := protocol.NewCOBSFramer(logger)
if err != nil {
logger.WithError(err).Fatal("could not create framer")
}
healthHandler := health.New(version, access)
revokingRepositories, signingRepositories, err := configureRepositories(caConfig, logger)
if err != nil {
logger.WithError(err).Fatal("could not setup repositories")
}
fetchCRLHandler := revoking.NewFetchCRLHandler(revokingRepositories)
signX509Handler := signing.NewSignCertificateHandler(signingRepositories)
proto, err := handler.New(
logger,
handler.RegisterHealthHandler(healthHandler),
handler.RegisterFetchCRLHandler(fetchCRLHandler),
handler.RegisterCAInfoHandler(access),
handler.RegisterCertificateSigningHandler(signX509Handler),
)
if err != nil {
logger.WithError(err).Fatal("could not setup protocol handler")
}
serialHandler, err := serial.New(caConfig.GetSerial(), logger, framer, proto)
if err != nil {
logger.WithError(err).Fatal("could not setup serial link handler")
}
logger.Info("setup complete, starting signer operation")
if err = runSigner(logger, serialHandler); err != nil {
logger.WithError(err).Error("error running serial handler")
os.Exit(1)
}
}
func runSigner(logger *logrus.Logger, serialHandler *serial.Handler) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer func() { _ = serialHandler.Close() }()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
logger.Info("received shutdown signal")
cancel()
}()
if err := serialHandler.Run(ctx); err != nil {
return fmt.Errorf("error from serial handler: %w", err)
}
return nil
}
func configureRepositories(
caConfig *config.SignerConfig,
logger *logrus.Logger,
) (map[string]*revoking.X509Revoking, map[string]map[string]*signing.X509Signing, error) {
var err error
revokers := make(map[string]*revoking.X509Revoking)
signers := make(map[string]map[string]*signing.X509Signing)
for _, name := range caConfig.RootCAs() {
revokers[name], err = buildX509Revoking(caConfig, name, logger)
if err != nil {
return nil, nil, err
}
}
for _, name := range caConfig.SubordinateCAs() {
revokers[name], err = buildX509Revoking(caConfig, name, logger)
if err != nil {
return nil, nil, err
}
signers[name], err = buildX509Signing(caConfig, name, logger)
if err != nil {
return nil, nil, err
}
}
return revokers, signers, nil
}
func buildX509Revoking(
caConfig *config.SignerConfig,
name string,
logger *logrus.Logger,
) (*revoking.X509Revoking, error) {
caDef, err := caConfig.GetCADefinition(name)
if err != nil {
return nil, fmt.Errorf("could not get CA definition for %s: %w", name, err)
}
repo, err := caConfig.Repository(name)
if err != nil {
return nil, fmt.Errorf("could not get repository for %s: %w", name, err)
}
return revoking.NewX509Revoking(
repo,
caDef.KeyInfo.CRLSignatureAlgorithm,
caDef.Certificate,
caDef.KeyPair,
logger,
), nil
}
func buildX509Signing(
caConfig *config.SignerConfig,
name string,
logger *logrus.Logger,
) (map[string]*signing.X509Signing, error) {
caDef, err := caConfig.GetCADefinition(name)
if err != nil {
return nil, fmt.Errorf("could not get CA definition for %s: %w", name, err)
}
repo, err := caConfig.Repository(name)
if err != nil {
return nil, fmt.Errorf("could not get repository for %s: %w", name, err)
}
result := make(map[string]*signing.X509Signing)
for _, prof := range caDef.Profiles {
result[prof.Name] = signing.NewX509Signing(signing.NewProfile(
logger, caDef.KeyPair, caDef.Certificate, prof.Name,
[]string{caConfig.BuildOCSPURL(caDef)}, prof.UseFor, prof.Years, prof.Months, prof.Days,
), repo)
}
return result, nil
}
func initializeHSM(caConfig *config.SignerConfig, setupMode, verbose bool, logger *logrus.Logger) *hsm.Access {
opts := make([]hsm.ConfigOption, 0)
opts = append(opts, hsm.CaConfigOption(caConfig))
if setupMode {
logger.Infof("running in setup mode")
opts = append(opts, hsm.SetupModeOption())
}
if verbose {
opts = append(opts, hsm.VerboseLoggingOption())
}
access, err := hsm.NewAccess(logger, opts...)
if err != nil {
logger.WithError(err).Fatal("could not setup HSM access")
}
err = access.EnsureCAKeysAndCertificates()
if err != nil {
logger.WithError(err).Fatal("could not ensure CA keys and certificates exist")
}
return access
}
func loadConfig(signerConfigFile string, logger *logrus.Logger) *config.SignerConfig {
configFile, err := os.Open(signerConfigFile)
if err != nil {
logger.WithError(err).Fatalf("could not open signer configuration file: %s", signerConfigFile)
}
caConfig, err := config.LoadConfiguration(configFile)
if err != nil {
logger.Fatalf("could not load CA hierarchy: %v", err)
}
return caConfig
}