s4:ldap_server: Add copy of nonā€privileged ops specifically for ldapi connections
[samba.git] / source4 / ldap_server / ldap_server.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    LDAP server
5
6    Copyright (C) Andrew Tridgell 2005
7    Copyright (C) Volker Lendecke 2004
8    Copyright (C) Stefan Metzmacher 2004
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/network.h"
26 #include "lib/events/events.h"
27 #include "auth/auth.h"
28 #include "auth/credentials/credentials.h"
29 #include "librpc/gen_ndr/ndr_samr.h"
30 #include "../lib/util/dlinklist.h"
31 #include "../lib/util/asn1.h"
32 #include "ldap_server/ldap_server.h"
33 #include "samba/service_task.h"
34 #include "samba/service_stream.h"
35 #include "samba/service.h"
36 #include "samba/process_model.h"
37 #include "lib/tls/tls.h"
38 #include "lib/messaging/irpc.h"
39 #include <ldb.h>
40 #include <ldb_errors.h>
41 #include "libcli/ldap/ldap_proto.h"
42 #include "system/network.h"
43 #include "lib/socket/netif.h"
44 #include "dsdb/samdb/samdb.h"
45 #include "param/param.h"
46 #include "../lib/tsocket/tsocket.h"
47 #include "../lib/util/tevent_ntstatus.h"
48 #include "../libcli/util/tstream.h"
49 #include "libds/common/roles.h"
50 #include "lib/util/time.h"
51 #include "lib/util/server_id.h"
52 #include "lib/util/server_id_db.h"
53 #include "lib/messaging/messaging_internal.h"
54
55 #undef strcasecmp
56
57 static void ldapsrv_terminate_connection_done(struct tevent_req *subreq);
58
59 /*
60   close the socket and shutdown a server_context
61 */
62 static void ldapsrv_terminate_connection(struct ldapsrv_connection *conn,
63                                          const char *reason)
64 {
65         struct tevent_req *subreq;
66
67         if (conn->limits.reason) {
68                 return;
69         }
70
71         DLIST_REMOVE(conn->service->connections, conn);
72
73         conn->limits.endtime = timeval_current_ofs(0, 500);
74
75         tevent_queue_stop(conn->sockets.send_queue);
76         TALLOC_FREE(conn->sockets.read_req);
77         TALLOC_FREE(conn->deferred_expire_disconnect);
78         if (conn->active_call) {
79                 tevent_req_cancel(conn->active_call);
80                 conn->active_call = NULL;
81         }
82
83         conn->limits.reason = talloc_strdup(conn, reason);
84         if (conn->limits.reason == NULL) {
85                 TALLOC_FREE(conn->sockets.tls);
86                 TALLOC_FREE(conn->sockets.sasl);
87                 TALLOC_FREE(conn->sockets.raw);
88                 stream_terminate_connection(conn->connection, reason);
89                 return;
90         }
91
92         subreq = tstream_disconnect_send(conn,
93                                          conn->connection->event.ctx,
94                                          conn->sockets.active);
95         if (subreq == NULL) {
96                 TALLOC_FREE(conn->sockets.tls);
97                 TALLOC_FREE(conn->sockets.sasl);
98                 TALLOC_FREE(conn->sockets.raw);
99                 stream_terminate_connection(conn->connection, reason);
100                 return;
101         }
102         tevent_req_set_endtime(subreq,
103                                conn->connection->event.ctx,
104                                conn->limits.endtime);
105         tevent_req_set_callback(subreq, ldapsrv_terminate_connection_done, conn);
106 }
107
108 static void ldapsrv_terminate_connection_done(struct tevent_req *subreq)
109 {
110         struct ldapsrv_connection *conn =
111                 tevent_req_callback_data(subreq,
112                 struct ldapsrv_connection);
113         int sys_errno;
114         bool ok;
115
116         tstream_disconnect_recv(subreq, &sys_errno);
117         TALLOC_FREE(subreq);
118
119         if (conn->sockets.active == conn->sockets.raw) {
120                 TALLOC_FREE(conn->sockets.tls);
121                 TALLOC_FREE(conn->sockets.sasl);
122                 TALLOC_FREE(conn->sockets.raw);
123                 stream_terminate_connection(conn->connection,
124                                             conn->limits.reason);
125                 return;
126         }
127
128         TALLOC_FREE(conn->sockets.tls);
129         TALLOC_FREE(conn->sockets.sasl);
130         conn->sockets.active = conn->sockets.raw;
131
132         subreq = tstream_disconnect_send(conn,
133                                          conn->connection->event.ctx,
134                                          conn->sockets.active);
135         if (subreq == NULL) {
136                 TALLOC_FREE(conn->sockets.raw);
137                 stream_terminate_connection(conn->connection,
138                                             conn->limits.reason);
139                 return;
140         }
141         ok = tevent_req_set_endtime(subreq,
142                                     conn->connection->event.ctx,
143                                     conn->limits.endtime);
144         if (!ok) {
145                 TALLOC_FREE(conn->sockets.raw);
146                 stream_terminate_connection(conn->connection,
147                                             conn->limits.reason);
148                 return;
149         }
150         tevent_req_set_callback(subreq, ldapsrv_terminate_connection_done, conn);
151 }
152
153 /*
154   called when a LDAP socket becomes readable
155 */
156 void ldapsrv_recv(struct stream_connection *c, uint16_t flags)
157 {
158         smb_panic(__location__);
159 }
160
161 /*
162   called when a LDAP socket becomes writable
163 */
164 static void ldapsrv_send(struct stream_connection *c, uint16_t flags)
165 {
166         smb_panic(__location__);
167 }
168
169 static int ldapsrv_load_limits(struct ldapsrv_connection *conn)
170 {
171         TALLOC_CTX *tmp_ctx;
172         const char *attrs[] = { "configurationNamingContext", NULL };
173         const char *attrs2[] = { "lDAPAdminLimits", NULL };
174         struct ldb_message_element *el;
175         struct ldb_result *res = NULL;
176         struct ldb_dn *basedn;
177         struct ldb_dn *conf_dn;
178         struct ldb_dn *policy_dn;
179         unsigned int i;
180         int ret;
181
182         /* set defaults limits in case of failure */
183         conn->limits.initial_timeout = 120;
184         conn->limits.conn_idle_time = 900;
185         conn->limits.max_page_size = 1000;
186         conn->limits.max_notifications = 5;
187         conn->limits.search_timeout = 120;
188         conn->limits.expire_time = (struct timeval) {
189                 .tv_sec = get_time_t_max(),
190         };
191
192
193         tmp_ctx = talloc_new(conn);
194         if (tmp_ctx == NULL) {
195                 return -1;
196         }
197
198         basedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);
199         if (basedn == NULL) {
200                 goto failed;
201         }
202
203         ret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL);
204         if (ret != LDB_SUCCESS) {
205                 goto failed;
206         }
207
208         if (res->count != 1) {
209                 goto failed;
210         }
211
212         conf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], "configurationNamingContext");
213         if (conf_dn == NULL) {
214                 goto failed;
215         }
216
217         policy_dn = ldb_dn_copy(tmp_ctx, conf_dn);
218         ldb_dn_add_child_fmt(policy_dn, "CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services");
219         if (policy_dn == NULL) {
220                 goto failed;
221         }
222
223         ret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL);
224         if (ret != LDB_SUCCESS) {
225                 goto failed;
226         }
227
228         if (res->count != 1) {
229                 goto failed;
230         }
231
232         el = ldb_msg_find_element(res->msgs[0], "lDAPAdminLimits");
233         if (el == NULL) {
234                 goto failed;
235         }
236
237         for (i = 0; i < el->num_values; i++) {
238                 char policy_name[256];
239                 int policy_value, s;
240
241                 s = sscanf((const char *)el->values[i].data, "%255[^=]=%d", policy_name, &policy_value);
242                 if (s != 2 || policy_value == 0)
243                         continue;
244                 if (strcasecmp("InitRecvTimeout", policy_name) == 0) {
245                         conn->limits.initial_timeout = policy_value;
246                         continue;
247                 }
248                 if (strcasecmp("MaxConnIdleTime", policy_name) == 0) {
249                         conn->limits.conn_idle_time = policy_value;
250                         continue;
251                 }
252                 if (strcasecmp("MaxPageSize", policy_name) == 0) {
253                         conn->limits.max_page_size = policy_value;
254                         continue;
255                 }
256                 if (strcasecmp("MaxNotificationPerConn", policy_name) == 0) {
257                         conn->limits.max_notifications = policy_value;
258                         continue;
259                 }
260                 if (strcasecmp("MaxQueryDuration", policy_name) == 0) {
261                         if (policy_value > 0) {
262                                 conn->limits.search_timeout = policy_value;
263                         }
264                         continue;
265                 }
266         }
267
268         return 0;
269
270 failed:
271         DBG_ERR("Failed to load ldap server query policies\n");
272         talloc_free(tmp_ctx);
273         return -1;
274 }
275
276 static int ldapsrv_call_destructor(struct ldapsrv_call *call)
277 {
278         if (call->conn == NULL) {
279                 return 0;
280         }
281
282         DLIST_REMOVE(call->conn->pending_calls, call);
283
284         call->conn = NULL;
285         return 0;
286 }
287
288 static struct tevent_req *ldapsrv_process_call_send(TALLOC_CTX *mem_ctx,
289                                                     struct tevent_context *ev,
290                                                     struct tevent_queue *call_queue,
291                                                     struct ldapsrv_call *call);
292 static NTSTATUS ldapsrv_process_call_recv(struct tevent_req *req);
293
294 static bool ldapsrv_call_read_next(struct ldapsrv_connection *conn);
295 static void ldapsrv_accept_tls_done(struct tevent_req *subreq);
296
297 /*
298   initialise a server_context from a open socket and register a event handler
299   for reading from that socket
300 */
301 static void ldapsrv_accept(struct stream_connection *c,
302                            struct auth_session_info *session_info,
303                            bool is_privileged)
304 {
305         struct ldapsrv_service *ldapsrv_service =
306                 talloc_get_type(c->private_data, struct ldapsrv_service);
307         struct ldapsrv_connection *conn;
308         struct cli_credentials *server_credentials;
309         struct socket_address *socket_address;
310         int port;
311         int ret;
312         struct tevent_req *subreq;
313         struct timeval endtime;
314         char *errstring = NULL;
315
316         conn = talloc_zero(c, struct ldapsrv_connection);
317         if (!conn) {
318                 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
319                 return;
320         }
321         conn->is_privileged = is_privileged;
322
323         conn->sockets.send_queue = tevent_queue_create(conn, "ldapsrv send queue");
324         if (conn->sockets.send_queue == NULL) {
325                 stream_terminate_connection(c,
326                                             "ldapsrv_accept: tevent_queue_create failed");
327                 return;
328         }
329
330         TALLOC_FREE(c->event.fde);
331
332         ret = tstream_bsd_existing_socket(conn,
333                                           socket_get_fd(c->socket),
334                                           &conn->sockets.raw);
335         if (ret == -1) {
336                 stream_terminate_connection(c,
337                                             "ldapsrv_accept: out of memory");
338                 return;
339         }
340         socket_set_flags(c->socket, SOCKET_FLAG_NOCLOSE);
341         /* as server we want to fail early */
342         tstream_bsd_fail_readv_first_error(conn->sockets.raw, true);
343
344         conn->connection  = c;
345         conn->service     = ldapsrv_service;
346         conn->lp_ctx      = ldapsrv_service->lp_ctx;
347
348         c->private_data   = conn;
349
350         socket_address = socket_get_my_addr(c->socket, conn);
351         if (!socket_address) {
352                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: failed to obtain local socket address!");
353                 return;
354         }
355         port = socket_address->port;
356         talloc_free(socket_address);
357         if (port == 3268 || port == 3269) /* Global catalog */ {
358                 conn->global_catalog = true;
359         }
360
361         server_credentials = cli_credentials_init_server(conn, conn->lp_ctx);
362         if (!server_credentials) {
363                 stream_terminate_connection(c, "Failed to init server credentials\n");
364                 return;
365         }
366
367         conn->server_credentials = server_credentials;
368
369         conn->session_info = session_info;
370
371         conn->sockets.active = conn->sockets.raw;
372
373         if (conn->is_privileged) {
374                 conn->require_strong_auth = LDAP_SERVER_REQUIRE_STRONG_AUTH_NO;
375         } else {
376                 conn->require_strong_auth = lpcfg_ldap_server_require_strong_auth(conn->lp_ctx);
377         }
378
379         ret = ldapsrv_backend_Init(conn, &errstring);
380         if (ret != LDB_SUCCESS) {
381                 char *reason = talloc_asprintf(conn,
382                                                "LDB backend for LDAP Init "
383                                                "failed: %s: %s",
384                                                errstring, ldb_strerror(ret));
385                 ldapsrv_terminate_connection(conn, reason);
386                 return;
387         }
388
389         /* load limits from the conf partition */
390         ldapsrv_load_limits(conn); /* should we fail on error ? */
391
392         /* register the server */
393         irpc_add_name(c->msg_ctx, "ldap_server");
394
395         DLIST_ADD_END(ldapsrv_service->connections, conn);
396
397         if (port != 636 && port != 3269) {
398                 ldapsrv_call_read_next(conn);
399                 return;
400         }
401
402         endtime = timeval_current_ofs(conn->limits.conn_idle_time, 0);
403
404         subreq = tstream_tls_accept_send(conn,
405                                          conn->connection->event.ctx,
406                                          conn->sockets.raw,
407                                          conn->service->tls_params);
408         if (subreq == NULL) {
409                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: "
410                                 "no memory for tstream_tls_accept_send");
411                 return;
412         }
413         tevent_req_set_endtime(subreq,
414                                conn->connection->event.ctx,
415                                endtime);
416         tevent_req_set_callback(subreq, ldapsrv_accept_tls_done, conn);
417 }
418
419 static void ldapsrv_accept_tls_done(struct tevent_req *subreq)
420 {
421         struct ldapsrv_connection *conn =
422                 tevent_req_callback_data(subreq,
423                 struct ldapsrv_connection);
424         int ret;
425         int sys_errno;
426
427         ret = tstream_tls_accept_recv(subreq, &sys_errno,
428                                       conn, &conn->sockets.tls);
429         TALLOC_FREE(subreq);
430         if (ret == -1) {
431                 const char *reason;
432
433                 reason = talloc_asprintf(conn, "ldapsrv_accept_tls_loop: "
434                                          "tstream_tls_accept_recv() - %d:%s",
435                                          sys_errno, strerror(sys_errno));
436                 if (!reason) {
437                         reason = "ldapsrv_accept_tls_loop: "
438                                  "tstream_tls_accept_recv() - failed";
439                 }
440
441                 ldapsrv_terminate_connection(conn, reason);
442                 return;
443         }
444
445         conn->sockets.active = conn->sockets.tls;
446         conn->referral_scheme = LDAP_REFERRAL_SCHEME_LDAPS;
447         ldapsrv_call_read_next(conn);
448 }
449
450 static void ldapsrv_call_read_done(struct tevent_req *subreq);
451 static NTSTATUS ldapsrv_packet_check(
452         struct tstream_context *stream,
453         void *private_data,
454         DATA_BLOB blob,
455         size_t *packet_size);
456
457 static bool ldapsrv_call_read_next(struct ldapsrv_connection *conn)
458 {
459         struct tevent_req *subreq;
460
461         if (conn->pending_calls != NULL) {
462                 conn->limits.endtime = timeval_zero();
463
464                 ldapsrv_notification_retry_setup(conn->service, false);
465         } else if (timeval_is_zero(&conn->limits.endtime)) {
466                 conn->limits.endtime =
467                         timeval_current_ofs(conn->limits.initial_timeout, 0);
468         } else {
469                 conn->limits.endtime =
470                         timeval_current_ofs(conn->limits.conn_idle_time, 0);
471         }
472
473         if (conn->sockets.read_req != NULL) {
474                 return true;
475         }
476
477         /*
478          * The minimum size of a LDAP pdu is 7 bytes
479          *
480          * dumpasn1 -hh ldap-unbind-min.dat
481          *
482          *     <30 05 02 01 09 42 00>
483          *    0    5: SEQUENCE {
484          *     <02 01 09>
485          *    2    1:   INTEGER 9
486          *     <42 00>
487          *    5    0:   [APPLICATION 2]
488          *          :     Error: Object has zero length.
489          *          :   }
490          *
491          * dumpasn1 -hh ldap-unbind-windows.dat
492          *
493          *     <30 84 00 00 00 05 02 01 09 42 00>
494          *    0    5: SEQUENCE {
495          *     <02 01 09>
496          *    6    1:   INTEGER 9
497          *     <42 00>
498          *    9    0:   [APPLICATION 2]
499          *          :     Error: Object has zero length.
500          *          :   }
501          *
502          * This means using an initial read size
503          * of 7 is ok.
504          */
505         subreq = tstream_read_pdu_blob_send(conn,
506                                             conn->connection->event.ctx,
507                                             conn->sockets.active,
508                                             7, /* initial_read_size */
509                                             ldapsrv_packet_check,
510                                             conn);
511         if (subreq == NULL) {
512                 ldapsrv_terminate_connection(conn, "ldapsrv_call_read_next: "
513                                 "no memory for tstream_read_pdu_blob_send");
514                 return false;
515         }
516         if (!timeval_is_zero(&conn->limits.endtime)) {
517                 bool ok;
518                 ok = tevent_req_set_endtime(subreq,
519                                             conn->connection->event.ctx,
520                                             conn->limits.endtime);
521                 if (!ok) {
522                         ldapsrv_terminate_connection(
523                                 conn,
524                                 "ldapsrv_call_read_next: "
525                                 "no memory for tevent_req_set_endtime");
526                         return false;
527                 }
528         }
529         tevent_req_set_callback(subreq, ldapsrv_call_read_done, conn);
530         conn->sockets.read_req = subreq;
531         return true;
532 }
533
534 static void ldapsrv_call_process_done(struct tevent_req *subreq);
535 static int ldapsrv_check_packet_size(
536         struct ldapsrv_connection *conn,
537         size_t size);
538
539 static void ldapsrv_call_read_done(struct tevent_req *subreq)
540 {
541         struct ldapsrv_connection *conn =
542                 tevent_req_callback_data(subreq,
543                 struct ldapsrv_connection);
544         NTSTATUS status;
545         struct ldapsrv_call *call;
546         struct asn1_data *asn1;
547         DATA_BLOB blob;
548         int ret = LDAP_SUCCESS;
549         struct ldap_request_limits limits = {0};
550
551         conn->sockets.read_req = NULL;
552
553         call = talloc_zero(conn, struct ldapsrv_call);
554         if (!call) {
555                 ldapsrv_terminate_connection(conn, "no memory");
556                 return;
557         }
558         talloc_set_destructor(call, ldapsrv_call_destructor);
559
560         call->conn = conn;
561
562         status = tstream_read_pdu_blob_recv(subreq,
563                                             call,
564                                             &blob);
565         TALLOC_FREE(subreq);
566         if (!NT_STATUS_IS_OK(status)) {
567                 const char *reason;
568
569                 reason = talloc_asprintf(call, "ldapsrv_call_loop: "
570                                          "tstream_read_pdu_blob_recv() - %s",
571                                          nt_errstr(status));
572                 if (!reason) {
573                         reason = nt_errstr(status);
574                 }
575
576                 ldapsrv_terminate_connection(conn, reason);
577                 return;
578         }
579
580         ret = ldapsrv_check_packet_size(conn, blob.length);
581         if (ret != LDAP_SUCCESS) {
582                 ldapsrv_terminate_connection(
583                         conn,
584                         "Request packet too large");
585                 return;
586         }
587
588         asn1 = asn1_init(call, ASN1_MAX_TREE_DEPTH);
589         if (asn1 == NULL) {
590                 ldapsrv_terminate_connection(conn, "no memory");
591                 return;
592         }
593
594         call->request = talloc(call, struct ldap_message);
595         if (call->request == NULL) {
596                 ldapsrv_terminate_connection(conn, "no memory");
597                 return;
598         }
599
600         asn1_load_nocopy(asn1, blob.data, blob.length);
601
602         limits.max_search_size =
603                 lpcfg_ldap_max_search_request_size(conn->lp_ctx);
604         status = ldap_decode(
605                 asn1,
606                 &limits,
607                 samba_ldap_control_handlers(),
608                 call->request);
609         if (!NT_STATUS_IS_OK(status)) {
610                 ldapsrv_terminate_connection(conn, nt_errstr(status));
611                 return;
612         }
613
614         data_blob_free(&blob);
615         TALLOC_FREE(asn1);
616
617
618         /* queue the call in the global queue */
619         subreq = ldapsrv_process_call_send(call,
620                                            conn->connection->event.ctx,
621                                            conn->service->call_queue,
622                                            call);
623         if (subreq == NULL) {
624                 ldapsrv_terminate_connection(conn, "ldapsrv_process_call_send failed");
625                 return;
626         }
627         tevent_req_set_callback(subreq, ldapsrv_call_process_done, call);
628         conn->active_call = subreq;
629 }
630
631 static void ldapsrv_call_wait_done(struct tevent_req *subreq);
632 static void ldapsrv_call_writev_start(struct ldapsrv_call *call);
633 static void ldapsrv_call_writev_done(struct tevent_req *subreq);
634
635 static void ldapsrv_call_process_done(struct tevent_req *subreq)
636 {
637         struct ldapsrv_call *call =
638                 tevent_req_callback_data(subreq,
639                 struct ldapsrv_call);
640         struct ldapsrv_connection *conn = call->conn;
641         NTSTATUS status;
642
643         conn->active_call = NULL;
644
645         status = ldapsrv_process_call_recv(subreq);
646         TALLOC_FREE(subreq);
647         if (!NT_STATUS_IS_OK(status)) {
648                 ldapsrv_terminate_connection(conn, nt_errstr(status));
649                 return;
650         }
651
652         if (call->wait_send != NULL) {
653                 subreq = call->wait_send(call,
654                                          conn->connection->event.ctx,
655                                          call->wait_private);
656                 if (subreq == NULL) {
657                         ldapsrv_terminate_connection(conn,
658                                         "ldapsrv_call_process_done: "
659                                         "call->wait_send - no memory");
660                         return;
661                 }
662                 tevent_req_set_callback(subreq,
663                                         ldapsrv_call_wait_done,
664                                         call);
665                 conn->active_call = subreq;
666                 return;
667         }
668
669         ldapsrv_call_writev_start(call);
670 }
671
672 static void ldapsrv_call_wait_done(struct tevent_req *subreq)
673 {
674         struct ldapsrv_call *call =
675                 tevent_req_callback_data(subreq,
676                 struct ldapsrv_call);
677         struct ldapsrv_connection *conn = call->conn;
678         NTSTATUS status;
679
680         conn->active_call = NULL;
681
682         status = call->wait_recv(subreq);
683         TALLOC_FREE(subreq);
684         if (!NT_STATUS_IS_OK(status)) {
685                 const char *reason;
686
687                 reason = talloc_asprintf(call, "ldapsrv_call_wait_done: "
688                                          "call->wait_recv() - %s",
689                                          nt_errstr(status));
690                 if (reason == NULL) {
691                         reason = nt_errstr(status);
692                 }
693
694                 ldapsrv_terminate_connection(conn, reason);
695                 return;
696         }
697
698         ldapsrv_call_writev_start(call);
699 }
700
701 static void ldapsrv_call_writev_start(struct ldapsrv_call *call)
702 {
703         struct ldapsrv_connection *conn = call->conn;
704         struct ldapsrv_reply *reply = NULL;
705         struct tevent_req *subreq = NULL;
706         struct timeval endtime;
707         size_t length = 0;
708         size_t i;
709
710         call->iov_count = 0;
711
712         /* build all the replies into an IOV (no copy) */
713         for (reply = call->replies;
714              reply != NULL;
715              reply = reply->next) {
716
717                 /* Cap output at 25MB per writev() */
718                 if (length > length + reply->blob.length
719                     || length + reply->blob.length > LDAP_SERVER_MAX_CHUNK_SIZE) {
720                         break;
721                 }
722
723                 /*
724                  * Overflow is harmless here, just used below to
725                  * decide if to read or write, but checked above anyway
726                  */
727                 length += reply->blob.length;
728
729                 /*
730                  * At worst an overflow would mean we send less
731                  * replies
732                  */
733                 call->iov_count++;
734         }
735
736         if (length == 0) {
737                 if (!call->notification.busy) {
738                         TALLOC_FREE(call);
739                 }
740
741                 ldapsrv_call_read_next(conn);
742                 return;
743         }
744
745         /* Cap call->iov_count at IOV_MAX */
746         call->iov_count = MIN(call->iov_count, IOV_MAX);
747
748         call->out_iov = talloc_array(call,
749                                      struct iovec,
750                                      call->iov_count);
751         if (!call->out_iov) {
752                 /* This is not ideal */
753                 ldapsrv_terminate_connection(conn,
754                                              "failed to allocate "
755                                              "iovec array");
756                 return;
757         }
758
759         /* We may have had to cap the number of replies at IOV_MAX */
760         for (i = 0;
761              i < call->iov_count && call->replies != NULL;
762              i++) {
763                 reply = call->replies;
764                 call->out_iov[i].iov_base = reply->blob.data;
765                 call->out_iov[i].iov_len = reply->blob.length;
766
767                 /* Keep only the ASN.1 encoded data */
768                 talloc_steal(call->out_iov, reply->blob.data);
769
770                 DLIST_REMOVE(call->replies, reply);
771                 TALLOC_FREE(reply);
772         }
773
774         if (i > call->iov_count) {
775                 /* This is not ideal, but also (essentially) impossible */
776                 ldapsrv_terminate_connection(conn,
777                                              "call list ended"
778                                              "before iov_count");
779                 return;
780         }
781
782         subreq = tstream_writev_queue_send(call,
783                                            conn->connection->event.ctx,
784                                            conn->sockets.active,
785                                            conn->sockets.send_queue,
786                                            call->out_iov, call->iov_count);
787         if (subreq == NULL) {
788                 ldapsrv_terminate_connection(conn, "stream_writev_queue_send failed");
789                 return;
790         }
791         endtime = timeval_current_ofs(conn->limits.conn_idle_time, 0);
792         tevent_req_set_endtime(subreq,
793                                conn->connection->event.ctx,
794                                endtime);
795         tevent_req_set_callback(subreq, ldapsrv_call_writev_done, call);
796 }
797
798 static void ldapsrv_call_postprocess_done(struct tevent_req *subreq);
799
800 static void ldapsrv_call_writev_done(struct tevent_req *subreq)
801 {
802         struct ldapsrv_call *call =
803                 tevent_req_callback_data(subreq,
804                 struct ldapsrv_call);
805         struct ldapsrv_connection *conn = call->conn;
806         int sys_errno;
807         int rc;
808
809         rc = tstream_writev_queue_recv(subreq, &sys_errno);
810         TALLOC_FREE(subreq);
811
812         /* This releases the ASN.1 encoded packets from memory */
813         TALLOC_FREE(call->out_iov);
814         if (rc == -1) {
815                 const char *reason;
816
817                 reason = talloc_asprintf(call, "ldapsrv_call_writev_done: "
818                                          "tstream_writev_queue_recv() - %d:%s",
819                                          sys_errno, strerror(sys_errno));
820                 if (reason == NULL) {
821                         reason = "ldapsrv_call_writev_done: "
822                                  "tstream_writev_queue_recv() failed";
823                 }
824
825                 ldapsrv_terminate_connection(conn, reason);
826                 return;
827         }
828
829         if (call->postprocess_send) {
830                 subreq = call->postprocess_send(call,
831                                                 conn->connection->event.ctx,
832                                                 call->postprocess_private);
833                 if (subreq == NULL) {
834                         ldapsrv_terminate_connection(conn, "ldapsrv_call_writev_done: "
835                                         "call->postprocess_send - no memory");
836                         return;
837                 }
838                 tevent_req_set_callback(subreq,
839                                         ldapsrv_call_postprocess_done,
840                                         call);
841                 return;
842         }
843
844         /* Perhaps still some more to send */
845         if (call->replies != NULL) {
846                 ldapsrv_call_writev_start(call);
847                 return;
848         }
849
850         if (!call->notification.busy) {
851                 TALLOC_FREE(call);
852         }
853
854         ldapsrv_call_read_next(conn);
855 }
856
857 static void ldapsrv_call_postprocess_done(struct tevent_req *subreq)
858 {
859         struct ldapsrv_call *call =
860                 tevent_req_callback_data(subreq,
861                 struct ldapsrv_call);
862         struct ldapsrv_connection *conn = call->conn;
863         NTSTATUS status;
864
865         status = call->postprocess_recv(subreq);
866         TALLOC_FREE(subreq);
867         if (!NT_STATUS_IS_OK(status)) {
868                 const char *reason;
869
870                 reason = talloc_asprintf(call, "ldapsrv_call_postprocess_done: "
871                                          "call->postprocess_recv() - %s",
872                                          nt_errstr(status));
873                 if (reason == NULL) {
874                         reason = nt_errstr(status);
875                 }
876
877                 ldapsrv_terminate_connection(conn, reason);
878                 return;
879         }
880
881         TALLOC_FREE(call);
882
883         ldapsrv_call_read_next(conn);
884 }
885
886 static void ldapsrv_notification_retry_done(struct tevent_req *subreq);
887
888 void ldapsrv_notification_retry_setup(struct ldapsrv_service *service, bool force)
889 {
890         struct ldapsrv_connection *conn = NULL;
891         struct timeval retry;
892         size_t num_pending = 0;
893         size_t num_active = 0;
894
895         if (force) {
896                 TALLOC_FREE(service->notification.retry);
897                 service->notification.generation += 1;
898         }
899
900         if (service->notification.retry != NULL) {
901                 return;
902         }
903
904         for (conn = service->connections; conn != NULL; conn = conn->next) {
905                 if (conn->pending_calls == NULL) {
906                         continue;
907                 }
908
909                 num_pending += 1;
910
911                 if (conn->pending_calls->notification.generation !=
912                     service->notification.generation)
913                 {
914                         num_active += 1;
915                 }
916         }
917
918         if (num_pending == 0) {
919                 return;
920         }
921
922         if (num_active != 0) {
923                 retry = timeval_current_ofs(0, 100);
924         } else {
925                 retry = timeval_current_ofs(5, 0);
926         }
927
928         service->notification.retry = tevent_wakeup_send(service,
929                                                          service->current_ev,
930                                                          retry);
931         if (service->notification.retry == NULL) {
932                 /* retry later */
933                 return;
934         }
935
936         tevent_req_set_callback(service->notification.retry,
937                                 ldapsrv_notification_retry_done,
938                                 service);
939 }
940
941 static void ldapsrv_notification_retry_done(struct tevent_req *subreq)
942 {
943         struct ldapsrv_service *service =
944                 tevent_req_callback_data(subreq,
945                 struct ldapsrv_service);
946         struct ldapsrv_connection *conn = NULL;
947         struct ldapsrv_connection *conn_next = NULL;
948         bool ok;
949
950         service->notification.retry = NULL;
951
952         ok = tevent_wakeup_recv(subreq);
953         TALLOC_FREE(subreq);
954         if (!ok) {
955                 /* ignore */
956         }
957
958         for (conn = service->connections; conn != NULL; conn = conn_next) {
959                 struct ldapsrv_call *call = conn->pending_calls;
960
961                 conn_next = conn->next;
962
963                 if (conn->pending_calls == NULL) {
964                         continue;
965                 }
966
967                 if (conn->active_call != NULL) {
968                         continue;
969                 }
970
971                 DLIST_DEMOTE(conn->pending_calls, call);
972                 call->notification.generation =
973                                 service->notification.generation;
974
975                 /* queue the call in the global queue */
976                 subreq = ldapsrv_process_call_send(call,
977                                                    conn->connection->event.ctx,
978                                                    conn->service->call_queue,
979                                                    call);
980                 if (subreq == NULL) {
981                         ldapsrv_terminate_connection(conn,
982                                         "ldapsrv_process_call_send failed");
983                         continue;
984                 }
985                 tevent_req_set_callback(subreq, ldapsrv_call_process_done, call);
986                 conn->active_call = subreq;
987         }
988
989         ldapsrv_notification_retry_setup(service, false);
990 }
991
992 struct ldapsrv_process_call_state {
993         struct ldapsrv_call *call;
994 };
995
996 static void ldapsrv_process_call_trigger(struct tevent_req *req,
997                                          void *private_data);
998
999 static struct tevent_req *ldapsrv_process_call_send(TALLOC_CTX *mem_ctx,
1000                                                     struct tevent_context *ev,
1001                                                     struct tevent_queue *call_queue,
1002                                                     struct ldapsrv_call *call)
1003 {
1004         struct tevent_req *req;
1005         struct ldapsrv_process_call_state *state;
1006         bool ok;
1007
1008         req = tevent_req_create(mem_ctx, &state,
1009                                 struct ldapsrv_process_call_state);
1010         if (req == NULL) {
1011                 return req;
1012         }
1013
1014         state->call = call;
1015
1016         ok = tevent_queue_add(call_queue, ev, req,
1017                               ldapsrv_process_call_trigger, NULL);
1018         if (!ok) {
1019                 tevent_req_oom(req);
1020                 return tevent_req_post(req, ev);
1021         }
1022
1023         return req;
1024 }
1025
1026 static void ldapsrv_disconnect_ticket_expired(struct tevent_req *subreq);
1027
1028 static void ldapsrv_process_call_trigger(struct tevent_req *req,
1029                                          void *private_data)
1030 {
1031         struct ldapsrv_process_call_state *state =
1032                 tevent_req_data(req,
1033                 struct ldapsrv_process_call_state);
1034         struct ldapsrv_connection *conn = state->call->conn;
1035         NTSTATUS status;
1036
1037         if (conn->deferred_expire_disconnect != NULL) {
1038                 /*
1039                  * Just drop this on the floor
1040                  */
1041                 tevent_req_done(req);
1042                 return;
1043         }
1044
1045         /* make the call */
1046         status = ldapsrv_do_call(state->call);
1047
1048         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)) {
1049                 /*
1050                  * For testing purposes, defer the TCP disconnect
1051                  * after having sent the msgid 0
1052                  * 1.3.6.1.4.1.1466.20036 exop response. LDAP clients
1053                  * should not wait for the TCP connection to close but
1054                  * handle this packet equivalent to a TCP
1055                  * disconnect. This delay enables testing both cases
1056                  * in LDAP client libraries.
1057                  */
1058
1059                 int defer_msec = lpcfg_parm_int(
1060                         conn->lp_ctx,
1061                         NULL,
1062                         "ldap_server",
1063                         "delay_expire_disconnect",
1064                         0);
1065
1066                 conn->deferred_expire_disconnect = tevent_wakeup_send(
1067                         conn,
1068                         conn->connection->event.ctx,
1069                         timeval_current_ofs_msec(defer_msec));
1070                 if (tevent_req_nomem(conn->deferred_expire_disconnect, req)) {
1071                         return;
1072                 }
1073                 tevent_req_set_callback(
1074                         conn->deferred_expire_disconnect,
1075                         ldapsrv_disconnect_ticket_expired,
1076                         conn);
1077
1078                 tevent_req_done(req);
1079                 return;
1080         }
1081
1082         if (!NT_STATUS_IS_OK(status)) {
1083                 tevent_req_nterror(req, status);
1084                 return;
1085         }
1086
1087         tevent_req_done(req);
1088 }
1089
1090 static void ldapsrv_disconnect_ticket_expired(struct tevent_req *subreq)
1091 {
1092         struct ldapsrv_connection *conn = tevent_req_callback_data(
1093                 subreq, struct ldapsrv_connection);
1094         bool ok;
1095
1096         ok = tevent_wakeup_recv(subreq);
1097         TALLOC_FREE(subreq);
1098         if (!ok) {
1099                 DBG_WARNING("tevent_wakeup_recv failed\n");
1100         }
1101         conn->deferred_expire_disconnect = NULL;
1102         ldapsrv_terminate_connection(conn, "network session expired");
1103 }
1104
1105 static NTSTATUS ldapsrv_process_call_recv(struct tevent_req *req)
1106 {
1107         NTSTATUS status;
1108
1109         if (tevent_req_is_nterror(req, &status)) {
1110                 tevent_req_received(req);
1111                 return status;
1112         }
1113
1114         tevent_req_received(req);
1115         return NT_STATUS_OK;
1116 }
1117
1118 static void ldapsrv_accept_nonpriv(struct stream_connection *c)
1119 {
1120         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
1121                 c->private_data, struct ldapsrv_service);
1122         struct auth_session_info *session_info;
1123         NTSTATUS status;
1124
1125         status = auth_anonymous_session_info(
1126                 c, ldapsrv_service->lp_ctx, &session_info);
1127         if (!NT_STATUS_IS_OK(status)) {
1128                 stream_terminate_connection(c, "failed to setup anonymous "
1129                                             "session info");
1130                 return;
1131         }
1132         ldapsrv_accept(c, session_info, false);
1133 }
1134
1135 static const struct stream_server_ops ldap_stream_nonpriv_ops = {
1136         .name                   = "ldap",
1137         .accept_connection      = ldapsrv_accept_nonpriv,
1138         .recv_handler           = ldapsrv_recv,
1139         .send_handler           = ldapsrv_send,
1140 };
1141
1142 static void ldapsrv_accept_nonpriv_ldapi(struct stream_connection *c)
1143 {
1144         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
1145                 c->private_data, struct ldapsrv_service);
1146         struct auth_session_info *session_info;
1147         NTSTATUS status;
1148
1149         status = auth_anonymous_session_info(
1150                 c, ldapsrv_service->lp_ctx, &session_info);
1151         if (!NT_STATUS_IS_OK(status)) {
1152                 stream_terminate_connection(c, "failed to setup anonymous "
1153                                             "session info");
1154                 return;
1155         }
1156         ldapsrv_accept(c, session_info, false);
1157 }
1158
1159 static const struct stream_server_ops ldapi_stream_nonpriv_ops = {
1160         .name                   = "ldap",
1161         .accept_connection      = ldapsrv_accept_nonpriv_ldapi,
1162         .recv_handler           = ldapsrv_recv,
1163         .send_handler           = ldapsrv_send,
1164 };
1165
1166 /* The feature removed behind an #ifdef until we can do it properly
1167  * with an EXTERNAL bind. */
1168
1169 #define WITH_LDAPI_PRIV_SOCKET
1170
1171 #ifdef WITH_LDAPI_PRIV_SOCKET
1172 static void ldapsrv_accept_priv_ldapi(struct stream_connection *c)
1173 {
1174         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
1175                 c->private_data, struct ldapsrv_service);
1176         struct auth_session_info *session_info;
1177
1178         session_info = system_session(ldapsrv_service->lp_ctx);
1179         if (!session_info) {
1180                 stream_terminate_connection(c, "failed to setup system "
1181                                             "session info");
1182                 return;
1183         }
1184         ldapsrv_accept(c, session_info, true);
1185 }
1186
1187 static const struct stream_server_ops ldapi_stream_priv_ops = {
1188         .name                   = "ldap",
1189         .accept_connection      = ldapsrv_accept_priv_ldapi,
1190         .recv_handler           = ldapsrv_recv,
1191         .send_handler           = ldapsrv_send,
1192 };
1193
1194 #endif
1195
1196
1197 /*
1198   add a socket address to the list of events, one event per port
1199 */
1200 static NTSTATUS add_socket(struct task_server *task,
1201                            struct loadparm_context *lp_ctx,
1202                            const struct model_ops *model_ops,
1203                            const char *address, struct ldapsrv_service *ldap_service)
1204 {
1205         uint16_t port = 389;
1206         NTSTATUS status;
1207         struct ldb_context *ldb;
1208
1209         status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1210                                      model_ops, &ldap_stream_nonpriv_ops,
1211                                      "ip", address, &port,
1212                                      lpcfg_socket_options(lp_ctx),
1213                                      ldap_service, task->process_context);
1214         if (!NT_STATUS_IS_OK(status)) {
1215                 DBG_ERR("ldapsrv failed to bind to %s:%u - %s\n",
1216                         address, port, nt_errstr(status));
1217                 return status;
1218         }
1219
1220         if (tstream_tls_params_enabled(ldap_service->tls_params)) {
1221                 /* add ldaps server */
1222                 port = 636;
1223                 status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1224                                              model_ops,
1225                                              &ldap_stream_nonpriv_ops,
1226                                              "ip", address, &port,
1227                                              lpcfg_socket_options(lp_ctx),
1228                                              ldap_service,
1229                                              task->process_context);
1230                 if (!NT_STATUS_IS_OK(status)) {
1231                         DBG_ERR("ldapsrv failed to bind to %s:%u - %s\n",
1232                                 address, port, nt_errstr(status));
1233                         return status;
1234                 }
1235         }
1236
1237         /* Load LDAP database, but only to read our settings */
1238         ldb = samdb_connect(ldap_service,
1239                             ldap_service->current_ev,
1240                             lp_ctx,
1241                             system_session(lp_ctx),
1242                             NULL,
1243                             0);
1244         if (!ldb) {
1245                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1246         }
1247
1248         if (samdb_is_gc(ldb)) {
1249                 port = 3268;
1250                 status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1251                                              model_ops,
1252                                              &ldap_stream_nonpriv_ops,
1253                                              "ip", address, &port,
1254                                              lpcfg_socket_options(lp_ctx),
1255                                              ldap_service,
1256                                              task->process_context);
1257                 if (!NT_STATUS_IS_OK(status)) {
1258                         DBG_ERR("ldapsrv failed to bind to %s:%u - %s\n",
1259                                 address, port, nt_errstr(status));
1260                         return status;
1261                 }
1262                 if (tstream_tls_params_enabled(ldap_service->tls_params)) {
1263                         /* add ldaps server for the global catalog */
1264                         port = 3269;
1265                         status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1266                                                      model_ops,
1267                                                      &ldap_stream_nonpriv_ops,
1268                                                      "ip", address, &port,
1269                                                      lpcfg_socket_options(lp_ctx),
1270                                                      ldap_service,
1271                                                      task->process_context);
1272                         if (!NT_STATUS_IS_OK(status)) {
1273                                 DBG_ERR("ldapsrv failed to bind to %s:%u - %s\n",
1274                                         address, port, nt_errstr(status));
1275                                 return status;
1276                         }
1277                 }
1278         }
1279
1280         /* And once we are bound, free the temporary ldb, it will
1281          * connect again on each incoming LDAP connection */
1282         talloc_unlink(ldap_service, ldb);
1283
1284         return NT_STATUS_OK;
1285 }
1286
1287 static void ldap_reload_certs(struct imessaging_context *msg_ctx,
1288                               void *private_data,
1289                               uint32_t msg_type,
1290                               struct server_id server_id,
1291                               size_t num_fds,
1292                               int *fds,
1293                               DATA_BLOB *data)
1294 {
1295         TALLOC_CTX *frame = talloc_stackframe();
1296         struct ldapsrv_service *ldap_service =
1297                 talloc_get_type_abort(private_data,
1298                 struct ldapsrv_service);
1299         int default_children;
1300         int num_children;
1301         int i;
1302         bool ok;
1303         struct server_id ldap_master_id;
1304         NTSTATUS status;
1305         struct tstream_tls_params *new_tls_params = NULL;
1306
1307         SMB_ASSERT(msg_ctx == ldap_service->current_msg);
1308
1309         /* reload certificates */
1310         status = tstream_tls_params_server(ldap_service,
1311                                            ldap_service->dns_host_name,
1312                                            lpcfg_tls_enabled(ldap_service->lp_ctx),
1313                                            lpcfg_tls_keyfile(frame, ldap_service->lp_ctx),
1314                                            lpcfg_tls_certfile(frame, ldap_service->lp_ctx),
1315                                            lpcfg_tls_cafile(frame, ldap_service->lp_ctx),
1316                                            lpcfg_tls_crlfile(frame, ldap_service->lp_ctx),
1317                                            lpcfg_tls_dhpfile(frame, ldap_service->lp_ctx),
1318                                            lpcfg_tls_priority(ldap_service->lp_ctx),
1319                                            &new_tls_params);
1320         if (!NT_STATUS_IS_OK(status)) {
1321                 DBG_ERR("ldapsrv failed tstream_tls_params_server - %s\n",
1322                         nt_errstr(status));
1323                 TALLOC_FREE(frame);
1324                 return;
1325         }
1326
1327         TALLOC_FREE(ldap_service->tls_params);
1328         ldap_service->tls_params = new_tls_params;
1329
1330         if (getpid() != ldap_service->parent_pid) {
1331                 /*
1332                  * If we are not the master process we are done
1333                  */
1334                 TALLOC_FREE(frame);
1335                 return;
1336         }
1337
1338         /*
1339          * Check we're running under the prefork model,
1340          * by checking if the prefork-master-ldap name
1341          * was registered
1342          */
1343         ok = server_id_db_lookup_one(msg_ctx->names, "prefork-master-ldap", &ldap_master_id);
1344         if (!ok) {
1345                 /*
1346                  * We are done if another process model is in use.
1347                  */
1348                 TALLOC_FREE(frame);
1349                 return;
1350         }
1351
1352         /*
1353          * Now we loop over all possible prefork workers
1354          * in order to notify them about the reload
1355          */
1356         default_children = lpcfg_prefork_children(ldap_service->lp_ctx);
1357         num_children = lpcfg_parm_int(ldap_service->lp_ctx,
1358                                       NULL, "prefork children", "ldap",
1359                                       default_children);
1360         for (i = 0; i < num_children; i++) {
1361                 char child_name[64] = { 0, };
1362                 struct server_id ldap_worker_id;
1363
1364                 snprintf(child_name, sizeof(child_name), "prefork-worker-ldap-%d", i);
1365                 ok = server_id_db_lookup_one(msg_ctx->names, child_name, &ldap_worker_id);
1366                 if (!ok) {
1367                         DBG_ERR("server_id_db_lookup_one(%s) - failed\n",
1368                                 child_name);
1369                         continue;
1370                 }
1371
1372                 status = imessaging_send(msg_ctx, ldap_worker_id,
1373                                          MSG_RELOAD_TLS_CERTIFICATES, NULL);
1374                 if (!NT_STATUS_IS_OK(status)) {
1375                         struct server_id_buf id_buf;
1376                         DBG_ERR("ldapsrv failed imessaging_send(%s, %s) - %s\n",
1377                                 child_name,
1378                                 server_id_str_buf(ldap_worker_id, &id_buf),
1379                                 nt_errstr(status));
1380                         continue;
1381                 }
1382         }
1383
1384         TALLOC_FREE(frame);
1385 }
1386
1387 /*
1388   open the ldap server sockets
1389 */
1390 static NTSTATUS ldapsrv_task_init(struct task_server *task)
1391 {
1392         char *ldapi_path;
1393 #ifdef WITH_LDAPI_PRIV_SOCKET
1394         char *priv_dir;
1395 #endif
1396         struct ldapsrv_service *ldap_service;
1397         NTSTATUS status;
1398
1399         switch (lpcfg_server_role(task->lp_ctx)) {
1400         case ROLE_STANDALONE:
1401                 task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration",
1402                                       false);
1403                 return NT_STATUS_INVALID_DOMAIN_ROLE;
1404         case ROLE_DOMAIN_MEMBER:
1405                 task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration",
1406                                       false);
1407                 return NT_STATUS_INVALID_DOMAIN_ROLE;
1408         case ROLE_ACTIVE_DIRECTORY_DC:
1409                 /* Yes, we want an LDAP server */
1410                 break;
1411         }
1412
1413         task_server_set_title(task, "task[ldapsrv]");
1414
1415         ldap_service = talloc_zero(task, struct ldapsrv_service);
1416         if (ldap_service == NULL) {
1417                 status = NT_STATUS_NO_MEMORY;
1418                 goto failed;
1419         }
1420
1421         ldap_service->lp_ctx = task->lp_ctx;
1422         ldap_service->current_ev = task->event_ctx;
1423         ldap_service->current_msg = task->msg_ctx;
1424
1425         ldap_service->dns_host_name = talloc_asprintf(ldap_service, "%s.%s",
1426                                         lpcfg_netbios_name(task->lp_ctx),
1427                                         lpcfg_dnsdomain(task->lp_ctx));
1428         if (ldap_service->dns_host_name == NULL) {
1429                 status = NT_STATUS_NO_MEMORY;
1430                 goto failed;
1431         }
1432
1433         ldap_service->parent_pid = getpid();
1434
1435         status = tstream_tls_params_server(ldap_service,
1436                                            ldap_service->dns_host_name,
1437                                            lpcfg_tls_enabled(task->lp_ctx),
1438                                            lpcfg_tls_keyfile(ldap_service, task->lp_ctx),
1439                                            lpcfg_tls_certfile(ldap_service, task->lp_ctx),
1440                                            lpcfg_tls_cafile(ldap_service, task->lp_ctx),
1441                                            lpcfg_tls_crlfile(ldap_service, task->lp_ctx),
1442                                            lpcfg_tls_dhpfile(ldap_service, task->lp_ctx),
1443                                            lpcfg_tls_priority(task->lp_ctx),
1444                                            &ldap_service->tls_params);
1445         if (!NT_STATUS_IS_OK(status)) {
1446                 DBG_ERR("ldapsrv failed tstream_tls_params_server - %s\n",
1447                         nt_errstr(status));
1448                 goto failed;
1449         }
1450
1451         ldap_service->call_queue = tevent_queue_create(ldap_service, "ldapsrv_call_queue");
1452         if (ldap_service->call_queue == NULL) {
1453                 status = NT_STATUS_NO_MEMORY;
1454                 goto failed;
1455         }
1456
1457         if (lpcfg_interfaces(task->lp_ctx) && lpcfg_bind_interfaces_only(task->lp_ctx)) {
1458                 struct interface *ifaces;
1459                 int num_interfaces;
1460                 int i;
1461
1462                 load_interface_list(task, task->lp_ctx, &ifaces);
1463                 num_interfaces = iface_list_count(ifaces);
1464
1465                 /* We have been given an interfaces line, and been
1466                    told to only bind to those interfaces. Create a
1467                    socket per interface and bind to only these.
1468                 */
1469                 for(i = 0; i < num_interfaces; i++) {
1470                         const char *address = iface_list_n_ip(ifaces, i);
1471                         status = add_socket(task, task->lp_ctx, task->model_ops,
1472                                             address, ldap_service);
1473                         if (!NT_STATUS_IS_OK(status)) goto failed;
1474                 }
1475         } else {
1476                 char **wcard;
1477                 size_t i;
1478                 size_t num_binds = 0;
1479                 wcard = iface_list_wildcard(task);
1480                 if (wcard == NULL) {
1481                         DBG_ERR("No wildcard addresses available\n");
1482                         status = NT_STATUS_UNSUCCESSFUL;
1483                         goto failed;
1484                 }
1485                 for (i=0; wcard[i]; i++) {
1486                         status = add_socket(task, task->lp_ctx, task->model_ops,
1487                                             wcard[i], ldap_service);
1488                         if (NT_STATUS_IS_OK(status)) {
1489                                 num_binds++;
1490                         }
1491                 }
1492                 talloc_free(wcard);
1493                 if (num_binds == 0) {
1494                         status = NT_STATUS_UNSUCCESSFUL;
1495                         goto failed;
1496                 }
1497         }
1498
1499         ldapi_path = lpcfg_private_path(ldap_service, task->lp_ctx, "ldapi");
1500         if (!ldapi_path) {
1501                 status = NT_STATUS_UNSUCCESSFUL;
1502                 goto failed;
1503         }
1504
1505         status = stream_setup_socket(task, task->event_ctx, task->lp_ctx,
1506                                      task->model_ops, &ldapi_stream_nonpriv_ops,
1507                                      "unix", ldapi_path, NULL,
1508                                      lpcfg_socket_options(task->lp_ctx),
1509                                      ldap_service, task->process_context);
1510         talloc_free(ldapi_path);
1511         if (!NT_STATUS_IS_OK(status)) {
1512                 DBG_ERR("ldapsrv failed to bind to %s - %s\n",
1513                         ldapi_path, nt_errstr(status));
1514         }
1515
1516 #ifdef WITH_LDAPI_PRIV_SOCKET
1517         priv_dir = lpcfg_private_path(ldap_service, task->lp_ctx, "ldap_priv");
1518         if (priv_dir == NULL) {
1519                 status = NT_STATUS_UNSUCCESSFUL;
1520                 goto failed;
1521         }
1522         /*
1523          * Make sure the directory for the privileged ldapi socket exists, and
1524          * is of the correct permissions
1525          */
1526         if (!directory_create_or_exist(priv_dir, 0750)) {
1527                 task_server_terminate(task, "Cannot create ldap "
1528                                       "privileged ldapi directory", true);
1529                 return NT_STATUS_UNSUCCESSFUL;
1530         }
1531         ldapi_path = talloc_asprintf(ldap_service, "%s/ldapi", priv_dir);
1532         talloc_free(priv_dir);
1533         if (ldapi_path == NULL) {
1534                 status = NT_STATUS_NO_MEMORY;
1535                 goto failed;
1536         }
1537
1538         status = stream_setup_socket(task, task->event_ctx, task->lp_ctx,
1539                                      task->model_ops, &ldapi_stream_priv_ops,
1540                                      "unix", ldapi_path, NULL,
1541                                      lpcfg_socket_options(task->lp_ctx),
1542                                      ldap_service,
1543                                      task->process_context);
1544         talloc_free(ldapi_path);
1545         if (!NT_STATUS_IS_OK(status)) {
1546                 DBG_ERR("ldapsrv failed to bind to %s - %s\n",
1547                         ldapi_path, nt_errstr(status));
1548         }
1549
1550 #endif
1551
1552         /* register the server */
1553         irpc_add_name(task->msg_ctx, "ldap_server");
1554
1555         task->private_data = ldap_service;
1556
1557         return NT_STATUS_OK;
1558
1559 failed:
1560         task_server_terminate(task, "Failed to startup ldap server task", true);
1561         return status;
1562 }
1563
1564 /*
1565  * Open a database to be later used by LDB wrap code (although it should be
1566  * plumbed through correctly eventually).
1567  */
1568 static void ldapsrv_post_fork(struct task_server *task, struct process_details *pd)
1569 {
1570         struct ldapsrv_service *ldap_service =
1571                 talloc_get_type_abort(task->private_data, struct ldapsrv_service);
1572
1573         /*
1574          * As ldapsrv_before_loop() may changed the values for the parent loop
1575          * we need to adjust the pointers to the correct value in the child
1576          */
1577         ldap_service->lp_ctx = task->lp_ctx;
1578         ldap_service->current_ev = task->event_ctx;
1579         ldap_service->current_msg = task->msg_ctx;
1580
1581         ldap_service->sam_ctx = samdb_connect(ldap_service,
1582                                               ldap_service->current_ev,
1583                                               ldap_service->lp_ctx,
1584                                               system_session(ldap_service->lp_ctx),
1585                                               NULL,
1586                                               0);
1587         if (ldap_service->sam_ctx == NULL) {
1588                 task_server_terminate(task, "Cannot open system session LDB",
1589                                       true);
1590                 return;
1591         }
1592 }
1593
1594 static void ldapsrv_before_loop(struct task_server *task)
1595 {
1596         struct ldapsrv_service *ldap_service =
1597                 talloc_get_type_abort(task->private_data, struct ldapsrv_service);
1598         NTSTATUS status;
1599
1600         if (ldap_service->sam_ctx != NULL) {
1601                 /*
1602                  * Make sure the values are still the same
1603                  * as set in ldapsrv_post_fork()
1604                  */
1605                 SMB_ASSERT(task->lp_ctx == ldap_service->lp_ctx);
1606                 SMB_ASSERT(task->event_ctx == ldap_service->current_ev);
1607                 SMB_ASSERT(task->msg_ctx == ldap_service->current_msg);
1608         } else {
1609                 /*
1610                  * We need to adjust the pointers to the correct value
1611                  * in the parent loop.
1612                  */
1613                 ldap_service->lp_ctx = task->lp_ctx;
1614                 ldap_service->current_ev = task->event_ctx;
1615                 ldap_service->current_msg = task->msg_ctx;
1616         }
1617
1618         status = imessaging_register(ldap_service->current_msg,
1619                                      ldap_service,
1620                                      MSG_RELOAD_TLS_CERTIFICATES,
1621                                      ldap_reload_certs);
1622         if (!NT_STATUS_IS_OK(status)) {
1623                 task_server_terminate(task, "Cannot register ldap_reload_certs",
1624                                       true);
1625                 return;
1626         }
1627 }
1628
1629 /*
1630  * Check the size of an ldap request packet.
1631  *
1632  * For authenticated connections the maximum packet size is controlled by
1633  * the smb.conf parameter "ldap max authenticated request size"
1634  *
1635  * For anonymous connections the maximum packet size is controlled by
1636  * the smb.conf parameter "ldap max anonymous request size"
1637  */
1638 static int ldapsrv_check_packet_size(
1639         struct ldapsrv_connection *conn,
1640         size_t size)
1641 {
1642         bool is_anonymous = false;
1643         size_t max_size = 0;
1644
1645         max_size = lpcfg_ldap_max_anonymous_request_size(conn->lp_ctx);
1646         if (size <= max_size) {
1647                 return LDAP_SUCCESS;
1648         }
1649
1650         /*
1651          * Request is larger than the maximum unauthenticated request size.
1652          * As this code is called frequently we avoid calling
1653          * security_token_is_anonymous if possible
1654          */
1655         if (conn->session_info != NULL &&
1656                 conn->session_info->security_token != NULL) {
1657                 is_anonymous = security_token_is_anonymous(
1658                         conn->session_info->security_token);
1659         }
1660
1661         if (is_anonymous) {
1662                 DBG_WARNING(
1663                         "LDAP request size (%zu) exceeds (%zu)\n",
1664                         size,
1665                         max_size);
1666                 return LDAP_UNWILLING_TO_PERFORM;
1667         }
1668
1669         max_size = lpcfg_ldap_max_authenticated_request_size(conn->lp_ctx);
1670         if (size > max_size) {
1671                 DBG_WARNING(
1672                         "LDAP request size (%zu) exceeds (%zu)\n",
1673                         size,
1674                         max_size);
1675                 return LDAP_UNWILLING_TO_PERFORM;
1676         }
1677         return LDAP_SUCCESS;
1678
1679 }
1680
1681 /*
1682  * Check that the blob contains enough data to be a valid packet
1683  * If there is a packet header check the size to ensure that it does not
1684  * exceed the maximum sizes.
1685  *
1686  */
1687 static NTSTATUS ldapsrv_packet_check(
1688         struct tstream_context *stream,
1689         void *private_data,
1690         DATA_BLOB blob,
1691         size_t *packet_size)
1692 {
1693         NTSTATUS ret;
1694         struct ldapsrv_connection *conn = private_data;
1695         int result = LDB_SUCCESS;
1696
1697         ret = ldap_full_packet(stream, private_data, blob, packet_size);
1698         if (!NT_STATUS_IS_OK(ret)) {
1699                 return ret;
1700         }
1701         result = ldapsrv_check_packet_size(conn, *packet_size);
1702         if (result != LDAP_SUCCESS) {
1703                 return NT_STATUS_LDAP(result);
1704         }
1705         return NT_STATUS_OK;
1706 }
1707
1708 NTSTATUS server_service_ldap_init(TALLOC_CTX *ctx)
1709 {
1710         static const struct service_details details = {
1711                 .inhibit_fork_on_accept = false,
1712                 .inhibit_pre_fork = false,
1713                 .task_init = ldapsrv_task_init,
1714                 .post_fork = ldapsrv_post_fork,
1715                 .before_loop = ldapsrv_before_loop,
1716         };
1717         return register_server_service(ctx, "ldap", &details);
1718 }