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