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