2021-11-05 14:24:04 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2021-11-06 10:47:10 +01:00
|
|
|
"context"
|
2021-11-05 14:24:04 +01:00
|
|
|
"encoding/pem"
|
|
|
|
"fmt"
|
2021-11-05 17:16:44 +01:00
|
|
|
"os"
|
2021-11-06 10:47:10 +01:00
|
|
|
"os/exec"
|
2021-11-05 17:16:44 +01:00
|
|
|
"os/user"
|
|
|
|
"strconv"
|
2021-11-06 17:46:38 +01:00
|
|
|
"strings"
|
2021-11-05 17:16:44 +01:00
|
|
|
"syscall"
|
2021-11-06 10:47:10 +01:00
|
|
|
"time"
|
|
|
|
"unicode/utf8"
|
2021-11-05 17:16:44 +01:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
2021-11-05 14:24:04 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// Max supported CA chain length
|
|
|
|
const MAX_CA_CHAIN_LENGTH = 8
|
|
|
|
|
|
|
|
type (
|
2021-11-05 17:16:44 +01:00
|
|
|
// Structure that describes the existing file for a certificate.
|
|
|
|
tExistingFileInfo struct {
|
|
|
|
owner uint32
|
|
|
|
group uint32
|
|
|
|
mode os.FileMode
|
|
|
|
}
|
|
|
|
|
2021-11-05 14:24:04 +01:00
|
|
|
// Certificate building, including the configuration, LDAP connection,
|
|
|
|
// and the array of chunks that's being built.
|
|
|
|
tCertificateBuilder struct {
|
2021-11-06 17:46:38 +01:00
|
|
|
// The certificate file's current configuration
|
2021-12-04 17:21:24 +01:00
|
|
|
Config *tCertificateFileConfig
|
2021-11-06 17:46:38 +01:00
|
|
|
// The LDAP connection to read data from
|
|
|
|
conn *tLdapConn
|
|
|
|
// The logger to use
|
|
|
|
logger *logrus.Entry
|
|
|
|
// The list of DNs that are involved in generating this certificate. If the
|
|
|
|
// command has a non-'*' selector, the list will be checked for a value
|
|
|
|
// matching the selector befor anything else is done.
|
|
|
|
dnList []string
|
|
|
|
// The various chunks of data that will be written to the resulting PEM file.
|
|
|
|
// Each chunk corresponds to a PEM block.
|
|
|
|
data [][]byte
|
|
|
|
// The output text
|
|
|
|
text []byte
|
|
|
|
// Information about the current file, if it exists.
|
2021-11-05 17:16:44 +01:00
|
|
|
existing *tExistingFileInfo
|
2021-11-06 17:46:38 +01:00
|
|
|
// Was the certificate file replaced?
|
|
|
|
changed bool
|
2021-11-05 14:24:04 +01:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// Initialize a certificate file building using a LDAP connection and
|
|
|
|
// certificate file configuration.
|
2021-12-04 17:21:24 +01:00
|
|
|
func NewCertificateBuilder(conn *tLdapConn, config *tCertificateFileConfig) *tCertificateBuilder {
|
|
|
|
return &tCertificateBuilder{
|
|
|
|
Config: config,
|
|
|
|
conn: conn,
|
|
|
|
logger: log.WithField("file", config.Path),
|
|
|
|
data: make([][]byte, 0),
|
2021-11-05 14:24:04 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Build the certificate file's data, returning any error that occurs while
|
|
|
|
// reading the source data.
|
|
|
|
func (b *tCertificateBuilder) Build() error {
|
2021-11-05 17:16:44 +01:00
|
|
|
b.logger.Debug("Checking for updates")
|
2021-12-04 17:21:24 +01:00
|
|
|
err := b.appendPemFiles(b.Config.PrependFiles)
|
2021-11-05 14:24:04 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = b.appendCertificate()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = b.appendCaCertificates()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-04 17:21:24 +01:00
|
|
|
err = b.appendPemFiles(b.Config.AppendFiles)
|
2021-11-05 14:24:04 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-04 17:21:24 +01:00
|
|
|
if b.Config.Reverse {
|
2021-11-05 14:24:04 +01:00
|
|
|
b.reverseChunks()
|
|
|
|
}
|
2021-11-05 17:16:44 +01:00
|
|
|
b.generateText()
|
2021-11-05 14:24:04 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-12-04 17:21:24 +01:00
|
|
|
// Check whether a selector matches one of the current certificate file's DNs.
|
|
|
|
func (b *tCertificateBuilder) SelectorMatches(selector string) bool {
|
|
|
|
if selector == "*" {
|
2021-11-06 17:46:38 +01:00
|
|
|
return true
|
|
|
|
}
|
2021-12-04 17:21:24 +01:00
|
|
|
sel := strings.ToLower(selector)
|
2021-11-06 17:46:38 +01:00
|
|
|
for _, v := range b.dnList {
|
|
|
|
if strings.ToLower(v) == sel {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2021-12-04 17:21:24 +01:00
|
|
|
b.logger.WithField("selector", selector).Debug("Selector does not match.")
|
2021-11-06 17:46:38 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check whether the data should be written to disk. This also caches the
|
|
|
|
// file's owner, group and mode. If the update is being forced it will return
|
|
|
|
// `true` even if nothing changed.
|
2021-12-04 17:21:24 +01:00
|
|
|
//
|
|
|
|
// Note: file information will be read even when updates are forced, because
|
|
|
|
// it is used later to set file privileges.
|
|
|
|
func (b *tCertificateBuilder) MustWrite(force bool) bool {
|
|
|
|
info, err := os.Lstat(b.Config.Path)
|
2021-11-05 17:16:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
sys_stat := info.Sys().(*syscall.Stat_t)
|
|
|
|
eif := &tExistingFileInfo{}
|
|
|
|
eif.mode = info.Mode()
|
|
|
|
eif.owner = sys_stat.Uid
|
|
|
|
eif.group = sys_stat.Gid
|
|
|
|
b.existing = eif
|
|
|
|
|
2021-12-04 17:21:24 +01:00
|
|
|
if force || sys_stat.Size != int64(len(b.text)) {
|
2021-11-05 17:16:44 +01:00
|
|
|
return true
|
|
|
|
}
|
2024-07-26 11:31:12 +02:00
|
|
|
existing, err := os.ReadFile(b.Config.Path)
|
2021-11-05 17:16:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
for i, ch := range b.text {
|
|
|
|
if ch != existing[i] {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write the file's data
|
|
|
|
func (b *tCertificateBuilder) WriteFile() error {
|
2021-12-04 17:21:24 +01:00
|
|
|
log.WithField("file", b.Config.Path).Info("Writing certificate data to file")
|
2024-07-26 11:31:12 +02:00
|
|
|
err := os.WriteFile(b.Config.Path, b.text, b.Config.FileMode())
|
2021-11-05 17:16:44 +01:00
|
|
|
if err == nil {
|
|
|
|
b.changed = true
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the file's owner and group
|
|
|
|
func (b *tCertificateBuilder) UpdatePrivileges() error {
|
2021-12-05 18:45:30 +01:00
|
|
|
update_mode := b.existing != nil && b.existing.mode != b.Config.FileMode()
|
2021-11-05 17:16:44 +01:00
|
|
|
if update_mode {
|
2021-12-05 18:45:30 +01:00
|
|
|
log.WithField("mode", b.Config.FileMode).Info("Updating file mode")
|
2021-12-05 18:19:17 +01:00
|
|
|
err := os.Chmod(b.Config.Path, b.Config.FileMode())
|
2021-11-05 17:16:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
log := b.logger
|
|
|
|
set_uid, set_gid := -1, -1
|
2021-12-04 17:21:24 +01:00
|
|
|
if b.Config.Owner != "" {
|
|
|
|
usr, err := user.Lookup(b.Config.Owner)
|
2021-11-05 17:16:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-07-26 13:46:43 +02:00
|
|
|
// Uid has already been validated when reading the config file
|
|
|
|
uid, _ := strconv.Atoi(usr.Uid)
|
2021-11-05 17:16:44 +01:00
|
|
|
if b.changed || b.existing == nil || b.existing.owner != uint32(uid) {
|
|
|
|
set_uid = uid
|
|
|
|
log = log.WithField("uid", set_uid)
|
|
|
|
}
|
|
|
|
}
|
2021-12-04 17:21:24 +01:00
|
|
|
if b.Config.Group != "" {
|
|
|
|
group, err := user.LookupGroup(b.Config.Group)
|
2021-11-05 17:16:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-07-26 13:46:43 +02:00
|
|
|
// Gid has already been validated when reading the config file
|
|
|
|
gid, _ := strconv.Atoi(group.Gid)
|
2021-11-05 17:16:44 +01:00
|
|
|
if b.changed || b.existing == nil || b.existing.group != uint32(gid) {
|
|
|
|
set_gid = gid
|
|
|
|
log = log.WithField("gid", set_gid)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if set_gid != -1 || set_uid != -1 {
|
|
|
|
log.Info("Updating file owner/group")
|
2021-12-04 17:21:24 +01:00
|
|
|
err := os.Chown(b.Config.Path, set_uid, set_gid)
|
2021-11-05 17:16:44 +01:00
|
|
|
if err == nil {
|
|
|
|
b.changed = true
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
} else {
|
|
|
|
b.changed = b.changed || update_mode
|
2021-12-05 18:45:30 +01:00
|
|
|
if !update_mode {
|
|
|
|
log.Debug("No update to privileges")
|
|
|
|
}
|
2021-11-05 17:16:44 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-04 17:21:24 +01:00
|
|
|
// Did this certificate change in any way?
|
|
|
|
func (b *tCertificateBuilder) Changed() bool {
|
|
|
|
return b.changed
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run the commands from the pre_commands section of the configuration.
|
|
|
|
// This is only called if the certificate file has been modified in
|
2021-11-06 10:47:10 +01:00
|
|
|
// any way. Execution will stop at the first failure.
|
2021-12-04 17:21:24 +01:00
|
|
|
func (b *tCertificateBuilder) RunPreCommands() error {
|
|
|
|
for i := range b.Config.AfterUpdate.PreCommands {
|
2021-11-06 10:47:10 +01:00
|
|
|
err := b.RunCommand(i)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"Failed while executing command '%s': %w",
|
2021-12-04 17:21:24 +01:00
|
|
|
b.Config.AfterUpdate.PreCommands[i],
|
2021-11-06 10:47:10 +01:00
|
|
|
err,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run a command through the `sh` shell.
|
|
|
|
func (b *tCertificateBuilder) RunCommand(pos int) error {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2021-12-04 17:21:24 +01:00
|
|
|
log := b.logger.WithField("command", b.Config.AfterUpdate.PreCommands[pos])
|
2021-11-06 10:47:10 +01:00
|
|
|
log.Debug("Executing command")
|
2021-12-04 17:21:24 +01:00
|
|
|
cmd := exec.CommandContext(ctx, "sh", "-c", b.Config.AfterUpdate.PreCommands[pos])
|
2021-11-06 10:47:10 +01:00
|
|
|
output, err := cmd.CombinedOutput()
|
|
|
|
if len(output) != 0 {
|
|
|
|
if utf8.Valid(output) {
|
|
|
|
log = log.WithField("output", string(output))
|
|
|
|
} else {
|
|
|
|
log = log.WithField("output", string(output))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err == nil {
|
|
|
|
log.Info("Command executed")
|
|
|
|
} else {
|
|
|
|
log.WithField("error", err).Error("Command failed")
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-11-05 14:24:04 +01:00
|
|
|
// Append PEM files from a list.
|
|
|
|
func (b *tCertificateBuilder) appendPemFiles(files []string) error {
|
|
|
|
for _, path := range files {
|
|
|
|
var err error
|
2021-11-05 17:16:44 +01:00
|
|
|
b.logger.WithField("source", path).Debug("Adding PEM file")
|
2021-11-05 14:24:04 +01:00
|
|
|
err = b.appendPem(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Append a PEM file to the current list of data chunks
|
|
|
|
func (b *tCertificateBuilder) appendPem(input string) error {
|
2024-07-26 11:31:12 +02:00
|
|
|
data, err := os.ReadFile(input)
|
2021-11-05 14:24:04 +01:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Could not load '%s': %w", input, err)
|
|
|
|
}
|
|
|
|
rest := data
|
|
|
|
hadBlock := false
|
|
|
|
for {
|
|
|
|
var block *pem.Block
|
|
|
|
block, rest = pem.Decode(rest)
|
|
|
|
if block == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
hadBlock = true
|
|
|
|
b.data = append(b.data, pem.EncodeToMemory(block))
|
|
|
|
}
|
|
|
|
if hadBlock {
|
|
|
|
return nil
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("No PEM blocks found in '%s'", input)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Append the main, end-entity certificate from the LDAP
|
|
|
|
func (b *tCertificateBuilder) appendCertificate() error {
|
2021-12-04 17:21:24 +01:00
|
|
|
if b.Config.Certificate != "" {
|
2021-11-06 10:05:45 +01:00
|
|
|
dn := b.conn.BaseDN()
|
2021-11-05 14:24:04 +01:00
|
|
|
if dn != "" {
|
|
|
|
dn = "," + dn
|
|
|
|
}
|
2021-12-04 17:21:24 +01:00
|
|
|
dn = b.Config.Certificate + dn
|
2021-11-06 17:46:38 +01:00
|
|
|
b.dnList = append(b.dnList, strings.ToLower(dn))
|
2021-11-05 17:16:44 +01:00
|
|
|
b.logger.WithField("dn", dn).Debug("Adding EE certificate from LDAP")
|
2021-11-06 10:05:45 +01:00
|
|
|
data, err := b.conn.GetEndEntityCertificate(dn)
|
2021-11-05 14:24:04 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
b.data = append(b.data, data)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Append all CA certificates, reading the list from the LDAP or from the
|
|
|
|
// configuration.
|
|
|
|
func (b *tCertificateBuilder) appendCaCertificates() error {
|
2021-12-04 17:21:24 +01:00
|
|
|
if len(b.Config.CACertificates) != 0 {
|
2021-11-05 14:24:04 +01:00
|
|
|
return b.appendListedCaCerts()
|
2021-12-04 17:21:24 +01:00
|
|
|
} else if b.Config.CAChainOf != "" {
|
2021-11-05 14:24:04 +01:00
|
|
|
return b.appendChainedCaCerts()
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Append CA certificates based on a list of DNs
|
|
|
|
func (b *tCertificateBuilder) appendListedCaCerts() error {
|
2021-11-06 10:05:45 +01:00
|
|
|
bdn := b.conn.BaseDN()
|
2021-11-05 14:24:04 +01:00
|
|
|
if bdn != "" {
|
|
|
|
bdn = "," + bdn
|
|
|
|
}
|
2021-12-04 17:21:24 +01:00
|
|
|
for _, dn := range b.Config.CACertificates {
|
2021-11-06 17:46:38 +01:00
|
|
|
full_dn := dn + bdn
|
|
|
|
b.dnList = append(b.dnList, strings.ToLower(full_dn))
|
|
|
|
b.logger.WithField("dn", full_dn).Debug("Adding CA certificate from LDAP")
|
|
|
|
data, _, err := b.conn.GetCaCertificate(full_dn)
|
2021-11-05 14:24:04 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if data == nil {
|
2021-11-06 17:46:38 +01:00
|
|
|
return fmt.Errorf("No CA certificate at DN '%s'", full_dn)
|
2021-11-05 14:24:04 +01:00
|
|
|
}
|
|
|
|
b.data = append(b.data, data)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Append CA certificates by following a chain starting at some DN
|
|
|
|
func (b *tCertificateBuilder) appendChainedCaCerts() error {
|
|
|
|
nFound := 0
|
2021-12-04 17:21:24 +01:00
|
|
|
dn := b.Config.CAChainOf
|
2021-11-06 10:05:45 +01:00
|
|
|
if b.conn.BaseDN() != "" {
|
|
|
|
dn = dn + "," + b.conn.BaseDN()
|
2021-11-05 14:24:04 +01:00
|
|
|
}
|
|
|
|
for {
|
2021-11-06 17:46:38 +01:00
|
|
|
b.dnList = append(b.dnList, strings.ToLower(dn))
|
2021-11-06 10:05:45 +01:00
|
|
|
data, nextDn, err := b.conn.GetCaCertificate(dn)
|
2021-11-05 14:24:04 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if nFound != 0 {
|
|
|
|
if data == nil {
|
|
|
|
return fmt.Errorf("No CA certificate at DN '%s'", dn)
|
|
|
|
}
|
2021-11-05 17:16:44 +01:00
|
|
|
b.logger.WithField("dn", dn).Debug("Adding CA certificate from LDAP chain")
|
2021-11-05 14:24:04 +01:00
|
|
|
b.data = append(b.data, data)
|
|
|
|
}
|
|
|
|
if nextDn == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
dn = nextDn
|
|
|
|
nFound += 1
|
|
|
|
if nFound == MAX_CA_CHAIN_LENGTH {
|
|
|
|
return fmt.Errorf("DN '%s': CA chain length exceeded", dn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reverse the chunks in the list
|
|
|
|
func (b *tCertificateBuilder) reverseChunks() {
|
2021-11-05 17:16:44 +01:00
|
|
|
b.logger.Debug("Reversing PEM list")
|
2021-11-05 14:24:04 +01:00
|
|
|
l := len(b.data) / 2
|
|
|
|
for i := 0; i < l/2; i++ {
|
|
|
|
j := l - i - 1
|
|
|
|
b.data[i], b.data[j] = b.data[j], b.data[i]
|
|
|
|
}
|
|
|
|
}
|
2021-11-05 17:16:44 +01:00
|
|
|
|
|
|
|
// Generate the final text of the file
|
|
|
|
func (b *tCertificateBuilder) generateText() {
|
|
|
|
size := int64(0)
|
|
|
|
for i := range b.data {
|
|
|
|
size += int64(len(b.data[i]))
|
|
|
|
if i != 0 && b.data[i-1][len(b.data[i-1])-1] != '\n' {
|
|
|
|
size++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
b.text = make([]byte, size)
|
|
|
|
pos := 0
|
|
|
|
for i := range b.data {
|
|
|
|
copied := copy(b.text[pos:], b.data[i])
|
|
|
|
pos += copied
|
|
|
|
if i != 0 && b.data[i-1][len(b.data[i-1])-1] != '\n' {
|
|
|
|
b.text[pos] = '\n'
|
|
|
|
pos++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
b.logger.WithField("size", size).Debug("Data generated")
|
|
|
|
}
|