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