diff --git a/dev-ops/compose/docker-compose.yml b/dev-ops/compose/docker-compose.yml index 2d3277420..16d664abb 100644 --- a/dev-ops/compose/docker-compose.yml +++ b/dev-ops/compose/docker-compose.yml @@ -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 @@ -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: diff --git a/dev-ops/compose/signer-e2e.sh b/dev-ops/compose/signer-e2e.sh index 5e3993828..3b28718aa 100755 --- a/dev-ops/compose/signer-e2e.sh +++ b/dev-ops/compose/signer-e2e.sh @@ -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 diff --git a/dev-ops/compose/signer/config.yaml b/dev-ops/compose/signer/config.yaml index e16acc05c..f5aafe077 100644 --- a/dev-ops/compose/signer/config.yaml +++ b/dev-ops/compose/signer/config.yaml @@ -53,6 +53,8 @@ signer: validation: principal_validator: none cache_ttl_seconds: 300 + krl: + path: /var/lib/custos-signer/revoked_keys logging: level: info diff --git a/dev-ops/compose/sshd-login/50-cert-auth.conf b/dev-ops/compose/sshd-login/50-cert-auth.conf index 13d8ee610..47180c9c0 100644 --- a/dev-ops/compose/sshd-login/50-cert-auth.conf +++ b/dev-ops/compose/sshd-login/50-cert-auth.conf @@ -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 diff --git a/dev-ops/compose/sshd-login/entrypoint.sh b/dev-ops/compose/sshd-login/entrypoint.sh index d3690b8ac..3c475d90e 100755 --- a/dev-ops/compose/sshd-login/entrypoint.sh +++ b/dev-ops/compose/sshd-login/entrypoint.sh @@ -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 diff --git a/extensions/SSH-Certificate-Signer/Dockerfile b/extensions/SSH-Certificate-Signer/Dockerfile index c0e8119f8..ce6cd3644 100644 --- a/extensions/SSH-Certificate-Signer/Dockerfile +++ b/extensions/SSH-Certificate-Signer/Dockerfile @@ -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"] diff --git a/extensions/SSH-Certificate-Signer/README.md b/extensions/SSH-Certificate-Signer/README.md index da28b2f77..cf774cb28 100644 --- a/extensions/SSH-Certificate-Signer/README.md +++ b/extensions/SSH-Certificate-Signer/README.md @@ -155,6 +155,18 @@ For `principal_validator: ldap`, store the LDAP settings at `ssh-ca/validation`, | `search_filter` | Search filter. `%s` becomes the user's subject. | | `username_attribute` | Optional. Default `uid`. | +### Login nodes + +Each login node's sshd needs two lines, usually in a drop-in under `/etc/ssh/sshd_config.d/`: + +``` +TrustedUserCAKeys /storage/keystore/custos/ssh/ca.pub +RevokedKeys /storage/keystore/custos/ssh/revoked_keys +``` + +`ca.pub` is the CA public key from `GET /api/v1/ca-public-key`. `revoked_keys` is the file the signer writes at +`signer.krl.path`. The signer writes it, the login nodes read it, so both point at one file on shared storage. + ### Configuration ```bash @@ -248,6 +260,7 @@ 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 `. @@ -255,8 +268,20 @@ Every route with a token takes `Authorization: Bearer `. `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. + +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 @@ -295,18 +320,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 diff --git a/extensions/SSH-Certificate-Signer/config.example.yaml b/extensions/SSH-Certificate-Signer/config.example.yaml index bcb9b8d9d..5c13ca134 100644 --- a/extensions/SSH-Certificate-Signer/config.example.yaml +++ b/extensions/SSH-Certificate-Signer/config.example.yaml @@ -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 diff --git a/extensions/SSH-Certificate-Signer/internal/audit/logger.go b/extensions/SSH-Certificate-Signer/internal/audit/logger.go index 763b6d7a7..e6fec3d8e 100644 --- a/extensions/SSH-Certificate-Signer/internal/audit/logger.go +++ b/extensions/SSH-Certificate-Signer/internal/audit/logger.go @@ -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, + ) +} diff --git a/extensions/SSH-Certificate-Signer/internal/config/config.go b/extensions/SSH-Certificate-Signer/internal/config/config.go index 148aa67ed..89851389b 100644 --- a/extensions/SSH-Certificate-Signer/internal/config/config.go +++ b/extensions/SSH-Certificate-Signer/internal/config/config.go @@ -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 { @@ -135,6 +142,7 @@ func DefaultConfig() *Config { PrincipalValidator: "none", CacheTTLSeconds: 300, // 5 minutes cache }, + KRL: KRLConfig{RefreshSeconds: 300}, }, Logging: LoggingConfig{ Level: "info", @@ -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 } diff --git a/extensions/SSH-Certificate-Signer/internal/config/config_test.go b/extensions/SSH-Certificate-Signer/internal/config/config_test.go index c2356bc21..7b163a21c 100644 --- a/extensions/SSH-Certificate-Signer/internal/config/config_test.go +++ b/extensions/SSH-Certificate-Signer/internal/config/config_test.go @@ -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") } diff --git a/extensions/SSH-Certificate-Signer/internal/handler/certificates.go b/extensions/SSH-Certificate-Signer/internal/handler/certificates.go index 6dd4ca599..9525daeb5 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/certificates.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/certificates.go @@ -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) { @@ -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, diff --git a/extensions/SSH-Certificate-Signer/internal/handler/health.go b/extensions/SSH-Certificate-Signer/internal/handler/health.go index 5adb7e190..f835445a6 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/health.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/health.go @@ -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 { @@ -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, } } @@ -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") diff --git a/extensions/SSH-Certificate-Signer/internal/handler/krl.go b/extensions/SSH-Certificate-Signer/internal/handler/krl.go new file mode 100644 index 000000000..b2cea2264 --- /dev/null +++ b/extensions/SSH-Certificate-Signer/internal/handler/krl.go @@ -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) +} diff --git a/extensions/SSH-Certificate-Signer/internal/handler/krl_test.go b/extensions/SSH-Certificate-Signer/internal/handler/krl_test.go new file mode 100644 index 000000000..00e3f01ee --- /dev/null +++ b/extensions/SSH-Certificate-Signer/internal/handler/krl_test.go @@ -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()) + } +} diff --git a/extensions/SSH-Certificate-Signer/internal/krl/krl.go b/extensions/SSH-Certificate-Signer/internal/krl/krl.go new file mode 100644 index 000000000..0b3f3c7b0 --- /dev/null +++ b/extensions/SSH-Certificate-Signer/internal/krl/krl.go @@ -0,0 +1,57 @@ +// 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 krl builds OpenSSH key revocation lists (PROTOCOL.krl). +package krl + +import ( + "encoding/binary" + "time" +) + +// Build returns a KRL that revokes the given certificate serials, whichever CA signed them. +// Serials never repeat across CA rotations, so one list covers every CA. +func Build(version uint64, generated time.Time, serials []int64) []byte { + b := []byte("SSHKRL\n\x00") + b = binary.BigEndian.AppendUint32(b, 1) + b = binary.BigEndian.AppendUint64(b, version) + b = binary.BigEndian.AppendUint64(b, uint64(generated.Unix())) + b = binary.BigEndian.AppendUint64(b, 0) // flags + b = appendString(b, nil) // reserved + b = appendString(b, nil) // comment + if len(serials) == 0 { + return b + } + + var list []byte + for _, serial := range serials { + list = binary.BigEndian.AppendUint64(list, uint64(serial)) + } + var section []byte + section = appendString(section, nil) // CA key, empty means any CA + section = appendString(section, nil) // reserved + section = append(section, 0x20) // serial list + section = appendString(section, list) + + b = append(b, 1) // certificates section + return appendString(b, section) +} + +func appendString(b, s []byte) []byte { + b = binary.BigEndian.AppendUint32(b, uint32(len(s))) + return append(b, s...) +} diff --git a/extensions/SSH-Certificate-Signer/internal/krl/krl_test.go b/extensions/SSH-Certificate-Signer/internal/krl/krl_test.go new file mode 100644 index 000000000..ca9f23cbd --- /dev/null +++ b/extensions/SSH-Certificate-Signer/internal/krl/krl_test.go @@ -0,0 +1,75 @@ +// 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 krl + +import ( + "crypto/ed25519" + "crypto/rand" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "golang.org/x/crypto/ssh" +) + +// Make sure OpenSSH reads the correct serials it was given. +func TestBuild_RevokesExactlyTheListedSerials(t *testing.T) { + keygen, err := exec.LookPath("ssh-keygen") + if err != nil { + t.Skip("ssh-keygen not installed") + } + dir := t.TempDir() + _, caKey, _ := ed25519.GenerateKey(rand.Reader) + ca, _ := ssh.NewSignerFromKey(caKey) + certFile := func(serial uint64) string { + pub, _, _ := ed25519.GenerateKey(rand.Reader) + key, _ := ssh.NewPublicKey(pub) + cert := &ssh.Certificate{Key: key, Serial: serial, CertType: ssh.UserCert, ValidPrincipals: []string{"jdoe"}, ValidBefore: ssh.CertTimeInfinity} + if err := cert.SignCert(rand.Reader, ca); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, fmt.Sprintf("cert-%d.pub", serial)) + if err := os.WriteFile(path, ssh.MarshalAuthorizedKey(cert), 0o600); err != nil { + t.Fatal(err) + } + return path + } + verdict := func(serials []int64, certPath string) string { + krlPath := filepath.Join(dir, "revoked.krl") + if err := os.WriteFile(krlPath, Build(1, time.Now(), serials), 0o600); err != nil { + t.Fatal(err) + } + out, _ := exec.Command(keygen, "-Q", "-f", krlPath, certPath).CombinedOutput() + return string(out) + } + + revoked, other := certFile(77), certFile(78) + if out := verdict([]int64{77}, revoked); !strings.Contains(out, "REVOKED") { + t.Fatalf("serial 77 should be revoked: %s", out) + } + if out := verdict([]int64{77}, other); !strings.Contains(out, "ok") { + t.Fatalf("serial 78 should pass: %s", out) + } + if out := verdict(nil, revoked); !strings.Contains(out, "ok") { + t.Fatalf("an empty list should revoke nothing: %s", out) + } +} diff --git a/extensions/SSH-Certificate-Signer/internal/krl/publisher.go b/extensions/SSH-Certificate-Signer/internal/krl/publisher.go new file mode 100644 index 000000000..3774807a0 --- /dev/null +++ b/extensions/SSH-Certificate-Signer/internal/krl/publisher.go @@ -0,0 +1,122 @@ +// 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 krl + +import ( + "context" + "fmt" + "log/slog" + "os" + "slices" + "sync" + "time" + + "github.com/apache/airavata-custos/signer/internal/audit" + "github.com/apache/airavata-custos/signer/internal/store" +) + +type Snapshot struct { + Bytes []byte + Version uint64 + At time.Time + Serials int +} + +// Publisher writes the current KRL to the login nodes' RevokedKeys file and keeps a copy to serve. +type Publisher struct { + db *store.DB + path string + audit *audit.Logger + logger *slog.Logger + // Holds at most one pending rebuild. Revokes that land during a build fold into the next one. + rebuild chan struct{} + + mu sync.Mutex + serials []int64 + current Snapshot +} + +func NewPublisher(db *store.DB, path string, audit *audit.Logger, logger *slog.Logger) *Publisher { + return &Publisher{db: db, path: path, audit: audit, logger: logger, rebuild: make(chan struct{}, 1)} +} + +// Trigger asks for a rebuild without waiting for it. +func (p *Publisher) Trigger() { + select { + case p.rebuild <- struct{}{}: + default: + } +} + +// Run rebuilds on every trigger and every refresh, so expired serials drop out and a failed write is retried. +func (p *Publisher) Run(ctx context.Context, refresh time.Duration) { + ticker := time.NewTicker(refresh) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-p.rebuild: + case <-ticker.C: + } + if err := p.Publish(ctx); err != nil { + p.logger.Error("failed to publish KRL", "error", err) + } + } +} + +// Publish rebuilds the KRL from every revoked certificate that has not expired. +// Nothing is written when the set is unchanged and the file is still there. +func (p *Publisher) Publish(ctx context.Context) error { + now := time.Now().UTC() + // Keep serials an hour past expiry, for safety. + serials, err := p.db.ListRevokedSerialsValidAfter(ctx, now.Add(-time.Hour)) + if err != nil { + return err + } + + p.mu.Lock() + defer p.mu.Unlock() + if p.current.Bytes != nil && slices.Equal(serials, p.serials) { + // A file that went missing is written again. + if _, err := os.Stat(p.path); err == nil { + return nil + } + } + // Two builds in the same second must not share a version, or a node takes a 304 for new content. + version := max(uint64(now.Unix()), p.current.Version+1) + b := Build(version, now, serials) + // The file is swapped in one step and never truncated. A missing or partial file locks every login out. + tmp := p.path + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return fmt.Errorf("writing KRL: %w", err) + } + if err := os.Rename(tmp, p.path); err != nil { + return fmt.Errorf("writing KRL: %w", err) + } + p.serials = serials + p.current = Snapshot{Bytes: b, Version: version, At: now, Serials: len(serials)} + p.audit.LogKRLPublished(ctx, version, len(serials), p.path) + return nil +} + +func (p *Publisher) Snapshot() Snapshot { + p.mu.Lock() + defer p.mu.Unlock() + return p.current +} diff --git a/extensions/SSH-Certificate-Signer/internal/server/routes.go b/extensions/SSH-Certificate-Signer/internal/server/routes.go index bf41a7f47..87eb97a67 100644 --- a/extensions/SSH-Certificate-Signer/internal/server/routes.go +++ b/extensions/SSH-Certificate-Signer/internal/server/routes.go @@ -30,6 +30,7 @@ type Handlers struct { Certificates http.HandlerFunc CertificateDetail http.HandlerFunc CertificateRevoke http.HandlerFunc + KRL http.HandlerFunc } func NewRouter(cfg *config.Config, handlers Handlers) *chi.Mux { @@ -38,8 +39,9 @@ func NewRouter(cfg *config.Config, handlers Handlers) *chi.Mux { r.Use(SecurityHeadersMiddleware) r.Use(BodyLimitMiddleware(1 << 20)) // 1 MB - // Health endpoint (no auth) + // No token needed for health and the revocation list endpoints r.Get("/api/v1/health", handlers.Health) + r.Get("/api/v1/krl", handlers.KRL) r.Group(func(r chi.Router) { r.Use(ServiceTokenMiddleware(cfg.Signer.ServiceToken)) diff --git a/extensions/SSH-Certificate-Signer/internal/server/routes_test.go b/extensions/SSH-Certificate-Signer/internal/server/routes_test.go index 65ea85607..0c62b024a 100644 --- a/extensions/SSH-Certificate-Signer/internal/server/routes_test.go +++ b/extensions/SSH-Certificate-Signer/internal/server/routes_test.go @@ -34,14 +34,14 @@ func testRouter() *chi.Mux { ok := func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) } cfg := &config.Config{} cfg.Signer.ServiceToken = testServiceToken - return NewRouter(cfg, Handlers{Sign: ok, CAPublicKey: ok, Health: ok, Certificates: ok, CertificateDetail: ok, CertificateRevoke: ok}) + return NewRouter(cfg, Handlers{Sign: ok, CAPublicKey: ok, Health: ok, Certificates: ok, CertificateDetail: ok, CertificateRevoke: ok, KRL: ok}) } -// Make sure every route except health needs the service token since nothing else protects the signer. +// Make sure every route except health and the revocation list needs the service token since nothing else protects the signer. func TestEveryRouteNeedsTheServiceToken(t *testing.T) { router := testRouter() err := chi.Walk(router, func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { - if route == "/api/v1/health" { + if route == "/api/v1/health" || route == "/api/v1/krl" { return nil } for _, header := range []string{"", "Bearer wrong-token"} { diff --git a/extensions/SSH-Certificate-Signer/internal/service/revocation.go b/extensions/SSH-Certificate-Signer/internal/service/revocation.go index ae3e04c0e..641dce593 100644 --- a/extensions/SSH-Certificate-Signer/internal/service/revocation.go +++ b/extensions/SSH-Certificate-Signer/internal/service/revocation.go @@ -90,7 +90,7 @@ func (s *RevocationService) Revoke(ctx context.Context, command RevokeCommand) ( event := &store.RevocationEvent{ SerialNumber: command.SerialNumber, KeyID: certificate.KeyID, CAFingerprint: certificate.CAFingerprint, - Reason: command.Reason, RevokedBy: command.RevokedBy, + Reason: command.Reason, RevokedBy: command.RevokedBy, ValidBefore: certificate.ValidBefore, } if err := store.InsertRevocationEventAt(ctx, tx, event, now); err != nil { return nil, err diff --git a/extensions/SSH-Certificate-Signer/internal/service/revocation_test.go b/extensions/SSH-Certificate-Signer/internal/service/revocation_test.go index b43140e6b..10df2d769 100644 --- a/extensions/SSH-Certificate-Signer/internal/service/revocation_test.go +++ b/extensions/SSH-Certificate-Signer/internal/service/revocation_test.go @@ -32,7 +32,7 @@ import ( const ( lookupCertificateQuery = "SELECT key_id, ca_fingerprint.*WHERE serial_number = \\$1" existingRevocationQuery = "SELECT revoked_at, reason.*WHERE serial_number = \\$1" - insertRevocationQuery = "INSERT INTO revocation_events.*VALUES \\(\\$1, \\$2, \\$3, \\$4, \\$5, \\$6\\)" + insertRevocationQuery = "INSERT INTO revocation_events.*VALUES \\(\\$1, \\$2, \\$3, \\$4, \\$5, \\$6, \\$7\\)" ) func newRevocationService(t *testing.T, now time.Time) (*RevocationService, sqlmock.Sqlmock) { @@ -66,7 +66,7 @@ func TestRevocationService_RevokeActive(t *testing.T) { mock.ExpectQuery(existingRevocationQuery).WithArgs(int64(42)).WillReturnError(sql.ErrNoRows) mock.ExpectExec(insertRevocationQuery).WithArgs( int64(42), "key-1", "SHA256:ca", now, - "compromised", "subject-1", + "compromised", "subject-1", now.Add(time.Hour), ).WillReturnResult(sqlmock.NewResult(1, 1)) mock.ExpectCommit() diff --git a/extensions/SSH-Certificate-Signer/internal/store/revocation.go b/extensions/SSH-Certificate-Signer/internal/store/revocation.go index c0b5dd23d..d53f49e12 100644 --- a/extensions/SSH-Certificate-Signer/internal/store/revocation.go +++ b/extensions/SSH-Certificate-Signer/internal/store/revocation.go @@ -32,6 +32,7 @@ type RevocationEvent struct { CAFingerprint string Reason string RevokedBy string + ValidBefore time.Time } type CertificateForRevocation struct { @@ -92,12 +93,30 @@ func GetLatestRevocation(ctx context.Context, db RevocationDBTX, serialNumber in func InsertRevocationEventAt(ctx context.Context, db RevocationDBTX, ev *RevocationEvent, revokedAt time.Time) error { _, err := db.ExecContext(ctx, `INSERT INTO revocation_events - (serial_number, key_id, ca_fingerprint, revoked_at, reason, revoked_by) - VALUES ($1, $2, $3, $4, $5, $6)`, - ev.SerialNumber, ev.KeyID, ev.CAFingerprint, revokedAt, ev.Reason, ev.RevokedBy, + (serial_number, key_id, ca_fingerprint, revoked_at, reason, revoked_by, valid_before) + VALUES ($1, $2, $3, $4, $5, $6, $7)`, + ev.SerialNumber, ev.KeyID, ev.CAFingerprint, revokedAt, ev.Reason, ev.RevokedBy, ev.ValidBefore, ) if err != nil { return fmt.Errorf("inserting revocation event: %w", err) } return nil } + +// ListRevokedSerialsValidAfter lists the revoked certificates that are still valid after t. +func (d *DB) ListRevokedSerialsValidAfter(ctx context.Context, t time.Time) ([]int64, error) { + rows, err := d.QueryContext(ctx, `SELECT serial_number FROM revocation_events WHERE valid_before > $1 ORDER BY serial_number`, t) + if err != nil { + return nil, fmt.Errorf("listing revoked serials: %w", err) + } + defer rows.Close() + var serials []int64 + for rows.Next() { + var serial int64 + if err := rows.Scan(&serial); err != nil { + return nil, fmt.Errorf("listing revoked serials: %w", err) + } + serials = append(serials, serial) + } + return serials, rows.Err() +} diff --git a/extensions/SSH-Certificate-Signer/main.go b/extensions/SSH-Certificate-Signer/main.go index e26ee72fb..8319a8e9e 100644 --- a/extensions/SSH-Certificate-Signer/main.go +++ b/extensions/SSH-Certificate-Signer/main.go @@ -28,6 +28,7 @@ import ( "github.com/apache/airavata-custos/signer/internal/cert" "github.com/apache/airavata-custos/signer/internal/config" "github.com/apache/airavata-custos/signer/internal/handler" + "github.com/apache/airavata-custos/signer/internal/krl" "github.com/apache/airavata-custos/signer/internal/policy" "github.com/apache/airavata-custos/signer/internal/server" signerservice "github.com/apache/airavata-custos/signer/internal/service" @@ -179,9 +180,16 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { CertificateLimit: cfg.Signer.Policy.CertificateLimit.MaxPerUser, CertificateLimitWindow: time.Duration(cfg.Signer.Policy.CertificateLimit.WindowSeconds) * time.Second, }, logger) + krlPublisher := krl.NewPublisher(db, cfg.Signer.KRL.Path, auditLogger, logger) + if err := krlPublisher.Publish(context.Background()); err != nil { + logger.Error("failed to publish KRL", "error", err) + os.Exit(1) + } + go krlPublisher.Run(context.Background(), time.Duration(cfg.Signer.KRL.RefreshSeconds)*time.Second) + caPublicKeyHandler := handler.NewCAPublicKeyHandler(vaultClient, logger) - healthHandler := handler.NewHealthHandler(db, vaultClient) - certificatesHandler := handler.NewCertificatesHandler(db, signerservice.NewRevocationService(db), cfg.Signer.LoginHost, cfg.Signer.LoginPort, logger) + healthHandler := handler.NewHealthHandler(db, vaultClient, krlPublisher) + certificatesHandler := handler.NewCertificatesHandler(db, signerservice.NewRevocationService(db), krlPublisher, cfg.Signer.LoginHost, cfg.Signer.LoginPort, logger) handlers := server.Handlers{ Sign: signHandler.Handle, @@ -190,6 +198,7 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { Certificates: certificatesHandler.HandleList, CertificateDetail: certificatesHandler.HandleGet, CertificateRevoke: certificatesHandler.HandleRevoke, + KRL: handler.NewKRLHandler(krlPublisher).Handle, } router := server.NewRouter(cfg, handlers) diff --git a/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql b/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql index 575fd1a3e..b864222b6 100644 --- a/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql +++ b/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql @@ -57,6 +57,7 @@ CREATE TABLE IF NOT EXISTS revocation_events revoked_at TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), reason VARCHAR(255) NOT NULL, revoked_by VARCHAR(255) NOT NULL, + valid_before TIMESTAMPTZ(6) NOT NULL, PRIMARY KEY (id) ); @@ -64,3 +65,4 @@ CREATE INDEX IF NOT EXISTS idx_revocation_serial ON revocation_events (serial_nu CREATE INDEX IF NOT EXISTS idx_revocation_keyid ON revocation_events (key_id); CREATE INDEX IF NOT EXISTS idx_revocation_ca_fingerprint ON revocation_events (ca_fingerprint); CREATE INDEX IF NOT EXISTS idx_revocation_revoked_at ON revocation_events (revoked_at); +CREATE INDEX IF NOT EXISTS idx_revocation_valid_before ON revocation_events (valid_before);