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