# DashCA Certificate Generation API

## Overview

DashCA now provides automatic SSL certificate generation for services on your network. This allows services like Technitium DNS to automatically obtain valid SSL certificates signed by your internal CA.

## Features

- **Automatic Certificate Generation**: Generate SSL certificates for any domain on demand
- **Multiple Formats**: PFX, PEM, CRT, KEY, and full chain certificates
- **Certificate Caching**: Certificates are cached and reused if still valid (>30 days remaining)
- **No Authentication Required**: Public API endpoints for easy automation
- **Automatic Renewal**: Certificates are regenerated when they expire in less than 30 days

## API Endpoints

### 1. Generate/Download Certificate

**GET** `/api/ca/cert/:domain`

Generate and download an SSL certificate for the specified domain.

**Parameters:**
- `:domain` (required) - The domain name (e.g., `dns1.sami`, `dns2.sami`)
- `format` (optional) - Certificate format: `pfx`, `pem`, `crt`, `key`, or `fullchain` (default: `pfx`)
- `password` (optional) - Password for PFX files (default: `dashcaddy`)

**Examples:**

```bash
# Download PFX certificate for dns1.sami
curl -O "https://ca.sami/api/ca/cert/dns1.sami?format=pfx&password=dashcaddy"

# Download PEM bundle (private key + certificate + chain)
curl -O "https://ca.sami/api/ca/cert/dns1.sami?format=pem"

# Download certificate only
curl -O "https://ca.sami/api/ca/cert/dns1.sami?format=crt"

# Download private key only
curl -O "https://ca.sami/api/ca/cert/dns1.sami?format=key"

# Download full certificate chain (cert + intermediate + root)
curl -O "https://ca.sami/api/ca/cert/dns1.sami?format=fullchain"
```

**PowerShell:**

```powershell
Invoke-WebRequest -Uri "https://ca.sami/api/ca/cert/dns1.sami?format=pfx" -OutFile "dns1.pfx"
```

### 2. List Generated Certificates

**GET** `/api/ca/certs`

List all generated certificates with their status and expiration information.

**Example:**

```bash
curl https://ca.sami/api/ca/certs
```

**Response:**

```json
{
  "success": true,
  "certificates": [
    {
      "domain": "dns1.sami",
      "subject": "CN=dns1.sami",
      "validFrom": "Feb 11 21:37:02 2026 GMT",
      "validUntil": "Feb 11 21:37:02 2027 GMT",
      "daysUntilExpiration": 364,
      "fingerprint": "4E:74:F8:49:...",
      "status": "valid"
    }
  ]
}
```

**Status values:**
- `valid` - Certificate is valid and has >30 days remaining
- `expiring-soon` - Certificate expires in less than 30 days
- `expired` - Certificate has expired

## Certificate Details

- **Validity**: 365 days (1 year)
- **Algorithm**: RSA 2048-bit (for broad compatibility)
- **Signature**: SHA-256
- **Key Usage**: Key Encipherment, Data Encipherment, Digital Signature
- **Extended Key Usage**: Server Authentication
- **Subject Alternative Names**: Primary domain + wildcard subdomain (if applicable)

Example: A certificate for `dns1.sami` includes both `dns1.sami` and `*.dns1.sami`.

## Automation Scripts

### PowerShell - Update Technitium DNS Certificate

Located at: `C:\caddy\scripts\update-technitium-cert.ps1`

```powershell
# Update certificate for a single DNS server
.\update-technitium-cert.ps1 `
    -Domain "dns1.sami" `
    -TechnitiumUrl "http://192.168.254.204:5380" `
    -CertPath "C:\ProgramData\Technitium\DnsServer\cert.pfx"

# Update all DNS servers at once
.\update-all-dns-certs.ps1
```

### Schedule Automatic Updates

Create a Windows scheduled task to update certificates monthly:

```powershell
# Create scheduled task for monthly certificate updates
schtasks /create `
    /tn "Update DNS Certificates" `
    /tr "powershell -ExecutionPolicy Bypass -File C:\caddy\scripts\update-all-dns-certs.ps1" `
    /sc monthly `
    /d 1 `
    /st 03:00 `
    /ru SYSTEM
```

## Manual Certificate Installation

### Technitium DNS

1. Download PFX certificate:
   ```bash
   curl -k -O "https://ca.sami/api/ca/cert/dns1.sami?format=pfx&password=dashcaddy"
   ```

2. Copy to Technitium directory:
   ```
   Copy dns1.sami.pfx to C:\ProgramData\Technitium\DnsServer\cert.pfx
   ```

3. Restart Technitium DNS Server service:
   ```powershell
   Restart-Service "Technitium DNS Server"
   ```

4. Access Technitium DNS web interface via HTTPS:
   ```
   https://dns1.sami:5380
   ```

### Other Services

For other services requiring SSL certificates, use the appropriate format:

- **PFX**: Windows services, .NET applications, IIS
- **PEM**: Most Linux services (Apache, Nginx, HAProxy)
- **CRT + KEY**: Separate certificate and key files (Nginx, Apache)
- **Fullchain**: Full certificate chain for maximum compatibility

## Security Considerations

1. **Root CA Protection**: The root CA private key is mounted read-only in the API container
2. **Serial Number Tracking**: Each certificate gets a unique serial number stored per domain
3. **Password Protection**: PFX files are password-protected (default: `dashcaddy`)
4. **Network Access**: Certificate API is available on your Tailscale network only
5. **No Revocation**: Certificates cannot be revoked; wait for expiration or delete manually

## Troubleshooting

### Certificate Generation Fails

Check if the PKI directory is accessible:
```bash
docker exec dashcaddy-api ls -la /app/pki/
```

Should show: `root.crt`, `root.key`, `intermediate.crt`, `intermediate.key`

### Certificate Not Trusted by Browser

Install the root CA certificate on your device:
```bash
curl -O https://ca.sami/root.crt
```

Follow platform-specific installation instructions on the DashCA homepage.

### Certificate Expired

Request a new certificate - it will automatically regenerate:
```bash
curl -O "https://ca.sami/api/ca/cert/dns1.sami?format=pfx"
```

### Generated Certificates Location

On the host system:
```
C:\caddy\generated-certs\
  ├── dns1.sami\
  │   ├── server.key
  │   ├── server.csr
  │   ├── server.crt
  │   ├── server.pfx
  │   ├── server.pem
  │   └── fullchain.pem
  ├── dns2.sami\
  └── dns3.sami\
```

## Integration Examples

### curl

```bash
# Simple download
curl -O https://ca.sami/api/ca/cert/myservice.sami?format=pfx

# With custom password
curl -O "https://ca.sami/api/ca/cert/myservice.sami?format=pfx&password=mypassword"
```

### PowerShell

```powershell
# Download and install
$certPath = "C:\certs\myservice.pfx"
Invoke-WebRequest -Uri "https://ca.sami/api/ca/cert/myservice.sami?format=pfx" -OutFile $certPath

# Verify certificate
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath, "dashcaddy")
Write-Host "Certificate valid until: $($cert.NotAfter)"
```

### Bash/Linux

```bash
#!/bin/bash
# Download and extract PEM files
curl -k "https://ca.sami/api/ca/cert/myservice.sami?format=pem" -o myservice.pem

# Extract key and cert
openssl pkey -in myservice.pem -out myservice.key
openssl x509 -in myservice.pem -out myservice.crt
```

### Docker Compose

```yaml
services:
  myservice:
    image: myimage
    volumes:
      - ./certs:/certs
    environment:
      SSL_CERT_FILE: /certs/myservice.crt
      SSL_KEY_FILE: /certs/myservice.key
    command: |
      sh -c "
        curl -k https://ca.sami/api/ca/cert/myservice.sami?format=crt -o /certs/myservice.crt &&
        curl -k https://ca.sami/api/ca/cert/myservice.sami?format=key -o /certs/myservice.key &&
        exec myservice
      "
```

## DNS Server Configuration

### DNS1 (Primary)
- **IP**: 192.168.254.204
- **Domain**: dns1.sami
- **Certificate**: https://ca.sami/api/ca/cert/dns1.sami?format=pfx

### DNS2 (Secondary)
- **IP**: 100.74.102.61 (Tailscale)
- **Domain**: dns2.sami
- **Certificate**: https://ca.sami/api/ca/cert/dns2.sami?format=pfx

### DNS3 (Tertiary)
- **IP**: 100.89.216.23 (Tailscale)
- **Domain**: dns3.sami
- **Certificate**: https://ca.sami/api/ca/cert/dns3.sami?format=pfx

## Future Enhancements

Potential features for future versions:

- Certificate revocation lists (CRL)
- OCSP responder
- Certificate renewal webhooks
- Email notifications for expiring certificates
- Web UI for certificate management
- Custom certificate validity periods
- Certificate templates for different service types
- Automatic DNS record validation

## Support

For issues or questions, check:
- DashCA homepage: https://ca.sami
- Certificate list: https://ca.sami/api/ca/certs
- Server logs: `docker logs dashcaddy-api`
