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