r10987: add support for tcp kdc requests
[kai/samba-autobuild/.git] / source4 / kdc / kdc.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    KDC Server startup
5
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
7    Copyright (C) Andrew Tridgell        2005
8    Copyright (C) Stefan Metzmacher      2005
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 "smbd/service_task.h"
27 #include "smbd/service_stream.h"
28 #include "lib/events/events.h"
29 #include "lib/socket/socket.h"
30 #include "kdc/kdc.h"
31 #include "system/network.h"
32 #include "dlinklist.h"
33 #include "lib/messaging/irpc.h"
34
35 /* hold all the info needed to send a reply */
36 struct kdc_reply {
37         struct kdc_reply *next, *prev;
38         const char *dest_address;
39         int dest_port;
40         DATA_BLOB packet;
41 };
42
43 /*
44   top level context structure for the kdc server
45 */
46 struct kdc_server {
47         struct task_server *task;
48         krb5_kdc_configuration *config;
49         struct smb_krb5_context *smb_krb5_context;
50 };
51
52 /* hold information about one kdc socket */
53 struct kdc_socket {
54         struct socket_context *sock;
55         struct kdc_server *kdc;
56         struct fd_event *fde;
57
58         /* a queue of outgoing replies that have been deferred */
59         struct kdc_reply *send_queue;
60 };
61 /*
62   state of an open tcp connection
63 */
64 struct kdc_tcp_connection {
65         /* stream connection we belong to */
66         struct stream_connection *conn;
67
68         /* the kdc_server the connection belongs to */
69         struct kdc_server *kdc;
70
71         /* the partial data we've receiced yet */
72         DATA_BLOB partial;
73
74         /* the amount that we used yet from the partial buffer */
75         uint32_t partial_read;
76
77         /* prevent loops when we use half async code, while processing a requuest */
78         BOOL processing;
79
80         /* a queue of outgoing replies that have been deferred */
81         struct data_blob_list_item *send_queue;
82 };
83
84 /*
85   handle fd send events on a KDC socket
86 */
87 static void kdc_send_handler(struct kdc_socket *kdc_socket)
88 {
89         while (kdc_socket->send_queue) {
90                 struct kdc_reply *rep = kdc_socket->send_queue;
91                 NTSTATUS status;
92                 size_t sendlen;
93
94                 status = socket_sendto(kdc_socket->sock, &rep->packet, &sendlen, 0,
95                                        rep->dest_address, rep->dest_port);
96                 if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
97                         break;
98                 }
99                 
100                 DLIST_REMOVE(kdc_socket->send_queue, rep);
101                 talloc_free(rep);
102         }
103
104         if (kdc_socket->send_queue == NULL) {
105                 EVENT_FD_NOT_WRITEABLE(kdc_socket->fde);
106         }
107 }
108
109
110 /*
111   handle fd recv events on a KDC socket
112 */
113 static void kdc_recv_handler(struct kdc_socket *kdc_socket)
114 {
115         NTSTATUS status;
116         TALLOC_CTX *tmp_ctx = talloc_new(kdc_socket);
117         DATA_BLOB blob;
118         struct kdc_reply *rep;
119         krb5_data reply;
120         size_t nread, dsize;
121         const char *src_addr;
122         int src_port;
123         struct sockaddr_in src_sock_addr;
124         struct ipv4_addr addr;
125         int ret;
126
127         status = socket_pending(kdc_socket->sock, &dsize);
128         if (!NT_STATUS_IS_OK(status)) {
129                 talloc_free(tmp_ctx);
130                 return;
131         }
132
133         blob = data_blob_talloc(kdc_socket, NULL, dsize);
134         if (blob.data == NULL) {
135                 /* hope this is a temporary low memory condition */
136                 talloc_free(tmp_ctx);
137                 return;
138         }
139
140         status = socket_recvfrom(kdc_socket->sock, blob.data, blob.length, &nread, 0,
141                                  &src_addr, &src_port);
142         if (!NT_STATUS_IS_OK(status)) {
143                 talloc_free(tmp_ctx);
144                 return;
145         }
146         talloc_steal(tmp_ctx, src_addr);
147         blob.length = nread;
148         
149         DEBUG(2,("Received krb5 UDP packet of length %u from %s:%u\n", 
150                  blob.length, src_addr, (uint16_t)src_port));
151         
152         /* TODO:  This really should be in a utility function somewhere */
153         ZERO_STRUCT(src_sock_addr);
154 #ifdef HAVE_SOCK_SIN_LEN
155         src_sock_addr.sin_len         = sizeof(src_sock_addr);
156 #endif
157         addr                     = interpret_addr2(src_addr);
158         src_sock_addr.sin_addr.s_addr = addr.addr;
159         src_sock_addr.sin_port        = htons(src_port);
160         src_sock_addr.sin_family      = PF_INET;
161         
162         /* Call krb5 */
163         ret = krb5_kdc_process_krb5_request(kdc_socket->kdc->smb_krb5_context->krb5_context, 
164                                             kdc_socket->kdc->config,
165                                             blob.data, blob.length, 
166                                             &reply,
167                                             src_addr,
168                                             (struct sockaddr *)&src_sock_addr);
169         if (ret == -1) {
170                 talloc_free(tmp_ctx);
171                 return;
172         }
173
174         /* queue a pending reply */
175         rep = talloc(kdc_socket, struct kdc_reply);
176         if (rep == NULL) {
177                 krb5_data_free(&reply);
178                 talloc_free(tmp_ctx);
179                 return;
180         }
181         rep->dest_address = talloc_steal(rep, src_addr);
182         rep->dest_port    = src_port;
183         rep->packet       = data_blob_talloc(rep, reply.data, reply.length);
184         krb5_data_free(&reply);
185
186         if (rep->packet.data == NULL) {
187                 talloc_free(rep);
188                 talloc_free(tmp_ctx);
189                 return;
190         }
191
192         DLIST_ADD_END(kdc_socket->send_queue, rep, struct kdc_reply *);
193         EVENT_FD_WRITEABLE(kdc_socket->fde);
194         talloc_free(tmp_ctx);
195 }
196
197 /*
198   handle fd events on a KDC socket
199 */
200 static void kdc_socket_handler(struct event_context *ev, struct fd_event *fde,
201                                uint16_t flags, void *private)
202 {
203         struct kdc_socket *kdc_socket = talloc_get_type(private, struct kdc_socket);
204         if (flags & EVENT_FD_WRITE) {
205                 kdc_send_handler(kdc_socket);
206         } 
207         if (flags & EVENT_FD_READ) {
208                 kdc_recv_handler(kdc_socket);
209         }
210 }
211
212 static void kdc_tcp_terminate_connection(struct kdc_tcp_connection *kdcconn, const char *reason)
213 {
214         stream_terminate_connection(kdcconn->conn, reason);
215 }
216
217 /*
218   called when we get a new connection
219 */
220 static void kdc_tcp_accept(struct stream_connection *conn)
221 {
222         struct kdc_server *kdc = talloc_get_type(conn->private, struct kdc_server);
223         struct kdc_tcp_connection *kdcconn;
224
225         kdcconn = talloc_zero(conn, struct kdc_tcp_connection);
226         if (!kdcconn) {
227                 stream_terminate_connection(conn, "kdc_tcp_accept: out of memory");
228                 return;
229         }
230         kdcconn->conn   = conn;
231         kdcconn->kdc    = kdc;
232         conn->private = kdcconn;
233 }
234
235 /*
236   receive some data on a winbind connection
237 */
238 static void kdc_tcp_recv(struct stream_connection *conn, uint16_t flags)
239 {
240         struct kdc_tcp_connection *kdcconn = talloc_get_type(conn->private, struct kdc_tcp_connection);
241         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
242         TALLOC_CTX *tmp_ctx = talloc_new(kdcconn);
243         struct data_blob_list_item *rep;
244         krb5_data reply;
245         size_t nread;
246         const char *src_addr;
247         int src_port;
248         struct sockaddr_in src_sock_addr;
249         struct ipv4_addr addr;
250         int ret;
251
252         /* avoid recursion, because of half async code */
253         if (kdcconn->processing) {
254                 EVENT_FD_NOT_READABLE(conn->event.fde);
255                 return;
256         }
257
258         if (kdcconn->partial.length == 0) {
259                 kdcconn->partial = data_blob_talloc(kdcconn, NULL, 4);
260                 if (!kdcconn->partial.data) goto nomem;
261
262                 kdcconn->partial_read = 0;
263         }
264
265         /* read in the packet length */
266         if (kdcconn->partial_read < 4) {
267                 uint32_t packet_length;
268
269                 status = socket_recv(conn->socket, 
270                                      kdcconn->partial.data + kdcconn->partial_read,
271                                      4 - kdcconn->partial_read,
272                                      &nread, 0);
273                 if (NT_STATUS_IS_ERR(status)) goto failed;
274                 if (!NT_STATUS_IS_OK(status)) return;
275
276                 kdcconn->partial_read += nread;
277                 if (kdcconn->partial_read != 4) return;
278
279                 packet_length = RIVAL(kdcconn->partial.data, 0) + 4;
280
281                 kdcconn->partial.data = talloc_realloc(kdcconn, kdcconn->partial.data, 
282                                                        uint8_t, packet_length);
283                 if (!kdcconn->partial.data) goto nomem;
284
285                 kdcconn->partial.length = packet_length;
286         }
287
288         /* read in the body */
289         status = socket_recv(conn->socket, 
290                              kdcconn->partial.data + kdcconn->partial_read,
291                              kdcconn->partial.length - kdcconn->partial_read,
292                              &nread, 0);
293         if (NT_STATUS_IS_ERR(status)) goto failed;
294         if (!NT_STATUS_IS_OK(status)) return;
295
296         kdcconn->partial_read += nread;
297         if (kdcconn->partial_read != kdcconn->partial.length) return;
298
299         /*
300          * we have parsed the request, so we can reset the kdcconn->partial_read,
301          * maybe we could also free kdcconn->partial, but for now we keep it,
302          * and overwrite it the next time
303          */
304         kdcconn->partial_read = 0;
305
306         src_addr = socket_get_peer_addr(kdcconn->conn->socket, tmp_ctx);
307         if (!src_addr) goto nomem;
308         src_port = socket_get_peer_port(kdcconn->conn->socket);
309
310         DEBUG(2,("Received krb5 TCP packet of length %u from %s:%u\n", 
311                  kdcconn->partial.length - 4, src_addr, src_port));
312
313         /* TODO:  This really should be in a utility function somewhere */
314         ZERO_STRUCT(src_sock_addr);
315 #ifdef HAVE_SOCK_SIN_LEN
316         src_sock_addr.sin_len           = sizeof(src_sock_addr);
317 #endif
318         addr                            = interpret_addr2(src_addr);
319         src_sock_addr.sin_addr.s_addr   = addr.addr;
320         src_sock_addr.sin_port          = htons(src_port);
321         src_sock_addr.sin_family        = PF_INET;
322
323         /* Call krb5 */
324         kdcconn->processing = True;
325         ret = krb5_kdc_process_krb5_request(kdcconn->kdc->smb_krb5_context->krb5_context, 
326                                             kdcconn->kdc->config,
327                                             kdcconn->partial.data + 4, kdcconn->partial.length - 4, 
328                                             &reply,
329                                             src_addr,
330                                             (struct sockaddr *)&src_sock_addr);
331         kdcconn->processing = False;
332         if (ret == -1) {
333                 status = NT_STATUS_INTERNAL_ERROR;
334                 goto failed;
335         }
336
337         /* and now encode the reply */
338         rep = talloc(kdcconn, struct data_blob_list_item);
339         if (!rep) {
340                 krb5_data_free(&reply);
341                 goto nomem;
342         }
343
344         rep->blob = data_blob_talloc(rep, NULL, reply.length + 4);
345         if (!rep->blob.data)  {
346                 krb5_data_free(&reply);
347                 goto nomem;
348         }
349
350         RSIVAL(rep->blob.data, 0, reply.length);
351         memcpy(rep->blob.data + 4, reply.data, reply.length);   
352         krb5_data_free(&reply);
353
354         if (!kdcconn->send_queue) {
355                 EVENT_FD_WRITEABLE(kdcconn->conn->event.fde);
356         }
357         DLIST_ADD_END(kdcconn->send_queue, rep, struct data_blob_list_item *);
358
359         EVENT_FD_READABLE(kdcconn->conn->event.fde);
360
361         /* the call isn't needed any more */
362         talloc_free(tmp_ctx);
363         return;
364 nomem:
365         status = NT_STATUS_NO_MEMORY;
366 failed:
367         kdc_tcp_terminate_connection(kdcconn, nt_errstr(status));
368 }
369
370 /*
371   called when we can write to a connection
372 */
373 static void kdc_tcp_send(struct stream_connection *conn, uint16_t flags)
374 {
375         struct kdc_tcp_connection *kdcconn = talloc_get_type(conn->private, struct kdc_tcp_connection);
376         NTSTATUS status;
377
378         while (kdcconn->send_queue) {
379                 struct data_blob_list_item *q = kdcconn->send_queue;
380                 size_t sendlen;
381
382                 status = socket_send(conn->socket, &q->blob, &sendlen, 0);
383                 if (NT_STATUS_IS_ERR(status)) goto failed;
384                 if (!NT_STATUS_IS_OK(status)) return;
385
386                 q->blob.length -= sendlen;
387                 q->blob.data   += sendlen;
388
389                 if (q->blob.length == 0) {
390                         DLIST_REMOVE(kdcconn->send_queue, q);
391                         talloc_free(q);
392                 }
393         }
394
395         EVENT_FD_NOT_WRITEABLE(conn->event.fde);
396         return;
397 failed:
398         kdc_tcp_terminate_connection(kdcconn, nt_errstr(status));
399 }
400
401 static const struct stream_server_ops kdc_tcp_stream_ops = {
402         .name                   = "kdc_tcp",
403         .accept_connection      = kdc_tcp_accept,
404         .recv_handler           = kdc_tcp_recv,
405         .send_handler           = kdc_tcp_send
406 };
407
408 /*
409   start listening on the given address
410 */
411 static NTSTATUS kdc_add_socket(struct kdc_server *kdc, const char *address)
412 {
413         const struct model_ops *model_ops;
414         struct kdc_socket *kdc_socket;
415         NTSTATUS status;
416         uint16_t port = lp_krb5_port();
417
418         kdc_socket = talloc(kdc, struct kdc_socket);
419         NT_STATUS_HAVE_NO_MEMORY(kdc_socket);
420
421         status = socket_create("ip", SOCKET_TYPE_DGRAM, &kdc_socket->sock, 0);
422         if (!NT_STATUS_IS_OK(status)) {
423                 talloc_free(kdc_socket);
424                 return status;
425         }
426
427         kdc_socket->kdc = kdc;
428         kdc_socket->send_queue = NULL;
429
430         talloc_steal(kdc_socket, kdc_socket->sock);
431
432         kdc_socket->fde = event_add_fd(kdc->task->event_ctx, kdc, 
433                                        socket_get_fd(kdc_socket->sock), EVENT_FD_READ,
434                                        kdc_socket_handler, kdc_socket);
435
436         status = socket_listen(kdc_socket->sock, address, port, 0, 0);
437         if (!NT_STATUS_IS_OK(status)) {
438                 DEBUG(0,("Failed to bind to %s:%d UDP - %s\n", 
439                          address, port, nt_errstr(status)));
440                 talloc_free(kdc_socket);
441                 return status;
442         }
443
444         /* within the kdc task we want to be a single process, so
445            ask for the single process model ops and pass these to the
446            stream_setup_socket() call. */
447         model_ops = process_model_byname("single");
448         if (!model_ops) {
449                 DEBUG(0,("Can't find 'single' process model_ops\n"));
450                 talloc_free(kdc_socket);
451                 return NT_STATUS_INTERNAL_ERROR;
452         }
453
454         status = stream_setup_socket(kdc->task->event_ctx, model_ops, &kdc_tcp_stream_ops, 
455                                      "ip", address, &port, kdc);
456         if (!NT_STATUS_IS_OK(status)) {
457                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
458                          address, port, nt_errstr(status)));
459                 talloc_free(kdc_socket);
460                 return status;
461         }
462
463         return NT_STATUS_OK;
464 }
465
466
467 /*
468   setup our listening sockets on the configured network interfaces
469 */
470 static NTSTATUS kdc_startup_interfaces(struct kdc_server *kdc)
471 {
472         int num_interfaces = iface_count();
473         TALLOC_CTX *tmp_ctx = talloc_new(kdc);
474         NTSTATUS status;
475
476         /* if we are allowing incoming packets from any address, then
477            we need to bind to the wildcard address */
478         if (!lp_bind_interfaces_only()) {
479                 status = kdc_add_socket(kdc, "0.0.0.0");
480                 NT_STATUS_NOT_OK_RETURN(status);
481         } else {
482                 int i;
483
484                 for (i=0; i<num_interfaces; i++) {
485                         const char *address = talloc_strdup(tmp_ctx, iface_n_ip(i));
486                         status = kdc_add_socket(kdc, address);
487                         NT_STATUS_NOT_OK_RETURN(status);
488                 }
489         }
490
491         talloc_free(tmp_ctx);
492
493         return NT_STATUS_OK;
494 }
495
496 /*
497   startup the kdc task
498 */
499 static void kdc_task_init(struct task_server *task)
500 {
501         struct kdc_server *kdc;
502         NTSTATUS status;
503         krb5_error_code ret;
504
505         if (iface_count() == 0) {
506                 task_server_terminate(task, "kdc: no network interfaces configured");
507                 return;
508         }
509
510         kdc = talloc(task, struct kdc_server);
511         if (kdc == NULL) {
512                 task_server_terminate(task, "kdc: out of memory");
513                 return;
514         }
515
516         kdc->task = task;
517
518         /* Setup the KDC configuration */
519         kdc->config = talloc(kdc, krb5_kdc_configuration);
520         if (!kdc->config) {
521                 task_server_terminate(task, "kdc: out of memory");
522                 return;
523         }
524         krb5_kdc_default_config(kdc->config);
525
526         /* NAT and the like make this pointless, and painful */
527         kdc->config->check_ticket_addresses = FALSE;
528
529         initialize_krb5_error_table();
530
531         ret = smb_krb5_init_context(kdc, &kdc->smb_krb5_context);
532         if (ret) {
533                 DEBUG(1,("kdc_task_init: krb5_init_context failed (%s)\n", 
534                          error_message(ret)));
535                 task_server_terminate(task, "kdc: krb5_init_context failed");
536                 return; 
537         }
538
539         krb5_add_et_list(kdc->smb_krb5_context->krb5_context, initialize_hdb_error_table_r);
540
541         kdc->config->logf = kdc->smb_krb5_context->logf;
542         kdc->config->db = talloc(kdc->config, struct HDB *);
543         if (!kdc->config->db) {
544                 task_server_terminate(task, "kdc: out of memory");
545                 return;
546         }
547         kdc->config->num_db = 1;
548                 
549         ret = hdb_ldb_create(kdc, kdc->smb_krb5_context->krb5_context, 
550                              &kdc->config->db[0], lp_sam_url());
551         if (ret != 0) {
552                 DEBUG(1, ("kdc_task_init: hdb_ldb_create fails: %s\n", 
553                           smb_get_krb5_error_message(kdc->smb_krb5_context->krb5_context, ret, kdc))); 
554                 task_server_terminate(task, "kdc: hdb_ldb_create failed");
555                 return; 
556         }
557
558         /* start listening on the configured network interfaces */
559         status = kdc_startup_interfaces(kdc);
560         if (!NT_STATUS_IS_OK(status)) {
561                 task_server_terminate(task, "kdc failed to setup interfaces");
562                 return;
563         }
564
565         irpc_add_name(task->msg_ctx, "kdc_server");
566 }
567
568
569 /*
570   called on startup of the KDC service 
571 */
572 static NTSTATUS kdc_init(struct event_context *event_ctx, 
573                          const struct model_ops *model_ops)
574 {       
575         return task_server_startup(event_ctx, model_ops, kdc_task_init);
576 }
577
578 /* called at smbd startup - register ourselves as a server service */
579 NTSTATUS server_service_kdc_init(void)
580 {
581         return register_server_service("kdc", kdc_init);
582 }