You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

300 lines
6.6 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.
*/
//go:generate go run github.com/shamaton/msgpackgen
// Package messages contains structure definitions for protocol messages
package messages
import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"math/big"
"strings"
"time"
// required for msgpackgen
_ "github.com/dave/jennifer"
"github.com/google/uuid"
)
type CommandCode int8
const (
CmdUndef CommandCode = iota
CmdHealth
CmdFetchCRL
)
var commandNames = map[CommandCode]string{
CmdUndef: "UNDEFINED",
CmdHealth: "HEALTH",
CmdFetchCRL: "FETCH CRL",
}
func (c CommandCode) String() string {
if name, ok := commandNames[c]; ok {
return name
}
return fmt.Sprintf("unknown %d", c)
}
type ResponseCode int8
const (
RespError ResponseCode = -1
RespUndef ResponseCode = iota
RespHealth
RespFetchCRL
)
var responseNames = map[ResponseCode]string{
RespError: "ERROR",
RespUndef: "UNDEFINED",
RespHealth: "HEALTH",
RespFetchCRL: "FETCH CRL",
}
func (c ResponseCode) String() string {
if name, ok := responseNames[c]; ok {
return name
}
return fmt.Sprintf("unknown %d", c)
}
type CommandAnnounce struct {
Code CommandCode `msgpack:"code"`
ID string `msgpack:"id"`
Created time.Time `msgpack:"created"`
}
func (r *CommandAnnounce) String() string {
return fmt.Sprintf("code=%s, id=%s, created=%s", r.Code, r.ID, r.Created.Format(time.RFC3339))
}
type ResponseAnnounce struct {
Code ResponseCode `msgpack:"code"`
Created time.Time `msgpack:"created"`
ID string `msgpack:"id"`
}
func (r *ResponseAnnounce) String() string {
return fmt.Sprintf("code=%s, id=%s, created=%s", r.Code, r.ID, r.Created.Format(time.RFC3339))
}
type FetchCRLCommand struct {
IssuerID string `msgpack:"issuer_id"`
LastKnownID []byte `msgpack:"last_known_id"`
}
func (f *FetchCRLCommand) String() string {
builder := &strings.Builder{}
_, _ = fmt.Fprintf(builder, "issuerId='%s'", f.IssuerID)
if f.LastKnownID != nil {
_, _ = fmt.Fprintf(builder, ", lastKnownId=0x%s", new(big.Int).SetBytes(f.LastKnownID).Text(16))
}
return builder.String()
}
type HealthCommand struct {
}
func (h *HealthCommand) String() string {
return ""
}
type HealthInfo struct {
Source string
Healthy bool
MoreInfo map[string]string
}
func (i *HealthInfo) String() string {
builder := &strings.Builder{}
_, _ = fmt.Fprintf(builder, "source: %s, healthy: %v, [\n", i.Source, i.Healthy)
for k, v := range i.MoreInfo {
_, _ = fmt.Fprintf(builder, " %s: '%s'\n", k, v)
}
_, _ = builder.WriteRune(']')
return builder.String()
}
type ProfileUsage string
const (
UsageOcsp ProfileUsage = "ocsp"
UsagePerson ProfileUsage = "person"
UsageClient ProfileUsage = "client"
UsageCode ProfileUsage = "code"
UsageServer ProfileUsage = "server"
)
var validProfileUsages = map[string]ProfileUsage{
"ocsp": UsageOcsp,
"person": UsagePerson,
"client": UsageClient,
"code": UsageCode,
"server": UsageServer,
}
func ParseUsage(u string) (ProfileUsage, error) {
usage, ok := validProfileUsages[u]
if !ok {
return "", fmt.Errorf("unsupported profile usage: %s", u)
}
return usage, nil
}
type CAProfile struct {
Name string `json:"name"`
UseFor ProfileUsage `json:"use-for"`
}
func (p CAProfile) String() string {
return fmt.Sprintf("profile['%s': '%s']", p.Name, p.UseFor)
}
type CertificateInfo struct {
Status string `json:"status"`
Signing bool `json:"signing"`
Profiles []CAProfile `json:"profiles"`
ValidUntil time.Time `json:"valid-until"`
}
func (i CertificateInfo) String() string {
marshal, _ := json.Marshal(i)
return string(marshal)
}
func (i *HealthInfo) ParseCertificateInfo(info string) (*CertificateInfo, error) {
certInfo := CertificateInfo{}
err := json.Unmarshal([]byte(info), &certInfo)
if err != nil {
return nil, fmt.Errorf("could not parse certificate information: %w", err)
}
return &certInfo, nil
}
type HealthResponse struct {
Version string `msgpack:"version"`
Healthy bool `msgpack:"healthy"`
Info []*HealthInfo
}
func (h *HealthResponse) String() string {
builder := &strings.Builder{}
_, _ = fmt.Fprintf(builder, "signer version=%s, healthy=%v, health data:\n", h.Version, h.Healthy)
for _, info := range h.Info {
_, _ = fmt.Fprintf(builder, " - %s", info)
}
return builder.String()
}
type FetchCRLResponse struct {
IssuerID string `msgpack:"issuer_id"`
IsDelta bool `msgpack:"is_delta"`
UnChanged bool `msgpack:"unchanged"`
CRLData []byte `msgpack:"crl_data"`
CRLNumber []byte `msgpack:"crl_number"`
}
func (r *FetchCRLResponse) String() string {
builder := &strings.Builder{}
_, _ = fmt.Fprintf(
builder,
"issuer id=%s, delta CRL data=%t, unchanged=%t, CRL number=0x%s",
r.IssuerID,
r.IsDelta,
r.UnChanged,
new(big.Int).SetBytes(r.CRLNumber).Text(16),
)
if r.UnChanged {
return builder.String()
}
if r.IsDelta {
_, _ = fmt.Fprint(builder, ", delta CRL data not shown")
return builder.String()
}
revocationList, err := x509.ParseRevocationList(r.CRLData)
if err != nil {
_, _ = fmt.Fprintf(builder, ", could not parse CRL: %s", err.Error())
return builder.String()
}
_, _ = fmt.Fprintf(
builder,
", CRL info: issuer=%s, number=0x%s, next update=%s, revoked certificates=%d",
revocationList.Issuer,
revocationList.Number.Text(16),
revocationList.NextUpdate,
len(revocationList.RevokedCertificates),
)
_, _ = builder.WriteString(", CRL data:\n")
_ = pem.Encode(builder, &pem.Block{
Type: "CERTIFICATE REVOCATION LIST",
Bytes: r.CRLData,
})
return builder.String()
}
type ErrorResponse struct {
Message string `msgpack:"message"`
}
func (e *ErrorResponse) String() string {
return fmt.Sprintf("message=%s", e.Message)
}
func BuildCommandAnnounce(code CommandCode) (*CommandAnnounce, error) {
commandID, err := uuid.NewUUID()
if err != nil {
return nil, fmt.Errorf("could not build command id: %w", err)
}
return &CommandAnnounce{Code: code, ID: commandID.String(), Created: time.Now().UTC()}, nil
}
func BuildResponseAnnounce(code ResponseCode, commandID string) *ResponseAnnounce {
return &ResponseAnnounce{Code: code, ID: commandID, Created: time.Now().UTC()}
}