14 Commits

Author SHA1 Message Date
0a78b70821 Refactored config system again
All checks were successful
Build (artifact) / build (push) Successful in 27s
2026-06-30 16:48:05 -04:00
c01195643a Lets see if this works
All checks were successful
Build (artifact) / build (push) Successful in 1m13s
2026-06-29 07:57:03 -04:00
6aacbfbb71 [CI-SKIP] Store Pre-Claude Code
All checks were successful
Build (artifact) / build (push) Has been skipped
2026-04-22 22:26:21 -04:00
727de333b4 Fixed data_root hash file bug
All checks were successful
Build (artifact) / build (push) Successful in 50s
2026-03-21 10:59:47 +01:00
f4e7a37fa6 Fixed bug with hash being written in wrong location
All checks were successful
Build (artifact) / build (push) Successful in 41s
2026-03-21 10:52:46 +01:00
18f414e474 [CI-SKIP] Fixed module name
All checks were successful
Build (artifact) / build (push) Has been skipped
2026-03-16 23:03:08 +01:00
f09d9cc359 [CI-SKIP] Fix go.mod
All checks were successful
Build (artifact) / build (push) Has been skipped
2026-03-16 22:48:47 +01:00
2414dc64c6 Fix CI
All checks were successful
Build (artifact) / build (push) Successful in 1m9s
2026-03-16 21:54:24 +01:00
e0f68788c0 Major Refactoring, Client can now be used as a library
Some checks failed
Build (artifact) / build (push) Failing after 1m3s
2026-03-16 21:48:32 +01:00
e6a2ba2f8b [CI-SKIP] Update README a lil, add CI SKIP feature to gitea workflow
All checks were successful
Build (artifact) / build (push) Has been skipped
2026-03-08 23:14:40 +01:00
41b3a76c3b Added release on build, fixed subdomains with new toml configs, and added trimmed build target
All checks were successful
Build (artifact) / build (push) Successful in 25s
2026-03-08 22:45:49 +01:00
a9c1529f9d Downgrade upload-artifact from v4 to v3
All checks were successful
Build (artifact) / build (push) Successful in 1m7s
2026-03-08 22:05:54 +01:00
693c324eb0 Fixed gitea actions file to use fill github paths 2026-03-08 21:29:49 +01:00
e806470b11 Fixed relative path saving configs in wrong dir 2026-03-08 20:17:24 +01:00
47 changed files with 2195 additions and 1636 deletions

View File

@@ -0,0 +1,86 @@
name: Build (artifact)
on:
workflow_dispatch:
push:
branches: [ "master" ]
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[CI-SKIP]')"
steps:
- name: Checkout
uses: https://github.com/actions/checkout@v4
- name: Setup Go
uses: https://github.com/actions/setup-go@v5
with:
go-version: "1.25"
- name: Install protoc
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
- name: Install Go protobuf plugins
run: |
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
- name: Read VERSION from Makefile
shell: bash
run: |
VERSION="$(awk -F':=' '/^VERSION[[:space:]]*:=/ {gsub(/[[:space:]]/,"",$2); print $2; exit}' Makefile)"
if [ -z "$VERSION" ]; then
echo "Failed to read VERSION from Makefile" >&2
exit 1
fi
echo "VERSION=$VERSION" >> $GITHUB_ENV
- name: Get latest commit message
run: echo "COMMIT_MSG=$(git log -1 --pretty=%s)" >> $GITHUB_ENV
- name: Build
run: make client server
- name: Upload artifact
uses: https://github.com/actions/upload-artifact@v3
with:
name: certman-${{ env.VERSION }}-amd64.zip
path: bin/
if-no-files-found: error
- name: Create release and upload binary
run: |
BODY=$(jq -n --arg tag "v${{ env.VERSION }}" --arg msg "$COMMIT_MSG" \
'{tag_name: $tag, name: $tag, body: $msg, draft: false, prerelease: false}')
# Create the release
RELEASE_RESPONSE=$(curl --fail --silent --show-error \
-X POST \
-H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
-H "Content-Type: application/json" \
-d "$BODY" \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases")
# Extract the release ID
RELEASE_ID=$(echo "$RELEASE_RESPONSE" | jq -r '.id')
if [ -z "$RELEASE_ID" ] || [ "$RELEASE_ID" = "null" ]; then
echo "Failed to create release" >&2
echo "$RELEASE_RESPONSE" >&2
exit 1
fi
# Upload the binaries as release attachments
for binary in bin/*; do
FILENAME=$(basename "$binary")
echo "Uploading $FILENAME..."
curl --fail --silent --show-error \
-X POST \
-H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
-H "Content-Type: application/octet-stream" \
--upload-file "$binary" \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets?name=$FILENAME"
done

1
.gitignore vendored
View File

@@ -129,3 +129,4 @@ $RECYCLE.BIN/
config.ini
certman
certman-*-amd64
bin/

View File

@@ -1,21 +1,55 @@
VERSION := 1.0.1-beta
VERSION := 1.1.7-beta
BUILD := $(shell git rev-parse --short HEAD)
UPDATE_SRC := "https://git.nevets.tech/api/v1/repos/Steven/certman/releases"
GO := go
BUILD_FLAGS := -buildmode=pie -trimpath
LDFLAGS := -linkmode=external -extldflags="-Wl,-z,relro,-z,now" -X git.nevets.tech/Keys/CertManager/internal.Version=$(VERSION) -X git.nevets.tech/Keys/CertManager/internal.Build=$(BUILD)
LDFLAGS := -linkmode=external -extldflags="-Wl,-z,relro,-z,now" -X git.nevets.tech/Steven/certman/common.Version=$(VERSION) -X git.nevets.tech/Steven/certman/common.Build=$(BUILD) -X git.nevets.tech/Steven/certman/app.SourceCertmanRepo=$(UPDATE_SRC)
.PHONY: proto build stage
.PHONY: proto bundle client server executor cryptr build debug stage help
proto:
@protoc --go_out=./proto --go-grpc_out=./proto proto/hook.proto
@protoc --go_out=./proto --go-grpc_out=./proto proto/symlink.proto
build: proto
bundle: proto
@echo "Building Bundled Certman"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-$(VERSION)-amd64 ./app/bundle
client: proto
@echo "Building Certman Client"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-client-$(VERSION)-amd64 ./app/client
server: proto
@echo "Building Certman Server"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-server-$(VERSION)-amd64 ./app/server
executor: proto
@echo "Building Certman Executor"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-executor-$(VERSION)-amd64 ./app/executor
cryptr:
@echo "Building Cryptr"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w -linkmode=external -extldflags="-Wl,-z,relro,-z,now"" -o ./bin/cryptr ./app/cryptr
build: proto bundle client server cryptr
@echo "All binaries successfully built"
debug: proto
$(GO) build $(BUILD_FLAGS) -ldflags="$(LDFLAGS)" -o ./certman .
@cp ./certman ./certman-$(VERSION)-amd64
stage: build
@sudo cp ./certman /srv/vm-passthru/certman
@ssh steven@192.168.122.44 updateCertman.sh
help:
@echo "proto - Generate gRPC proto stubs"
@echo "bundle - Build bundled binary (client, server, executor)"
@echo "client - Build client binary"
@echo "server - Build server binary"
@echo "executor - Build executor binary"
@echo "build - Build all binaries"
@echo "debug - Build bundled binary without stripping and hardening"
@echo "stage - Build all binaries and upload to dev environment (vm)"

View File

@@ -1,2 +1,35 @@
# CertManager
### Features to Add
- Integrations as modules (systemd integration, generic commands, docker integration)
- Dedicated builds for server, client, and executor(?)
## Quick Start
## Daemonizing CertManager
The `install` command creates the certman user, directories, and runs chown on the created dirs
### Server
```bash
sudo certman install -mode server
sudo certman new-domain example.com
```
### Client
```bash
sudo certman install -mode client
sudo certman new-domain example.com
```
### TODO
- Add systemd units during install
- Add update command to pull from latest release
## Scratch Board
- Server Flow
- Read from
# Coding Conventions
- Keep Config() calls in app space

40
app/bundle/main.go Normal file
View File

@@ -0,0 +1,40 @@
package main
import (
"fmt"
"os"
"git.nevets.tech/Steven/certman/app"
"github.com/spf13/cobra"
)
//TODO create logic for gh vs gt repos
func main() {
rootCmd := &cobra.Command{
Use: "certman",
Short: "CertMan",
Long: "Certificate Manager",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
rootCmd.AddCommand(app.VersionCmd)
rootCmd.AddCommand(app.NewKeyCmd)
rootCmd.AddCommand(app.DevCmd)
rootCmd.AddCommand(app.NewDomainCmd)
rootCmd.AddCommand(app.InstallCmd)
rootCmd.AddCommand(app.CertCmd)
//rootCmd.AddCommand(executor.ExecutorCmd)
rootCmd.AddCommand(app.DaemonCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

15
app/certs.go Normal file
View File

@@ -0,0 +1,15 @@
package app
import (
"github.com/spf13/cobra"
)
var (
CertCmd = &cobra.Command{
Use: "cert",
Short: "Certificate management",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
)

96
app/client/certs.go Normal file
View File

@@ -0,0 +1,96 @@
package main
import (
"fmt"
"path/filepath"
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/client"
"git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/spf13/cobra"
)
var (
renewCertSubCmd = &cobra.Command{
Use: "renew",
Short: "Renews a domains certificate",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return renewCert(args[0])
},
}
updateCertLinkSubCmd = &cobra.Command{
Use: "update-link",
Short: "Update linked certificates",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return updateLinks(args[0])
},
}
decryptCertsSubCmd = &cobra.Command{
Use: "decrypt [certPath] [cryptoKey]",
Short: "Decrypt certificates",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return client.DecryptCertificates(args[0], args[1])
},
}
)
func init() {
renewCertSubCmd.AddCommand(updateCertLinkSubCmd, decryptCertsSubCmd)
app.CertCmd.AddCommand(renewCertSubCmd)
}
func renewCert(domain string) error {
config := app.Config()
domainConfig, exists := app.ClientDomainStore().Get(domain)
if !exists {
return app.ErrConfigNotFound
}
gitWorkspace := &common.GitWorkspace{
Domain: domain,
URL: config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git",
Storage: memory.NewStorage(),
FS: memfs.New(),
}
if err := client.PullCerts(config, gitWorkspace); err != nil {
return err
}
certsDir := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
return client.DecryptAndWriteCertificates(certsDir, config, domainConfig, gitWorkspace)
}
func updateLinks(domain string) error {
domainConfig, exists := app.ClientDomainStore().Get(domain)
if !exists {
return fmt.Errorf("domain %s does not exist", domain)
}
effectiveDataRoot := common.EffectiveDataRoot(app.Config(), domainConfig.Certificates.DataRoot)
certsDir := filepath.Join(effectiveDataRoot, "certificates", domain)
certLinks := domainConfig.Certificates.CertSymlinks
for _, certLink := range certLinks {
err := common.LinkFile(filepath.Join(certsDir, domain+".crt"), certLink, domain, ".crt")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", certLink, domain, err)
continue
}
}
keyLinks := domainConfig.Certificates.KeySymlinks
for _, keyLink := range keyLinks {
err := common.LinkFile(filepath.Join(certsDir, domain+".key"), keyLink, domain, ".key")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err)
continue
}
}
return nil
}

17
app/client/commands.go Normal file
View File

@@ -0,0 +1,17 @@
package main
import (
"git.nevets.tech/Steven/certman/app"
"github.com/spf13/cobra"
)
func init() {
app.DaemonCmd.AddCommand(&cobra.Command{
Use: "start",
Short: "Start the daemon",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return app.RunDaemonCmd(&Daemon{})
},
})
}

View File

@@ -1,4 +1,4 @@
package client
package main
import (
"fmt"
@@ -7,77 +7,55 @@ import (
"path/filepath"
"strings"
"git.nevets.tech/Keys/CertManager/internal"
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/client"
"git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
)
func Init() {
err := internal.LoadDomainConfigs()
type Daemon struct{}
func (d *Daemon) Init() {
fmt.Println("Starting CertManager in client mode...")
err := app.LoadClientDomainConfigs()
if err != nil {
log.Fatalf("Error loading domain configs: %v", err)
}
Tick()
d.Tick()
}
func Tick() {
fmt.Println("Tick!")
func (d *Daemon) Tick() {
fmt.Println("tick!")
// Get local copy of configs
config := internal.Config()
localDomainConfigs := internal.DomainStore().Snapshot()
config := app.Config()
localDomainConfigs := app.ClientDomainStore().Snapshot()
// Loop over all domain configs (domains)
for domainStr, domainConfig := range localDomainConfigs {
// Skip non-enabled domains
if !domainConfig.GetBool("Domain.enabled") {
if !domainConfig.Domain.Enabled {
continue
}
// Skip domains with up-to-date commit hashes
// If the repo doesn't exist, we can't check for a remote commit, so stop the rest of the check
repoExists := domainConfig.GetBool("Internal.repo_exists")
if repoExists {
localHash, err := internal.LocalCommitHash(domainStr)
if err != nil {
fmt.Printf("No local commit hash found for domain %s\n", domainStr)
}
gitSource, err := internal.StrToGitSource(internal.Config().GetString("Git.host"))
if err != nil {
fmt.Printf("Error getting git source for domain %s: %v\n", domainStr, err)
continue
}
remoteHash, err := internal.RemoteCommitHash(domainStr, gitSource)
if err != nil {
fmt.Printf("Error getting remote commit hash for domain %s: %v\n", domainStr, err)
}
// If both hashes are blank (errored), break
// If localHash equals remoteHash (local is up-to-date), skip
if !(localHash == "" && remoteHash == "") && localHash == remoteHash {
fmt.Printf("Domain %s is up to date. Skipping...\n", domainStr)
continue
}
}
gitWorkspace := &internal.GitWorkspace{
gitWorkspace := &common.GitWorkspace{
Domain: domainStr,
URL: app.Config().Git.Server + "/" + config.Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git",
Storage: memory.NewStorage(),
FS: memfs.New(),
}
// Ex: https://git.example.com/Org/Repo-suffix.git
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
repoUrl := internal.Config().GetString("Git.server") + "/" + config.GetString("Git.org_name") + "/" + domainStr + domainConfig.GetString("Repo.repo_suffix") + ".git"
err := internal.CloneRepo(repoUrl, gitWorkspace, internal.Client)
err := gitWorkspace.CloneRepo(common.Client, config)
if err != nil {
fmt.Printf("Error cloning domain repo %s: %v\n", domainStr, err)
continue
}
certsDir, err := internal.DomainCertsDirWConf(domainStr, domainConfig)
if err != nil {
fmt.Printf("Error getting certificates dir for domain %s: %v\n", domainStr, err)
continue
}
effectiveDataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
certsDir := filepath.Join(effectiveDataRoot, "certificates", domainStr)
// Get files in repo
fileInfos, err := gitWorkspace.FS.ReadDir("/")
@@ -106,7 +84,7 @@ func Tick() {
continue
}
err = internal.DecryptFileFromBytes(domainConfig.GetString("Certificates.crypto_key"), fileBytes, filepath.Join(certsDir, filename), nil)
err = common.DecryptFileFromBytes(domainConfig.Certificates.CryptoKey, fileBytes, filepath.Join(certsDir, filename), nil)
if err != nil {
fmt.Printf("Error decrypting file %s in domain %s: %v\n", filename, domainStr, err)
continue
@@ -118,24 +96,25 @@ func Tick() {
continue
}
err = internal.WriteCommitHash(headRef.Hash().String(), domainConfig)
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = client.WriteCommitHash(headRef.Hash().String(), dataRoot)
if err != nil {
fmt.Printf("Error writing commit hash: %v\n", err)
continue
}
certLinks := domainConfig.GetStringSlice("Certificates.cert_symlinks")
certLinks := domainConfig.Certificates.CertSymlinks
for _, certLink := range certLinks {
err = internal.LinkFile(filepath.Join(certsDir, domainStr+".crt"), certLink, domainStr, ".crt")
err = common.LinkFile(filepath.Join(certsDir, domainStr+".crt"), certLink, domainStr, ".crt")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v\n", certLink, domainStr, err)
continue
}
}
keyLinks := domainConfig.GetStringSlice("Certificates.key_symlinks")
keyLinks := domainConfig.Certificates.KeySymlinks
for _, keyLink := range keyLinks {
err = internal.LinkFile(filepath.Join(certsDir, domainStr+".key"), keyLink, domainStr, ".key")
err = common.LinkFile(filepath.Join(certsDir, domainStr+".key"), keyLink, domainStr, ".key")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v\n", keyLink, domainStr, err)
continue
@@ -146,16 +125,16 @@ func Tick() {
}
}
func Reload() {
func (d *Daemon) Reload() {
fmt.Println("Reloading configs...")
err := internal.LoadDomainConfigs()
err := app.LoadClientDomainConfigs()
if err != nil {
fmt.Printf("Error loading domain configs: %v\n", err)
return
}
}
func Stop() {
func (d *Daemon) Stop() {
fmt.Println("Shutting down client")
}

26
app/client/grpc.go Normal file
View File

@@ -0,0 +1,26 @@
package main
import (
"context"
"fmt"
"time"
pb "git.nevets.tech/Steven/certman/proto/v1"
)
// SendHook is currently a no-op pending hook config modeling on ClientDomainConfig.
func SendHook(domain string) {}
func sendHook(client pb.HookServiceClient, hook *pb.Hook) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
res, err := client.ExecuteHook(ctx, &pb.ExecuteHookRequest{Hook: hook})
if err != nil {
fmt.Printf("Error executing hook: %v\n", err)
return
}
if res.GetError() != "" {
fmt.Printf("Error executing hook: %s\n", res.GetError())
}
}

37
app/client/main.go Normal file
View File

@@ -0,0 +1,37 @@
package main
import (
"fmt"
"os"
"git.nevets.tech/Steven/certman/app"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: "certman",
Short: "CertMan",
Long: "Certificate Manager",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
rootCmd.AddCommand(app.VersionCmd)
rootCmd.AddCommand(app.NewKeyCmd)
rootCmd.AddCommand(app.UpdateCmd)
rootCmd.AddCommand(app.DevCmd)
rootCmd.AddCommand(app.NewDomainCmd)
rootCmd.AddCommand(app.InstallCmd)
rootCmd.AddCommand(app.CertCmd)
rootCmd.AddCommand(app.DaemonCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

230
app/commands.go Normal file
View File

@@ -0,0 +1,230 @@
package app
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"git.nevets.tech/Steven/certman/common"
"github.com/spf13/cobra"
)
var (
VersionCmd = basicCmd("version", "Show version", versionCmd)
NewKeyCmd = basicCmd("gen-key", "Generates encryption key", GenKeyCmd)
UpdateCmd = basicCmd("update", "Updates if new version is found", updateCmd)
DevCmd = basicCmd("dev", "Dev Function", devCmd)
domainCertDir string
NewDomainCmd = &cobra.Command{
Use: "new-domain",
Short: "Create config and directories for new domain",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
dirOverridden := cmd.Flags().Changed("dir")
return newDomainCmd(args[0], domainCertDir, dirOverridden)
},
}
modeFlag string
thinInstallFlag bool
InstallCmd = &cobra.Command{
Use: "install",
Short: "Create certman files and directories",
RunE: func(cmd *cobra.Command, args []string) error {
switch modeFlag {
case "server", "client":
return installCmd(thinInstallFlag, modeFlag)
default:
return fmt.Errorf("invalid --mode %q (must be server or client)", modeFlag)
}
},
}
)
func init() {
NewDomainCmd.Flags().StringVar(&domainCertDir, "dir", "/var/local/certman/certificates/", "Alternate directory for certificates")
InstallCmd.Flags().StringVar(&modeFlag, "mode", "client", "CertManager mode [server, client]")
InstallCmd.Flags().BoolVarP(&thinInstallFlag, "thin", "t", false, "Thin install (skip creating dirs)")
}
func devCmd(cmd *cobra.Command, args []string) {
//testDomain := "lunamc.org"
//err := LoadConfig()
//if err != nil {
// log.Fatalf("Error loading configuration: %v\n", err)
//}
//err = LoadDomainConfigs()
//if err != nil {
// log.Fatalf("Error loading configs: %v\n", err)
//}
//
//fmt.Println(testDomain)
}
func versionCmd(cmd *cobra.Command, args []string) {
fmt.Printf("CertManager (certman) - Steven Tracey\nVersion: %s build-%s\n",
common.Version, common.Build,
)
}
func GenKeyCmd(cmd *cobra.Command, args []string) {
key, err := common.GenerateKey()
if err != nil {
log.Fatalf("%v", err)
}
fmt.Printf(key)
}
func updateCmd(cmd *cobra.Command, args []string) {
if os.Geteuid() != 0 {
log.Fatal(fmt.Errorf("installation must be run as root"))
}
err := LoadConfig()
if err != nil {
log.Fatalf("%v", err)
}
resp, err := http.Get(SourceCertmanRepo + "/latest")
if err != nil {
log.Fatalf("%v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
var release GiteaRelease
err = json.Unmarshal(body, &release)
if err != nil {
log.Fatalf("%v", err)
}
for _, asset := range release.Assets {
if strings.Contains(asset.Name, Config().App.Mode) {
if !strings.Contains(asset.Name, common.Version) {
fmt.Printf("Found a newer version: %s\n", asset.Name)
err = downloadFile("/usr/local/bin/certman", SourceCertmanRepo+"/"+strconv.Itoa(release.Id)+"/assets/"+strconv.Itoa(asset.Id))
if err != nil {
log.Fatalf("%v", err)
}
}
}
}
}
func newDomainCmd(domain, domainDir string, dirOverridden bool) error {
//TODO add config option for "overridden dir"
if !common.IsValidFQDN(domain) {
return fmt.Errorf("invalid FQDN: %q", domain)
}
err := LoadConfig()
if err != nil {
return err
}
fmt.Printf("Creating new domain %s\n", domain)
err = CreateDomainConfig(domain)
if err != nil {
return err
}
CreateDomainCertsDir(domain, domainDir, dirOverridden)
certmanUser, err := user.Lookup("certman")
if err != nil {
return fmt.Errorf("error getting user certman: %v", err)
}
uid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Uid))
if err != nil {
return err
}
gid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Gid))
if err != nil {
return err
}
err = common.ChownRecursive("/etc/certman/domains", uid, gid)
if err != nil {
return err
}
err = common.ChownRecursive("/var/local/certman", uid, gid)
if err != nil {
return err
}
fmt.Println("Successfully created domain entry for " + domain + "\nUpdate config file as needed in /etc/certman/domains/" + domain + ".conf\n")
return nil
}
func installCmd(isThin bool, mode string) error {
if !isThin {
if os.Geteuid() != 0 {
return fmt.Errorf("installation must be run as root")
}
MakeDirs()
CreateConfig(mode)
err := LoadConfig()
if err != nil {
return err
}
f, err := os.OpenFile("/var/run/certman.pid", os.O_RDONLY|os.O_CREATE, 0755)
if err != nil {
return fmt.Errorf("error creating pid file: %v", err)
}
err = f.Close()
if err != nil {
return fmt.Errorf("error closing pid file: %v", err)
}
newUserCmd := exec.Command("useradd", "-d", "/var/local/certman", "-U", "-r", "-s", "/sbin/nologin", "certman")
if output, err := newUserCmd.CombinedOutput(); err != nil {
if !strings.Contains(err.Error(), "exit status 9") {
return fmt.Errorf("error creating user: %v: output %s", err, output)
}
}
newGroupCmd := exec.Command("groupadd", "-r", "-U", "certman", "certsock")
if output, err := newGroupCmd.CombinedOutput(); err != nil {
if !strings.Contains(err.Error(), "exit status 9") {
return fmt.Errorf("error creating group: %v: output %s", err, output)
}
}
//TODO chmod after chown
uid, gid, err := GetUserIds("certman")
if err != nil {
return err
}
err = common.ChownRecursive("/etc/certman", uid, gid)
if err != nil {
return fmt.Errorf("error changing uid/gid: %v", err)
}
err = common.ChownRecursive("/var/local/certman", uid, gid)
if err != nil {
return fmt.Errorf("error changing uid/gid: %v", err)
}
err = os.Chown("/var/run/certman.pid", uid, gid)
if err != nil {
return fmt.Errorf("error changing uid/gid: %v", err)
}
} else {
CreateConfig(mode)
}
//TODO move executable to /usr/bin
//execPath, err := os.Executable()
//if err != nil {
// return err
//}
return nil
}

View File

@@ -1,7 +1,6 @@
package internal
package app
import (
"bytes"
"errors"
"fmt"
"log"
@@ -10,8 +9,9 @@ import (
"strings"
"sync"
pb "git.nevets.tech/Keys/CertManager/proto/v1"
"git.nevets.tech/Steven/certman/common"
"github.com/google/uuid"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
)
@@ -20,42 +20,46 @@ var (
ErrConfigNotFound = errors.New("config file not found")
)
type DomainConfigStore struct {
// ---------------------------------------------------------------------------
// Generic domain config store
// ---------------------------------------------------------------------------
type DomainConfigStore[T any] struct {
mu sync.RWMutex
configs map[string]*viper.Viper
configs map[string]*T
}
func NewDomainConfigStore() *DomainConfigStore {
return &DomainConfigStore{
configs: make(map[string]*viper.Viper),
func NewDomainConfigStore[T any]() *DomainConfigStore[T] {
return &DomainConfigStore[T]{
configs: make(map[string]*T),
}
}
func (s *DomainConfigStore) Get(domain string) (*viper.Viper, bool) {
func (s *DomainConfigStore[T]) Get(domain string) (*T, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.configs[domain]
return v, ok
}
func (s *DomainConfigStore) Set(domain string, v *viper.Viper) {
func (s *DomainConfigStore[T]) Set(domain string, v *T) {
s.mu.Lock()
defer s.mu.Unlock()
s.configs[domain] = v
}
// Swap atomically replaces the entire config map (used during reload).
func (s *DomainConfigStore) Swap(newConfigs map[string]*viper.Viper) {
func (s *DomainConfigStore[T]) Swap(newConfigs map[string]*T) {
s.mu.Lock()
defer s.mu.Unlock()
s.configs = newConfigs
}
// Snapshot returns a shallow copy safe to iterate without holding the lock.
func (s *DomainConfigStore) Snapshot() map[string]*viper.Viper {
func (s *DomainConfigStore[T]) Snapshot() map[string]*T {
s.mu.RLock()
defer s.mu.RUnlock()
snap := make(map[string]*viper.Viper, len(s.configs))
snap := make(map[string]*T, len(s.configs))
for k, v := range s.configs {
snap[k] = v
}
@@ -67,21 +71,24 @@ func (s *DomainConfigStore) Snapshot() map[string]*viper.Viper {
// ---------------------------------------------------------------------------
var (
config *viper.Viper
configMu sync.RWMutex
domainStore = NewDomainConfigStore()
config *common.AppConfig
configMu sync.RWMutex
serverDomainStore = NewDomainConfigStore[common.ServerDomainConfig]()
clientDomainStore = NewDomainConfigStore[common.ClientDomainConfig]()
)
func Config() *viper.Viper {
func Config() *common.AppConfig {
configMu.RLock()
defer configMu.RUnlock()
return config
}
func DomainStore() *DomainConfigStore {
domainStore.mu.RLock()
defer domainStore.mu.RUnlock()
return domainStore
func ServerDomainStore() *DomainConfigStore[common.ServerDomainConfig] {
return serverDomainStore
}
func ClientDomainStore() *DomainConfigStore[common.ClientDomainConfig] {
return clientDomainStore
}
// ---------------------------------------------------------------------------
@@ -90,37 +97,37 @@ func DomainStore() *DomainConfigStore {
// LoadConfig reads the main certman.conf into config.
func LoadConfig() error {
config = viper.New()
config.SetConfigFile("/etc/certman/certman.conf")
config.SetConfigType("toml")
err := config.ReadInConfig()
if err != nil {
vConfig := viper.New()
vConfig.SetConfigFile("/etc/certman/certman.conf")
vConfig.SetConfigType("toml")
if err := vConfig.ReadInConfig(); err != nil {
return err
}
switch config.GetString("App.mode") {
case "server":
config.SetConfigType("toml")
config.SetConfigFile("server.conf")
return config.MergeInConfig()
case "Client":
config.SetConfigType("toml")
config.SetConfigFile("Client.conf")
return config.MergeInConfig()
if vConfig.GetString("App.mode") == "server" {
vConfig.SetConfigType("toml")
vConfig.SetConfigFile("/etc/certman/server.conf")
if err := vConfig.MergeInConfig(); err != nil {
return err
}
}
if err := vConfig.Unmarshal(&config); err != nil {
return err
}
return nil
}
// LoadDomainConfigs reads every .conf file in the domains directory.
func LoadDomainConfigs() error {
// loadDomainConfigs walks /etc/certman/domains and unmarshals every .conf file
// into T, keyed by domain.domain_name.
func loadDomainConfigs[T any]() (map[string]*T, error) {
dir := "/etc/certman/domains/"
entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("reading domain config dir: %w", err)
return nil, fmt.Errorf("reading domain config dir: %w", err)
}
temp := make(map[string]*viper.Viper)
out := make(map[string]*T)
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".conf" {
@@ -133,22 +140,47 @@ func LoadDomainConfigs() error {
v.SetConfigType("toml")
if err := v.ReadInConfig(); err != nil {
return fmt.Errorf("loading %s: %w", path, err)
return nil, fmt.Errorf("loading %s: %w", path, err)
}
domain := v.GetString("domain.domain_name")
if domain == "" {
return fmt.Errorf("%s: missing domain.domain_name", path)
return nil, fmt.Errorf("%s: missing domain.domain_name", path)
}
if _, exists := temp[domain]; exists {
if _, exists := out[domain]; exists {
fmt.Printf("Duplicate domain in %s, skipping...\n", path)
continue
}
temp[domain] = v
cfg := new(T)
if err = v.Unmarshal(cfg); err != nil {
return nil, fmt.Errorf("unmarshaling %s: %w", path, err)
}
out[domain] = cfg
}
domainStore.Swap(temp)
return out, nil
}
// LoadServerDomainConfigs reads every .conf file in the domains directory into
// the server-typed store.
func LoadServerDomainConfigs() error {
configs, err := loadDomainConfigs[common.ServerDomainConfig]()
if err != nil {
return err
}
serverDomainStore.Swap(configs)
return nil
}
// LoadClientDomainConfigs reads every .conf file in the domains directory into
// the client-typed store.
func LoadClientDomainConfigs() error {
configs, err := loadDomainConfigs[common.ClientDomainConfig]()
if err != nil {
return err
}
clientDomainStore.Swap(configs)
return nil
}
@@ -156,109 +188,56 @@ func LoadDomainConfigs() error {
// Saving
// ---------------------------------------------------------------------------
func WriteConfig(filePath string, config *viper.Viper) error {
var buf bytes.Buffer
if err := config.WriteConfigTo(&buf); err != nil {
return fmt.Errorf("marshal config: %w", err)
func WriteConfig(filePath string, config *common.AppConfig) error {
buf, err := toml.Marshal(&config)
if err != nil {
return fmt.Errorf("marshaling config: %w", err)
}
if err = os.WriteFile(filePath, buf, 0640); err != nil {
return fmt.Errorf("write config file: %w", err)
}
if err := os.WriteFile(filePath, buf.Bytes(), 0640); err != nil {
return nil
}
func writeDomainConfigFile(domainName string, v any) error {
buf, err := toml.Marshal(v)
if err != nil {
return fmt.Errorf("marshaling domain config: %w", err)
}
configPath := filepath.Join("/etc/certman/domains", domainName+".conf")
if err = os.WriteFile(configPath, buf, 0640); err != nil {
return fmt.Errorf("write config file: %w", err)
}
return nil
}
func WriteMainConfig() error {
return WriteConfig("/etc/certman/certman.conf", config)
func WriteServerDomainConfig(config *common.ServerDomainConfig) error {
return writeDomainConfigFile(config.Domain.DomainName, config)
}
func WriteDomainConfig(config *viper.Viper) error {
return WriteConfig(config.GetString("Domain.domain_name"), config)
func WriteClientDomainConfig(config *common.ClientDomainConfig) error {
return writeDomainConfigFile(config.Domain.DomainName, config)
}
// SaveDomainConfigs writes every loaded domain config back to disk.
func SaveDomainConfigs() error {
for domain, v := range domainStore.Snapshot() {
err := WriteConfig("/etc/certman/domains/"+domain+".conf", v)
if err != nil {
// SaveServerDomainConfigs writes every loaded server domain config back to disk.
func SaveServerDomainConfigs() error {
for _, v := range serverDomainStore.Snapshot() {
if err := WriteServerDomainConfig(v); err != nil {
return err
}
}
return nil
}
// ---------------------------------------------------------------------------
// Domain Specific Lookups
// ---------------------------------------------------------------------------
func PostPullHooks(domain string) ([]*pb.Hook, error) {
var hooks []*pb.Hook
if err := viper.UnmarshalKey("Hooks.PostPull", hooks); err != nil {
return nil, err
}
return hooks, nil
}
// ---------------------------------------------------------------------------
// Effective lookups (domain → global fallback)
// ---------------------------------------------------------------------------
// EffectiveString looks up a key in the domain config first, falling back to
// the global config. Keys use dot notation matching INI sections, e.g.
// "certificates.data_root".
func EffectiveString(domainCfg *viper.Viper, key string) (string, error) {
if domainCfg != nil {
val := strings.TrimSpace(domainCfg.GetString(key))
if val != "" {
return val, nil
// SaveClientDomainConfigs writes every loaded client domain config back to disk.
func SaveClientDomainConfigs() error {
for _, v := range clientDomainStore.Snapshot() {
if err := WriteClientDomainConfig(v); err != nil {
return err
}
}
if config == nil {
return "", ErrConfigNotFound
}
val := strings.TrimSpace(config.GetString(key))
if val == "" {
return "", ErrBlankConfigEntry
}
return val, nil
}
// MustEffectiveString is like EffectiveString but logs a fatal error on failure.
func MustEffectiveString(domainCfg *viper.Viper, key string) string {
val, err := EffectiveString(domainCfg, key)
if err != nil {
log.Fatalf("Config key %q: %v", key, err)
}
return val
}
// EffectiveInt returns an int with domain → global fallback. Returns the
// fallback value if the key is missing or zero in both configs.
func EffectiveInt(domainCfg *viper.Viper, key string, fallback int) int {
if domainCfg != nil {
if val := domainCfg.GetInt(key); val != 0 {
return val
}
}
if config != nil {
if val := config.GetInt(key); val != 0 {
return val
}
}
return fallback
}
// EffectiveBool returns a bool with domain → global fallback.
func EffectiveBool(domainCfg *viper.Viper, key string) bool {
if domainCfg != nil && domainCfg.IsSet(key) {
return domainCfg.GetBool(key)
}
if config != nil {
return config.GetBool(key)
}
return false
return nil
}
// ---------------------------------------------------------------------------
@@ -298,13 +277,14 @@ func CreateConfig(mode string) {
}
func CreateDomainConfig(domain string) error {
key, err := GenerateKey()
key, err := common.GenerateKey()
if err != nil {
return fmt.Errorf("unable to generate key: %v", err)
}
localConfig := Config()
var content string
switch Config().GetString("App.mode") {
switch localConfig.App.Mode {
case "server":
content = strings.NewReplacer(
"{domain}", domain,
@@ -316,7 +296,7 @@ func CreateDomainConfig(domain string) error {
"{key}", key,
).Replace(defaultClientDomainConfig)
default:
return fmt.Errorf("unknown certman mode: %v", Config().GetString("App.mode"))
return fmt.Errorf("unknown certman mode: %v", localConfig.App.Mode)
}
path := filepath.Join("/etc/certman/domains", domain+".conf")
@@ -341,10 +321,6 @@ func CreateDomainCertsDir(domain string, dir string, dirOverride bool) {
}
}
// ---------------------------------------------------------------------------
// Default config templates
// ---------------------------------------------------------------------------
const defaultConfig = `[App]
mode = '{mode}'
tick_rate = 2
@@ -365,21 +341,13 @@ uuid = '{uuid}'
[Certificates]
email = 'User@example.com'
data_root = '/var/local/certman'
ca_dir_url = 'https://acme-v02.api.letsencrypt.org/directory'
[Cloudflare]
cf_email = 'email@example.com'
cf_api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'`
const defaultClientConfig = ``
const defaultServerDomainConfig = `[Domain]
domain_name = '{domain}'
enabled = true
dns_server = 'default'
[Certificates]
const defaultServerDomainConfig = `[Certificates]
data_root = ''
expiry = 90
request_method = 'dns-01'
@@ -387,6 +355,11 @@ renew_period = 30
subdomains = []
crypto_key = '{key}'
[Domain]
domain_name = '{domain}'
enabled = true
dns_server = 'default'
[Repo]
repo_suffix = '-certificates'
@@ -415,5 +388,3 @@ env = { "FOO" = "bar" }
[Repo]
repo_suffix = '-certificates'
`
const readme = ``

117
app/cryptr/main.go Normal file
View File

@@ -0,0 +1,117 @@
package main
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"os"
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: "cryptr",
Short: "cryptr is a tool for encrypting and decrypting files",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
rootCmd.AddCommand(&cobra.Command{
Use: "key-gen",
Short: "Generates encryption key",
Run: app.GenKeyCmd,
})
var (
keyUTF8 bool
keyFile string
)
encryptCmd := &cobra.Command{
Use: "encrypt",
Short: "encrypt a file",
RunE: func(cmd *cobra.Command, args []string) error {
key, err := getKey(keyFile, keyUTF8)
if err != nil {
return err
}
fmt.Println(key)
inFilePath := args[0]
outFilePath := args[1]
return common.EncryptFileXChaCha(key, inFilePath, outFilePath, nil)
},
}
encryptCmd.Flags().BoolVar(&keyUTF8, "utf8", false, "Use UTF-8 encoded key")
encryptCmd.Flags().StringVar(&keyFile, "key", "", "File containing key")
rootCmd.AddCommand(encryptCmd)
decryptCmd := &cobra.Command{
Use: "decrypt",
Short: "decrypt a file",
RunE: func(cmd *cobra.Command, args []string) error {
key, err := getKey(keyFile, keyUTF8)
if err != nil {
return err
}
inFilePath := args[0]
outFilePath := args[1]
inFile, err := os.ReadFile(inFilePath)
if err != nil {
return err
}
return common.DecryptFileFromBytes(key, inFile, outFilePath, nil)
},
}
decryptCmd.Flags().BoolVar(&keyUTF8, "utf8", false, "Use UTF-8 encoded key")
decryptCmd.Flags().StringVar(&keyFile, "key", "", "File containing key")
rootCmd.AddCommand(decryptCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func normalizeKey(b []byte) []byte {
out := make([]byte, 32)
copy(out, b)
return out
}
func getKey(keyFile string, keyUTF8 bool) (string, error) {
var raw []byte
if keyFile != "" {
b, err := os.ReadFile(keyFile)
if err != nil {
return "", err
}
raw = b
} else {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Key: ")
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return "", err
}
}
raw = scanner.Bytes()
}
var keyBytes []byte
if keyUTF8 {
keyBytes = normalizeKey(bytes.TrimSpace(raw))
} else {
decoded, err := base64.StdEncoding.DecodeString(string(bytes.TrimSpace(raw)))
if err != nil {
return "", fmt.Errorf("key is not valid base64: %w", err)
}
keyBytes = normalizeKey(decoded)
}
return base64.StdEncoding.EncodeToString(keyBytes), nil
}

View File

@@ -1,4 +1,4 @@
package commands
package app
import (
"context"
@@ -10,21 +10,73 @@ import (
"syscall"
"time"
"git.nevets.tech/Keys/CertManager/client"
"git.nevets.tech/Keys/CertManager/internal"
"git.nevets.tech/Keys/CertManager/server"
"git.nevets.tech/Steven/certman/common"
"github.com/spf13/cobra"
)
type Daemon interface {
Init()
Tick()
Reload()
Stop()
}
var (
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
DaemonCmd = &cobra.Command{
Use: "daemon",
Short: "Daemon management",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
)
func RunDaemonCmd() error {
err := internal.CreateOrUpdatePIDFile("/var/run/certman.pid")
func init() {
DaemonCmd.AddCommand(&cobra.Command{
Use: "stop",
Short: "stop the daemon",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return stopDaemonCmd()
},
})
DaemonCmd.AddCommand(&cobra.Command{
Use: "reload",
Short: "reload daemon configs",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return reloadDaemonCmd()
},
})
DaemonCmd.AddCommand(&cobra.Command{
Use: "tick",
Short: "Manually triggers daemon tick",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return tickDaemonCmd()
},
})
DaemonCmd.AddCommand(&cobra.Command{
Use: "status",
Short: "Show daemon status",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return daemonStatusCmd()
},
})
}
func RunDaemonCmd(daemon Daemon) error {
err := common.CreateOrUpdatePIDFile("/var/run/certman.pid")
if err != nil {
if errors.Is(err, internal.ErrorPIDInUse) {
if errors.Is(err, common.ErrorPIDInUse) {
return fmt.Errorf("daemon process is already running")
}
return fmt.Errorf("error creating pidfile: %v", err)
@@ -38,10 +90,11 @@ func RunDaemonCmd() error {
} else if err != nil {
return fmt.Errorf("error opening /etc/certman/certman.conf: %v", err)
}
err = internal.LoadConfig()
err = LoadConfig()
if err != nil {
return fmt.Errorf("error loading configuration: %v", err)
}
localConfig := Config()
// Setup SIGINT and SIGTERM listeners
sigChannel := make(chan os.Signal, 1)
@@ -56,54 +109,28 @@ func RunDaemonCmd() error {
signal.Notify(tickSigChan, syscall.SIGUSR1)
defer signal.Stop(tickSigChan)
tickRate := internal.Config().GetInt("App.tick_rate")
tickRate := localConfig.App.TickRate
ticker := time.NewTicker(time.Duration(tickRate) * time.Hour)
defer ticker.Stop()
wg.Add(1)
if internal.Config().GetString("App.mode") == "server" {
fmt.Println("Starting CertManager in server mode...")
// Server Task loop
go func() {
server.Init()
defer wg.Done()
for {
select {
case <-ctx.Done():
server.Stop()
return
case <-reloadSigChan:
server.Reload()
case <-ticker.C:
server.Tick()
case <-tickSigChan:
server.Tick()
}
go func() {
daemon.Init()
defer wg.Done()
for {
select {
case <-ctx.Done():
daemon.Stop()
return
case <-reloadSigChan:
daemon.Reload()
case <-ticker.C:
daemon.Tick()
case <-tickSigChan:
daemon.Tick()
}
}()
} else if internal.Config().GetString("App.mode") == "client" {
fmt.Println("Starting CertManager in client mode...")
// Client Task loop
go func() {
client.Init()
defer wg.Done()
for {
select {
case <-ctx.Done():
client.Stop()
return
case <-reloadSigChan:
client.Reload()
case <-ticker.C:
client.Tick()
case <-tickSigChan:
client.Tick()
}
}
}()
} else {
return fmt.Errorf("invalid operating mode \"" + internal.Config().GetString("App.mode") + "\"")
}
}
}()
// Cleanup on stop
sig := <-sigChannel
@@ -116,11 +143,11 @@ func RunDaemonCmd() error {
func stop() {
cancel()
internal.ClearPIDFile()
common.ClearPIDFile()
}
func StopDaemonCmd() error {
proc, err := internal.DaemonProcess()
func stopDaemonCmd() error {
proc, err := common.DaemonProcess()
if err != nil {
return fmt.Errorf("error getting daemon process: %v", err)
}
@@ -132,8 +159,8 @@ func StopDaemonCmd() error {
return nil
}
func ReloadDaemonCmd() error {
proc, err := internal.DaemonProcess()
func reloadDaemonCmd() error {
proc, err := common.DaemonProcess()
if err != nil {
return fmt.Errorf("error getting daemon process: %v", err)
}
@@ -145,8 +172,8 @@ func ReloadDaemonCmd() error {
return nil
}
func TickDaemonCmd() error {
proc, err := internal.DaemonProcess()
func tickDaemonCmd() error {
proc, err := common.DaemonProcess()
if err != nil {
return fmt.Errorf("error getting daemon process: %v", err)
}
@@ -158,7 +185,7 @@ func TickDaemonCmd() error {
return nil
}
func DaemonStatusCmd() error {
func daemonStatusCmd() error {
fmt.Println("Not implemented :/")
return nil
}

View File

@@ -1,4 +1,4 @@
package commands
package main
import (
"fmt"
@@ -6,13 +6,23 @@ import (
"os/signal"
"syscall"
"git.nevets.tech/Keys/CertManager/executor"
"github.com/spf13/cobra"
)
var executorServer *executor.Server
var (
executorServer *Server
func StartExecutorCmd() error {
executorServer = &executor.Server{}
ExecutorCmd = &cobra.Command{
Use: "executor",
Short: "Privileged daemon",
RunE: func(cmd *cobra.Command, args []string) error {
return startExecutorCmd()
},
}
)
func startExecutorCmd() error {
executorServer = &Server{}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

View File

@@ -1,11 +1,11 @@
package executor
package main
import (
"fmt"
"net"
"sync"
pb "git.nevets.tech/Keys/CertManager/proto/v1"
pb "git.nevets.tech/Steven/certman/proto/v1"
"github.com/coreos/go-systemd/v22/activation"
"google.golang.org/grpc"
)

View File

@@ -1,4 +1,4 @@
package executor
package main
import (
"context"
@@ -8,8 +8,8 @@ import (
"syscall"
"time"
"git.nevets.tech/Keys/CertManager/internal"
pb "git.nevets.tech/Keys/CertManager/proto/v1"
"git.nevets.tech/Steven/certman/common"
pb "git.nevets.tech/Steven/certman/proto/v1"
)
type hookServer struct {
@@ -51,7 +51,7 @@ func (s *hookServer) ExecuteHook(ctx context.Context, req *pb.ExecuteHookRequest
// Run as user/group if specified (Linux/Unix)
if h.GetUser() != "" || h.GetGroup() != "" {
cred, err := internal.MakeCredential(h.GetUser(), h.GetGroup())
cred, err := common.MakeCredential(h.GetUser(), h.GetGroup())
if err != nil {
return &pb.ExecuteHookResponse{Error: brief(err)}, nil
}

7
app/executor/main.go Normal file
View File

@@ -0,0 +1,7 @@
package main
import "fmt"
func main() {
fmt.Println("Hello Executor")
}

View File

@@ -1,4 +1,4 @@
package executor
package main
import "fmt"

125
app/server/certs.go Normal file
View File

@@ -0,0 +1,125 @@
package main
import (
"fmt"
"path/filepath"
"time"
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common"
"git.nevets.tech/Steven/certman/server"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/spf13/cobra"
)
var (
noPush bool
renewCertSubCmd = &cobra.Command{
Use: "renew",
Short: "Renews a domains certificate",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return renewCertCmd(args[0], noPush)
},
}
)
func init() {
renewCertSubCmd.Flags().BoolVar(&noPush, "no-push", false, "Don't push certs to repo, renew locally only [server mode only]")
app.CertCmd.AddCommand(renewCertSubCmd)
}
func renewCertCmd(domain string, noPush bool) error {
if err := app.LoadConfig(); err != nil {
return err
}
if err := app.LoadServerDomainConfigs(); err != nil {
return err
}
mgr, err := server.NewACMEManager(app.Config())
if err != nil {
return err
}
err = renewCerts(domain, noPush, mgr)
if err != nil {
return err
}
// return ReloadDaemonCmd() // Not sure if this is necessary
return nil
}
func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
config := app.Config()
domainConfig, exists := app.ServerDomainStore().Get(domain)
if !exists {
return fmt.Errorf("domain %s does not exist", domain)
}
_, err := mgr.RenewForDomain(domainConfig)
if err != nil {
// if no existing cert, obtain instead
_, err = mgr.ObtainForDomain(config, domainConfig)
if err != nil {
return fmt.Errorf("error obtaining domain certificates for domain %s: %v", domain, err)
}
}
domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
err = app.WriteServerDomainConfig(domainConfig)
if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err)
}
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(mgr.CertsRoot, domain, domain+".crt"), filepath.Join(mgr.CertsRoot, domain, domain+".crt.crpt"), nil)
if err != nil {
return fmt.Errorf("error encrypting domain cert for domain %s: %v", domain, err)
}
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(mgr.CertsRoot, domain, domain+".key"), filepath.Join(mgr.CertsRoot, domain, domain+".key.crpt"), nil)
if err != nil {
return fmt.Errorf("error encrypting domain key for domain %s: %v", domain, err)
}
if !noPush {
giteaClient := common.CreateGiteaClient(config)
if giteaClient == nil {
return fmt.Errorf("error creating gitea client for domain %s: %v", domain, err)
}
gitWorkspace := &common.GitWorkspace{
Storage: memory.NewStorage(),
FS: memfs.New(),
}
if !domainConfig.Internal.RepoExists {
gitWorkspace.URL = common.CreateGiteaRepo(domain, giteaClient, config, domainConfig)
if gitWorkspace.URL == "" {
return fmt.Errorf("error creating Gitea repo for domain %s", domain)
}
domainConfig.Internal.RepoExists = true
err = app.WriteServerDomainConfig(domainConfig)
if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err)
}
err = gitWorkspace.InitRepo()
if err != nil {
return fmt.Errorf("error initializing repo for domain %s: %v", domain, err)
}
} else {
gitWorkspace.URL = config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git"
err = gitWorkspace.CloneRepo(common.Server, config)
if err != nil {
return fmt.Errorf("error cloning repo for domain %s: %v", domain, err)
}
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = server.AddAndPushCerts(gitWorkspace, dataRoot, domainConfig.Repo.RepoSuffix, config)
if err != nil {
return fmt.Errorf("error pushing certificates for domain %s: %v", domain, err)
}
fmt.Printf("Successfully pushed certificates for domain %s\n", domain)
}
return nil
}

17
app/server/commands.go Normal file
View File

@@ -0,0 +1,17 @@
package main
import (
"git.nevets.tech/Steven/certman/app"
"github.com/spf13/cobra"
)
func init() {
app.DaemonCmd.AddCommand(&cobra.Command{
Use: "start",
Short: "Start the daemon",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return app.RunDaemonCmd(&Daemon{})
},
})
}

175
app/server/daemon.go Normal file
View File

@@ -0,0 +1,175 @@
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
appShared "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common"
"git.nevets.tech/Steven/certman/server"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
)
type Daemon struct {
ACMEManager *server.ACMEManager
TickMu sync.Mutex
MgrMu sync.Mutex
}
func (d *Daemon) loadACMEManager() error {
d.MgrMu.Lock()
defer d.MgrMu.Unlock()
if d.ACMEManager == nil {
var err error
d.ACMEManager, err = server.NewACMEManager(appShared.Config())
if err != nil {
return err
}
}
return nil
}
func (d *Daemon) Init() {
fmt.Println("Starting CertManager in server mode...")
err := appShared.LoadServerDomainConfigs()
if err != nil {
log.Fatalf("Error loading domain configs: %v", err)
}
d.Tick()
}
func (d *Daemon) Tick() {
d.TickMu.Lock()
defer d.TickMu.Unlock()
fmt.Println("Tick!")
if err := d.loadACMEManager(); err != nil {
fmt.Printf("Error getting acme manager: %v\n", err)
return
}
now := time.Now().UTC()
config := appShared.Config()
localDomainConfigs := appShared.ServerDomainStore().Snapshot()
for domainStr, domainConfig := range localDomainConfigs {
if !domainConfig.Domain.Enabled {
continue
}
//TODO: have renewPeriod logic default to use certificate expiry if available
renewPeriod := domainConfig.Certificates.RenewPeriod
lastIssued := time.Unix(domainConfig.Internal.LastIssued, 0).UTC()
renewalDue := lastIssued.AddDate(0, 0, renewPeriod)
if now.After(renewalDue) {
//TODO extra check if certificate expiry (create cache?)
_, err := d.ACMEManager.RenewForDomain(domainConfig)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// if no existing cert, obtain instead
_, err = d.ACMEManager.ObtainForDomain(appShared.Config(), domainConfig)
if err != nil {
fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err)
continue
}
}
fmt.Printf("Error: %v\n", err)
continue
}
domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
err = appShared.WriteServerDomainConfig(domainConfig)
if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue
}
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".crt"), filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".crt.crpt"), nil)
if err != nil {
fmt.Printf("Error encrypting domain cert for domain %s: %v\n", domainStr, err)
continue
}
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".key"), filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".key.crpt"), nil)
if err != nil {
fmt.Printf("Error encrypting domain key for domain %s: %v\n", domainStr, err)
continue
}
giteaClient := common.CreateGiteaClient(config)
if giteaClient == nil {
fmt.Printf("Error creating gitea client for domain %s: %v\n", domainStr, err)
continue
}
gitWorkspace := &common.GitWorkspace{
Storage: memory.NewStorage(),
FS: memfs.New(),
}
if !domainConfig.Internal.RepoExists {
gitWorkspace.URL = common.CreateGiteaRepo(domainStr, giteaClient, config, domainConfig)
if gitWorkspace.URL == "" {
fmt.Printf("Error creating Gitea repo for domain %s\n", domainStr)
continue
}
domainConfig.Internal.RepoExists = true
err = appShared.WriteServerDomainConfig(domainConfig)
if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue
}
err = gitWorkspace.InitRepo()
if err != nil {
fmt.Printf("Error initializing repo for domain %s: %v\n", domainStr, err)
continue
}
} else {
gitWorkspace.URL = appShared.Config().Git.Server + "/" + appShared.Config().Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git"
err = gitWorkspace.CloneRepo(common.Server, config)
if err != nil {
fmt.Printf("Error cloning repo for domain %s: %v\n", domainStr, err)
continue
}
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = server.AddAndPushCerts(gitWorkspace, dataRoot, domainConfig.Repo.RepoSuffix, config)
if err != nil {
fmt.Printf("Error pushing certificates for domain %s: %v\n", domainStr, err)
continue
}
fmt.Printf("Successfully pushed certificates for domain %s\n", domainStr)
}
}
if err := appShared.SaveServerDomainConfigs(); err != nil {
fmt.Printf("Error saving domain configs: %v\n", err)
}
}
func (d *Daemon) Reload() {
fmt.Println("Reloading configs...")
err := appShared.LoadServerDomainConfigs()
if err != nil {
fmt.Printf("Error loading domain configs: %v\n", err)
return
}
d.MgrMu.Lock()
d.ACMEManager = nil
d.MgrMu.Unlock()
fmt.Println("Successfully reloaded configs")
}
func (d *Daemon) Stop() {
fmt.Println("Shutting down server")
}

38
app/server/main.go Normal file
View File

@@ -0,0 +1,38 @@
package main
import (
"fmt"
"os"
"git.nevets.tech/Steven/certman/app"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: "certman",
Short: "CertMan",
Long: "Certificate Manager",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
rootCmd.AddCommand(app.VersionCmd)
rootCmd.AddCommand(app.NewKeyCmd)
rootCmd.AddCommand(app.UpdateCmd)
rootCmd.AddCommand(app.DevCmd)
rootCmd.AddCommand(app.NewDomainCmd)
//-----------------------------------
rootCmd.AddCommand(app.InstallCmd)
rootCmd.AddCommand(app.CertCmd)
rootCmd.AddCommand(app.DaemonCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

130
app/util.go Normal file
View File

@@ -0,0 +1,130 @@
package app
import (
"fmt"
"io"
"net/http"
"os"
"os/user"
"strconv"
"strings"
"github.com/spf13/cobra"
)
var SourceCertmanRepo = "http://127.0.0.1"
type GiteaRelease struct {
Id int `json:"id"`
Assets []Asset `json:"assets"`
}
type Asset struct {
Id int `json:"id"`
Name string `json:"name"`
}
func GetUserIds(username string) (int, int, error) {
userEntry, err := user.Lookup(username)
if err != nil {
return -1, -1, fmt.Errorf("error getting user %s: %v", username, err)
}
uid, err := strconv.Atoi(strings.TrimSpace(userEntry.Uid))
if err != nil {
return -1, -1, err
}
gid, err := strconv.Atoi(strings.TrimSpace(userEntry.Gid))
if err != nil {
return -1, -1, err
}
return uid, gid, nil
}
func createFile(fileName string, filePermission os.FileMode, data []byte) {
fileInfo, err := os.Stat(fileName)
if err != nil {
if os.IsNotExist(err) {
file, err := os.Create(fileName)
if err != nil {
fmt.Println("Error creating configuration file: ", err)
os.Exit(1)
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
fmt.Println("Error writing to file: ", err)
os.Exit(1)
}
err = file.Chmod(filePermission)
if err != nil {
fmt.Println("Error changing file permission: ", err)
}
} else {
fmt.Println("Error opening configuration file: ", err)
os.Exit(1)
}
} else {
if fileInfo.Size() == 0 {
file, err := os.Create(fileName)
if err != nil {
fmt.Println("Error creating configuration file: ", err)
os.Exit(1)
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
fmt.Println("Error writing to file:", err)
os.Exit(1)
}
}
}
}
// downloadFile streams data from a URL and saves it directly to a local file path
func downloadFile(filepath string, url string) error {
// 1. Send the HTTP GET request
resp, err := http.Get(url)
if err != nil {
return err
}
// Always close the response body to prevent resource leaks
defer resp.Body.Close()
// 2. Check for a valid HTTP 200 OK status code
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
// 3. Create the local destination file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
uid, gid, err := GetUserIds("certman")
if err != nil {
return err
}
err = out.Chown(uid, gid)
if err != nil {
return err
}
err = out.Chmod(775)
if err != nil {
return err
}
// 4. Stream the server response body directly into the local file
_, err = io.Copy(out, resp.Body)
return err
}
func basicCmd(use, short string, commandFunc func(cmd *cobra.Command, args []string)) *cobra.Command {
return &cobra.Command{
Use: use,
Short: short,
Run: commandFunc,
}
}

109
client/certificates.go Normal file
View File

@@ -0,0 +1,109 @@
package client
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"git.nevets.tech/Steven/certman/common"
)
func PullCerts(config *common.AppConfig, gitWorkspace *common.GitWorkspace) error {
// Ex: https://git.example.com/Org/Repo-suffix.git
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
err := gitWorkspace.CloneRepo(common.Client, config)
if err != nil {
return fmt.Errorf("Error cloning domain repo %s: %v\n", gitWorkspace.Domain, err)
}
return nil
}
func DecryptAndWriteCertificates(certsDir string, config *common.AppConfig, domainConfig *common.ClientDomainConfig, gitWorkspace *common.GitWorkspace) error {
// Get files in repo
fileInfos, err := gitWorkspace.FS.ReadDir("/")
if err != nil {
return fmt.Errorf("Error reading directory in memFS on domain %s: %v\n", gitWorkspace.Domain, err)
}
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added
for _, fileInfo := range fileInfos {
if strings.HasSuffix(fileInfo.Name(), ".crpt") {
filename, _ := strings.CutSuffix(fileInfo.Name(), ".crpt")
file, err := gitWorkspace.FS.Open(fileInfo.Name())
if err != nil {
fmt.Printf("Error opening file in memFS on domain %s: %v\n", gitWorkspace.Domain, err)
continue
}
fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Printf("Error reading file in memFS on domain %s: %v\n", gitWorkspace.Domain, err)
file.Close()
continue
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file on domain %s: %v\n", gitWorkspace.Domain, err)
continue
}
err = common.DecryptFileFromBytes(domainConfig.Certificates.CryptoKey, fileBytes, filepath.Join(certsDir, filename), nil)
if err != nil {
fmt.Printf("Error decrypting file %s in domain %s: %v\n", filename, gitWorkspace.Domain, err)
continue
}
headRef, err := gitWorkspace.Repo.Head()
if err != nil {
fmt.Printf("Error getting head reference for domain %s: %v\n", gitWorkspace.Domain, err)
continue
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = WriteCommitHash(headRef.Hash().String(), dataRoot)
if err != nil {
fmt.Printf("Error writing commit hash: %v\n", err)
continue
}
}
}
return nil
}
func DecryptCertificates(certPath, cryptoKey string) error {
// Get files in repo
fileInfos, err := os.ReadDir(certPath)
if err != nil {
return fmt.Errorf("error reading directory: %v", err)
}
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added
for _, fileInfo := range fileInfos {
if strings.HasSuffix(fileInfo.Name(), ".crpt") {
filename, _ := strings.CutSuffix(fileInfo.Name(), ".crpt")
file, err := os.OpenFile(fileInfo.Name(), os.O_RDONLY, 0640)
if err != nil {
fmt.Printf("Error opening file: %v\n", err)
continue
}
fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Printf("Error reading file: %v\n", err)
file.Close()
continue
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
continue
}
err = common.DecryptFileFromBytes(cryptoKey, fileBytes, filepath.Join(certPath, filename), nil)
if err != nil {
fmt.Printf("Error decrypting file %s: %v\n", filename, err)
continue
}
}
}
return nil
}

61
client/git.go Normal file
View File

@@ -0,0 +1,61 @@
package client
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"git.nevets.tech/Steven/certman/common"
)
func WriteCommitHash(hash, dataRoot string) error {
//TODO: unfuck this logic, maybe use a domain struct with a flag for non-standard data root?
//var dataRoot string
//if domainConfig.Certificates.DataRoot == "" {
// dataRoot = filepath.Join(config.Certificates.DataRoot, "certificates", domainConfig.Domain.DomainName)
//} else {
// dataRoot = domainConfig.Certificates.DataRoot
//}
err := os.WriteFile(filepath.Join(dataRoot, "hash"), []byte(hash), 0644)
if err != nil {
return err
}
return nil
}
func LocalCommitHash(domain string, certsDir string) (string, error) {
data, err := os.ReadFile(filepath.Join(certsDir, "hash"))
if err != nil {
if !os.IsNotExist(err) {
fmt.Printf("Error reading file for domain %s: %v\n", domain, err)
return "", err
}
}
return strings.TrimSpace(string(data)), nil
}
func RemoteCommitHash(domain string, gitSource common.GitSource, config *common.AppConfig, domainConfig *common.ClientDomainConfig) (string, error) {
switch gitSource {
case common.Gitea:
return getRemoteCommitHashGitea(config.Git.OrgName, domain+domainConfig.Repo.RepoSuffix, "master", config)
default:
fmt.Printf("Unimplemented git source %v\n", gitSource)
return "", errors.New("unimplemented git source")
}
}
func getRemoteCommitHashGitea(org, repo, branchName string, config *common.AppConfig) (string, error) {
giteaClient := common.CreateGiteaClient(config)
branch, _, err := giteaClient.GetRepoBranch(org, repo, branchName)
if err != nil {
fmt.Printf("Error getting repo branch: %v\n", err)
return "", err
}
//TODO catch repo not found as ErrRepoNotInit
return branch.Commit.ID, nil
}

View File

@@ -1,57 +0,0 @@
package client
import (
"context"
"flag"
"fmt"
"log"
"time"
"git.nevets.tech/Keys/CertManager/internal"
pb "git.nevets.tech/Keys/CertManager/proto/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
var (
tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
caFile = flag.String("ca_file", "", "The file containing the CA root cert file")
serverAddr = flag.String("addr", "localhost:50051", "The server address in the format of host:port")
serverHostOverride = flag.String("server_host_override", "x.test.example.com", "The server name used to verify the hostname returned by the TLS handshake")
)
func SendHook(domain string) {
conn, err := grpc.NewClient(
"unix:///run/certman.sock",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewHookServiceClient(conn)
hooks, err := internal.PostPullHooks(domain)
if err != nil {
fmt.Printf("Error getting hooks: %v\n", err)
return
}
for _, hook := range hooks {
sendHook(client, hook)
}
}
func sendHook(client pb.HookServiceClient, hook *pb.Hook) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
res, err := client.ExecuteHook(ctx, &pb.ExecuteHookRequest{Hook: hook})
if err != nil {
fmt.Printf("Error executing hook: %v\n", err)
return
}
if res.GetError() != "" {
fmt.Printf("Error executing hook: %s\n", res.GetError())
}
}

View File

@@ -1,37 +0,0 @@
package commands
import (
"fmt"
"log"
"git.nevets.tech/Keys/CertManager/internal"
"github.com/spf13/cobra"
)
func DevCmd(cmd *cobra.Command, args []string) {
testDomain := "lunamc.org"
err := internal.LoadConfig()
if err != nil {
log.Fatalf("Error loading configuration: %v\n", err)
}
err = internal.LoadDomainConfigs()
if err != nil {
log.Fatalf("Error loading configs: %v\n", err)
}
fmt.Println(testDomain)
}
func VersionCmd(cmd *cobra.Command, args []string) {
fmt.Printf("CertManager (certman) - Steven Tracey\nVersion: %s build-%s\n",
internal.Version, internal.Build,
)
}
func NewKeyCmd(cmd *cobra.Command, args []string) {
key, err := internal.GenerateKey()
if err != nil {
log.Fatalf("%v", err)
}
fmt.Printf(key)
}

View File

@@ -1,266 +0,0 @@
package commands
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"git.nevets.tech/Keys/CertManager/internal"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
)
var mgr *internal.ACMEManager
func RenewCertCmd(domain string, noPush bool, certmanMode internal.CertManMode) error {
err := internal.LoadConfig()
if err != nil {
return err
}
err = internal.LoadDomainConfigs()
if err != nil {
return err
}
switch internal.Config().GetString("App.mode") {
case "server":
mgr, err = internal.NewACMEManager()
if err != nil {
return err
}
err = renewCerts(domain, noPush, certmanMode)
if err != nil {
return err
}
return ReloadDaemonCmd()
case "client":
return pullCerts(domain, certmanMode)
default:
return fmt.Errorf("invalid operating mode %s", internal.Config().GetString("App.mode"))
}
}
func renewCerts(domain string, noPush bool, certmanMode internal.CertManMode) error {
_, err := mgr.RenewForDomain(domain)
if err != nil {
// if no existing cert, obtain instead
_, err = mgr.ObtainForDomain(domain)
if err != nil {
return fmt.Errorf("error obtaining domain certificates for domain %s: %v", domain, err)
}
}
domainConfig, exists := internal.DomainStore().Get(domain)
if !exists {
return fmt.Errorf("domain %s does not exist", domain)
}
domainConfig.Set("Internal.last_issued", time.Now().UTC().Unix())
err = internal.WriteDomainConfig(domainConfig)
if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err)
}
err = internal.EncryptFileXChaCha(domainConfig.GetString("Certificates.crypto_key"), filepath.Join(mgr.CertsRoot, domain, domain+".crt"), filepath.Join(mgr.CertsRoot, domain, domain+".crt.crpt"), nil)
if err != nil {
return fmt.Errorf("error encrypting domain cert for domain %s: %v", domain, err)
}
err = internal.EncryptFileXChaCha(domainConfig.GetString("Certificates.crypto_key"), filepath.Join(mgr.CertsRoot, domain, domain+".key"), filepath.Join(mgr.CertsRoot, domain, domain+".key.crpt"), nil)
if err != nil {
return fmt.Errorf("error encrypting domain key for domain %s: %v", domain, err)
}
if !noPush {
giteaClient := internal.CreateGiteaClient()
if giteaClient == nil {
return fmt.Errorf("error creating gitea client for domain %s: %v", domain, err)
}
gitWorkspace := &internal.GitWorkspace{
Storage: memory.NewStorage(),
FS: memfs.New(),
}
var repoUrl string
if !domainConfig.GetBool("Internal.repo_exists") {
repoUrl = internal.CreateGiteaRepo(domain, giteaClient)
if repoUrl == "" {
return fmt.Errorf("error creating Gitea repo for domain %s", domain)
}
domainConfig.Set("Internal.repo_exists", true)
err = internal.WriteDomainConfig(domainConfig)
if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err)
}
err = internal.InitRepo(repoUrl, gitWorkspace)
if err != nil {
return fmt.Errorf("error initializing repo for domain %s: %v", domain, err)
}
} else {
repoUrl = internal.Config().GetString("Git.server") + "/" + internal.Config().GetString("Git.org_name") + "/" + domain + domainConfig.GetString("Repo.repo_suffix") + ".git"
err = internal.CloneRepo(repoUrl, gitWorkspace, certmanMode)
if err != nil {
return fmt.Errorf("error cloning repo for domain %s: %v", domain, err)
}
}
err = internal.AddAndPushCerts(domain, gitWorkspace)
if err != nil {
return fmt.Errorf("error pushing certificates for domain %s: %v", domain, err)
}
fmt.Printf("Successfully pushed certificates for domain %s\n", domain)
}
return nil
}
func pullCerts(domain string, certmanMode internal.CertManMode) error {
gitWorkspace := &internal.GitWorkspace{
Storage: memory.NewStorage(),
FS: memfs.New(),
}
domainConfig, exists := internal.DomainStore().Get(domain)
if !exists {
return fmt.Errorf("domain %s does not exist", domain)
}
// Ex: https://git.example.com/Org/Repo-suffix.git
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
repoUrl := internal.Config().GetString("Git.server") + "/" + internal.Config().GetString("Git.org_name") + "/" + domain + domainConfig.GetString("Repo.repo_suffix") + ".git"
err := internal.CloneRepo(repoUrl, gitWorkspace, certmanMode)
if err != nil {
return fmt.Errorf("Error cloning domain repo %s: %v\n", domain, err)
}
certsDir, err := internal.DomainCertsDirWConf(domain, domainConfig)
if err != nil {
return fmt.Errorf("Error getting certificates dir for domain %s: %v\n", domain, err)
}
// Get files in repo
fileInfos, err := gitWorkspace.FS.ReadDir("/")
if err != nil {
return fmt.Errorf("Error reading directory in memFS on domain %s: %v\n", domain, err)
}
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added
for _, fileInfo := range fileInfos {
if strings.HasSuffix(fileInfo.Name(), ".crpt") {
filename, _ := strings.CutSuffix(fileInfo.Name(), ".crpt")
file, err := gitWorkspace.FS.Open(fileInfo.Name())
if err != nil {
fmt.Printf("Error opening file in memFS on domain %s: %v\n", domain, err)
continue
}
fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Printf("Error reading file in memFS on domain %s: %v\n", domain, err)
file.Close()
continue
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file on domain %s: %v\n", domain, err)
continue
}
err = internal.DecryptFileFromBytes(domainConfig.GetString("Certificates.crypto_key"), fileBytes, filepath.Join(certsDir, filename), nil)
if err != nil {
fmt.Printf("Error decrypting file %s in domain %s: %v\n", filename, domain, err)
continue
}
headRef, err := gitWorkspace.Repo.Head()
if err != nil {
fmt.Printf("Error getting head reference for domain %s: %v\n", domain, err)
continue
}
err = internal.WriteCommitHash(headRef.Hash().String(), domainConfig)
if err != nil {
fmt.Printf("Error writing commit hash: %v\n", err)
continue
}
certLinks := domainConfig.GetStringSlice("Certificates.cert_symlinks")
for _, certLink := range certLinks {
if certLink == "" {
continue
}
linkInfo, err := os.Stat(certLink)
if err != nil {
if !os.IsNotExist(err) {
fmt.Printf("Error stating cert link %s: %v\n", certLink, err)
continue
}
}
if linkInfo.IsDir() {
certLink = filepath.Join(certLink, domain+".crt")
}
err = os.Link(filepath.Join(certsDir, domain+".crt"), certLink)
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v\n", certLink, domain, err)
continue
}
}
keyLinks := domainConfig.GetStringSlice("Certificates.key_symlinks")
for _, keyLink := range keyLinks {
if keyLink == "" {
continue
}
linkInfo, err := os.Stat(keyLink)
if err != nil {
if !os.IsNotExist(err) {
fmt.Printf("Error stating key link %s: %v\n", keyLink, err)
continue
}
}
if linkInfo.IsDir() {
keyLink = filepath.Join(keyLink, domain+".crt")
}
err = os.Link(filepath.Join(certsDir, domain+".crt"), keyLink)
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v\n", keyLink, domain, err)
continue
}
}
}
}
return nil
}
func UpdateLinksCmd(domain string) error {
domainConfig, exists := internal.DomainStore().Get(domain)
if !exists {
return fmt.Errorf("domain %s does not exist", domain)
}
certsDir, err := internal.DomainCertsDirWConf(domain, domainConfig)
if err != nil {
return fmt.Errorf("error getting certificates dir for domain %s: %v", domain, err)
}
certLinks := domainConfig.GetStringSlice("Certificates.cert_symlinks")
for _, certLink := range certLinks {
err = internal.LinkFile(filepath.Join(certsDir, domain+".crt"), certLink, domain, ".crt")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", certLink, domain, err)
continue
}
}
keyLinks := domainConfig.GetStringSlice("Certificates.key_symlinks")
for _, keyLink := range keyLinks {
err = internal.LinkFile(filepath.Join(certsDir, domain+".crt"), keyLink, domain, ".key")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err)
continue
}
}
return nil
}

View File

@@ -1,116 +0,0 @@
package commands
import (
"fmt"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"git.nevets.tech/Keys/CertManager/internal"
)
func NewDomainCmd(domain, domainDir string, dirOverridden bool) error {
//TODO add config option for "overriden dir"
err := internal.LoadConfig()
if err != nil {
return err
}
fmt.Printf("Creating new domain %s\n", domain)
err = internal.CreateDomainConfig(domain)
if err != nil {
return err
}
internal.CreateDomainCertsDir(domain, domainDir, dirOverridden)
certmanUser, err := user.Lookup("certman")
if err != nil {
return fmt.Errorf("error getting user certman: %v", err)
}
uid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Uid))
if err != nil {
return err
}
gid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Gid))
if err != nil {
return err
}
err = internal.ChownRecursive("/etc/certman/domains", uid, gid)
if err != nil {
return err
}
err = internal.ChownRecursive("/var/local/certman", uid, gid)
if err != nil {
return err
}
fmt.Println("Successfully created domain entry for " + domain + "\nUpdate config file as needed in /etc/certman/domains/" + domain + ".conf\n")
return nil
}
func InstallCmd(isThin bool, mode string) error {
if !isThin {
if os.Geteuid() != 0 {
return fmt.Errorf("installation must be run as root")
}
internal.MakeDirs()
internal.CreateConfig(mode)
err := internal.LoadConfig()
if err != nil {
return err
}
f, err := os.OpenFile("/var/run/certman.pid", os.O_RDONLY|os.O_CREATE, 0755)
if err != nil {
return fmt.Errorf("error creating pid file: %v", err)
}
err = f.Close()
if err != nil {
return fmt.Errorf("error closing pid file: %v", err)
}
newUserCmd := exec.Command("useradd", "-d", "/var/local/certman", "-U", "-r", "-s", "/sbin/nologin", "certman")
if output, err := newUserCmd.CombinedOutput(); err != nil {
if !strings.Contains(err.Error(), "exit status 9") {
return fmt.Errorf("error creating user: %v: output %s", err, output)
}
}
newGroupCmd := exec.Command("groupadd", "-r", "-U", "certman", "certsock")
if output, err := newGroupCmd.CombinedOutput(); err != nil {
if !strings.Contains(err.Error(), "exit status 9") {
return fmt.Errorf("error creating group: %v: output %s", err, output)
}
}
certmanUser, err := user.Lookup("certman")
if err != nil {
return fmt.Errorf("error getting user certman: %v", err)
}
uid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Uid))
if err != nil {
return err
}
gid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Gid))
if err != nil {
return err
}
err = internal.ChownRecursive("/etc/certman", uid, gid)
if err != nil {
return fmt.Errorf("error changing uid/gid: %v", err)
}
err = internal.ChownRecursive("/var/local/certman", uid, gid)
if err != nil {
return fmt.Errorf("error changing uid/gid: %v", err)
}
err = os.Chown("/var/run/certman.pid", uid, gid)
if err != nil {
return fmt.Errorf("error changing uid/gid: %v", err)
}
} else {
internal.CreateConfig(mode)
}
return nil
}

View File

@@ -1,4 +1,4 @@
package internal
package common
var (
Version = "dev"

95
common/config.go Normal file
View File

@@ -0,0 +1,95 @@
package common
// ---------------------------------------------------------------------------
// Default config templates
// ---------------------------------------------------------------------------
type AppConfig struct {
App App `mapstructure:"app" toml:"app"`
Certificates Certificates `mapstructure:"certificates" toml:"certificates"`
Cloudflare Cloudflare `mapstructure:"cloudflare" toml:"cloudflare"`
Git Git `mapstructure:"git" toml:"git"`
}
type App struct {
Mode string `mapstructure:"mode" toml:"mode"`
TickRate int `mapstructure:"tick_rate" toml:"tick_rate"`
UUID string `mapstructure:"uuid" toml:"uuid"`
}
type Git struct {
Host string `mapstructure:"host" toml:"host"`
Server string `mapstructure:"server" toml:"server"`
Username string `mapstructure:"username" toml:"username"`
APIToken string `mapstructure:"api_token" toml:"api_token"`
OrgName string `mapstructure:"org_name" toml:"org_name"`
}
type Certificates struct {
DataRoot string `mapstructure:"data_root" toml:"data_root"`
Email string `mapstructure:"email" toml:"email"`
CADirURL string `mapstructure:"ca_dir_url" toml:"ca_dir_url"`
}
type Cloudflare struct {
CFEmail string `mapstructure:"cf_email" toml:"cf_email"`
CFAPIKey string `mapstructure:"cf_api_key" toml:"cf_api_key"`
}
type Repo struct {
RepoSuffix string `mapstructure:"repo_suffix" toml:"repo_suffix"`
}
type Internal struct {
LastIssued int64 `mapstructure:"last_issued" toml:"last_issued"`
RepoExists bool `mapstructure:"repo_exists" toml:"repo_exists"`
Status string `mapstructure:"status" toml:"status"`
}
// ---------------------------------------------------------------------------
// Server domain config
// ---------------------------------------------------------------------------
type ServerDomainConfig struct {
Domain ServerDomainCfg `mapstructure:"domain" toml:"domain"`
Certificates ServerDomainCerts `mapstructure:"certificates" toml:"certificates"`
Repo Repo `mapstructure:"repo" toml:"repo"`
Internal Internal `mapstructure:"internal" toml:"internal"`
}
type ServerDomainCfg struct {
DomainName string `mapstructure:"domain_name" toml:"domain_name"`
Enabled bool `mapstructure:"enabled" toml:"enabled"`
DNSServer string `mapstructure:"dns_server" toml:"dns_server"`
}
type ServerDomainCerts struct {
DataRoot string `mapstructure:"data_root" toml:"data_root"`
CryptoKey string `mapstructure:"crypto_key" toml:"crypto_key"`
RequestMethod string `mapstructure:"request_method" toml:"request_method"`
Expiry int `mapstructure:"expiry" toml:"expiry"`
RenewPeriod int `mapstructure:"renew_period" toml:"renew_period"`
SubDomains []string `mapstructure:"sub_domains" toml:"sub_domains"`
}
// ---------------------------------------------------------------------------
// Client domain config
// ---------------------------------------------------------------------------
type ClientDomainConfig struct {
Domain ClientDomainCfg `mapstructure:"domain" toml:"domain"`
Certificates ClientDomainCerts `mapstructure:"certificates" toml:"certificates"`
Repo Repo `mapstructure:"repo" toml:"repo"`
}
type ClientDomainCfg struct {
DomainName string `mapstructure:"domain_name" toml:"domain_name"`
Enabled bool `mapstructure:"enabled" toml:"enabled"`
}
type ClientDomainCerts struct {
DataRoot string `mapstructure:"data_root" toml:"data_root"`
CryptoKey string `mapstructure:"crypto_key" toml:"crypto_key"`
CertSymlinks []string `mapstructure:"cert_symlinks" toml:"cert_symlinks"`
KeySymlinks []string `mapstructure:"key_symlinks" toml:"key_symlinks"`
}

View File

@@ -1,4 +1,4 @@
package internal
package common
import (
"crypto/rand"
@@ -68,39 +68,6 @@ func EncryptFileXChaCha(keyB64, inPath, outPath string, aad []byte) error {
return nil
}
func DecryptFileXChaCha(keyB64, inPath, outPath string, aad []byte) error {
key, err := decodeKey(keyB64)
if err != nil {
return err
}
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return fmt.Errorf("new aead: %w", err)
}
in, err := os.ReadFile(inPath)
if err != nil {
return fmt.Errorf("read input: %w", err)
}
if len(in) < chacha20poly1305.NonceSizeX {
return errors.New("ciphertext too short")
}
nonce := in[:chacha20poly1305.NonceSizeX]
ciphertext := in[chacha20poly1305.NonceSizeX:]
plaintext, err := aead.Open(nil, nonce, ciphertext, aad)
if err != nil {
return fmt.Errorf("decrypt/auth failed: %w", err)
}
if err := os.WriteFile(outPath, plaintext, 0640); err != nil {
return fmt.Errorf("write output: %w", err)
}
return nil
}
func DecryptFileFromBytes(keyB64 string, inBytes []byte, outPath string, aad []byte) error {
key, err := decodeKey(keyB64)
if err != nil {

183
common/git.go Normal file
View File

@@ -0,0 +1,183 @@
package common
import (
"errors"
"fmt"
"io"
"os"
"strings"
"code.gitea.io/sdk/gitea"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-git/v5"
gitconf "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory"
)
type CertManMode int
const (
Server CertManMode = iota
Client
)
type GitWorkspace struct {
Domain string
URL string
Repo *git.Repository
Storage *memory.Storage
FS billy.Filesystem
WorkTree *git.Worktree
}
type GitSource int
const (
Github GitSource = iota
Gitlab
Gitea
Gogs
Bitbucket
CodeCommit
)
var GitSourceName = map[GitSource]string{
Github: "github",
Gitlab: "gitlab",
Gitea: "gitea",
Gogs: "gogs",
Bitbucket: "bitbucket",
CodeCommit: "code-commit",
}
func StrToGitSource(s string) (GitSource, error) {
for k, v := range GitSourceName {
if v == s {
return k, nil
}
}
return GitSource(0), errors.New("invalid gitsource name")
}
//func createGithubClient() *github.Client {
// return github.NewClient(nil).WithAuthToken(config.GetString("Git.api_token"))
//}
func CreateGiteaClient(config *AppConfig) *gitea.Client {
client, err := gitea.NewClient(config.Git.Server, gitea.SetToken(config.Git.APIToken))
if err != nil {
fmt.Printf("Error connecting to gitea instance: %v\n", err)
return nil
}
return client
}
//func createGithubRepo(domain *Domain, Client *github.Client) string {
// name := domain.name
// owner := domain.config.GetString("Repo.owner")
// description := domain.description
// private := true
// includeAllBranches := false
//
// ctx := context.Background()
// template := &github.TemplateRepoRequest{
// Name: name,
// Owner: &owner,
// Description: description,
// Private: &private,
// IncludeAllBranches: &includeAllBranches,
// }
// repo, _, err := Client.Repositories.CreateFromTemplate(ctx, config.GetString("Git.org_name"), config.GetString("Git.template_name"), template)
// if err != nil {
// fmt.Println("Error creating repository from template,", err)
// return ""
// }
// return *repo.CloneURL
//}
func CreateGiteaRepo(domain string, giteaClient *gitea.Client, config *AppConfig, domainConfig *ServerDomainConfig) string {
options := gitea.CreateRepoOption{
Name: domain + domainConfig.Repo.RepoSuffix,
Description: "Certificate storage for " + domain,
Private: true,
IssueLabels: "",
AutoInit: false,
Template: false,
Gitignores: "",
License: "",
Readme: "",
DefaultBranch: "master",
TrustModel: gitea.TrustModelDefault,
}
giteaRepo, _, err := giteaClient.CreateOrgRepo(config.Git.OrgName, options)
if err != nil {
fmt.Printf("Error creating repo: %v\n", err)
return ""
}
return giteaRepo.CloneURL
}
func (ws *GitWorkspace) InitRepo() error {
var err error
ws.Repo, err = git.Init(ws.Storage, ws.FS)
if err != nil {
fmt.Printf("Error initializing local repo: %v\n", err)
return err
}
_, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{
Name: "origin",
URLs: []string{ws.URL},
})
if err != nil && !errors.Is(err, git.ErrRemoteExists) {
fmt.Printf("Error creating remote origin repo: %v\n", err)
return err
}
ws.WorkTree, err = ws.Repo.Worktree()
if err != nil {
fmt.Printf("Error getting worktree from local repo: %v\n", err)
return err
}
return nil
}
func (ws *GitWorkspace) CloneRepo(certmanMode CertManMode, config *AppConfig) error {
creds := &http.BasicAuth{
Username: config.Git.Username,
Password: config.Git.APIToken,
}
var err error
ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: ws.URL, Auth: creds})
if err != nil {
fmt.Printf("Error cloning repo: %v\n", err)
}
ws.WorkTree, err = ws.Repo.Worktree()
if err != nil {
fmt.Printf("Error getting worktree from cloned repo: %v\n", err)
return err
}
if certmanMode == Server {
serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("server ID file not found for %s, adopting domain\n", ws.URL)
return nil
}
return err
}
serverIdBytes, err := io.ReadAll(serverIdFile)
if err != nil {
return err
}
serverId := strings.TrimSpace(string(serverIdBytes))
if serverId != config.App.UUID {
return fmt.Errorf("domain is already managed by server with uuid %s", serverId)
}
}
return nil
}

View File

@@ -1,4 +1,4 @@
package internal
package common
import (
"errors"
@@ -7,12 +7,12 @@ import (
"os"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"code.gitea.io/sdk/gitea"
"github.com/spf13/viper"
)
var (
@@ -23,7 +23,7 @@ var (
type Domain struct {
name *string
config *viper.Viper
config *AppConfig
description *string
gtClient *gitea.Client
}
@@ -168,46 +168,6 @@ func DaemonProcess() (*os.Process, error) {
return proc, nil
}
func createFile(fileName string, filePermission os.FileMode, data []byte) {
fileInfo, err := os.Stat(fileName)
if err != nil {
if os.IsNotExist(err) {
file, err := os.Create(fileName)
if err != nil {
fmt.Println("Error creating configuration file: ", err)
os.Exit(1)
}
_, err = file.Write(data)
if err != nil {
fmt.Println("Error writing to file: ", err)
os.Exit(1)
}
err = file.Chmod(filePermission)
if err != nil {
fmt.Println("Error changing file permission: ", err)
}
} else {
fmt.Println("Error opening configuration file: ", err)
os.Exit(1)
}
} else {
if fileInfo.Size() == 0 {
file, err := os.Create(fileName)
if err != nil {
fmt.Println("Error creating configuration file: ", err)
os.Exit(1)
}
_, err = file.Write(data)
if err != nil {
fmt.Println("Error writing to file:", err)
os.Exit(1)
}
}
}
}
func LinkFile(source, target, domain, extension string) error {
if target == "" {
return ErrBlankCert
@@ -234,7 +194,7 @@ func LinkFile(source, target, domain, extension string) error {
return nil
}
func fileExists(path string) bool {
func FileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
@@ -262,31 +222,6 @@ func SanitizeDomainKey(s string) string {
return r.Replace(s)
}
// DomainCertsDir Can return ErrBlankConfigEntry, ErrConfigNotFound, or other errors
func DomainCertsDir(domain string) (string, error) {
domainConfig, exists := domainStore.Get(domain)
if !exists {
return "", ErrConfigNotFound
}
return DomainCertsDirWConf(domain, domainConfig)
}
// DomainCertsDirWConf Can return ErrBlankConfigEntry or other errors
func DomainCertsDirWConf(domain string, domainConfig *viper.Viper) (string, error) {
effectiveDataRoot, err := EffectiveString(domainConfig, "Certificates.data_root")
if err != nil {
return "", err
}
return filepath.Join(effectiveDataRoot, "certificates", domain), nil
}
func DomainCertsDirWOnlyConf(domainConfig *viper.Viper) (string, error) {
domain := domainConfig.GetString("Domain.domain_name")
return DomainCertsDirWConf(domain, domainConfig)
}
func ChownRecursive(path string, uid, gid int) error {
return filepath.WalkDir(path, func(name string, d fs.DirEntry, err error) error {
if err != nil {
@@ -357,3 +292,30 @@ func MakeCredential(username, groupname string) (*syscall.Credential, error) {
return &syscall.Credential{Uid: uid, Gid: gid}, nil
}
// EffectiveDataRoot resolves the data root for a domain. The per-domain
// override takes precedence; otherwise the app-level data root is used; if
// both are empty, the current working directory is used.
func EffectiveDataRoot(config *AppConfig, domainDataRoot string) string {
if config == nil {
return ""
}
if domainDataRoot == "" {
if config.Certificates.DataRoot == "" {
workDir, err := os.Getwd()
if err != nil {
return "./"
}
return workDir
}
return config.Certificates.DataRoot
}
return domainDataRoot
}
var fqdnRegex = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$`)
func IsValidFQDN(domain string) bool {
return len(domain) <= 253 && fqdnRegex.MatchString(domain)
}

2
go.mod
View File

@@ -1,4 +1,4 @@
module git.nevets.tech/Keys/CertManager
module git.nevets.tech/Steven/certman
go 1.25.0

View File

@@ -1,374 +0,0 @@
package internal
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"code.gitea.io/sdk/gitea"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-git/v5"
gitconf "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/spf13/viper"
)
type CertManMode int
const (
Server CertManMode = iota
Client
)
type GitWorkspace struct {
Repo *git.Repository
Storage *memory.Storage
FS billy.Filesystem
WorkTree *git.Worktree
}
type GitSource int
const (
Github GitSource = iota
Gitlab
Gitea
Gogs
Bitbucket
CodeCommit
)
var GitSourceName = map[GitSource]string{
Github: "github",
Gitlab: "gitlab",
Gitea: "gitea",
Gogs: "gogs",
Bitbucket: "bitbucket",
CodeCommit: "code-commit",
}
func StrToGitSource(s string) (GitSource, error) {
for k, v := range GitSourceName {
if v == s {
return k, nil
}
}
return GitSource(0), errors.New("invalid gitsource name")
}
//func createGithubClient() *github.Client {
// return github.NewClient(nil).WithAuthToken(config.GetString("Git.api_token"))
//}
func CreateGiteaClient() *gitea.Client {
client, err := gitea.NewClient(config.GetString("Git.server"), gitea.SetToken(config.GetString("Git.api_token")))
if err != nil {
fmt.Printf("Error connecting to gitea instance: %v\n", err)
return nil
}
return client
}
//func createGithubRepo(domain *Domain, Client *github.Client) string {
// name := domain.name
// owner := domain.config.GetString("Repo.owner")
// description := domain.description
// private := true
// includeAllBranches := false
//
// ctx := context.Background()
// template := &github.TemplateRepoRequest{
// Name: name,
// Owner: &owner,
// Description: description,
// Private: &private,
// IncludeAllBranches: &includeAllBranches,
// }
// repo, _, err := Client.Repositories.CreateFromTemplate(ctx, config.GetString("Git.org_name"), config.GetString("Git.template_name"), template)
// if err != nil {
// fmt.Println("Error creating repository from template,", err)
// return ""
// }
// return *repo.CloneURL
//}
func CreateGiteaRepo(domain string, giteaClient *gitea.Client) string {
domainConfig, exists := domainStore.Get(domain)
if !exists {
fmt.Printf("Domain %s config does not exist\n", domain)
return ""
}
options := gitea.CreateRepoOption{
Name: domain + domainConfig.GetString("Repo.repo_suffix"),
Description: "Certificate storage for " + domain,
Private: true,
IssueLabels: "",
AutoInit: false,
Template: false,
Gitignores: "",
License: "",
Readme: "",
DefaultBranch: "master",
TrustModel: gitea.TrustModelDefault,
}
giteaRepo, _, err := giteaClient.CreateOrgRepo(config.GetString("Git.org_name"), options)
if err != nil {
fmt.Printf("Error creating repo: %v\n", err)
return ""
}
return giteaRepo.CloneURL
}
func InitRepo(url string, ws *GitWorkspace) error {
var err error
ws.Repo, err = git.Init(ws.Storage, ws.FS)
if err != nil {
fmt.Printf("Error initializing local repo: %v\n", err)
return err
}
_, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{
Name: "origin",
URLs: []string{url},
})
if err != nil && !errors.Is(err, git.ErrRemoteExists) {
fmt.Printf("Error creating remote origin repo: %v\n", err)
return err
}
ws.WorkTree, err = ws.Repo.Worktree()
if err != nil {
fmt.Printf("Error getting worktree from local repo: %v\n", err)
return err
}
return nil
}
func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode) error {
creds := &http.BasicAuth{
Username: config.GetString("Git.username"),
Password: config.GetString("Git.api_token"),
}
var err error
ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: url, Auth: creds})
if err != nil {
fmt.Printf("Error cloning repo: %v\n", err)
}
ws.WorkTree, err = ws.Repo.Worktree()
if err != nil {
fmt.Printf("Error getting worktree from cloned repo: %v\n", err)
return err
}
if certmanMode == Server {
serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("Server ID file not found for %s, adopting domain\n", url)
return nil
}
return err
}
serverIdBytes, err := io.ReadAll(serverIdFile)
if err != nil {
return err
}
serverId := strings.TrimSpace(string(serverIdBytes))
if serverId != config.GetString("App.uuid") {
return fmt.Errorf("domain is already managed by server with uuid %s", serverId)
}
}
return nil
}
func AddAndPushCerts(domain string, ws *GitWorkspace) error {
domainConfig, exists := domainStore.Get(domain)
if !exists {
fmt.Printf("Domain %s config does not exist\n", domain)
return ErrConfigNotFound
}
certsDir, err := DomainCertsDirWConf(domain, domainConfig)
if err != nil {
if errors.Is(err, ErrConfigNotFound) {
fmt.Printf("Domain %s config not found: %v\n", domain, err)
return err
}
fmt.Printf("Error getting domain %s certs dir: %v\n", domain, err)
}
certFiles, err := os.ReadDir(certsDir)
if err != nil {
fmt.Printf("Error reading from directory: %v\n", err)
return err
}
for _, entry := range certFiles {
if strings.HasSuffix(entry.Name(), ".crpt") {
file, err := ws.FS.Create(entry.Name())
if err != nil {
fmt.Printf("Error copying file to memfs: %v\n", err)
return err
}
certFile, err := os.ReadFile(filepath.Join(certsDir, entry.Name()))
if err != nil {
fmt.Printf("Error reading file to memfs: %v\n", err)
file.Close()
return err
}
_, err = file.Write(certFile)
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
}
file, err := ws.FS.Create("/SERVER_ID")
if err != nil {
fmt.Printf("Error creating file in memfs: %v\n", err)
return err
}
_, err = file.Write([]byte(config.GetString("App.uuid")))
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
}
status, err := ws.WorkTree.Status()
if err != nil {
fmt.Printf("Error getting repo status: %v\n", err)
return err
}
if status.IsClean() {
fmt.Printf("Repository is clean, skipping commit...\n")
return nil
}
fmt.Println("Work Tree Status:\n" + status.String())
signature := &object.Signature{
Name: "Cert Manager",
Email: config.GetString("Certificates.email"),
When: time.Now(),
}
_, err = ws.WorkTree.Commit("Update "+domain+" @ "+time.Now().Format("Mon Jan _2 2006 15:04:05 MST"), &git.CommitOptions{Author: signature, Committer: signature})
if err != nil {
fmt.Printf("Error committing certs: %v\n", err)
return err
}
creds := &http.BasicAuth{
Username: config.GetString("Git.username"),
Password: config.GetString("Git.api_token"),
}
err = ws.Repo.Push(&git.PushOptions{
Auth: creds,
Force: true,
RemoteName: "origin",
RefSpecs: []gitconf.RefSpec{
"refs/heads/master:refs/heads/master",
},
})
if err != nil {
fmt.Printf("Error pushing to origin: %v\n", err)
return err
}
fmt.Println("Successfully uploaded to " + config.GetString("Git.server") + "/" + config.GetString("Git.org_name") + "/" + domain + domainConfig.GetString("Repo.repo_suffix") + ".git")
return nil
}
func WriteCommitHash(hash string, domainConfig *viper.Viper) error {
certsDir, err := DomainCertsDirWOnlyConf(domainConfig)
if err != nil {
if errors.Is(err, ErrConfigNotFound) {
return err
}
return err
}
err = os.WriteFile(filepath.Join(certsDir, "hash"), []byte(hash), 0644)
if err != nil {
return err
}
return nil
}
func LocalCommitHash(domain string) (string, error) {
certsDir, err := DomainCertsDir(domain)
if err != nil {
if errors.Is(err, ErrConfigNotFound) {
fmt.Printf("Domain %s config not found: %v\n", domain, err)
return "", err
}
fmt.Printf("Error getting domain %s certs dir: %v\n", domain, err)
}
data, err := os.ReadFile(filepath.Join(certsDir, "hash"))
if err != nil {
if !os.IsNotExist(err) {
fmt.Printf("Error reading file for domain %s: %v\n", domain, err)
return "", err
}
}
return strings.TrimSpace(string(data)), nil
}
func RemoteCommitHash(domain string, gitSource GitSource) (string, error) {
domainConfig, exists := DomainStore().Get(domain)
if !exists {
fmt.Printf("Domain %s config does not exist\n", domain)
return "", ErrConfigNotFound
}
switch gitSource {
case Gitea:
return getRemoteCommitHashGitea(config.GetString("Git.org_name"), domain+domainConfig.GetString("Repo.repo_suffix"), "master")
default:
fmt.Printf("Unimplemented git source %v\n", gitSource)
return "", errors.New("unimplemented git source")
}
}
func getRemoteCommitHashGitea(org, repo, branchName string) (string, error) {
giteaClient := CreateGiteaClient()
branch, _, err := giteaClient.GetRepoBranch(org, repo, branchName)
if err != nil {
fmt.Printf("Error getting repo branch: %v\n", err)
return "", err
}
//TODO catch repo not found as ErrRepoNotInit
return branch.Commit.ID, nil
}

View File

@@ -1 +0,0 @@
package internal

181
main.go
View File

@@ -1,181 +0,0 @@
package main
import (
"fmt"
"os"
"regexp"
"git.nevets.tech/Keys/CertManager/commands"
"git.nevets.tech/Keys/CertManager/internal"
"github.com/spf13/cobra"
)
var configFile string
var fqdnRegex = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$`)
//TODO create logic for gh vs gt repos
func main() {
rootCmd := &cobra.Command{
Use: "certman",
Short: "CertMan",
Long: "Certificate Manager",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "/etc/certman/certman.conf", "Configuration file")
rootCmd.AddCommand(basicCmd("version", "Show version", commands.VersionCmd))
rootCmd.AddCommand(basicCmd("gen-key", "Generates encryption key", commands.NewKeyCmd))
rootCmd.AddCommand(basicCmd("dev", "Dev Function", commands.DevCmd))
var domainCertDir string
newDomainCmd := &cobra.Command{
Use: "new-domain",
Short: "Create config and directories for new domain",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
dirOverridden := cmd.Flags().Changed("dir")
return commands.NewDomainCmd(args[0], domainCertDir, dirOverridden)
},
}
newDomainCmd.Flags().StringVar(&domainCertDir, "dir", "/var/local/certman/certificates/", "Alternate directory for certificates")
rootCmd.AddCommand(newDomainCmd)
var (
modeFlag string
thinInstallFlag bool
)
installCmd := &cobra.Command{
Use: "install",
Short: "Create certman files and directories",
RunE: func(cmd *cobra.Command, args []string) error {
switch modeFlag {
case "server", "client":
return commands.InstallCmd(thinInstallFlag, modeFlag)
default:
return fmt.Errorf("invalid --mode %q (must be server or client)", modeFlag)
}
},
}
installCmd.Flags().StringVar(&modeFlag, "mode", "client", "CertManager mode [server, client]")
installCmd.Flags().BoolVarP(&thinInstallFlag, "thin", "t", false, "Thin install (skip creating dirs)")
rootCmd.AddCommand(installCmd)
certCmd := &cobra.Command{
Use: "cert",
Short: "Certificate management",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
var noPush bool
renewCertCmd := &cobra.Command{
Use: "renew",
Short: "Renews a domains certificate",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return commands.RenewCertCmd(args[0], noPush, internal.Server)
},
}
renewCertCmd.Flags().BoolVar(&noPush, "no-push", false, "Don't push certs to repo, renew locally only [server mode only]")
certCmd.AddCommand(renewCertCmd)
updateCertLinkCmd := &cobra.Command{
Use: "update-link",
Short: "Update linked certificates",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return commands.UpdateLinksCmd(args[0])
},
}
certCmd.AddCommand(updateCertLinkCmd)
rootCmd.AddCommand(certCmd)
rootCmd.AddCommand(&cobra.Command{
Use: "executor",
Short: "Privileged daemon",
RunE: func(cmd *cobra.Command, args []string) error {
return commands.StartExecutorCmd()
},
})
daemonCmd := &cobra.Command{
Use: "daemon",
Short: "Daemon management",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
daemonCmd.AddCommand(&cobra.Command{
Use: "start",
Short: "Start the daemon",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return commands.RunDaemonCmd()
},
})
daemonCmd.AddCommand(&cobra.Command{
Use: "stop",
Short: "Stop the daemon",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return commands.StopDaemonCmd()
},
})
daemonCmd.AddCommand(&cobra.Command{
Use: "reload",
Short: "Reload daemon configs",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return commands.ReloadDaemonCmd()
},
})
daemonCmd.AddCommand(&cobra.Command{
Use: "tick",
Short: "Manually triggers daemon tick",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return commands.TickDaemonCmd()
},
})
daemonCmd.AddCommand(&cobra.Command{
Use: "status",
Short: "Show daemon status",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return commands.DaemonStatusCmd()
},
})
rootCmd.AddCommand(daemonCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func basicCmd(use, short string, commandFunc func(cmd *cobra.Command, args []string)) *cobra.Command {
return &cobra.Command{
Use: use,
Short: short,
Run: commandFunc,
}
}
func IsValidFQDN(domain string) bool {
return len(domain) <= 253 && fqdnRegex.MatchString(domain)
}

View File

@@ -1,4 +1,4 @@
package internal
package server
import (
"crypto"
@@ -16,8 +16,10 @@ import (
"sync"
"time"
"git.nevets.tech/Steven/certman/common"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/providers/dns/cloudflare"
"github.com/go-acme/lego/v4/registration"
@@ -57,6 +59,11 @@ type ACMEManager struct {
Client *lego.Client
User *fileUser
// cached DNS-01 provider so we can re-bind it with per-domain recursive nameservers
cfProvider *cloudflare.DNSProvider
// snapshot of /etc/resolv.conf nameservers taken at manager init
defaultNameservers []string
// root dirs
dataRoot string // e.g. /var/local/certman
accountRoot string // e.g. /var/local/certman/accounts
@@ -93,11 +100,11 @@ type StoredCertMeta struct {
// - persistent ECDSA P-256 account key
// - Lets Encrypt production by default (from config fallback)
// - Cloudflare DNS-01 only
func NewACMEManager() (*ACMEManager, error) {
func NewACMEManager(config *common.AppConfig) (*ACMEManager, error) {
// Pull effective (main-only) certificate settings.
email := config.GetString("Certificates.email")
dataRoot := config.GetString("Certificates.data_root")
caDirURL := config.GetString("Certificates.ca_dir_url")
email := config.Certificates.Email
dataRoot := config.Certificates.DataRoot
caDirURL := config.Certificates.CADirURL
// Build manager paths
mgr := &ACMEManager{
@@ -121,7 +128,7 @@ func NewACMEManager() (*ACMEManager, error) {
// Cloudflare provider (DNS-01 only).
// lego Cloudflare provider expects env vars (CLOUDFLARE_EMAIL/CLOUDFLARE_API_KEY or tokens). :contentReference[oaicite:2]{index=2}
restoreEnv, err := setCloudflareEnvFromMainConfig()
restoreEnv, err := setCloudflareEnvFromMainConfig(config)
if err != nil {
return nil, err
}
@@ -142,7 +149,10 @@ func NewACMEManager() (*ACMEManager, error) {
return nil, fmt.Errorf("cloudflare dns provider: %w", err)
}
if err := client.Challenge.SetDNS01Provider(cfProvider); err != nil {
mgr.cfProvider = cfProvider
mgr.defaultNameservers = dns01.ParseNameservers(readResolvConfNameservers("/etc/resolv.conf"))
if err = client.Challenge.SetDNS01Provider(cfProvider, dns01.AddRecursiveNameservers(mgr.defaultNameservers)); err != nil {
return nil, fmt.Errorf("set dns-01 provider: %w", err)
}
@@ -158,7 +168,7 @@ func NewACMEManager() (*ACMEManager, error) {
return nil, fmt.Errorf("acme registration: %w", err)
}
mgr.User.Registration = reg
if err := saveACMEUser(mgr.accountRoot, mgr.User); err != nil {
if err = saveACMEUser(mgr.accountRoot, mgr.User); err != nil {
return nil, fmt.Errorf("save acme User registration: %w", err)
}
}
@@ -167,8 +177,10 @@ func NewACMEManager() (*ACMEManager, error) {
}
// ObtainForDomain obtains a new cert for a configured domain and saves it to disk.
func (m *ACMEManager) ObtainForDomain(domainKey string) (*certificate.Resource, error) {
rcfg, err := buildDomainRuntimeConfig(domainKey)
func (m *ACMEManager) ObtainForDomain(config *common.AppConfig, domainConfig *common.ServerDomainConfig) (*certificate.Resource, error) {
domainKey := domainConfig.Domain.DomainName
rcfg, err := buildDomainRuntimeConfig(config, domainConfig)
if err != nil {
return nil, err
}
@@ -186,6 +198,10 @@ func (m *ACMEManager) ObtainForDomain(domainKey string) (*certificate.Resource,
m.MU.Lock()
defer m.MU.Unlock()
if err := m.applyDNS01ForDomain(domainConfig); err != nil {
return nil, fmt.Errorf("apply dns-01 nameservers for %q: %w", domainKey, err)
}
res, err := m.Client.Certificate.Obtain(req)
if err != nil {
return nil, fmt.Errorf("obtain %q: %w", domainKey, err)
@@ -199,7 +215,9 @@ func (m *ACMEManager) ObtainForDomain(domainKey string) (*certificate.Resource,
}
// RenewForDomain renews an existing stored cert for a domain key.
func (m *ACMEManager) RenewForDomain(domainKey string) (*certificate.Resource, error) {
func (m *ACMEManager) RenewForDomain(domainConfig *common.ServerDomainConfig) (*certificate.Resource, error) {
domainKey := domainConfig.Domain.DomainName
m.MU.Lock()
defer m.MU.Unlock()
@@ -208,6 +226,10 @@ func (m *ACMEManager) RenewForDomain(domainKey string) (*certificate.Resource, e
return nil, fmt.Errorf("load stored resource for %q: %w", domainKey, err)
}
if err := m.applyDNS01ForDomain(domainConfig); err != nil {
return nil, fmt.Errorf("apply dns-01 nameservers for %q: %w", domainKey, err)
}
// RenewWithOptions is preferred in newer lego versions.
renewed, err := m.Client.Certificate.RenewWithOptions(*existing, &certificate.RenewOptions{
Bundle: true,
@@ -225,42 +247,71 @@ func (m *ACMEManager) RenewForDomain(domainKey string) (*certificate.Resource, e
// GetCertPaths returns disk paths for the domain's cert material.
func (m *ACMEManager) GetCertPaths(domainKey string) (certPEM, keyPEM string) {
base := SanitizeDomainKey(domainKey)
base := common.SanitizeDomainKey(domainKey)
dir := filepath.Join(m.CertsRoot, base)
return filepath.Join(dir, base+".crt"),
filepath.Join(dir, base+".key")
}
// applyDNS01ForDomain re-binds the lego DNS-01 provider with recursive nameservers
// appropriate for this domain. When ServerDomainCfg.DNSServer is empty or "default", the
// resolv.conf snapshot taken at NewACMEManager time is used; otherwise the configured
// server is used. Caller must hold m.MU.
func (m *ACMEManager) applyDNS01ForDomain(domainConfig *common.ServerDomainConfig) error {
ns := m.defaultNameservers
cfgDNS := strings.TrimSpace(domainConfig.Domain.DNSServer)
if cfgDNS != "" && !strings.EqualFold(cfgDNS, "default") {
ns = dns01.ParseNameservers([]string{cfgDNS})
}
return m.Client.Challenge.SetDNS01Provider(m.cfProvider, dns01.AddRecursiveNameservers(ns))
}
// readResolvConfNameservers parses `nameserver` lines from a resolv.conf-style file.
// Returns nil on any error so the caller falls through to lego's own defaults.
func readResolvConfNameservers(path string) []string {
data, err := os.ReadFile(path)
if err != nil {
return nil
}
var servers []string
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
continue
}
rest, ok := strings.CutPrefix(line, "nameserver")
if !ok {
continue
}
ns := strings.TrimSpace(rest)
if ns != "" {
servers = append(servers, ns)
}
}
return servers
}
// ---------------------------------------------
// Domain runtime config assembly
// ---------------------------------------------
func buildDomainRuntimeConfig(domainKey string) (*DomainRuntimeConfig, error) {
domainCfg, exists := domainStore.Get(domainKey)
if !exists {
return nil, fmt.Errorf("domain config not found for %q", domainKey)
}
func buildDomainRuntimeConfig(config *common.AppConfig, domainConfig *common.ServerDomainConfig) (*DomainRuntimeConfig, error) {
domainName := domainConfig.Domain.DomainName
domainName := domainCfg.GetString("Domain.domain_name")
email := config.GetString("Certificates.email")
email := config.Certificates.Email
// domain override data_root can be blank -> main fallback
dataRoot, err := EffectiveString(domainCfg, "Certificates.data_root")
if err != nil {
return nil, err
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
caDirURL := config.GetString("Certificates.ca_dir_url")
caDirURL := config.Certificates.CADirURL
expiry := domainCfg.GetInt("Certificates.expiry")
expiry := domainConfig.Certificates.Expiry
renewPeriod := domainCfg.GetInt("Certificates.renew_period")
renewPeriod := domainConfig.Certificates.RenewPeriod
requestMethod := domainCfg.GetString("Certificates.request_method")
requestMethod := domainConfig.Certificates.RequestMethod
subdomains := domainCfg.GetString("Certificates.subdomains")
subdomainArray := parseCSVLines(subdomains)
subdomainArray := domainConfig.Certificates.SubDomains
return &DomainRuntimeConfig{
DomainName: domainName,
@@ -274,25 +325,11 @@ func buildDomainRuntimeConfig(domainKey string) (*DomainRuntimeConfig, error) {
}, nil
}
func parseCSVLines(raw string) []string {
// supports comma-separated and newline-separated lists
fields := strings.FieldsFunc(raw, func(r rune) bool {
return r == ',' || r == '\n' || r == '\r'
})
out := make([]string, 0, len(fields))
for _, f := range fields {
s := strings.TrimSpace(f)
if s != "" {
out = append(out, s)
}
}
return out
}
// If subdomains contains ["www","api"], returns ["example.com","www.example.com","api.example.com"].
// If a subdomain entry looks like a full FQDN already, it is used as-is.
func buildDomainList(baseDomain string, subs []string) []string {
seen := map[string]struct{}{}
out := make([]string, 0, len(subs)+1)
add := func(d string) {
d = strings.TrimSpace(strings.ToLower(d))
if d == "" {
@@ -302,6 +339,7 @@ func buildDomainList(baseDomain string, subs []string) []string {
return
}
seen[d] = struct{}{}
out = append(out, d)
}
add(baseDomain)
@@ -333,10 +371,6 @@ func buildDomainList(baseDomain string, subs []string) []string {
add(s + "." + baseDomain)
}
out := make([]string, 0, len(seen))
for d := range seen {
out = append(out, d)
}
return out
}
@@ -344,11 +378,11 @@ func buildDomainList(baseDomain string, subs []string) []string {
// Cloudflare env setup from main config
// ---------------------------------------------
func setCloudflareEnvFromMainConfig() (restore func(), err error) {
func setCloudflareEnvFromMainConfig(config *common.AppConfig) (restore func(), err error) {
// Your current defaults show legacy email + API key fields.
// Prefer API tokens in the future if you add them. Cloudflare provider supports both styles. :contentReference[oaicite:3]{index=3}
cfEmail := config.GetString("Cloudflare.cf_email")
cfAPIKey := config.GetString("Cloudflare.cf_api_key")
cfEmail := config.Cloudflare.CFEmail
cfAPIKey := config.Cloudflare.CFAPIKey
// Save prior env values so we can restore them after provider creation.
prevEmail, hadEmail := os.LookupEnv("CLOUDFLARE_EMAIL")
@@ -388,8 +422,8 @@ func loadOrCreateACMEUser(accountRoot, email string) (*fileUser, error) {
accountJSON := filepath.Join(accountRoot, "account.json")
accountKey := filepath.Join(accountRoot, "account.key.pem")
jsonExists := fileExists(accountJSON)
keyExists := fileExists(accountKey)
jsonExists := common.FileExists(accountJSON)
keyExists := common.FileExists(accountKey)
switch {
case jsonExists && keyExists:
@@ -524,7 +558,7 @@ func (m *ACMEManager) saveCertFiles(domainKey string, res *certificate.Resource,
return errors.New("nil certificate resource")
}
base := SanitizeDomainKey(domainKey)
base := common.SanitizeDomainKey(domainKey)
dir := filepath.Join(m.CertsRoot, base)
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
@@ -598,10 +632,13 @@ func (m *ACMEManager) saveCertFiles(domainKey string, res *certificate.Resource,
}
func (m *ACMEManager) loadStoredResource(domainKey string) (*certificate.Resource, error) {
base := SanitizeDomainKey(domainKey)
base := common.SanitizeDomainKey(domainKey)
dir := filepath.Join(m.CertsRoot, base)
raw, err := os.ReadFile(filepath.Join(dir, base+".json"))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, os.ErrNotExist
}
return nil, err
}
@@ -622,7 +659,7 @@ func (m *ACMEManager) loadStoredResource(domainKey string) (*certificate.Resourc
}
func (m *ACMEManager) loadMeta(domainKey string) (*StoredCertMeta, error) {
base := SanitizeDomainKey(domainKey)
base := common.SanitizeDomainKey(domainKey)
dir := filepath.Join(m.CertsRoot, base)
raw, err := os.ReadFile(filepath.Join(dir, base+".meta.json"))
if err != nil {

View File

@@ -0,0 +1,15 @@
package server
import (
"fmt"
"slices"
"testing"
)
func TestBuildDomainList(t *testing.T) {
domains := buildDomainList("example.com", []string{"*", "dev"})
fmt.Printf("domains: %v\n", domains)
if slices.Compare(domains, []string{"example.com", "*.example.com", "dev.example.com"}) != 0 {
t.Errorf("domains not equal")
}
}

118
server/git.go Normal file
View File

@@ -0,0 +1,118 @@
package server
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-git/v5"
gitconf "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
)
func AddAndPushCerts(ws *common.GitWorkspace, dataRoot, repoSuffix string, config *common.AppConfig) error {
certFiles, err := os.ReadDir(dataRoot)
if err != nil {
fmt.Printf("Error reading from directory: %v\n", err)
return err
}
for _, entry := range certFiles {
if strings.HasSuffix(entry.Name(), ".crpt") {
file, err := ws.FS.Create(entry.Name())
if err != nil {
fmt.Printf("Error copying file to memfs: %v\n", err)
return err
}
certFile, err := os.ReadFile(filepath.Join(dataRoot, entry.Name()))
if err != nil {
fmt.Printf("Error reading file to memfs: %v\n", err)
file.Close()
return err
}
_, err = file.Write(certFile)
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
}
}
file, err := ws.FS.Create("/SERVER_ID")
if err != nil {
fmt.Printf("Error creating file in memfs: %v\n", err)
return err
}
_, err = file.Write([]byte(config.App.UUID))
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
status, err := ws.WorkTree.Status()
if err != nil {
fmt.Printf("Error getting repo status: %v\n", err)
return err
}
if status.IsClean() {
fmt.Printf("Repository is clean, skipping commit...\n")
return nil
}
fmt.Println("Work Tree Status:\n" + status.String())
signature := &object.Signature{
Name: "Cert Manager",
Email: config.Certificates.Email,
When: time.Now(),
}
_, err = ws.WorkTree.Commit("Update "+ws.Domain+" @ "+time.Now().Format("Mon Jan _2 2006 15:04:05 MST"), &git.CommitOptions{Author: signature, Committer: signature})
if err != nil {
fmt.Printf("Error committing certs: %v\n", err)
return err
}
creds := &http.BasicAuth{
Username: config.Git.Username,
Password: config.Git.APIToken,
}
err = ws.Repo.Push(&git.PushOptions{
Auth: creds,
Force: true,
RemoteName: "origin",
RefSpecs: []gitconf.RefSpec{
"refs/heads/master:refs/heads/master",
},
})
if err != nil {
fmt.Printf("Error pushing to origin: %v\n", err)
return err
}
fmt.Println("Successfully uploaded to " + config.Git.Server + "/" + config.Git.OrgName + "/" + ws.Domain + repoSuffix + ".git")
return nil
}

View File

@@ -1,167 +0,0 @@
package server
import (
"fmt"
"log"
"path/filepath"
"sync"
"time"
"git.nevets.tech/Keys/CertManager/internal"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
)
var (
tickMu sync.Mutex
mgr *internal.ACMEManager
mgrMu sync.Mutex
)
func getACMEManager() (*internal.ACMEManager, error) {
mgrMu.Lock()
defer mgrMu.Unlock()
if mgr == nil {
var err error
mgr, err = internal.NewACMEManager()
if err != nil {
return nil, err
}
}
return mgr, nil
}
func Init() {
err := internal.LoadDomainConfigs()
if err != nil {
log.Fatalf("Error loading domain configs: %v", err)
}
Tick()
}
func Tick() {
tickMu.Lock()
defer tickMu.Unlock()
fmt.Println("Tick!")
var err error
mgr, err = getACMEManager()
if err != nil {
fmt.Printf("Error getting acme manager: %v\n", err)
return
}
now := time.Now().UTC()
localDomainConfigs := internal.DomainStore().Snapshot()
for domainStr, domainConfig := range localDomainConfigs {
if !domainConfig.GetBool("Domain.enabled") {
continue
}
renewPeriod := domainConfig.GetInt("Certificates.renew_period")
lastIssued := time.Unix(domainConfig.GetInt64("Internal.last_issued"), 0).UTC()
renewalDue := lastIssued.AddDate(0, 0, renewPeriod)
if now.After(renewalDue) {
//TODO extra check if certificate expiry (create cache?)
_, err = mgr.RenewForDomain(domainStr)
if err != nil {
// if no existing cert, obtain instead
_, err = mgr.ObtainForDomain(domainStr)
if err != nil {
fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err)
continue
}
}
domainConfig.Set("Internal.last_issued", time.Now().UTC().Unix())
err = internal.WriteDomainConfig(domainConfig)
if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue
}
err = internal.EncryptFileXChaCha(domainConfig.GetString("Certificates.crypto_key"), filepath.Join(mgr.CertsRoot, domainStr, domainStr+".crt"), filepath.Join(mgr.CertsRoot, domainStr, domainStr+".crt.crpt"), nil)
if err != nil {
fmt.Printf("Error encrypting domain cert for domain %s: %v\n", domainStr, err)
continue
}
err = internal.EncryptFileXChaCha(domainConfig.GetString("Certificates.crypto_key"), filepath.Join(mgr.CertsRoot, domainStr, domainStr+".key"), filepath.Join(mgr.CertsRoot, domainStr, domainStr+".key.crpt"), nil)
if err != nil {
fmt.Printf("Error encrypting domain key for domain %s: %v\n", domainStr, err)
continue
}
giteaClient := internal.CreateGiteaClient()
if giteaClient == nil {
fmt.Printf("Error creating gitea client for domain %s: %v\n", domainStr, err)
continue
}
gitWorkspace := &internal.GitWorkspace{
Storage: memory.NewStorage(),
FS: memfs.New(),
}
var repoUrl string
if !domainConfig.GetBool("Internal.repo_exists") {
repoUrl = internal.CreateGiteaRepo(domainStr, giteaClient)
if repoUrl == "" {
fmt.Printf("Error creating Gitea repo for domain %s\n", domainStr)
continue
}
domainConfig.Set("Internal.repo_exists", true)
err = internal.WriteDomainConfig(domainConfig)
if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue
}
err = internal.InitRepo(repoUrl, gitWorkspace)
if err != nil {
fmt.Printf("Error initializing repo for domain %s: %v\n", domainStr, err)
continue
}
} else {
repoUrl = internal.Config().GetString("Git.server") + "/" + internal.Config().GetString("Git.org_name") + "/" + domainStr + domainConfig.GetString("Repo.repo_suffix") + ".git"
err = internal.CloneRepo(repoUrl, gitWorkspace, internal.Server)
if err != nil {
fmt.Printf("Error cloning repo for domain %s: %v\n", domainStr, err)
continue
}
}
err = internal.AddAndPushCerts(domainStr, gitWorkspace)
if err != nil {
fmt.Printf("Error pushing certificates for domain %s: %v\n", domainStr, err)
continue
}
fmt.Printf("Successfully pushed certificates for domain %s\n", domainStr)
}
}
err = internal.SaveDomainConfigs()
if err != nil {
fmt.Printf("Error saving domain configs: %v\n", err)
}
}
func Reload() {
fmt.Println("Reloading configs...")
err := internal.LoadDomainConfigs()
if err != nil {
fmt.Printf("Error loading domain configs: %v\n", err)
return
}
mgrMu.Lock()
mgr = nil
mgrMu.Unlock()
fmt.Println("Successfully reloaded configs")
}
func Stop() {
fmt.Println("Shutting down server")
}