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