smbXsrv_session: add smbXsrv_session_create_auth()
[gd/samba-autobuild/.git] / source3 / smbd / smbXsrv_session.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Stefan Metzmacher 2011-2012
5    Copyright (C) Michael Adam 2012
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 #include "includes.h"
22 #include "system/filesys.h"
23 #include <tevent.h>
24 #include "smbd/smbd.h"
25 #include "smbd/globals.h"
26 #include "dbwrap/dbwrap.h"
27 #include "dbwrap/dbwrap_rbt.h"
28 #include "dbwrap/dbwrap_open.h"
29 #include "dbwrap/dbwrap_watch.h"
30 #include "session.h"
31 #include "auth.h"
32 #include "auth/gensec/gensec.h"
33 #include "../lib/tsocket/tsocket.h"
34 #include "../libcli/security/security.h"
35 #include "messages.h"
36 #include "lib/util/util_tdb.h"
37 #include "librpc/gen_ndr/ndr_smbXsrv.h"
38 #include "serverid.h"
39 #include "lib/util/tevent_ntstatus.h"
40
41 struct smbXsrv_session_table {
42         struct {
43                 struct db_context *db_ctx;
44                 uint32_t lowest_id;
45                 uint32_t highest_id;
46                 uint32_t max_sessions;
47                 uint32_t num_sessions;
48         } local;
49         struct {
50                 struct db_context *db_ctx;
51         } global;
52 };
53
54 static struct db_context *smbXsrv_session_global_db_ctx = NULL;
55
56 NTSTATUS smbXsrv_session_global_init(void)
57 {
58         char *global_path = NULL;
59         struct db_context *db_ctx = NULL;
60
61         if (smbXsrv_session_global_db_ctx != NULL) {
62                 return NT_STATUS_OK;
63         }
64
65         /*
66          * This contains secret information like session keys!
67          */
68         global_path = lock_path("smbXsrv_session_global.tdb");
69         if (global_path == NULL) {
70                 return NT_STATUS_NO_MEMORY;
71         }
72
73         db_ctx = db_open(NULL, global_path,
74                          0, /* hash_size */
75                          TDB_DEFAULT |
76                          TDB_CLEAR_IF_FIRST |
77                          TDB_INCOMPATIBLE_HASH,
78                          O_RDWR | O_CREAT, 0600,
79                          DBWRAP_LOCK_ORDER_1,
80                          DBWRAP_FLAG_NONE);
81         TALLOC_FREE(global_path);
82         if (db_ctx == NULL) {
83                 NTSTATUS status;
84
85                 status = map_nt_error_from_unix_common(errno);
86
87                 return status;
88         }
89
90         smbXsrv_session_global_db_ctx = db_ctx;
91
92         return NT_STATUS_OK;
93 }
94
95 /*
96  * NOTE:
97  * We need to store the keys in big endian so that dbwrap_rbt's memcmp
98  * has the same result as integer comparison between the uint32_t
99  * values.
100  *
101  * TODO: implement string based key
102  */
103
104 #define SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE sizeof(uint32_t)
105
106 static TDB_DATA smbXsrv_session_global_id_to_key(uint32_t id,
107                                                  uint8_t *key_buf)
108 {
109         TDB_DATA key;
110
111         RSIVAL(key_buf, 0, id);
112
113         key = make_tdb_data(key_buf, SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE);
114
115         return key;
116 }
117
118 #if 0
119 static NTSTATUS smbXsrv_session_global_key_to_id(TDB_DATA key, uint32_t *id)
120 {
121         if (id == NULL) {
122                 return NT_STATUS_INVALID_PARAMETER;
123         }
124
125         if (key.dsize != SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE) {
126                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
127         }
128
129         *id = RIVAL(key.dptr, 0);
130
131         return NT_STATUS_OK;
132 }
133 #endif
134
135 #define SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE sizeof(uint32_t)
136
137 static TDB_DATA smbXsrv_session_local_id_to_key(uint32_t id,
138                                                 uint8_t *key_buf)
139 {
140         TDB_DATA key;
141
142         RSIVAL(key_buf, 0, id);
143
144         key = make_tdb_data(key_buf, SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE);
145
146         return key;
147 }
148
149 static NTSTATUS smbXsrv_session_local_key_to_id(TDB_DATA key, uint32_t *id)
150 {
151         if (id == NULL) {
152                 return NT_STATUS_INVALID_PARAMETER;
153         }
154
155         if (key.dsize != SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE) {
156                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
157         }
158
159         *id = RIVAL(key.dptr, 0);
160
161         return NT_STATUS_OK;
162 }
163
164 static void smbXsrv_session_close_loop(struct tevent_req *subreq);
165
166 static NTSTATUS smbXsrv_session_table_init(struct smbXsrv_connection *conn,
167                                            uint32_t lowest_id,
168                                            uint32_t highest_id,
169                                            uint32_t max_sessions)
170 {
171         struct smbXsrv_client *client = conn->client;
172         struct smbXsrv_session_table *table;
173         NTSTATUS status;
174         struct tevent_req *subreq;
175         uint64_t max_range;
176
177         if (lowest_id > highest_id) {
178                 return NT_STATUS_INTERNAL_ERROR;
179         }
180
181         max_range = highest_id;
182         max_range -= lowest_id;
183         max_range += 1;
184
185         if (max_sessions > max_range) {
186                 return NT_STATUS_INTERNAL_ERROR;
187         }
188
189         table = talloc_zero(client, struct smbXsrv_session_table);
190         if (table == NULL) {
191                 return NT_STATUS_NO_MEMORY;
192         }
193
194         table->local.db_ctx = db_open_rbt(table);
195         if (table->local.db_ctx == NULL) {
196                 TALLOC_FREE(table);
197                 return NT_STATUS_NO_MEMORY;
198         }
199         table->local.lowest_id = lowest_id;
200         table->local.highest_id = highest_id;
201         table->local.max_sessions = max_sessions;
202
203         status = smbXsrv_session_global_init();
204         if (!NT_STATUS_IS_OK(status)) {
205                 TALLOC_FREE(table);
206                 return status;
207         }
208
209         table->global.db_ctx = smbXsrv_session_global_db_ctx;
210
211         dbwrap_watch_db(table->global.db_ctx, client->msg_ctx);
212
213         subreq = messaging_read_send(table, client->ev_ctx, client->msg_ctx,
214                                      MSG_SMBXSRV_SESSION_CLOSE);
215         if (subreq == NULL) {
216                 TALLOC_FREE(table);
217                 return NT_STATUS_NO_MEMORY;
218         }
219         tevent_req_set_callback(subreq, smbXsrv_session_close_loop, client);
220
221         client->session_table = table;
222         return NT_STATUS_OK;
223 }
224
225 static void smbXsrv_session_close_shutdown_done(struct tevent_req *subreq);
226
227 static void smbXsrv_session_close_loop(struct tevent_req *subreq)
228 {
229         struct smbXsrv_client *client =
230                 tevent_req_callback_data(subreq,
231                 struct smbXsrv_client);
232         struct smbXsrv_session_table *table = client->session_table;
233         int ret;
234         struct messaging_rec *rec = NULL;
235         struct smbXsrv_session_closeB close_blob;
236         enum ndr_err_code ndr_err;
237         struct smbXsrv_session_close0 *close_info0 = NULL;
238         struct smbXsrv_session *session = NULL;
239         NTSTATUS status;
240         struct timeval tv = timeval_current();
241         NTTIME now = timeval_to_nttime(&tv);
242
243         ret = messaging_read_recv(subreq, talloc_tos(), &rec);
244         TALLOC_FREE(subreq);
245         if (ret != 0) {
246                 goto next;
247         }
248
249         ndr_err = ndr_pull_struct_blob(&rec->buf, rec, &close_blob,
250                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_session_closeB);
251         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
252                 status = ndr_map_error2ntstatus(ndr_err);
253                 DEBUG(1,("smbXsrv_session_close_loop: "
254                          "ndr_pull_struct_blob - %s\n",
255                          nt_errstr(status)));
256                 goto next;
257         }
258
259         DEBUG(10,("smbXsrv_session_close_loop: MSG_SMBXSRV_SESSION_CLOSE\n"));
260         if (DEBUGLVL(10)) {
261                 NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
262         }
263
264         if (close_blob.version != SMBXSRV_VERSION_0) {
265                 DEBUG(0,("smbXsrv_session_close_loop: "
266                          "ignore invalid version %u\n", close_blob.version));
267                 NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
268                 goto next;
269         }
270
271         close_info0 = close_blob.info.info0;
272         if (close_info0 == NULL) {
273                 DEBUG(0,("smbXsrv_session_close_loop: "
274                          "ignore NULL info %u\n", close_blob.version));
275                 NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
276                 goto next;
277         }
278
279         status = smb2srv_session_lookup_client(client,
280                                                close_info0->old_session_wire_id,
281                                                now, &session);
282         if (NT_STATUS_EQUAL(status, NT_STATUS_USER_SESSION_DELETED)) {
283                 DEBUG(4,("smbXsrv_session_close_loop: "
284                          "old_session_wire_id %llu not found\n",
285                          (unsigned long long)close_info0->old_session_wire_id));
286                 if (DEBUGLVL(4)) {
287                         NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
288                 }
289                 goto next;
290         }
291         if (!NT_STATUS_IS_OK(status) &&
292             !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) &&
293             !NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)) {
294                 DEBUG(1,("smbXsrv_session_close_loop: "
295                          "old_session_wire_id %llu - %s\n",
296                          (unsigned long long)close_info0->old_session_wire_id,
297                          nt_errstr(status)));
298                 if (DEBUGLVL(1)) {
299                         NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
300                 }
301                 goto next;
302         }
303
304         if (session->global->session_global_id != close_info0->old_session_global_id) {
305                 DEBUG(1,("smbXsrv_session_close_loop: "
306                          "old_session_wire_id %llu - global %u != %u\n",
307                          (unsigned long long)close_info0->old_session_wire_id,
308                          session->global->session_global_id,
309                          close_info0->old_session_global_id));
310                 if (DEBUGLVL(1)) {
311                         NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
312                 }
313                 goto next;
314         }
315
316         if (session->global->creation_time != close_info0->old_creation_time) {
317                 DEBUG(1,("smbXsrv_session_close_loop: "
318                          "old_session_wire_id %llu - "
319                          "creation %s (%llu) != %s (%llu)\n",
320                          (unsigned long long)close_info0->old_session_wire_id,
321                          nt_time_string(rec, session->global->creation_time),
322                          (unsigned long long)session->global->creation_time,
323                          nt_time_string(rec, close_info0->old_creation_time),
324                          (unsigned long long)close_info0->old_creation_time));
325                 if (DEBUGLVL(1)) {
326                         NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
327                 }
328                 goto next;
329         }
330
331         subreq = smb2srv_session_shutdown_send(session, client->ev_ctx,
332                                                session, NULL);
333         if (subreq == NULL) {
334                 status = NT_STATUS_NO_MEMORY;
335                 DEBUG(0, ("smbXsrv_session_close_loop: "
336                           "smb2srv_session_shutdown_send(%llu) failed: %s\n",
337                           (unsigned long long)session->global->session_wire_id,
338                           nt_errstr(status)));
339                 if (DEBUGLVL(1)) {
340                         NDR_PRINT_DEBUG(smbXsrv_session_closeB, &close_blob);
341                 }
342                 goto next;
343         }
344         tevent_req_set_callback(subreq,
345                                 smbXsrv_session_close_shutdown_done,
346                                 session);
347
348 next:
349         TALLOC_FREE(rec);
350
351         subreq = messaging_read_send(table, client->ev_ctx, client->msg_ctx,
352                                      MSG_SMBXSRV_SESSION_CLOSE);
353         if (subreq == NULL) {
354                 const char *r;
355                 r = "messaging_read_send(MSG_SMBXSRV_SESSION_CLOSE) failed";
356                 exit_server_cleanly(r);
357                 return;
358         }
359         tevent_req_set_callback(subreq, smbXsrv_session_close_loop, client);
360 }
361
362 static void smbXsrv_session_close_shutdown_done(struct tevent_req *subreq)
363 {
364         struct smbXsrv_session *session =
365                 tevent_req_callback_data(subreq,
366                 struct smbXsrv_session);
367         NTSTATUS status;
368
369         status = smb2srv_session_shutdown_recv(subreq);
370         TALLOC_FREE(subreq);
371         if (!NT_STATUS_IS_OK(status)) {
372                 DEBUG(0, ("smbXsrv_session_close_loop: "
373                           "smb2srv_session_shutdown_recv(%llu) failed: %s\n",
374                           (unsigned long long)session->global->session_wire_id,
375                           nt_errstr(status)));
376         }
377
378         status = smbXsrv_session_logoff(session);
379         if (!NT_STATUS_IS_OK(status)) {
380                 DEBUG(0, ("smbXsrv_session_close_loop: "
381                           "smbXsrv_session_logoff(%llu) failed: %s\n",
382                           (unsigned long long)session->global->session_wire_id,
383                           nt_errstr(status)));
384         }
385
386         TALLOC_FREE(session);
387 }
388
389 struct smb1srv_session_local_allocate_state {
390         const uint32_t lowest_id;
391         const uint32_t highest_id;
392         uint32_t last_id;
393         uint32_t useable_id;
394         NTSTATUS status;
395 };
396
397 static int smb1srv_session_local_allocate_traverse(struct db_record *rec,
398                                                    void *private_data)
399 {
400         struct smb1srv_session_local_allocate_state *state =
401                 (struct smb1srv_session_local_allocate_state *)private_data;
402         TDB_DATA key = dbwrap_record_get_key(rec);
403         uint32_t id = 0;
404         NTSTATUS status;
405
406         status = smbXsrv_session_local_key_to_id(key, &id);
407         if (!NT_STATUS_IS_OK(status)) {
408                 state->status = status;
409                 return -1;
410         }
411
412         if (id <= state->last_id) {
413                 state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
414                 return -1;
415         }
416         state->last_id = id;
417
418         if (id > state->useable_id) {
419                 state->status = NT_STATUS_OK;
420                 return -1;
421         }
422
423         if (state->useable_id == state->highest_id) {
424                 state->status = NT_STATUS_INSUFFICIENT_RESOURCES;
425                 return -1;
426         }
427
428         state->useable_id +=1;
429         return 0;
430 }
431
432 static NTSTATUS smb1srv_session_local_allocate_id(struct db_context *db,
433                                                   uint32_t lowest_id,
434                                                   uint32_t highest_id,
435                                                   TALLOC_CTX *mem_ctx,
436                                                   struct db_record **_rec,
437                                                   uint32_t *_id)
438 {
439         struct smb1srv_session_local_allocate_state state = {
440                 .lowest_id = lowest_id,
441                 .highest_id = highest_id,
442                 .last_id = 0,
443                 .useable_id = lowest_id,
444                 .status = NT_STATUS_INTERNAL_ERROR,
445         };
446         uint32_t i;
447         uint32_t range;
448         NTSTATUS status;
449         int count = 0;
450
451         *_rec = NULL;
452         *_id = 0;
453
454         if (lowest_id > highest_id) {
455                 return NT_STATUS_INSUFFICIENT_RESOURCES;
456         }
457
458         /*
459          * first we try randomly
460          */
461         range = (highest_id - lowest_id) + 1;
462
463         for (i = 0; i < (range / 2); i++) {
464                 uint32_t id;
465                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
466                 TDB_DATA key;
467                 TDB_DATA val;
468                 struct db_record *rec = NULL;
469
470                 id = generate_random() % range;
471                 id += lowest_id;
472
473                 if (id < lowest_id) {
474                         id = lowest_id;
475                 }
476                 if (id > highest_id) {
477                         id = highest_id;
478                 }
479
480                 key = smbXsrv_session_local_id_to_key(id, key_buf);
481
482                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
483                 if (rec == NULL) {
484                         return NT_STATUS_INSUFFICIENT_RESOURCES;
485                 }
486
487                 val = dbwrap_record_get_value(rec);
488                 if (val.dsize != 0) {
489                         TALLOC_FREE(rec);
490                         continue;
491                 }
492
493                 *_rec = rec;
494                 *_id = id;
495                 return NT_STATUS_OK;
496         }
497
498         /*
499          * if the range is almost full,
500          * we traverse the whole table
501          * (this relies on sorted behavior of dbwrap_rbt)
502          */
503         status = dbwrap_traverse_read(db, smb1srv_session_local_allocate_traverse,
504                                       &state, &count);
505         if (NT_STATUS_IS_OK(status)) {
506                 if (NT_STATUS_IS_OK(state.status)) {
507                         return NT_STATUS_INTERNAL_ERROR;
508                 }
509
510                 if (!NT_STATUS_EQUAL(state.status, NT_STATUS_INTERNAL_ERROR)) {
511                         return state.status;
512                 }
513
514                 if (state.useable_id <= state.highest_id) {
515                         state.status = NT_STATUS_OK;
516                 } else {
517                         return NT_STATUS_INSUFFICIENT_RESOURCES;
518                 }
519         } else if (!NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_DB_CORRUPTION)) {
520                 /*
521                  * Here we really expect NT_STATUS_INTERNAL_DB_CORRUPTION!
522                  *
523                  * If we get anything else it is an error, because it
524                  * means we did not manage to find a free slot in
525                  * the db.
526                  */
527                 return NT_STATUS_INSUFFICIENT_RESOURCES;
528         }
529
530         if (NT_STATUS_IS_OK(state.status)) {
531                 uint32_t id;
532                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
533                 TDB_DATA key;
534                 TDB_DATA val;
535                 struct db_record *rec = NULL;
536
537                 id = state.useable_id;
538
539                 key = smbXsrv_session_local_id_to_key(id, key_buf);
540
541                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
542                 if (rec == NULL) {
543                         return NT_STATUS_INSUFFICIENT_RESOURCES;
544                 }
545
546                 val = dbwrap_record_get_value(rec);
547                 if (val.dsize != 0) {
548                         TALLOC_FREE(rec);
549                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
550                 }
551
552                 *_rec = rec;
553                 *_id = id;
554                 return NT_STATUS_OK;
555         }
556
557         return state.status;
558 }
559
560 struct smbXsrv_session_local_fetch_state {
561         struct smbXsrv_session *session;
562         NTSTATUS status;
563 };
564
565 static void smbXsrv_session_local_fetch_parser(TDB_DATA key, TDB_DATA data,
566                                                void *private_data)
567 {
568         struct smbXsrv_session_local_fetch_state *state =
569                 (struct smbXsrv_session_local_fetch_state *)private_data;
570         void *ptr;
571
572         if (data.dsize != sizeof(ptr)) {
573                 state->status = NT_STATUS_INTERNAL_DB_ERROR;
574                 return;
575         }
576
577         memcpy(&ptr, data.dptr, data.dsize);
578         state->session = talloc_get_type_abort(ptr, struct smbXsrv_session);
579         state->status = NT_STATUS_OK;
580 }
581
582 static NTSTATUS smbXsrv_session_local_lookup(struct smbXsrv_session_table *table,
583                                              /* conn: optional */
584                                              struct smbXsrv_connection *conn,
585                                              uint32_t session_local_id,
586                                              NTTIME now,
587                                              struct smbXsrv_session **_session)
588 {
589         struct smbXsrv_session_local_fetch_state state = {
590                 .session = NULL,
591                 .status = NT_STATUS_INTERNAL_ERROR,
592         };
593         uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
594         TDB_DATA key;
595         NTSTATUS status;
596
597         *_session = NULL;
598
599         if (session_local_id == 0) {
600                 return NT_STATUS_USER_SESSION_DELETED;
601         }
602
603         if (table == NULL) {
604                 /* this might happen before the end of negprot */
605                 return NT_STATUS_USER_SESSION_DELETED;
606         }
607
608         if (table->local.db_ctx == NULL) {
609                 return NT_STATUS_INTERNAL_ERROR;
610         }
611
612         key = smbXsrv_session_local_id_to_key(session_local_id, key_buf);
613
614         status = dbwrap_parse_record(table->local.db_ctx, key,
615                                      smbXsrv_session_local_fetch_parser,
616                                      &state);
617         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
618                 return NT_STATUS_USER_SESSION_DELETED;
619         } else if (!NT_STATUS_IS_OK(status)) {
620                 return status;
621         }
622         if (!NT_STATUS_IS_OK(state.status)) {
623                 return state.status;
624         }
625
626         if (NT_STATUS_EQUAL(state.session->status, NT_STATUS_USER_SESSION_DELETED)) {
627                 return NT_STATUS_USER_SESSION_DELETED;
628         }
629
630         /*
631          * If a connection is specified check if the session is
632          * valid on the channel.
633          */
634         if (conn != NULL) {
635                 struct smbXsrv_channel_global0 *c = NULL;
636
637                 status = smbXsrv_session_find_channel(state.session, conn, &c);
638                 if (!NT_STATUS_IS_OK(status)) {
639                         return status;
640                 }
641         }
642
643         state.session->idle_time = now;
644
645         if (!NT_STATUS_IS_OK(state.session->status)) {
646                 *_session = state.session;
647                 return state.session->status;
648         }
649
650         if (now > state.session->global->expiration_time) {
651                 state.session->status = NT_STATUS_NETWORK_SESSION_EXPIRED;
652         }
653
654         *_session = state.session;
655         return state.session->status;
656 }
657
658 static int smbXsrv_session_global_destructor(struct smbXsrv_session_global0 *global)
659 {
660         return 0;
661 }
662
663 static void smbXsrv_session_global_verify_record(struct db_record *db_rec,
664                                         bool *is_free,
665                                         bool *was_free,
666                                         TALLOC_CTX *mem_ctx,
667                                         struct smbXsrv_session_global0 **_g);
668
669 static NTSTATUS smbXsrv_session_global_allocate(struct db_context *db,
670                                         TALLOC_CTX *mem_ctx,
671                                         struct smbXsrv_session_global0 **_global)
672 {
673         uint32_t i;
674         struct smbXsrv_session_global0 *global = NULL;
675         uint32_t last_free = 0;
676         const uint32_t min_tries = 3;
677
678         *_global = NULL;
679
680         global = talloc_zero(mem_ctx, struct smbXsrv_session_global0);
681         if (global == NULL) {
682                 return NT_STATUS_NO_MEMORY;
683         }
684         talloc_set_destructor(global, smbXsrv_session_global_destructor);
685
686         /*
687          * Here we just randomly try the whole 32-bit space
688          *
689          * We use just 32-bit, because we want to reuse the
690          * ID for SRVSVC.
691          */
692         for (i = 0; i < UINT32_MAX; i++) {
693                 bool is_free = false;
694                 bool was_free = false;
695                 uint32_t id;
696                 uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
697                 TDB_DATA key;
698
699                 if (i >= min_tries && last_free != 0) {
700                         id = last_free;
701                 } else {
702                         id = generate_random();
703                 }
704                 if (id == 0) {
705                         id++;
706                 }
707                 if (id == UINT32_MAX) {
708                         id--;
709                 }
710
711                 key = smbXsrv_session_global_id_to_key(id, key_buf);
712
713                 global->db_rec = dbwrap_fetch_locked(db, mem_ctx, key);
714                 if (global->db_rec == NULL) {
715                         talloc_free(global);
716                         return NT_STATUS_INSUFFICIENT_RESOURCES;
717                 }
718
719                 smbXsrv_session_global_verify_record(global->db_rec,
720                                                      &is_free,
721                                                      &was_free,
722                                                      NULL, NULL);
723
724                 if (!is_free) {
725                         TALLOC_FREE(global->db_rec);
726                         continue;
727                 }
728
729                 if (!was_free && i < min_tries) {
730                         /*
731                          * The session_id is free now,
732                          * but was not free before.
733                          *
734                          * This happens if a smbd crashed
735                          * and did not cleanup the record.
736                          *
737                          * If this is one of our first tries,
738                          * then we try to find a real free one.
739                          */
740                         if (last_free == 0) {
741                                 last_free = id;
742                         }
743                         TALLOC_FREE(global->db_rec);
744                         continue;
745                 }
746
747                 global->session_global_id = id;
748
749                 *_global = global;
750                 return NT_STATUS_OK;
751         }
752
753         /* should not be reached */
754         talloc_free(global);
755         return NT_STATUS_INTERNAL_ERROR;
756 }
757
758 static void smbXsrv_session_global_verify_record(struct db_record *db_rec,
759                                         bool *is_free,
760                                         bool *was_free,
761                                         TALLOC_CTX *mem_ctx,
762                                         struct smbXsrv_session_global0 **_g)
763 {
764         TDB_DATA key;
765         TDB_DATA val;
766         DATA_BLOB blob;
767         struct smbXsrv_session_globalB global_blob;
768         enum ndr_err_code ndr_err;
769         struct smbXsrv_session_global0 *global = NULL;
770         bool exists;
771         TALLOC_CTX *frame = talloc_stackframe();
772
773         *is_free = false;
774
775         if (was_free) {
776                 *was_free = false;
777         }
778         if (_g) {
779                 *_g = NULL;
780         }
781
782         key = dbwrap_record_get_key(db_rec);
783
784         val = dbwrap_record_get_value(db_rec);
785         if (val.dsize == 0) {
786                 TALLOC_FREE(frame);
787                 *is_free = true;
788                 if (was_free) {
789                         *was_free = true;
790                 }
791                 return;
792         }
793
794         blob = data_blob_const(val.dptr, val.dsize);
795
796         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
797                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_session_globalB);
798         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
799                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
800                 DEBUG(1,("smbXsrv_session_global_verify_record: "
801                          "key '%s' ndr_pull_struct_blob - %s\n",
802                          hex_encode_talloc(frame, key.dptr, key.dsize),
803                          nt_errstr(status)));
804                 TALLOC_FREE(frame);
805                 return;
806         }
807
808         DEBUG(10,("smbXsrv_session_global_verify_record\n"));
809         if (DEBUGLVL(10)) {
810                 NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
811         }
812
813         if (global_blob.version != SMBXSRV_VERSION_0) {
814                 DEBUG(0,("smbXsrv_session_global_verify_record: "
815                          "key '%s' use unsupported version %u\n",
816                          hex_encode_talloc(frame, key.dptr, key.dsize),
817                          global_blob.version));
818                 NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
819                 TALLOC_FREE(frame);
820                 return;
821         }
822
823         global = global_blob.info.info0;
824
825         exists = serverid_exists(&global->channels[0].server_id);
826         if (!exists) {
827                 struct server_id_buf idbuf;
828                 DEBUG(2,("smbXsrv_session_global_verify_record: "
829                          "key '%s' server_id %s does not exist.\n",
830                          hex_encode_talloc(frame, key.dptr, key.dsize),
831                          server_id_str_buf(global->channels[0].server_id,
832                                            &idbuf)));
833                 if (DEBUGLVL(2)) {
834                         NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
835                 }
836                 TALLOC_FREE(frame);
837                 dbwrap_record_delete(db_rec);
838                 *is_free = true;
839                 return;
840         }
841
842         if (_g) {
843                 *_g = talloc_move(mem_ctx, &global);
844         }
845         TALLOC_FREE(frame);
846 }
847
848 static NTSTATUS smbXsrv_session_global_store(struct smbXsrv_session_global0 *global)
849 {
850         struct smbXsrv_session_globalB global_blob;
851         DATA_BLOB blob = data_blob_null;
852         TDB_DATA key;
853         TDB_DATA val;
854         NTSTATUS status;
855         enum ndr_err_code ndr_err;
856
857         /*
858          * TODO: if we use other versions than '0'
859          * we would add glue code here, that would be able to
860          * store the information in the old format.
861          */
862
863         if (global->db_rec == NULL) {
864                 return NT_STATUS_INTERNAL_ERROR;
865         }
866
867         key = dbwrap_record_get_key(global->db_rec);
868         val = dbwrap_record_get_value(global->db_rec);
869
870         ZERO_STRUCT(global_blob);
871         global_blob.version = smbXsrv_version_global_current();
872         if (val.dsize >= 8) {
873                 global_blob.seqnum = IVAL(val.dptr, 4);
874         }
875         global_blob.seqnum += 1;
876         global_blob.info.info0 = global;
877
878         ndr_err = ndr_push_struct_blob(&blob, global->db_rec, &global_blob,
879                         (ndr_push_flags_fn_t)ndr_push_smbXsrv_session_globalB);
880         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
881                 status = ndr_map_error2ntstatus(ndr_err);
882                 DEBUG(1,("smbXsrv_session_global_store: key '%s' ndr_push - %s\n",
883                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
884                          nt_errstr(status)));
885                 TALLOC_FREE(global->db_rec);
886                 return status;
887         }
888
889         val = make_tdb_data(blob.data, blob.length);
890         status = dbwrap_record_store(global->db_rec, val, TDB_REPLACE);
891         if (!NT_STATUS_IS_OK(status)) {
892                 DEBUG(1,("smbXsrv_session_global_store: key '%s' store - %s\n",
893                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
894                          nt_errstr(status)));
895                 TALLOC_FREE(global->db_rec);
896                 return status;
897         }
898
899         if (DEBUGLVL(10)) {
900                 DEBUG(10,("smbXsrv_session_global_store: key '%s' stored\n",
901                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize)));
902                 NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
903         }
904
905         TALLOC_FREE(global->db_rec);
906
907         return NT_STATUS_OK;
908 }
909
910 struct smb2srv_session_close_previous_state {
911         struct tevent_context *ev;
912         struct smbXsrv_connection *connection;
913         struct dom_sid *current_sid;
914         uint64_t current_session_id;
915         struct db_record *db_rec;
916 };
917
918 static void smb2srv_session_close_previous_check(struct tevent_req *req);
919 static void smb2srv_session_close_previous_modified(struct tevent_req *subreq);
920
921 struct tevent_req *smb2srv_session_close_previous_send(TALLOC_CTX *mem_ctx,
922                                         struct tevent_context *ev,
923                                         struct smbXsrv_connection *conn,
924                                         struct auth_session_info *session_info,
925                                         uint64_t previous_session_id,
926                                         uint64_t current_session_id)
927 {
928         struct tevent_req *req;
929         struct smb2srv_session_close_previous_state *state;
930         uint32_t global_id = previous_session_id & UINT32_MAX;
931         uint64_t global_zeros = previous_session_id & 0xFFFFFFFF00000000LLU;
932         struct smbXsrv_session_table *table = conn->client->session_table;
933         struct security_token *current_token = NULL;
934         uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
935         TDB_DATA key;
936
937         req = tevent_req_create(mem_ctx, &state,
938                                 struct smb2srv_session_close_previous_state);
939         if (req == NULL) {
940                 return NULL;
941         }
942         state->ev = ev;
943         state->connection = conn;
944         state->current_session_id = current_session_id;
945
946         if (global_zeros != 0) {
947                 tevent_req_done(req);
948                 return tevent_req_post(req, ev);
949         }
950
951         if (session_info == NULL) {
952                 tevent_req_done(req);
953                 return tevent_req_post(req, ev);
954         }
955         current_token = session_info->security_token;
956
957         if (current_token->num_sids > PRIMARY_USER_SID_INDEX) {
958                 state->current_sid = &current_token->sids[PRIMARY_USER_SID_INDEX];
959         }
960
961         if (state->current_sid == NULL) {
962                 tevent_req_done(req);
963                 return tevent_req_post(req, ev);
964         }
965
966         if (!security_token_has_nt_authenticated_users(current_token)) {
967                 /* TODO */
968                 tevent_req_done(req);
969                 return tevent_req_post(req, ev);
970         }
971
972         key = smbXsrv_session_global_id_to_key(global_id, key_buf);
973
974         state->db_rec = dbwrap_fetch_locked(table->global.db_ctx,
975                                             state, key);
976         if (state->db_rec == NULL) {
977                 tevent_req_nterror(req, NT_STATUS_UNSUCCESSFUL);
978                 return tevent_req_post(req, ev);
979         }
980
981         smb2srv_session_close_previous_check(req);
982         if (!tevent_req_is_in_progress(req)) {
983                 return tevent_req_post(req, ev);
984         }
985
986         return req;
987 }
988
989 static void smb2srv_session_close_previous_check(struct tevent_req *req)
990 {
991         struct smb2srv_session_close_previous_state *state =
992                 tevent_req_data(req,
993                 struct smb2srv_session_close_previous_state);
994         struct smbXsrv_connection *conn = state->connection;
995         DATA_BLOB blob;
996         struct security_token *previous_token = NULL;
997         struct smbXsrv_session_global0 *global = NULL;
998         enum ndr_err_code ndr_err;
999         struct smbXsrv_session_close0 close_info0;
1000         struct smbXsrv_session_closeB close_blob;
1001         struct tevent_req *subreq = NULL;
1002         NTSTATUS status;
1003         bool is_free = false;
1004
1005         smbXsrv_session_global_verify_record(state->db_rec,
1006                                              &is_free,
1007                                              NULL,
1008                                              state,
1009                                              &global);
1010
1011         if (is_free) {
1012                 TALLOC_FREE(state->db_rec);
1013                 tevent_req_done(req);
1014                 return;
1015         }
1016
1017         if (global->auth_session_info == NULL) {
1018                 TALLOC_FREE(state->db_rec);
1019                 tevent_req_done(req);
1020                 return;
1021         }
1022
1023         previous_token = global->auth_session_info->security_token;
1024
1025         if (!security_token_is_sid(previous_token, state->current_sid)) {
1026                 TALLOC_FREE(state->db_rec);
1027                 tevent_req_done(req);
1028                 return;
1029         }
1030
1031         subreq = dbwrap_record_watch_send(state, state->ev,
1032                                           state->db_rec, conn->msg_ctx);
1033         if (tevent_req_nomem(subreq, req)) {
1034                 TALLOC_FREE(state->db_rec);
1035                 return;
1036         }
1037         tevent_req_set_callback(subreq,
1038                                 smb2srv_session_close_previous_modified,
1039                                 req);
1040
1041         close_info0.old_session_global_id = global->session_global_id;
1042         close_info0.old_session_wire_id = global->session_wire_id;
1043         close_info0.old_creation_time = global->creation_time;
1044         close_info0.new_session_wire_id = state->current_session_id;
1045
1046         ZERO_STRUCT(close_blob);
1047         close_blob.version = smbXsrv_version_global_current();
1048         close_blob.info.info0 = &close_info0;
1049
1050         ndr_err = ndr_push_struct_blob(&blob, state, &close_blob,
1051                         (ndr_push_flags_fn_t)ndr_push_smbXsrv_session_closeB);
1052         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1053                 TALLOC_FREE(state->db_rec);
1054                 status = ndr_map_error2ntstatus(ndr_err);
1055                 DEBUG(1,("smb2srv_session_close_previous_check: "
1056                          "old_session[%llu] new_session[%llu] ndr_push - %s\n",
1057                          (unsigned long long)close_info0.old_session_wire_id,
1058                          (unsigned long long)close_info0.new_session_wire_id,
1059                          nt_errstr(status)));
1060                 tevent_req_nterror(req, status);
1061                 return;
1062         }
1063
1064         status = messaging_send(conn->msg_ctx,
1065                                 global->channels[0].server_id,
1066                                 MSG_SMBXSRV_SESSION_CLOSE, &blob);
1067         TALLOC_FREE(state->db_rec);
1068         if (tevent_req_nterror(req, status)) {
1069                 return;
1070         }
1071
1072         TALLOC_FREE(global);
1073         return;
1074 }
1075
1076 static void smb2srv_session_close_previous_modified(struct tevent_req *subreq)
1077 {
1078         struct tevent_req *req =
1079                 tevent_req_callback_data(subreq,
1080                 struct tevent_req);
1081         struct smb2srv_session_close_previous_state *state =
1082                 tevent_req_data(req,
1083                 struct smb2srv_session_close_previous_state);
1084         NTSTATUS status;
1085
1086         status = dbwrap_record_watch_recv(subreq, state, &state->db_rec);
1087         TALLOC_FREE(subreq);
1088         if (tevent_req_nterror(req, status)) {
1089                 return;
1090         }
1091
1092         smb2srv_session_close_previous_check(req);
1093 }
1094
1095 NTSTATUS smb2srv_session_close_previous_recv(struct tevent_req *req)
1096 {
1097         NTSTATUS status;
1098
1099         if (tevent_req_is_nterror(req, &status)) {
1100                 tevent_req_received(req);
1101                 return status;
1102         }
1103
1104         tevent_req_received(req);
1105         return NT_STATUS_OK;
1106 }
1107
1108 static NTSTATUS smbXsrv_session_clear_and_logoff(struct smbXsrv_session *session)
1109 {
1110         NTSTATUS status;
1111         struct smbXsrv_connection *xconn = NULL;
1112
1113         if (session->client != NULL) {
1114                 xconn = session->client->connections;
1115         }
1116
1117         for (; xconn != NULL; xconn = xconn->next) {
1118                 struct smbd_smb2_request *preq;
1119
1120                 for (preq = xconn->smb2.requests; preq != NULL; preq = preq->next) {
1121                         if (preq->session != session) {
1122                                 continue;
1123                         }
1124
1125                         preq->session = NULL;
1126                         /*
1127                          * If we no longer have a session we can't
1128                          * sign or encrypt replies.
1129                          */
1130                         preq->do_signing = false;
1131                         preq->do_encryption = false;
1132                         preq->preauth = NULL;
1133                 }
1134         }
1135
1136         status = smbXsrv_session_logoff(session);
1137         return status;
1138 }
1139
1140 static int smbXsrv_session_destructor(struct smbXsrv_session *session)
1141 {
1142         NTSTATUS status;
1143
1144         status = smbXsrv_session_clear_and_logoff(session);
1145         if (!NT_STATUS_IS_OK(status)) {
1146                 DEBUG(0, ("smbXsrv_session_destructor: "
1147                           "smbXsrv_session_logoff() failed: %s\n",
1148                           nt_errstr(status)));
1149         }
1150
1151         TALLOC_FREE(session->global);
1152
1153         return 0;
1154 }
1155
1156 NTSTATUS smbXsrv_session_create(struct smbXsrv_connection *conn,
1157                                 NTTIME now,
1158                                 struct smbXsrv_session **_session)
1159 {
1160         struct smbXsrv_session_table *table = conn->client->session_table;
1161         struct db_record *local_rec = NULL;
1162         struct smbXsrv_session *session = NULL;
1163         void *ptr = NULL;
1164         TDB_DATA val;
1165         struct smbXsrv_session_global0 *global = NULL;
1166         struct smbXsrv_channel_global0 *channels = NULL;
1167         NTSTATUS status;
1168
1169         if (table->local.num_sessions >= table->local.max_sessions) {
1170                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1171         }
1172
1173         session = talloc_zero(table, struct smbXsrv_session);
1174         if (session == NULL) {
1175                 return NT_STATUS_NO_MEMORY;
1176         }
1177         session->table = table;
1178         session->idle_time = now;
1179         session->status = NT_STATUS_MORE_PROCESSING_REQUIRED;
1180         session->client = conn->client;
1181
1182         if (conn->protocol >= PROTOCOL_SMB3_10) {
1183                 session->preauth = talloc(session, struct smbXsrv_preauth);
1184                 if (session->preauth == NULL) {
1185                         TALLOC_FREE(session);
1186                         return NT_STATUS_NO_MEMORY;
1187                 }
1188                 *session->preauth = conn->smb2.preauth;
1189         }
1190
1191         status = smbXsrv_session_global_allocate(table->global.db_ctx,
1192                                                  session,
1193                                                  &global);
1194         if (!NT_STATUS_IS_OK(status)) {
1195                 TALLOC_FREE(session);
1196                 return status;
1197         }
1198         session->global = global;
1199
1200         if (conn->protocol >= PROTOCOL_SMB2_02) {
1201                 uint64_t id = global->session_global_id;
1202                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
1203                 TDB_DATA key;
1204
1205                 global->connection_dialect = conn->smb2.server.dialect;
1206
1207                 global->session_wire_id = id;
1208
1209                 status = smb2srv_tcon_table_init(session);
1210                 if (!NT_STATUS_IS_OK(status)) {
1211                         TALLOC_FREE(session);
1212                         return status;
1213                 }
1214
1215                 session->local_id = global->session_global_id;
1216
1217                 key = smbXsrv_session_local_id_to_key(session->local_id, key_buf);
1218
1219                 local_rec = dbwrap_fetch_locked(table->local.db_ctx,
1220                                                 session, key);
1221                 if (local_rec == NULL) {
1222                         TALLOC_FREE(session);
1223                         return NT_STATUS_NO_MEMORY;
1224                 }
1225
1226                 val = dbwrap_record_get_value(local_rec);
1227                 if (val.dsize != 0) {
1228                         TALLOC_FREE(session);
1229                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1230                 }
1231         } else {
1232
1233                 status = smb1srv_session_local_allocate_id(table->local.db_ctx,
1234                                                         table->local.lowest_id,
1235                                                         table->local.highest_id,
1236                                                         session,
1237                                                         &local_rec,
1238                                                         &session->local_id);
1239                 if (!NT_STATUS_IS_OK(status)) {
1240                         TALLOC_FREE(session);
1241                         return status;
1242                 }
1243
1244                 global->session_wire_id = session->local_id;
1245         }
1246
1247         global->creation_time = now;
1248         global->expiration_time = GENSEC_EXPIRE_TIME_INFINITY;
1249
1250         global->num_channels = 1;
1251         channels = talloc_zero_array(global,
1252                                      struct smbXsrv_channel_global0,
1253                                      global->num_channels);
1254         if (channels == NULL) {
1255                 TALLOC_FREE(session);
1256                 return NT_STATUS_NO_MEMORY;
1257         }
1258         global->channels = channels;
1259
1260         channels[0].server_id = messaging_server_id(conn->msg_ctx);
1261         channels[0].local_address = tsocket_address_string(conn->local_address,
1262                                                            channels);
1263         if (channels[0].local_address == NULL) {
1264                 TALLOC_FREE(session);
1265                 return NT_STATUS_NO_MEMORY;
1266         }
1267         channels[0].remote_address = tsocket_address_string(conn->remote_address,
1268                                                             channels);
1269         if (channels[0].remote_address == NULL) {
1270                 TALLOC_FREE(session);
1271                 return NT_STATUS_NO_MEMORY;
1272         }
1273         channels[0].remote_name = talloc_strdup(channels, conn->remote_hostname);
1274         if (channels[0].remote_name == NULL) {
1275                 TALLOC_FREE(session);
1276                 return NT_STATUS_NO_MEMORY;
1277         }
1278         channels[0].signing_key = data_blob_null;
1279         channels[0].connection = conn;
1280
1281         ptr = session;
1282         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
1283         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
1284         TALLOC_FREE(local_rec);
1285         if (!NT_STATUS_IS_OK(status)) {
1286                 TALLOC_FREE(session);
1287                 return status;
1288         }
1289         table->local.num_sessions += 1;
1290
1291         talloc_set_destructor(session, smbXsrv_session_destructor);
1292
1293         status = smbXsrv_session_global_store(global);
1294         if (!NT_STATUS_IS_OK(status)) {
1295                 DEBUG(0,("smbXsrv_session_create: "
1296                          "global_id (0x%08x) store failed - %s\n",
1297                          session->global->session_global_id,
1298                          nt_errstr(status)));
1299                 TALLOC_FREE(session);
1300                 return status;
1301         }
1302
1303         if (DEBUGLVL(10)) {
1304                 struct smbXsrv_sessionB session_blob;
1305
1306                 ZERO_STRUCT(session_blob);
1307                 session_blob.version = SMBXSRV_VERSION_0;
1308                 session_blob.info.info0 = session;
1309
1310                 DEBUG(10,("smbXsrv_session_create: global_id (0x%08x) stored\n",
1311                          session->global->session_global_id));
1312                 NDR_PRINT_DEBUG(smbXsrv_sessionB, &session_blob);
1313         }
1314
1315         *_session = session;
1316         return NT_STATUS_OK;
1317 }
1318
1319 NTSTATUS smbXsrv_session_update(struct smbXsrv_session *session)
1320 {
1321         struct smbXsrv_session_table *table = session->table;
1322         NTSTATUS status;
1323         uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
1324         TDB_DATA key;
1325
1326         if (session->global->db_rec != NULL) {
1327                 DEBUG(0, ("smbXsrv_session_update(0x%08x): "
1328                           "Called with db_rec != NULL'\n",
1329                           session->global->session_global_id));
1330                 return NT_STATUS_INTERNAL_ERROR;
1331         }
1332
1333         key = smbXsrv_session_global_id_to_key(
1334                                         session->global->session_global_id,
1335                                         key_buf);
1336
1337         session->global->db_rec = dbwrap_fetch_locked(table->global.db_ctx,
1338                                                       session->global, key);
1339         if (session->global->db_rec == NULL) {
1340                 DEBUG(0, ("smbXsrv_session_update(0x%08x): "
1341                           "Failed to lock global key '%s'\n",
1342                           session->global->session_global_id,
1343                           hex_encode_talloc(talloc_tos(), key.dptr,
1344                                             key.dsize)));
1345                 return NT_STATUS_INTERNAL_DB_ERROR;
1346         }
1347
1348         status = smbXsrv_session_global_store(session->global);
1349         if (!NT_STATUS_IS_OK(status)) {
1350                 DEBUG(0,("smbXsrv_session_update: "
1351                          "global_id (0x%08x) store failed - %s\n",
1352                          session->global->session_global_id,
1353                          nt_errstr(status)));
1354                 return status;
1355         }
1356
1357         if (DEBUGLVL(10)) {
1358                 struct smbXsrv_sessionB session_blob;
1359
1360                 ZERO_STRUCT(session_blob);
1361                 session_blob.version = SMBXSRV_VERSION_0;
1362                 session_blob.info.info0 = session;
1363
1364                 DEBUG(10,("smbXsrv_session_update: global_id (0x%08x) stored\n",
1365                           session->global->session_global_id));
1366                 NDR_PRINT_DEBUG(smbXsrv_sessionB, &session_blob);
1367         }
1368
1369         return NT_STATUS_OK;
1370 }
1371
1372 NTSTATUS smbXsrv_session_find_channel(const struct smbXsrv_session *session,
1373                                       const struct smbXsrv_connection *conn,
1374                                       struct smbXsrv_channel_global0 **_c)
1375 {
1376         uint32_t i;
1377
1378         for (i=0; i < session->global->num_channels; i++) {
1379                 struct smbXsrv_channel_global0 *c = &session->global->channels[i];
1380
1381                 if (c->connection == conn) {
1382                         *_c = c;
1383                         return NT_STATUS_OK;
1384                 }
1385         }
1386
1387         return NT_STATUS_USER_SESSION_DELETED;
1388 }
1389
1390 NTSTATUS smbXsrv_session_find_auth(const struct smbXsrv_session *session,
1391                                    const struct smbXsrv_connection *conn,
1392                                    NTTIME now,
1393                                    struct smbXsrv_session_auth0 **_a)
1394 {
1395         struct smbXsrv_session_auth0 *a;
1396
1397         for (a = session->pending_auth; a != NULL; a = a->next) {
1398                 if (a->connection == conn) {
1399                         if (now != 0) {
1400                                 a->idle_time = now;
1401                         }
1402                         *_a = a;
1403                         return NT_STATUS_OK;
1404                 }
1405         }
1406
1407         return NT_STATUS_USER_SESSION_DELETED;
1408 }
1409
1410 static int smbXsrv_session_auth0_destructor(struct smbXsrv_session_auth0 *a)
1411 {
1412         if (a->session == NULL) {
1413                 return 0;
1414         }
1415
1416         DLIST_REMOVE(a->session->pending_auth, a);
1417         a->session = NULL;
1418         return 0;
1419 }
1420
1421 NTSTATUS smbXsrv_session_create_auth(struct smbXsrv_session *session,
1422                                      struct smbXsrv_connection *conn,
1423                                      NTTIME now,
1424                                      uint8_t in_flags,
1425                                      uint8_t in_security_mode,
1426                                      struct smbXsrv_session_auth0 **_a)
1427 {
1428         struct smbXsrv_session_auth0 *a;
1429         NTSTATUS status;
1430
1431         status = smbXsrv_session_find_auth(session, conn, 0, &a);
1432         if (NT_STATUS_IS_OK(status)) {
1433                 return NT_STATUS_INTERNAL_ERROR;
1434         }
1435
1436         a = talloc_zero(session, struct smbXsrv_session_auth0);
1437         if (a == NULL) {
1438                 return NT_STATUS_NO_MEMORY;
1439         }
1440         a->session = session;
1441         a->connection = conn;
1442         a->in_flags = in_flags;
1443         a->in_security_mode = in_security_mode;
1444         a->creation_time = now;
1445         a->idle_time = now;
1446
1447         if (conn->protocol >= PROTOCOL_SMB3_10) {
1448                 a->preauth = talloc(a, struct smbXsrv_preauth);
1449                 if (a->preauth == NULL) {
1450                         TALLOC_FREE(session);
1451                         return NT_STATUS_NO_MEMORY;
1452                 }
1453                 *a->preauth = conn->smb2.preauth;
1454         }
1455
1456         talloc_set_destructor(a, smbXsrv_session_auth0_destructor);
1457         DLIST_ADD_END(session->pending_auth, a, NULL);
1458
1459         *_a = a;
1460         return NT_STATUS_OK;
1461 }
1462
1463 struct smb2srv_session_shutdown_state {
1464         struct tevent_queue *wait_queue;
1465 };
1466
1467 static void smb2srv_session_shutdown_wait_done(struct tevent_req *subreq);
1468
1469 struct tevent_req *smb2srv_session_shutdown_send(TALLOC_CTX *mem_ctx,
1470                                         struct tevent_context *ev,
1471                                         struct smbXsrv_session *session,
1472                                         struct smbd_smb2_request *current_req)
1473 {
1474         struct tevent_req *req;
1475         struct smb2srv_session_shutdown_state *state;
1476         struct tevent_req *subreq;
1477         struct smbXsrv_connection *xconn = NULL;
1478         size_t len = 0;
1479
1480         /*
1481          * Make sure that no new request will be able to use this session.
1482          */
1483         session->status = NT_STATUS_USER_SESSION_DELETED;
1484
1485         req = tevent_req_create(mem_ctx, &state,
1486                                 struct smb2srv_session_shutdown_state);
1487         if (req == NULL) {
1488                 return NULL;
1489         }
1490
1491         state->wait_queue = tevent_queue_create(state, "smb2srv_session_shutdown_queue");
1492         if (tevent_req_nomem(state->wait_queue, req)) {
1493                 return tevent_req_post(req, ev);
1494         }
1495
1496         for (xconn = session->client->connections; xconn != NULL; xconn = xconn->next) {
1497                 struct smbd_smb2_request *preq;
1498
1499                 for (preq = xconn->smb2.requests; preq != NULL; preq = preq->next) {
1500                         if (preq == current_req) {
1501                                 /* Can't cancel current request. */
1502                                 continue;
1503                         }
1504                         if (preq->session != session) {
1505                                 /* Request on different session. */
1506                                 continue;
1507                         }
1508
1509                         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
1510                                 preq->session = NULL;
1511                                 /*
1512                                  * If we no longer have a session we can't
1513                                  * sign or encrypt replies.
1514                                  */
1515                                 preq->do_signing = false;
1516                                 preq->do_encryption = false;
1517                                 preq->preauth = NULL;
1518
1519                                 if (preq->subreq != NULL) {
1520                                         tevent_req_cancel(preq->subreq);
1521                                 }
1522                                 continue;
1523                         }
1524
1525                         /*
1526                          * Never cancel anything in a compound
1527                          * request. Way too hard to deal with
1528                          * the result.
1529                          */
1530                         if (!preq->compound_related && preq->subreq != NULL) {
1531                                 tevent_req_cancel(preq->subreq);
1532                         }
1533
1534                         /*
1535                          * Now wait until the request is finished.
1536                          *
1537                          * We don't set a callback, as we just want to block the
1538                          * wait queue and the talloc_free() of the request will
1539                          * remove the item from the wait queue.
1540                          */
1541                         subreq = tevent_queue_wait_send(preq, ev, state->wait_queue);
1542                         if (tevent_req_nomem(subreq, req)) {
1543                                 return tevent_req_post(req, ev);
1544                         }
1545                 }
1546         }
1547
1548         len = tevent_queue_length(state->wait_queue);
1549         if (len == 0) {
1550                 tevent_req_done(req);
1551                 return tevent_req_post(req, ev);
1552         }
1553
1554         /*
1555          * Now we add our own waiter to the end of the queue,
1556          * this way we get notified when all pending requests are finished
1557          * and send to the socket.
1558          */
1559         subreq = tevent_queue_wait_send(state, ev, state->wait_queue);
1560         if (tevent_req_nomem(subreq, req)) {
1561                 return tevent_req_post(req, ev);
1562         }
1563         tevent_req_set_callback(subreq, smb2srv_session_shutdown_wait_done, req);
1564
1565         return req;
1566 }
1567
1568 static void smb2srv_session_shutdown_wait_done(struct tevent_req *subreq)
1569 {
1570         struct tevent_req *req =
1571                 tevent_req_callback_data(subreq,
1572                 struct tevent_req);
1573
1574         tevent_queue_wait_recv(subreq);
1575         TALLOC_FREE(subreq);
1576
1577         tevent_req_done(req);
1578 }
1579
1580 NTSTATUS smb2srv_session_shutdown_recv(struct tevent_req *req)
1581 {
1582         return tevent_req_simple_recv_ntstatus(req);
1583 }
1584
1585 NTSTATUS smbXsrv_session_logoff(struct smbXsrv_session *session)
1586 {
1587         struct smbXsrv_session_table *table;
1588         struct db_record *local_rec = NULL;
1589         struct db_record *global_rec = NULL;
1590         struct smbd_server_connection *sconn = NULL;
1591         NTSTATUS status;
1592         NTSTATUS error = NT_STATUS_OK;
1593
1594         if (session->table == NULL) {
1595                 return NT_STATUS_OK;
1596         }
1597
1598         table = session->table;
1599         session->table = NULL;
1600
1601         sconn = session->client->sconn;
1602         session->client = NULL;
1603         session->status = NT_STATUS_USER_SESSION_DELETED;
1604
1605         global_rec = session->global->db_rec;
1606         session->global->db_rec = NULL;
1607         if (global_rec == NULL) {
1608                 uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
1609                 TDB_DATA key;
1610
1611                 key = smbXsrv_session_global_id_to_key(
1612                                         session->global->session_global_id,
1613                                         key_buf);
1614
1615                 global_rec = dbwrap_fetch_locked(table->global.db_ctx,
1616                                                  session->global, key);
1617                 if (global_rec == NULL) {
1618                         DEBUG(0, ("smbXsrv_session_logoff(0x%08x): "
1619                                   "Failed to lock global key '%s'\n",
1620                                   session->global->session_global_id,
1621                                   hex_encode_talloc(global_rec, key.dptr,
1622                                                     key.dsize)));
1623                         error = NT_STATUS_INTERNAL_ERROR;
1624                 }
1625         }
1626
1627         if (global_rec != NULL) {
1628                 status = dbwrap_record_delete(global_rec);
1629                 if (!NT_STATUS_IS_OK(status)) {
1630                         TDB_DATA key = dbwrap_record_get_key(global_rec);
1631
1632                         DEBUG(0, ("smbXsrv_session_logoff(0x%08x): "
1633                                   "failed to delete global key '%s': %s\n",
1634                                   session->global->session_global_id,
1635                                   hex_encode_talloc(global_rec, key.dptr,
1636                                                     key.dsize),
1637                                   nt_errstr(status)));
1638                         error = status;
1639                 }
1640         }
1641         TALLOC_FREE(global_rec);
1642
1643         local_rec = session->db_rec;
1644         if (local_rec == NULL) {
1645                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
1646                 TDB_DATA key;
1647
1648                 key = smbXsrv_session_local_id_to_key(session->local_id,
1649                                                       key_buf);
1650
1651                 local_rec = dbwrap_fetch_locked(table->local.db_ctx,
1652                                                 session, key);
1653                 if (local_rec == NULL) {
1654                         DEBUG(0, ("smbXsrv_session_logoff(0x%08x): "
1655                                   "Failed to lock local key '%s'\n",
1656                                   session->global->session_global_id,
1657                                   hex_encode_talloc(local_rec, key.dptr,
1658                                                     key.dsize)));
1659                         error = NT_STATUS_INTERNAL_ERROR;
1660                 }
1661         }
1662
1663         if (local_rec != NULL) {
1664                 status = dbwrap_record_delete(local_rec);
1665                 if (!NT_STATUS_IS_OK(status)) {
1666                         TDB_DATA key = dbwrap_record_get_key(local_rec);
1667
1668                         DEBUG(0, ("smbXsrv_session_logoff(0x%08x): "
1669                                   "failed to delete local key '%s': %s\n",
1670                                   session->global->session_global_id,
1671                                   hex_encode_talloc(local_rec, key.dptr,
1672                                                     key.dsize),
1673                                   nt_errstr(status)));
1674                         error = status;
1675                 }
1676                 table->local.num_sessions -= 1;
1677         }
1678         if (session->db_rec == NULL) {
1679                 TALLOC_FREE(local_rec);
1680         }
1681         session->db_rec = NULL;
1682
1683         if (session->compat) {
1684                 file_close_user(sconn, session->compat->vuid);
1685         }
1686
1687         if (session->tcon_table != NULL) {
1688                 /*
1689                  * Note: We only have a tcon_table for SMB2.
1690                  */
1691                 status = smb2srv_tcon_disconnect_all(session);
1692                 if (!NT_STATUS_IS_OK(status)) {
1693                         DEBUG(0, ("smbXsrv_session_logoff(0x%08x): "
1694                                   "smb2srv_tcon_disconnect_all() failed: %s\n",
1695                                   session->global->session_global_id,
1696                                   nt_errstr(status)));
1697                         error = status;
1698                 }
1699         }
1700
1701         if (session->compat) {
1702                 invalidate_vuid(sconn, session->compat->vuid);
1703                 session->compat = NULL;
1704         }
1705
1706         return error;
1707 }
1708
1709 struct smbXsrv_session_logoff_all_state {
1710         NTSTATUS first_status;
1711         int errors;
1712 };
1713
1714 static int smbXsrv_session_logoff_all_callback(struct db_record *local_rec,
1715                                                void *private_data);
1716
1717 NTSTATUS smbXsrv_session_logoff_all(struct smbXsrv_connection *conn)
1718 {
1719         struct smbXsrv_session_table *table = conn->client->session_table;
1720         struct smbXsrv_session_logoff_all_state state;
1721         NTSTATUS status;
1722         int count = 0;
1723
1724         if (table == NULL) {
1725                 DEBUG(10, ("smbXsrv_session_logoff_all: "
1726                            "empty session_table, nothing to do.\n"));
1727                 return NT_STATUS_OK;
1728         }
1729
1730         ZERO_STRUCT(state);
1731
1732         status = dbwrap_traverse(table->local.db_ctx,
1733                                  smbXsrv_session_logoff_all_callback,
1734                                  &state, &count);
1735         if (!NT_STATUS_IS_OK(status)) {
1736                 DEBUG(0, ("smbXsrv_session_logoff_all: "
1737                           "dbwrap_traverse() failed: %s\n",
1738                           nt_errstr(status)));
1739                 return status;
1740         }
1741
1742         if (!NT_STATUS_IS_OK(state.first_status)) {
1743                 DEBUG(0, ("smbXsrv_session_logoff_all: "
1744                           "count[%d] errors[%d] first[%s]\n",
1745                           count, state.errors,
1746                           nt_errstr(state.first_status)));
1747                 return state.first_status;
1748         }
1749
1750         return NT_STATUS_OK;
1751 }
1752
1753 static int smbXsrv_session_logoff_all_callback(struct db_record *local_rec,
1754                                                void *private_data)
1755 {
1756         struct smbXsrv_session_logoff_all_state *state =
1757                 (struct smbXsrv_session_logoff_all_state *)private_data;
1758         TDB_DATA val;
1759         void *ptr = NULL;
1760         struct smbXsrv_session *session = NULL;
1761         NTSTATUS status;
1762
1763         val = dbwrap_record_get_value(local_rec);
1764         if (val.dsize != sizeof(ptr)) {
1765                 status = NT_STATUS_INTERNAL_ERROR;
1766                 if (NT_STATUS_IS_OK(state->first_status)) {
1767                         state->first_status = status;
1768                 }
1769                 state->errors++;
1770                 return 0;
1771         }
1772
1773         memcpy(&ptr, val.dptr, val.dsize);
1774         session = talloc_get_type_abort(ptr, struct smbXsrv_session);
1775
1776         session->db_rec = local_rec;
1777
1778         status = smbXsrv_session_clear_and_logoff(session);
1779         if (!NT_STATUS_IS_OK(status)) {
1780                 if (NT_STATUS_IS_OK(state->first_status)) {
1781                         state->first_status = status;
1782                 }
1783                 state->errors++;
1784                 return 0;
1785         }
1786
1787         return 0;
1788 }
1789
1790 NTSTATUS smb1srv_session_table_init(struct smbXsrv_connection *conn)
1791 {
1792         /*
1793          * Allow a range from 1..65534 with 65534 values.
1794          */
1795         return smbXsrv_session_table_init(conn, 1, UINT16_MAX - 1,
1796                                           UINT16_MAX - 1);
1797 }
1798
1799 NTSTATUS smb1srv_session_lookup(struct smbXsrv_connection *conn,
1800                                 uint16_t vuid, NTTIME now,
1801                                 struct smbXsrv_session **session)
1802 {
1803         struct smbXsrv_session_table *table = conn->client->session_table;
1804         uint32_t local_id = vuid;
1805
1806         return smbXsrv_session_local_lookup(table, conn, local_id, now,
1807                                             session);
1808 }
1809
1810 NTSTATUS smb2srv_session_table_init(struct smbXsrv_connection *conn)
1811 {
1812         /*
1813          * Allow a range from 1..4294967294 with 65534 (same as SMB1) values.
1814          */
1815         return smbXsrv_session_table_init(conn, 1, UINT32_MAX - 1,
1816                                           UINT16_MAX - 1);
1817 }
1818
1819 static NTSTATUS smb2srv_session_lookup_raw(struct smbXsrv_session_table *table,
1820                                            /* conn: optional */
1821                                            struct smbXsrv_connection *conn,
1822                                            uint64_t session_id, NTTIME now,
1823                                            struct smbXsrv_session **session)
1824 {
1825         uint32_t local_id = session_id & UINT32_MAX;
1826         uint64_t local_zeros = session_id & 0xFFFFFFFF00000000LLU;
1827
1828         if (local_zeros != 0) {
1829                 return NT_STATUS_USER_SESSION_DELETED;
1830         }
1831
1832         return smbXsrv_session_local_lookup(table, conn, local_id, now,
1833                                             session);
1834 }
1835
1836 NTSTATUS smb2srv_session_lookup_conn(struct smbXsrv_connection *conn,
1837                                      uint64_t session_id, NTTIME now,
1838                                      struct smbXsrv_session **session)
1839 {
1840         struct smbXsrv_session_table *table = conn->client->session_table;
1841         return smb2srv_session_lookup_raw(table, conn, session_id, now,
1842                                           session);
1843 }
1844
1845 NTSTATUS smb2srv_session_lookup_client(struct smbXsrv_client *client,
1846                                        uint64_t session_id, NTTIME now,
1847                                        struct smbXsrv_session **session)
1848 {
1849         struct smbXsrv_session_table *table = client->session_table;
1850         return smb2srv_session_lookup_raw(table, NULL, session_id, now,
1851                                           session);
1852 }
1853
1854 struct smbXsrv_session_global_traverse_state {
1855         int (*fn)(struct smbXsrv_session_global0 *, void *);
1856         void *private_data;
1857 };
1858
1859 static int smbXsrv_session_global_traverse_fn(struct db_record *rec, void *data)
1860 {
1861         int ret = -1;
1862         struct smbXsrv_session_global_traverse_state *state =
1863                 (struct smbXsrv_session_global_traverse_state*)data;
1864         TDB_DATA key = dbwrap_record_get_key(rec);
1865         TDB_DATA val = dbwrap_record_get_value(rec);
1866         DATA_BLOB blob = data_blob_const(val.dptr, val.dsize);
1867         struct smbXsrv_session_globalB global_blob;
1868         enum ndr_err_code ndr_err;
1869         TALLOC_CTX *frame = talloc_stackframe();
1870
1871         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
1872                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_session_globalB);
1873         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1874                 DEBUG(1,("Invalid record in smbXsrv_session_global.tdb:"
1875                          "key '%s' ndr_pull_struct_blob - %s\n",
1876                          hex_encode_talloc(frame, key.dptr, key.dsize),
1877                          ndr_errstr(ndr_err)));
1878                 goto done;
1879         }
1880
1881         if (global_blob.version != SMBXSRV_VERSION_0) {
1882                 DEBUG(1,("Invalid record in smbXsrv_session_global.tdb:"
1883                          "key '%s' unsuported version - %d\n",
1884                          hex_encode_talloc(frame, key.dptr, key.dsize),
1885                          (int)global_blob.version));
1886                 goto done;
1887         }
1888
1889         global_blob.info.info0->db_rec = rec;
1890         ret = state->fn(global_blob.info.info0, state->private_data);
1891 done:
1892         TALLOC_FREE(frame);
1893         return ret;
1894 }
1895
1896 NTSTATUS smbXsrv_session_global_traverse(
1897                         int (*fn)(struct smbXsrv_session_global0 *, void *),
1898                         void *private_data)
1899 {
1900
1901         NTSTATUS status;
1902         int count = 0;
1903         struct smbXsrv_session_global_traverse_state state = {
1904                 .fn = fn,
1905                 .private_data = private_data,
1906         };
1907
1908         become_root();
1909         status = smbXsrv_session_global_init();
1910         if (!NT_STATUS_IS_OK(status)) {
1911                 unbecome_root();
1912                 DEBUG(0, ("Failed to initialize session_global: %s\n",
1913                           nt_errstr(status)));
1914                 return status;
1915         }
1916
1917         status = dbwrap_traverse_read(smbXsrv_session_global_db_ctx,
1918                                       smbXsrv_session_global_traverse_fn,
1919                                       &state,
1920                                       &count);
1921         unbecome_root();
1922
1923         return status;
1924 }