smbd: Use leases_db in lease_match()
[gd/samba-autobuild/.git] / auth / auth_log.c
index 97b65371bdc23ae09fdb894eefb78c1d1ab2c25f..d9b83b0ea0d5624ca9c335e3726cc5914d029258 100644 (file)
@@ -41,7 +41,7 @@
  * increment the major version.
  */
 #define AUTH_MAJOR 1
-#define AUTH_MINOR 0
+#define AUTH_MINOR 2
 #define AUTHZ_MAJOR 1
 #define AUTHZ_MINOR 1
 
 #include "lib/util/server_id_db.h"
 #include "lib/param/param.h"
 #include "librpc/ndr/libndr.h"
-
-/*
- * Get a human readable timestamp.
- *
- * Returns the current time formatted as
- *  "Tue, 14 Mar 2017 08:38:42.209028 NZDT"
- *
- * The returned string is allocated by talloc in the supplied context.
- * It is the callers responsibility to free it.
- *
- */
-static const char* get_timestamp(TALLOC_CTX *frame)
-{
-       char buffer[40];        /* formatted time less usec and timezone */
-       char tz[10];            /* formatted time zone                   */
-       struct tm* tm_info;     /* current local time                    */
-       struct timeval tv;      /* current system time                   */
-       int r;                  /* response code from gettimeofday       */
-       const char * ts;        /* formatted time stamp                  */
-
-       r = gettimeofday(&tv, NULL);
-       if (r) {
-               DBG_ERR("Unable to get time of day: (%d) %s\n",
-                       errno,
-                       strerror(errno));
-               return NULL;
-       }
-
-       tm_info = localtime(&tv.tv_sec);
-       if (tm_info == NULL) {
-               DBG_ERR("Unable to determine local time\n");
-               return NULL;
-       }
-
-       strftime(buffer, sizeof(buffer)-1, "%a, %d %b %Y %H:%M:%S", tm_info);
-       strftime(tz, sizeof(tz)-1, "%Z", tm_info);
-       ts = talloc_asprintf(frame, "%s.%06ld %s", buffer, tv.tv_usec, tz);
-       if (ts == NULL) {
-               DBG_ERR("Out of memory formatting time stamp\n");
-       }
-       return ts;
-}
+#include "librpc/gen_ndr/windows_event_ids.h"
+#include "lib/audit_logging/audit_logging.h"
 
 /*
  * Determine the type of the password supplied for the
@@ -112,343 +72,48 @@ static const char* get_password_type(const struct auth_usersupplied_info *ui);
 #include <jansson.h>
 #include "system/time.h"
 
-/*
- * Context required by the JSON generation
- *  routines
- *
- */
-struct json_context {
-       json_t *root;
-       bool error;
-};
-
-static NTSTATUS get_auth_event_server(struct imessaging_context *msg_ctx,
-                                     struct server_id *auth_event_server)
-{
-       NTSTATUS status;
-       TALLOC_CTX *frame = talloc_stackframe();
-       unsigned num_servers, i;
-       struct server_id *servers;
-
-       status = irpc_servers_byname(msg_ctx, frame,
-                                    AUTH_EVENT_NAME,
-                                    &num_servers, &servers);
-
-       if (!NT_STATUS_IS_OK(status)) {
-               DBG_NOTICE("Failed to find 'auth_event' registered on the "
-                          "message bus to send JSON authentication events to: %s\n",
-                          nt_errstr(status));
-               TALLOC_FREE(frame);
-               return status;
-       }
-
-       /*
-        * Select the first server that is listening, because
-        * we get connection refused as
-        * NT_STATUS_OBJECT_NAME_NOT_FOUND without waiting
-        */
-       for (i = 0; i < num_servers; i++) {
-               status = imessaging_send(msg_ctx, servers[i], MSG_PING,
-                                        &data_blob_null);
-               if (NT_STATUS_IS_OK(status)) {
-                       *auth_event_server = servers[i];
-                       TALLOC_FREE(frame);
-                       return NT_STATUS_OK;
-               }
-       }
-       DBG_NOTICE("Failed to find a running 'auth_event' server "
-                  "registered on the message bus to send JSON "
-                  "authentication events to\n");
-       TALLOC_FREE(frame);
-       return NT_STATUS_OBJECT_NAME_NOT_FOUND;
-}
-
-static void auth_message_send(struct imessaging_context *msg_ctx,
-                             const char *json)
-{
-       struct server_id auth_event_server;
-       NTSTATUS status;
-       DATA_BLOB json_blob = data_blob_string_const(json);
-       if (msg_ctx == NULL) {
-               return;
-       }
-
-       /* Need to refetch the address each time as the destination server may
-        * have disconnected and reconnected in the interim, in which case
-        * messages may get lost, manifests in the auth_log tests
-        */
-       status = get_auth_event_server(msg_ctx, &auth_event_server);
-       if (!NT_STATUS_IS_OK(status)) {
-               return;
-       }
-
-       status = imessaging_send(msg_ctx, auth_event_server, MSG_AUTH_LOG,
-                                &json_blob);
-
-       /* If the server crashed, try to find it again */
-       if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
-               status = get_auth_event_server(msg_ctx, &auth_event_server);
-               if (!NT_STATUS_IS_OK(status)) {
-                       return;
-               }
-               imessaging_send(msg_ctx, auth_event_server, MSG_AUTH_LOG,
-                               &json_blob);
-
-       }
-}
-
 /*
  * Write the json object to the debug logs.
  *
  */
 static void log_json(struct imessaging_context *msg_ctx,
                     struct loadparm_context *lp_ctx,
-                    struct json_context *context,
-                    const char *type, int debug_class, int debug_level)
+                    struct json_object *object,
+                    int debug_class,
+                    int debug_level)
 {
-       char* json = NULL;
-
-       if (context->error) {
-               return;
-       }
-
-       json = json_dumps(context->root, 0);
-       if (json == NULL) {
-               DBG_ERR("Unable to convert JSON object to string\n");
-               context->error = true;
-               return;
-       }
-
-       DEBUGC(debug_class, debug_level, ("JSON %s: %s\n", type, json));
+       audit_log_json(object, debug_class, debug_level);
        if (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx)) {
-               auth_message_send(msg_ctx, json);
-       }
-
-       if (json) {
-               free(json);
-       }
-
-}
-
-/*
- * Create a new json logging context.
- *
- * Free with a call to free_json_context
- *
- */
-static struct json_context get_json_context(void) {
-
-       struct json_context context;
-       context.error = false;
-
-       context.root = json_object();
-       if (context.root == NULL) {
-               context.error = true;
-               DBG_ERR("Unable to create json_object\n");
-       }
-       return context;
-}
-
-/*
- * free a previously created json_context
- *
- */
-static void free_json_context(struct json_context *context)
-{
-       if (context->root) {
-               json_decref(context->root);
-       }
-}
-
-/*
- * Output a JSON pair with name name and integer value value
- *
- */
-static void add_int(struct json_context *context,
-                   const char* name,
-                   const int value)
-{
-       int rc = 0;
-
-       if (context->error) {
-               return;
-       }
-
-       rc = json_object_set_new(context->root, name, json_integer(value));
-       if (rc) {
-               DBG_ERR("Unable to set name [%s] value [%d]\n", name, value);
-               context->error = true;
-       }
-
-}
-
-/*
- * Output a JSON pair with name name and string value value
- *
- */
-static void add_string(struct json_context *context,
-                      const char* name,
-                      const char* value)
-{
-       int rc = 0;
-
-       if (context->error) {
-               return;
-       }
-
-       if (value) {
-               rc = json_object_set_new(context->root, name, json_string(value));
-       } else {
-               rc = json_object_set_new(context->root, name, json_null());
-       }
-       if (rc) {
-               DBG_ERR("Unable to set name [%s] value [%s]\n", name, value);
-               context->error = true;
-       }
-}
-
-
-/*
- * Output a JSON pair with name name and object value
- *
- */
-static void add_object(struct json_context *context,
-                      const char* name,
-                      struct json_context *value)
-{
-       int rc = 0;
-
-       if (value->error) {
-               context->error = true;
-       }
-       if (context->error) {
-               return;
-       }
-       rc = json_object_set_new(context->root, name, value->root);
-       if (rc) {
-               DBG_ERR("Unable to add object [%s]\n", name);
-               context->error = true;
-       }
-}
-
-/*
- * Output a version object
- *
- * "version":{"major":1,"minor":0}
- *
- */
-static void add_version(struct json_context *context, int major, int minor)
-{
-       struct json_context version = get_json_context();
-       add_int(&version, "major", major);
-       add_int(&version, "minor", minor);
-       add_object(context, "version", &version);
-}
-
-/*
- * Output the current date and time as a timestamp in ISO 8601 format
- *
- * "timestamp":"2017-03-06T17:18:04.455081+1300"
- *
- */
-static void add_timestamp(struct json_context *context)
-{
-       char buffer[40];        /* formatted time less usec and timezone */
-       char timestamp[50];     /* the formatted ISO 8601 time stamp     */
-       char tz[10];            /* formatted time zone                   */
-       struct tm* tm_info;     /* current local time                    */
-       struct timeval tv;      /* current system time                   */
-       int r;                  /* response code from gettimeofday       */
-
-       if (context->error) {
-               return;
-       }
-
-       r = gettimeofday(&tv, NULL);
-       if (r) {
-               DBG_ERR("Unable to get time of day: (%d) %s\n",
-                       errno,
-                       strerror(errno));
-               context->error = true;
-               return;
-       }
-
-       tm_info = localtime(&tv.tv_sec);
-       if (tm_info == NULL) {
-               DBG_ERR("Unable to determine local time\n");
-               context->error = true;
-               return;
-       }
-
-       strftime(buffer, sizeof(buffer)-1, "%Y-%m-%dT%T", tm_info);
-       strftime(tz, sizeof(tz)-1, "%z", tm_info);
-       snprintf(timestamp, sizeof(timestamp),"%s.%06ld%s",
-                buffer, tv.tv_usec, tz);
-       add_string(context,"timestamp", timestamp);
-}
-
-
-/*
- * Output an address pair, with name name.
- *
- * "localAddress":"ipv6::::0"
- *
- */
-static void add_address(struct json_context *context,
-                       const char *name,
-                       const struct tsocket_address *address)
-{
-       char *s = NULL;
-       TALLOC_CTX *frame = talloc_stackframe();
-
-       if (context->error) {
-               return;
+               audit_message_send(msg_ctx,
+                                  AUTH_EVENT_NAME,
+                                  MSG_AUTH_LOG,
+                                  object);
        }
-
-       s = tsocket_address_string(address, frame);
-       add_string(context, name, s);
-       talloc_free(frame);
-
 }
 
 /*
- * Output a SID with name name
+ * Determine the Windows logon type for the current authorisation attempt.
  *
- * "sid":"S-1-5-18"
+ * Currently Samba only supports
  *
- */
-static void add_sid(struct json_context *context,
-                   const char *name,
-                   const struct dom_sid *sid)
-{
-       char sid_buf[DOM_SID_STR_BUFLEN];
-
-       if (context->error) {
-               return;
-       }
-
-       dom_sid_string_buf(sid, sid_buf, sizeof(sid_buf));
-       add_string(context, name, sid_buf);
-}
-
-/*
- * Add a formatted string representation of a GUID to a json object.
+ * 2 Interactive      A user logged on to this computer.
+ * 3 Network          A user or computer logged on to this computer from
+ *                    the network.
+ * 8 NetworkCleartext A user logged on to this computer from the network.
+ *                    The user's password was passed to the authentication
+ *                    package in its unhashed form.
  *
  */
-static void add_guid(struct json_context *context,
-                    const char *name,
-                    struct GUID *guid)
+static enum event_logon_type get_logon_type(
+       const struct auth_usersupplied_info *ui)
 {
-
-       char *guid_str;
-       struct GUID_txt_buf guid_buff;
-
-       if (context->error) {
-               return;
+       if ((ui->logon_parameters & MSV1_0_CLEARTEXT_PASSWORD_SUPPLIED)
+          || (ui->password_state == AUTH_PASSWORD_PLAIN)) {
+               return EVT_LOGON_NETWORK_CLEAR_TEXT;
+       } else if (ui->flags & USER_INFO_INTERACTIVE_LOGON) {
+               return EVT_LOGON_INTERACTIVE;
        }
-
-       guid_str = GUID_buf_string(guid, &guid_buff);
-       add_string(context, name, guid_str);
+       return EVT_LOGON_NETWORK;
 }
 
 /*
@@ -462,9 +127,8 @@ static void add_guid(struct json_context *context,
  *  To process the resulting log lines from the commend line use jq to
  *  parse the json.
  *
- *  grep "JSON Authentication" log file |
- *  sed 's;^[^{]*;;' |
- * jq -rc  '"\(.timestamp)\t\(.Authentication.status)\t
+ *  grep "^  {" log file |
+ *  jq -rc '"\(.timestamp)\t\(.Authentication.status)\t
  *           \(.Authentication.clientDomain)\t
  *           \(.Authentication.clientAccount)
  *           \t\(.Authentication.workstation)
@@ -472,67 +136,199 @@ static void add_guid(struct json_context *context,
  *           \t\(.Authentication.localAddress)"'
  */
 static void log_authentication_event_json(
-                       struct imessaging_context *msg_ctx,
-                       struct loadparm_context *lp_ctx,
-                       const struct auth_usersupplied_info *ui,
-                       NTSTATUS status,
-                       const char *domain_name,
-                       const char *account_name,
-                       const char *unix_username,
-                       struct dom_sid *sid,
-                       int debug_level)
+       struct imessaging_context *msg_ctx,
+       struct loadparm_context *lp_ctx,
+       const struct timeval *start_time,
+       const struct auth_usersupplied_info *ui,
+       NTSTATUS status,
+       const char *domain_name,
+       const char *account_name,
+       const char *unix_username,
+       struct dom_sid *sid,
+       enum event_id_type event_id,
+       int debug_level)
 {
-       struct json_context context = get_json_context();
-       struct json_context authentication;
+       struct json_object wrapper = json_empty_object;
+       struct json_object authentication = json_empty_object;
        char negotiate_flags[11];
+       char logon_id[19];
+       int rc = 0;
 
-       add_timestamp(&context);
-       add_string(&context, "type", AUTH_JSON_TYPE);
-
-       authentication = get_json_context();
-       add_version(&authentication, AUTH_MAJOR, AUTH_MINOR);
-       add_string(&authentication, "status", nt_errstr(status));
-       add_address(&authentication, "localAddress", ui->local_host);
-       add_address(&authentication, "remoteAddress", ui->remote_host);
-       add_string(&authentication,
-                  "serviceDescription",
-                  ui->service_description);
-       add_string(&authentication, "authDescription", ui->auth_description);
-       add_string(&authentication, "clientDomain", ui->client.domain_name);
-       add_string(&authentication, "clientAccount", ui->client.account_name);
-       add_string(&authentication, "workstation", ui->workstation_name);
-       add_string(&authentication, "becameAccount", account_name);
-       add_string(&authentication, "becameDomain", domain_name);
-       add_sid(&authentication, "becameSid", sid);
-       add_string(&authentication, "mappedAccount", ui->mapped.account_name);
-       add_string(&authentication, "mappedDomain", ui->mapped.domain_name);
-       add_string(&authentication,
-                  "netlogonComputer",
-                  ui->netlogon_trust_account.computer_name);
-       add_string(&authentication,
-                  "netlogonTrustAccount",
-                  ui->netlogon_trust_account.account_name);
+       authentication = json_new_object();
+       if (json_is_invalid(&authentication)) {
+               goto failure;
+       }
+       rc = json_add_version(&authentication, AUTH_MAJOR, AUTH_MINOR);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_int(&authentication,
+                         "eventId",
+                         event_id);
+       if (rc != 0) {
+               goto failure;
+       }
+       snprintf(logon_id,
+                sizeof( logon_id),
+                "%"PRIx64"",
+                ui->logon_id);
+       rc = json_add_string(&authentication, "logonId", logon_id);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_int(&authentication, "logonType", get_logon_type(ui));
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&authentication, "status", nt_errstr(status));
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_address(&authentication, "localAddress", ui->local_host);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc =
+           json_add_address(&authentication, "remoteAddress", ui->remote_host);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "serviceDescription", ui->service_description);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "authDescription", ui->auth_description);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "clientDomain", ui->client.domain_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "clientAccount", ui->client.account_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "workstation", ui->workstation_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&authentication, "becameAccount", account_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&authentication, "becameDomain", domain_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_sid(&authentication, "becameSid", sid);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "mappedAccount", ui->mapped.account_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "mappedDomain", ui->mapped.domain_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&authentication,
+                            "netlogonComputer",
+                            ui->netlogon_trust_account.computer_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&authentication,
+                            "netlogonTrustAccount",
+                            ui->netlogon_trust_account.account_name);
+       if (rc != 0) {
+               goto failure;
+       }
        snprintf(negotiate_flags,
                 sizeof( negotiate_flags),
                 "0x%08X",
                 ui->netlogon_trust_account.negotiate_flags);
-       add_string(&authentication, "netlogonNegotiateFlags", negotiate_flags);
-       add_int(&authentication,
-               "netlogonSecureChannelType",
-               ui->netlogon_trust_account.secure_channel_type);
-       add_sid(&authentication,
-               "netlogonTrustAccountSid",
-               ui->netlogon_trust_account.sid);
-       add_string(&authentication, "passwordType", get_password_type(ui));
-       add_object(&context,AUTH_JSON_TYPE, &authentication);
+       rc = json_add_string(
+           &authentication, "netlogonNegotiateFlags", negotiate_flags);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_int(&authentication,
+                         "netlogonSecureChannelType",
+                         ui->netlogon_trust_account.secure_channel_type);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_sid(&authentication,
+                         "netlogonTrustAccountSid",
+                         ui->netlogon_trust_account.sid);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authentication, "passwordType", get_password_type(ui));
+       if (rc != 0) {
+               goto failure;
+       }
+
+       wrapper = json_new_object();
+       if (json_is_invalid(&wrapper)) {
+               goto failure;
+       }
+       rc = json_add_timestamp(&wrapper);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&wrapper, "type", AUTH_JSON_TYPE);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_object(&wrapper, AUTH_JSON_TYPE, &authentication);
+       if (rc != 0) {
+               goto failure;
+       }
+
+       /*
+        * While not a general-purpose profiling solution this will
+        * assist some to determine how long NTLM and KDC
+        * authentication takes once this process can handle it.  This
+        * covers transactions elsewhere but not (eg) the delay while
+        * this is waiting unread on the input socket.
+        */
+       if (start_time != NULL) {
+               struct timeval current_time = timeval_current();
+               uint64_t duration =  usec_time_diff(&current_time,
+                                                   start_time);
+               rc = json_add_int(&authentication, "duration", duration);
+               if (rc != 0) {
+                       goto failure;
+               }
+       }
 
        log_json(msg_ctx,
                 lp_ctx,
-                &context,
-                AUTH_JSON_TYPE,
-                DBGC_AUTH_AUDIT,
+                &wrapper,
+                DBGC_AUTH_AUDIT_JSON,
                 debug_level);
-       free_json_context(&context);
+       json_free(&wrapper);
+       return;
+failure:
+       /*
+        * On a failure authentication will not have been added to wrapper so it
+        * needs to be freed to avoid a leak.
+        *
+        */
+       json_free(&authentication);
+       json_free(&wrapper);
+       DBG_ERR("Failed to write authentication event JSON log message\n");
 }
 
 /*
@@ -547,8 +343,7 @@ static void log_authentication_event_json(
  *  To process the resulting log lines from the commend line use jq to
  *  parse the json.
  *
- *  grep "JSON Authentication" log_file |\
- *  sed "s;^[^{]*;;" |\
+ *  grep "^  {" log_file |\
  *  jq -rc '"\(.timestamp)\t
  *           \(.Authorization.domain)\t
  *           \(.Authorization.account)\t
@@ -556,54 +351,119 @@ static void log_authentication_event_json(
  *
  */
 static void log_successful_authz_event_json(
-                               struct imessaging_context *msg_ctx,
-                               struct loadparm_context *lp_ctx,
-                               const struct tsocket_address *remote,
-                               const struct tsocket_address *local,
-                               const char *service_description,
-                               const char *auth_type,
-                               const char *transport_protection,
-                               struct auth_session_info *session_info,
-                               int debug_level)
+       struct imessaging_context *msg_ctx,
+       struct loadparm_context *lp_ctx,
+       const struct tsocket_address *remote,
+       const struct tsocket_address *local,
+       const char *service_description,
+       const char *auth_type,
+       const char *transport_protection,
+       struct auth_session_info *session_info,
+       int debug_level)
 {
-       struct json_context context = get_json_context();
-       struct json_context authorization;
+       struct json_object wrapper = json_empty_object;
+       struct json_object authorization = json_empty_object;
        char account_flags[11];
+       int rc = 0;
 
-       //start_object(&context, NULL);
-       add_timestamp(&context);
-       add_string(&context, "type", AUTHZ_JSON_TYPE);
-       authorization = get_json_context();
-       add_version(&authorization, AUTHZ_MAJOR, AUTHZ_MINOR);
-       add_address(&authorization, "localAddress", local);
-       add_address(&authorization, "remoteAddress", remote);
-       add_string(&authorization, "serviceDescription", service_description);
-       add_string(&authorization, "authType", auth_type);
-       add_string(&authorization, "domain", session_info->info->domain_name);
-       add_string(&authorization, "account", session_info->info->account_name);
-       add_sid(&authorization, "sid", &session_info->security_token->sids[0]);
-       add_guid(&authorization,
-                "sessionId",
-                &session_info->unique_session_token);
-       add_string(&authorization,
-                  "logonServer",
-                  session_info->info->logon_server);
-       add_string(&authorization, "transportProtection", transport_protection);
+       authorization = json_new_object();
+       if (json_is_invalid(&authorization)) {
+               goto failure;
+       }
+       rc = json_add_version(&authorization, AUTHZ_MAJOR, AUTHZ_MINOR);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_address(&authorization, "localAddress", local);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_address(&authorization, "remoteAddress", remote);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authorization, "serviceDescription", service_description);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&authorization, "authType", auth_type);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authorization, "domain", session_info->info->domain_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authorization, "account", session_info->info->account_name);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_sid(
+           &authorization, "sid", &session_info->security_token->sids[0]);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_guid(
+           &authorization, "sessionId", &session_info->unique_session_token);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authorization, "logonServer", session_info->info->logon_server);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(
+           &authorization, "transportProtection", transport_protection);
+       if (rc != 0) {
+               goto failure;
+       }
 
        snprintf(account_flags,
                 sizeof(account_flags),
                 "0x%08X",
                 session_info->info->acct_flags);
-       add_string(&authorization, "accountFlags", account_flags);
-       add_object(&context,AUTHZ_JSON_TYPE, &authorization);
+       rc = json_add_string(&authorization, "accountFlags", account_flags);
+       if (rc != 0) {
+               goto failure;
+       }
+
+       wrapper = json_new_object();
+       if (json_is_invalid(&wrapper)) {
+               goto failure;
+       }
+       rc = json_add_timestamp(&wrapper);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_string(&wrapper, "type", AUTHZ_JSON_TYPE);
+       if (rc != 0) {
+               goto failure;
+       }
+       rc = json_add_object(&wrapper, AUTHZ_JSON_TYPE, &authorization);
+       if (rc != 0) {
+               goto failure;
+       }
 
        log_json(msg_ctx,
                 lp_ctx,
-                &context,
-                AUTHZ_JSON_TYPE,
-                DBGC_AUTH_AUDIT,
+                &wrapper,
+                DBGC_AUTH_AUDIT_JSON,
                 debug_level);
-       free_json_context(&context);
+       json_free(&wrapper);
+       return;
+failure:
+       /*
+        * On a failure authorization will not have been added to wrapper so it
+        * needs to be freed to avoid a leak.
+        *
+        */
+       json_free(&authorization);
+       json_free(&wrapper);
+       DBG_ERR("Unable to log Authentication event JSON audit message\n");
 }
 
 #else
@@ -615,13 +475,15 @@ static void log_no_json(struct imessaging_context *msg_ctx,
                static bool auth_event_logged = false;
                if (auth_event_logged == false) {
                        auth_event_logged = true;
-                       DBG_ERR("auth event notification = true but Samba was not compiled with jansson\n");
+                       DBG_ERR("auth event notification = true but Samba was "
+                               "not compiled with jansson\n");
                }
        } else {
                static bool json_logged = false;
                if (json_logged == false) {
                        json_logged = true;
-                       DBG_NOTICE("JSON auth logs not available unless compiled with jansson\n");
+                       DBG_NOTICE("JSON auth logs not available unless "
+                                  "compiled with jansson\n");
                }
        }
 
@@ -629,30 +491,32 @@ static void log_no_json(struct imessaging_context *msg_ctx,
 }
 
 static void log_authentication_event_json(
-                       struct imessaging_context *msg_ctx,
-                       struct loadparm_context *lp_ctx,
-                       const struct auth_usersupplied_info *ui,
-                       NTSTATUS status,
-                       const char *domain_name,
-                       const char *account_name,
-                       const char *unix_username,
-                       struct dom_sid *sid,
-                       int debug_level)
+       struct imessaging_context *msg_ctx,
+       struct loadparm_context *lp_ctx,
+       const struct timeval *start_time,
+       const struct auth_usersupplied_info *ui,
+       NTSTATUS status,
+       const char *domain_name,
+       const char *account_name,
+       const char *unix_username,
+       struct dom_sid *sid,
+       enum event_id_type event_id,
+       int debug_level)
 {
        log_no_json(msg_ctx, lp_ctx);
        return;
 }
 
 static void log_successful_authz_event_json(
-                               struct imessaging_context *msg_ctx,
-                               struct loadparm_context *lp_ctx,
-                               const struct tsocket_address *remote,
-                               const struct tsocket_address *local,
-                               const char *service_description,
-                               const char *auth_type,
-                               const char *transport_protection,
-                               struct auth_session_info *session_info,
-                               int debug_level)
+       struct imessaging_context *msg_ctx,
+       struct loadparm_context *lp_ctx,
+       const struct tsocket_address *remote,
+       const struct tsocket_address *local,
+       const char *service_description,
+       const char *auth_type,
+       const char *transport_protection,
+       struct auth_session_info *session_info,
+       int debug_level)
 {
        log_no_json(msg_ctx, lp_ctx);
        return;
@@ -715,13 +579,13 @@ static const char* get_password_type(const struct auth_usersupplied_info *ui)
  *
  */
 static void log_authentication_event_human_readable(
-                       const struct auth_usersupplied_info *ui,
-                       NTSTATUS status,
-                       const char *domain_name,
-                       const char *account_name,
-                       const char *unix_username,
-                       struct dom_sid *sid,
-                       int debug_level)
+       const struct auth_usersupplied_info *ui,
+       NTSTATUS status,
+       const char *domain_name,
+       const char *account_name,
+       const char *unix_username,
+       struct dom_sid *sid,
+       int debug_level)
 {
        TALLOC_CTX *frame = NULL;
 
@@ -738,7 +602,7 @@ static void log_authentication_event_human_readable(
 
        password_type = get_password_type(ui);
        /* Get the current time */
-        ts = get_timestamp(frame);
+        ts = audit_get_timestamp(frame);
 
        /* Only log the NETLOGON details if they are present */
        if (ui->netlogon_trust_account.computer_name ||
@@ -756,14 +620,13 @@ static void log_authentication_event_human_readable(
        local = tsocket_address_string(ui->local_host, frame);
 
        if (NT_STATUS_IS_OK(status)) {
-               char sid_buf[DOM_SID_STR_BUFLEN];
+               struct dom_sid_buf sid_buf;
 
-               dom_sid_string_buf(sid, sid_buf, sizeof(sid_buf));
                logon_line = talloc_asprintf(frame,
                                             " became [%s]\\[%s] [%s].",
                                             log_escape(frame, domain_name),
                                             log_escape(frame, account_name),
-                                            sid_buf);
+                                            dom_sid_str_buf(sid, &sid_buf));
        } else {
                logon_line = talloc_asprintf(
                                frame,
@@ -790,7 +653,7 @@ static void log_authentication_event_human_readable(
                logon_line,
                local,
                nl ? nl : ""
-              ));
+       ));
 
        talloc_free(frame);
 }
@@ -802,20 +665,24 @@ static void log_authentication_event_human_readable(
  * NOTE: msg_ctx and lp_ctx is optional, but when supplied allows streaming the
  * authentication events over the message bus.
  */
-void log_authentication_event(struct imessaging_context *msg_ctx,
-                             struct loadparm_context *lp_ctx,
-                             const struct auth_usersupplied_info *ui,
-                             NTSTATUS status,
-                             const char *domain_name,
-                             const char *account_name,
-                             const char *unix_username,
-                             struct dom_sid *sid)
+void log_authentication_event(
+       struct imessaging_context *msg_ctx,
+       struct loadparm_context *lp_ctx,
+       const struct timeval *start_time,
+       const struct auth_usersupplied_info *ui,
+       NTSTATUS status,
+       const char *domain_name,
+       const char *account_name,
+       const char *unix_username,
+       struct dom_sid *sid)
 {
        /* set the log level */
        int debug_level = AUTH_FAILURE_LEVEL;
+       enum event_id_type event_id = EVT_ID_UNSUCCESSFUL_LOGON;
 
        if (NT_STATUS_IS_OK(status)) {
                debug_level = AUTH_SUCCESS_LEVEL;
+               event_id = EVT_ID_SUCCESSFUL_LOGON;
                if (dom_sid_equal(sid, &global_sid_Anonymous)) {
                        debug_level = AUTH_ANONYMOUS_LEVEL;
                }
@@ -832,13 +699,16 @@ void log_authentication_event(struct imessaging_context *msg_ctx,
        }
        if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT_JSON, debug_level) ||
            (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx))) {
-               log_authentication_event_json(msg_ctx, lp_ctx,
+               log_authentication_event_json(msg_ctx,
+                                             lp_ctx,
+                                             start_time,
                                              ui,
                                              status,
                                              domain_name,
                                              account_name,
                                              unix_username,
                                              sid,
+                                             event_id,
                                              debug_level);
        }
 }
@@ -851,33 +721,29 @@ void log_authentication_event(struct imessaging_context *msg_ctx,
  *
  */
 static void log_successful_authz_event_human_readable(
-                               const struct tsocket_address *remote,
-                               const struct tsocket_address *local,
-                               const char *service_description,
-                               const char *auth_type,
-                               const char *transport_protection,
-                               struct auth_session_info *session_info,
-                               int debug_level)
+       const struct tsocket_address *remote,
+       const struct tsocket_address *local,
+       const char *service_description,
+       const char *auth_type,
+       const char *transport_protection,
+       struct auth_session_info *session_info,
+       int debug_level)
 {
        TALLOC_CTX *frame = NULL;
 
        const char *ts = NULL;       /* formatted current time      */
        char *remote_str = NULL;     /* formatted remote host       */
        char *local_str = NULL;      /* formatted local host        */
-       char sid_buf[DOM_SID_STR_BUFLEN];
+       struct dom_sid_buf sid_buf;
 
        frame = talloc_stackframe();
 
        /* Get the current time */
-        ts = get_timestamp(frame);
+        ts = audit_get_timestamp(frame);
 
        remote_str = tsocket_address_string(remote, frame);
        local_str = tsocket_address_string(local, frame);
 
-       dom_sid_string_buf(&session_info->security_token->sids[0],
-                          sid_buf,
-                          sizeof(sid_buf));
-
        DEBUGC(DBGC_AUTH_AUDIT, debug_level,
               ("Successful AuthZ: [%s,%s] user [%s]\\[%s] [%s]"
                " at [%s]"
@@ -887,7 +753,8 @@ static void log_successful_authz_event_human_readable(
                auth_type,
                log_escape(frame, session_info->info->domain_name),
                log_escape(frame, session_info->info->account_name),
-               sid_buf,
+               dom_sid_str_buf(&session_info->security_token->sids[0],
+                               &sid_buf),
                ts,
                remote_str,
                local_str));
@@ -907,14 +774,15 @@ static void log_successful_authz_event_human_readable(
  * NOTE: msg_ctx and lp_ctx is optional, but when supplied allows streaming the
  * authentication events over the message bus.
  */
-void log_successful_authz_event(struct imessaging_context *msg_ctx,
-                               struct loadparm_context *lp_ctx,
-                               const struct tsocket_address *remote,
-                               const struct tsocket_address *local,
-                               const char *service_description,
-                               const char *auth_type,
-                               const char *transport_protection,
-                               struct auth_session_info *session_info)
+void log_successful_authz_event(
+       struct imessaging_context *msg_ctx,
+       struct loadparm_context *lp_ctx,
+       const struct tsocket_address *remote,
+       const struct tsocket_address *local,
+       const char *service_description,
+       const char *auth_type,
+       const char *transport_protection,
+       struct auth_session_info *session_info)
 {
        int debug_level = AUTHZ_SUCCESS_LEVEL;