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