From 7d752dc12d7483e563a56d1c01b00ea166dce13a Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Sun, 22 Nov 2026 09:30:10 +1100 Subject: [PATCH] feat(packs,sdk): add signed database audit parsers and typed OWASP ASVS SDK helpers (#208) --- docs/deployment/database-audit.md | 18 +- packs/owasp-asvs-app-logging/pack.yaml | 7 +- .../parsers/mongodb-audit-json.json | 99 ++++ .../parsers/mysql-audit-json.json | 111 ++++ .../parsers/pgaudit-jsonlog.json | 84 +++ .../parsers/sqlserver-audit-33205.json | 111 ++++ src/Bower.Packs/PackRuntime.cs | 57 +- src/Bower.Pipeline/CustomLogParser.cs | 20 +- src/Bower.Sdk/AsvsSemanticEvents.cs | 253 +++++++++ src/Bower.Sdk/BufferedBowerClient.Asvs.cs | 537 ++++++++++++++++++ src/Bower.Sdk/BufferedBowerClient.cs | 2 +- src/Bower.Sdk/IAsvsTelemetry.cs | 53 ++ src/Bower.Sdk/ServiceCollectionExtensions.cs | 1 + .../AsvsSdkAndDbParsersTests.cs | 266 +++++++++ 14 files changed, 1603 insertions(+), 16 deletions(-) create mode 100644 packs/owasp-asvs-app-logging/parsers/mongodb-audit-json.json create mode 100644 packs/owasp-asvs-app-logging/parsers/mysql-audit-json.json create mode 100644 packs/owasp-asvs-app-logging/parsers/pgaudit-jsonlog.json create mode 100644 packs/owasp-asvs-app-logging/parsers/sqlserver-audit-33205.json create mode 100644 src/Bower.Sdk/AsvsSemanticEvents.cs create mode 100644 src/Bower.Sdk/BufferedBowerClient.Asvs.cs create mode 100644 src/Bower.Sdk/IAsvsTelemetry.cs create mode 100644 tests/Bower.UnitTests/AsvsSdkAndDbParsersTests.cs diff --git a/docs/deployment/database-audit.md b/docs/deployment/database-audit.md index b67d224c..9c45d478 100644 --- a/docs/deployment/database-audit.md +++ b/docs/deployment/database-audit.md @@ -16,11 +16,19 @@ Use the database's native audit facility first. Then pick one of two paths into [ASVS pack](../security/asvs-logging-pack.md) policy `BWR-PACK-ASVS-DB-AUDIT` selects them, and they land in `BowerSecurity_CL` beside the application events. -Bower doesn't ship a parser for any of these formats yet. The -[file tail](file-tail-source.md) and [syslog](syslog-source.md) sources plus a -[custom parser](../developer-integration/custom-log-parser.md) are the building blocks; -each format still needs its own signed parser, privacy fixtures and samples before it counts -as supported. +Bower ships four signed parsers in `packs/owasp-asvs-app-logging/parsers/` for self-managed +database audit streams: + +- `pgaudit-jsonlog.json` — PostgreSQL 15+ `jsonlog` `AUDIT:` and password-failure records +- `mysql-audit-json.json` — MySQL Enterprise Audit and Percona `audit_log_filter` JSON records +- `mongodb-audit-json.json` — MongoDB Enterprise / Atlas JSON audit records +- `sqlserver-audit-33205.json` — SQL Server Audit Windows Event ID `33205` via the Windows Event Log source + +Pair them with the [file tail](file-tail-source.md), [syslog](syslog-source.md) or +[Windows Event Log](windows-event-log-source.md) source. Every parser maps only allow-listed +security metadata (`actor.username`, `source.ipAddress`, `target.name`, `labels.dbEngine`, +`labels.dbStatementClass`) and drops raw SQL or command statements before redaction and +persistence. Cosmos DB continues to use Azure native diagnostic settings (path 1). ## The `database_audit` event diff --git a/packs/owasp-asvs-app-logging/pack.yaml b/packs/owasp-asvs-app-logging/pack.yaml index b97e9963..39b57024 100644 --- a/packs/owasp-asvs-app-logging/pack.yaml +++ b/packs/owasp-asvs-app-logging/pack.yaml @@ -2,7 +2,7 @@ apiVersion: bower.security/v1 kind: Pack metadata: id: owasp-asvs-app-logging - version: 1.0.0 + version: 1.1.0 name: OWASP ASVS 5.0 application security logging description: >- Starter pack for the security events OWASP ASVS 5.0 chapter V16 asks applications to @@ -28,6 +28,11 @@ policies: - policies/errors-and-control-failures.yaml - policies/database-audit.yaml privacyProfile: privacy.yaml +parsers: + - parsers/pgaudit-jsonlog.json + - parsers/mysql-audit-json.json + - parsers/mongodb-audit-json.json + - parsers/sqlserver-audit-33205.json detections: - detections/mfa-factor-removed.yml - detections/authorisation-stale-grant.yml diff --git a/packs/owasp-asvs-app-logging/parsers/mongodb-audit-json.json b/packs/owasp-asvs-app-logging/parsers/mongodb-audit-json.json new file mode 100644 index 00000000..6617a56e --- /dev/null +++ b/packs/owasp-asvs-app-logging/parsers/mongodb-audit-json.json @@ -0,0 +1,99 @@ +{ + "version": "1.0", + "format": "Json", + "fields": [ + { "sourceName": "atype", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "uuid", "type": "Text", "ocsfPath": "metadata.uid", "asimField": "EventOriginalUid", "sensitive": false }, + { "sourceName": "result", "type": "WholeNumber", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "event_id", "type": "Text", "ocsfPath": "metadata.uid", "asimField": "EventOriginalUid", "sensitive": true }, + { "sourceName": "event_time", "type": "DateTime", "ocsfPath": "time", "asimField": "TimeGenerated", "sensitive": true }, + { "sourceName": "event_category", "type": "Text", "ocsfPath": "category_name", "asimField": "EventType", "sensitive": true }, + { "sourceName": "event_action", "type": "Text", "ocsfPath": "activity_name", "asimField": "EventSubType", "sensitive": true }, + { "sourceName": "event_result", "type": "Text", "ocsfPath": "status", "asimField": "EventResult", "sensitive": true }, + { "sourceName": "actor_user", "type": "Text", "ocsfPath": "actor.user.name", "asimField": "TargetUsername", "sensitive": true }, + { "sourceName": "source_ip", "type": "IpAddress", "ocsfPath": "src_endpoint.ip", "asimField": "SrcIpAddr", "sensitive": true }, + { "sourceName": "target_type", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "target_name", "type": "Text", "ocsfPath": "database.name", "asimField": "TargetAppName", "sensitive": true }, + { "sourceName": "db_engine", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "statement_class", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "reason", "type": "Text", "ocsfPath": "status_detail", "asimField": "EventResultDetails", "sensitive": true }, + { "sourceName": "matched", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": true } + ], + "runtime": { + "applicationName": "mongodb-audit", + "environment": "production", + "eventCategory": "administrative-activity", + "eventType": "database_audit", + "eventAction": "db.dcl", + "eventResult": "success", + "transforms": [ + ".event_time = parse_timestamp(coalesce(.ts.\"$date\", .ts), \"rfc3339\")", + ".event_id = concat(\"mongodb-audit-\", coalesce(.uuid.\"$binary\", .uuid, .event_time))", + ".u0 = at(.users, 0)", + ".actor_user = coalesce(.u0.user, .param.user)", + ".ipm = regex_extract(.remote.ip, '^(?[0-9A-Fa-f.:]{2,45})$')", + ".source_ip = .ipm.ip", + ".target_type = \"database\"", + ".target_name = coalesce(.param.ns, .param.db, .u0.db, \"admin\")", + ".db_engine = \"mongodb\"", + ".statement_class = .atype", + ".ma = lookup(\"actions\", .atype)", + ".matched = \"ignored\"", + "if .ma != null && .actor_user != null { .matched = \"yes\"; .event_category = lookup(\"categories\", .atype); .event_action = .ma; .event_result = \"success\"; .reason = .atype }", + "if .matched == \"yes\" && .result != 0 { .event_result = \"failure\"; .reason = concat(\"MongoResult_\", to_string(.result)) }", + "if .matched == \"yes\" && .atype == \"authenticate\" && .result != 0 { .event_action = \"db.logon_failure\" }", + "del(.u0)", + "del(.ipm)", + "del(.ma)" + ], + "tables": { + "actions": { + "authenticate": "db.logon", + "logout": "db.logoff", + "createUser": "db.dcl", + "dropUser": "db.dcl", + "grantRolesToUser": "db.dcl", + "revokeRolesFromUser": "db.dcl", + "createRole": "db.dcl", + "dropRole": "db.dcl", + "createCollection": "db.ddl", + "dropCollection": "db.ddl", + "dropDatabase": "db.ddl", + "authCheck": "db.sensitive_read", + "shutdown": "db.privileged" + }, + "categories": { + "authenticate": "authentication", + "logout": "authentication", + "createUser": "administrative-activity", + "dropUser": "administrative-activity", + "grantRolesToUser": "administrative-activity", + "revokeRolesFromUser": "administrative-activity", + "createRole": "administrative-activity", + "dropRole": "administrative-activity", + "createCollection": "administrative-activity", + "dropCollection": "administrative-activity", + "dropDatabase": "administrative-activity", + "authCheck": "data-access", + "shutdown": "administrative-activity" + } + }, + "match": { + "matched": "yes" + }, + "fields": { + "eventId": "event_id", + "timeGenerated": "event_time", + "eventCategory": "event_category", + "eventAction": "event_action", + "eventResult": "event_result", + "actor.username": "actor_user", + "source.ipAddress": "source_ip", + "target.type": "target_type", + "target.name": "target_name", + "labels.dbEngine": "db_engine", + "labels.dbStatementClass": "statement_class", + "eventOutcomeReason": "reason" + } + } +} diff --git a/packs/owasp-asvs-app-logging/parsers/mysql-audit-json.json b/packs/owasp-asvs-app-logging/parsers/mysql-audit-json.json new file mode 100644 index 00000000..49174a3b --- /dev/null +++ b/packs/owasp-asvs-app-logging/parsers/mysql-audit-json.json @@ -0,0 +1,111 @@ +{ + "version": "1.0", + "format": "Json", + "fields": [ + { "sourceName": "timestamp", "type": "Text", "ocsfPath": "time", "asimField": "TimeGenerated", "sensitive": false }, + { "sourceName": "id", "type": "Text", "ocsfPath": "metadata.uid", "asimField": "EventOriginalUid", "sensitive": false }, + { "sourceName": "class", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "event", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "user", "type": "Text", "ocsfPath": "actor.user.name", "asimField": "TargetUsername", "sensitive": true }, + { "sourceName": "ip", "type": "Text", "ocsfPath": "src_endpoint.ip", "asimField": "SrcIpAddr", "sensitive": true }, + { "sourceName": "db", "type": "Text", "ocsfPath": "database.name", "asimField": "TargetAppName", "sensitive": false }, + { "sourceName": "command", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "status", "type": "WholeNumber", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "event_id", "type": "Text", "ocsfPath": "metadata.uid", "asimField": "EventOriginalUid", "sensitive": false }, + { "sourceName": "event_time", "type": "DateTime", "ocsfPath": "time", "asimField": "TimeGenerated", "sensitive": false }, + { "sourceName": "event_category", "type": "Text", "ocsfPath": "category_name", "asimField": "EventType", "sensitive": true }, + { "sourceName": "event_action", "type": "Text", "ocsfPath": "activity_name", "asimField": "EventSubType", "sensitive": true }, + { "sourceName": "event_result", "type": "Text", "ocsfPath": "status", "asimField": "EventResult", "sensitive": true }, + { "sourceName": "actor_user", "type": "Text", "ocsfPath": "actor.user.name", "asimField": "TargetUsername", "sensitive": true }, + { "sourceName": "source_ip", "type": "IpAddress", "ocsfPath": "src_endpoint.ip", "asimField": "SrcIpAddr", "sensitive": true }, + { "sourceName": "target_type", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "target_name", "type": "Text", "ocsfPath": "database.name", "asimField": "TargetAppName", "sensitive": true }, + { "sourceName": "db_engine", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "statement_class", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": true }, + { "sourceName": "reason", "type": "Text", "ocsfPath": "status_detail", "asimField": "EventResultDetails", "sensitive": true }, + { "sourceName": "matched", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": true } + ], + "runtime": { + "applicationName": "mysql-audit", + "environment": "production", + "eventCategory": "data-access", + "eventType": "database_audit", + "eventAction": "db.ddl", + "eventResult": "success", + "transforms": [ + ".event_time = parse_timestamp(.timestamp, \"rfc3339\")", + ".event_id = concat(\"mysql-audit-\", to_string(.id))", + ".actor_user = coalesce(.account.user, .user)", + ".ipm = regex_extract(coalesce(.ip, .connection_data.ip), '^(?[0-9A-Fa-f.:]{2,45})$')", + ".source_ip = .ipm.ip", + ".target_type = \"database\"", + ".target_name = coalesce(.db, .table_access_data.db, .connection_data.db, \"mysql\")", + ".db_engine = \"mysql\"", + ".cmd = upper(coalesce(.command, .general_data.sql_command, .event, \"\"))", + ".st = coalesce(.status, .connection_data.status, .general_data.status, 0)", + ".matched = \"ignored\"", + "if .class == \"connection\" && .event == \"connect\" && .actor_user != null { .matched = \"yes\"; .event_category = \"authentication\"; .statement_class = \"CONNECT\" }", + "if .matched == \"yes\" && .class == \"connection\" && .event == \"connect\" && .st == 0 { .event_action = \"db.logon\"; .event_result = \"success\"; .reason = \"ConnectSucceeded\" }", + "if .matched == \"yes\" && .class == \"connection\" && .event == \"connect\" && .st != 0 { .event_action = \"db.logon_failure\"; .event_result = \"failure\"; .reason = concat(\"MySqlStatus_\", to_string(.st)) }", + "if .class == \"connection\" && .event == \"disconnect\" && .actor_user != null { .matched = \"yes\"; .event_category = \"authentication\"; .event_action = \"db.logoff\"; .event_result = \"success\"; .statement_class = \"DISCONNECT\"; .reason = \"Disconnect\" }", + "if .matched == \"ignored\" && lookup(\"actions\", .cmd) != null && .actor_user != null { .matched = \"yes\"; .event_action = lookup(\"actions\", .cmd); .event_category = lookup(\"categories\", .cmd); .statement_class = .cmd; .event_result = \"success\"; .reason = .cmd }", + "if .matched == \"yes\" && .class != \"connection\" && .st != 0 { .event_action = \"db.query_error\"; .event_category = \"data-access\"; .event_result = \"failure\"; .reason = concat(\"MySqlStatus_\", to_string(.st)) }", + "del(.ipm)", + "del(.cmd)", + "del(.st)" + ], + "tables": { + "actions": { + "CREATE_TABLE": "db.ddl", + "ALTER_TABLE": "db.ddl", + "DROP_TABLE": "db.ddl", + "CREATE_DB": "db.ddl", + "DROP_DB": "db.ddl", + "GRANT": "db.dcl", + "REVOKE": "db.dcl", + "CREATE_USER": "db.dcl", + "DROP_USER": "db.dcl", + "ALTER_USER": "db.dcl", + "SELECT": "db.sensitive_read", + "READ": "db.sensitive_read", + "INSERT": "db.sensitive_write", + "UPDATE": "db.sensitive_write", + "DELETE": "db.sensitive_write" + }, + "categories": { + "CREATE_TABLE": "administrative-activity", + "ALTER_TABLE": "administrative-activity", + "DROP_TABLE": "administrative-activity", + "CREATE_DB": "administrative-activity", + "DROP_DB": "administrative-activity", + "GRANT": "administrative-activity", + "REVOKE": "administrative-activity", + "CREATE_USER": "administrative-activity", + "DROP_USER": "administrative-activity", + "ALTER_USER": "administrative-activity", + "SELECT": "data-access", + "READ": "data-access", + "INSERT": "data-access", + "UPDATE": "data-access", + "DELETE": "data-access" + } + }, + "match": { + "matched": "yes" + }, + "fields": { + "eventId": "event_id", + "timeGenerated": "event_time", + "eventCategory": "event_category", + "eventAction": "event_action", + "eventResult": "event_result", + "actor.username": "actor_user", + "source.ipAddress": "source_ip", + "target.type": "target_type", + "target.name": "target_name", + "labels.dbEngine": "db_engine", + "labels.dbStatementClass": "statement_class", + "eventOutcomeReason": "reason" + } + } +} diff --git a/packs/owasp-asvs-app-logging/parsers/pgaudit-jsonlog.json b/packs/owasp-asvs-app-logging/parsers/pgaudit-jsonlog.json new file mode 100644 index 00000000..f753efb7 --- /dev/null +++ b/packs/owasp-asvs-app-logging/parsers/pgaudit-jsonlog.json @@ -0,0 +1,84 @@ +{ + "version": "1.0", + "format": "Json", + "fields": [ + { "sourceName": "timestamp", "type": "Text", "ocsfPath": "time", "asimField": "TimeGenerated", "sensitive": false }, + { "sourceName": "session_id", "type": "Text", "ocsfPath": "metadata.uid", "asimField": "EventOriginalUid", "sensitive": false }, + { "sourceName": "session_line_num", "type": "WholeNumber", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "user", "type": "Text", "ocsfPath": "actor.user.name", "asimField": "TargetUsername", "sensitive": true }, + { "sourceName": "dbname", "type": "Text", "ocsfPath": "database.name", "asimField": "TargetAppName", "sensitive": false }, + { "sourceName": "remote_host", "type": "Text", "ocsfPath": "src_endpoint.ip", "asimField": "SrcIpAddr", "sensitive": true }, + { "sourceName": "error_severity", "type": "Text", "ocsfPath": "severity", "asimField": "EventSeverity", "sensitive": false }, + { "sourceName": "message", "type": "Text", "ocsfPath": "message", "asimField": "EventMessage", "sensitive": true }, + { "sourceName": "event_id", "type": "Text", "ocsfPath": "metadata.uid", "asimField": "EventOriginalUid", "sensitive": false }, + { "sourceName": "event_time", "type": "DateTime", "ocsfPath": "time", "asimField": "TimeGenerated", "sensitive": false }, + { "sourceName": "event_category", "type": "Text", "ocsfPath": "category_name", "asimField": "EventType", "sensitive": true }, + { "sourceName": "event_action", "type": "Text", "ocsfPath": "activity_name", "asimField": "EventSubType", "sensitive": true }, + { "sourceName": "event_result", "type": "Text", "ocsfPath": "status", "asimField": "EventResult", "sensitive": true }, + { "sourceName": "target_type", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "target_name", "type": "Text", "ocsfPath": "database.name", "asimField": "TargetAppName", "sensitive": false }, + { "sourceName": "source_ip", "type": "IpAddress", "ocsfPath": "src_endpoint.ip", "asimField": "SrcIpAddr", "sensitive": true }, + { "sourceName": "db_engine", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "statement_class", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": true }, + { "sourceName": "reason", "type": "Text", "ocsfPath": "status_detail", "asimField": "EventResultDetails", "sensitive": true }, + { "sourceName": "matched", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": true } + ], + "runtime": { + "applicationName": "postgresql-pgaudit", + "environment": "production", + "eventCategory": "data-access", + "eventType": "database_audit", + "eventAction": "db.ddl", + "eventResult": "success", + "transforms": [ + ".event_time = parse_timestamp(.timestamp, \"rfc3339\")", + ".event_id = concat(\"pgaudit-\", coalesce(.session_id, \"unknown\"), \"-\", coalesce(to_string(.session_line_num), \"0\"))", + ".m = regex_extract(.message, '^AUDIT: (?:SESSION|OBJECT),[0-9]+,[0-9]+,(?READ|WRITE|FUNCTION|ROLE|DDL|MISC|MISC_SET),(?[A-Z0-9_ ]+),')", + ".ipm = regex_extract(.remote_host, '^(?[0-9A-Fa-f.:]{2,45})$')", + ".source_ip = .ipm.ip", + ".target_type = \"database\"", + ".target_name = coalesce(.dbname, \"postgres\")", + ".db_engine = \"postgresql\"", + "if .m.class != null && .user != null { .matched = \"yes\"; .statement_class = .m.class; .event_action = coalesce(lookup(\"actions\", .m.class), \"db.privileged\"); .event_category = coalesce(lookup(\"categories\", .m.class), \"administrative-activity\"); .event_result = \"success\"; .reason = .m.command } else if contains(.message, \"password authentication failed\") && .user != null { .matched = \"yes\"; .statement_class = \"AUTH\"; .event_action = \"db.logon_failure\"; .event_category = \"authentication\"; .event_result = \"failure\"; .reason = \"PasswordAuthenticationFailed\" } else { .matched = \"ignored\" }", + "del(.m)", + "del(.ipm)" + ], + "tables": { + "actions": { + "DDL": "db.ddl", + "ROLE": "db.dcl", + "READ": "db.sensitive_read", + "WRITE": "db.sensitive_write", + "FUNCTION": "db.privileged", + "MISC": "db.privileged", + "MISC_SET": "db.audit_config" + }, + "categories": { + "DDL": "administrative-activity", + "ROLE": "administrative-activity", + "READ": "data-access", + "WRITE": "data-access", + "FUNCTION": "administrative-activity", + "MISC": "administrative-activity", + "MISC_SET": "administrative-activity" + } + }, + "match": { + "matched": "yes" + }, + "fields": { + "eventId": "event_id", + "timeGenerated": "event_time", + "eventCategory": "event_category", + "eventAction": "event_action", + "eventResult": "event_result", + "actor.username": "user", + "source.ipAddress": "source_ip", + "target.type": "target_type", + "target.name": "target_name", + "labels.dbEngine": "db_engine", + "labels.dbStatementClass": "statement_class", + "eventOutcomeReason": "reason" + } + } +} diff --git a/packs/owasp-asvs-app-logging/parsers/sqlserver-audit-33205.json b/packs/owasp-asvs-app-logging/parsers/sqlserver-audit-33205.json new file mode 100644 index 00000000..83acc83d --- /dev/null +++ b/packs/owasp-asvs-app-logging/parsers/sqlserver-audit-33205.json @@ -0,0 +1,111 @@ +{ + "version": "1.0", + "format": "Json", + "fields": [ + { "sourceName": "id", "type": "Text", "ocsfPath": "metadata.uid", "asimField": "EventOriginalUid", "sensitive": false }, + { "sourceName": "timeCreated", "type": "DateTime", "ocsfPath": "time", "asimField": "TimeGenerated", "sensitive": false }, + { "sourceName": "provider", "type": "Text", "ocsfPath": "metadata.product.name", "asimField": "EventProduct", "sensitive": false }, + { "sourceName": "channel", "type": "Text", "ocsfPath": "metadata.log_name", "asimField": "EventOriginalSubType", "sensitive": false }, + { "sourceName": "eventId", "type": "WholeNumber", "ocsfPath": "metadata.event_code", "asimField": "EventOriginalType", "sensitive": false }, + { "sourceName": "data.action_id", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "data.succeeded", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "data.server_principal_name", "type": "Text", "ocsfPath": "actor.user.name", "asimField": "TargetUsername", "sensitive": true }, + { "sourceName": "data.database_name", "type": "Text", "ocsfPath": "database.name", "asimField": "TargetAppName", "sensitive": false }, + { "sourceName": "data.object_name", "type": "Text", "ocsfPath": "target.name", "asimField": "TargetOriginalAppType", "sensitive": false }, + { "sourceName": "data.client_ip", "type": "Text", "ocsfPath": "src_endpoint.ip", "asimField": "SrcIpAddr", "sensitive": true }, + { "sourceName": "data.statement", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": true }, + { "sourceName": "event_category", "type": "Text", "ocsfPath": "category_name", "asimField": "EventType", "sensitive": true }, + { "sourceName": "event_action", "type": "Text", "ocsfPath": "activity_name", "asimField": "EventSubType", "sensitive": true }, + { "sourceName": "event_result", "type": "Text", "ocsfPath": "status", "asimField": "EventResult", "sensitive": true }, + { "sourceName": "actor_user", "type": "Text", "ocsfPath": "actor.user.name", "asimField": "TargetUsername", "sensitive": true }, + { "sourceName": "source_ip", "type": "IpAddress", "ocsfPath": "src_endpoint.ip", "asimField": "SrcIpAddr", "sensitive": true }, + { "sourceName": "target_type", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "target_name", "type": "Text", "ocsfPath": "database.name", "asimField": "TargetAppName", "sensitive": false }, + { "sourceName": "db_engine", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "statement_class", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": false }, + { "sourceName": "reason", "type": "Text", "ocsfPath": "status_detail", "asimField": "EventResultDetails", "sensitive": true }, + { "sourceName": "matched", "type": "Text", "ocsfPath": null, "asimField": null, "sensitive": true } + ], + "runtime": { + "applicationName": "sqlserver-audit", + "environment": "production", + "eventCategory": "administrative-activity", + "eventType": "database_audit", + "eventAction": "db.ddl", + "eventResult": "success", + "transforms": [ + ".code = trim(upper(coalesce(.\"data.action_id\", \"\")))", + ".ma = lookup(\"actions\", .code)", + ".actor_user = .\"data.server_principal_name\"", + ".ipm = regex_extract(.\"data.client_ip\", '^(?[0-9A-Fa-f.:]{2,45})$')", + ".source_ip = .ipm.ip", + ".target_type = \"database\"", + ".target_name = coalesce(.\"data.object_name\", .\"data.database_name\", \"master\")", + ".db_engine = \"sqlserver\"", + ".statement_class = .code", + ".ok = lower(coalesce(.\"data.succeeded\", \"true\"))", + ".matched = \"ignored\"", + "if (.channel == \"Security\" || .channel == \"Application\") && to_string(.eventId) == \"33205\" && starts_with(.provider, \"MSSQL\") && .ma != null && .actor_user != null { .matched = \"yes\"; .event_action = .ma; .event_category = lookup(\"categories\", .code); .event_result = \"success\"; .reason = .code }", + "if .matched == \"yes\" && .ok != \"true\" { .event_result = \"failure\"; .reason = concat(.code, \"_Failed\") }", + "del(.code)", + "del(.ma)", + "del(.ipm)", + "del(.ok)" + ], + "tables": { + "actions": { + "LGIS": "db.logon", + "LGIF": "db.logon_failure", + "LGO": "db.logoff", + "CR": "db.ddl", + "DR": "db.ddl", + "AL": "db.ddl", + "G": "db.dcl", + "R": "db.dcl", + "D": "db.dcl", + "APRL": "db.dcl", + "ADBO": "db.privileged", + "SL": "db.sensitive_read", + "IN": "db.sensitive_write", + "UP": "db.sensitive_write", + "DL": "db.sensitive_write", + "AUSC": "db.audit_config" + }, + "categories": { + "LGIS": "authentication", + "LGIF": "authentication", + "LGO": "authentication", + "CR": "administrative-activity", + "DR": "administrative-activity", + "AL": "administrative-activity", + "G": "administrative-activity", + "R": "administrative-activity", + "D": "administrative-activity", + "APRL": "administrative-activity", + "ADBO": "administrative-activity", + "SL": "data-access", + "IN": "data-access", + "UP": "data-access", + "DL": "data-access", + "AUSC": "administrative-activity" + } + }, + "match": { + "matched": "yes" + }, + "fields": { + "eventId": "id", + "timeGenerated": "timeCreated", + "eventCategory": "event_category", + "eventAction": "event_action", + "eventResult": "event_result", + "actor.username": "actor_user", + "source.ipAddress": "source_ip", + "target.type": "target_type", + "target.name": "target_name", + "labels.dbEngine": "db_engine", + "labels.dbStatementClass": "statement_class", + "eventOutcomeReason": "reason" + } + } +} diff --git a/src/Bower.Packs/PackRuntime.cs b/src/Bower.Packs/PackRuntime.cs index 2107d3af..f96d89a6 100644 --- a/src/Bower.Packs/PackRuntime.cs +++ b/src/Bower.Packs/PackRuntime.cs @@ -70,6 +70,16 @@ string Read(string name) return valid ? text : throw new InvalidDataException("pack-field-type-invalid"); } + string? ReadOptional(string name) + { + if (!root.TryGetProperty(name, out JsonElement value) || value.ValueKind == JsonValueKind.Null) + { + return null; + } + + return Read(name); + } + foreach ((string field, string expected) in mapping.Match) { if (!string.Equals(Read(field), expected, StringComparison.Ordinal)) @@ -79,6 +89,7 @@ string Read(string name) } string? Mapped(string target) => mapping.Fields.TryGetValue(target, out string? source) ? Read(source) : null; + string? MappedOptional(string target) => mapping.Fields.TryGetValue(target, out string? source) ? ReadOptional(source) : null; string id = Mapped("eventId")!; string timestamp = Mapped("timeGenerated")!; if (id.Length > 128 || !TryTimestamp(timestamp, out DateTimeOffset generated)) @@ -86,14 +97,46 @@ string Read(string name) throw new InvalidDataException("pack-identity-or-time-invalid"); } + string category = Mapped("eventCategory") ?? mapping.EventCategory; + string action = Mapped("eventAction") ?? mapping.EventAction; + string resultText = Mapped("eventResult") ?? mapping.EventResult; + if (category.Length > 128 || action.Length > 128 + || resultText is not ("success" or "failure" or "denied" or "unknown")) + { + throw new InvalidDataException("pack-field-invalid"); + } + string? username = Mapped("actor.username"); string? userId = Mapped("actor.userId"); - string? ip = Mapped("source.ipAddress"); + string? ip = MappedOptional("source.ipAddress"); if (ip is not null && !IsAddress(ip)) { throw new InvalidDataException("pack-source-invalid"); } + string? targetType = Mapped("target.type"); + string? targetId = MappedOptional("target.id"); + string? targetName = MappedOptional("target.name"); + if (targetType is null && (targetId is not null || targetName is not null)) + { + throw new InvalidDataException("pack-field-invalid"); + } + + Dictionary? labels = null; + foreach ((string target, string source) in mapping.Fields) + { + if (!target.StartsWith("labels.", StringComparison.Ordinal)) + { + continue; + } + + if (ReadOptional(source) is { } labelValue) + { + labels ??= new Dictionary(StringComparer.Ordinal); + labels[target[7..]] = labelValue; + } + } + string? correlation = Mapped("request.correlationId"); return new SecurityEventEnvelope { @@ -101,15 +144,17 @@ string Read(string name) EventId = id, EventOriginalId = id, TimeGenerated = generated, - EventCategory = mapping.EventCategory, + EventCategory = category, EventType = mapping.EventType, - EventAction = mapping.EventAction, - EventResult = Enum.Parse(mapping.EventResult, ignoreCase: true), - EventOutcomeReason = Mapped("eventOutcomeReason"), + EventAction = action, + EventResult = Enum.Parse(resultText, ignoreCase: true), + EventOutcomeReason = MappedOptional("eventOutcomeReason"), Application = new ApplicationContext { Name = mapping.ApplicationName, Environment = mapping.Environment }, Actor = username is null && userId is null ? null : new ActorContext { Username = username, UserId = userId }, + Target = targetType is null ? null : new TargetContext { Type = targetType, Id = targetId, Name = targetName }, Source = ip is null ? null : new SourceContext { IpAddress = ip }, - Request = correlation is null ? null : new RequestContext { CorrelationId = correlation } + Request = correlation is null ? null : new RequestContext { CorrelationId = correlation }, + Labels = labels }; } diff --git a/src/Bower.Pipeline/CustomLogParser.cs b/src/Bower.Pipeline/CustomLogParser.cs index 53324387..29c9d291 100644 --- a/src/Bower.Pipeline/CustomLogParser.cs +++ b/src/Bower.Pipeline/CustomLogParser.cs @@ -428,21 +428,35 @@ when configuration.KeyValueSeparator is not ("=" or ":"): { string[] metadata = [runtime.ApplicationName, runtime.Environment, runtime.EventCategory, runtime.EventType, runtime.EventAction]; - string[] targets = ["eventId", "timeGenerated", "actor.username", "actor.userId", + string[] targets = ["eventId", "timeGenerated", "eventCategory", "eventAction", "eventResult", + "actor.username", "actor.userId", "target.type", "target.id", "target.name", "source.ipAddress", "request.correlationId", "eventOutcomeReason"]; + static bool IsValidRuntimeTarget(string target, string[] allowedTargets) => + allowedTargets.Contains(target, StringComparer.Ordinal) + || (target.StartsWith("labels.", StringComparison.Ordinal) + && target.Length is > 7 and <= 71 + && IsValidLabelKey(target[7..])); + if (configuration.Format != CustomLogFormat.Json || metadata.Any(value => string.IsNullOrWhiteSpace(value) || value.Length > 128) || runtime.EventResult is not ("success" or "failure" or "denied" or "unknown") || runtime.Match is null || runtime.Match.Count is < 1 or > 16 - || runtime.Fields is null || runtime.Fields.Count is < 2 or > 7 + || runtime.Fields is null || runtime.Fields.Count is < 2 or > 16 || !runtime.Fields.ContainsKey("eventId") || !runtime.Fields.ContainsKey("timeGenerated") - || runtime.Fields.Keys.Any(target => !targets.Contains(target, StringComparer.Ordinal)) + || runtime.Fields.Keys.Any(target => !IsValidRuntimeTarget(target, targets)) + || runtime.Fields.Keys.Count(target => target.StartsWith("labels.", StringComparison.Ordinal)) > 8 || runtime.Fields.Values.Any(source => !names.Contains(source)) || runtime.Match.Any(pair => !names.Contains(pair.Key) || string.IsNullOrEmpty(pair.Value) || pair.Value.Length > 2048)) { issues.Add("Invalid runtime semantic mapping; only bounded, filtered JSON mappings are supported."); } + static bool IsValidLabelKey(string key) => + !string.IsNullOrWhiteSpace(key) + && char.IsAsciiLetter(key[0]) + && key.All(ch => char.IsAsciiLetterOrDigit(ch) || ch is '_' or '.' or '-') + && !IsProhibited(key); + if (runtime.ToTransformDefinition(configuration.Fields) is { } transforms) { issues.AddRange(TransformProgram.Validate(transforms).Select(issue => issue.ToString())); diff --git a/src/Bower.Sdk/AsvsSemanticEvents.cs b/src/Bower.Sdk/AsvsSemanticEvents.cs new file mode 100644 index 00000000..77ff80b8 --- /dev/null +++ b/src/Bower.Sdk/AsvsSemanticEvents.cs @@ -0,0 +1,253 @@ +using System.Net; +using Bower.Contracts; + +namespace Bower.Sdk; + +public enum AuthenticationSuccessKind +{ + Login, + Reauthenticate, + TokenIssued +} + +public sealed record AuthenticationSucceededEvent +{ + public string? UserId { get; init; } + public string? Username { get; init; } + public AuthenticationSuccessKind Kind { get; init; } = AuthenticationSuccessKind.Login; + public string? AuthMethod { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public string? UserAgent { get; init; } + public string? TraceId { get; init; } + public required string CorrelationId { get; init; } +} + +public enum MfaOutcome +{ + Challenge, + Success, + Failure +} + +public sealed record MfaSecurityEvent +{ + public string? UserId { get; init; } + public string? Username { get; init; } + public required MfaOutcome Outcome { get; init; } + public required string Factor { get; init; } + public string? Reason { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public string? UserAgent { get; init; } + public string? TraceId { get; init; } + public required string CorrelationId { get; init; } +} + +public enum FactorLifecycleAction +{ + MfaEnrolled, + MfaRemoved, + MfaRevoked, + PasswordResetRequested, + PasswordResetCompleted, + PasswordChanged +} + +public sealed record AuthenticationFactorLifecycleEvent +{ + public string? ActorUserId { get; init; } + public string? ActorUsername { get; init; } + public required string TargetUserId { get; init; } + public required FactorLifecycleAction Action { get; init; } + public EventResult Result { get; init; } = EventResult.Success; + public string? Factor { get; init; } + public string? InitiatedBy { get; init; } + public string? Reason { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public string? UserAgent { get; init; } + public required string CorrelationId { get; init; } +} + +public enum AccountStatusAction +{ + Create, + Disable, + Enable, + Delete, + Unlock +} + +public sealed record AccountStatusChangedEvent +{ + public required string ActorUserId { get; init; } + public string? ActorRole { get; init; } + public required string TargetUserId { get; init; } + public required AccountStatusAction Action { get; init; } + public EventResult Result { get; init; } = EventResult.Success; + public string? Reason { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public required string CorrelationId { get; init; } +} + +public enum SessionLifecycleAction +{ + Logout, + Timeout, + AdminTerminate, + RevokeOthers, + RevokeAll, + Rotate +} + +public sealed record SessionLifecycleEvent +{ + public string? ActorUserId { get; init; } + public string? ActorUsername { get; init; } + public string? TargetId { get; init; } + public required SessionLifecycleAction Action { get; init; } + public EventResult Result { get; init; } = EventResult.Success; + public string? SessionId { get; init; } + public long? SessionsTerminated { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public string? UserAgent { get; init; } + public required string CorrelationId { get; init; } +} + +public enum AuthorisationFailureKind +{ + FunctionLevel, + ObjectLevel, + FieldLevel, + StaleGrant +} + +public sealed record AuthorisationFailedEvent +{ + public string? ActorUserId { get; init; } + public string? ActorUsername { get; init; } + public string? ActorRole { get; init; } + public required AuthorisationFailureKind Kind { get; init; } + public required string TargetType { get; init; } + public string? TargetId { get; init; } + public EventResult Result { get; init; } = EventResult.Denied; + public string? Route { get; init; } + public string? HttpMethod { get; init; } + public string? RequiredPermission { get; init; } + public string? Reason { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public required string CorrelationId { get; init; } +} + +public enum SensitiveDataOperation +{ + Read, + Create, + Update, + Delete +} + +public sealed record SensitiveDataAccessEvent +{ + public required string ActorUserId { get; init; } + public required SensitiveDataOperation Operation { get; init; } + public required string TargetType { get; init; } + public required string TargetId { get; init; } + public required string DataClassification { get; init; } + public EventResult Result { get; init; } = EventResult.Success; + public long? RecordCount { get; init; } + public string? Route { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public required string CorrelationId { get; init; } +} + +public enum AdministrativeEventKind +{ + AdminAction, + ConfigurationChanged, + PermissionChanged +} + +public sealed record AdministrativeSecurityEvent +{ + public required string ActorUserId { get; init; } + public string? ActorRole { get; init; } + public required AdministrativeEventKind Kind { get; init; } + public required string Action { get; init; } + public required string TargetType { get; init; } + public string? TargetId { get; init; } + public string? ChangedField { get; init; } + public EventResult Result { get; init; } = EventResult.Success; + public string? Reason { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public string? UserAgent { get; init; } + public required string CorrelationId { get; init; } +} + +public enum ControlBypassKind +{ + InputValidationFailure, + BusinessLogicViolation, + AntiAutomationTriggered +} + +public sealed record ControlBypassEvent +{ + public required ControlBypassKind Kind { get; init; } + public required string Action { get; init; } + public EventResult Result { get; init; } = EventResult.Denied; + public string? ActorUserId { get; init; } + public string? ActorUsername { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public string? Route { get; init; } + public string? HttpMethod { get; init; } + public string? UserAgent { get; init; } + public string? Reason { get; init; } + public required string CorrelationId { get; init; } +} + +public enum SecurityErrorKind +{ + ApplicationError, + SecurityControlFailure +} + +public sealed record SecurityErrorEvent +{ + public required SecurityErrorKind Kind { get; init; } + public required string Action { get; init; } + public required string Reason { get; init; } + public string? ErrorType { get; init; } + public string? Route { get; init; } + public int? StatusCode { get; init; } + public EventSeverity Severity { get; init; } = EventSeverity.High; + public string? TraceId { get; init; } + public required string CorrelationId { get; init; } +} + +public enum DatabaseAuditAction +{ + Logon, + Logoff, + LogonFailure, + Ddl, + Dcl, + Privileged, + SensitiveRead, + SensitiveWrite, + QueryError, + AuditConfig +} + +public sealed record DatabaseAuditEvent +{ + public required string DbEngine { get; init; } + public required DatabaseAuditAction Action { get; init; } + public EventResult Result { get; init; } = EventResult.Success; + public string? ActorUsername { get; init; } + public string? ActorUserId { get; init; } + public string TargetType { get; init; } = "database"; + public string? TargetName { get; init; } + public string? StatementClass { get; init; } + public string? Reason { get; init; } + public IPAddress? SourceIpAddress { get; init; } + public string? CorrelationId { get; init; } +} diff --git a/src/Bower.Sdk/BufferedBowerClient.Asvs.cs b/src/Bower.Sdk/BufferedBowerClient.Asvs.cs new file mode 100644 index 00000000..a16a817a --- /dev/null +++ b/src/Bower.Sdk/BufferedBowerClient.Asvs.cs @@ -0,0 +1,537 @@ +using System.Text.Json; +using Bower.Contracts; + +namespace Bower.Sdk; + +internal sealed partial class BufferedBowerClient +{ + public ValueTask AuthenticationSucceededAsync( + AuthenticationSucceededEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + RequireAtLeastOne(securityEvent.UserId, securityEvent.Username, nameof(securityEvent), "UserId or Username is required."); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + + string action = securityEvent.Kind switch + { + AuthenticationSuccessKind.Login => "authentication.login", + AuthenticationSuccessKind.Reauthenticate => "authentication.reauthenticate", + AuthenticationSuccessKind.TokenIssued => "authentication.token_issued", + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + Dictionary? labels = BuildLabels( + ("authMethod", securityEvent.AuthMethod), + ("userAgent", securityEvent.UserAgent)); + + SecurityEventEnvelope envelope = CreateEnvelope( + SecurityEventCategories.Authentication, + "authentication_success", + action, + EventResult.Success, + null, + new ActorContext { UserId = securityEvent.UserId, Username = securityEvent.Username, Type = ActorType.Human }, + null, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Request = new RequestContext { CorrelationId = securityEvent.CorrelationId, TraceId = securityEvent.TraceId }, + Labels = labels + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask MfaEventAsync( + MfaSecurityEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + RequireAtLeastOne(securityEvent.UserId, securityEvent.Username, nameof(securityEvent), "UserId or Username is required."); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.Factor); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + + (string eventType, string action, EventResult result) = securityEvent.Outcome switch + { + MfaOutcome.Challenge => ("mfa_challenge", "mfa.challenge", EventResult.Success), + MfaOutcome.Success => ("mfa_success", "mfa.verify", EventResult.Success), + MfaOutcome.Failure => ("mfa_failure", "mfa.verify", EventResult.Failure), + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + Dictionary? labels = BuildLabels( + ("mfaFactor", securityEvent.Factor), + ("userAgent", securityEvent.UserAgent)); + + SecurityEventEnvelope envelope = CreateEnvelope( + SecurityEventCategories.Authentication, + eventType, + action, + result, + securityEvent.Reason, + new ActorContext { UserId = securityEvent.UserId, Username = securityEvent.Username, Type = ActorType.Human }, + null, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Request = new RequestContext { CorrelationId = securityEvent.CorrelationId, TraceId = securityEvent.TraceId }, + Labels = labels + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask AuthenticationFactorLifecycleAsync( + AuthenticationFactorLifecycleEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + RequireAtLeastOne(securityEvent.ActorUserId, securityEvent.ActorUsername, nameof(securityEvent), "ActorUserId or ActorUsername is required."); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.TargetUserId); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + + (string eventType, string action) = securityEvent.Action switch + { + FactorLifecycleAction.MfaEnrolled => ("mfa_factor_enrolled", "mfa.enrol"), + FactorLifecycleAction.MfaRemoved => ("mfa_factor_removed", "mfa.remove"), + FactorLifecycleAction.MfaRevoked => ("mfa_factor_removed", "mfa.revoke"), + FactorLifecycleAction.PasswordResetRequested => ("password_reset_requested", "password.reset_request"), + FactorLifecycleAction.PasswordResetCompleted => ("password_reset_completed", "password.reset_complete"), + FactorLifecycleAction.PasswordChanged => ("password_changed", "password.change"), + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + Dictionary? labels = BuildLabels( + ("mfaFactor", securityEvent.Factor), + ("initiatedBy", securityEvent.InitiatedBy), + ("userAgent", securityEvent.UserAgent)); + + SecurityEventEnvelope envelope = CreateEnvelope( + SecurityEventCategories.IdentityManagement, + eventType, + action, + securityEvent.Result, + securityEvent.Reason, + new ActorContext { UserId = securityEvent.ActorUserId, Username = securityEvent.ActorUsername, Type = ActorType.Human }, + new TargetContext { Type = "user", Id = securityEvent.TargetUserId }, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Labels = labels + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask AccountStatusChangedAsync( + AccountStatusChangedEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.ActorUserId); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.TargetUserId); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + + string action = securityEvent.Action switch + { + AccountStatusAction.Create => "account.create", + AccountStatusAction.Disable => "account.disable", + AccountStatusAction.Enable => "account.enable", + AccountStatusAction.Delete => "account.delete", + AccountStatusAction.Unlock => "account.unlock", + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + SecurityEventEnvelope envelope = CreateEnvelope( + SecurityEventCategories.IdentityManagement, + "account_status_changed", + action, + securityEvent.Result, + securityEvent.Reason, + new ActorContext { UserId = securityEvent.ActorUserId, Role = securityEvent.ActorRole, Type = ActorType.Human }, + new TargetContext { Type = "user", Id = securityEvent.TargetUserId }, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null); + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask SessionLifecycleAsync( + SessionLifecycleEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + if (string.IsNullOrWhiteSpace(securityEvent.ActorUserId) + && string.IsNullOrWhiteSpace(securityEvent.ActorUsername) + && string.IsNullOrWhiteSpace(securityEvent.TargetId)) + { + throw new ArgumentException("At least one of ActorUserId, ActorUsername, or TargetId is required.", nameof(securityEvent)); + } + + if (securityEvent.SessionsTerminated is < 0) + { + throw new ArgumentOutOfRangeException(nameof(securityEvent), "SessionsTerminated cannot be negative."); + } + + (string eventType, string action) = securityEvent.Action switch + { + SessionLifecycleAction.Logout => ("session_terminated", "session.logout"), + SessionLifecycleAction.Timeout => ("session_terminated", "session.timeout"), + SessionLifecycleAction.AdminTerminate => ("session_terminated", "session.admin_terminate"), + SessionLifecycleAction.RevokeOthers => ("session_terminated", "session.revoke_others"), + SessionLifecycleAction.RevokeAll => ("session_terminated", "session.revoke_all"), + SessionLifecycleAction.Rotate => ("session_rotated", "session.rotate"), + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + Dictionary? attributes = securityEvent.SessionsTerminated is { } count + ? new Dictionary + { + ["sessionsTerminated"] = JsonSerializer.SerializeToElement(count, SdkJsonContext.Default.Int64) + } + : null; + + SecurityEventEnvelope envelope = CreateEnvelope( + SecurityEventCategories.Authentication, + eventType, + action, + securityEvent.Result, + null, + securityEvent.ActorUserId is null && securityEvent.ActorUsername is null + ? null + : new ActorContext { UserId = securityEvent.ActorUserId, Username = securityEvent.ActorUsername, Type = ActorType.Human }, + securityEvent.TargetId is null ? null : new TargetContext { Type = "session", Id = securityEvent.TargetId }, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Request = new RequestContext + { + CorrelationId = securityEvent.CorrelationId, + SessionId = securityEvent.SessionId + }, + Labels = BuildLabels(("userAgent", securityEvent.UserAgent)), + Attributes = attributes + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask AuthorisationFailedAsync( + AuthorisationFailedEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.TargetType); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + if (securityEvent.Result is not (EventResult.Denied or EventResult.Failure)) + { + throw new ArgumentOutOfRangeException(nameof(securityEvent), "AuthorisationFailedEvent Result must be Denied or Failure."); + } + + if (string.IsNullOrWhiteSpace(securityEvent.ActorUserId) + && string.IsNullOrWhiteSpace(securityEvent.ActorUsername) + && securityEvent.SourceIpAddress is null) + { + throw new ArgumentException("At least one of ActorUserId, ActorUsername, or SourceIpAddress is required.", nameof(securityEvent)); + } + + string action = securityEvent.Kind switch + { + AuthorisationFailureKind.FunctionLevel => "authz.function", + AuthorisationFailureKind.ObjectLevel => "authz.object", + AuthorisationFailureKind.FieldLevel => "authz.field", + AuthorisationFailureKind.StaleGrant => "authz.stale_grant", + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + SecurityEventEnvelope envelope = CreateEnvelope( + "authorisation", + "authorisation_failure", + action, + securityEvent.Result, + securityEvent.Reason, + securityEvent.ActorUserId is null && securityEvent.ActorUsername is null + ? null + : new ActorContext + { + UserId = securityEvent.ActorUserId, + Username = securityEvent.ActorUsername, + Role = securityEvent.ActorRole, + Type = ActorType.Human + }, + new TargetContext { Type = securityEvent.TargetType, Id = securityEvent.TargetId }, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Request = new RequestContext + { + CorrelationId = securityEvent.CorrelationId, + Method = securityEvent.HttpMethod + }, + Labels = BuildLabels( + ("route", securityEvent.Route), + ("requiredPermission", securityEvent.RequiredPermission)) + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask SensitiveDataAccessedAsync( + SensitiveDataAccessEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.ActorUserId); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.TargetType); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.TargetId); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.DataClassification); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + if (securityEvent.RecordCount is < 0) + { + throw new ArgumentOutOfRangeException(nameof(securityEvent), "RecordCount cannot be negative."); + } + + (string eventType, string action) = securityEvent.Operation switch + { + SensitiveDataOperation.Read => ("sensitive_data_accessed", "data.read"), + SensitiveDataOperation.Create => ("sensitive_record_changed", "data.create"), + SensitiveDataOperation.Update => ("sensitive_record_changed", "data.update"), + SensitiveDataOperation.Delete => ("sensitive_record_changed", "data.delete"), + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + Dictionary? attributes = securityEvent.RecordCount is { } count + ? new Dictionary + { + ["recordCount"] = JsonSerializer.SerializeToElement(count, SdkJsonContext.Default.Int64) + } + : null; + + SecurityEventEnvelope envelope = CreateEnvelope( + SecurityEventCategories.DataAccess, + eventType, + action, + securityEvent.Result, + null, + new ActorContext { UserId = securityEvent.ActorUserId, Type = ActorType.Human }, + new TargetContext { Type = securityEvent.TargetType, Id = securityEvent.TargetId }, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Labels = BuildLabels( + ("dataClassification", securityEvent.DataClassification), + ("route", securityEvent.Route)), + Attributes = attributes + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask AdministrativeActionAsync( + AdministrativeSecurityEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.ActorUserId); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.Action); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.TargetType); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + + string eventType = securityEvent.Kind switch + { + AdministrativeEventKind.AdminAction => "admin_action", + AdministrativeEventKind.ConfigurationChanged => "configuration_changed", + AdministrativeEventKind.PermissionChanged => "permission_changed", + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + SecurityEventEnvelope envelope = CreateEnvelope( + SecurityEventCategories.AdministrativeActivity, + eventType, + securityEvent.Action, + securityEvent.Result, + securityEvent.Reason, + new ActorContext { UserId = securityEvent.ActorUserId, Role = securityEvent.ActorRole, Type = ActorType.Human }, + new TargetContext { Type = securityEvent.TargetType, Id = securityEvent.TargetId }, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Change = string.IsNullOrWhiteSpace(securityEvent.ChangedField) + ? null + : new ChangeContext { Field = securityEvent.ChangedField }, + Labels = BuildLabels(("userAgent", securityEvent.UserAgent)) + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask ControlBypassAttemptedAsync( + ControlBypassEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.Action); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + if (securityEvent.Result is not (EventResult.Denied or EventResult.Failure)) + { + throw new ArgumentOutOfRangeException(nameof(securityEvent), "ControlBypassEvent Result must be Denied or Failure."); + } + + if (securityEvent.SourceIpAddress is null + && string.IsNullOrWhiteSpace(securityEvent.ActorUserId) + && string.IsNullOrWhiteSpace(securityEvent.ActorUsername)) + { + throw new ArgumentException("At least one of SourceIpAddress, ActorUserId, or ActorUsername is required.", nameof(securityEvent)); + } + + string eventType = securityEvent.Kind switch + { + ControlBypassKind.InputValidationFailure => "input_validation_failure", + ControlBypassKind.BusinessLogicViolation => "business_logic_violation", + ControlBypassKind.AntiAutomationTriggered => "anti_automation_triggered", + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + SecurityEventEnvelope envelope = CreateEnvelope( + "application-security", + eventType, + securityEvent.Action, + securityEvent.Result, + securityEvent.Reason, + securityEvent.ActorUserId is null && securityEvent.ActorUsername is null + ? null + : new ActorContext { UserId = securityEvent.ActorUserId, Username = securityEvent.ActorUsername, Type = ActorType.Human }, + null, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId, + null) with + { + Request = new RequestContext + { + CorrelationId = securityEvent.CorrelationId, + Method = securityEvent.HttpMethod + }, + Labels = BuildLabels( + ("route", securityEvent.Route), + ("userAgent", securityEvent.UserAgent)) + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask SecurityErrorAsync( + SecurityErrorEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.Action); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.Reason); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.CorrelationId); + + string eventType = securityEvent.Kind switch + { + SecurityErrorKind.ApplicationError => "application_error", + SecurityErrorKind.SecurityControlFailure => "security_control_failure", + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + SecurityEventEnvelope envelope = CreateEnvelope( + "application-security", + eventType, + securityEvent.Action, + EventResult.Failure, + securityEvent.Reason, + null, + null, + null, + securityEvent.CorrelationId, + null) with + { + EventSeverity = securityEvent.Severity, + Request = new RequestContext + { + CorrelationId = securityEvent.CorrelationId, + TraceId = securityEvent.TraceId, + StatusCode = securityEvent.StatusCode + }, + Labels = BuildLabels( + ("route", securityEvent.Route), + ("errorType", securityEvent.ErrorType)) + }; + return EnqueueAsync(envelope, cancellationToken); + } + + public ValueTask DatabaseAuditAsync( + DatabaseAuditEvent securityEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.DbEngine); + ArgumentException.ThrowIfNullOrWhiteSpace(securityEvent.TargetType); + RequireAtLeastOne(securityEvent.ActorUsername, securityEvent.ActorUserId, nameof(securityEvent), "ActorUsername or ActorUserId is required."); + + (string category, string action) = securityEvent.Action switch + { + DatabaseAuditAction.Logon => (SecurityEventCategories.Authentication, "db.logon"), + DatabaseAuditAction.Logoff => (SecurityEventCategories.Authentication, "db.logoff"), + DatabaseAuditAction.LogonFailure => (SecurityEventCategories.Authentication, "db.logon_failure"), + DatabaseAuditAction.Ddl => (SecurityEventCategories.AdministrativeActivity, "db.ddl"), + DatabaseAuditAction.Dcl => (SecurityEventCategories.AdministrativeActivity, "db.dcl"), + DatabaseAuditAction.Privileged => (SecurityEventCategories.AdministrativeActivity, "db.privileged"), + DatabaseAuditAction.AuditConfig => (SecurityEventCategories.AdministrativeActivity, "db.audit_config"), + DatabaseAuditAction.SensitiveRead => (SecurityEventCategories.DataAccess, "db.sensitive_read"), + DatabaseAuditAction.SensitiveWrite => (SecurityEventCategories.DataAccess, "db.sensitive_write"), + DatabaseAuditAction.QueryError => (SecurityEventCategories.DataAccess, "db.query_error"), + _ => throw new ArgumentOutOfRangeException(nameof(securityEvent)) + }; + + SecurityEventEnvelope envelope = CreateEnvelope( + category, + "database_audit", + action, + securityEvent.Result, + securityEvent.Reason, + new ActorContext + { + Username = securityEvent.ActorUsername, + UserId = securityEvent.ActorUserId, + Type = ActorType.Human + }, + new TargetContext { Type = securityEvent.TargetType, Name = securityEvent.TargetName }, + securityEvent.SourceIpAddress is null ? null : new SourceContext { IpAddress = securityEvent.SourceIpAddress.ToString() }, + securityEvent.CorrelationId ?? Guid.CreateVersion7().ToString(), + null) with + { + Labels = BuildLabels( + ("dbEngine", securityEvent.DbEngine), + ("dbStatementClass", securityEvent.StatementClass)) + }; + return EnqueueAsync(envelope, cancellationToken); + } + + private static void RequireAtLeastOne(string? first, string? second, string paramName, string message) + { + if (string.IsNullOrWhiteSpace(first) && string.IsNullOrWhiteSpace(second)) + { + throw new ArgumentException(message, paramName); + } + } + + private static Dictionary? BuildLabels(params (string Key, string? Value)[] pairs) + { + Dictionary? labels = null; + foreach ((string key, string? value) in pairs) + { + if (string.IsNullOrWhiteSpace(value)) + { + continue; + } + + labels ??= new Dictionary(StringComparer.Ordinal); + labels[key] = value; + } + + return labels; + } +} diff --git a/src/Bower.Sdk/BufferedBowerClient.cs b/src/Bower.Sdk/BufferedBowerClient.cs index 4fc37bdc..3c283e0c 100644 --- a/src/Bower.Sdk/BufferedBowerClient.cs +++ b/src/Bower.Sdk/BufferedBowerClient.cs @@ -3,7 +3,7 @@ namespace Bower.Sdk; -internal sealed class BufferedBowerClient : IBowerTelemetry, IBowerTelemetryDiagnostics, IAsyncDisposable +internal sealed partial class BufferedBowerClient : IBowerTelemetry, IAsvsTelemetry, IBowerTelemetryDiagnostics, IAsyncDisposable { private readonly BowerOptions options; private readonly Channel channel; diff --git a/src/Bower.Sdk/IAsvsTelemetry.cs b/src/Bower.Sdk/IAsvsTelemetry.cs new file mode 100644 index 00000000..457d56cd --- /dev/null +++ b/src/Bower.Sdk/IAsvsTelemetry.cs @@ -0,0 +1,53 @@ +namespace Bower.Sdk; + +/// +/// Strongly typed OWASP ASVS 5.0 application security telemetry API matching +/// packs/owasp-asvs-app-logging. Composes with +/// without altering existing contracts. +/// +public interface IAsvsTelemetry +{ + ValueTask AuthenticationSucceededAsync( + AuthenticationSucceededEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask MfaEventAsync( + MfaSecurityEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask AuthenticationFactorLifecycleAsync( + AuthenticationFactorLifecycleEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask AccountStatusChangedAsync( + AccountStatusChangedEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask SessionLifecycleAsync( + SessionLifecycleEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask AuthorisationFailedAsync( + AuthorisationFailedEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask SensitiveDataAccessedAsync( + SensitiveDataAccessEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask AdministrativeActionAsync( + AdministrativeSecurityEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask ControlBypassAttemptedAsync( + ControlBypassEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask SecurityErrorAsync( + SecurityErrorEvent securityEvent, + CancellationToken cancellationToken = default); + + ValueTask DatabaseAuditAsync( + DatabaseAuditEvent securityEvent, + CancellationToken cancellationToken = default); +} diff --git a/src/Bower.Sdk/ServiceCollectionExtensions.cs b/src/Bower.Sdk/ServiceCollectionExtensions.cs index a40f7aab..70635e10 100644 --- a/src/Bower.Sdk/ServiceCollectionExtensions.cs +++ b/src/Bower.Sdk/ServiceCollectionExtensions.cs @@ -17,6 +17,7 @@ public static IServiceCollection AddBower( services.AddSingleton(options); services.AddSingleton(); services.AddSingleton(provider => provider.GetRequiredService()); + services.AddSingleton(provider => provider.GetRequiredService()); services.AddSingleton(provider => provider.GetRequiredService()); return services; } diff --git a/tests/Bower.UnitTests/AsvsSdkAndDbParsersTests.cs b/tests/Bower.UnitTests/AsvsSdkAndDbParsersTests.cs new file mode 100644 index 00000000..6c2a1f18 --- /dev/null +++ b/tests/Bower.UnitTests/AsvsSdkAndDbParsersTests.cs @@ -0,0 +1,266 @@ +using System.Net; +using System.Text.Json; +using Bower.Abstractions; +using Bower.Contracts; +using Bower.Integrity; +using Bower.Packs; +using Bower.PolicyEngine; +using Bower.Redaction.Privacy; +using Bower.Sdk; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; + +namespace Bower.UnitTests; + +public sealed class AsvsSdkAndDbParsersTests +{ + private const string PackId = "owasp-asvs-app-logging"; + private static readonly DateTimeOffset EvaluationTime = new(2026, 11, 22, 0, 0, 0, TimeSpan.Zero); + + [Fact] + public void SignedDbAuditParsers_MapAllowedEvents_DropSqlStatements_AndPassAsvsPolicy() + { + LoadedPack pack = BuildAsvsPack(); + Assert.Equal(4, pack.Parsers.Count); + + PrivacyEngine privacy = new(PrivacyProfileLoader.Load(pack.PrivacyProfileYaml!, new byte[32], "k1").Policy); + DeterministicPolicyEvaluator evaluator = new(pack.Policies); + + (string AppName, string Raw, string ExpectedEngine, string ExpectedAction, string ExpectedCategory)[] cases = + [ + ( + "postgresql-pgaudit", + """{"timestamp":"2026-11-22T00:00:00Z","session_id":"673f1a.12","session_line_num":4,"user":"db_admin","dbname":"billing","remote_host":"192.0.2.21","error_severity":"LOG","message":"AUDIT: SESSION,1,1,ROLE,GRANT,,,GRANT super_role TO alice; SELECT 'secret-token-xyz'"}""", + "postgresql", + "db.dcl", + "administrative-activity" + ), + ( + "mysql-audit", + """{"timestamp":"2026-11-22T00:00:00Z","id":"991","class":"connection","event":"connect","user":"app_svc","ip":"192.0.2.22","db":"orders","status":1045,"statement":"SELECT secret_col FROM customers"}""", + "mysql", + "db.logon_failure", + "authentication" + ), + ( + "mongodb-audit", + """{"atype":"grantRolesToUser","ts":{"$date":"2026-11-22T00:00:00Z"},"uuid":"m-100","remote":{"ip":"192.0.2.23"},"users":[{"user":"ops_admin","db":"admin"}],"param":{"db":"ledger","user":"bob"},"result":0}""", + "mongodb", + "db.dcl", + "administrative-activity" + ), + ( + "sqlserver-audit", + """{"id":"win-33205-1","timeCreated":"2026-11-22T00:00:00Z","provider":"MSSQLSERVER$AUDIT","channel":"Security","eventId":33205,"data.action_id":"AL ","data.succeeded":"true","data.server_principal_name":"CONTOSO\\sa_ops","data.database_name":"finance","data.object_name":"dbo.accounts","data.client_ip":"192.0.2.24","data.statement":"ALTER TABLE dbo.accounts ADD secret_note nvarchar(50)"}""", + "sqlserver", + "db.ddl", + "administrative-activity" + ) + ]; + + foreach ((string appName, string raw, string expectedEngine, string expectedAction, string expectedCategory) in cases) + { + var parser = Assert.Single(pack.Parsers, p => p.Runtime?.ApplicationName == appName); + SecurityEventEnvelope? parsed = PackRuntime.Parse(parser, raw, EvaluationTime); + Assert.NotNull(parsed); + Assert.Equal("database_audit", parsed.EventType); + Assert.Equal(expectedAction, parsed.EventAction); + Assert.Equal(expectedCategory, parsed.EventCategory); + Assert.Equal(expectedEngine, parsed.Labels!["dbEngine"]); + + string json = JsonSerializer.Serialize(parsed, BowerJson.Envelope); + Assert.DoesNotContain("secret-token-xyz", json, StringComparison.Ordinal); + Assert.DoesNotContain("secret_col", json, StringComparison.Ordinal); + Assert.DoesNotContain("secret_note", json, StringComparison.Ordinal); + + PrivacyScanResult redacted = privacy.RedactJson(json); + Assert.True(redacted.Succeeded); + Assert.DoesNotContain("db_admin", redacted.RedactedJson!, StringComparison.Ordinal); + Assert.DoesNotContain("app_svc", redacted.RedactedJson!, StringComparison.Ordinal); + Assert.DoesNotContain("ops_admin", redacted.RedactedJson!, StringComparison.Ordinal); + Assert.DoesNotContain("sa_ops", redacted.RedactedJson!, StringComparison.Ordinal); + + SecurityEventEnvelope envelope = JsonSerializer.Deserialize(redacted.RedactedJson!, BowerJson.Envelope)!; + PolicyDecision decision = evaluator.Evaluate(envelope); + Assert.Equal(DecisionAction.Accept, decision.Action); + Assert.Equal("BWR-PACK-ASVS-DB-AUDIT", decision.PolicyId); + } + + // Unapproved / non-audit records return null (default deny). + Assert.Null(PackRuntime.Parse( + Assert.Single(pack.Parsers, p => p.Runtime?.ApplicationName == "postgresql-pgaudit"), + """{"timestamp":"2026-11-22T00:00:00Z","session_id":"s1","session_line_num":1,"user":"app","message":"checkpoint complete"}""", + EvaluationTime)); + Assert.Null(PackRuntime.Parse( + Assert.Single(pack.Parsers, p => p.Runtime?.ApplicationName == "sqlserver-audit"), + """{"id":"win-4625-1","timeCreated":"2026-11-22T00:00:00Z","provider":"Microsoft-Windows-Security-Auditing","channel":"Security","eventId":4625,"data.action_id":"AL","data.server_principal_name":"u"}""", + EvaluationTime)); + } + + [Fact] + public async Task AsvsSdk_EmitsAllElevenEventFamilies_PassingAsvsPackPoliciesAndPrivacy() + { + CancellationToken ct = TestContext.Current.CancellationToken; + LoadedPack pack = BuildAsvsPack(); + PrivacyEngine privacy = new(PrivacyProfileLoader.Load(pack.PrivacyProfileYaml!, new byte[32], "k1").Policy); + DeterministicPolicyEvaluator evaluator = new(pack.Policies); + + List received = []; + WebApplicationBuilder sinkBuilder = WebApplication.CreateSlimBuilder(); + sinkBuilder.WebHost.UseUrls("http://127.0.0.1:0"); + await using WebApplication sink = sinkBuilder.Build(); + sink.MapPost("/v1/events", async (HttpContext ctx) => + { + using StreamReader reader = new(ctx.Request.Body); + string body = await reader.ReadToEndAsync(ct); + lock (received) { received.Add(body); } + return Results.Accepted(); + }); + await sink.StartAsync(ct); + string endpoint = sink.Urls.Single(); + + ServiceCollection services = new(); + services.AddBower(options => + { + options.Application.Name = "asvs-sdk-app"; + options.Application.Environment = "production"; + options.Application.TenantId = "tenant-1"; + options.LocalCollector.Endpoint = endpoint; + options.ShutdownFlushTimeout = TimeSpan.FromSeconds(5); + }); + + await using ServiceProvider provider = services.BuildServiceProvider(); + IAsvsTelemetry asvs = provider.GetRequiredService(); + + IPAddress ip = IPAddress.Parse("192.0.2.55"); + await asvs.AuthenticationSucceededAsync(new AuthenticationSucceededEvent + { + UserId = "u-1", + Username = "alice@example.com", + AuthMethod = "passkey", + SourceIpAddress = ip, + CorrelationId = "c-1" + }, ct); + await asvs.MfaEventAsync(new MfaSecurityEvent + { + UserId = "u-1", + Outcome = MfaOutcome.Failure, + Factor = "totp", + Reason = "invalid_code", + SourceIpAddress = ip, + CorrelationId = "c-2" + }, ct); + await asvs.AuthenticationFactorLifecycleAsync(new AuthenticationFactorLifecycleEvent + { + ActorUserId = "u-admin", + TargetUserId = "u-1", + Action = FactorLifecycleAction.MfaRemoved, + Factor = "totp", + InitiatedBy = "admin", + CorrelationId = "c-3" + }, ct); + await asvs.AccountStatusChangedAsync(new AccountStatusChangedEvent + { + ActorUserId = "u-admin", + TargetUserId = "u-2", + Action = AccountStatusAction.Disable, + Reason = "offboarding", + CorrelationId = "c-4" + }, ct); + await asvs.SessionLifecycleAsync(new SessionLifecycleEvent + { + ActorUserId = "u-1", + Action = SessionLifecycleAction.RevokeAll, + SessionId = "sess-raw-secret-token", + SessionsTerminated = 3, + CorrelationId = "c-5" + }, ct); + await asvs.AuthorisationFailedAsync(new AuthorisationFailedEvent + { + ActorUserId = "u-1", + Kind = AuthorisationFailureKind.ObjectLevel, + TargetType = "invoice", + TargetId = "inv-9", + Route = "/api/invoices/inv-9", + HttpMethod = "GET", + SourceIpAddress = ip, + CorrelationId = "c-6" + }, ct); + await asvs.SensitiveDataAccessedAsync(new SensitiveDataAccessEvent + { + ActorUserId = "u-1", + Operation = SensitiveDataOperation.Read, + TargetType = "record", + TargetId = "rec-7", + DataClassification = "OFFICIAL:Sensitive", + RecordCount = 1, + CorrelationId = "c-7" + }, ct); + await asvs.AdministrativeActionAsync(new AdministrativeSecurityEvent + { + ActorUserId = "u-admin", + Kind = AdministrativeEventKind.ConfigurationChanged, + Action = "config.update", + TargetType = "setting", + TargetId = "mfa-policy", + ChangedField = "requireMfa", + CorrelationId = "c-8" + }, ct); + await asvs.ControlBypassAttemptedAsync(new ControlBypassEvent + { + Kind = ControlBypassKind.AntiAutomationTriggered, + Action = "rate_limit.exceeded", + SourceIpAddress = ip, + Route = "/login", + Reason = "threshold_exceeded", + CorrelationId = "c-9" + }, ct); + await asvs.SecurityErrorAsync(new SecurityErrorEvent + { + Kind = SecurityErrorKind.SecurityControlFailure, + Action = "tls.verify", + Reason = "certificate_expired", + ErrorType = "TlsValidationError", + CorrelationId = "c-10" + }, ct); + await asvs.DatabaseAuditAsync(new DatabaseAuditEvent + { + DbEngine = "postgresql", + Action = DatabaseAuditAction.Dcl, + ActorUsername = "db_ops", + TargetName = "billing", + StatementClass = "ROLE", + SourceIpAddress = ip + }, ct); + + await provider.DisposeAsync(); + await sink.StopAsync(ct); + + Assert.Equal(11, received.Count); + HashSet matchedPolicies = new(StringComparer.Ordinal); + foreach (string rawJson in received) + { + PrivacyScanResult redacted = privacy.RedactJson(rawJson); + Assert.True(redacted.Succeeded); + Assert.DoesNotContain("alice@example.com", redacted.RedactedJson!, StringComparison.Ordinal); + Assert.DoesNotContain("sess-raw-secret-token", redacted.RedactedJson!, StringComparison.Ordinal); + + SecurityEventEnvelope envelope = JsonSerializer.Deserialize(redacted.RedactedJson!, BowerJson.Envelope)!; + PolicyDecision decision = evaluator.Evaluate(envelope); + Assert.Equal(DecisionAction.Accept, decision.Action); + matchedPolicies.Add(decision.PolicyId); + } + + Assert.Equal(11, matchedPolicies.Count); + } + + private static LoadedPack BuildAsvsPack() + { + using TemporaryDirectory output = new(); + (string privatePem, string publicPem, _) = DetachedSigner.GenerateKeyPair(); + string archive = PackArchive.Build(Path.Combine(AppContext.BaseDirectory, "packs", PackId), privatePem, output.Path); + return PackArchive.Load(archive, [publicPem]); + } +}