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