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