This is an automated email from the ASF dual-hosted git repository. lahirujayathilake pushed a commit to branch signer-machine-api in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit d200e42ff0411330643b9aadc731bf76eba62fd6 Author: lahiruj <[email protected]> AuthorDate: Mon Nov 9 15:21:24 2026 -0500 Add an optional source address to signed certificates --- dev-ops/compose/signer-e2e.sh | 34 ++++++++++++++++++++-- extensions/SSH-Certificate-Signer/README.md | 15 ++++++---- .../internal/audit/logger.go | 3 ++ .../internal/handler/certificates.go | 2 ++ .../internal/handler/sign.go | 29 ++++++++++++++++-- .../internal/handler/sign_test.go | 10 +++++++ .../internal/store/certificate_query.go | 10 ++----- .../internal/store/certificate_query_test.go | 6 ++-- .../internal/store/issuance_log.go | 7 +++-- .../migrations/001_initial_schema.up.sql | 1 + .../core/signer/components/CertificateDetail.tsx | 1 + .../core/signer/components/MyCertificateDetail.tsx | 1 + web/src/features/core/signer/schemas.ts | 1 + 13 files changed, 97 insertions(+), 23 deletions(-) diff --git a/dev-ops/compose/signer-e2e.sh b/dev-ops/compose/signer-e2e.sh index 9d7e225bc..4c543c3d7 100755 --- a/dev-ops/compose/signer-e2e.sh +++ b/dev-ops/compose/signer-e2e.sh @@ -58,14 +58,14 @@ ssh-keygen -t ed25519 -N "" -q -f "$WORK_DIR/key" PUBKEY=$(cat "$WORK_DIR/key.pub") sign_body() { - echo "{\"principal\":\"$1\",\"ttl_seconds\":$2,\"public_key\":\"$PUBKEY\",\"user_email\":\"$USER_EMAIL\",\"user_sub\":\"$USER_SUB\",\"requested_by\":\"$REQUESTED_BY\"}" + echo "{\"principal\":\"$1\",\"ttl_seconds\":$2,\"public_key\":\"$PUBKEY\",\"user_email\":\"$USER_EMAIL\",\"user_sub\":\"$USER_SUB\",\"requested_by\":\"$REQUESTED_BY\"${3:+,\"source_address\":\"$3\"}}" } sign() { curl -s -o "$WORK_DIR/resp.json" -w "%{http_code}" "$SIGNER_URL/api/v1/sign" \ -H "Authorization: Bearer $SERVICE_TOKEN" \ -H "Content-Type: application/json" \ - -d "$(sign_body "$1" "$2")" + -d "$(sign_body "$1" "$2" "${3:-}")" } code=$(curl -s -o /dev/null -w "%{http_code}" "$SIGNER_URL/api/v1/sign" \ @@ -132,6 +132,36 @@ revoked=$(curl -s "$SIGNER_URL/api/v1/certificates/$SERIAL" -H "Authorization: B [ "$revoked" = "True self" ] check "certificate shows revoked by self (saw: $revoked)" $? +# --- source address: sshd accepts the certificate only from the listed addresses +code=$(sign "$PRINCIPAL" 300 "203.0.113.5,2001:db8::/32,0.0.0.0/0") +[ "$code" = "200" ] +check "sign certificate with a source address list (HTTP $code)" $? +write_cert +out=$(ssh "${SSH_OPTS[@]}" "[email protected]" whoami) +[ "$out" = "$PRINCIPAL" ] +check "SSH login from an address on the list" $? + +code=$(sign "$PRINCIPAL" 300 "192.0.2.0/24") +[ "$code" = "200" ] +check "sign certificate limited to another network (HTTP $code)" $? +write_cert +RESTRICTED_SERIAL=$(json_get serial_number < "$WORK_DIR/resp.json") +ssh-keygen -Lf "$WORK_DIR/key-cert.pub" | grep -q "source-address 192.0.2.0/24" +check "certificate carries the source address" $? +if ssh "${SSH_OPTS[@]}" "[email protected]" true 2>/dev/null; then + check "SSH login from an address not on the list rejected" 1 +else + check "SSH login from an address not on the list rejected" 0 +fi + +stored=$(curl -s "$SIGNER_URL/api/v1/certificates/$RESTRICTED_SERIAL" -H "Authorization: Bearer $SERVICE_TOKEN" | json_get source_address) +[ "$stored" = "192.0.2.0/24" ] +check "certificate record shows the source address (saw: $stored)" $? + +code=$(sign "$PRINCIPAL" 300 "10.0.0.5/24") +[ "$code" = "400" ] +check "CIDR with host bits set rejected (HTTP $code)" $? + # --- expired cert: TTL 1s, wait, connection must fail code=$(sign "$PRINCIPAL" 1) [ "$code" = "200" ] diff --git a/extensions/SSH-Certificate-Signer/README.md b/extensions/SSH-Certificate-Signer/README.md index e99314894..40dd747ae 100644 --- a/extensions/SSH-Certificate-Signer/README.md +++ b/extensions/SSH-Certificate-Signer/README.md @@ -48,12 +48,15 @@ not interpret `requested_by`. The certificate names who it is for. The CA signature covers all of it. -| Field | Value | -|--------------------------------------------|-------------------------------------------------------------| -| Key ID | `<email>:<requested_by>`. sshd writes it to the login log. | -| Extension `[email protected]` | The user's subject | -| Extension `[email protected]` | The user's email | -| Extension `[email protected]` | Who asked. Custos sends `user/<id>` or `app/<id>`. | +| Field | Value | +|--------------------------------------------|------------------------------------------------------------| +| Key ID | `<email>:<requested_by>`. sshd writes it to the login log. | +| Extension `[email protected]` | The user's subject | +| Extension `[email protected]` | The user's email | +| Extension `[email protected]` | Who asked. Custos sends `user/<id>` or `app/<id>`. | + +A request can also set `source_address`, a comma-separated list of IP addresses or CIDR blocks. It goes in the +certificate's `source-address` critical option, and sshd then accepts the certificate only from those addresses. A deployment has one Ed25519 CA. It is generated in Vault by the first request that reads it. diff --git a/extensions/SSH-Certificate-Signer/internal/audit/logger.go b/extensions/SSH-Certificate-Signer/internal/audit/logger.go index 9fbc7b634..b2b64bfe2 100644 --- a/extensions/SSH-Certificate-Signer/internal/audit/logger.go +++ b/extensions/SSH-Certificate-Signer/internal/audit/logger.go @@ -50,6 +50,7 @@ type IssuanceEntry struct { ValidBefore time.Time GrantedExtensions []string ForceCommand *string + SourceAddress *string } func (l *Logger) LogIssuance(ctx context.Context, entry *IssuanceEntry) error { @@ -66,6 +67,7 @@ func (l *Logger) LogIssuance(ctx context.Context, entry *IssuanceEntry) error { ValidBefore: entry.ValidBefore, GrantedExtensions: entry.GrantedExtensions, ForceCommand: entry.ForceCommand, + SourceAddress: entry.SourceAddress, } if err := l.db.InsertIssuanceLog(ctx, dbLog); err != nil { @@ -87,6 +89,7 @@ func (l *Logger) LogIssuance(ctx context.Context, entry *IssuanceEntry) error { "valid_before", entry.ValidBefore.Unix(), "granted_extensions", entry.GrantedExtensions, "force_command", entry.ForceCommand, + "source_address", entry.SourceAddress, ) return nil diff --git a/extensions/SSH-Certificate-Signer/internal/handler/certificates.go b/extensions/SSH-Certificate-Signer/internal/handler/certificates.go index 059933b89..905df99ab 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/certificates.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/certificates.go @@ -48,6 +48,7 @@ type CertificateResponse struct { IssuedAt int64 `json:"issued_at"` GrantedExtensions []string `json:"granted_extensions,omitempty"` ForceCommand *string `json:"force_command,omitempty"` + SourceAddress *string `json:"source_address,omitempty"` Revoked bool `json:"revoked"` RevokedAt *int64 `json:"revoked_at,omitempty"` RevocationReason string `json:"revocation_reason,omitempty"` @@ -253,6 +254,7 @@ func toCertificateResponse(c *store.CertificateWithStatus) CertificateResponse { IssuedAt: c.IssuedAt.Unix(), GrantedExtensions: c.GrantedExtensions, ForceCommand: c.ForceCommand, + SourceAddress: c.SourceAddress, Revoked: c.Revoked, RevocationReason: c.RevocationReason, RevokedBy: c.RevokedBy, diff --git a/extensions/SSH-Certificate-Signer/internal/handler/sign.go b/extensions/SSH-Certificate-Signer/internal/handler/sign.go index 1a25ed0af..24c21ed6e 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/sign.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/sign.go @@ -20,6 +20,7 @@ import ( "errors" "log/slog" "net/http" + "net/netip" "regexp" "slices" "strings" @@ -51,6 +52,7 @@ type SignRequest struct { UserSub string `json:"user_sub"` RequestedBy string `json:"requested_by"` ForceCommand string `json:"force_command,omitempty"` + SourceAddress string `json:"source_address,omitempty"` ExcludeExtensions []string `json:"exclude_extensions,omitempty"` } @@ -147,6 +149,11 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "invalid_request", "user_email, user_sub, requested_by or force_command is not valid") return } + if req.SourceAddress != "" && !validSourceAddress(req.SourceAddress) { + metrics.SignRequestsTotal.WithLabelValues("error").Inc() + writeError(w, http.StatusBadRequest, "invalid_request", "source_address must be a comma-separated list of IP addresses or CIDR blocks") + return + } sshPubKey, err := cert.ParseSSHPublicKey(req.PublicKey) if err != nil { @@ -219,9 +226,12 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { metrics.VaultOperationsTotal.WithLabelValues("increment_serial", "success").Inc() mark("vault_serial_us") - var criticalOpts map[string]string + criticalOpts := map[string]string{} if req.ForceCommand != "" { - criticalOpts = map[string]string{"force-command": req.ForceCommand} + criticalOpts["force-command"] = req.ForceCommand + } + if req.SourceAddress != "" { + criticalOpts["source-address"] = req.SourceAddress } signReq := &cert.SignRequest{ @@ -261,6 +271,7 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { ValidBefore: time.Unix(int64(signResult.ValidBefore), 0).UTC(), GrantedExtensions: grantedExtNames, ForceCommand: stringPtrIfNonEmpty(req.ForceCommand), + SourceAddress: stringPtrIfNonEmpty(req.SourceAddress), } auditErr := h.auditLogger.LogIssuance(r.Context(), auditEntry) @@ -352,6 +363,20 @@ func validAttributes(req *SignRequest) bool { !strings.Contains(req.UserEmail, ":") && !strings.Contains(req.RequestedBy, ":") } +// validSourceAddress validate the ip address that is going be restricted on the certificate +func validSourceAddress(list string) bool { + for entry := range strings.SplitSeq(list, ",") { + if addr, err := netip.ParseAddr(entry); err == nil && addr.Zone() == "" && !addr.Is4In6() { + continue + } + prefix, err := netip.ParsePrefix(entry) + if err != nil || prefix != prefix.Masked() || prefix.Addr().Is4In6() { + return false + } + } + return true +} + // isDuplicateKeyError detects a unique-constraint violation (SQLSTATE 23505). func isDuplicateKeyError(err error) bool { var pgErr *pgconn.PgError diff --git a/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go b/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go index 6f95598b9..1da6d21f3 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go @@ -62,6 +62,16 @@ func TestSign_RefusesUnsafeAttributes(t *testing.T) { } } +// Make sure an address list sshd would reject or never match is refused at signing. +func TestSign_RefusesUnreadableSourceAddress(t *testing.T) { + for _, address := range []string{"10.0.0.5/24", "10.0.0.1, 10.0.0.2", "10.0.0.1,", "login.example.edu", "fe80::1%eth0", "::ffff:10.0.0.1", "::ffff:10.0.0.0/104"} { + body := `{"principal":"jdoe","public_key":"k","user_email":"[email protected]","user_sub":"s","requested_by":"user/1","source_address":"` + address + `"}` + if code, errorCode := signError(t, body); code != http.StatusBadRequest || errorCode != "invalid_request" { + t.Errorf("%s: got %d %s", address, code, errorCode) + } + } +} + // Make sure a certificate cannot be issued without saying who it is for and who asked. func TestSign_RequiresUserAndRequester(t *testing.T) { for _, body := range []string{ diff --git a/extensions/SSH-Certificate-Signer/internal/store/certificate_query.go b/extensions/SSH-Certificate-Signer/internal/store/certificate_query.go index 46a288d82..c444e7081 100644 --- a/extensions/SSH-Certificate-Signer/internal/store/certificate_query.go +++ b/extensions/SSH-Certificate-Signer/internal/store/certificate_query.go @@ -17,7 +17,6 @@ package store import ( "context" - "database/sql" "encoding/json" "fmt" "strings" @@ -39,6 +38,7 @@ type CertificateWithStatus struct { IssuedAt time.Time GrantedExtensions []string ForceCommand *string + SourceAddress *string Revoked bool RevokedAt *time.Time RevocationReason string @@ -65,7 +65,7 @@ const certificateSelect = `SELECT c.id, c.serial_number, c.key_id, c.principal, c.user_email, c.user_sub, c.requested_by, c.public_key_fingerprint, c.ca_fingerprint, c.valid_after, c.valid_before, c.issued_at, - c.granted_extensions, c.force_command, + c.granted_extensions, c.force_command, c.source_address, CASE WHEN r.id IS NOT NULL THEN TRUE ELSE FALSE END AS revoked, r.revoked_at, COALESCE(r.reason, '') AS revocation_reason, @@ -139,12 +139,11 @@ func scanCertificates(rows certificateRows) ([]CertificateWithStatus, error) { var cert CertificateWithStatus var revokedAt *time.Time var grantedExtensionsJSON []byte - var forceCommand sql.NullString if err := rows.Scan( &cert.ID, &cert.SerialNumber, &cert.KeyID, &cert.Principal, &cert.UserEmail, &cert.UserSub, &cert.RequestedBy, &cert.PublicKeyFingerprint, &cert.CAFingerprint, &cert.ValidAfter, &cert.ValidBefore, &cert.IssuedAt, - &grantedExtensionsJSON, &forceCommand, + &grantedExtensionsJSON, &cert.ForceCommand, &cert.SourceAddress, &cert.Revoked, &revokedAt, &cert.RevocationReason, &cert.RevokedBy, ); err != nil { return nil, fmt.Errorf("scanning certificate row: %w", err) @@ -154,9 +153,6 @@ func scanCertificates(rows certificateRows) ([]CertificateWithStatus, error) { return nil, fmt.Errorf("unmarshaling granted_extensions: %w", err) } } - if forceCommand.Valid { - cert.ForceCommand = &forceCommand.String - } cert.RevokedAt = revokedAt certs = append(certs, cert) } diff --git a/extensions/SSH-Certificate-Signer/internal/store/certificate_query_test.go b/extensions/SSH-Certificate-Signer/internal/store/certificate_query_test.go index 49c4ceb9a..c0380d4f0 100644 --- a/extensions/SSH-Certificate-Signer/internal/store/certificate_query_test.go +++ b/extensions/SSH-Certificate-Signer/internal/store/certificate_query_test.go @@ -32,11 +32,11 @@ func certificateQueryRow() *sqlmock.Rows { return sqlmock.NewRows([]string{ "id", "serial_number", "key_id", "principal", "user_email", "user_sub", "requested_by", "public_key_fingerprint", "ca_fingerprint", "valid_after", "valid_before", "issued_at", - "granted_extensions", "force_command", "revoked", "revoked_at", "revocation_reason", "revoked_by", + "granted_extensions", "force_command", "source_address", "revoked", "revoked_at", "revocation_reason", "revoked_by", }).AddRow( 1, 42, "key-1", "alice", "[email protected]", "sub-1", "app-1", "SHA256:key", "SHA256:ca", issued, issued.Add(time.Hour), issued, - []byte(`["permit-pty"]`), nil, true, revoked, "compromised", "[email protected]", + []byte(`["permit-pty"]`), nil, nil, true, revoked, "compromised", "[email protected]", ) } @@ -100,7 +100,7 @@ func TestListCertificatesDeploymentWideUsesCursorAndTimestampTieBreaker(t *testi rows.AddRow( 2, 41, "key-2", "alice", "[email protected]", "sub-1", "app-1", "SHA256:key2", "SHA256:ca", issued, issued.Add(time.Hour), issued, - []byte(`[]`), nil, false, nil, "", "", + []byte(`[]`), nil, nil, false, nil, "", "", ) mock.ExpectQuery("WHERE \\(c.issued_at < \\$1 OR \\(c.issued_at = \\$2 AND c.id < \\$3\\)\\)"). WithArgs(issued, issued, int64(10), 2). diff --git a/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go b/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go index d4e6bb631..6da122c22 100644 --- a/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go +++ b/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go @@ -35,6 +35,7 @@ type IssuanceLog struct { ValidBefore time.Time GrantedExtensions []string ForceCommand *string + SourceAddress *string } // InsertIssuanceLog writes a certificate issuance entry. Fails on duplicate serial_number. @@ -51,11 +52,11 @@ func (d *DB) InsertIssuanceLog(ctx context.Context, log *IssuanceLog) error { _, err = d.ExecContext(ctx, `INSERT INTO certificate_issuance_logs (serial_number, key_id, principal, user_email, user_sub, requested_by, public_key_fingerprint, - ca_fingerprint, valid_after, valid_before, granted_extensions, force_command) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + ca_fingerprint, valid_after, valid_before, granted_extensions, force_command, source_address) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`, log.SerialNumber, log.KeyID, log.Principal, log.UserEmail, log.UserSub, log.RequestedBy, log.PublicKeyFingerprint, log.CAFingerprint, log.ValidAfter, log.ValidBefore, - grantedExtensionsJSON, log.ForceCommand, + grantedExtensionsJSON, log.ForceCommand, log.SourceAddress, ) if err != nil { return fmt.Errorf("inserting issuance log: %w", err) 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 091130186..1d19b8a90 100644 --- a/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql +++ b/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql @@ -31,6 +31,7 @@ CREATE TABLE IF NOT EXISTS certificate_issuance_logs issued_at TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), granted_extensions JSONB NOT NULL, force_command TEXT NULL, + source_address TEXT NULL, PRIMARY KEY (id), CONSTRAINT uq_issuance_serial UNIQUE (serial_number) diff --git a/web/src/features/core/signer/components/CertificateDetail.tsx b/web/src/features/core/signer/components/CertificateDetail.tsx index 91cfeb369..20f3ba409 100644 --- a/web/src/features/core/signer/components/CertificateDetail.tsx +++ b/web/src/features/core/signer/components/CertificateDetail.tsx @@ -158,6 +158,7 @@ function CertificateMetadata({ cert }: { cert: Certificate }) { value: cert.granted_extensions?.length ? cert.granted_extensions.join(", ") : "—", }, { label: "Force command", value: cert.force_command || "—" }, + { label: "Source address", value: cert.source_address || "Any" }, ]; if (cert.revoked) { diff --git a/web/src/features/core/signer/components/MyCertificateDetail.tsx b/web/src/features/core/signer/components/MyCertificateDetail.tsx index d0994bbfa..ed175c7ec 100644 --- a/web/src/features/core/signer/components/MyCertificateDetail.tsx +++ b/web/src/features/core/signer/components/MyCertificateDetail.tsx @@ -65,6 +65,7 @@ export function MyCertificateDetail({ serial }: { serial: string }) { ["Lifetime", formatCertificateLifetime(cert)], ["Options", cert.granted_extensions?.join(", ") || "None"], ["Command", cert.force_command || "None"], + ["Can log in from", cert.source_address || "Any address"], ]; return ( diff --git a/web/src/features/core/signer/schemas.ts b/web/src/features/core/signer/schemas.ts index 9cc4dc3dd..b8efb3bd0 100644 --- a/web/src/features/core/signer/schemas.ts +++ b/web/src/features/core/signer/schemas.ts @@ -35,6 +35,7 @@ export const certificateSchema = z.object({ issued_at: z.number().int(), granted_extensions: z.array(z.string()).optional(), force_command: z.string().nullable().optional(), + source_address: z.string().nullable().optional(), revoked: z.boolean(), revoked_at: z.number().int().nullable().optional(), revocation_reason: z.string().optional(),
