Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions dev-ops/compose/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ services:
SIGNER_SERVICE_TOKEN: ${SIGNER_SERVICE_TOKEN:-dev-service-token-not-for-production}
volumes:
- ./signer/config.yaml:/app/config.yaml:ro
- krl:/var/lib/custos-signer
depends_on:
db:
condition: service_healthy
Expand All @@ -174,9 +175,13 @@ services:
environment:
SIGNER_URL: http://signer:8084
SIGNER_SERVICE_TOKEN: ${SIGNER_SERVICE_TOKEN:-dev-service-token-not-for-production}
volumes:
# The signer writes the revocation list here, the login node only reads it.
- krl:/etc/ssh/krl:ro
depends_on:
signer:
condition: service_healthy

volumes:
openbao-data:
krl:
19 changes: 14 additions & 5 deletions dev-ops/compose/signer-e2e.sh
Original file line number Diff line number Diff line change
Expand Up @@ -175,19 +175,28 @@ else
check "expired certificate rejected" 0
fi

# --- revoked serial: sign, revoke via KRL on the login node, must fail, then reset
# --- revoked serial: revoke through the API, the signer publishes the list the login node reads, login must fail
code=$(sign "$PRINCIPAL" 300)
[ "$code" = "200" ]
check "sign certificate to revoke (HTTP $code)" $?
write_cert
SERIAL=$(json_get serial_number < "$WORK_DIR/resp.json")

docker compose exec -T sshd-login sh -c 'cat > /tmp/revoke-cert.pub && ssh-keygen -kuf /etc/ssh/revoked_keys.krl /tmp/revoke-cert.pub' < "$WORK_DIR/key-cert.pub"
code=$(curl -s -o "$WORK_DIR/resp.json" -w "%{http_code}" -X POST "$SIGNER_URL/api/v1/certificates/$SERIAL/revoke" \
-H "Authorization: Bearer $SERVICE_TOKEN" -H "Content-Type: application/json" \
-d '{"reason":"e2e","revoked_by":"user/e2e"}')
[ "$code" = "200" ]
check "revoke through the API (HTTP $code)" $?

for _ in $(seq 1 10); do
ssh "${SSH_OPTS[@]}" "$PRINCIPAL@127.0.0.1" true 2>/dev/null || break
sleep 2
done
if ssh "${SSH_OPTS[@]}" "$PRINCIPAL@127.0.0.1" true 2>/dev/null; then
check "revoked certificate rejected" 1
check "revoked certificate rejected once the list is published" 1
else
check "revoked certificate rejected" 0
check "revoked certificate rejected once the list is published" 0
fi
docker compose exec -T sshd-login ssh-keygen -kf /etc/ssh/revoked_keys.krl

# --- per-user limit: keep signing for this user until the signer refuses
code=200
Expand Down
2 changes: 2 additions & 0 deletions dev-ops/compose/signer/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ signer:
validation:
principal_validator: none
cache_ttl_seconds: 300
krl:
path: /var/lib/custos-signer/revoked_keys

logging:
level: info
Expand Down
2 changes: 1 addition & 1 deletion dev-ops/compose/sshd-login/50-cert-auth.conf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
TrustedUserCAKeys /etc/ssh/trusted-user-ca-keys.pub
AuthorizedPrincipalsFile /etc/ssh/auth_principals/%u
RevokedKeys /etc/ssh/revoked_keys.krl
RevokedKeys /etc/ssh/krl/revoked_keys
PasswordAuthentication no
1 change: 0 additions & 1 deletion dev-ops/compose/sshd-login/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ until curl -sf \
done
echo "CA key installed: $(cut -c1-40 /etc/ssh/trusted-user-ca-keys.pub)..."

[ -s /etc/ssh/revoked_keys.krl ] || ssh-keygen -kf /etc/ssh/revoked_keys.krl
ssh-keygen -A

exec /usr/sbin/sshd -D -e
2 changes: 2 additions & 0 deletions extensions/SSH-Certificate-Signer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ WORKDIR /app
COPY --from=build /custos-signer /usr/local/bin/custos-signer
# migrate runs with a path relative to the workdir
COPY --from=build /src/migrations /app/migrations
# Where the revocation list is written. A volume mounted here keeps this owner.
RUN mkdir -p /var/lib/custos-signer && chown 65534:65534 /var/lib/custos-signer
EXPOSE 8084
USER 65534:65534
ENTRYPOINT ["custos-signer"]
Expand Down
43 changes: 29 additions & 14 deletions extensions/SSH-Certificate-Signer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,15 +248,28 @@ The service handles SIGTERM and SIGINT for graceful shutdown:
| `GET` | `/api/v1/certificates/{serial}` | One certificate, with the `login_host` and `login_port` to use it on |
| `POST` | `/api/v1/certificates/{serial}/revoke` | Revoke an active certificate. `revoked_by` is required and `reason` can be empty |
| `GET` | `/api/v1/health` | Health check, no token |
| `GET` | `/api/v1/krl` | The revocation list for `RevokedKeys`, no token. `ETag` is its version |

Every route with a token takes `Authorization: Bearer <service token>`.

`q` matches the serial, principal, email or key ID. `status` is `active`, `not-yet-valid`, `expired` or `revoked`.
`GET /api/v1/certificates` uses keyset pagination. Pass `limit`, and `cursor` set to the last `next_cursor`.
It returns no total or offset.

> **Revocation.** The signer records revocations. It does not generate or distribute OpenSSH KRLs, so login nodes still
> accept a revoked certificate.
### Revocation

A revoke writes a row, then the signer rebuilds the OpenSSH revocation list (KRL) from every revoked certificate that
has not expired and writes it to `signer.krl.path`, the file the login nodes' `RevokedKeys` points at, on storage they
share with the signer. It writes a temp file next to it and renames, so the file is never missing or half written. The
same bytes are served at `/api/v1/krl` for a node without that storage. The list is rebuilt every `refresh_seconds`
too, so expired serials drop out, a failed write is retried and a file that went missing is written again. Login nodes
see a new list once their NFS attribute cache refreshes, about a minute.
Comment thread
lahirujayathilake marked this conversation as resolved.
Resolved

sshd checks the list only at login. A session that is already open stays open after its certificate is revoked.

The list names serials only, under any CA, since serials never repeat across CA rotations. Never delete the file or
leave it empty: a missing file makes sshd refuse every key and certificate login, and a zero-byte file revokes nothing.
To reset one by hand, write an empty real list with `ssh-keygen -k -f revoked_keys`.

### Examples

Expand Down Expand Up @@ -295,18 +308,20 @@ curl -s -X POST http://localhost:8084/api/v1/certificates/42/revoke \

## Troubleshooting

| Error | Cause | Fix |
|---------------------------------------|---------------------------------------------|---------------------------------------------------------------------|
| "failed to connect to database" | PostgreSQL unreachable or wrong credentials | Check host/port, verify DB user permissions, ensure database exists |
| "failed to create vault client" | Vault unreachable or bad token | Check `VAULT_ADDRESS`, ensure token is valid, verify KV v2 enabled |
| Migrations not found | The working directory is not this one | Run the signer from `extensions/SSH-Certificate-Signer` |
| HTTP 401 on any route | Wrong service token | Set the same `SIGNER_SERVICE_TOKEN` on the signer and the caller |
| HTTP 403 `reserved_username` | The username is in `reserved_usernames` | Certificates are not issued for these names |
| HTTP 429 `too_many_certificates` | The user reached the per-user limit | Wait for the window to pass, or raise `certificate_limit` |
| HTTP 503 "CA key storage unavailable" | Vault down during signing | Check Vault status and network connectivity |
| Exits with "no CA key in vault" | No CA at `vault.ca_key_path` | Fix the path. A new CA is not trusted by the login nodes |
| Exits with "check-and-set parameter" | The CA's latest version in Vault is deleted | Undelete that version. The signer never replaces an existing CA |
| HTTP 500 on every sign | `certificate_serial_seq` is missing | `CREATE SEQUENCE certificate_serial_seq`, then the `setval` above |
| Error | Cause | Fix |
|---------------------------------------|---------------------------------------------|----------------------------------------------------------------------------------------|
| "failed to connect to database" | PostgreSQL unreachable or wrong credentials | Check host/port, verify DB user permissions, ensure database exists |
| "failed to create vault client" | Vault unreachable or bad token | Check `VAULT_ADDRESS`, ensure token is valid, verify KV v2 enabled |
| Migrations not found | The working directory is not this one | Run the signer from `extensions/SSH-Certificate-Signer` |
| HTTP 401 on any route | Wrong service token | Set the same `SIGNER_SERVICE_TOKEN` on the signer and the caller |
| HTTP 403 `reserved_username` | The username is in `reserved_usernames` | Certificates are not issued for these names |
| HTTP 429 `too_many_certificates` | The user reached the per-user limit | Wait for the window to pass, or raise `certificate_limit` |
| HTTP 503 "CA key storage unavailable" | Vault down during signing | Check Vault status and network connectivity |
| Exits with "no CA key in vault" | No CA at `vault.ca_key_path` | Fix the path. A new CA is not trusted by the login nodes |
| Exits with "check-and-set parameter" | The CA's latest version in Vault is deleted | Undelete that version. The signer never replaces an existing CA |
| HTTP 500 on every sign | `certificate_serial_seq` is missing | `CREATE SEQUENCE certificate_serial_seq`, then the `setval` above |
| Exits with "failed to publish KRL" | `signer.krl.path` is not writable | Check the service user owns the folder and the share is mounted rw |
| Revoked certificate still logs in | The list did not reach the node | `ssh-keygen -Q -l -f revoked_keys` on the node, compare `/api/v1/health` `krl.version` |

## License

Expand Down
3 changes: 3 additions & 0 deletions extensions/SSH-Certificate-Signer/config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ signer:
validation:
principal_validator: none # "none", or "ldap" for the site's own check
cache_ttl_seconds: 300 # Vault credential cache TTL for validators
krl:
path: /var/lib/custos-signer/revoked_keys # the login nodes' RevokedKeys file, required
refresh_seconds: 300 # rebuild to drop expired serials and retry a failed write

logging:
level: info # debug, info, warn, error
Expand Down
10 changes: 10 additions & 0 deletions extensions/SSH-Certificate-Signer/internal/audit/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,13 @@ func (l *Logger) LogCACreated(ctx context.Context, caFingerprint string) {
"ca_fingerprint", caFingerprint,
)
}

func (l *Logger) LogKRLPublished(ctx context.Context, version uint64, serials int, path string) {
l.slogger.InfoContext(ctx, "KRL published",
"event_type", "krl_published",
"timestamp", time.Now().UTC().Format(time.RFC3339),
"krl_version", version,
"serials", serials,
"path", path,
)
}
14 changes: 14 additions & 0 deletions extensions/SSH-Certificate-Signer/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ type SignerConfig struct {
CA CAConfig `yaml:"ca"`
Policy PolicyConfig `yaml:"policy"`
Validation ValidationConfig `yaml:"validation"`
KRL KRLConfig `yaml:"krl"`
}

// KRLConfig says where the revocation list is written and how often it is rebuilt.
type KRLConfig struct {
Path string `yaml:"path"`
RefreshSeconds int `yaml:"refresh_seconds"`
}

type CAConfig struct {
Expand Down Expand Up @@ -135,6 +142,7 @@ func DefaultConfig() *Config {
PrincipalValidator: "none",
CacheTTLSeconds: 300, // 5 minutes cache
},
KRL: KRLConfig{RefreshSeconds: 300},
},
Logging: LoggingConfig{
Level: "info",
Expand Down Expand Up @@ -178,6 +186,12 @@ func (c *Config) Validate() error {
if limit := c.Signer.Policy.CertificateLimit; limit.MaxPerUser < 1 || limit.WindowSeconds < 1 {
return fmt.Errorf("certificate_limit max_per_user and window_seconds must be at least 1")
}
if c.Signer.KRL.Path == "" {
return fmt.Errorf("krl path is required")
}
if c.Signer.KRL.RefreshSeconds < 1 {
return fmt.Errorf("krl refresh_seconds must be at least 1")
}
return nil
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
func TestValidate_RefusesWeakServiceToken(t *testing.T) {
cfg := DefaultConfig()
cfg.Signer.LoginHost = "login.example.edu"
cfg.Signer.KRL.Path = "/var/lib/custos-signer/revoked_keys"
if err := cfg.Validate(); err == nil {
t.Error("started without a service token")
}
Expand Down
12 changes: 10 additions & 2 deletions extensions/SSH-Certificate-Signer/internal/handler/certificates.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,16 +87,21 @@ type CertificateRevoker interface {
Revoke(context.Context, signerservice.RevokeCommand) (*signerservice.RevokedCertificate, error)
}

type KRLPublisher interface {
Trigger()
}

type CertificatesHandler struct {
db CertificateStore
revoker CertificateRevoker
krl KRLPublisher
loginHost string
loginPort int
logger *slog.Logger
}

func NewCertificatesHandler(db CertificateStore, revoker CertificateRevoker, loginHost string, loginPort int, logger *slog.Logger) *CertificatesHandler {
return &CertificatesHandler{db: db, revoker: revoker, loginHost: loginHost, loginPort: loginPort, logger: logger}
func NewCertificatesHandler(db CertificateStore, revoker CertificateRevoker, krl KRLPublisher, loginHost string, loginPort int, logger *slog.Logger) *CertificatesHandler {
return &CertificatesHandler{db: db, revoker: revoker, krl: krl, loginHost: loginHost, loginPort: loginPort, logger: logger}
}

func (h *CertificatesHandler) HandleList(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -205,6 +210,9 @@ func (h *CertificatesHandler) HandleRevoke(w http.ResponseWriter, r *http.Reques
if result.AlreadyRevoked {
message = "Certificate was already revoked"
}
if !result.AlreadyRevoked {
h.krl.Trigger()
}
writeJSON(w, http.StatusOK, CertificateRevokeResponse{
Success: true, Message: message, SerialNumber: result.SerialNumber, Revoked: true,
RevokedAt: result.RevokedAt.Unix(), Reason: result.Reason, AlreadyRevoked: result.AlreadyRevoked,
Expand Down
13 changes: 12 additions & 1 deletion extensions/SSH-Certificate-Signer/internal/handler/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ import (
type HealthResponse struct {
Status string `json:"status"`
Checks map[string]*HealthCheckResult `json:"checks"`
KRL KRLStatus `json:"krl"`
}

type KRLStatus struct {
Version uint64 `json:"version"`
PublishedAt string `json:"published_at"`
Serials int `json:"serials"`
}

type HealthCheckResult struct {
Expand All @@ -39,12 +46,14 @@ type HealthCheckResult struct {
type HealthHandler struct {
db *store.DB
vaultClient *vaultpkg.Client
krl KRLSource
}

func NewHealthHandler(db *store.DB, vaultClient *vaultpkg.Client) *HealthHandler {
func NewHealthHandler(db *store.DB, vaultClient *vaultpkg.Client, krl KRLSource) *HealthHandler {
return &HealthHandler{
db: db,
vaultClient: vaultClient,
krl: krl,
}
}

Expand Down Expand Up @@ -72,9 +81,11 @@ func (h *HealthHandler) Handle(w http.ResponseWriter, r *http.Request) {
httpStatus = http.StatusServiceUnavailable
}

s := h.krl.Snapshot()
resp := HealthResponse{
Status: status,
Checks: checks,
KRL: KRLStatus{Version: s.Version, PublishedAt: s.At.Format(time.RFC3339), Serials: s.Serials},
}

w.Header().Set("Content-Type", "application/json")
Expand Down
50 changes: 50 additions & 0 deletions extensions/SSH-Certificate-Signer/internal/handler/krl.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package handler

import (
"fmt"
"net/http"

"github.com/apache/airavata-custos/signer/internal/krl"
)

type KRLSource interface {
Snapshot() krl.Snapshot
}

type KRLHandler struct {
source KRLSource
}

func NewKRLHandler(source KRLSource) *KRLHandler {
return &KRLHandler{source: source}
}

func (h *KRLHandler) Handle(w http.ResponseWriter, r *http.Request) {
s := h.source.Snapshot()
etag := fmt.Sprintf(`"%d"`, s.Version)
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "no-cache")
if r.Header.Get("If-None-Match") == etag {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Write(s.Bytes)
}
49 changes: 49 additions & 0 deletions extensions/SSH-Certificate-Signer/internal/handler/krl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package handler

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/apache/airavata-custos/signer/internal/krl"
)

type fixedKRL krl.Snapshot

func (f fixedKRL) Snapshot() krl.Snapshot { return krl.Snapshot(f) }

// Make sure a node gets the list with its version, and a 304 with no body once it has that version.
func TestKRL_ServesTheListOnceUntilTheVersionChanges(t *testing.T) {
h := NewKRLHandler(fixedKRL{Bytes: []byte("list"), Version: 7})

first := httptest.NewRecorder()
h.Handle(first, httptest.NewRequest(http.MethodGet, "/api/v1/krl", nil))
if first.Code != http.StatusOK || first.Body.String() != "list" || first.Header().Get("ETag") != `"7"` {
t.Fatalf("got %d %q etag %s", first.Code, first.Body, first.Header().Get("ETag"))
}

req := httptest.NewRequest(http.MethodGet, "/api/v1/krl", nil)
req.Header.Set("If-None-Match", `"7"`)
again := httptest.NewRecorder()
h.Handle(again, req)
if again.Code != http.StatusNotModified || again.Body.Len() != 0 {
t.Fatalf("got %d with %d bytes, want 304 and no body", again.Code, again.Body.Len())
}
}
Loading
Loading