r10709: fixed a crash bug rather similar to the one volker found in the dcerpc
[bbaumbach/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 "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
37 /*
38   close the socket and shutdown a server_context
39 */
40 static void ldapsrv_terminate_connection(struct ldapsrv_connection *conn, 
41                                          const char *reason)
42 {
43         /* we don't actually do the stream termination here as the
44            recv/send functions dereference the connection after the
45            packet processing callbacks. Instead we mark it for
46            termination and do the real termination in the send/recv
47            functions */
48         conn->terminate = reason;
49 }
50
51 /*
52   process a decoded ldap message
53 */
54 static void ldapsrv_process_message(struct ldapsrv_connection *conn,
55                                     struct ldap_message *msg)
56 {
57         struct ldapsrv_call *call;
58         NTSTATUS status;
59         DATA_BLOB blob;
60         struct data_blob_list_item *q;
61         BOOL enable_wrap = conn->enable_wrap;
62
63         call = talloc(conn, struct ldapsrv_call);
64         if (!call) {
65                 ldapsrv_terminate_connection(conn, "no memory");
66                 return;         
67         }
68         
69         call->request = talloc_steal(call, msg);
70         call->conn = conn;
71         call->replies = NULL;
72
73         /* make the call */
74         status = ldapsrv_do_call(call);
75         if (!NT_STATUS_IS_OK(status)) {
76                 goto failed;
77         }
78         
79         blob = data_blob(NULL, 0);
80
81         if (call->replies == NULL) {
82                 talloc_free(call);
83                 return;
84         }
85
86         /* build all the replies into a single blob */
87         while (call->replies) {
88                 DATA_BLOB b;
89
90                 msg = call->replies->msg;
91                 if (!ldap_encode(msg, &b, call)) {
92                         DEBUG(0,("Failed to encode ldap reply of type %d\n", msg->type));
93                         goto failed;
94                 }
95
96                 status = data_blob_append(call, &blob, b.data, b.length);
97                 data_blob_free(&b);
98
99                 if (!NT_STATUS_IS_OK(status)) goto failed;
100
101                 DLIST_REMOVE(call->replies, call->replies);
102         }
103
104         /* possibly encrypt/sign the reply */
105         if (enable_wrap) {
106                 DATA_BLOB wrapped;
107
108                 status = gensec_wrap(conn->gensec, call, &blob, &wrapped);
109                 if (!NT_STATUS_IS_OK(status)) {
110                         goto failed;
111                 }
112                 data_blob_free(&blob);
113                 blob = data_blob_talloc(call, NULL, wrapped.length + 4);
114                 if (blob.data == NULL) {
115                         goto failed;
116                 }
117                 RSIVAL(blob.data, 0, wrapped.length);
118                 memcpy(blob.data+4, wrapped.data, wrapped.length);
119                 data_blob_free(&wrapped);
120         }
121
122         q = talloc(conn, struct data_blob_list_item);
123         if (q == NULL) goto failed;
124
125         q->blob = blob;
126         talloc_steal(q, blob.data);
127         
128         if (conn->send_queue == NULL) {
129                 EVENT_FD_WRITEABLE(conn->connection->event.fde);
130         }
131         DLIST_ADD_END(conn->send_queue, q, struct data_blob_list_item *);
132         talloc_free(call);
133         return;
134
135 failed:
136         talloc_free(call);
137 }
138
139
140 /*
141   try and decode the partial input buffer
142 */
143 static void ldapsrv_try_decode_plain(struct ldapsrv_connection *conn)
144 {
145         struct asn1_data asn1;
146
147         if (!asn1_load(&asn1, conn->partial)) {
148                 ldapsrv_terminate_connection(conn, "out of memory");
149                 return;
150         }
151
152         /* try and decode - this will fail if we don't have a full packet yet */
153         while (asn1.ofs < asn1.length) {
154                 struct ldap_message *msg = talloc(conn, struct ldap_message);
155                 off_t saved_ofs = asn1.ofs;
156                         
157                 if (msg == NULL) {
158                         ldapsrv_terminate_connection(conn, "out of memory");
159                         return;
160                 }
161
162                 if (ldap_decode(&asn1, msg)) {
163                         ldapsrv_process_message(conn, msg);
164                 } else {
165                         if (asn1.ofs < asn1.length) {
166                                 ldapsrv_terminate_connection(conn, "ldap_decode failed");
167                                 return;
168                         }
169                         asn1.ofs = saved_ofs;
170                         talloc_free(msg);
171                         break;
172                 }
173         }
174
175         /* keep any remaining data in conn->partial */
176         data_blob_free(&conn->partial);
177         if (asn1.ofs != asn1.length) {
178                 conn->partial = data_blob_talloc(conn, 
179                                                  asn1.data + asn1.ofs, 
180                                                  asn1.length - asn1.ofs);
181         }
182         asn1_free(&asn1);
183 }
184
185
186 /*
187   try and decode/process wrapped data
188 */
189 static void ldapsrv_try_decode_wrapped(struct ldapsrv_connection *conn)
190 {
191         uint32_t len;
192
193         /* keep decoding while we have a full wrapped packet */
194         while (conn->partial.length >= 4 &&
195                (len=RIVAL(conn->partial.data, 0)) <= conn->partial.length-4) {
196                 DATA_BLOB wrapped, unwrapped;
197                 struct asn1_data asn1;
198                 struct ldap_message *msg = talloc(conn, struct ldap_message);
199                 NTSTATUS status;
200
201                 if (msg == NULL) {
202                         ldapsrv_terminate_connection(conn, "out of memory");
203                         return;
204                 }
205
206                 wrapped.data   = conn->partial.data+4;
207                 wrapped.length = len;
208
209                 status = gensec_unwrap(conn->gensec, msg, &wrapped, &unwrapped);
210                 if (!NT_STATUS_IS_OK(status)) {
211                         ldapsrv_terminate_connection(conn, "gensec unwrap failed");
212                         return;
213                 }
214
215                 if (!asn1_load(&asn1, unwrapped)) {
216                         ldapsrv_terminate_connection(conn, "out of memory");
217                         return;
218                 }
219
220                 while (ldap_decode(&asn1, msg)) {
221                         ldapsrv_process_message(conn, msg);
222                         msg = talloc(conn, struct ldap_message);
223                 }
224
225                 if (asn1.ofs < asn1.length) {
226                         ldapsrv_terminate_connection(conn, "ldap_decode failed");
227                         return;
228                 }
229                 
230                 talloc_free(msg);
231                 asn1_free(&asn1);
232
233                 if (conn->partial.length == len + 4) {
234                         data_blob_free(&conn->partial);
235                 } else {
236                         memmove(conn->partial.data, conn->partial.data+len+4,
237                                 conn->partial.length - (len+4));
238                         conn->partial.length -= len + 4;
239                 }
240         }
241 }
242
243
244 /*
245   called when a LDAP socket becomes readable
246 */
247 static void ldapsrv_recv(struct stream_connection *c, uint16_t flags)
248 {
249         struct ldapsrv_connection *conn = 
250                 talloc_get_type(c->private, struct ldapsrv_connection);
251         NTSTATUS status;
252         size_t npending, nread;
253
254         if (conn->processing) {
255                 EVENT_FD_NOT_READABLE(c->event.fde);
256                 return;
257         }
258
259         /* work out how much data is pending */
260         status = tls_socket_pending(conn->tls, &npending);
261         if (!NT_STATUS_IS_OK(status)) {
262                 ldapsrv_terminate_connection(conn, "socket_pending() failed");
263                 return;
264         }
265         if (npending == 0) {
266                 ldapsrv_terminate_connection(conn, "EOF from client");
267                 return;
268         }
269
270         conn->partial.data = talloc_realloc_size(conn, conn->partial.data, 
271                                                  conn->partial.length + npending);
272         if (conn->partial.data == NULL) {
273                 ldapsrv_terminate_connection(conn, "out of memory");
274                 return;
275         }
276
277         /* receive the data */
278         status = tls_socket_recv(conn->tls, conn->partial.data + conn->partial.length,
279                                  npending, &nread);
280         if (NT_STATUS_IS_ERR(status)) {
281                 ldapsrv_terminate_connection(conn, "socket_recv() failed");
282                 return;
283         }
284         if (!NT_STATUS_IS_OK(status)) {
285                 return;
286         }
287         if (nread == 0) {
288                 ldapsrv_terminate_connection(conn, "EOF from client");
289                 return;
290         }
291         conn->partial.length += nread;
292
293         conn->processing = True;
294         /* see if we can decode what we have */
295         if (conn->enable_wrap) {
296                 ldapsrv_try_decode_wrapped(conn);
297         } else {
298                 ldapsrv_try_decode_plain(conn);
299         }
300         conn->processing = False;
301
302         EVENT_FD_READABLE(c->event.fde);
303
304         if (conn->terminate) {
305                 if (conn->tls) {
306                         talloc_free(conn->tls);
307                         conn->tls = NULL;
308                 }
309                 stream_terminate_connection(conn->connection, conn->terminate);
310         }
311 }
312         
313 /*
314   called when a LDAP socket becomes writable
315 */
316 static void ldapsrv_send(struct stream_connection *c, uint16_t flags)
317 {
318         struct ldapsrv_connection *conn = 
319                 talloc_get_type(c->private, struct ldapsrv_connection);
320         while (conn->send_queue) {
321                 struct data_blob_list_item *q = conn->send_queue;
322                 size_t nsent;
323                 NTSTATUS status;
324
325                 status = tls_socket_send(conn->tls, &q->blob, &nsent);
326                 if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
327                         break;
328                 }
329                 if (!NT_STATUS_IS_OK(status)) {
330                         ldapsrv_terminate_connection(conn, "socket_send error");
331                         return;
332                 }
333
334                 q->blob.data += nsent;
335                 q->blob.length -= nsent;
336                 if (q->blob.length == 0) {
337                         DLIST_REMOVE(conn->send_queue, q);
338                 }
339         }
340         if (conn->send_queue == NULL) {
341                 EVENT_FD_NOT_WRITEABLE(c->event.fde);
342         }
343
344         if (conn->terminate) {
345                 if (conn->tls) {
346                         talloc_free(conn->tls);
347                         conn->tls = NULL;
348                 }
349                 stream_terminate_connection(conn->connection, conn->terminate);
350         }
351 }
352
353 /*
354   initialise a server_context from a open socket and register a event handler
355   for reading from that socket
356 */
357 static void ldapsrv_accept(struct stream_connection *c)
358 {
359         struct ldapsrv_service *ldapsrv_service = 
360                 talloc_get_type(c->private, struct ldapsrv_service);
361         struct ldapsrv_connection *conn;
362         int port;
363
364         conn = talloc_zero(c, struct ldapsrv_connection);
365         if (!conn) {
366                 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
367                 return;
368         }
369
370         conn->enable_wrap = False;
371         conn->partial     = data_blob(NULL, 0);
372         conn->send_queue  = NULL;
373         conn->connection  = c;
374         conn->service     = ldapsrv_service;
375         conn->processing  = False;
376         c->private        = conn;
377
378         port = socket_get_my_port(c->socket);
379
380         /* note that '0' is a ASN1_SEQUENCE(0), which is the first byte on
381            any ldap connection */
382         conn->tls = tls_init_server(ldapsrv_service->tls_params, c->socket, 
383                                     c->event.fde, NULL, port != 389);
384         if (!conn->tls) {
385                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: tls_init_server() failed");
386                 return;
387         }
388
389         irpc_add_name(c->msg_ctx, "ldap_server");
390 }
391
392 static const struct stream_server_ops ldap_stream_ops = {
393         .name                   = "ldap",
394         .accept_connection      = ldapsrv_accept,
395         .recv_handler           = ldapsrv_recv,
396         .send_handler           = ldapsrv_send,
397 };
398
399 /*
400   add a socket address to the list of events, one event per port
401 */
402 static NTSTATUS add_socket(struct event_context *event_context,
403                            const struct model_ops *model_ops,
404                            const char *address, struct ldapsrv_service *ldap_service)
405 {
406         uint16_t port = 389;
407         NTSTATUS status;
408
409         status = stream_setup_socket(event_context, model_ops, &ldap_stream_ops, 
410                                      "ipv4", address, &port, ldap_service);
411         if (!NT_STATUS_IS_OK(status)) {
412                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
413                          address, port, nt_errstr(status)));
414         }
415
416         if (tls_support(ldap_service->tls_params)) {
417                 /* add ldaps server */
418                 port = 636;
419                 status = stream_setup_socket(event_context, model_ops, &ldap_stream_ops, 
420                                              "ipv4", address, &port, ldap_service);
421                 if (!NT_STATUS_IS_OK(status)) {
422                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
423                                  address, port, nt_errstr(status)));
424                 }
425         }
426
427         return status;
428 }
429
430 /*
431   open the ldap server sockets
432 */
433 static void ldapsrv_task_init(struct task_server *task)
434 {       
435         struct ldapsrv_service *ldap_service;
436         struct ldapsrv_partition *rootDSE_part;
437         struct ldapsrv_partition *part;
438         NTSTATUS status;
439
440         ldap_service = talloc_zero(task, struct ldapsrv_service);
441         if (ldap_service == NULL) goto failed;
442
443         ldap_service->tls_params = tls_initialise(ldap_service);
444         if (ldap_service->tls_params == NULL) goto failed;
445
446         rootDSE_part = talloc(ldap_service, struct ldapsrv_partition);
447         if (rootDSE_part == NULL) goto failed;
448
449         rootDSE_part->base_dn = ""; /* RootDSE */
450         rootDSE_part->ops = ldapsrv_get_rootdse_partition_ops();
451
452         ldap_service->rootDSE = rootDSE_part;
453         DLIST_ADD_END(ldap_service->partitions, rootDSE_part, struct ldapsrv_partition *);
454
455         part = talloc(ldap_service, struct ldapsrv_partition);
456         if (part == NULL) goto failed;
457
458         part->base_dn = "*"; /* default partition */
459         if (lp_parm_bool(-1, "ldapsrv", "hacked", False)) {
460                 part->ops = ldapsrv_get_hldb_partition_ops();
461         } else {
462                 part->ops = ldapsrv_get_sldb_partition_ops();
463         }
464
465         ldap_service->default_partition = part;
466         DLIST_ADD_END(ldap_service->partitions, part, struct ldapsrv_partition *);
467
468         if (lp_interfaces() && lp_bind_interfaces_only()) {
469                 int num_interfaces = iface_count();
470                 int i;
471
472                 /* We have been given an interfaces line, and been 
473                    told to only bind to those interfaces. Create a
474                    socket per interface and bind to only these.
475                 */
476                 for(i = 0; i < num_interfaces; i++) {
477                         const char *address = iface_n_ip(i);
478                         status = add_socket(task->event_ctx, task->model_ops, address, ldap_service);
479                         if (!NT_STATUS_IS_OK(status)) goto failed;
480                 }
481         } else {
482                 status = add_socket(task->event_ctx, task->model_ops, lp_socket_address(), ldap_service);
483                 if (!NT_STATUS_IS_OK(status)) goto failed;
484         }
485
486         return;
487
488 failed:
489         task_server_terminate(task, "Failed to startup ldap server task");      
490 }
491
492 /*
493   called on startup of the web server service It's job is to start
494   listening on all configured sockets
495 */
496 static NTSTATUS ldapsrv_init(struct event_context *event_context, 
497                              const struct model_ops *model_ops)
498 {       
499         return task_server_startup(event_context, model_ops, ldapsrv_task_init);
500 }
501
502
503 NTSTATUS server_service_ldap_init(void)
504 {
505         return register_server_service("ldap", ldapsrv_init);
506 }