// Device authentication module // Handles device registration, challenge-response, and session management package auth import ( "crypto/ecdsa" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "errors" "fmt" "sync" "time" commonCrypto "security-connector/common/crypto" "security-connector/common/proto" "security-connector/common/types" "security-connector/server/attest" "security-connector/server/audit" serverCrypto "security-connector/server/crypto" ) // DeviceAuthenticator handles device authentication type DeviceAuthenticator struct { mu sync.RWMutex // Server key manager keyManager *ServerKeyManager // Remote attestation verifier. Never nil: NewDeviceAuthenticator installs a // strict verifier by default so that forgetting to configure attestation // fails closed rather than silently admitting anyone. attestor *attest.Verifier // Optional audit sink for management-plane actions (revoke, etc). Wired // post-construction via SetAuditLogger so the management plane can plug // it in without changing every constructor signature. auditLog *audit.Logger // Active challenges challenges map[string]*types.Challenge // Registered devices devices map[string]*types.Device // Challenge expiry duration challengeExpiry time.Duration } // ServerKeyManager is an alias for clarity type ServerKeyManager = serverCrypto.ServerKeyManager // NewDeviceAuthenticator creates a new device authenticator with strict // attestation and an in-memory (non-persistent) golden-value store. func NewDeviceAuthenticator(keyManager *serverCrypto.ServerKeyManager) *DeviceAuthenticator { return NewDeviceAuthenticatorWithAttestor(keyManager, attest.NewVerifier(attest.ModeStrict, attest.DefaultPolicy())) } // NewDeviceAuthenticatorWithAttestor lets the caller supply a configured // attestation verifier (mode, policy, persistence). func NewDeviceAuthenticatorWithAttestor(keyManager *serverCrypto.ServerKeyManager, attestor *attest.Verifier) *DeviceAuthenticator { if attestor == nil { attestor = attest.NewVerifier(attest.ModeStrict, attest.DefaultPolicy()) } return &DeviceAuthenticator{ keyManager: keyManager, attestor: attestor, challenges: make(map[string]*types.Challenge), devices: make(map[string]*types.Device), challengeExpiry: 5 * time.Minute, } } // Attestor exposes the attestation verifier (used by the API layer to issue // enrollment nonces). func (da *DeviceAuthenticator) Attestor() *attest.Verifier { return da.attestor } // SetAuditLogger wires an audit logger into the authenticator so that operator // actions (revoke) are recorded alongside device-side events. Safe to call at // most once and safe to leave unset; revoke then just skips the audit entry. func (da *DeviceAuthenticator) SetAuditLogger(al *audit.Logger) { da.mu.Lock() defer da.mu.Unlock() da.auditLog = al } // IssueEnrollmentNonce mints the attestation challenge a device must quote over // before it may register. func (da *DeviceAuthenticator) IssueEnrollmentNonce(deviceID string) (*proto.EnrollNonceResponse, error) { ch, err := da.attestor.IssueNonce(deviceID) if err != nil { return nil, err } return &proto.EnrollNonceResponse{ APIResponse: *proto.NewSuccessResponse(proto.TypeEnrollNonceResponse), Nonce: ch.NonceB64(), PCRMask: ch.PCRMask, ExpireAt: ch.ExpireAt.Unix(), }, nil } // RegisterDevice handles device registration request. // // Enrollment is gated on remote attestation: the device must present a TPM // quote, signed by the very key it is enrolling, over a nonce this server // issued moments ago, committing to its boot measurements. Prior to this the // quote fields were accepted and discarded, which meant possession of nothing // more than a freshly generated P-256 key was sufficient to obtain a KEK. func (da *DeviceAuthenticator) RegisterDevice(req *proto.RegisterRequest) (*proto.RegisterResponse, error) { da.mu.Lock() defer da.mu.Unlock() if req.DeviceID == "" { return nil, errors.New("device id required") } // Parse device public key devicePubKeyBytes, err := base64.StdEncoding.DecodeString(req.TPMPublicKey) if err != nil { return nil, fmt.Errorf("invalid TPM public key: %w", err) } devicePubKey, err := commonCrypto.ParsePublicKey(devicePubKeyBytes) if err != nil { return nil, fmt.Errorf("failed to parse device public key: %w", err) } // Remote attestation. The AIK is the enrolling key itself: a quote signed // by a different key would let an attacker relay a healthy device's // measurement while enrolling its own key. attestation, err := da.attestor.Verify(attest.Input{ DeviceID: req.DeviceID, AIK: devicePubKey, QuoteB64: req.TPMQuote, SignatureB64: req.QuoteSignature, NonceB64: req.Nonce, PCRMask: req.QuotePCRMask, FirmwareHash: req.FirmwareHash, }) if err != nil { return nil, fmt.Errorf("attestation failed: %w", err) } // Derive KEK for this device kek, err := da.keyManager.DeriveDeviceKEK(req.DeviceID, devicePubKey) if err != nil { return nil, fmt.Errorf("failed to derive KEK: %w", err) } // Generate session key for this registration sessionKey, err := commonCrypto.DeriveKey(nil, kek.Key, commonCrypto.HKDFInfoSession, commonCrypto.AES256KeySize) if err != nil { return nil, fmt.Errorf("failed to derive session key: %w", err) } // Encrypt KEK with session key (simplified for Phase 1) encryptedKEK, err := da.keyManager.EncryptKEKForDevice(kek, sessionKey) if err != nil { return nil, fmt.Errorf("failed to encrypt KEK: %w", err) } // Get server public key for ECDH serverPubKey, err := da.keyManager.GetServerPublicKey() if err != nil { return nil, fmt.Errorf("failed to get server public key: %w", err) } // A device that did not clear attestation is recorded, but it is not handed // "active" status - downstream policy can then refuse it a tunnel. status := types.StatusActive if !attestation.Verified { status = types.StatusPending } pcrValues := make([]string, 0, len(attestation.PCRs)) for _, p := range attestation.PCRs { pcrValues = append(pcrValues, fmt.Sprintf("%d:%s", p.Index, p.Digest)) } // Create device entry now := time.Now() device := &types.Device{ DeviceID: req.DeviceID, Status: status, TPMPublicKey: req.TPMPublicKey, KeyVersion: kek.Version, KEKID: kek.KeyID, FirmwareHash: req.FirmwareHash, PCRValues: pcrValues, // Endpoint is reported by the connector at registration, or derived // from the device id so the SSWFlow management plane can bind this // security-plane record back to its connector record via endpoint. Endpoint: deviceEndpoint(req.DeviceID, req.Endpoint), // Attestation footprint (also surfaced to /device/status for the // SSWFlow management plane). AttestStatus: attestation.Status, AttestMode: string(da.attestor.Mode()), PCRDigest: attestation.PCRDigest, PCRMask: da.attestor.RequiredPCRMask(), QuoteSignedAt: attestation.VerifiedAt, LastAttestTime: &now, CreatedAt: now, UpdatedAt: now, } da.devices[req.DeviceID] = device return &proto.RegisterResponse{ APIResponse: *proto.NewSuccessResponse(proto.TypeRegisterResponse), EncryptedKEK: base64.StdEncoding.EncodeToString(encryptedKEK), KEKVersion: kek.Version, ServerPublicKey: base64.StdEncoding.EncodeToString(serverPubKey), ValidUntil: time.Now().Add(24 * time.Hour).Unix(), AttestationStatus: attestation.Status, PCRDigest: attestation.PCRDigest, }, nil } // deviceEndpoint resolves the platform endpoint a device is reachable at. // Connectors may report their own endpoint during registration; otherwise we // derive a stable per-device default (https://.ssw.local:8443) so // the SSWFlow management plane can still bind the security-plane record back // to its connector record by endpoint even when none was explicitly reported. func deviceEndpoint(deviceID, reported string) string { if reported != "" { return reported } return fmt.Sprintf("https://%s.ssw.local:8443", deviceID) } // CreateChallenge creates a new challenge for a device func (da *DeviceAuthenticator) CreateChallenge(deviceID string) (*proto.ChallengeRequest, error) { da.mu.Lock() defer da.mu.Unlock() // Check if device exists device, exists := da.devices[deviceID] if !exists { return nil, fmt.Errorf("device not found: %s", deviceID) } // Generate nonce and challenge nonce, err := commonCrypto.GenerateNonce(32) if err != nil { return nil, fmt.Errorf("failed to generate nonce: %w", err) } challenge, err := commonCrypto.GenerateNonce(32) if err != nil { return nil, fmt.Errorf("failed to generate challenge: %w", err) } // Store challenge da.challenges[deviceID] = &types.Challenge{ DeviceID: deviceID, Nonce: nonce, Challenge: challenge, ExpiresAt: time.Now().Add(da.challengeExpiry), Used: false, } device.LastAuthAt = nil device.UpdatedAt = time.Now() return &proto.ChallengeRequest{ APIRequest: proto.APIRequest{ Type: proto.TypeChallengeRequest, DeviceID: deviceID, }, Nonce: base64.StdEncoding.EncodeToString(nonce), Challenge: base64.StdEncoding.EncodeToString(challenge), ExpireAt: time.Now().Add(da.challengeExpiry).Unix(), }, nil } // VerifyChallengeResponse verifies the device's challenge response func (da *DeviceAuthenticator) VerifyChallengeResponse(deviceID string, resp *proto.ChallengeResponse) (*proto.AuthResponse, error) { da.mu.Lock() defer da.mu.Unlock() // Find the challenge challenge, exists := da.challenges[deviceID] if !exists { return nil, errors.New("no active challenge found") } // Check if challenge is expired if time.Now().After(challenge.ExpiresAt) { delete(da.challenges, deviceID) return nil, errors.New("challenge expired") } // Check if challenge was already used if challenge.Used { return nil, errors.New("challenge already used") } // Verify nonce matches respNonce, err := base64.StdEncoding.DecodeString(resp.Nonce) if err != nil { return nil, fmt.Errorf("invalid nonce encoding: %w", err) } if string(respNonce) != string(challenge.Nonce) { return nil, errors.New("nonce mismatch") } // Mark challenge as used challenge.Used = true // Get device device, exists := da.devices[deviceID] if !exists { return nil, errors.New("device not found") } // Parse device public key devicePubKeyBytes, err := base64.StdEncoding.DecodeString(device.TPMPublicKey) if err != nil { return nil, fmt.Errorf("invalid TPM public key: %w", err) } devicePubKey, err := commonCrypto.ParsePublicKey(devicePubKeyBytes) if err != nil { return nil, fmt.Errorf("failed to parse device public key: %w", err) } // Verify signature signature, err := base64.StdEncoding.DecodeString(resp.Signature) if err != nil { return nil, fmt.Errorf("invalid signature encoding: %w", err) } // Build signed data (challenge + nonce) signedData := append(challenge.Challenge, challenge.Nonce...) if !commonCrypto.Verify(devicePubKey, signedData, signature) { return nil, errors.New("signature verification failed") } // Generate session key kek, err := da.keyManager.GetDeviceKEK(deviceID) if err != nil { return nil, fmt.Errorf("failed to get KEK: %w", err) } sessionKey, err := commonCrypto.DeriveKey(nil, kek.Key, commonCrypto.HKDFInfoSession, commonCrypto.AES256KeySize) if err != nil { return nil, fmt.Errorf("failed to derive session key: %w", err) } // Update device status device.Status = types.StatusActive device.LastAuthAt = timePtr(time.Now()) device.UpdatedAt = time.Now() // Clean up challenge delete(da.challenges, deviceID) return &proto.AuthResponse{ APIResponse: *proto.NewSuccessResponse(proto.TypeAuthResponse), SessionKey: base64.StdEncoding.EncodeToString(sessionKey), ValidUntil: time.Now().Add(24 * time.Hour).Unix(), }, nil } // GetDevice retrieves a device by ID func (da *DeviceAuthenticator) GetDevice(deviceID string) (*types.Device, error) { da.mu.RLock() defer da.mu.RUnlock() device, exists := da.devices[deviceID] if !exists { return nil, errors.New("device not found") } return device, nil } // GetDeviceStatus retrieves device status func (da *DeviceAuthenticator) GetDeviceStatus(deviceID string) (*proto.DeviceStatus, error) { device, err := da.GetDevice(deviceID) if err != nil { return nil, err } return &proto.DeviceStatus{ DeviceID: device.DeviceID, Status: string(device.Status), KeyVersion: device.KeyVersion, LastAuthTime: timePtrToTime(device.LastAuthAt), KEKID: device.KEKID, }, nil } // ListDevices lists all registered devices func (da *DeviceAuthenticator) ListDevices() []*types.Device { da.mu.RLock() defer da.mu.RUnlock() devices := make([]*types.Device, 0, len(da.devices)) for _, device := range da.devices { devices = append(devices, device) } return devices } // RevokeDevice marks a device as revoked so subsequent challenges fail-closed. // It is intended to be called from a management plane (SSWFlow TDS) over the // admin REST API. The state change is recorded through the audit logger when // available so the operator action shows up in the same JSONL stream as // device-side events. func (da *DeviceAuthenticator) RevokeDevice(deviceID, operator, reason string) (*types.Device, error) { if deviceID == "" { return nil, errors.New("device_id required") } da.mu.Lock() device, exists := da.devices[deviceID] if !exists { da.mu.Unlock() return nil, errors.New("device not found") } device.Status = types.StatusRevoked now := time.Now() device.LastAuthAt = &now da.mu.Unlock() if da.auditLog != nil { details, _ := json.Marshal(map[string]interface{}{ "operator": operator, "reason": reason, }) da.auditLog.Log(&types.AuditEvent{ EventType: types.AuditRevoke, DeviceID: deviceID, Operator: operator, Result: "success", Details: details, }) } return device, nil } // Helper functions func timePtr(t time.Time) *time.Time { return &t } func timePtrToTime(t *time.Time) time.Time { if t == nil { return time.Time{} } return *t } // GetECDSAPublicKey parses and returns an ECDSA public key func GetECDSAPublicKey(pemBytes []byte) (*ecdsa.PublicKey, error) { // Try PEM parsing first block, _ := pem.Decode(pemBytes) if block != nil { pemBytes = block.Bytes } key, err := x509.ParsePKIXPublicKey(pemBytes) if err != nil { return nil, err } ecdsaKey, ok := key.(*ecdsa.PublicKey) if !ok { return nil, errors.New("not an ECDSA public key") } return ecdsaKey, nil }