Fix more valgrind issues.
[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 "system/network.h"
41 #include "lib/socket/netif.h"
42 #include "dsdb/samdb/samdb.h"
43 #include "param/param.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                 bool ret;
103
104                 msg = call->replies->msg;
105                 if (!ldap_encode(msg, &b, call)) {
106                         DEBUG(0,("Failed to encode ldap reply of type %d\n", msg->type));
107                         talloc_free(call);
108                         return;
109                 }
110
111                 ret = data_blob_append(call, &blob, b.data, b.length);
112                 data_blob_free(&b);
113
114                 talloc_set_name_const(blob.data, "Outgoing, encoded LDAP packet");
115
116                 if (!ret) {
117                         talloc_free(call);
118                         return;
119                 }
120
121                 DLIST_REMOVE(call->replies, call->replies);
122         }
123
124         packet_send_callback(conn->packet, blob, 
125                              call->send_callback, call->send_private);
126         talloc_free(call);
127         return;
128 }
129
130 /*
131   decode/process data
132 */
133 static NTSTATUS ldapsrv_decode(void *private, DATA_BLOB blob)
134 {
135         NTSTATUS status;
136         struct ldapsrv_connection *conn = talloc_get_type(private, 
137                                                           struct ldapsrv_connection);
138         struct asn1_data *asn1 = asn1_init(conn);
139         struct ldap_message *msg = talloc(conn, struct ldap_message);
140
141         if (asn1 == NULL || msg == NULL) {
142                 return NT_STATUS_NO_MEMORY;
143         }
144
145         if (!asn1_load(asn1, blob)) {
146                 talloc_free(msg);
147                 talloc_free(asn1);
148                 return NT_STATUS_NO_MEMORY;
149         }
150
151         status = ldap_decode(asn1, msg);
152         if (!NT_STATUS_IS_OK(status)) {
153                 asn1_free(asn1);
154                 return status;
155         }
156
157         data_blob_free(&blob);
158         talloc_steal(conn, msg);
159         asn1_free(asn1);
160
161         ldapsrv_process_message(conn, msg);
162         return NT_STATUS_OK;
163 }
164
165 /*
166  Idle timeout handler
167 */
168 static void ldapsrv_conn_idle_timeout(struct event_context *ev,
169                                       struct timed_event *te,
170                                       struct timeval t,
171                                       void *private)
172 {
173         struct ldapsrv_connection *conn = talloc_get_type(private, struct ldapsrv_connection);
174
175         ldapsrv_terminate_connection(conn, "Timeout. No requests after bind");
176 }
177
178 /*
179   called when a LDAP socket becomes readable
180 */
181 void ldapsrv_recv(struct stream_connection *c, uint16_t flags)
182 {
183         struct ldapsrv_connection *conn = 
184                 talloc_get_type(c->private, struct ldapsrv_connection);
185
186         if (conn->limits.ite) { /* clean initial timeout if any */
187                 talloc_free(conn->limits.ite);
188                 conn->limits.ite = NULL;
189         }
190
191         if (conn->limits.te) { /* clean idle timeout if any */
192                 talloc_free(conn->limits.te);
193                 conn->limits.te = NULL;
194         }
195
196         packet_recv(conn->packet);
197
198         /* set idle timeout */
199         conn->limits.te = event_add_timed(c->event.ctx, conn, 
200                                            timeval_current_ofs(conn->limits.conn_idle_time, 0),
201                                            ldapsrv_conn_idle_timeout, conn);
202 }
203
204 /*
205   called when a LDAP socket becomes writable
206 */
207 static void ldapsrv_send(struct stream_connection *c, uint16_t flags)
208 {
209         struct ldapsrv_connection *conn = 
210                 talloc_get_type(c->private, struct ldapsrv_connection);
211         
212         packet_queue_run(conn->packet);
213 }
214
215 static void ldapsrv_conn_init_timeout(struct event_context *ev,
216                                       struct timed_event *te,
217                                       struct timeval t,
218                                       void *private)
219 {
220         struct ldapsrv_connection *conn = talloc_get_type(private, struct ldapsrv_connection);
221
222         ldapsrv_terminate_connection(conn, "Timeout. No requests after initial connection");
223 }
224
225 static int ldapsrv_load_limits(struct ldapsrv_connection *conn)
226 {
227         TALLOC_CTX *tmp_ctx;
228         const char *attrs[] = { "configurationNamingContext", NULL };
229         const char *attrs2[] = { "lDAPAdminLimits", NULL };
230         struct ldb_message_element *el;
231         struct ldb_result *res = NULL;
232         struct ldb_dn *basedn;
233         struct ldb_dn *conf_dn;
234         struct ldb_dn *policy_dn;
235         int i,ret;
236
237         /* set defaults limits in case of failure */
238         conn->limits.initial_timeout = 120;
239         conn->limits.conn_idle_time = 900;
240         conn->limits.max_page_size = 1000;
241         conn->limits.search_timeout = 120;
242
243
244         tmp_ctx = talloc_new(conn);
245         if (tmp_ctx == NULL) {
246                 return -1;
247         }
248
249         basedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);
250         if ( ! ldb_dn_validate(basedn)) {
251                 goto failed;
252         }
253
254         ret = ldb_search(conn->ldb, basedn, LDB_SCOPE_BASE, NULL, attrs, &res);
255         if (ret != LDB_SUCCESS) {
256                 goto failed;
257         }
258
259         talloc_steal(tmp_ctx, res);
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, policy_dn, LDB_SCOPE_BASE, NULL, attrs2, &res);
277         if (ret != LDB_SUCCESS) {
278                 goto failed;
279         }
280
281         talloc_steal(tmp_ctx, res);
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 {
332         struct ldapsrv_service *ldapsrv_service = 
333                 talloc_get_type(c->private, struct ldapsrv_service);
334         struct ldapsrv_connection *conn;
335         struct cli_credentials *server_credentials;
336         struct socket_address *socket_address;
337         NTSTATUS status;
338         int port;
339
340         conn = talloc_zero(c, struct ldapsrv_connection);
341         if (!conn) {
342                 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
343                 return;
344         }
345
346         conn->packet      = NULL;
347         conn->connection  = c;
348         conn->service     = ldapsrv_service;
349         conn->sockets.raw = c->socket;
350         conn->lp_ctx      = ldapsrv_service->task->lp_ctx;
351
352         c->private        = conn;
353
354         socket_address = socket_get_my_addr(c->socket, conn);
355         if (!socket_address) {
356                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: failed to obtain local socket address!");
357                 return;
358         }
359         port = socket_address->port;
360         talloc_free(socket_address);
361
362         if (port == 636) {
363                 struct socket_context *tls_socket = tls_init_server(ldapsrv_service->tls_params, c->socket, 
364                                                                     c->event.fde, NULL);
365                 if (!tls_socket) {
366                         ldapsrv_terminate_connection(conn, "ldapsrv_accept: tls_init_server() failed");
367                         return;
368                 }
369                 talloc_unlink(c, c->socket);
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         /* Ensure we don't get packets until the database is ready below */
393         packet_recv_disable(conn->packet);
394
395         server_credentials = cli_credentials_init(conn);
396         if (!server_credentials) {
397                 stream_terminate_connection(c, "Failed to init server credentials\n");
398                 return;
399         }
400         
401         cli_credentials_set_conf(server_credentials, conn->lp_ctx);
402         status = cli_credentials_set_machine_account(server_credentials, conn->lp_ctx);
403         if (!NT_STATUS_IS_OK(status)) {
404                 stream_terminate_connection(c, talloc_asprintf(conn, "Failed to obtain server credentials, perhaps a standalone server?: %s\n", nt_errstr(status)));
405                 return;
406         }
407         conn->server_credentials = server_credentials;
408
409         /* Connections start out anonymous */
410         if (!NT_STATUS_IS_OK(auth_anonymous_session_info(conn, conn->lp_ctx, &conn->session_info))) {
411                 ldapsrv_terminate_connection(conn, "failed to setup anonymous session info");
412                 return;
413         }
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 const struct stream_server_ops ldap_stream_ops = {
436         .name                   = "ldap",
437         .accept_connection      = ldapsrv_accept,
438         .recv_handler           = ldapsrv_recv,
439         .send_handler           = ldapsrv_send,
440 };
441
442 /*
443   add a socket address to the list of events, one event per port
444 */
445 static NTSTATUS add_socket(struct event_context *event_context,
446                            struct loadparm_context *lp_ctx, 
447                            const struct model_ops *model_ops,
448                            const char *address, struct ldapsrv_service *ldap_service)
449 {
450         uint16_t port = 389;
451         NTSTATUS status;
452         struct ldb_context *ldb;
453
454         status = stream_setup_socket(event_context, lp_ctx,
455                                      model_ops, &ldap_stream_ops, 
456                                      "ipv4", address, &port, 
457                                      lp_socket_options(lp_ctx), 
458                                      ldap_service);
459         if (!NT_STATUS_IS_OK(status)) {
460                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
461                          address, port, nt_errstr(status)));
462         }
463
464         if (tls_support(ldap_service->tls_params)) {
465                 /* add ldaps server */
466                 port = 636;
467                 status = stream_setup_socket(event_context, lp_ctx, 
468                                              model_ops, &ldap_stream_ops, 
469                                              "ipv4", address, &port, 
470                                              lp_socket_options(lp_ctx), 
471                                              ldap_service);
472                 if (!NT_STATUS_IS_OK(status)) {
473                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
474                                  address, port, nt_errstr(status)));
475                 }
476         }
477
478         /* Load LDAP database */
479         ldb = samdb_connect(ldap_service, lp_ctx, system_session(ldap_service, lp_ctx));
480         if (!ldb) {
481                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
482         }
483         
484         if (samdb_is_gc(ldb)) {
485                 port = 3268;
486                 status = stream_setup_socket(event_context, lp_ctx,
487                                              model_ops, &ldap_stream_ops, 
488                                              "ipv4", address, &port, 
489                                              lp_socket_options(lp_ctx), 
490                                              ldap_service);
491                 if (!NT_STATUS_IS_OK(status)) {
492                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
493                                  address, port, nt_errstr(status)));
494                 }
495         }
496
497         return status;
498 }
499
500 /*
501   open the ldap server sockets
502 */
503 static void ldapsrv_task_init(struct task_server *task)
504 {       
505         char *ldapi_path;
506         struct ldapsrv_service *ldap_service;
507         NTSTATUS status;
508         const struct model_ops *model_ops;
509
510         switch (lp_server_role(task->lp_ctx)) {
511         case ROLE_STANDALONE:
512                 task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration");
513                 return;
514         case ROLE_DOMAIN_MEMBER:
515                 task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration");
516                 return;
517         case ROLE_DOMAIN_CONTROLLER:
518                 /* Yes, we want an LDAP server */
519                 break;
520         }
521
522         task_server_set_title(task, "task[ldapsrv]");
523
524         /* run the ldap server as a single process */
525         model_ops = process_model_byname("single");
526         if (!model_ops) goto failed;
527
528         ldap_service = talloc_zero(task, struct ldapsrv_service);
529         if (ldap_service == NULL) goto failed;
530
531         ldap_service->task = task;
532
533         ldap_service->tls_params = tls_initialise(ldap_service, task->lp_ctx);
534         if (ldap_service->tls_params == NULL) goto failed;
535
536         if (lp_interfaces(task->lp_ctx) && lp_bind_interfaces_only(task->lp_ctx)) {
537                 struct interface *ifaces;
538                 int num_interfaces;
539                 int i;
540
541                 load_interfaces(task, lp_interfaces(task->lp_ctx), &ifaces);
542                 num_interfaces = iface_count(ifaces);
543
544                 /* We have been given an interfaces line, and been 
545                    told to only bind to those interfaces. Create a
546                    socket per interface and bind to only these.
547                 */
548                 for(i = 0; i < num_interfaces; i++) {
549                         const char *address = iface_n_ip(ifaces, i);
550                         status = add_socket(task->event_ctx, task->lp_ctx, model_ops, address, ldap_service);
551                         if (!NT_STATUS_IS_OK(status)) goto failed;
552                 }
553         } else {
554                 status = add_socket(task->event_ctx, task->lp_ctx, model_ops, 
555                                     lp_socket_address(task->lp_ctx), ldap_service);
556                 if (!NT_STATUS_IS_OK(status)) goto failed;
557         }
558
559         ldapi_path = private_path(ldap_service, task->lp_ctx, "ldapi");
560         if (!ldapi_path) {
561                 goto failed;
562         }
563
564         status = stream_setup_socket(task->event_ctx, task->lp_ctx,
565                                      model_ops, &ldap_stream_ops, 
566                                      "unix", ldapi_path, NULL, 
567                                      lp_socket_options(task->lp_ctx), 
568                                      ldap_service);
569         talloc_free(ldapi_path);
570         if (!NT_STATUS_IS_OK(status)) {
571                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
572                          ldapi_path, nt_errstr(status)));
573         }
574
575         return;
576
577 failed:
578         task_server_terminate(task, "Failed to startup ldap server task");      
579 }
580
581
582 NTSTATUS server_service_ldap_init(void)
583 {
584         return register_server_service("ldap", ldapsrv_task_init);
585 }