r21806: I've been working over the last week to fix up the LDAP backend for
[ira/wip.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 2 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, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.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 "libcli/util/asn_1.h"
32 #include "ldap_server/ldap_server.h"
33 #include "smbd/service_task.h"
34 #include "smbd/service_stream.h"
35 #include "smbd/service.h"
36 #include "smbd/process_model.h"
37 #include "lib/tls/tls.h"
38 #include "lib/messaging/irpc.h"
39 #include "lib/ldb/include/ldb.h"
40 #include "lib/ldb/include/ldb_errors.h"
41 #include "system/network.h"
42 #include "lib/socket/netif.h"
43 #include "dsdb/samdb/samdb.h"
44 /*
45   close the socket and shutdown a server_context
46 */
47 void ldapsrv_terminate_connection(struct ldapsrv_connection *conn, 
48                                          const char *reason)
49 {
50         stream_terminate_connection(conn->connection, reason);
51 }
52
53 /*
54   handle packet errors
55 */
56 static void ldapsrv_error_handler(void *private, NTSTATUS status)
57 {
58         struct ldapsrv_connection *conn = talloc_get_type(private, 
59                                                           struct ldapsrv_connection);
60         ldapsrv_terminate_connection(conn, nt_errstr(status));
61 }
62
63 /*
64   process a decoded ldap message
65 */
66 static void ldapsrv_process_message(struct ldapsrv_connection *conn,
67                                     struct ldap_message *msg)
68 {
69         struct ldapsrv_call *call;
70         NTSTATUS status;
71         DATA_BLOB blob;
72
73         call = talloc(conn, struct ldapsrv_call);
74         if (!call) {
75                 ldapsrv_terminate_connection(conn, "no memory");
76                 return;         
77         }
78         
79         call->request = talloc_steal(call, msg);
80         call->conn = conn;
81         call->replies = NULL;
82         call->send_callback = NULL;
83         call->send_private = NULL;
84         
85         /* make the call */
86         status = ldapsrv_do_call(call);
87         if (!NT_STATUS_IS_OK(status)) {
88                 talloc_free(call);
89                 return;
90         }
91         
92         blob = data_blob(NULL, 0);
93
94         if (call->replies == NULL) {
95                 talloc_free(call);
96                 return;
97         }
98
99         /* build all the replies into a single blob */
100         while (call->replies) {
101                 DATA_BLOB b;
102
103                 msg = call->replies->msg;
104                 if (!ldap_encode(msg, &b, call)) {
105                         DEBUG(0,("Failed to encode ldap reply of type %d\n", msg->type));
106                         talloc_free(call);
107                         return;
108                 }
109
110                 status = data_blob_append(call, &blob, b.data, b.length);
111                 data_blob_free(&b);
112
113                 talloc_set_name_const(blob.data, "Outgoing, encoded LDAP packet");
114
115                 if (!NT_STATUS_IS_OK(status)) {
116                         talloc_free(call);
117                         return;
118                 }
119
120                 DLIST_REMOVE(call->replies, call->replies);
121         }
122
123         packet_send_callback(conn->packet, blob, 
124                              call->send_callback, call->send_private);
125         talloc_free(call);
126         return;
127 }
128
129 /*
130   decode/process data
131 */
132 static NTSTATUS ldapsrv_decode(void *private, DATA_BLOB blob)
133 {
134         NTSTATUS status;
135         struct ldapsrv_connection *conn = talloc_get_type(private, 
136                                                           struct ldapsrv_connection);
137         struct asn1_data asn1;
138         struct ldap_message *msg = talloc(conn, struct ldap_message);
139
140         if (msg == NULL) {
141                 return NT_STATUS_NO_MEMORY;
142         }
143
144         if (!asn1_load(&asn1, blob)) {
145                 return NT_STATUS_NO_MEMORY;
146         }
147
148         status = ldap_decode(&asn1, msg);
149         if (!NT_STATUS_IS_OK(status)) {
150                 asn1_free(&asn1);
151                 return status;
152         }
153
154         data_blob_free(&blob);
155         ldapsrv_process_message(conn, msg);
156         asn1_free(&asn1);
157         return NT_STATUS_OK;
158 }
159
160 /*
161  Idle timeout handler
162 */
163 static void ldapsrv_conn_idle_timeout(struct event_context *ev,
164                                       struct timed_event *te,
165                                       struct timeval t,
166                                       void *private)
167 {
168         struct ldapsrv_connection *conn = talloc_get_type(private, struct ldapsrv_connection);
169
170         ldapsrv_terminate_connection(conn, "Timeout. No requests after bind");
171 }
172
173 /*
174   called when a LDAP socket becomes readable
175 */
176 void ldapsrv_recv(struct stream_connection *c, uint16_t flags)
177 {
178         struct ldapsrv_connection *conn = 
179                 talloc_get_type(c->private, struct ldapsrv_connection);
180
181         if (conn->limits.ite) { /* clean initial timeout if any */
182                 talloc_free(conn->limits.ite);
183                 conn->limits.ite = NULL;
184         }
185
186         if (conn->limits.te) { /* clean idle timeout if any */
187                 talloc_free(conn->limits.te);
188                 conn->limits.te = NULL;
189         }
190
191         packet_recv(conn->packet);
192
193         /* set idle timeout */
194         conn->limits.te = event_add_timed(c->event.ctx, conn, 
195                                            timeval_current_ofs(conn->limits.conn_idle_time, 0),
196                                            ldapsrv_conn_idle_timeout, conn);
197 }
198
199 /*
200   called when a LDAP socket becomes writable
201 */
202 static void ldapsrv_send(struct stream_connection *c, uint16_t flags)
203 {
204         struct ldapsrv_connection *conn = 
205                 talloc_get_type(c->private, struct ldapsrv_connection);
206         
207         packet_queue_run(conn->packet);
208 }
209
210 static void ldapsrv_conn_init_timeout(struct event_context *ev,
211                                       struct timed_event *te,
212                                       struct timeval t,
213                                       void *private)
214 {
215         struct ldapsrv_connection *conn = talloc_get_type(private, struct ldapsrv_connection);
216
217         ldapsrv_terminate_connection(conn, "Timeout. No requests after initial connection");
218 }
219
220 static int ldapsrv_load_limits(struct ldapsrv_connection *conn)
221 {
222         TALLOC_CTX *tmp_ctx;
223         const char *attrs[] = { "configurationNamingContext", NULL };
224         const char *attrs2[] = { "lDAPAdminLimits", NULL };
225         struct ldb_message_element *el;
226         struct ldb_result *res = NULL;
227         struct ldb_dn *basedn;
228         struct ldb_dn *conf_dn;
229         struct ldb_dn *policy_dn;
230         int i,ret;
231
232         /* set defaults limits in case of failure */
233         conn->limits.initial_timeout = 120;
234         conn->limits.conn_idle_time = 900;
235         conn->limits.max_page_size = 1000;
236         conn->limits.search_timeout = 120;
237
238
239         tmp_ctx = talloc_new(conn);
240         if (tmp_ctx == NULL) {
241                 return -1;
242         }
243
244         basedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);
245         if ( ! ldb_dn_validate(basedn)) {
246                 goto failed;
247         }
248
249         ret = ldb_search(conn->ldb, basedn, LDB_SCOPE_BASE, NULL, attrs, &res);
250         if (ret != LDB_SUCCESS) {
251                 goto failed;
252         }
253
254         talloc_steal(tmp_ctx, res);
255
256         if (res->count != 1) {
257                 goto failed;
258         }
259
260         conf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], "configurationNamingContext");
261         if (conf_dn == NULL) {
262                 goto failed;
263         }
264
265         policy_dn = ldb_dn_copy(tmp_ctx, conf_dn);
266         ldb_dn_add_child_fmt(policy_dn, "CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services");
267         if (policy_dn == NULL) {
268                 goto failed;
269         }
270
271         ret = ldb_search(conn->ldb, policy_dn, LDB_SCOPE_BASE, NULL, attrs2, &res);
272         if (ret != LDB_SUCCESS) {
273                 goto failed;
274         }
275
276         talloc_steal(tmp_ctx, res);
277
278         if (res->count != 1) {
279                 goto failed;
280         }
281
282         el = ldb_msg_find_element(res->msgs[0], "lDAPAdminLimits");
283         if (el == NULL) {
284                 goto failed;
285         }
286
287         for (i = 0; i < el->num_values; i++) {
288                 char policy_name[256];
289                 int policy_value, s;
290
291                 s = sscanf((const char *)el->values[i].data, "%255[^=]=%d", policy_name, &policy_value);
292                 if (ret != 2 || policy_value == 0)
293                         continue;
294                 
295                 if (strcasecmp("InitRecvTimeout", policy_name) == 0) {
296                         conn->limits.initial_timeout = policy_value;
297                         continue;
298                 }
299                 if (strcasecmp("MaxConnIdleTime", policy_name) == 0) {
300                         conn->limits.conn_idle_time = policy_value;
301                         continue;
302                 }
303                 if (strcasecmp("MaxPageSize", policy_name) == 0) {
304                         conn->limits.max_page_size = policy_value;
305                         continue;
306                 }
307                 if (strcasecmp("MaxQueryDuration", policy_name) == 0) {
308                         conn->limits.search_timeout = policy_value;
309                         continue;
310                 }
311         }
312
313         return 0;
314
315 failed:
316         DEBUG(0, ("Failed to load ldap server query policies\n"));
317         talloc_free(tmp_ctx);
318         return -1;
319 }
320
321 /*
322   initialise a server_context from a open socket and register a event handler
323   for reading from that socket
324 */
325 static void ldapsrv_accept(struct stream_connection *c)
326 {
327         struct ldapsrv_service *ldapsrv_service = 
328                 talloc_get_type(c->private, struct ldapsrv_service);
329         struct ldapsrv_connection *conn;
330         struct cli_credentials *server_credentials;
331         struct socket_address *socket_address;
332         NTSTATUS status;
333         int port;
334
335         conn = talloc_zero(c, struct ldapsrv_connection);
336         if (!conn) {
337                 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
338                 return;
339         }
340
341         conn->packet      = NULL;
342         conn->connection  = c;
343         conn->service     = ldapsrv_service;
344         conn->sockets.raw = c->socket;
345
346         c->private        = conn;
347
348         socket_address = socket_get_my_addr(c->socket, conn);
349         if (!socket_address) {
350                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: failed to obtain local socket address!");
351                 return;
352         }
353         port = socket_address->port;
354         talloc_free(socket_address);
355
356         if (port == 636) {
357                 struct socket_context *tls_socket = tls_init_server(ldapsrv_service->tls_params, c->socket, 
358                                                                     c->event.fde, NULL);
359                 if (!tls_socket) {
360                         ldapsrv_terminate_connection(conn, "ldapsrv_accept: tls_init_server() failed");
361                         return;
362                 }
363                 talloc_unlink(c, c->socket);
364                 talloc_steal(c, tls_socket);
365                 c->socket = tls_socket;
366                 conn->sockets.tls = tls_socket;
367
368         } else if (port == 3268) /* Global catalog */ {
369                 conn->global_catalog = True;
370         }
371         conn->packet = packet_init(conn);
372         if (conn->packet == NULL) {
373                 ldapsrv_terminate_connection(conn, "out of memory");
374                 return;
375         }
376
377         packet_set_private(conn->packet, conn);
378         packet_set_socket(conn->packet, c->socket);
379         packet_set_callback(conn->packet, ldapsrv_decode);
380         packet_set_full_request(conn->packet, ldap_full_packet);
381         packet_set_error_handler(conn->packet, ldapsrv_error_handler);
382         packet_set_event_context(conn->packet, c->event.ctx);
383         packet_set_fde(conn->packet, c->event.fde);
384         packet_set_serialise(conn->packet);
385         
386         /* Ensure we don't get packets until the database is ready below */
387         packet_recv_disable(conn->packet);
388
389         server_credentials 
390                 = cli_credentials_init(conn);
391         if (!server_credentials) {
392                 stream_terminate_connection(c, "Failed to init server credentials\n");
393                 return;
394         }
395         
396         cli_credentials_set_conf(server_credentials);
397         status = cli_credentials_set_machine_account(server_credentials);
398         if (!NT_STATUS_IS_OK(status)) {
399                 stream_terminate_connection(c, talloc_asprintf(conn, "Failed to obtain server credentials, perhaps a standalone server?: %s\n", nt_errstr(status)));
400                 return;
401         }
402         conn->server_credentials = server_credentials;
403
404         /* Connections start out anonymous */
405         if (!NT_STATUS_IS_OK(auth_anonymous_session_info(conn, &conn->session_info))) {
406                 ldapsrv_terminate_connection(conn, "failed to setup anonymous session info");
407                 return;
408         }
409
410         if (!NT_STATUS_IS_OK(ldapsrv_backend_Init(conn))) {
411                 ldapsrv_terminate_connection(conn, "backend Init failed");
412                 return;
413         }
414
415         /* load limits from the conf partition */
416         ldapsrv_load_limits(conn); /* should we fail on error ? */
417
418         /* register the server */       
419         irpc_add_name(c->msg_ctx, "ldap_server");
420
421         /* set connections limits */
422         conn->limits.ite = event_add_timed(c->event.ctx, conn, 
423                                            timeval_current_ofs(conn->limits.initial_timeout, 0),
424                                            ldapsrv_conn_init_timeout, conn);
425
426         packet_recv_enable(conn->packet);
427
428 }
429
430 static const struct stream_server_ops ldap_stream_ops = {
431         .name                   = "ldap",
432         .accept_connection      = ldapsrv_accept,
433         .recv_handler           = ldapsrv_recv,
434         .send_handler           = ldapsrv_send,
435 };
436
437 /*
438   add a socket address to the list of events, one event per port
439 */
440 static NTSTATUS add_socket(struct event_context *event_context,
441                            const struct model_ops *model_ops,
442                            const char *address, struct ldapsrv_service *ldap_service)
443 {
444         uint16_t port = 389;
445         NTSTATUS status;
446         const char *attrs[] = { "options", NULL };
447         int ret;
448         struct ldb_result *res;
449         struct ldb_context *ldb;
450         int options;
451
452         status = stream_setup_socket(event_context, model_ops, &ldap_stream_ops, 
453                                      "ipv4", address, &port, ldap_service);
454         if (!NT_STATUS_IS_OK(status)) {
455                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
456                          address, port, nt_errstr(status)));
457         }
458
459         if (tls_support(ldap_service->tls_params)) {
460                 /* add ldaps server */
461                 port = 636;
462                 status = stream_setup_socket(event_context, model_ops, &ldap_stream_ops, 
463                                              "ipv4", address, &port, ldap_service);
464                 if (!NT_STATUS_IS_OK(status)) {
465                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
466                                  address, port, nt_errstr(status)));
467                 }
468         }
469
470         /* Load LDAP database */
471         ldb = samdb_connect(ldap_service, system_session(ldap_service));
472         if (!ldb) {
473                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
474         }
475         
476         /* Query cn=ntds settings,.... */
477         ret = ldb_search(ldb, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, NULL, attrs, &res);
478         if (ret) {
479                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
480         }
481         if (res->count != 1) {
482                 talloc_free(res);
483                 return NT_STATUS_NOT_FOUND;
484         }
485
486         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
487         talloc_free(res);
488         talloc_free(ldb);
489
490         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
491         if (options & 0x000000001) {
492                 port = 3268;
493                 status = stream_setup_socket(event_context, model_ops, &ldap_stream_ops, 
494                                              "ipv4", address, &port, ldap_service);
495                 if (!NT_STATUS_IS_OK(status)) {
496                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
497                                  address, port, nt_errstr(status)));
498                 }
499         }
500
501         return status;
502 }
503
504 /*
505   open the ldap server sockets
506 */
507 static void ldapsrv_task_init(struct task_server *task)
508 {       
509         struct ldapsrv_service *ldap_service;
510         NTSTATUS status;
511         const struct model_ops *model_ops;
512
513         task_server_set_title(task, "task[ldapsrv]");
514
515         /* run the ldap server as a single process */
516         model_ops = process_model_byname("single");
517         if (!model_ops) goto failed;
518
519         ldap_service = talloc_zero(task, struct ldapsrv_service);
520         if (ldap_service == NULL) goto failed;
521
522         ldap_service->tls_params = tls_initialise(ldap_service);
523         if (ldap_service->tls_params == NULL) goto failed;
524
525         if (lp_interfaces() && lp_bind_interfaces_only()) {
526                 int num_interfaces = iface_count();
527                 int i;
528
529                 /* We have been given an interfaces line, and been 
530                    told to only bind to those interfaces. Create a
531                    socket per interface and bind to only these.
532                 */
533                 for(i = 0; i < num_interfaces; i++) {
534                         const char *address = iface_n_ip(i);
535                         status = add_socket(task->event_ctx, model_ops, address, ldap_service);
536                         if (!NT_STATUS_IS_OK(status)) goto failed;
537                 }
538         } else {
539                 status = add_socket(task->event_ctx, model_ops, lp_socket_address(), ldap_service);
540                 if (!NT_STATUS_IS_OK(status)) goto failed;
541         }
542
543         return;
544
545 failed:
546         task_server_terminate(task, "Failed to startup ldap server task");      
547 }
548
549 /*
550   called on startup of the web server service It's job is to start
551   listening on all configured sockets
552 */
553 static NTSTATUS ldapsrv_init(struct event_context *event_context, 
554                              const struct model_ops *model_ops)
555 {       
556         return task_server_startup(event_context, model_ops, ldapsrv_task_init);
557 }
558
559
560 NTSTATUS server_service_ldap_init(void)
561 {
562         return register_server_service("ldap", ldapsrv_init);
563 }