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