s4:ldap_server: the tls code steals the original socket on its own now
[obnox/samba/samba-obnox.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 "lib/events/events.h"
26 #include "auth/auth.h"
27 #include "auth/credentials/credentials.h"
28 #include "librpc/gen_ndr/ndr_samr.h"
29 #include "../lib/util/dlinklist.h"
30 #include "../lib/util/asn1.h"
31 #include "ldap_server/ldap_server.h"
32 #include "smbd/service_task.h"
33 #include "smbd/service_stream.h"
34 #include "smbd/service.h"
35 #include "smbd/process_model.h"
36 #include "lib/tls/tls.h"
37 #include "lib/messaging/irpc.h"
38 #include "lib/ldb/include/ldb.h"
39 #include "lib/ldb/include/ldb_errors.h"
40 #include "libcli/ldap/ldap.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 /*
47   close the socket and shutdown a server_context
48 */
49 void ldapsrv_terminate_connection(struct ldapsrv_connection *conn, 
50                                          const char *reason)
51 {
52         packet_recv_disable(conn->packet);
53         TALLOC_FREE(conn->packet);
54         stream_terminate_connection(conn->connection, reason);
55 }
56
57 /*
58   handle packet errors
59 */
60 static void ldapsrv_error_handler(void *private_data, NTSTATUS status)
61 {
62         struct ldapsrv_connection *conn = talloc_get_type(private_data,
63                                                           struct ldapsrv_connection);
64         ldapsrv_terminate_connection(conn, nt_errstr(status));
65 }
66
67 /*
68   process a decoded ldap message
69 */
70 static void ldapsrv_process_message(struct ldapsrv_connection *conn,
71                                     struct ldap_message *msg)
72 {
73         struct ldapsrv_call *call;
74         NTSTATUS status;
75         DATA_BLOB blob;
76
77         call = talloc(conn, struct ldapsrv_call);
78         if (!call) {
79                 ldapsrv_terminate_connection(conn, "no memory");
80                 return;         
81         }
82
83         call->request = talloc_steal(call, msg);
84         call->conn = conn;
85         call->replies = NULL;
86         call->send_callback = NULL;
87         call->send_private = NULL;
88
89         /* make the call */
90         status = ldapsrv_do_call(call);
91         if (!NT_STATUS_IS_OK(status)) {
92                 talloc_free(call);
93                 return;
94         }
95
96         blob = data_blob(NULL, 0);
97
98         if (call->replies == NULL) {
99                 talloc_free(call);
100                 return;
101         }
102
103         /* build all the replies into a single blob */
104         while (call->replies) {
105                 DATA_BLOB b;
106                 bool ret;
107
108                 msg = call->replies->msg;
109                 if (!ldap_encode(msg, samba_ldap_control_handlers(), &b, call)) {
110                         DEBUG(0,("Failed to encode ldap reply of type %d\n", msg->type));
111                         talloc_free(call);
112                         return;
113                 }
114
115                 ret = data_blob_append(call, &blob, b.data, b.length);
116                 data_blob_free(&b);
117
118                 talloc_set_name_const(blob.data, "Outgoing, encoded LDAP packet");
119
120                 if (!ret) {
121                         talloc_free(call);
122                         return;
123                 }
124
125                 DLIST_REMOVE(call->replies, call->replies);
126         }
127
128         packet_send_callback(conn->packet, blob, 
129                              call->send_callback, call->send_private);
130         talloc_free(call);
131         return;
132 }
133
134 /*
135   decode/process data
136 */
137 static NTSTATUS ldapsrv_decode(void *private_data, DATA_BLOB blob)
138 {
139         NTSTATUS status;
140         struct ldapsrv_connection *conn = talloc_get_type(private_data,
141                                                           struct ldapsrv_connection);
142         struct asn1_data *asn1 = asn1_init(conn);
143         struct ldap_message *msg = talloc(conn, struct ldap_message);
144
145         if (asn1 == NULL || msg == NULL) {
146                 return NT_STATUS_NO_MEMORY;
147         }
148
149         if (!asn1_load(asn1, blob)) {
150                 talloc_free(msg);
151                 talloc_free(asn1);
152                 return NT_STATUS_NO_MEMORY;
153         }
154
155         status = ldap_decode(asn1, samba_ldap_control_handlers(), msg);
156         if (!NT_STATUS_IS_OK(status)) {
157                 asn1_free(asn1);
158                 return status;
159         }
160
161         data_blob_free(&blob);
162         talloc_steal(conn, msg);
163         asn1_free(asn1);
164
165         ldapsrv_process_message(conn, msg);
166         return NT_STATUS_OK;
167 }
168
169 /*
170  Idle timeout handler
171 */
172 static void ldapsrv_conn_idle_timeout(struct tevent_context *ev,
173                                       struct tevent_timer *te,
174                                       struct timeval t,
175                                       void *private_data)
176 {
177         struct ldapsrv_connection *conn = talloc_get_type(private_data, struct ldapsrv_connection);
178
179         ldapsrv_terminate_connection(conn, "Timeout. No requests after bind");
180 }
181
182 /*
183   called when a LDAP socket becomes readable
184 */
185 void ldapsrv_recv(struct stream_connection *c, uint16_t flags)
186 {
187         struct ldapsrv_connection *conn = 
188                 talloc_get_type(c->private_data, struct ldapsrv_connection);
189
190         if (conn->limits.ite) { /* clean initial timeout if any */
191                 talloc_free(conn->limits.ite);
192                 conn->limits.ite = NULL;
193         }
194
195         if (conn->limits.te) { /* clean idle timeout if any */
196                 talloc_free(conn->limits.te);
197                 conn->limits.te = NULL;
198         }
199
200         packet_recv(conn->packet);
201
202         /* set idle timeout */
203         conn->limits.te = event_add_timed(c->event.ctx, conn, 
204                                            timeval_current_ofs(conn->limits.conn_idle_time, 0),
205                                            ldapsrv_conn_idle_timeout, conn);
206 }
207
208 /*
209   called when a LDAP socket becomes writable
210 */
211 static void ldapsrv_send(struct stream_connection *c, uint16_t flags)
212 {
213         struct ldapsrv_connection *conn = 
214                 talloc_get_type(c->private_data, struct ldapsrv_connection);
215
216         packet_queue_run(conn->packet);
217 }
218
219 static void ldapsrv_conn_init_timeout(struct tevent_context *ev,
220                                       struct tevent_timer *te,
221                                       struct timeval t,
222                                       void *private_data)
223 {
224         struct ldapsrv_connection *conn = talloc_get_type(private_data, struct ldapsrv_connection);
225
226         ldapsrv_terminate_connection(conn, "Timeout. No requests after initial connection");
227 }
228
229 static int ldapsrv_load_limits(struct ldapsrv_connection *conn)
230 {
231         TALLOC_CTX *tmp_ctx;
232         const char *attrs[] = { "configurationNamingContext", NULL };
233         const char *attrs2[] = { "lDAPAdminLimits", NULL };
234         struct ldb_message_element *el;
235         struct ldb_result *res = NULL;
236         struct ldb_dn *basedn;
237         struct ldb_dn *conf_dn;
238         struct ldb_dn *policy_dn;
239         int i,ret;
240
241         /* set defaults limits in case of failure */
242         conn->limits.initial_timeout = 120;
243         conn->limits.conn_idle_time = 900;
244         conn->limits.max_page_size = 1000;
245         conn->limits.search_timeout = 120;
246
247
248         tmp_ctx = talloc_new(conn);
249         if (tmp_ctx == NULL) {
250                 return -1;
251         }
252
253         basedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);
254         if ( ! ldb_dn_validate(basedn)) {
255                 goto failed;
256         }
257
258         ret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL);
259         if (ret != LDB_SUCCESS) {
260                 goto failed;
261         }
262
263         if (res->count != 1) {
264                 goto failed;
265         }
266
267         conf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], "configurationNamingContext");
268         if (conf_dn == NULL) {
269                 goto failed;
270         }
271
272         policy_dn = ldb_dn_copy(tmp_ctx, conf_dn);
273         ldb_dn_add_child_fmt(policy_dn, "CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services");
274         if (policy_dn == NULL) {
275                 goto failed;
276         }
277
278         ret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL);
279         if (ret != LDB_SUCCESS) {
280                 goto failed;
281         }
282
283         if (res->count != 1) {
284                 goto failed;
285         }
286
287         el = ldb_msg_find_element(res->msgs[0], "lDAPAdminLimits");
288         if (el == NULL) {
289                 goto failed;
290         }
291
292         for (i = 0; i < el->num_values; i++) {
293                 char policy_name[256];
294                 int policy_value, s;
295
296                 s = sscanf((const char *)el->values[i].data, "%255[^=]=%d", policy_name, &policy_value);
297                 if (ret != 2 || policy_value == 0)
298                         continue;
299
300                 if (strcasecmp("InitRecvTimeout", policy_name) == 0) {
301                         conn->limits.initial_timeout = policy_value;
302                         continue;
303                 }
304                 if (strcasecmp("MaxConnIdleTime", policy_name) == 0) {
305                         conn->limits.conn_idle_time = policy_value;
306                         continue;
307                 }
308                 if (strcasecmp("MaxPageSize", policy_name) == 0) {
309                         conn->limits.max_page_size = policy_value;
310                         continue;
311                 }
312                 if (strcasecmp("MaxQueryDuration", policy_name) == 0) {
313                         conn->limits.search_timeout = policy_value;
314                         continue;
315                 }
316         }
317
318         return 0;
319
320 failed:
321         DEBUG(0, ("Failed to load ldap server query policies\n"));
322         talloc_free(tmp_ctx);
323         return -1;
324 }
325
326 /*
327   initialise a server_context from a open socket and register a event handler
328   for reading from that socket
329 */
330 static void ldapsrv_accept(struct stream_connection *c,
331                            struct auth_session_info *session_info)
332 {
333         struct ldapsrv_service *ldapsrv_service = 
334                 talloc_get_type(c->private_data, struct ldapsrv_service);
335         struct ldapsrv_connection *conn;
336         struct cli_credentials *server_credentials;
337         struct socket_address *socket_address;
338         NTSTATUS status;
339         int port;
340
341         conn = talloc_zero(c, struct ldapsrv_connection);
342         if (!conn) {
343                 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
344                 return;
345         }
346
347         conn->packet      = NULL;
348         conn->connection  = c;
349         conn->service     = ldapsrv_service;
350         conn->sockets.raw = c->socket;
351         conn->lp_ctx      = ldapsrv_service->task->lp_ctx;
352
353         c->private_data   = conn;
354
355         socket_address = socket_get_my_addr(c->socket, conn);
356         if (!socket_address) {
357                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: failed to obtain local socket address!");
358                 return;
359         }
360         port = socket_address->port;
361         talloc_free(socket_address);
362
363         if (port == 636) {
364                 struct socket_context *tls_socket = tls_init_server(ldapsrv_service->tls_params, c->socket, 
365                                                                     c->event.fde, NULL);
366                 if (!tls_socket) {
367                         ldapsrv_terminate_connection(conn, "ldapsrv_accept: tls_init_server() failed");
368                         return;
369                 }
370                 talloc_steal(c, tls_socket);
371                 c->socket = tls_socket;
372                 conn->sockets.tls = tls_socket;
373
374         } else if (port == 3268) /* Global catalog */ {
375                 conn->global_catalog = true;
376         }
377         conn->packet = packet_init(conn);
378         if (conn->packet == NULL) {
379                 ldapsrv_terminate_connection(conn, "out of memory");
380                 return;
381         }
382
383         packet_set_private(conn->packet, conn);
384         packet_set_socket(conn->packet, c->socket);
385         packet_set_callback(conn->packet, ldapsrv_decode);
386         packet_set_full_request(conn->packet, ldap_full_packet);
387         packet_set_error_handler(conn->packet, ldapsrv_error_handler);
388         packet_set_event_context(conn->packet, c->event.ctx);
389         packet_set_fde(conn->packet, c->event.fde);
390         packet_set_serialise(conn->packet);
391
392         if (conn->sockets.tls) {
393                 packet_set_unreliable_select(conn->packet);
394         }
395
396         /* Ensure we don't get packets until the database is ready below */
397         packet_recv_disable(conn->packet);
398
399         server_credentials = cli_credentials_init(conn);
400         if (!server_credentials) {
401                 stream_terminate_connection(c, "Failed to init server credentials\n");
402                 return;
403         }
404
405         cli_credentials_set_conf(server_credentials, conn->lp_ctx);
406         status = cli_credentials_set_machine_account(server_credentials, conn->lp_ctx);
407         if (!NT_STATUS_IS_OK(status)) {
408                 stream_terminate_connection(c, talloc_asprintf(conn, "Failed to obtain server credentials, perhaps a standalone server?: %s\n", nt_errstr(status)));
409                 return;
410         }
411         conn->server_credentials = server_credentials;
412
413         conn->session_info = talloc_move(conn, &session_info);
414
415         if (!NT_STATUS_IS_OK(ldapsrv_backend_Init(conn))) {
416                 ldapsrv_terminate_connection(conn, "backend Init failed");
417                 return;
418         }
419
420         /* load limits from the conf partition */
421         ldapsrv_load_limits(conn); /* should we fail on error ? */
422
423         /* register the server */       
424         irpc_add_name(c->msg_ctx, "ldap_server");
425
426         /* set connections limits */
427         conn->limits.ite = event_add_timed(c->event.ctx, conn, 
428                                            timeval_current_ofs(conn->limits.initial_timeout, 0),
429                                            ldapsrv_conn_init_timeout, conn);
430
431         packet_recv_enable(conn->packet);
432
433 }
434
435 static void ldapsrv_accept_nonpriv(struct stream_connection *c)
436 {
437         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
438                 c->private_data, struct ldapsrv_service);
439         struct auth_session_info *session_info;
440         NTSTATUS status;
441
442         status = auth_anonymous_session_info(
443                 c, c->event.ctx, ldapsrv_service->task->lp_ctx, &session_info);
444         if (!NT_STATUS_IS_OK(status)) {
445                 stream_terminate_connection(c, "failed to setup anonymous "
446                                             "session info");
447                 return;
448         }
449         ldapsrv_accept(c, session_info);
450 }
451
452 static const struct stream_server_ops ldap_stream_nonpriv_ops = {
453         .name                   = "ldap",
454         .accept_connection      = ldapsrv_accept_nonpriv,
455         .recv_handler           = ldapsrv_recv,
456         .send_handler           = ldapsrv_send,
457 };
458
459 /* The feature removed behind an #ifdef until we can do it properly
460  * with an EXTERNAL bind. */
461
462 #define WITH_LDAPI_PRIV_SOCKET
463
464 #ifdef WITH_LDAPI_PRIV_SOCKET
465 static void ldapsrv_accept_priv(struct stream_connection *c)
466 {
467         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
468                 c->private_data, struct ldapsrv_service);
469         struct auth_session_info *session_info;
470         NTSTATUS status;
471
472         status = auth_system_session_info(
473                 c, ldapsrv_service->task->lp_ctx, &session_info);
474         if (!NT_STATUS_IS_OK(status)) {
475                 stream_terminate_connection(c, "failed to setup system "
476                                             "session info");
477                 return;
478         }
479         ldapsrv_accept(c, session_info);
480 }
481
482 static const struct stream_server_ops ldap_stream_priv_ops = {
483         .name                   = "ldap",
484         .accept_connection      = ldapsrv_accept_priv,
485         .recv_handler           = ldapsrv_recv,
486         .send_handler           = ldapsrv_send,
487 };
488
489 #endif
490 /*
491   add a socket address to the list of events, one event per port
492 */
493 static NTSTATUS add_socket(struct tevent_context *event_context,
494                            struct loadparm_context *lp_ctx, 
495                            const struct model_ops *model_ops,
496                            const char *address, struct ldapsrv_service *ldap_service)
497 {
498         uint16_t port = 389;
499         NTSTATUS status;
500         struct ldb_context *ldb;
501
502         status = stream_setup_socket(event_context, lp_ctx,
503                                      model_ops, &ldap_stream_nonpriv_ops,
504                                      "ipv4", address, &port, 
505                                      lp_socket_options(lp_ctx), 
506                                      ldap_service);
507         if (!NT_STATUS_IS_OK(status)) {
508                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
509                          address, port, nt_errstr(status)));
510         }
511
512         if (tls_support(ldap_service->tls_params)) {
513                 /* add ldaps server */
514                 port = 636;
515                 status = stream_setup_socket(event_context, lp_ctx, 
516                                              model_ops,
517                                              &ldap_stream_nonpriv_ops,
518                                              "ipv4", address, &port, 
519                                              lp_socket_options(lp_ctx), 
520                                              ldap_service);
521                 if (!NT_STATUS_IS_OK(status)) {
522                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
523                                  address, port, nt_errstr(status)));
524                 }
525         }
526
527         /* Load LDAP database, but only to read our settings */
528         ldb = samdb_connect(ldap_service, ldap_service->task->event_ctx, 
529                             lp_ctx, system_session(ldap_service, lp_ctx));
530         if (!ldb) {
531                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
532         }
533
534         if (samdb_is_gc(ldb)) {
535                 port = 3268;
536                 status = stream_setup_socket(event_context, lp_ctx,
537                                              model_ops,
538                                              &ldap_stream_nonpriv_ops,
539                                              "ipv4", address, &port, 
540                                              lp_socket_options(lp_ctx), 
541                                              ldap_service);
542                 if (!NT_STATUS_IS_OK(status)) {
543                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
544                                  address, port, nt_errstr(status)));
545                 }
546         }
547
548         /* And once we are bound, free the tempoary ldb, it will
549          * connect again on each incoming LDAP connection */
550         talloc_free(ldb);
551
552         return status;
553 }
554
555 /*
556   open the ldap server sockets
557 */
558 static void ldapsrv_task_init(struct task_server *task)
559 {       
560         char *ldapi_path;
561 #ifdef WITH_LDAPI_PRIV_SOCKET
562         char *priv_dir;
563 #endif
564         struct ldapsrv_service *ldap_service;
565         NTSTATUS status;
566         const struct model_ops *model_ops;
567
568         switch (lp_server_role(task->lp_ctx)) {
569         case ROLE_STANDALONE:
570                 task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration");
571                 return;
572         case ROLE_DOMAIN_MEMBER:
573                 task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration");
574                 return;
575         case ROLE_DOMAIN_CONTROLLER:
576                 /* Yes, we want an LDAP server */
577                 break;
578         }
579
580         task_server_set_title(task, "task[ldapsrv]");
581
582         /* run the ldap server as a single process */
583         model_ops = process_model_startup(task->event_ctx, "single");
584         if (!model_ops) goto failed;
585
586         ldap_service = talloc_zero(task, struct ldapsrv_service);
587         if (ldap_service == NULL) goto failed;
588
589         ldap_service->task = task;
590
591         ldap_service->tls_params = tls_initialise(ldap_service, task->lp_ctx);
592         if (ldap_service->tls_params == NULL) goto failed;
593
594         if (lp_interfaces(task->lp_ctx) && lp_bind_interfaces_only(task->lp_ctx)) {
595                 struct interface *ifaces;
596                 int num_interfaces;
597                 int i;
598
599                 load_interfaces(task, lp_interfaces(task->lp_ctx), &ifaces);
600                 num_interfaces = iface_count(ifaces);
601
602                 /* We have been given an interfaces line, and been 
603                    told to only bind to those interfaces. Create a
604                    socket per interface and bind to only these.
605                 */
606                 for(i = 0; i < num_interfaces; i++) {
607                         const char *address = iface_n_ip(ifaces, i);
608                         status = add_socket(task->event_ctx, task->lp_ctx, model_ops, address, ldap_service);
609                         if (!NT_STATUS_IS_OK(status)) goto failed;
610                 }
611         } else {
612                 status = add_socket(task->event_ctx, task->lp_ctx, model_ops, 
613                                     lp_socket_address(task->lp_ctx), ldap_service);
614                 if (!NT_STATUS_IS_OK(status)) goto failed;
615         }
616
617         ldapi_path = private_path(ldap_service, task->lp_ctx, "ldapi");
618         if (!ldapi_path) {
619                 goto failed;
620         }
621
622         status = stream_setup_socket(task->event_ctx, task->lp_ctx,
623                                      model_ops, &ldap_stream_nonpriv_ops,
624                                      "unix", ldapi_path, NULL, 
625                                      lp_socket_options(task->lp_ctx), 
626                                      ldap_service);
627         talloc_free(ldapi_path);
628         if (!NT_STATUS_IS_OK(status)) {
629                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
630                          ldapi_path, nt_errstr(status)));
631         }
632
633 #ifdef WITH_LDAPI_PRIV_SOCKET
634         priv_dir = private_path(ldap_service, task->lp_ctx, "ldap_priv");
635         if (priv_dir == NULL) {
636                 goto failed;
637         }
638         /*
639          * Make sure the directory for the privileged ldapi socket exists, and
640          * is of the correct permissions
641          */
642         if (!directory_create_or_exist(priv_dir, geteuid(), 0750)) {
643                 task_server_terminate(task, "Cannot create ldap "
644                                       "privileged ldapi directory");
645                 return;
646         }
647         ldapi_path = talloc_asprintf(ldap_service, "%s/ldapi", priv_dir);
648         talloc_free(priv_dir);
649         if (ldapi_path == NULL) {
650                 goto failed;
651         }
652
653         status = stream_setup_socket(task->event_ctx, task->lp_ctx,
654                                      model_ops, &ldap_stream_priv_ops,
655                                      "unix", ldapi_path, NULL,
656                                      lp_socket_options(task->lp_ctx),
657                                      ldap_service);
658         talloc_free(ldapi_path);
659         if (!NT_STATUS_IS_OK(status)) {
660                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
661                          ldapi_path, nt_errstr(status)));
662         }
663
664 #endif
665         return;
666
667 failed:
668         task_server_terminate(task, "Failed to startup ldap server task");      
669 }
670
671
672 NTSTATUS server_service_ldap_init(void)
673 {
674         return register_server_service("ldap", ldapsrv_task_init);
675 }