cacert-gosigner/internal/handler/msgpack.go

474 lines
13 KiB
Go
Raw Normal View History

/*
Copyright 2022-2023 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 handler
import (
"context"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"fmt"
"math/big"
"time"
"github.com/shamaton/msgpackgen/msgpack"
"github.com/sirupsen/logrus"
"git.cacert.org/cacert-gosigner/internal/cainfo"
"git.cacert.org/cacert-gosigner/internal/health"
"git.cacert.org/cacert-gosigner/internal/x509/revoking"
"git.cacert.org/cacert-gosigner/internal/x509/signing"
"git.cacert.org/cacert-gosigner/pkg/messages"
"git.cacert.org/cacert-gosigner/pkg/protocol"
)
const readCommandTimeOut = 5 * time.Second
var errReadCommandTimeout = errors.New("read command timeout expired")
// MsgPackHandler is a ServerHandler implementation for the msgpack serialization format.
type MsgPackHandler struct {
logger *logrus.Logger
healthHandler *health.Handler
certificateAuthorityInfoHandler cainfo.Handler
fetchCRLHandler *revoking.FetchCRLHandler
x509SigningHandler signing.Handler
}
func (m *MsgPackHandler) CommandAnnounce(ctx context.Context, frames <-chan []byte) (*protocol.Command, error) {
select {
case <-ctx.Done():
return nil, nil
case frame := <-frames:
var ann messages.CommandAnnounce
if err := msgpack.Unmarshal(frame, &ann); err != nil {
return nil, fmt.Errorf("could not unmarshal command announcement: %w", err)
}
if ann.Code == messages.CmdUndef {
return nil, fmt.Errorf("received undefined command announcement: %s", ann)
}
m.logger.WithField("announcement", &ann).Debug("received command announcement")
return &protocol.Command{Announce: &ann}, nil
}
}
func (m *MsgPackHandler) CommandData(ctx context.Context, frames <-chan []byte, command *protocol.Command) error {
select {
case <-ctx.Done():
return nil
case frame := <-frames:
err := m.parseCommand(frame, command)
if err != nil {
return err
}
return nil
case <-time.After(readCommandTimeOut):
return errReadCommandTimeout
}
}
func (m *MsgPackHandler) HandleCommand(_ context.Context, command *protocol.Command) (*protocol.Response, error) {
var (
response *protocol.Response
err error
)
response, err = m.handleCommand(command)
if err != nil {
m.logger.WithError(err).Error("command handling failed")
response = m.buildErrorResponse(command.Announce.ID, "command handling failed")
}
m.logCommandResponse(command, response)
return response, nil
}
func (m *MsgPackHandler) logCommandResponse(command *protocol.Command, response *protocol.Response) {
m.logger.WithField("command", command.Announce).Info("handled command")
m.logger.WithField("command", command).WithField("response", response).Debug("command and response")
}
func (m *MsgPackHandler) Respond(ctx context.Context, response *protocol.Response, out chan<- []byte) error {
announce, err := msgpack.Marshal(response.Announce)
if err != nil {
return fmt.Errorf("could not marshal response announcement: %w", err)
}
m.logger.WithField("length", len(announce)).Debug("write response announcement")
select {
case <-ctx.Done():
return nil
case out <- announce:
break
}
data, err := msgpack.Marshal(response.Response)
if err != nil {
return fmt.Errorf("could not marshal response: %w", err)
}
m.logger.WithField("length", len(data)).Debug("write response")
select {
case <-ctx.Done():
return nil
case out <- data:
break
}
return nil
}
func (m *MsgPackHandler) parseHealthCommand(frame []byte) (*messages.HealthCommand, error) {
var command messages.HealthCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Error("unmarshal failed")
return nil, errors.New("could not unmarshal health command")
}
return &command, nil
}
func (m *MsgPackHandler) parseCAInfoCommand(frame []byte) (*messages.CAInfoCommand, error) {
var command messages.CAInfoCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Error("unmarshal failed")
return nil, errors.New("could not unmarshal CA info command")
}
return &command, nil
}
func (m *MsgPackHandler) parseFetchCRLCommand(frame []byte) (*messages.FetchCRLCommand, error) {
var command messages.FetchCRLCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Error("unmarshal failed")
return nil, errors.New("could not unmarshal fetch crl command")
}
return &command, nil
}
func (m *MsgPackHandler) parseSignCertificateCommand(frame []byte) (*messages.SignCertificateCommand, error) {
var command messages.SignCertificateCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Error("unmarshal failed")
return nil, errors.New("could not unmarshal sign certificate command")
}
return &command, nil
}
func (m *MsgPackHandler) handleCommand(command *protocol.Command) (*protocol.Response, error) {
var (
responseCode messages.ResponseCode
responseData interface{}
)
switch cmd := command.Command.(type) {
case *messages.HealthCommand:
response, err := m.handleHealthCommand()
if err != nil {
return nil, err
}
responseCode, responseData = messages.RespHealth, response
case *messages.CAInfoCommand:
response, err := m.handleCAInfoCommand(cmd)
if err != nil {
return nil, err
}
responseCode, responseData = messages.RespCAInfo, response
case *messages.FetchCRLCommand:
response, err := m.handleFetchCRLCommand(cmd)
if err != nil {
return nil, err
}
responseCode, responseData = messages.RespFetchCRL, response
case *messages.SignCertificateCommand:
response, err := m.handleSignCertificateCommand(cmd)
if err != nil {
return nil, err
}
responseCode, responseData = messages.RespSignCertificate, response
default:
return nil, fmt.Errorf("unhandled command %s", command.Announce)
}
return &protocol.Response{
Announce: messages.BuildResponseAnnounce(responseCode, command.Announce.ID),
Response: responseData,
}, nil
}
func (m *MsgPackHandler) buildErrorResponse(commandID string, errMsg string) *protocol.Response {
return &protocol.Response{
Announce: messages.BuildResponseAnnounce(messages.RespError, commandID),
Response: &messages.ErrorResponse{Message: errMsg},
}
}
func (m *MsgPackHandler) parseCommand(frame []byte, command *protocol.Command) error {
switch command.Announce.Code {
case messages.CmdHealth:
healthCommand, err := m.parseHealthCommand(frame)
if err != nil {
return err
}
command.Command = healthCommand
case messages.CmdCAInfo:
caInfoCommand, err := m.parseCAInfoCommand(frame)
if err != nil {
return err
}
command.Command = caInfoCommand
case messages.CmdFetchCRL:
fetchCRLCommand, err := m.parseFetchCRLCommand(frame)
if err != nil {
return err
}
command.Command = fetchCRLCommand
case messages.CmdSignCertificate:
signCertificateCommand, err := m.parseSignCertificateCommand(frame)
if err != nil {
return err
}
command.Command = signCertificateCommand
case messages.CmdRevokeCertificate:
revokeCertificateCommand, err := m.parseRevokeCertificateCommand(frame)
if err != nil {
return err
}
command.Command = revokeCertificateCommand
case messages.CmdSignOpenPGP:
signOpenPGPCommand, err := m.parseSignOpenPGPCommand(frame)
if err != nil {
return err
}
command.Command = signOpenPGPCommand
default:
return fmt.Errorf("unhandled command code %s", command.Announce.Code)
}
return nil
}
func (m *MsgPackHandler) handleHealthCommand() (*messages.HealthResponse, error) {
res, err := m.healthHandler.CheckHealth()
if err != nil {
return nil, fmt.Errorf("could not check health: %w", err)
}
response := &messages.HealthResponse{
Version: res.Version,
Healthy: res.Healthy,
}
for _, info := range res.Info {
response.Info = append(response.Info, &messages.HealthInfo{
Source: info.Source,
Healthy: info.Healthy,
MoreInfo: info.MoreInfo,
})
}
return response, nil
}
func (m *MsgPackHandler) handleCAInfoCommand(command *messages.CAInfoCommand) (*messages.CAInfoResponse, error) {
res, err := m.certificateAuthorityInfoHandler.GetCAInfo(command.Name)
if err != nil {
return nil, fmt.Errorf("could not get CA information")
}
response := &messages.CAInfoResponse{
Name: command.Name,
Certificate: res.Certificate,
Signing: res.Certificate != nil && len(res.Profiles) > 0,
Profiles: res.Profiles,
}
return response, nil
}
func (m *MsgPackHandler) handleFetchCRLCommand(command *messages.FetchCRLCommand) (*messages.FetchCRLResponse, error) {
var crlNumber *big.Int
if command.LastKnownID != nil {
crlNumber = new(big.Int).SetBytes(command.LastKnownID)
}
res, err := m.fetchCRLHandler.FetchCRL(command.IssuerID, crlNumber)
if err != nil {
return nil, fmt.Errorf("could not fetch CRL: %w", err)
}
unchanged := crlNumber != nil && crlNumber.Cmp(res.Number) == 0
response := &messages.FetchCRLResponse{
IssuerID: command.IssuerID,
IsDelta: res.IsDelta,
UnChanged: unchanged,
CRLNumber: res.Number.Bytes(),
}
if !unchanged {
response.CRLData = res.CRLData
}
return response, nil
}
func (m *MsgPackHandler) handleSignCertificateCommand(
command *messages.SignCertificateCommand,
) (*messages.SignCertificateResponse, error) {
csr, err := x509.ParseCertificateRequest(command.CSRData)
if err != nil {
return nil, fmt.Errorf("could not parse certificate signing request: %w", err)
}
signerRequest := &signing.SignerRequest{
CSR: csr,
SubjectDN: pkix.Name{CommonName: command.CommonName},
Emails: command.EmailAddresses,
DNSNames: command.Hostnames,
PreferredHash: command.PreferredHash,
}
if command.Organization != "" {
signerRequest.SubjectDN.Organization = []string{command.Organization}
}
if command.OrganizationalUnit != "" {
signerRequest.SubjectDN.OrganizationalUnit = []string{command.OrganizationalUnit}
}
if command.Locality != "" {
signerRequest.SubjectDN.Locality = []string{command.Locality}
}
if command.Province != "" {
signerRequest.SubjectDN.Province = []string{command.Province}
}
if command.Country != "" {
signerRequest.SubjectDN.Country = []string{command.Country}
}
x509Signing, err := m.x509SigningHandler.GetSigner(command.IssuerID, command.ProfileName)
if err != nil {
return nil, fmt.Errorf("could not get X.509 signing component: %w", err)
}
res, err := x509Signing.Sign(signerRequest)
if err != nil {
return nil, fmt.Errorf("could not sign certificate: %w", err)
}
return &messages.SignCertificateResponse{CertificateData: res.Certificate.Raw}, nil
}
func (m *MsgPackHandler) parseRevokeCertificateCommand(frame []byte) (*messages.RevokeCertificateCommand, error) {
var command messages.RevokeCertificateCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Errorf("unmarshal failed")
return nil, errors.New("could not unmarshal revoke certificate command")
}
return &command, nil
}
func (m *MsgPackHandler) parseSignOpenPGPCommand(frame []byte) (*messages.SignOpenPGPCommand, error) {
var command messages.SignOpenPGPCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Errorf("unmarshal failed")
return nil, errors.New("could not unmarshal sign OpenPGP command")
}
return &command, nil
}
func New(logger *logrus.Logger, handlers ...RegisterHandler) (protocol.ServerHandler, error) {
messages.RegisterGeneratedResolver()
h := &MsgPackHandler{
logger: logger,
}
for _, reg := range handlers {
reg(h)
}
return h, nil
}
type RegisterHandler func(handler *MsgPackHandler)
func RegisterHealthHandler(healthHandler *health.Handler) func(*MsgPackHandler) {
return func(h *MsgPackHandler) {
h.healthHandler = healthHandler
}
}
func RegisterFetchCRLHandler(fetchCRLHandler *revoking.FetchCRLHandler) func(handler *MsgPackHandler) {
return func(h *MsgPackHandler) {
h.fetchCRLHandler = fetchCRLHandler
}
}
func RegisterCAInfoHandler(caInfoHandler cainfo.Handler) func(handler *MsgPackHandler) {
return func(h *MsgPackHandler) {
h.certificateAuthorityInfoHandler = caInfoHandler
}
}
func RegisterCertificateSigningHandler(signingHandler signing.Handler) func(handler *MsgPackHandler) {
return func(h *MsgPackHandler) {
h.x509SigningHandler = signingHandler
}
}