auth/spnego: set spnego_state->{state_position,expected_packet} gensec_spnego_create_...
[samba.git] / auth / auth_log.c
1 /*
2
3    Authentication and authorization logging
4
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2017
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /*
22  * Debug log levels for authentication logging (these both map to
23  * LOG_NOTICE in syslog)
24  */
25 #define AUTH_FAILURE_LEVEL 2
26 #define AUTH_SUCCESS_LEVEL 3
27 #define AUTHZ_SUCCESS_LEVEL 4
28
29 /* 5 is used for both authentication and authorization */
30 #define AUTH_ANONYMOUS_LEVEL 5
31 #define AUTHZ_ANONYMOUS_LEVEL 5
32
33 #define AUTHZ_JSON_TYPE "Authorization"
34 #define AUTH_JSON_TYPE  "Authentication"
35
36 /*
37  * JSON message version numbers
38  *
39  * If adding a field increment the minor version
40  * If removing or changing the format/meaning of a field
41  * increment the major version.
42  */
43 #define AUTH_MAJOR 1
44 #define AUTH_MINOR 0
45 #define AUTHZ_MAJOR 1
46 #define AUTHZ_MINOR 0
47
48 #include "includes.h"
49 #include "../lib/tsocket/tsocket.h"
50 #include "common_auth.h"
51 #include "lib/util/util_str_escape.h"
52 #include "libcli/security/dom_sid.h"
53 #include "libcli/security/security_token.h"
54 #include "librpc/gen_ndr/server_id.h"
55 #include "source4/lib/messaging/messaging.h"
56 #include "source4/lib/messaging/irpc.h"
57 #include "lib/util/server_id_db.h"
58 #include "lib/param/param.h"
59
60 /*
61  * Get a human readable timestamp.
62  *
63  * Returns the current time formatted as
64  *  "Tue, 14 Mar 2017 08:38:42.209028 NZDT"
65  *
66  * The returned string is allocated by talloc in the supplied context.
67  * It is the callers responsibility to free it.
68  *
69  */
70 static const char* get_timestamp(TALLOC_CTX *frame)
71 {
72         char buffer[40];        /* formatted time less usec and timezone */
73         char tz[10];            /* formatted time zone                   */
74         struct tm* tm_info;     /* current local time                    */
75         struct timeval tv;      /* current system time                   */
76         int r;                  /* response code from gettimeofday       */
77         const char * ts;        /* formatted time stamp                  */
78
79         r = gettimeofday(&tv, NULL);
80         if (r) {
81                 DBG_ERR("Unable to get time of day: (%d) %s\n",
82                         errno,
83                         strerror(errno));
84                 return NULL;
85         }
86
87         tm_info = localtime(&tv.tv_sec);
88         if (tm_info == NULL) {
89                 DBG_ERR("Unable to determine local time\n");
90                 return NULL;
91         }
92
93         strftime(buffer, sizeof(buffer)-1, "%a, %d %b %Y %H:%M:%S", tm_info);
94         strftime(tz, sizeof(tz)-1, "%Z", tm_info);
95         ts = talloc_asprintf(frame, "%s.%06ld %s", buffer, tv.tv_usec, tz);
96         if (ts == NULL) {
97                 DBG_ERR("Out of memory formatting time stamp\n");
98         }
99         return ts;
100 }
101
102 /*
103  * Determine the type of the password supplied for the
104  * authorisation attempt.
105  *
106  */
107 static const char* get_password_type(const struct auth_usersupplied_info *ui);
108
109 #ifdef HAVE_JANSSON
110
111 #include <jansson.h>
112 #include "system/time.h"
113
114 /*
115  * Context required by the JSON generation
116  *  routines
117  *
118  */
119 struct json_context {
120         json_t *root;
121         bool error;
122 };
123
124 static NTSTATUS get_auth_event_server(struct imessaging_context *msg_ctx,
125                                       struct server_id *auth_event_server)
126 {
127         NTSTATUS status;
128         TALLOC_CTX *frame = talloc_stackframe();
129         unsigned num_servers, i;
130         struct server_id *servers;
131
132         status = irpc_servers_byname(msg_ctx, frame,
133                                      AUTH_EVENT_NAME,
134                                      &num_servers, &servers);
135
136         if (!NT_STATUS_IS_OK(status)) {
137                 DBG_NOTICE("Failed to find 'auth_event' registered on the "
138                            "message bus to send JSON authentication events to: %s\n",
139                            nt_errstr(status));
140                 TALLOC_FREE(frame);
141                 return status;
142         }
143
144         /*
145          * Select the first server that is listening, because
146          * we get connection refused as
147          * NT_STATUS_OBJECT_NAME_NOT_FOUND without waiting
148          */
149         for (i = 0; i < num_servers; i++) {
150                 status = imessaging_send(msg_ctx, servers[i], MSG_PING,
151                                          &data_blob_null);
152                 if (NT_STATUS_IS_OK(status)) {
153                         *auth_event_server = servers[i];
154                         TALLOC_FREE(frame);
155                         return NT_STATUS_OK;
156                 }
157         }
158         DBG_NOTICE("Failed to find a running 'auth_event' server "
159                    "registered on the message bus to send JSON "
160                    "authentication events to\n");
161         TALLOC_FREE(frame);
162         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
163 }
164
165 static void auth_message_send(struct imessaging_context *msg_ctx,
166                               const char *json)
167 {
168         struct server_id auth_event_server;
169         NTSTATUS status;
170         DATA_BLOB json_blob = data_blob_string_const(json);
171         if (msg_ctx == NULL) {
172                 return;
173         }
174
175         /* Need to refetch the address each time as the destination server may
176          * have disconnected and reconnected in the interim, in which case
177          * messages may get lost, manifests in the auth_log tests
178          */
179         status = get_auth_event_server(msg_ctx, &auth_event_server);
180         if (!NT_STATUS_IS_OK(status)) {
181                 return;
182         }
183
184         status = imessaging_send(msg_ctx, auth_event_server, MSG_AUTH_LOG,
185                                  &json_blob);
186
187         /* If the server crashed, try to find it again */
188         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
189                 status = get_auth_event_server(msg_ctx, &auth_event_server);
190                 if (!NT_STATUS_IS_OK(status)) {
191                         return;
192                 }
193                 imessaging_send(msg_ctx, auth_event_server, MSG_AUTH_LOG,
194                                 &json_blob);
195
196         }
197 }
198
199 /*
200  * Write the json object to the debug logs.
201  *
202  */
203 static void log_json(struct imessaging_context *msg_ctx,
204                      struct json_context *context,
205                      const char *type, int debug_class, int debug_level)
206 {
207         char* json = NULL;
208
209         if (context->error) {
210                 return;
211         }
212
213         json = json_dumps(context->root, 0);
214         if (json == NULL) {
215                 DBG_ERR("Unable to convert JSON object to string\n");
216                 context->error = true;
217                 return;
218         }
219
220         DEBUGC(debug_class, debug_level, ("JSON %s: %s\n", type, json));
221         auth_message_send(msg_ctx, json);
222
223         if (json) {
224                 free(json);
225         }
226
227 }
228
229 /*
230  * Create a new json logging context.
231  *
232  * Free with a call to free_json_context
233  *
234  */
235 static struct json_context get_json_context(void) {
236
237         struct json_context context;
238         context.error = false;
239
240         context.root = json_object();
241         if (context.root == NULL) {
242                 context.error = true;
243                 DBG_ERR("Unable to create json_object\n");
244         }
245         return context;
246 }
247
248 /*
249  * free a previously created json_context
250  *
251  */
252 static void free_json_context(struct json_context *context)
253 {
254         if (context->root) {
255                 json_decref(context->root);
256         }
257 }
258
259 /*
260  * Output a JSON pair with name name and integer value value
261  *
262  */
263 static void add_int(struct json_context *context,
264                     const char* name,
265                     const int value)
266 {
267         int rc = 0;
268
269         if (context->error) {
270                 return;
271         }
272
273         rc = json_object_set_new(context->root, name, json_integer(value));
274         if (rc) {
275                 DBG_ERR("Unable to set name [%s] value [%d]\n", name, value);
276                 context->error = true;
277         }
278
279 }
280
281 /*
282  * Output a JSON pair with name name and string value value
283  *
284  */
285 static void add_string(struct json_context *context,
286                        const char* name,
287                        const char* value)
288 {
289         int rc = 0;
290
291         if (context->error) {
292                 return;
293         }
294
295         if (value) {
296                 rc = json_object_set_new(context->root, name, json_string(value));
297         } else {
298                 rc = json_object_set_new(context->root, name, json_null());
299         }
300         if (rc) {
301                 DBG_ERR("Unable to set name [%s] value [%s]\n", name, value);
302                 context->error = true;
303         }
304 }
305
306
307 /*
308  * Output a JSON pair with name name and object value
309  *
310  */
311 static void add_object(struct json_context *context,
312                        const char* name,
313                        struct json_context *value)
314 {
315         int rc = 0;
316
317         if (value->error) {
318                 context->error = true;
319         }
320         if (context->error) {
321                 return;
322         }
323         rc = json_object_set_new(context->root, name, value->root);
324         if (rc) {
325                 DBG_ERR("Unable to add object [%s]\n", name);
326                 context->error = true;
327         }
328 }
329
330 /*
331  * Output a version object
332  *
333  * "version":{"major":1,"minor":0}
334  *
335  */
336 static void add_version(struct json_context *context, int major, int minor)
337 {
338         struct json_context version = get_json_context();
339         add_int(&version, "major", major);
340         add_int(&version, "minor", minor);
341         add_object(context, "version", &version);
342 }
343
344 /*
345  * Output the current date and time as a timestamp in ISO 8601 format
346  *
347  * "timestamp":"2017-03-06T17:18:04.455081+1300"
348  *
349  */
350 static void add_timestamp(struct json_context *context)
351 {
352         char buffer[40];        /* formatted time less usec and timezone */
353         char timestamp[50];     /* the formatted ISO 8601 time stamp     */
354         char tz[10];            /* formatted time zone                   */
355         struct tm* tm_info;     /* current local time                    */
356         struct timeval tv;      /* current system time                   */
357         int r;                  /* response code from gettimeofday       */
358
359         if (context->error) {
360                 return;
361         }
362
363         r = gettimeofday(&tv, NULL);
364         if (r) {
365                 DBG_ERR("Unable to get time of day: (%d) %s\n",
366                         errno,
367                         strerror(errno));
368                 context->error = true;
369                 return;
370         }
371
372         tm_info = localtime(&tv.tv_sec);
373         if (tm_info == NULL) {
374                 DBG_ERR("Unable to determine local time\n");
375                 context->error = true;
376                 return;
377         }
378
379         strftime(buffer, sizeof(buffer)-1, "%Y-%m-%dT%T", tm_info);
380         strftime(tz, sizeof(tz)-1, "%z", tm_info);
381         snprintf(timestamp, sizeof(timestamp),"%s.%06ld%s",
382                  buffer, tv.tv_usec, tz);
383         add_string(context,"timestamp", timestamp);
384 }
385
386
387 /*
388  * Output an address pair, with name name.
389  *
390  * "localAddress":"ipv6::::0"
391  *
392  */
393 static void add_address(struct json_context *context,
394                         const char *name,
395                         const struct tsocket_address *address)
396 {
397         char *s = NULL;
398         TALLOC_CTX *frame = talloc_stackframe();
399
400         if (context->error) {
401                 return;
402         }
403
404         s = tsocket_address_string(address, frame);
405         add_string(context, name, s);
406         talloc_free(frame);
407
408 }
409
410 /*
411  * Output a SID with name name
412  *
413  * "sid":"S-1-5-18"
414  *
415  */
416 static void add_sid(struct json_context *context,
417                     const char *name,
418                     const struct dom_sid *sid)
419 {
420         char sid_buf[DOM_SID_STR_BUFLEN];
421
422         if (context->error) {
423                 return;
424         }
425
426         dom_sid_string_buf(sid, sid_buf, sizeof(sid_buf));
427         add_string(context, name, sid_buf);
428 }
429
430 /*
431  * Write a machine parsable json formatted authentication log entry.
432  *
433  * IF removing or changing the format/meaning of a field please update the
434  *    major version number AUTH_MAJOR
435  *
436  * IF adding a new field please update the minor version number AUTH_MINOR
437  *
438  *  To process the resulting log lines from the commend line use jq to
439  *  parse the json.
440  *
441  *  grep "JSON Authentication" log file |
442  *  sed 's;^[^{]*;;' |
443  * jq -rc  '"\(.timestamp)\t\(.Authentication.status)\t
444  *           \(.Authentication.clientDomain)\t
445  *           \(.Authentication.clientAccount)
446  *           \t\(.Authentication.workstation)
447  *           \t\(.Authentication.remoteAddress)
448  *           \t\(.Authentication.localAddress)"'
449  */
450 static void log_authentication_event_json(
451                         struct imessaging_context *msg_ctx,
452                         struct loadparm_context *lp_ctx,
453                         const struct auth_usersupplied_info *ui,
454                         NTSTATUS status,
455                         const char *domain_name,
456                         const char *account_name,
457                         const char *unix_username,
458                         struct dom_sid *sid,
459                         int debug_level)
460 {
461         struct json_context context = get_json_context();
462         struct json_context authentication;
463         char negotiate_flags[11];
464
465         add_timestamp(&context);
466         add_string(&context, "type", AUTH_JSON_TYPE);
467
468         authentication = get_json_context();
469         add_version(&authentication, AUTH_MAJOR, AUTH_MINOR);
470         add_string(&authentication, "status", nt_errstr(status));
471         add_address(&authentication, "localAddress", ui->local_host);
472         add_address(&authentication, "remoteAddress", ui->remote_host);
473         add_string(&authentication,
474                    "serviceDescription",
475                    ui->service_description);
476         add_string(&authentication, "authDescription", ui->auth_description);
477         add_string(&authentication, "clientDomain", ui->client.domain_name);
478         add_string(&authentication, "clientAccount", ui->client.account_name);
479         add_string(&authentication, "workstation", ui->workstation_name);
480         add_string(&authentication, "becameAccount", account_name);
481         add_string(&authentication, "becameDomain", domain_name);
482         add_sid(&authentication, "becameSid", sid);
483         add_string(&authentication, "mappedAccount", ui->mapped.account_name);
484         add_string(&authentication, "mappedDomain", ui->mapped.domain_name);
485         add_string(&authentication,
486                    "netlogonComputer",
487                    ui->netlogon_trust_account.computer_name);
488         add_string(&authentication,
489                    "netlogonTrustAccount",
490                    ui->netlogon_trust_account.account_name);
491         snprintf(negotiate_flags,
492                  sizeof( negotiate_flags),
493                  "0x%08X",
494                  ui->netlogon_trust_account.negotiate_flags);
495         add_string(&authentication, "netlogonNegotiateFlags", negotiate_flags);
496         add_int(&authentication,
497                 "netlogonSecureChannelType",
498                 ui->netlogon_trust_account.secure_channel_type);
499         add_sid(&authentication,
500                 "netlogonTrustAccountSid",
501                 ui->netlogon_trust_account.sid);
502         add_string(&authentication, "passwordType", get_password_type(ui));
503         add_object(&context,AUTH_JSON_TYPE, &authentication);
504
505         log_json(msg_ctx, &context, AUTH_JSON_TYPE, DBGC_AUTH_AUDIT, debug_level);
506         free_json_context(&context);
507 }
508
509 /*
510  * Log details of a successful authorization to a service,
511  * in a machine parsable json format
512  *
513  * IF removing or changing the format/meaning of a field please update the
514  *    major version number AUTHZ_MAJOR
515  *
516  * IF adding a new field please update the minor version number AUTHZ_MINOR
517  *
518  *  To process the resulting log lines from the commend line use jq to
519  *  parse the json.
520  *
521  *  grep "JSON Authentication" log_file |\
522  *  sed "s;^[^{]*;;" |\
523  *  jq -rc '"\(.timestamp)\t
524  *           \(.Authorization.domain)\t
525  *           \(.Authorization.account)\t
526  *           \(.Authorization.remoteAddress)"'
527  *
528  */
529 static void log_successful_authz_event_json(
530                                 struct imessaging_context *msg_ctx,
531                                 struct loadparm_context *lp_ctx,
532                                 const struct tsocket_address *remote,
533                                 const struct tsocket_address *local,
534                                 const char *service_description,
535                                 const char *auth_type,
536                                 const char *transport_protection,
537                                 struct auth_session_info *session_info,
538                                 int debug_level)
539 {
540         struct json_context context = get_json_context();
541         struct json_context authorization;
542         char account_flags[11];
543
544         //start_object(&context, NULL);
545         add_timestamp(&context);
546         add_string(&context, "type", AUTHZ_JSON_TYPE);
547         authorization = get_json_context();
548         add_version(&authorization, AUTHZ_MAJOR, AUTHZ_MINOR);
549         add_address(&authorization, "localAddress", local);
550         add_address(&authorization, "remoteAddress", remote);
551         add_string(&authorization, "serviceDescription", service_description);
552         add_string(&authorization, "authType", auth_type);
553         add_string(&authorization, "domain", session_info->info->domain_name);
554         add_string(&authorization, "account", session_info->info->account_name);
555         add_sid(&authorization, "sid", &session_info->security_token->sids[0]);
556         add_string(&authorization,
557                    "logonServer",
558                    session_info->info->logon_server);
559         add_string(&authorization, "transportProtection", transport_protection);
560
561         snprintf(account_flags,
562                  sizeof(account_flags),
563                  "0x%08X",
564                  session_info->info->acct_flags);
565         add_string(&authorization, "accountFlags", account_flags);
566         add_object(&context,AUTHZ_JSON_TYPE, &authorization);
567
568         log_json(msg_ctx,
569                  &context,
570                  AUTHZ_JSON_TYPE,
571                  DBGC_AUTH_AUDIT,
572                  debug_level);
573         free_json_context(&context);
574 }
575
576 #else
577
578 static void log_no_json(struct imessaging_context *msg_ctx,
579                         struct loadparm_context *lp_ctx)
580 {
581         if (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx)) {
582                 static bool auth_event_logged = false;
583                 if (auth_event_logged == false) {
584                         auth_event_logged = true;
585                         DBG_ERR("auth event notification = true but Samba was not compiled with jansson\n");
586                 }
587         } else {
588                 static bool json_logged = false;
589                 if (json_logged == false) {
590                         json_logged = true;
591                         DBG_NOTICE("JSON auth logs not available unless compiled with jansson\n");
592                 }
593         }
594
595         return;
596 }
597
598 static void log_authentication_event_json(
599                         struct imessaging_context *msg_ctx,
600                         struct loadparm_context *lp_ctx,
601                         const struct auth_usersupplied_info *ui,
602                         NTSTATUS status,
603                         const char *domain_name,
604                         const char *account_name,
605                         const char *unix_username,
606                         struct dom_sid *sid,
607                         int debug_level)
608 {
609         log_no_json(msg_ctx, lp_ctx);
610         return;
611 }
612
613 static void log_successful_authz_event_json(
614                                 struct imessaging_context *msg_ctx,
615                                 struct loadparm_context *lp_ctx,
616                                 const struct tsocket_address *remote,
617                                 const struct tsocket_address *local,
618                                 const char *service_description,
619                                 const char *auth_type,
620                                 const char *transport_protection,
621                                 struct auth_session_info *session_info,
622                                 int debug_level)
623 {
624         log_no_json(msg_ctx, lp_ctx);
625         return;
626 }
627
628 #endif
629
630 /*
631  * Determine the type of the password supplied for the
632  * authorisation attempt.
633  *
634  */
635 static const char* get_password_type(const struct auth_usersupplied_info *ui)
636 {
637
638         const char *password_type = NULL;
639
640         if (ui->password_type != NULL) {
641                 password_type = ui->password_type;
642         } else if (ui->password_state == AUTH_PASSWORD_RESPONSE &&
643                    (ui->logon_parameters & MSV1_0_ALLOW_MSVCHAPV2) &&
644                    ui->password.response.nt.length == 24) {
645                 password_type = "MSCHAPv2";
646         } else if ((ui->logon_parameters & MSV1_0_CLEARTEXT_PASSWORD_SUPPLIED)
647                    || (ui->password_state == AUTH_PASSWORD_PLAIN)) {
648                 password_type = "Plaintext";
649         } else if (ui->password_state == AUTH_PASSWORD_HASH) {
650                 password_type = "Supplied-NT-Hash";
651         } else if (ui->password_state == AUTH_PASSWORD_RESPONSE
652                    && ui->password.response.nt.length > 24) {
653                 password_type = "NTLMv2";
654         } else if (ui->password_state == AUTH_PASSWORD_RESPONSE
655                    && ui->password.response.nt.length == 24) {
656                 password_type = "NTLMv1";
657         } else if (ui->password_state == AUTH_PASSWORD_RESPONSE
658                    && ui->password.response.lanman.length == 24) {
659                 password_type = "LANMan";
660         } else if (ui->password_state == AUTH_PASSWORD_RESPONSE
661                    && ui->password.response.nt.length == 0
662                    && ui->password.response.lanman.length == 0) {
663                 password_type = "No-Password";
664         }
665         return password_type;
666 }
667
668 /*
669  * Write a human readable authentication log entry.
670  *
671  */
672 static void log_authentication_event_human_readable(
673                         const struct auth_usersupplied_info *ui,
674                         NTSTATUS status,
675                         const char *domain_name,
676                         const char *account_name,
677                         const char *unix_username,
678                         struct dom_sid *sid,
679                         int debug_level)
680 {
681         TALLOC_CTX *frame = NULL;
682
683         const char *ts = NULL;             /* formatted current time      */
684         char *remote = NULL;               /* formatted remote host       */
685         char *local = NULL;                /* formatted local host        */
686         char *nl = NULL;                   /* NETLOGON details if present */
687         char *trust_computer_name = NULL;
688         char *trust_account_name = NULL;
689         char *logon_line = NULL;
690         const char *password_type = NULL;
691
692         frame = talloc_stackframe();
693
694         password_type = get_password_type(ui);
695         /* Get the current time */
696         ts = get_timestamp(frame);
697
698         /* Only log the NETLOGON details if they are present */
699         if (ui->netlogon_trust_account.computer_name ||
700             ui->netlogon_trust_account.account_name) {
701                 trust_computer_name = log_escape(frame,
702                         ui->netlogon_trust_account.computer_name);
703                 trust_account_name  = log_escape(frame,
704                         ui->netlogon_trust_account.account_name);
705                 nl = talloc_asprintf(frame,
706                         " NETLOGON computer [%s] trust account [%s]",
707                         trust_computer_name, trust_account_name);
708         }
709
710         remote = tsocket_address_string(ui->remote_host, frame);
711         local = tsocket_address_string(ui->local_host, frame);
712
713         if (NT_STATUS_IS_OK(status)) {
714                 char sid_buf[DOM_SID_STR_BUFLEN];
715
716                 dom_sid_string_buf(sid, sid_buf, sizeof(sid_buf));
717                 logon_line = talloc_asprintf(frame,
718                                              " became [%s]\\[%s] [%s].",
719                                              log_escape(frame, domain_name),
720                                              log_escape(frame, account_name),
721                                              sid_buf);
722         } else {
723                 logon_line = talloc_asprintf(
724                                 frame,
725                                 " mapped to [%s]\\[%s].",
726                                 log_escape(frame, ui->mapped.domain_name),
727                                 log_escape(frame, ui->mapped.account_name));
728         }
729
730         DEBUGC(DBGC_AUTH_AUDIT, debug_level,
731                ("Auth: [%s,%s] user [%s]\\[%s]"
732                 " at [%s] with [%s] status [%s]"
733                 " workstation [%s] remote host [%s]"
734                 "%s local host [%s]"
735                 " %s\n",
736                 ui->service_description,
737                 ui->auth_description,
738                 log_escape(frame, ui->client.domain_name),
739                 log_escape(frame, ui->client.account_name),
740                 ts,
741                 password_type,
742                 nt_errstr(status),
743                 log_escape(frame, ui->workstation_name),
744                 remote,
745                 logon_line,
746                 local,
747                 nl ? nl : ""
748                ));
749
750         talloc_free(frame);
751 }
752
753 /*
754  * Log details of an authentication attempt.
755  * Successful and unsuccessful attempts are logged.
756  *
757  * NOTE: msg_ctx and lp_ctx is optional, but when supplied allows streaming the
758  * authentication events over the message bus.
759  */
760 void log_authentication_event(struct imessaging_context *msg_ctx,
761                               struct loadparm_context *lp_ctx,
762                               const struct auth_usersupplied_info *ui,
763                               NTSTATUS status,
764                               const char *domain_name,
765                               const char *account_name,
766                               const char *unix_username,
767                               struct dom_sid *sid)
768 {
769         /* set the log level */
770         int debug_level = AUTH_FAILURE_LEVEL;
771
772         if (NT_STATUS_IS_OK(status)) {
773                 debug_level = AUTH_SUCCESS_LEVEL;
774                 if (dom_sid_equal(sid, &global_sid_Anonymous)) {
775                         debug_level = AUTH_ANONYMOUS_LEVEL;
776                 }
777         }
778
779         if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT, debug_level)) {
780                 log_authentication_event_human_readable(ui,
781                                                         status,
782                                                         domain_name,
783                                                         account_name,
784                                                         unix_username,
785                                                         sid,
786                                                         debug_level);
787         }
788         if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT_JSON, debug_level) ||
789             (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx))) {
790                 log_authentication_event_json(msg_ctx, lp_ctx,
791                                               ui,
792                                               status,
793                                               domain_name,
794                                               account_name,
795                                               unix_username,
796                                               sid,
797                                               debug_level);
798         }
799 }
800
801
802
803 /*
804  * Log details of a successful authorization to a service,
805  * in a human readable format.
806  *
807  */
808 static void log_successful_authz_event_human_readable(
809                                 const struct tsocket_address *remote,
810                                 const struct tsocket_address *local,
811                                 const char *service_description,
812                                 const char *auth_type,
813                                 const char *transport_protection,
814                                 struct auth_session_info *session_info,
815                                 int debug_level)
816 {
817         TALLOC_CTX *frame = NULL;
818
819         const char *ts = NULL;       /* formatted current time      */
820         char *remote_str = NULL;     /* formatted remote host       */
821         char *local_str = NULL;      /* formatted local host        */
822         char sid_buf[DOM_SID_STR_BUFLEN];
823
824         frame = talloc_stackframe();
825
826         /* Get the current time */
827         ts = get_timestamp(frame);
828
829         remote_str = tsocket_address_string(remote, frame);
830         local_str = tsocket_address_string(local, frame);
831
832         dom_sid_string_buf(&session_info->security_token->sids[0],
833                            sid_buf,
834                            sizeof(sid_buf));
835
836         DEBUGC(DBGC_AUTH_AUDIT, debug_level,
837                ("Successful AuthZ: [%s,%s] user [%s]\\[%s] [%s]"
838                 " at [%s]"
839                 " Remote host [%s]"
840                 " local host [%s]\n",
841                 service_description,
842                 auth_type,
843                 log_escape(frame, session_info->info->domain_name),
844                 log_escape(frame, session_info->info->account_name),
845                 sid_buf,
846                 ts,
847                 remote_str,
848                 local_str));
849
850         talloc_free(frame);
851 }
852
853 /*
854  * Log details of a successful authorization to a service.
855  *
856  * Only successful authorizations are logged.  For clarity:
857  * - NTLM bad passwords will be recorded by log_authentication_event
858  * - Kerberos decrypt failures need to be logged in gensec_gssapi et al
859  *
860  * The service may later refuse authorization due to an ACL.
861  *
862  * NOTE: msg_ctx and lp_ctx is optional, but when supplied allows streaming the
863  * authentication events over the message bus.
864  */
865 void log_successful_authz_event(struct imessaging_context *msg_ctx,
866                                 struct loadparm_context *lp_ctx,
867                                 const struct tsocket_address *remote,
868                                 const struct tsocket_address *local,
869                                 const char *service_description,
870                                 const char *auth_type,
871                                 const char *transport_protection,
872                                 struct auth_session_info *session_info)
873 {
874         int debug_level = AUTHZ_SUCCESS_LEVEL;
875
876         /* set the log level */
877         if (security_token_is_anonymous(session_info->security_token)) {
878                 debug_level = AUTH_ANONYMOUS_LEVEL;
879         }
880
881         if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT, debug_level)) {
882                 log_successful_authz_event_human_readable(remote,
883                                                           local,
884                                                           service_description,
885                                                           auth_type,
886                                                           transport_protection,
887                                                           session_info,
888                                                           debug_level);
889         }
890         if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT_JSON, debug_level) ||
891             (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx))) {
892                 log_successful_authz_event_json(msg_ctx, lp_ctx,
893                                                 remote,
894                                                 local,
895                                                 service_description,
896                                                 auth_type,
897                                                 transport_protection,
898                                                 session_info,
899                                                 debug_level);
900         }
901 }