s4-loadparm: 2nd half of lp_ to lpcfg_ conversion
[nivanova/samba-autobuild/.git] / source4 / ntp_signd / ntp_signd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    NTP packet signing server
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 3 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, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "smbd/service_task.h"
26 #include "smbd/service.h"
27 #include "smbd/service_stream.h"
28 #include "smbd/process_model.h"
29 #include "lib/stream/packet.h"
30 #include "lib/tsocket/tsocket.h"
31 #include "libcli/util/tstream.h"
32 #include "librpc/gen_ndr/ndr_ntp_signd.h"
33 #include "param/param.h"
34 #include "dsdb/samdb/samdb.h"
35 #include "auth/auth.h"
36 #include "libcli/security/security.h"
37 #include "lib/ldb/include/ldb.h"
38 #include "lib/ldb/include/ldb_errors.h"
39 #include "../lib/crypto/md5.h"
40 #include "system/network.h"
41 #include "system/passwd.h"
42
43 /*
44   top level context structure for the ntp_signd server
45 */
46 struct ntp_signd_server {
47         struct task_server *task;
48         struct ldb_context *samdb;
49 };
50
51 /*
52   state of an open connection
53 */
54 struct ntp_signd_connection {
55         /* stream connection we belong to */
56         struct stream_connection *conn;
57
58         /* the ntp_signd_server the connection belongs to */
59         struct ntp_signd_server *ntp_signd;
60
61         struct tstream_context *tstream;
62
63         struct tevent_queue *send_queue;
64 };
65
66 static void ntp_signd_terminate_connection(struct ntp_signd_connection *ntp_signd_conn, const char *reason)
67 {
68         stream_terminate_connection(ntp_signd_conn->conn, reason);
69 }
70
71 static NTSTATUS signing_failure(struct ntp_signd_connection *ntp_signdconn,
72                                 TALLOC_CTX *mem_ctx,
73                                 DATA_BLOB *output,
74                                 uint32_t packet_id)
75 {
76         struct signed_reply signed_reply;
77         enum ndr_err_code ndr_err;
78
79         signed_reply.op = SIGNING_FAILURE;
80         signed_reply.packet_id = packet_id;
81         signed_reply.signed_packet = data_blob(NULL, 0);
82         
83         ndr_err = ndr_push_struct_blob(output, mem_ctx, &signed_reply,
84                                        (ndr_push_flags_fn_t)ndr_push_signed_reply);
85
86         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
87                 DEBUG(1,("failed to push ntp error reply\n"));
88                 return ndr_map_error2ntstatus(ndr_err);
89         }
90
91         return NT_STATUS_OK;
92 }
93
94 /*
95   receive a full packet on a NTP_SIGND connection
96 */
97 static NTSTATUS ntp_signd_process(struct ntp_signd_connection *ntp_signd_conn,
98                                   TALLOC_CTX *mem_ctx,
99                                   DATA_BLOB *input,
100                                   DATA_BLOB *output)
101 {
102         const struct dom_sid *domain_sid;
103         struct dom_sid *sid;
104         struct sign_request sign_request;
105         struct signed_reply signed_reply;
106         enum ndr_err_code ndr_err;
107         struct ldb_result *res;
108         const char *attrs[] = { "unicodePwd", "userAccountControl", "cn", NULL };
109         struct MD5Context ctx;
110         struct samr_Password *nt_hash;
111         uint32_t user_account_control;
112         int ret;
113
114         ndr_err = ndr_pull_struct_blob_all(input, mem_ctx,
115                                            &sign_request,
116                                            (ndr_pull_flags_fn_t)ndr_pull_sign_request);
117
118         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
119                 DEBUG(1,("failed to parse ntp signing request\n"));
120                 dump_data(1, input->data, input->length);
121                 return ndr_map_error2ntstatus(ndr_err);
122         }
123
124         /* We need to implement 'check signature' and 'request server
125          * to sign' operations at some point */
126         if (sign_request.op != SIGN_TO_CLIENT) {
127                 return signing_failure(ntp_signd_conn,
128                                        mem_ctx,
129                                        output,
130                                        sign_request.packet_id);
131         }
132
133         /* We need to implement 'check signature' and 'request server
134          * to sign' operations at some point */
135         if (sign_request.version != NTP_SIGND_PROTOCOL_VERSION_0) {
136                 return signing_failure(ntp_signd_conn,
137                                        mem_ctx,
138                                        output,
139                                        sign_request.packet_id);
140         }
141
142         domain_sid = samdb_domain_sid(ntp_signd_conn->ntp_signd->samdb);
143         if (domain_sid == NULL) {
144                 return signing_failure(ntp_signd_conn,
145                                        mem_ctx,
146                                        output,
147                                        sign_request.packet_id);
148         }
149         
150         /* The top bit is a 'key selector' */
151         sid = dom_sid_add_rid(mem_ctx, domain_sid,
152                               sign_request.key_id & 0x7FFFFFFF);
153         if (sid == NULL) {
154                 talloc_free(mem_ctx);
155                 return signing_failure(ntp_signd_conn,
156                                        mem_ctx,
157                                        output,
158                                        sign_request.packet_id);
159         }
160
161         ret = ldb_search(ntp_signd_conn->ntp_signd->samdb, mem_ctx,
162                                  &res,
163                                  ldb_get_default_basedn(ntp_signd_conn->ntp_signd->samdb),
164                                  LDB_SCOPE_SUBTREE,
165                                  attrs,
166                                  "(&(objectSid=%s)(objectClass=user))",
167                                  dom_sid_string(mem_ctx, sid));
168         if (ret != LDB_SUCCESS) {
169                 DEBUG(2, ("Failed to search for SID %s in SAM for NTP signing: "
170                           "%s\n",
171                           dom_sid_string(mem_ctx, sid),
172                           ldb_errstring(ntp_signd_conn->ntp_signd->samdb)));
173                 return signing_failure(ntp_signd_conn,
174                                        mem_ctx,
175                                        output,
176                                        sign_request.packet_id);
177         }
178
179         if (res->count == 0) {
180                 DEBUG(5, ("Failed to find SID %s in SAM for NTP signing\n",
181                           dom_sid_string(mem_ctx, sid)));
182         } else if (res->count != 1) {
183                 DEBUG(1, ("Found SID %s %u times in SAM for NTP signing\n",
184                           dom_sid_string(mem_ctx, sid), res->count));
185                 return signing_failure(ntp_signd_conn,
186                                        mem_ctx,
187                                        output,
188                                        sign_request.packet_id);
189         }
190
191         user_account_control = ldb_msg_find_attr_as_uint(res->msgs[0],
192                                                          "userAccountControl",
193                                                          0);
194
195         if (user_account_control & UF_ACCOUNTDISABLE) {
196                 DEBUG(1, ("Account %s for SID [%s] is disabled\n",
197                           ldb_dn_get_linearized(res->msgs[0]->dn),
198                           dom_sid_string(mem_ctx, sid)));
199                 return NT_STATUS_ACCESS_DENIED;
200         }
201
202         if (!(user_account_control & (UF_INTERDOMAIN_TRUST_ACCOUNT|UF_SERVER_TRUST_ACCOUNT|UF_WORKSTATION_TRUST_ACCOUNT))) {
203                 DEBUG(1, ("Account %s for SID [%s] is not a trust account\n",
204                           ldb_dn_get_linearized(res->msgs[0]->dn),
205                           dom_sid_string(mem_ctx, sid)));
206                 return NT_STATUS_ACCESS_DENIED;
207         }
208
209         nt_hash = samdb_result_hash(mem_ctx, res->msgs[0], "unicodePwd");
210         if (!nt_hash) {
211                 DEBUG(1, ("No unicodePwd found on record of SID %s "
212                           "for NTP signing\n", dom_sid_string(mem_ctx, sid)));
213                 return signing_failure(ntp_signd_conn,
214                                        mem_ctx,
215                                        output,
216                                        sign_request.packet_id);
217         }
218
219         /* Generate the reply packet */
220         signed_reply.packet_id = sign_request.packet_id;
221         signed_reply.op = SIGNING_SUCCESS;
222         signed_reply.signed_packet = data_blob_talloc(mem_ctx,
223                                                       NULL,
224                                                       sign_request.packet_to_sign.length + 20);
225
226         if (!signed_reply.signed_packet.data) {
227                 return signing_failure(ntp_signd_conn,
228                                        mem_ctx,
229                                        output,
230                                        sign_request.packet_id);
231         }
232
233         memcpy(signed_reply.signed_packet.data, sign_request.packet_to_sign.data, sign_request.packet_to_sign.length);
234         SIVAL(signed_reply.signed_packet.data, sign_request.packet_to_sign.length, sign_request.key_id);
235
236         /* Sign the NTP response with the unicodePwd */
237         MD5Init(&ctx);
238         MD5Update(&ctx, nt_hash->hash, sizeof(nt_hash->hash));
239         MD5Update(&ctx, sign_request.packet_to_sign.data, sign_request.packet_to_sign.length);
240         MD5Final(signed_reply.signed_packet.data + sign_request.packet_to_sign.length + 4, &ctx);
241
242
243         /* Place it into the packet for the wire */
244         ndr_err = ndr_push_struct_blob(output, mem_ctx, &signed_reply,
245                                        (ndr_push_flags_fn_t)ndr_push_signed_reply);
246
247         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
248                 DEBUG(1,("failed to push ntp error reply\n"));
249                 return ndr_map_error2ntstatus(ndr_err);
250         }
251
252         return NT_STATUS_OK;
253 }
254
255 /*
256   called on a tcp recv
257 */
258 static void ntp_signd_recv(struct stream_connection *conn, uint16_t flags)
259 {
260         struct ntp_signd_connection *ntp_signd_conn = talloc_get_type(conn->private_data,
261                                                         struct ntp_signd_connection);
262         ntp_signd_terminate_connection(ntp_signd_conn,
263                                        "ntp_signd_recv: called");
264 }
265
266 /*
267   called when we can write to a connection
268 */
269 static void ntp_signd_send(struct stream_connection *conn, uint16_t flags)
270 {
271         struct ntp_signd_connection *ntp_signd_conn = talloc_get_type(conn->private_data,
272                                                         struct ntp_signd_connection);
273         /* this should never be triggered! */
274         ntp_signd_terminate_connection(ntp_signd_conn,
275                                        "ntp_signd_send: called");
276 }
277
278 struct ntp_signd_call {
279         struct ntp_signd_connection *ntp_signd_conn;
280         DATA_BLOB in;
281         DATA_BLOB out;
282         uint8_t out_hdr[4];
283         struct iovec out_iov[2];
284 };
285
286 static void ntp_signd_call_writev_done(struct tevent_req *subreq);
287
288 static void ntp_signd_call_loop(struct tevent_req *subreq)
289 {
290         struct ntp_signd_connection *ntp_signd_conn = tevent_req_callback_data(subreq,
291                                       struct ntp_signd_connection);
292         struct ntp_signd_call *call;
293         NTSTATUS status;
294
295         call = talloc(ntp_signd_conn, struct ntp_signd_call);
296         if (call == NULL) {
297                 ntp_signd_terminate_connection(ntp_signd_conn,
298                                 "ntp_signd_call_loop: "
299                                 "no memory for ntp_signd_call");
300                 return;
301         }
302         call->ntp_signd_conn = ntp_signd_conn;
303
304         status = tstream_read_pdu_blob_recv(subreq,
305                                             call,
306                                             &call->in);
307         TALLOC_FREE(subreq);
308         if (!NT_STATUS_IS_OK(status)) {
309                 const char *reason;
310
311                 reason = talloc_asprintf(call, "ntp_signd_call_loop: "
312                                          "tstream_read_pdu_blob_recv() - %s",
313                                          nt_errstr(status));
314                 if (reason == NULL) {
315                         reason = nt_errstr(status);
316                 }
317
318                 ntp_signd_terminate_connection(ntp_signd_conn, reason);
319                 return;
320         }
321
322         DEBUG(10,("Received NTP TCP packet of length %lu from %s\n",
323                  (long) call->in.length,
324                  tsocket_address_string(ntp_signd_conn->conn->remote_address, call)));
325
326         /* skip length header */
327         call->in.data +=4;
328         call->in.length -= 4;
329
330         status = ntp_signd_process(ntp_signd_conn,
331                                      call,
332                                      &call->in,
333                                      &call->out);
334         if (! NT_STATUS_IS_OK(status)) {
335                 const char *reason;
336
337                 reason = talloc_asprintf(call, "ntp_signd_process failed: %s",
338                                          nt_errstr(status));
339                 if (reason == NULL) {
340                         reason = nt_errstr(status);
341                 }
342
343                 ntp_signd_terminate_connection(ntp_signd_conn, reason);
344                 return;
345         }
346
347         /* First add the length of the out buffer */
348         RSIVAL(call->out_hdr, 0, call->out.length);
349         call->out_iov[0].iov_base = (char *) call->out_hdr;
350         call->out_iov[0].iov_len = 4;
351
352         call->out_iov[1].iov_base = (char *) call->out.data;
353         call->out_iov[1].iov_len = call->out.length;
354
355         subreq = tstream_writev_queue_send(call,
356                                            ntp_signd_conn->conn->event.ctx,
357                                            ntp_signd_conn->tstream,
358                                            ntp_signd_conn->send_queue,
359                                            call->out_iov, 2);
360         if (subreq == NULL) {
361                 ntp_signd_terminate_connection(ntp_signd_conn, "ntp_signd_call_loop: "
362                                 "no memory for tstream_writev_queue_send");
363                 return;
364         }
365
366         tevent_req_set_callback(subreq, ntp_signd_call_writev_done, call);
367
368         /*
369          * The NTP tcp pdu's has the length as 4 byte (initial_read_size),
370          * packet_full_request_u32 provides the pdu length then.
371          */
372         subreq = tstream_read_pdu_blob_send(ntp_signd_conn,
373                                             ntp_signd_conn->conn->event.ctx,
374                                             ntp_signd_conn->tstream,
375                                             4, /* initial_read_size */
376                                             packet_full_request_u32,
377                                             ntp_signd_conn);
378         if (subreq == NULL) {
379                 ntp_signd_terminate_connection(ntp_signd_conn, "ntp_signd_call_loop: "
380                                 "no memory for tstream_read_pdu_blob_send");
381                 return;
382         }
383         tevent_req_set_callback(subreq, ntp_signd_call_loop, ntp_signd_conn);
384 }
385
386 static void ntp_signd_call_writev_done(struct tevent_req *subreq)
387 {
388         struct ntp_signd_call *call = tevent_req_callback_data(subreq,
389                         struct ntp_signd_call);
390         int sys_errno;
391         int rc;
392
393         rc = tstream_writev_queue_recv(subreq, &sys_errno);
394         TALLOC_FREE(subreq);
395         if (rc == -1) {
396                 const char *reason;
397
398                 reason = talloc_asprintf(call, "ntp_signd_call_writev_done: "
399                                          "tstream_writev_queue_recv() - %d:%s",
400                                          sys_errno, strerror(sys_errno));
401                 if (!reason) {
402                         reason = "ntp_signd_call_writev_done: "
403                                  "tstream_writev_queue_recv() failed";
404                 }
405
406                 ntp_signd_terminate_connection(call->ntp_signd_conn, reason);
407                 return;
408         }
409
410         /* We don't care about errors */
411
412         talloc_free(call);
413 }
414
415 /*
416   called when we get a new connection
417 */
418 static void ntp_signd_accept(struct stream_connection *conn)
419 {
420         struct ntp_signd_server *ntp_signd = talloc_get_type(conn->private_data,
421                                                 struct ntp_signd_server);
422         struct ntp_signd_connection *ntp_signd_conn;
423         struct tevent_req *subreq;
424         int rc;
425
426         ntp_signd_conn = talloc_zero(conn, struct ntp_signd_connection);
427         if (ntp_signd_conn == NULL) {
428                 stream_terminate_connection(conn,
429                                 "ntp_signd_accept: out of memory");
430                 return;
431         }
432
433         ntp_signd_conn->send_queue = tevent_queue_create(conn,
434                         "ntp_signd_accept");
435         if (ntp_signd_conn->send_queue == NULL) {
436                 stream_terminate_connection(conn,
437                                 "ntp_signd_accept: out of memory");
438                 return;
439         }
440
441         TALLOC_FREE(conn->event.fde);
442
443         rc = tstream_bsd_existing_socket(ntp_signd_conn,
444                         socket_get_fd(conn->socket),
445                         &ntp_signd_conn->tstream);
446         if (rc < 0) {
447                 stream_terminate_connection(conn,
448                                 "ntp_signd_accept: out of memory");
449                 return;
450         }
451
452         ntp_signd_conn->conn = conn;
453         ntp_signd_conn->ntp_signd = ntp_signd;
454         conn->private_data = ntp_signd_conn;
455
456         /*
457          * The NTP tcp pdu's has the length as 4 byte (initial_read_size),
458          * packet_full_request_u32 provides the pdu length then.
459          */
460         subreq = tstream_read_pdu_blob_send(ntp_signd_conn,
461                                             ntp_signd_conn->conn->event.ctx,
462                                             ntp_signd_conn->tstream,
463                                             4, /* initial_read_size */
464                                             packet_full_request_u32,
465                                             ntp_signd_conn);
466         if (subreq == NULL) {
467                 ntp_signd_terminate_connection(ntp_signd_conn,
468                                 "ntp_signd_accept: "
469                                 "no memory for tstream_read_pdu_blob_send");
470                 return;
471         }
472         tevent_req_set_callback(subreq, ntp_signd_call_loop, ntp_signd_conn);
473 }
474
475 static const struct stream_server_ops ntp_signd_stream_ops = {
476         .name                   = "ntp_signd",
477         .accept_connection      = ntp_signd_accept,
478         .recv_handler           = ntp_signd_recv,
479         .send_handler           = ntp_signd_send
480 };
481
482 /*
483   startup the ntp_signd task
484 */
485 static void ntp_signd_task_init(struct task_server *task)
486 {
487         struct ntp_signd_server *ntp_signd;
488         NTSTATUS status;
489
490         const struct model_ops *model_ops;
491
492         const char *address;
493
494         if (!directory_create_or_exist(lpcfg_ntp_signd_socket_directory(task->lp_ctx), geteuid(), 0755)) {
495                 char *error = talloc_asprintf(task, "Cannot create NTP signd pipe directory: %s", 
496                                               lpcfg_ntp_signd_socket_directory(task->lp_ctx));
497                 task_server_terminate(task,
498                                       error, true);
499                 return;
500         }
501
502         /* within the ntp_signd task we want to be a single process, so
503            ask for the single process model ops and pass these to the
504            stream_setup_socket() call. */
505         model_ops = process_model_startup(task->event_ctx, "single");
506         if (!model_ops) {
507                 DEBUG(0,("Can't find 'single' process model_ops\n"));
508                 return;
509         }
510
511         task_server_set_title(task, "task[ntp_signd]");
512
513         ntp_signd = talloc(task, struct ntp_signd_server);
514         if (ntp_signd == NULL) {
515                 task_server_terminate(task, "ntp_signd: out of memory", true);
516                 return;
517         }
518
519         ntp_signd->task = task;
520
521         /* Must be system to get at the password hashes */
522         ntp_signd->samdb = samdb_connect(ntp_signd, task->event_ctx, task->lp_ctx, system_session(task->lp_ctx));
523         if (ntp_signd->samdb == NULL) {
524                 task_server_terminate(task, "ntp_signd failed to open samdb", true);
525                 return;
526         }
527
528         address = talloc_asprintf(ntp_signd, "%s/socket", lpcfg_ntp_signd_socket_directory(task->lp_ctx));
529
530         status = stream_setup_socket(ntp_signd->task->event_ctx, 
531                                      ntp_signd->task->lp_ctx,
532                                      model_ops, 
533                                      &ntp_signd_stream_ops, 
534                                      "unix", address, NULL,
535                                      lpcfg_socket_options(ntp_signd->task->lp_ctx),
536                                      ntp_signd);
537         if (!NT_STATUS_IS_OK(status)) {
538                 DEBUG(0,("Failed to bind to %s - %s\n",
539                          address, nt_errstr(status)));
540                 return;
541         }
542
543 }
544
545
546 /* called at smbd startup - register ourselves as a server service */
547 NTSTATUS server_service_ntp_signd_init(void)
548 {
549         return register_server_service("ntp_signd", ntp_signd_task_init);
550 }