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