40 Commits

Author SHA1 Message Date
a2528e0526 Added a new test script.
Some checks failed
Release / release (push) Failing after 1m6s
2025-08-04 22:09:23 +02:00
9b0d1eceae Re-enginnered information output during issuance phase. 2025-08-04 22:09:11 +02:00
45dfdf0afc Removed --overwrite flag. 2025-08-03 12:02:47 +02:00
6e69377d1a Enhance SAN handling in issueSingleCertificate: extract CN from DN if present 2025-08-03 09:38:31 +02:00
8114d667ec Fixed a bug that prevented adding a mandatory SAN if the certificate type is server. 2025-08-03 07:37:55 +02:00
176901d960 Small fix for set-version.sh.
Some checks failed
Release / release (push) Failing after 45s
2025-08-02 13:57:27 +02:00
1991963cab Bug fixes for referening and not copying objects and few others. 2025-08-02 13:51:14 +02:00
b0f0467346 Added helper scripts that will lock and unlock changes to version.go. 2025-08-02 13:50:39 +02:00
028788f357 Updated build.sh to embed version information to the binary using changes to the version.go file. 2025-08-02 13:45:45 +02:00
090fb4b423 Moved Version variable to a separate file. 2025-08-02 13:42:25 +02:00
eb5c5c0e43 Updated tea repository name. 2025-07-30 09:01:00 +02:00
8181ac8287 Added missing go mod tidy. 2025-07-30 08:58:58 +02:00
3fe908226d Fixed unchange placeholder names. 2025-07-30 08:56:17 +02:00
8a36588c62 Added manual trigger. 2025-07-30 08:49:49 +02:00
90ce7edd28 Fixed incorrect workflow directory name. 2025-07-30 08:47:09 +02:00
11bed9c8b1 Added release workflow. 2025-07-30 08:37:21 +02:00
2fe228858f Update build process and version embedding. 2025-07-30 08:17:15 +02:00
e9d2634819 Updated documentation. 2025-07-28 21:27:05 +02:00
9d226df44f Fixes for bugs related to rendering certificate templates from defaults and variables. 2025-07-28 21:26:52 +02:00
71412ace5e Added example client,email certificate. 2025-07-28 21:25:23 +02:00
2350e3cbc1 Added a script that prints certificates. 2025-07-28 21:25:03 +02:00
d045938ff8 Updated test script 2025-07-28 21:24:46 +02:00
72424379e0 Moved test CA test location to 'ca' subdirectory. 2025-07-28 21:24:32 +02:00
54296f7526 Updated tests. 2025-07-28 19:15:51 +02:00
6682be6eb1 Added list command and ability to combine certificate usages. 2025-07-28 18:58:37 +02:00
9b7b995e97 Added function that can look for a certificate in the database. 2025-07-28 18:57:57 +02:00
b387a016be Added state file location defintion to the CA configuration. Added more certificate properties to certificate database. 2025-07-28 17:41:41 +02:00
e4469fde96 More renames. 2025-07-28 15:53:17 +02:00
bea0285007 Refactoring 2025-07-28 15:36:45 +02:00
a8308e0f4f Moved global flag variables to the global scope. Refactored some functions interfaces and removed passing global flags. 2025-07-28 13:48:38 +02:00
911d33deb2 A fix to module name. 2025-07-28 11:54:48 +02:00
8b103f4c0f Updated documentation. 2025-07-28 10:44:10 +02:00
0e86c49965 Mostly implemented issue and provision commands. Restructured AI generateed code. 2025-07-28 10:20:52 +02:00
9696f95043 Few manual optimizations and corrections of AI generated code. 2025-07-28 06:40:17 +02:00
6c5842826e Added certificate revocation and CRL generation code. 2025-07-28 01:34:21 +02:00
bd9547ff70 Simplified template rendering. 2025-07-27 21:46:27 +02:00
dba4ced05f Moved loading CA's private key and certificate to global configuration loading process. 2025-07-27 21:16:18 +02:00
e2039550e0 CAConfig global variable and refactoring. 2025-07-27 20:45:05 +02:00
10ec83273d Refactored code to one IssueCertificate function. 2025-07-27 20:00:43 +02:00
0c32da1e84 Partial implementation of CA database. 2025-07-27 19:48:38 +02:00
17 changed files with 1365 additions and 617 deletions

View File

@@ -0,0 +1,54 @@
name: Release
on:
workflow_dispatch:
push:
tags:
- 'v*.*.*'
jobs:
release:
runs-on: ubuntu-latest
steps:
# 1. Checkout source code
- name: Checkout
uses: actions/checkout@v4
# 2. Setup Go environment
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24.5'
# 3. Build binary with Version injected
- name: Build binary
run: |
VERSION=${GITEA_REF_NAME}
echo "Building version $VERSION"
go mod tidy
go build -ldflags "-s -w -X main.Version=$VERSION" -o lab-ca .
# 4. Install the tea CLI
- name: Install tea CLI
run: go install code.gitea.io/tea@latest
# 5. Authenticate tea CLI
- name: Login to Gitea
run: |
tea login add --name ci --url $GITEA_URL --token $GITEA_TOKEN
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_URL: ${{ secrets.GITEA_URL }}
# 6. Create or update release
- name: Create or update release
run: |
tea release create $GITEA_REF_NAME \
--title "$GITEA_REF_NAME" \
--note "Automated release for $GITEA_REF_NAME" || \
echo "Release already exists, skipping create."
# 7. Upload binary to the release
- name: Upload binary
run: tea release upload $GITEA_REF_NAME lab-ca

7
.gitignore vendored
View File

@@ -2,11 +2,18 @@
**/go.sum
# Ignore the binary output
lab-ca*
build
# Ignore any certificate files
*.pem
# Ignore CA configuration and certificate definitions.
*.hcl
# Ignore state files
*.json
# Include example files
!/examples/*.hcl
# Exclude MacOS Finder metadata files
.DS_Store
# Exclude default certificate and private key files directories
/ca
# Don't share VS Code files
.vscode/

222
README.md
View File

@@ -2,42 +2,50 @@
This repository contains a simple CLI tool for managing a Certificate Authority (CA).
It has been designed to be as easy to use as possible and provides a basic set of CA features:
It is designed to be easy to use and provides a basic set of CA features:
- Create a CA and a self-signed CA certificate
- Create and sign a few most common types of certificates:
- Create and sign common types of certificates:
- Server certificate
- Client certificate
- Code signing certificate
- Email certificate
- Sign a CSR to create a certificate
- Revoke a certificate
- List issued certificates
- Create a CRL (Certificate Revocation List)
> **NOTE:** Certificate types can be combined (e.g. `server,client`).
## Usage
The tool is designed to be used from the command line. It has a simple command structure:
The tool is used from the command line. It has a simple command structure:
```bash
lab-ca <command> [options]
```
There are two commands available:
The main commands available are:
- `initca` - initialize a new CA - this command creates a new CA and a self-signed CA certificate.
- `issue` - issue a new certificate - this command creates a new certificate signed by the CA.
- `initca` — Initialize a new CA and create a self-signed CA certificate and key.
- `issue` — Issue a new certificate signed by the CA (single certificate, command-line options).
- `provision` — Provision multiple certificates from a batch file (HCL) in one go.
- `revoke` — Revoke a certificate by name or serial number.
- `crl` — Generate a Certificate Revocation List (CRL) from revoked certificates.
- `list` — List issued certificates (optionally including revoked).
- `version` — Show version information for the tool.
Run the command with `-h` or `--help` or without any arguments to see the usage information. Each command has its own set of options, arguments, and a help message.
Run the command with `-h` or `--help` or without any arguments to see usage information. Each command has its own set of options, arguments, and a help message.
---
### CA Initialization
Create a new CA configuration file:
Create a new CA configuration file (HCL):
```
```hcl
ca "example_ca" {
name = "Example CA"
country = "PL"
country = "US"
organization = "ACME Corp"
key_size = 4096
validity = "10y"
@@ -45,60 +53,188 @@ ca "example_ca" {
paths {
certificates = "certs"
private_keys = "private"
state_file = "ca_state.json"
}
}
```
> **NOTE:** `lab-ca` uses HCL (HashiCorp Configuration Language) for configuration files. You can find more information about HCL [here](https://github.com/hashicorp/hcl).
- The `ca` block's label is used as a logical name for the CA and for the default state file name.
- The `paths` block defines where certificates, private keys, and the CA state file are stored.
- On Linux/macOS, the private keys directory is created with `0700` permissions.
- The command does not encrypt private keys. Do not use in production.
The `ca` block's label has no function, but may be used to identify the CA in the future.
---
The following attributes are available:
### Listing Certificates
- `name` - the name of the CA
- `country` - the country of the CA
- `organization` - the organization of the CA
- `organizational_unit` - the organizational unit of the CA (optional)
- `locality` - the locality of the CA (optional)
- `province` - the province of the CA (optional)
- `email` - the email address of the CA (optional)
- `key_size` - the size of the CA key in bits (default: 4096)
- `validity` - the validity period of the CA certificate (default: 10 years)
- `paths` - paths to store certificates and private keys
List all issued (non-revoked) certificates:
The `paths` block defines where the command will store the generated certificates and private keys. On Linux and macOS, the directory specified for private keys will be created with `0700` permissions. However, the command does not check if the directory has correct permissions, so you should ensure that the directory is not accessible by other users. On Windows, both directories will be created with the default ACL for the current user. You have to secure the private keys directory yourself.
```bash
lab-ca list
```
> **NOTE:** The command does not encrypt private keys. It is not designed to be used in a production environment.
To include revoked certificates:
## Certificate Issuance
```bash
lab-ca list --revoked
```
To issue a new certificate, you can use the `issue` command and specify the certificate definition on the command line, or use batch mode and provide a file with certificate definitions.
---
The definition file also uses HCL syntax. Here is an example of a certificate definition:
### Issuing a Certificate
Issue a new certificate from the command line:
```bash
lab-ca issue --name <name> [--subject <subject>] [--type <type>] [--validity <period>] [--san <SAN> ...] [--overwrite] [--dry-run] [--verbose]
```
- `--name` (required): Name for the certificate and key files (used as subject if `--subject` is omitted)
- `--subject`: Subject Common Name or full DN (optional, defaults to `--name`)
- `--type`: Certificate type: `client`, `server`, `code-signing`, `email` (comma-separated for multiple usages; default: `server`)
- `--validity`: Validity period (e.g. `2y`, `6m`, `30d`; default: `1y`)
- `--san`: Subject Alternative Name (repeatable; e.g. `dns:example.com`, `ip:1.2.3.4`, `email:user@example.com`)
- `--overwrite`: Allow overwriting existing files
- `--dry-run`: Validate and show what would be created, but do not write files
- `--verbose`: Print detailed information
---
### Provisioning Certificates (Batch)
Provision multiple certificates from a batch file (HCL):
```bash
lab-ca provision --file <certificates.hcl> [--overwrite] [--verbose]
```
#### Example HCL Provisioning File
```hcl
defaults {
subject = "{{ .Name }}.example.com"
type = "server"
subject = "{{ .Name }}.example.org"
type = "server,client"
validity = "1y"
san = ["DNS:{{ .Name }}.example.com"]
san = ["DNS:{{ .Name }}.example.org"]
}
certificate "grafana" {
# from default: subject = "{{ .Name }}.example.com" # result: grafana.example.com
# from default: type = "server"
# from default: validity = "1y"
# from default: san = ["DNS:{{ .Name }}.example.com"] # result: [ "DNS:grafana.example.com" ]
variables = {
Domain = "example.net"
Country = "EX"
}
certificate "loki" {
subject = "{{ .Name }}.example.net" # result: loki.example.net
# from default: type = "server"
certificate "service1" {
# from default: subject = "{{ .Name }}.example.org"
# from default: type = "server,client"
# from default: validity = "1y"
san = ["DNS:{{ .Name }}.example.net"] # result: [ "DNS:loki.example.net" ]
# from default: san = ["DNS:service1.example.org"]
}
certificate "service2" {
subject = "{{ .Name }}.{{ .Domain }}" # result: service2.example.net
san = ["DNS:{{ .Name }}.{{ .Domain }}"] # result: [ "DNS:service2.example.net" ]
}
certificate "service3" {}
certificate "user1" {
subject = "CN=User One,emailAddress=user1@example.org,O=Example,C=US"
type = "client,email"
validity = "1y"
san = ["email:user1@example.net"]
}
```
Values specified in the `defaults` block will be used for all certificates unless overridden in individual certificate definitions. Go-style template syntax is also supported, so you can use `{{ .Name }}` to refer to the certificate name.
- The `defaults` block provides default values for all certificates unless overridden.
- The `variables` map can be used in Go template expressions in any field.
- Each `certificate` block defines a certificate to be issued. The block label is available as `{{ .Name }}` in templates.
- Fields:
- `subject`: Subject string (can be a template)
- `type`: Comma-separated usages (server, client, code-signing, email)
- `validity`: Validity period (e.g. `1y`, `6m`, `30d`)
- `san`: List of SANs (e.g. `DNS:...`, `IP:...`, `email:...`)
You can use DNS or IP SANs for server certificates (`server` and `server-only`), and email SANs for email certificates (`email`). The command will check if the SAN is valid based on the type of certificate.
---
### Revoking a Certificate
Revoke a certificate by name or serial number:
```bash
lab-ca revoke --name <name> [--reason <reason>]
lab-ca revoke --serial <serial> [--reason <reason>]
```
- `--reason` can be one of: `unspecified`, `keyCompromise`, `caCompromise`, `affiliationChanged`, `superseded`, `cessationOfOperation`, `certificateHold`, `removeFromCRL` (default: `cessationOfOperation`)
---
### Generating a CRL
Generate a Certificate Revocation List (CRL) from revoked certificates:
```bash
lab-ca crl [--crl-file <path>] [--validity-days <days>]
```
- `--crl-file`: Output path for CRL file (default: `crl.pem`)
- `--validity-days`: CRL validity in days (default: 30)
---
### Version
Show version information:
```bash
lab-ca version
```
---
## Configuration and Templates
- All configuration and provisioning files use HCL (HashiCorp Configuration Language).
- Go template syntax is supported in `subject`, `san`, and other string fields. The following variables are available:
- `.Name`: The certificate name (from the block label)
- Any key from the `variables` map
Example:
```hcl
subject = "{{ .Name }}.{{ .Domain }}"
san = ["DNS:{{ .Name }}.{{ .Domain }}"]
```
## Certificate Types and SANs
- `server`: For server certificates. SANs should be DNS or IP.
- `client`: For client certificates. SANs can be email or DNS.
- `email`: For S/MIME/email certificates. SANs should be email.
- `code-signing`: For code signing certificates.
The tool checks that SANs are valid for the selected certificate type(s). Certificate usage can be combined (e.g. `server,client`).
---
## Example: Real-World Provisioning File
See `examples/example-certificates.hcl` for a more advanced provisioning file with templates and variables.
## Building the Tool
The repository includes a `build.sh` script to build the CLI tool. It updates the version in `version.go` and builds the binary.
To ignore changes made to `version.go` in Git, you can run:
```bash
git update-index --assume-unchanged version.go
```
---
## Notes
- The tool does not encrypt private keys. Protect your private keys directory.
- Not intended for production use.
- For more information about HCL, see: https://github.com/hashicorp/hcl

View File

@@ -6,4 +6,21 @@ if [ $? -eq 0 ]; then
else
VERSION="dev"
fi
go build -ldflags "-X main.Version=$VERSION" -o lab-ca
# Hardcode the version into main.go
sed -i '' "s/^var Version = .*/var Version = \"$VERSION\"/" version.go
if echo $VERSION | grep -q 'dirty$'; then
echo "Building in development mode, output directory is set to 'build'."
OUTPUT_DIR=build
# Make sure the output directory exists, create it if it is not
mkdir -p $OUTPUT_DIR
else
echo "Building with version: $VERSION"
OUTPUT_DIR=$GOHOME/bin
fi
# Build the Lab CA binary with version information
# go build -ldflags "-X main.Version=$VERSION" -o $OUTPUT_DIR/lab-ca
go build -o $OUTPUT_DIR/lab-ca

1020
ca.go

File diff suppressed because it is too large Load Diff

220
certdb.go Normal file
View File

@@ -0,0 +1,220 @@
// A certificate database management functions
package main
import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/json"
"encoding/pem"
"fmt"
"math/big"
"os"
"time"
)
// CAState represents the persisted CA state in JSON
type CAState struct {
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
Serial int `json:"serial,omitempty"`
CRLNumber int `json:"crlNumber"`
Certificates []CertificateRecord `json:"certificates"`
}
// CertificateRecord represents a single certificate record in the CA state
type CertificateRecord struct {
Name string `json:"name"`
Subject string `json:"subject"`
Type string `json:"type"`
Issued string `json:"issued"`
Expires string `json:"expires"`
Serial string `json:"serial"`
RevokedAt string `json:"revokedAt,omitempty"`
RevokeReason int `json:"revokeReason,omitempty"`
}
// Look for a certifcate by its name
func (c *CAState) FindByName(name string, all bool) *CertificateRecord {
for i := range c.Certificates {
cert := &c.Certificates[i]
if cert.RevokedAt != "" && !all {
continue
}
if cert.Name == name {
return cert
}
}
return nil
}
// Look for a certificate by its serial
func (c *CAState) FindBySerial(serial string, all bool) *CertificateRecord {
for i := range c.Certificates {
cert := &c.Certificates[i]
if cert.RevokedAt != "" && !all {
continue
}
if cert.Serial == serial {
return cert
}
}
return nil
}
// LoadCAState loads the CA state from a JSON file
func LoadCAState() error {
fmt.Printf("Loading CA state from %s\n", caStatePath)
f, err := os.Open(caStatePath)
if err != nil {
if os.IsNotExist(err) {
// File does not exist, treat as empty state
caState = &CAState{}
return nil
}
return err
}
defer f.Close()
caState = &CAState{}
if err := json.NewDecoder(f).Decode(caState); err != nil {
return err
}
return nil
}
// SaveCAState saves the CA state to a JSON file
func SaveCAState() error {
caState.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
f, err := os.Create(caStatePath)
if err != nil {
return err
}
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
return enc.Encode(caState)
}
// UpdateCAStateAfterIssue updates the CA state JSON after issuing a certificate
func (s *CAState) UpdateCAStateAfterIssue(serialType, name string, subject string, certType string, serialNumber any, validity time.Duration) error {
if s == nil {
return fmt.Errorf("CAState is nil in UpdateCAStateAfterIssue. This indicates a programming error.")
}
issued := time.Now().UTC().Format(time.RFC3339)
expires := time.Now().Add(validity).UTC().Format(time.RFC3339)
serialStr := ""
switch serialType {
case "sequential":
serialStr = fmt.Sprintf("%d", caState.Serial)
caState.Serial++
case "random":
serialStr = fmt.Sprintf("%x", serialNumber)
default:
serialStr = fmt.Sprintf("%v", serialNumber)
}
s.AddCertificate(name, subject, certType, issued, expires, serialStr)
return nil
}
func (s *CAState) AddCertificate(name, subject, certType, issued, expires, serial string) {
if s == nil {
fmt.Fprintf(os.Stderr, "FATAL: CAState is nil in AddCertificate. This indicates a programming error.\n")
return
}
rec := CertificateRecord{
Name: name,
Subject: subject,
Type: certType,
Issued: issued,
Expires: expires,
Serial: serial,
}
s.Certificates = append(s.Certificates, rec)
}
// RevokeCertificate revokes a certificate by serial number and reason code, updates state, and saves to disk
func (s *CAState) RevokeCertificate(serial string, reason int) error {
if s == nil {
return fmt.Errorf("CAState is nil in RevokeCertificate. This indicates a programming error.")
}
revoked := false
revokedAt := time.Now().UTC().Format(time.RFC3339)
for i, rec := range s.Certificates {
if rec.Serial == serial && rec.RevokedAt == "" {
s.Certificates[i].RevokedAt = revokedAt
s.Certificates[i].RevokeReason = reason
revoked = true
}
}
if !revoked {
return fmt.Errorf("certificate with serial %s not found or already revoked", serial)
}
s.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
if err := SaveCAState(); err != nil {
return fmt.Errorf("failed to save CA state after revocation: %v", err)
}
return nil
}
// GenerateCRL generates a CRL file from revoked certificates and writes it to the given path
// validityDays defines the number of days for which the CRL is valid (NextUpdate - ThisUpdate)
func (s *CAState) GenerateCRL(crlPath string, validityDays int) error {
if s == nil {
return fmt.Errorf("CAState is nil in GenerateCRL")
}
if caCert == nil || caKey == nil {
return fmt.Errorf("CA certificate or key not loaded")
}
var revokedCerts []pkix.RevokedCertificate
for _, rec := range s.Certificates {
if rec.RevokedAt != "" {
serial := new(big.Int)
serial.SetString(rec.Serial, 16) // Parse serial as hex
revokedTime, err := time.Parse(time.RFC3339, rec.RevokedAt)
if err != nil {
return fmt.Errorf("invalid revocation time for serial %s: %v", rec.Serial, err)
}
reasonCode := rec.RevokeReason
// RFC 5280: Reason code must be encoded as ASN.1 ENUMERATED, not a raw byte
// Use ASN.1 encoding for ENUMERATED
asn1Reason, err := asn1.Marshal(asn1.Enumerated(reasonCode))
if err != nil {
return fmt.Errorf("failed to ASN.1 encode reason code: %v", err)
}
revokedCerts = append(revokedCerts, pkix.RevokedCertificate{
SerialNumber: serial,
RevocationTime: revokedTime,
Extensions: []pkix.Extension{{Id: []int{2, 5, 29, 21}, Value: asn1Reason}},
})
}
}
now := time.Now().UTC()
nextUpdate := now.Add(time.Duration(validityDays) * 24 * time.Hour) // validityDays * 24 * 60 * 60 * 1000 milliseconds
template := &x509.RevocationList{
SignatureAlgorithm: caCert.SignatureAlgorithm,
RevokedCertificates: revokedCerts,
Number: big.NewInt(int64(s.CRLNumber + 1)),
ThisUpdate: now,
NextUpdate: nextUpdate,
Issuer: caCert.Subject,
}
crlBytes, err := x509.CreateRevocationList(nil, template, caCert, caKey)
if err != nil {
return fmt.Errorf("failed to create CRL: %v", err)
}
f, err := os.Create(crlPath)
if err != nil {
return fmt.Errorf("failed to create CRL file: %v", err)
}
defer f.Close()
if err := pem.Encode(f, &pem.Block{Type: "X509 CRL", Bytes: crlBytes}); err != nil {
return fmt.Errorf("failed to write CRL PEM: %v", err)
}
// Update CRL number and save state
s.CRLNumber++
s.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
if err := SaveCAState(); err != nil {
return fmt.Errorf("failed to update CA state after CRL generation: %v", err)
}
return nil
}

View File

@@ -1,13 +1,14 @@
ca "example_ca" {
name = "Example CA"
country = "PL"
name = "Example CA"
country = "PL"
organization = "ACME Corp"
serial_type = "random"
key_size = 4096
validity = "10y"
serial_type = "random"
key_size = 4096
validity = "10y"
paths {
certificates = "certs"
private_keys = "private"
state_file = "ca_state.json"
}
}

View File

@@ -1,10 +1,15 @@
defaults {
subject = "{{ .Name }}.koszewscy.waw.pl"
type = "server"
type = "server,client"
validity = "1y"
san = ["DNS:{{ .Name }}.koszewscy.waw.pl"]
}
variables = {
Domain = "koszewscy.email"
Country = "PL"
}
certificate "grafana" {
# from default: subject = "{{ .Name }}.koszewscy.waw.pl" # result: grafana.koszewscy.waw.pl
# from default: type = "server"
@@ -18,3 +23,17 @@ certificate "loki" {
# from default: validity = "1y"
san = ["DNS:{{ .Name }}.koszewscy.email"] # result: [ "DNS:loki.koszewscy.email" ]
}
certificate "alloy" {}
certificate "prometheus" {
subject = "{{ .Name }}.{{ .Domain }}" # result: prometheus.koszewscy.email
san = ["DNS:{{ .Name }}.{{ .Domain }}"] # result: [ "DNS:prometheus.koszewscy.email" ]
}
certificate "slawek" {
subject = "CN=Slawomir Koszewski,emailAddress=slawek@koszewscy.waw.pl,O=Koszewscy,C=PL"
type = "client,email"
validity = "1y"
san = ["email:slawek@koszewscy.email"]
}

View File

@@ -0,0 +1,14 @@
{
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-01T00:00:00Z",
"serial": 1,
"certificates": [
{
"name": "",
"issued": "",
"expires": "",
"serial": "",
"valid": true
}
]
}

2
go.mod
View File

@@ -1,4 +1,4 @@
module koszewscy.waw.pl/slawek/lab-ca
module gitea.koszewscy.waw.pl/slawek/lab-ca
go 1.24.5

View File

@@ -0,0 +1,3 @@
#!/bin/bash
git update-index --assume-unchanged version.go

294
main.go
View File

@@ -7,19 +7,33 @@ import (
"github.com/spf13/cobra"
)
var Version = "dev"
// Global flags available to all commands
var dryRun bool
var verbose bool
func main() {
var configPath string
var overwrite bool
// list command flags
var listRevoked bool
// issue command flags
var name string
var subject string
var certType string
var validity string
var san []string
var name string
var fromFile string
var dryRun bool
var verbose bool
// provision command flags
var provisionFile string
// crl command flags
var crlFile string
var crlValidityDays int
// revoke command flags
var revokeName string
var revokeSerial string
var revokeReasonStr string
var rootCmd = &cobra.Command{
Use: "lab-ca",
@@ -30,124 +44,186 @@ func main() {
},
}
var initcaCmd = &cobra.Command{
// Define persistent flags (global for all commands)
rootCmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "Print detailed information about each processed certificate")
rootCmd.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Validate and show what would be created, but do not write files (batch mode)")
rootCmd.PersistentFlags().StringVar(&caConfigPath, "config", "ca_config.hcl", "Path to CA configuration file")
// lab-ca initca command
var initCmd = &cobra.Command{
Use: "initca",
Short: "Generate a new CA certificate and key",
Run: func(cmd *cobra.Command, args []string) {
InitCA(configPath, overwrite)
InitCA()
},
}
rootCmd.AddCommand(initCmd)
initcaCmd.Flags().StringVar(&configPath, "config", "ca_config.hcl", "Path to CA configuration file")
initcaCmd.Flags().BoolVar(&overwrite, "overwrite", false, "Allow overwriting existing files")
// lab-ca list command
var listCmd = &cobra.Command{
Use: "list",
Short: "List issued certificates",
Run: func(cmd *cobra.Command, args []string) {
err := LoadCA()
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(1)
}
for _, certDef := range caState.Certificates {
if certDef.RevokedAt != "" {
continue
}
fmt.Printf("Certificate %s\n", certDef.Name)
fmt.Printf("\tSubject: %s\n\tType: %s\n\tIssued at: %s\n",
certDef.Subject, certDef.Type, certDef.Issued)
}
},
}
listCmd.Flags().BoolVar(&listRevoked, "revoked", false, "List all certificates, including revoked ones")
rootCmd.AddCommand(listCmd)
// lab-ca issue command
var issueCmd = &cobra.Command{
Use: "issue",
Short: "Issue a new certificate (client, server, server-only, code-signing, email)",
Run: func(cmd *cobra.Command, args []string) {
if fromFile != "" {
certDefs, defaults, err := LoadCertificatesFile(fromFile)
if err != nil {
fmt.Printf("Error loading certificates file: %v\n", err)
return
}
successes := 0
errors := 0
for i, def := range certDefs {
if defaults != nil {
if def.Type == "" {
def.Type = defaults.Type
}
if def.Validity == "" {
def.Validity = defaults.Validity
}
if len(def.SAN) == 0 && len(defaults.SAN) > 0 {
def.SAN = defaults.SAN
}
}
finalDef := renderCertificateDefTemplates(def, defaults)
err := IssueCertificate(CertificateDefinition{
Name: name,
Subject: subject,
Type: certType,
Validity: validity,
SAN: san,
})
fmt.Printf("[%d/%d] Issuing %s... ", i+1, len(certDefs), finalDef.Name)
if dryRun {
fmt.Printf("(dry run)\n")
}
if verbose {
fmt.Printf("\n Name: %s\n", finalDef.Name)
fmt.Printf(" Subject: %s\n", finalDef.Subject)
fmt.Printf(" Type: %s\n", finalDef.Type)
fmt.Printf(" Validity: %s\n", finalDef.Validity)
fmt.Printf(" SAN: %v\n\n", finalDef.SAN)
}
basename := finalDef.Name + "." + finalDef.Type
if dryRun {
successes++
continue
}
err := IssueCertificateWithBasename(configPath, basename, finalDef.Subject, finalDef.Type, finalDef.Validity, finalDef.SAN, overwrite, dryRun)
if err != nil {
fmt.Printf("ERROR: %v\n", err)
errors++
} else {
if !verbose {
fmt.Printf("done\n")
}
successes++
}
}
fmt.Printf("Batch complete: %d succeeded, %d failed.\n", successes, errors)
return
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(1)
}
// Simple mode
subjectName := subject
if subjectName == "" {
subjectName = name
}
finalDef := renderCertificateDefTemplates(CertificateDef{Name: name, Subject: subject, Type: certType, Validity: validity, SAN: san}, nil)
if verbose {
fmt.Printf("\nCertificate:\n")
fmt.Printf(" Name: %s\n", finalDef.Name)
fmt.Printf(" Subject: %s\n", finalDef.Subject)
fmt.Printf(" Type: %s\n", finalDef.Type)
fmt.Printf(" Validity: %s\n", finalDef.Validity)
fmt.Printf(" SAN: %v\n", finalDef.SAN)
}
IssueCertificate(configPath, finalDef.Name, finalDef.Subject, finalDef.Type, finalDef.Validity, finalDef.SAN, overwrite)
},
}
issueCmd.Flags().StringVar(&configPath, "config", "ca_config.hcl", "Path to CA configuration file")
issueCmd.Flags().StringVar(&subject, "subject", "", "Subject Common Name for the certificate (optional, defaults to --name)")
issueCmd.Flags().StringVar(&certType, "type", "server", "Certificate type: client, server, server-only, code-signing, email")
issueCmd.Flags().StringArrayVar(&san, "san", nil,
"Subject Alternative Name (SAN). Use multiple times for multiple values.\n"+
"Format: dns:example.com, ip:1.2.3.4, email:user@example.com")
issueCmd.Flags().StringVar(&validity, "validity", "1y", "Certificate validity (e.g. 2y, 6m, 30d). Overrides config file for this certificate.")
issueCmd.Flags().BoolVar(&overwrite, "overwrite", false, "Allow overwriting existing files")
issueCmd.Flags().StringVar(&fromFile, "from-file", "", "Path to HCL file with multiple certificate definitions (batch mode)")
issueCmd.Flags().BoolVar(&dryRun, "dry-run", false, "Validate and show what would be created, but do not write files (batch mode)")
issueCmd.Flags().BoolVar(&verbose, "verbose", false, "Print detailed information about each processed certificate")
// Only require --name in simple mode
issueCmd.Flags().StringVar(&name, "name", "", "Name for the certificate and key files (used as subject if --subject is omitted)")
issueCmd.PreRun = func(cmd *cobra.Command, args []string) {
if fromFile == "" {
cmd.MarkFlagRequired("name")
}
issueCmd.Flags().StringVar(&subject, "subject", "", "Subject Common Name for the certificate (optional, defaults to --name)")
issueCmd.Flags().StringVar(&certType, "type", "server",
"Certificate type: client, server, code-signing, email.\nCombine by specifying more than one separated by comma.")
issueCmd.Flags().StringArrayVar(&san, "san", nil,
"Subject Alternative Name (SAN). Use multiple times for multiple values.\nFormat: dns:example.com, ip:1.2.3.4, email:user@example.com")
issueCmd.Flags().StringVar(&validity, "validity", "1y", "Certificate validity (e.g. 2y, 6m, 30d). Overrides config file for this certificate.")
issueCmd.MarkFlagRequired("name")
rootCmd.AddCommand(issueCmd)
// lab-ca provision command
var provisionCmd = &cobra.Command{
Use: "provision",
Short: "Provision certificates from a batch file (HCL)",
Run: func(cmd *cobra.Command, args []string) {
err := ProvisionCertificates(provisionFile)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(1)
}
},
}
provisionCmd.Flags().StringVar(&provisionFile, "file", "", "Path to HCL file with certificate definitions (required)")
provisionCmd.MarkFlagRequired("file")
rootCmd.AddCommand(provisionCmd)
// lab-ca revoke command
var revokeCmd = &cobra.Command{
Use: "revoke",
Short: "Revoke a certificate by name or serial number",
Run: func(cmd *cobra.Command, args []string) {
if err := LoadCA(); err != nil {
fmt.Printf("ERROR: %v\n", err)
os.Exit(1)
}
if (revokeName == "" && revokeSerial == "") || (revokeName != "" && revokeSerial != "") {
fmt.Println("ERROR: You must specify either --name or --serial (but not both)")
os.Exit(1)
}
serial := ""
if revokeName != "" {
found := false
for _, rec := range caState.Certificates {
if rec.Name == revokeName {
serial = rec.Serial
found = true
break
}
}
if !found {
fmt.Printf("ERROR: Certificate with name '%s' not found\n", revokeName)
os.Exit(1)
}
} else {
serial = revokeSerial
}
reasonMap := map[string]int{
"unspecified": 0,
"keyCompromise": 1,
"caCompromise": 2,
"affiliationChanged": 3,
"superseded": 4,
"cessationOfOperation": 5,
"certificateHold": 6,
"removeFromCRL": 8,
}
reasonCode, ok := reasonMap[revokeReasonStr]
if !ok {
fmt.Printf("ERROR: Unknown revocation reason '%s'. Valid reasons: ", revokeReasonStr)
for k := range reasonMap {
fmt.Printf("%s ", k)
}
fmt.Println()
os.Exit(1)
}
if err := caState.RevokeCertificate(serial, reasonCode); err != nil {
fmt.Printf("ERROR: %v\n", err)
os.Exit(1)
}
fmt.Printf("Certificate with serial %s revoked (reason: %s, code %d)\n", serial, revokeReasonStr, reasonCode)
},
}
revokeCmd.Flags().StringVar(&revokeName, "name", "", "Certificate name to revoke (mutually exclusive with --serial)")
revokeCmd.Flags().StringVar(&revokeSerial, "serial", "", "Certificate serial number to revoke (mutually exclusive with --name)")
revokeCmd.Flags().StringVar(&revokeReasonStr, "reason", "cessationOfOperation", "Revocation reason (unspecified, keyCompromise, caCompromise, affiliationChanged, superseded, cessationOfOperation, certificateHold, removeFromCRL)")
rootCmd.AddCommand(revokeCmd)
// lab-ca crl command
var crlCmd = &cobra.Command{
Use: "crl",
Short: "Generate a Certificate Revocation List (CRL)",
Run: func(cmd *cobra.Command, args []string) {
if err := LoadCA(); err != nil {
fmt.Printf("ERROR: %v\n", err)
os.Exit(1)
}
if crlValidityDays <= 0 {
crlValidityDays = 30 // default to 30 days
}
err := caState.GenerateCRL(crlFile, crlValidityDays)
if err != nil {
fmt.Printf("ERROR generating CRL: %v\n", err)
os.Exit(1)
}
fmt.Printf("CRL written to %s (valid for %d days)\n", crlFile, crlValidityDays)
},
}
crlCmd.Flags().StringVar(&crlFile, "crl-file", "crl.pem", "Output path for CRL file (default: crl.pem)")
crlCmd.Flags().IntVar(&crlValidityDays, "validity-days", 30, "CRL validity in days (default: 30)")
rootCmd.AddCommand(crlCmd)
// lab-ca version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "Show version information",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("lab-ca version: %s\n", Version)
fmt.Printf("lab-ca version: %s\n", getVersionDescription())
},
}
rootCmd.AddCommand(initcaCmd)
rootCmd.AddCommand(issueCmd)
rootCmd.AddCommand(versionCmd)
if err := rootCmd.Execute(); err != nil {
@@ -155,16 +231,28 @@ func main() {
}
}
func getVersionDescription() string {
if Version == "" {
return "no version information was compiled in"
}
return Version
}
func printMainHelp() {
fmt.Println("lab-ca - Certificate Authority Utility")
fmt.Printf("lab-ca - Certificate Authority Utility\n")
fmt.Printf("Version: %s\n", getVersionDescription())
fmt.Println()
fmt.Println("Usage:")
fmt.Println(" lab-ca <command> [options]")
fmt.Println()
fmt.Println("Available commands:")
fmt.Println(" initca Generate a new CA certificate and key")
fmt.Println(" issue Issue a new client/server certificate")
fmt.Println(" version Show version information")
fmt.Println(" list List issued certificates")
fmt.Println(" issue Issue a new certificate")
fmt.Println(" provision Provision certificates from a batch file (HCL)")
fmt.Println(" revoke Revoke a certificate by name or serial number")
fmt.Println(" crl Generate a Certificate Revocation List (CRL)")
fmt.Println(" version Show version information")
fmt.Println()
fmt.Println("Use 'lab-ca <command> --help' for more information about a command.")
}

11
print-certificates.sh Executable file
View File

@@ -0,0 +1,11 @@
#!/bin/bash
GREEN='\033[0;32m'
NC='\033[0m' # No Color
for cert in ca/certs/*.pem
do
echo -e "${GREEN}----- Certificate: $(basename $cert)${NC}"
openssl x509 -in "$cert" -noout -text
echo -e "${GREEN}----- End of Certificate -----${NC}\n"
done

13
run-test-2.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/bin/bash
if [ "-v" == "$1" ]; then
VERBOSE="--verbose"
shift
else
VERBOSE=""
fi
./build.sh
rm -rf docker_ca
build/lab-ca $VERBOSE --config docker_ca.hcl initca
build/lab-ca $VERBOSE --config docker_ca.hcl provision --file docker.hcl

59
run-test.sh Executable file
View File

@@ -0,0 +1,59 @@
#!/bin/bash
GREEN='\033[0;32m'
NC='\033[0m' # No Color
LAB_CA="build/lab-ca"
PROVISION_CONFIG="examples/example-certificates.hcl"
# Build and install
# Build script for lab-ca with version injection from git tag
git describe --tags --always --dirty > /dev/null 2>&1
if [ $? -eq 0 ]; then
VERSION=$(git describe --tags --always --dirty)
else
VERSION="dev"
fi
go build -ldflags "-X main.Version=$VERSION" -o $LAB_CA
if [ $? -ne 0 ]; then
echo -e "${GREEN}Build failed!${NC}"
exit 1
fi
echo -e "${GREEN}Build successful! Version: $VERSION${NC}"
rm -rf ca
echo -e "\n${GREEN}Initializing CA...${NC}"
$LAB_CA initca || exit 1
echo -e "\n${GREEN}Issuing single certificate with incorrect argument..${NC}"
$LAB_CA issue --name "blackpanther2.koszewscy.waw.pl"
if [ $? -ne 0 ]; then
echo -e "${GREEN}Failed to issue certificate.${NC} - that's fine it was intended."
else
echo -e "${GREEN}FATAL: The command should fail, but it didn't!${NC}"
exit 1
fi
echo -e "\n${GREEN}Issuing single certificate..${NC}"
$LAB_CA issue --name "blackpanther2" --subject "blackpanther2.koszewscy.waw.pl" || exit 1
echo -e "\n${GREEN}Issuing multiple certificates from file...${NC}"
$LAB_CA provision --file $PROVISION_CONFIG --verbose || exit 1
echo -e "\n${GREEN}Revoking a certificate by name...${NC}"
$LAB_CA revoke --name "loki" || exit 1
echo -e "\n${GREEN}Generating CRL...${NC}"
$LAB_CA crl --validity-days 7 --crl-file crl-1.pem || exit 1
openssl crl -noout -text -in crl-1.pem
echo -e "\n${GREEN}Revoking a second certificate by name...${NC}"
$LAB_CA revoke --name "alloy" || exit 1
echo -e "\n${GREEN}Generating a second CRL...${NC}"
$LAB_CA crl --validity-days 7 --crl-file crl-2.pem || exit 1
openssl crl -noout -text -in crl-2.pem
echo -e "\n${GREEN}Dumping CA state...${NC}"
jq '.' ca/ca_state.json
# Finished
echo -e "\n${GREEN}All operations completed successfully!${NC}"

7
set-version.sh Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
VERSION=${1:-$(git describe --tags --always --dirty 2>/dev/null || echo "dev")}
# Allow git to track changes to version.go
git update-index --no-assume-unchanged version.go
# Hardcode the version into main.go
sed -i '' "s/^var Version = .*/var Version = \"$VERSION\"/" version.go

3
version.go Normal file
View File

@@ -0,0 +1,3 @@
package main
var Version = "v0.3.2"