s3:rpc_server: wrap make_auth4_context() into {become,unbecome}_root()
[nivanova/samba-autobuild/.git] / source3 / rpc_server / srv_pipe.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Almost completely rewritten by (C) Jeremy Allison 2005 - 2010
5  *  
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 3 of the License, or
9  *  (at your option) any later version.
10  *  
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *  
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*  this module apparently provides an implementation of DCE/RPC over a
21  *  named pipe (IPC$ connection using SMBtrans).  details of DCE/RPC
22  *  documentation are available (in on-line form) from the X-Open group.
23  *
24  *  this module should provide a level of abstraction between SMB
25  *  and DCE/RPC, while minimising the amount of mallocs, unnecessary
26  *  data copies, and network traffic.
27  *
28  */
29
30 #include "includes.h"
31 #include "system/filesys.h"
32 #include "srv_pipe_internal.h"
33 #include "../librpc/gen_ndr/ndr_dcerpc.h"
34 #include "../librpc/rpc/rpc_common.h"
35 #include "dcesrv_auth_generic.h"
36 #include "rpc_server.h"
37 #include "rpc_dce.h"
38 #include "smbd/smbd.h"
39 #include "auth.h"
40 #include "ntdomain.h"
41 #include "rpc_server/srv_pipe.h"
42 #include "rpc_server/rpc_contexts.h"
43 #include "lib/param/param.h"
44 #include "librpc/ndr/ndr_table.h"
45 #include "auth/gensec/gensec.h"
46 #include "librpc/ndr/ndr_dcerpc.h"
47 #include "lib/tsocket/tsocket.h"
48 #include "../librpc/gen_ndr/ndr_samr.h"
49 #include "../librpc/gen_ndr/ndr_lsa.h"
50 #include "../librpc/gen_ndr/ndr_netlogon.h"
51 #include "../librpc/gen_ndr/ndr_epmapper.h"
52 #include "../librpc/gen_ndr/ndr_echo.h"
53 #include "../librpc/gen_ndr/ndr_winspool.h"
54
55 #undef DBGC_CLASS
56 #define DBGC_CLASS DBGC_RPC_SRV
57
58 static NTSTATUS pipe_auth_verify_final(struct pipes_struct *p);
59
60 /**
61  * Dump everything from the start of the end up of the provided data
62  * into a file, but only at debug level >= 50
63  **/
64 static void dump_pdu_region(const char *name, int v,
65                             DATA_BLOB *data, size_t start, size_t end)
66 {
67         int fd, i;
68         char *fname = NULL;
69         ssize_t sz;
70
71         if (DEBUGLEVEL < 50) return;
72
73         if (start > data->length || end > data->length || start > end) return;
74
75         for (i = 1; i < 100; i++) {
76                 if (v != -1) {
77                         fname = talloc_asprintf(talloc_tos(),
78                                                 "/tmp/%s_%d.%d.prs",
79                                                 name, v, i);
80                 } else {
81                         fname = talloc_asprintf(talloc_tos(),
82                                                 "/tmp/%s_%d.prs",
83                                                 name, i);
84                 }
85                 if (!fname) {
86                         return;
87                 }
88                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
89                 if (fd != -1 || errno != EEXIST) break;
90         }
91         if (fd != -1) {
92                 sz = write(fd, data->data + start, end - start);
93                 i = close(fd);
94                 if ((sz != end - start) || (i != 0) ) {
95                         DEBUG(0, ("Error writing/closing %s: %ld!=%ld %d\n",
96                                   fname, (unsigned long)sz,
97                                   (unsigned long)end - start, i));
98                 } else {
99                         DEBUG(0,("created %s\n", fname));
100                 }
101         }
102         TALLOC_FREE(fname);
103 }
104
105 static DATA_BLOB generic_session_key(void)
106 {
107         return data_blob_const("SystemLibraryDTC", 16);
108 }
109
110 /*******************************************************************
111  Generate the next PDU to be returned from the data.
112 ********************************************************************/
113
114 static NTSTATUS create_next_packet(TALLOC_CTX *mem_ctx,
115                                    struct pipe_auth_data *auth,
116                                    uint32_t call_id,
117                                    DATA_BLOB *rdata,
118                                    size_t data_sent_length,
119                                    DATA_BLOB *frag,
120                                    size_t *pdu_size)
121 {
122         union dcerpc_payload u;
123         uint8_t pfc_flags;
124         size_t data_left;
125         size_t data_to_send;
126         size_t frag_len;
127         size_t pad_len = 0;
128         size_t auth_len = 0;
129         NTSTATUS status;
130
131         ZERO_STRUCT(u.response);
132
133         /* Set up rpc packet pfc flags. */
134         if (data_sent_length == 0) {
135                 pfc_flags = DCERPC_PFC_FLAG_FIRST;
136         } else {
137                 pfc_flags = 0;
138         }
139
140         /* Work out how much we can fit in a single PDU. */
141         data_left = rdata->length - data_sent_length;
142
143         /* Ensure there really is data left to send. */
144         if (!data_left) {
145                 DEBUG(0, ("No data left to send !\n"));
146                 return NT_STATUS_BUFFER_TOO_SMALL;
147         }
148
149         status = dcerpc_guess_sizes(auth,
150                                     DCERPC_RESPONSE_LENGTH,
151                                     data_left,
152                                     RPC_MAX_PDU_FRAG_LEN,
153                                     &data_to_send, &frag_len,
154                                     &auth_len, &pad_len);
155         if (!NT_STATUS_IS_OK(status)) {
156                 return status;
157         }
158
159         /* Set up the alloc hint. This should be the data left to send. */
160         u.response.alloc_hint = data_left;
161
162         /* Work out if this PDU will be the last. */
163         if (data_sent_length + data_to_send >= rdata->length) {
164                 pfc_flags |= DCERPC_PFC_FLAG_LAST;
165         }
166
167         /* Prepare data to be NDR encoded. */
168         u.response.stub_and_verifier =
169                 data_blob_const(rdata->data + data_sent_length, data_to_send);
170
171         /* Store the packet in the data stream. */
172         status = dcerpc_push_ncacn_packet(mem_ctx, DCERPC_PKT_RESPONSE,
173                                           pfc_flags, auth_len, call_id,
174                                           &u, frag);
175         if (!NT_STATUS_IS_OK(status)) {
176                 DEBUG(0, ("Failed to marshall RPC Packet.\n"));
177                 return status;
178         }
179
180         if (auth_len) {
181                 /* Set the proper length on the pdu, including padding.
182                  * Only needed if an auth trailer will be appended. */
183                 dcerpc_set_frag_length(frag, frag->length
184                                                 + pad_len
185                                                 + DCERPC_AUTH_TRAILER_LENGTH
186                                                 + auth_len);
187         }
188
189         if (auth_len) {
190                 status = dcerpc_add_auth_footer(auth, pad_len, frag);
191                 if (!NT_STATUS_IS_OK(status)) {
192                         data_blob_free(frag);
193                         return status;
194                 }
195         }
196
197         *pdu_size = data_to_send;
198         return NT_STATUS_OK;
199 }
200
201 /*******************************************************************
202  Generate the next PDU to be returned from the data in p->rdata. 
203 ********************************************************************/
204
205 bool create_next_pdu(struct pipes_struct *p)
206 {
207         size_t pdu_size = 0;
208         NTSTATUS status;
209
210         /*
211          * If we're in the fault state, keep returning fault PDU's until
212          * the pipe gets closed. JRA.
213          */
214         if (p->fault_state) {
215                 setup_fault_pdu(p, NT_STATUS(p->fault_state));
216                 return true;
217         }
218
219         status = create_next_packet(p->mem_ctx, &p->auth,
220                                     p->call_id, &p->out_data.rdata,
221                                     p->out_data.data_sent_length,
222                                     &p->out_data.frag, &pdu_size);
223         if (!NT_STATUS_IS_OK(status)) {
224                 DEBUG(0, ("Failed to create packet with error %s, "
225                           "(auth level %u / type %u)\n",
226                           nt_errstr(status),
227                           (unsigned int)p->auth.auth_level,
228                           (unsigned int)p->auth.auth_type));
229                 return false;
230         }
231
232         /* Setup the counts for this PDU. */
233         p->out_data.data_sent_length += pdu_size;
234         p->out_data.current_pdu_sent = 0;
235         return true;
236 }
237
238
239 static bool pipe_init_outgoing_data(struct pipes_struct *p);
240
241 /*******************************************************************
242  Marshall a bind_nak pdu.
243 *******************************************************************/
244
245 static bool setup_bind_nak(struct pipes_struct *p, struct ncacn_packet *pkt)
246 {
247         NTSTATUS status;
248         union dcerpc_payload u;
249
250         /* Free any memory in the current return data buffer. */
251         pipe_init_outgoing_data(p);
252
253         /*
254          * Initialize a bind_nak header.
255          */
256
257         ZERO_STRUCT(u);
258
259         u.bind_nak.reject_reason  = 0;
260
261         /*
262          * Marshall directly into the outgoing PDU space. We
263          * must do this as we need to set to the bind response
264          * header and are never sending more than one PDU here.
265          */
266
267         status = dcerpc_push_ncacn_packet(p->mem_ctx,
268                                           DCERPC_PKT_BIND_NAK,
269                                           DCERPC_PFC_FLAG_FIRST |
270                                                 DCERPC_PFC_FLAG_LAST,
271                                           0,
272                                           pkt->call_id,
273                                           &u,
274                                           &p->out_data.frag);
275         if (!NT_STATUS_IS_OK(status)) {
276                 return False;
277         }
278
279         p->out_data.data_sent_length = 0;
280         p->out_data.current_pdu_sent = 0;
281
282         set_incoming_fault(p);
283         TALLOC_FREE(p->auth.auth_ctx);
284         p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
285         p->auth.auth_type = DCERPC_AUTH_TYPE_NONE;
286         p->pipe_bound = False;
287         p->allow_bind = false;
288         p->allow_alter = false;
289         p->allow_auth3 = false;
290
291         return True;
292 }
293
294 /*******************************************************************
295  Marshall a fault pdu.
296 *******************************************************************/
297
298 bool setup_fault_pdu(struct pipes_struct *p, NTSTATUS fault_status)
299 {
300         NTSTATUS status;
301         union dcerpc_payload u;
302
303         /* Free any memory in the current return data buffer. */
304         pipe_init_outgoing_data(p);
305
306         /*
307          * Initialize a fault header.
308          */
309
310         ZERO_STRUCT(u);
311
312         u.fault.status          = NT_STATUS_V(fault_status);
313
314         /*
315          * Marshall directly into the outgoing PDU space. We
316          * must do this as we need to set to the bind response
317          * header and are never sending more than one PDU here.
318          */
319
320         status = dcerpc_push_ncacn_packet(p->mem_ctx,
321                                           DCERPC_PKT_FAULT,
322                                           DCERPC_PFC_FLAG_FIRST |
323                                            DCERPC_PFC_FLAG_LAST |
324                                            DCERPC_PFC_FLAG_DID_NOT_EXECUTE,
325                                           0,
326                                           p->call_id,
327                                           &u,
328                                           &p->out_data.frag);
329         if (!NT_STATUS_IS_OK(status)) {
330                 return False;
331         }
332
333         p->out_data.data_sent_length = 0;
334         p->out_data.current_pdu_sent = 0;
335
336         return True;
337 }
338
339 /*******************************************************************
340  Ensure a bind request has the correct abstract & transfer interface.
341  Used to reject unknown binds from Win2k.
342 *******************************************************************/
343
344 static bool check_bind_req(struct pipes_struct *p,
345                            struct ndr_syntax_id* abstract,
346                            struct ndr_syntax_id* transfer,
347                            uint32_t context_id)
348 {
349         struct pipe_rpc_fns *context_fns;
350         bool ok;
351         const char *interface_name = NULL;
352
353         DEBUG(3,("check_bind_req for %s context_id=%u\n",
354                  ndr_interface_name(&abstract->uuid,
355                                     abstract->if_version),
356                  (unsigned)context_id));
357
358         ok = ndr_syntax_id_equal(transfer, &ndr_transfer_syntax_ndr);
359         if (!ok) {
360                 DEBUG(1,("check_bind_req unknown transfer syntax for "
361                          "%s context_id=%u\n",
362                          ndr_interface_name(&abstract->uuid,
363                                     abstract->if_version),
364                          (unsigned)context_id));
365                 return false;
366         }
367
368         for (context_fns = p->contexts;
369              context_fns != NULL;
370              context_fns = context_fns->next)
371         {
372                 if (context_fns->context_id != context_id) {
373                         continue;
374                 }
375
376                 ok = ndr_syntax_id_equal(&context_fns->syntax,
377                                          abstract);
378                 if (ok) {
379                         return true;
380                 }
381
382                 DEBUG(1,("check_bind_req: changing abstract syntax for "
383                          "%s context_id=%u into %s not supported\n",
384                          ndr_interface_name(&context_fns->syntax.uuid,
385                                             context_fns->syntax.if_version),
386                          (unsigned)context_id,
387                          ndr_interface_name(&abstract->uuid,
388                                             abstract->if_version)));
389                 return false;
390         }
391
392         /* we have to check all now since win2k introduced a new UUID on the lsaprpc pipe */
393         if (!rpc_srv_pipe_exists_by_id(abstract)) {
394                 return false;
395         }
396
397         DEBUG(3, ("check_bind_req: %s -> %s rpc service\n",
398                   rpc_srv_get_pipe_cli_name(abstract),
399                   rpc_srv_get_pipe_srv_name(abstract)));
400
401         ok = init_pipe_handles(p, abstract);
402         if (!ok) {
403                 DEBUG(1, ("Failed to init pipe handles!\n"));
404                 return false;
405         }
406
407         context_fns = talloc_zero(p, struct pipe_rpc_fns);
408         if (context_fns == NULL) {
409                 DEBUG(0,("check_bind_req: talloc() failed!\n"));
410                 return false;
411         }
412
413         interface_name = ndr_interface_name(&abstract->uuid,
414                                             abstract->if_version);
415         SMB_ASSERT(interface_name != NULL);
416
417         context_fns->next = context_fns->prev = NULL;
418         context_fns->n_cmds = rpc_srv_get_pipe_num_cmds(abstract);
419         context_fns->cmds = rpc_srv_get_pipe_cmds(abstract);
420         context_fns->context_id = context_id;
421         context_fns->syntax = *abstract;
422
423         context_fns->allow_connect = lp_allow_dcerpc_auth_level_connect();
424         /*
425          * for the samr, lsarpc and netlogon interfaces we don't allow "connect"
426          * auth_level by default.
427          */
428         ok = ndr_syntax_id_equal(abstract, &ndr_table_samr.syntax_id);
429         if (ok) {
430                 context_fns->allow_connect = false;
431         }
432         ok = ndr_syntax_id_equal(abstract, &ndr_table_lsarpc.syntax_id);
433         if (ok) {
434                 context_fns->allow_connect = false;
435         }
436         ok = ndr_syntax_id_equal(abstract, &ndr_table_netlogon.syntax_id);
437         if (ok) {
438                 context_fns->allow_connect = false;
439         }
440         /*
441          * for the epmapper and echo interfaces we allow "connect"
442          * auth_level by default.
443          */
444         ok = ndr_syntax_id_equal(abstract, &ndr_table_epmapper.syntax_id);
445         if (ok) {
446                 context_fns->allow_connect = true;
447         }
448         ok = ndr_syntax_id_equal(abstract, &ndr_table_rpcecho.syntax_id);
449         if (ok) {
450                 context_fns->allow_connect = true;
451         }
452         /*
453          * every interface can be modified to allow "connect" auth_level by
454          * using a parametric option like:
455          * allow dcerpc auth level connect:<interface>
456          * e.g.
457          * allow dcerpc auth level connect:samr = yes
458          */
459         context_fns->allow_connect = lp_parm_bool(-1,
460                 "allow dcerpc auth level connect",
461                 interface_name, context_fns->allow_connect);
462
463         ok = ndr_syntax_id_equal(abstract, &ndr_table_iremotewinspool.syntax_id);
464         if (ok) {
465                 context_fns->min_auth_level = DCERPC_AUTH_LEVEL_PACKET;
466         }
467
468         /* add to the list of open contexts */
469
470         DLIST_ADD( p->contexts, context_fns );
471
472         return True;
473 }
474
475 /**
476  * Is a named pipe known?
477  * @param[in] pipename          Just the filename
478  * @result                      Do we want to serve this?
479  */
480 bool is_known_pipename(const char *pipename, struct ndr_syntax_id *syntax)
481 {
482         NTSTATUS status;
483
484         if (strchr(pipename, '/')) {
485                 DEBUG(1, ("Refusing open on pipe %s\n", pipename));
486                 return false;
487         }
488
489         if (lp_disable_spoolss() && strequal(pipename, "spoolss")) {
490                 DEBUG(10, ("refusing spoolss access\n"));
491                 return false;
492         }
493
494         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
495                 return true;
496         }
497
498         status = smb_probe_module("rpc", pipename);
499         if (!NT_STATUS_IS_OK(status)) {
500                 DEBUG(10, ("is_known_pipename: %s unknown\n", pipename));
501                 return false;
502         }
503         DEBUG(10, ("is_known_pipename: %s loaded dynamically\n", pipename));
504
505         /*
506          * Scan the list again for the interface id
507          */
508         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
509                 return true;
510         }
511
512         DEBUG(10, ("is_known_pipename: pipe %s did not register itself!\n",
513                    pipename));
514
515         return false;
516 }
517
518 /*******************************************************************
519  Handle an NTLMSSP bind auth.
520 *******************************************************************/
521
522 static bool pipe_auth_generic_bind(struct pipes_struct *p,
523                                    struct ncacn_packet *pkt,
524                                    struct dcerpc_auth *auth_info,
525                                    const char *service_description,
526                                    DATA_BLOB *response)
527 {
528         TALLOC_CTX *mem_ctx = pkt;
529         struct gensec_security *gensec_security = NULL;
530         NTSTATUS status;
531
532         status = auth_generic_server_authtype_start(p,
533                                                     auth_info->auth_type,
534                                                     auth_info->auth_level,
535                                                     p->remote_address,
536                                                     p->local_address,
537                                                     service_description,
538                                                     &gensec_security);
539         if (!NT_STATUS_IS_OK(status)) {
540                 DEBUG(0, (__location__ ": auth_generic_server_authtype_start[%u/%u] failed: %s\n",
541                           auth_info->auth_type, auth_info->auth_level, nt_errstr(status)));
542                 return false;
543         }
544
545         p->auth.auth_ctx = gensec_security;
546         p->auth.auth_type = auth_info->auth_type;
547         p->auth.auth_level = auth_info->auth_level;
548         p->auth.auth_context_id = auth_info->auth_context_id;
549
550         if (pkt->pfc_flags & DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN) {
551                 p->auth.client_hdr_signing = true;
552                 p->auth.hdr_signing = gensec_have_feature(gensec_security,
553                                                 GENSEC_FEATURE_SIGN_PKT_HEADER);
554         }
555
556         if (p->auth.hdr_signing) {
557                 gensec_want_feature(gensec_security,
558                                     GENSEC_FEATURE_SIGN_PKT_HEADER);
559         }
560
561         status = auth_generic_server_step(gensec_security, mem_ctx,
562                                           &auth_info->credentials,
563                                           response);
564         if (!NT_STATUS_IS_OK(status) &&
565             !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED))
566         {
567                 DEBUG(2, (__location__ ": "
568                           "auth_generic_server_step[%u/%u] failed: %s\n",
569                           auth_info->auth_type, auth_info->auth_level,
570                           nt_errstr(status)));
571                 return false;
572         }
573
574         if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
575                 return true;
576         }
577
578         status = pipe_auth_verify_final(p);
579         if (!NT_STATUS_IS_OK(status)) {
580                 DEBUG(0, ("pipe_auth_verify_final failed: %s\n",
581                           nt_errstr(status)));
582                 return false;
583         }
584
585         return true;
586 }
587
588 /*******************************************************************
589  Process an NTLMSSP authentication response.
590  If this function succeeds, the user has been authenticated
591  and their domain, name and calling workstation stored in
592  the pipe struct.
593 *******************************************************************/
594
595 static bool pipe_auth_generic_verify_final(TALLOC_CTX *mem_ctx,
596                                 struct gensec_security *gensec_security,
597                                 enum dcerpc_AuthLevel auth_level,
598                                 struct auth_session_info **session_info)
599 {
600         NTSTATUS status;
601         bool ret;
602
603         DEBUG(5, (__location__ ": checking user details\n"));
604
605         /* Finally - if the pipe negotiated integrity (sign) or privacy (seal)
606            ensure the underlying NTLMSSP flags are also set. If not we should
607            refuse the bind. */
608
609         status = auth_generic_server_check_flags(gensec_security,
610                                             (auth_level >=
611                                                 DCERPC_AUTH_LEVEL_PACKET),
612                                             (auth_level ==
613                                                 DCERPC_AUTH_LEVEL_PRIVACY));
614         if (!NT_STATUS_IS_OK(status)) {
615                 DEBUG(0, (__location__ ": Client failed to negotatie proper "
616                           "security for rpc connection\n"));
617                 return false;
618         }
619
620         TALLOC_FREE(*session_info);
621
622         status = auth_generic_server_get_user_info(gensec_security,
623                                                 mem_ctx, session_info);
624         if (!NT_STATUS_IS_OK(status)) {
625                 DEBUG(0, (__location__ ": failed to obtain the server info "
626                           "for authenticated user: %s\n", nt_errstr(status)));
627                 return false;
628         }
629
630         if ((*session_info)->security_token == NULL) {
631                 DEBUG(1, ("Auth module failed to provide nt_user_token\n"));
632                 return false;
633         }
634
635         if ((*session_info)->unix_token == NULL) {
636                 DEBUG(1, ("Auth module failed to provide unix_token\n"));
637                 return false;
638         }
639
640         /*
641          * We're an authenticated bind over smb, so the session key needs to
642          * be set to "SystemLibraryDTC". Weird, but this is what Windows
643          * does. See the RPC-SAMBA3SESSIONKEY.
644          */
645
646         ret = session_info_set_session_key((*session_info), generic_session_key());
647         if (!ret) {
648                 DEBUG(0, ("Failed to set session key!\n"));
649                 return false;
650         }
651
652         return true;
653 }
654
655 static NTSTATUS pipe_auth_verify_final(struct pipes_struct *p)
656 {
657         struct gensec_security *gensec_security;
658         bool ok;
659
660         if (p->auth.auth_type == DCERPC_AUTH_TYPE_NONE) {
661                 p->pipe_bound = true;
662                 return NT_STATUS_OK;
663         }
664
665         gensec_security = p->auth.auth_ctx;
666
667         ok = pipe_auth_generic_verify_final(p, gensec_security,
668                                             p->auth.auth_level,
669                                             &p->session_info);
670         if (!ok) {
671                 return NT_STATUS_ACCESS_DENIED;
672         }
673
674         p->pipe_bound = true;
675
676         return NT_STATUS_OK;
677 }
678
679 /*******************************************************************
680  Respond to a pipe bind request.
681 *******************************************************************/
682
683 static bool api_pipe_bind_req(struct pipes_struct *p,
684                                 struct ncacn_packet *pkt)
685 {
686         struct dcerpc_auth auth_info = {0};
687         uint16_t assoc_gid;
688         NTSTATUS status;
689         struct ndr_syntax_id id;
690         uint8_t pfc_flags = 0;
691         union dcerpc_payload u;
692         struct dcerpc_ack_ctx bind_ack_ctx;
693         DATA_BLOB auth_resp = data_blob_null;
694         DATA_BLOB auth_blob = data_blob_null;
695         const struct ndr_interface_table *table;
696         const char *secondary_address = NULL;
697
698         if (!p->allow_bind) {
699                 DEBUG(2,("Pipe not in allow bind state\n"));
700                 return setup_bind_nak(p, pkt);
701         }
702         p->allow_bind = false;
703
704         status = dcerpc_verify_ncacn_packet_header(pkt,
705                         DCERPC_PKT_BIND,
706                         pkt->u.bind.auth_info.length,
707                         0, /* required flags */
708                         DCERPC_PFC_FLAG_FIRST |
709                         DCERPC_PFC_FLAG_LAST |
710                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
711                         0x08 | /* this is not defined, but should be ignored */
712                         DCERPC_PFC_FLAG_CONC_MPX |
713                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
714                         DCERPC_PFC_FLAG_MAYBE |
715                         DCERPC_PFC_FLAG_OBJECT_UUID);
716         if (!NT_STATUS_IS_OK(status)) {
717                 DEBUG(1, ("api_pipe_bind_req: invalid pdu: %s\n",
718                           nt_errstr(status)));
719                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
720                 goto err_exit;
721         }
722
723         if (pkt->u.bind.num_contexts == 0) {
724                 DEBUG(1, ("api_pipe_bind_req: no rpc contexts around\n"));
725                 goto err_exit;
726         }
727
728         if (pkt->u.bind.ctx_list[0].num_transfer_syntaxes == 0) {
729                 DEBUG(1, ("api_pipe_bind_req: no transfer syntaxes around\n"));
730                 goto err_exit;
731         }
732
733         /*
734          * Try and find the correct pipe name to ensure
735          * that this is a pipe name we support.
736          */
737         id = pkt->u.bind.ctx_list[0].abstract_syntax;
738
739         table = ndr_table_by_uuid(&id.uuid);
740         if (table == NULL) {
741                 DEBUG(0,("unknown interface\n"));
742                 return false;
743         }
744
745         if (rpc_srv_pipe_exists_by_id(&id)) {
746                 DEBUG(3, ("api_pipe_bind_req: %s -> %s rpc service\n",
747                           rpc_srv_get_pipe_cli_name(&id),
748                           rpc_srv_get_pipe_srv_name(&id)));
749         } else {
750                 status = smb_probe_module(
751                         "rpc", dcerpc_default_transport_endpoint(pkt,
752                                 NCACN_NP, table));
753
754                 if (NT_STATUS_IS_ERR(status)) {
755                         DEBUG(3,("api_pipe_bind_req: Unknown rpc service name "
756                                  "%s in bind request.\n",
757                                  ndr_interface_name(&id.uuid,
758                                                     id.if_version)));
759
760                         return setup_bind_nak(p, pkt);
761                 }
762
763                 if (rpc_srv_get_pipe_interface_by_cli_name(
764                                 dcerpc_default_transport_endpoint(pkt,
765                                         NCACN_NP, table),
766                                 &id)) {
767                         DEBUG(3, ("api_pipe_bind_req: %s -> %s rpc service\n",
768                                   rpc_srv_get_pipe_cli_name(&id),
769                                   rpc_srv_get_pipe_srv_name(&id)));
770                 } else {
771                         DEBUG(0, ("module %s doesn't provide functions for "
772                                   "pipe %s!\n",
773                                   ndr_interface_name(&id.uuid,
774                                                      id.if_version),
775                                   ndr_interface_name(&id.uuid,
776                                                      id.if_version)));
777                         return setup_bind_nak(p, pkt);
778                 }
779         }
780
781         DEBUG(5,("api_pipe_bind_req: make response. %d\n", __LINE__));
782
783         if (pkt->u.bind.assoc_group_id != 0) {
784                 assoc_gid = pkt->u.bind.assoc_group_id;
785         } else {
786                 assoc_gid = 0x53f0;
787         }
788
789         /*
790          * Create the bind response struct.
791          */
792
793         /* If the requested abstract synt uuid doesn't match our client pipe,
794                 reject the bind_ack & set the transfer interface synt to all 0's,
795                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
796                 unknown to NT4)
797                 Needed when adding entries to a DACL from NT5 - SK */
798
799         if (check_bind_req(p,
800                         &pkt->u.bind.ctx_list[0].abstract_syntax,
801                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
802                         pkt->u.bind.ctx_list[0].context_id)) {
803
804                 bind_ack_ctx.result = 0;
805                 bind_ack_ctx.reason.value = 0;
806                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
807         } else {
808                 /* Rejection reason: abstract syntax not supported */
809                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
810                 bind_ack_ctx.reason.value = DCERPC_BIND_REASON_ASYNTAX;
811                 bind_ack_ctx.syntax = ndr_syntax_id_null;
812         }
813
814         /*
815          * Check if this is an authenticated bind request.
816          */
817         if (pkt->auth_length) {
818                 /*
819                  * Decode the authentication verifier.
820                  */
821                 status = dcerpc_pull_auth_trailer(pkt, pkt,
822                                                   &pkt->u.bind.auth_info,
823                                                   &auth_info, NULL, true);
824                 if (!NT_STATUS_IS_OK(status)) {
825                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
826                         goto err_exit;
827                 }
828
829                 if (!pipe_auth_generic_bind(p, pkt,
830                                             &auth_info,
831                                             table->name,
832                                             &auth_resp)) {
833                         goto err_exit;
834                 }
835         } else {
836                 TALLOC_CTX *frame = talloc_stackframe();
837                 struct auth4_context *auth4_context;
838                 const char *transport_protection = AUTHZ_TRANSPORT_PROTECTION_NONE;
839                 if (p->transport == NCACN_NP) {
840                         transport_protection = AUTHZ_TRANSPORT_PROTECTION_SMB;
841                 }
842
843                 p->auth.auth_type = DCERPC_AUTH_TYPE_NONE;
844                 p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
845                 p->auth.auth_context_id = 0;
846
847                 become_root();
848                 status = make_auth4_context(frame, &auth4_context);
849                 unbecome_root();
850                 if (!NT_STATUS_IS_OK(status)) {
851                         DEBUG(0, ("Unable to make auth context for authz log.\n"));
852                         TALLOC_FREE(frame);
853                         goto err_exit;
854                 }
855
856                 /*
857                  * Log the authorization to this RPC interface.  This
858                  * covered ncacn_np pass-through auth, and anonymous
859                  * DCE/RPC (eg epmapper, netlogon etc)
860                  */
861                 log_successful_authz_event(auth4_context->msg_ctx,
862                                            auth4_context->lp_ctx,
863                                            p->remote_address,
864                                            p->local_address,
865                                            table->name,
866                                            derpc_transport_string_by_transport(p->transport),
867                                            transport_protection,
868                                            p->session_info);
869                 TALLOC_FREE(frame);
870         }
871
872         ZERO_STRUCT(u.bind_ack);
873         u.bind_ack.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
874         u.bind_ack.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
875         u.bind_ack.assoc_group_id = assoc_gid;
876
877         switch (p->transport) {
878         case NCACN_IP_TCP:
879                 secondary_address = talloc_asprintf(pkt, "%d",
880                         tsocket_address_inet_port(p->local_address));
881                 break;
882         case NCACN_NP:
883         default:
884                 /* name has to be \PIPE\xxxxx */
885                 secondary_address =
886                                 talloc_asprintf(pkt, "\\PIPE\\%s",
887                                                 rpc_srv_get_pipe_srv_name(&id));
888                 break;
889         }
890
891         if (secondary_address == NULL) {
892                 DEBUG(0, ("Out of memory!\n"));
893                 goto err_exit;
894         }
895
896         u.bind_ack.secondary_address = secondary_address;
897         u.bind_ack.secondary_address_size =
898                                 strlen(u.bind_ack.secondary_address) + 1;
899
900         u.bind_ack.num_results = 1;
901         u.bind_ack.ctx_list = &bind_ack_ctx;
902
903         /* NOTE: We leave the auth_info empty so we can calculate the padding
904          * later and then append the auth_info --simo */
905
906         /*
907          * Marshall directly into the outgoing PDU space. We
908          * must do this as we need to set to the bind response
909          * header and are never sending more than one PDU here.
910          */
911
912         pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST;
913
914         if (p->auth.hdr_signing) {
915                 pfc_flags |= DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN;
916         }
917
918         status = dcerpc_push_ncacn_packet(p->mem_ctx,
919                                           DCERPC_PKT_BIND_ACK,
920                                           pfc_flags,
921                                           auth_resp.length,
922                                           pkt->call_id,
923                                           &u,
924                                           &p->out_data.frag);
925         if (!NT_STATUS_IS_OK(status)) {
926                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
927                           nt_errstr(status)));
928                 goto err_exit;
929         }
930
931         if (auth_resp.length) {
932                 status = dcerpc_push_dcerpc_auth(pkt,
933                                                  p->auth.auth_type,
934                                                  p->auth.auth_level,
935                                                  0, /* pad_len */
936                                                  p->auth.auth_context_id,
937                                                  &auth_resp,
938                                                  &auth_blob);
939                 if (!NT_STATUS_IS_OK(status)) {
940                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
941                         goto err_exit;
942                 }
943         }
944
945         /* Now that we have the auth len store it into the right place in
946          * the dcerpc header */
947         dcerpc_set_frag_length(&p->out_data.frag,
948                                 p->out_data.frag.length + auth_blob.length);
949
950         if (auth_blob.length) {
951
952                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
953                                         auth_blob.data, auth_blob.length)) {
954                         DEBUG(0, ("Append of auth info failed.\n"));
955                         goto err_exit;
956                 }
957         }
958
959         /*
960          * Setup the lengths for the initial reply.
961          */
962
963         p->out_data.data_sent_length = 0;
964         p->out_data.current_pdu_sent = 0;
965
966         TALLOC_FREE(auth_blob.data);
967
968         if (bind_ack_ctx.result == 0) {
969                 p->allow_alter = true;
970                 p->allow_auth3 = true;
971                 if (p->auth.auth_type == DCERPC_AUTH_TYPE_NONE) {
972                         status = pipe_auth_verify_final(p);
973                         if (!NT_STATUS_IS_OK(status)) {
974                                 DEBUG(0, ("pipe_auth_verify_final failed: %s\n",
975                                           nt_errstr(status)));
976                                 goto err_exit;
977                         }
978                 }
979         } else {
980                 goto err_exit;
981         }
982
983         return True;
984
985   err_exit:
986
987         data_blob_free(&p->out_data.frag);
988         TALLOC_FREE(auth_blob.data);
989         return setup_bind_nak(p, pkt);
990 }
991
992 /*******************************************************************
993  This is the "stage3" response after a bind request and reply.
994 *******************************************************************/
995
996 bool api_pipe_bind_auth3(struct pipes_struct *p, struct ncacn_packet *pkt)
997 {
998         struct dcerpc_auth auth_info;
999         DATA_BLOB response = data_blob_null;
1000         struct gensec_security *gensec_security;
1001         NTSTATUS status;
1002
1003         DEBUG(5, ("api_pipe_bind_auth3: decode request. %d\n", __LINE__));
1004
1005         if (!p->allow_auth3) {
1006                 DEBUG(1, ("Pipe not in allow auth3 state.\n"));
1007                 goto err;
1008         }
1009
1010         status = dcerpc_verify_ncacn_packet_header(pkt,
1011                         DCERPC_PKT_AUTH3,
1012                         pkt->u.auth3.auth_info.length,
1013                         0, /* required flags */
1014                         DCERPC_PFC_FLAG_FIRST |
1015                         DCERPC_PFC_FLAG_LAST |
1016                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1017                         0x08 | /* this is not defined, but should be ignored */
1018                         DCERPC_PFC_FLAG_CONC_MPX |
1019                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1020                         DCERPC_PFC_FLAG_MAYBE |
1021                         DCERPC_PFC_FLAG_OBJECT_UUID);
1022         if (!NT_STATUS_IS_OK(status)) {
1023                 DEBUG(1, ("api_pipe_bind_auth3: invalid pdu: %s\n",
1024                           nt_errstr(status)));
1025                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
1026                 goto err;
1027         }
1028
1029         /* We can only finish if the pipe is unbound for now */
1030         if (p->pipe_bound) {
1031                 DEBUG(0, (__location__ ": Pipe already bound, "
1032                           "AUTH3 not supported!\n"));
1033                 goto err;
1034         }
1035
1036         if (pkt->auth_length == 0) {
1037                 DEBUG(1, ("No auth field sent for auth3 request!\n"));
1038                 goto err;
1039         }
1040
1041         /*
1042          * Decode the authentication verifier response.
1043          */
1044
1045         status = dcerpc_pull_auth_trailer(pkt, pkt,
1046                                           &pkt->u.auth3.auth_info,
1047                                           &auth_info, NULL, true);
1048         if (!NT_STATUS_IS_OK(status)) {
1049                 DEBUG(1, ("Failed to unmarshall dcerpc_auth.\n"));
1050                 goto err;
1051         }
1052
1053         /* We must NEVER look at auth_info->auth_pad_len here,
1054          * as old Samba client code gets it wrong and sends it
1055          * as zero. JRA.
1056          */
1057
1058         if (auth_info.auth_type != p->auth.auth_type) {
1059                 DEBUG(1, ("Auth type mismatch! Client sent %d, "
1060                           "but auth was started as type %d!\n",
1061                           auth_info.auth_type, p->auth.auth_type));
1062                 goto err;
1063         }
1064
1065         if (auth_info.auth_level != p->auth.auth_level) {
1066                 DEBUG(1, ("Auth level mismatch! Client sent %d, "
1067                           "but auth was started as level %d!\n",
1068                           auth_info.auth_level, p->auth.auth_level));
1069                 goto err;
1070         }
1071
1072         if (auth_info.auth_context_id != p->auth.auth_context_id) {
1073                 DEBUG(0, ("Auth context id mismatch! Client sent %u, "
1074                           "but auth was started as level %u!\n",
1075                           (unsigned)auth_info.auth_context_id,
1076                           (unsigned)p->auth.auth_context_id));
1077                 goto err;
1078         }
1079
1080         gensec_security = p->auth.auth_ctx;
1081
1082         status = auth_generic_server_step(gensec_security,
1083                                           pkt, &auth_info.credentials,
1084                                           &response);
1085
1086         if (NT_STATUS_EQUAL(status,
1087                             NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1088             response.length) {
1089                 DEBUG(1, (__location__ ": This was supposed to be the final "
1090                           "leg, but crypto machinery claims a response is "
1091                           "needed, aborting auth!\n"));
1092                 data_blob_free(&response);
1093                 goto err;
1094         }
1095         if (!NT_STATUS_IS_OK(status)) {
1096                 DEBUG(2, ("Auth failed (%s)\n", nt_errstr(status)));
1097                 goto err;
1098         }
1099
1100         /* Now verify auth was indeed successful and extract server info */
1101         status = pipe_auth_verify_final(p);
1102         if (!NT_STATUS_IS_OK(status)) {
1103                 DEBUG(2, ("Auth Verify failed (%s)\n", nt_errstr(status)));
1104                 goto err;
1105         }
1106
1107         return true;
1108
1109 err:
1110         p->pipe_bound = false;
1111         p->allow_bind = false;
1112         p->allow_alter = false;
1113         p->allow_auth3 = false;
1114
1115         TALLOC_FREE(p->auth.auth_ctx);
1116         return false;
1117 }
1118
1119 /****************************************************************************
1120  Deal with an alter context call. Can be third part of 3 leg auth request for
1121  SPNEGO calls.
1122 ****************************************************************************/
1123
1124 static bool api_pipe_alter_context(struct pipes_struct *p,
1125                                         struct ncacn_packet *pkt)
1126 {
1127         struct dcerpc_auth auth_info = {0};
1128         uint16_t assoc_gid;
1129         NTSTATUS status;
1130         union dcerpc_payload u;
1131         struct dcerpc_ack_ctx alter_ack_ctx;
1132         DATA_BLOB auth_resp = data_blob_null;
1133         DATA_BLOB auth_blob = data_blob_null;
1134         struct gensec_security *gensec_security;
1135
1136         DEBUG(5,("api_pipe_alter_context: make response. %d\n", __LINE__));
1137
1138         if (!p->allow_alter) {
1139                 DEBUG(1, ("Pipe not in allow alter state.\n"));
1140                 goto err_exit;
1141         }
1142
1143         status = dcerpc_verify_ncacn_packet_header(pkt,
1144                         DCERPC_PKT_ALTER,
1145                         pkt->u.alter.auth_info.length,
1146                         0, /* required flags */
1147                         DCERPC_PFC_FLAG_FIRST |
1148                         DCERPC_PFC_FLAG_LAST |
1149                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1150                         0x08 | /* this is not defined, but should be ignored */
1151                         DCERPC_PFC_FLAG_CONC_MPX |
1152                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1153                         DCERPC_PFC_FLAG_MAYBE |
1154                         DCERPC_PFC_FLAG_OBJECT_UUID);
1155         if (!NT_STATUS_IS_OK(status)) {
1156                 DEBUG(1, ("api_pipe_alter_context: invalid pdu: %s\n",
1157                           nt_errstr(status)));
1158                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
1159                 goto err_exit;
1160         }
1161
1162         if (pkt->u.alter.num_contexts == 0) {
1163                 DEBUG(1, ("api_pipe_alter_context: no rpc contexts around\n"));
1164                 goto err_exit;
1165         }
1166
1167         if (pkt->u.alter.ctx_list[0].num_transfer_syntaxes == 0) {
1168                 DEBUG(1, ("api_pipe_alter_context: no transfer syntaxes around\n"));
1169                 goto err_exit;
1170         }
1171
1172         if (pkt->u.alter.assoc_group_id != 0) {
1173                 assoc_gid = pkt->u.alter.assoc_group_id;
1174         } else {
1175                 assoc_gid = 0x53f0;
1176         }
1177
1178         /*
1179          * Create the bind response struct.
1180          */
1181
1182         /* If the requested abstract synt uuid doesn't match our client pipe,
1183                 reject the alter_ack & set the transfer interface synt to all 0's,
1184                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1185                 unknown to NT4)
1186                 Needed when adding entries to a DACL from NT5 - SK */
1187
1188         if (check_bind_req(p,
1189                         &pkt->u.alter.ctx_list[0].abstract_syntax,
1190                         &pkt->u.alter.ctx_list[0].transfer_syntaxes[0],
1191                         pkt->u.alter.ctx_list[0].context_id)) {
1192
1193                 alter_ack_ctx.result = 0;
1194                 alter_ack_ctx.reason.value = 0;
1195                 alter_ack_ctx.syntax = pkt->u.alter.ctx_list[0].transfer_syntaxes[0];
1196         } else {
1197                 /* Rejection reason: abstract syntax not supported */
1198                 alter_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1199                 alter_ack_ctx.reason.value = DCERPC_BIND_REASON_ASYNTAX;
1200                 alter_ack_ctx.syntax = ndr_syntax_id_null;
1201         }
1202
1203         /*
1204          * Check if this is an authenticated alter context request.
1205          */
1206         if (pkt->auth_length) {
1207                 /* We can only finish if the pipe is unbound for now */
1208                 if (p->pipe_bound) {
1209                         DEBUG(0, (__location__ ": Pipe already bound, "
1210                                   "Altering Context not yet supported!\n"));
1211                         goto err_exit;
1212                 }
1213
1214                 status = dcerpc_pull_auth_trailer(pkt, pkt,
1215                                                   &pkt->u.alter.auth_info,
1216                                                   &auth_info, NULL, true);
1217                 if (!NT_STATUS_IS_OK(status)) {
1218                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1219                         goto err_exit;
1220                 }
1221
1222                 if (auth_info.auth_type != p->auth.auth_type) {
1223                         DEBUG(0, ("Auth type mismatch! Client sent %d, "
1224                                   "but auth was started as type %d!\n",
1225                                   auth_info.auth_type, p->auth.auth_type));
1226                         goto err_exit;
1227                 }
1228
1229                 if (auth_info.auth_level != p->auth.auth_level) {
1230                         DEBUG(0, ("Auth level mismatch! Client sent %d, "
1231                                   "but auth was started as level %d!\n",
1232                                   auth_info.auth_level, p->auth.auth_level));
1233                         goto err_exit;
1234                 }
1235
1236                 if (auth_info.auth_context_id != p->auth.auth_context_id) {
1237                         DEBUG(0, ("Auth context id mismatch! Client sent %u, "
1238                                   "but auth was started as level %u!\n",
1239                                   (unsigned)auth_info.auth_context_id,
1240                                   (unsigned)p->auth.auth_context_id));
1241                         goto err_exit;
1242                 }
1243
1244                 gensec_security = p->auth.auth_ctx;
1245                 status = auth_generic_server_step(gensec_security,
1246                                                   pkt,
1247                                                   &auth_info.credentials,
1248                                                   &auth_resp);
1249                 if (NT_STATUS_IS_OK(status)) {
1250                         /* third leg of auth, verify auth info */
1251                         status = pipe_auth_verify_final(p);
1252                         if (!NT_STATUS_IS_OK(status)) {
1253                                 DEBUG(0, ("Auth Verify failed (%s)\n",
1254                                           nt_errstr(status)));
1255                                 goto err_exit;
1256                         }
1257                 } else if (NT_STATUS_EQUAL(status,
1258                                         NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1259                         DEBUG(10, ("More auth legs required.\n"));
1260                 } else {
1261                         DEBUG(0, ("Auth step returned an error (%s)\n",
1262                                   nt_errstr(status)));
1263                         goto err_exit;
1264                 }
1265         }
1266
1267         ZERO_STRUCT(u.alter_resp);
1268         u.alter_resp.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1269         u.alter_resp.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1270         u.alter_resp.assoc_group_id = assoc_gid;
1271
1272         /* secondary address CAN be NULL
1273          * as the specs say it's ignored.
1274          * It MUST be NULL to have the spoolss working.
1275          */
1276         u.alter_resp.secondary_address = "";
1277         u.alter_resp.secondary_address_size = 1;
1278
1279         u.alter_resp.num_results = 1;
1280         u.alter_resp.ctx_list = &alter_ack_ctx;
1281
1282         /* NOTE: We leave the auth_info empty so we can calculate the padding
1283          * later and then append the auth_info --simo */
1284
1285         /*
1286          * Marshall directly into the outgoing PDU space. We
1287          * must do this as we need to set to the bind response
1288          * header and are never sending more than one PDU here.
1289          */
1290
1291         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1292                                           DCERPC_PKT_ALTER_RESP,
1293                                           DCERPC_PFC_FLAG_FIRST |
1294                                                 DCERPC_PFC_FLAG_LAST,
1295                                           auth_resp.length,
1296                                           pkt->call_id,
1297                                           &u,
1298                                           &p->out_data.frag);
1299         if (!NT_STATUS_IS_OK(status)) {
1300                 DEBUG(0, ("Failed to marshall alter_resp packet. (%s)\n",
1301                           nt_errstr(status)));
1302                 goto err_exit;
1303         }
1304
1305         if (auth_resp.length) {
1306                 status = dcerpc_push_dcerpc_auth(pkt,
1307                                                  p->auth.auth_type,
1308                                                  p->auth.auth_level,
1309                                                  0, /* pad_len */
1310                                                  p->auth.auth_context_id,
1311                                                  &auth_resp,
1312                                                  &auth_blob);
1313                 if (!NT_STATUS_IS_OK(status)) {
1314                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1315                         goto err_exit;
1316                 }
1317         }
1318
1319         /* Now that we have the auth len store it into the right place in
1320          * the dcerpc header */
1321         dcerpc_set_frag_length(&p->out_data.frag,
1322                                 p->out_data.frag.length +
1323                                 auth_blob.length);
1324
1325         if (auth_resp.length) {
1326                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1327                                         auth_blob.data, auth_blob.length)) {
1328                         DEBUG(0, ("Append of auth info failed.\n"));
1329                         goto err_exit;
1330                 }
1331         }
1332
1333         /*
1334          * Setup the lengths for the initial reply.
1335          */
1336
1337         p->out_data.data_sent_length = 0;
1338         p->out_data.current_pdu_sent = 0;
1339
1340         TALLOC_FREE(auth_blob.data);
1341         return True;
1342
1343   err_exit:
1344
1345         data_blob_free(&p->out_data.frag);
1346         TALLOC_FREE(auth_blob.data);
1347         return setup_bind_nak(p, pkt);
1348 }
1349
1350 static bool api_rpcTNP(struct pipes_struct *p, struct ncacn_packet *pkt,
1351                        const struct api_struct *api_rpc_cmds, int n_cmds,
1352                        const struct ndr_syntax_id *syntax);
1353
1354 static bool srv_pipe_check_verification_trailer(struct pipes_struct *p,
1355                                                 struct ncacn_packet *pkt,
1356                                                 struct pipe_rpc_fns *pipe_fns)
1357 {
1358         TALLOC_CTX *frame = talloc_stackframe();
1359         struct dcerpc_sec_verification_trailer *vt = NULL;
1360         const uint32_t bitmask1 =
1361                 p->auth.client_hdr_signing ? DCERPC_SEC_VT_CLIENT_SUPPORTS_HEADER_SIGNING : 0;
1362         const struct dcerpc_sec_vt_pcontext pcontext = {
1363                 .abstract_syntax = pipe_fns->syntax,
1364                 .transfer_syntax = ndr_transfer_syntax_ndr,
1365         };
1366         const struct dcerpc_sec_vt_header2 header2 =
1367                dcerpc_sec_vt_header2_from_ncacn_packet(pkt);
1368         struct ndr_pull *ndr;
1369         enum ndr_err_code ndr_err;
1370         bool ret = false;
1371
1372         ndr = ndr_pull_init_blob(&p->in_data.data, frame);
1373         if (ndr == NULL) {
1374                 goto done;
1375         }
1376
1377         ndr_err = ndr_pop_dcerpc_sec_verification_trailer(ndr, frame, &vt);
1378         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1379                 goto done;
1380         }
1381
1382         ret = dcerpc_sec_verification_trailer_check(vt, &bitmask1,
1383                                                     &pcontext, &header2);
1384 done:
1385         TALLOC_FREE(frame);
1386         return ret;
1387 }
1388
1389 /****************************************************************************
1390  Find the correct RPC function to call for this request.
1391  If the pipe is authenticated then become the correct UNIX user
1392  before doing the call.
1393 ****************************************************************************/
1394
1395 static bool api_pipe_request(struct pipes_struct *p,
1396                                 struct ncacn_packet *pkt)
1397 {
1398         TALLOC_CTX *frame = talloc_stackframe();
1399         bool ret = False;
1400         struct pipe_rpc_fns *pipe_fns;
1401         const char *interface_name = NULL;
1402
1403         if (!p->pipe_bound) {
1404                 DEBUG(1, ("Pipe not bound!\n"));
1405                 data_blob_free(&p->out_data.rdata);
1406                 TALLOC_FREE(frame);
1407                 return false;
1408         }
1409
1410         /* get the set of RPC functions for this context */
1411         pipe_fns = find_pipe_fns_by_context(p->contexts,
1412                                             pkt->u.request.context_id);
1413         if (pipe_fns == NULL) {
1414                 DEBUG(0, ("No rpc function table associated with context "
1415                           "[%d]\n",
1416                           pkt->u.request.context_id));
1417                 data_blob_free(&p->out_data.rdata);
1418                 TALLOC_FREE(frame);
1419                 return false;
1420         }
1421
1422         interface_name = ndr_interface_name(&pipe_fns->syntax.uuid,
1423                                             pipe_fns->syntax.if_version);
1424         SMB_ASSERT(interface_name != NULL);
1425
1426         if (p->auth.auth_level < pipe_fns->min_auth_level) {
1427
1428                 DEBUG(1, ("%s: auth level required for %s: 0x%x, got: 0x%0x\n",
1429                           __func__, interface_name,
1430                           pipe_fns->min_auth_level,
1431                           p->auth.auth_level));
1432
1433                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_ACCESS_DENIED));
1434                 TALLOC_FREE(frame);
1435                 return true;
1436         }
1437
1438         switch (p->auth.auth_level) {
1439         case DCERPC_AUTH_LEVEL_NONE:
1440         case DCERPC_AUTH_LEVEL_PACKET:
1441         case DCERPC_AUTH_LEVEL_INTEGRITY:
1442         case DCERPC_AUTH_LEVEL_PRIVACY:
1443                 break;
1444         default:
1445                 if (!pipe_fns->allow_connect) {
1446                         char *addr;
1447
1448                         addr = tsocket_address_string(p->remote_address, frame);
1449
1450                         DEBUG(1, ("%s: restrict auth_level_connect access "
1451                                   "to [%s] with auth[type=0x%x,level=0x%x] "
1452                                   "on [%s] from [%s]\n",
1453                                   __func__, interface_name,
1454                                   p->auth.auth_type,
1455                                   p->auth.auth_level,
1456                                   derpc_transport_string_by_transport(p->transport),
1457                                   addr));
1458
1459                         setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_ACCESS_DENIED));
1460                         TALLOC_FREE(frame);
1461                         return true;
1462                 }
1463                 break;
1464         }
1465
1466         if (!srv_pipe_check_verification_trailer(p, pkt, pipe_fns)) {
1467                 DEBUG(1, ("srv_pipe_check_verification_trailer: failed\n"));
1468                 set_incoming_fault(p);
1469                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_ACCESS_DENIED));
1470                 data_blob_free(&p->out_data.rdata);
1471                 TALLOC_FREE(frame);
1472                 return true;
1473         }
1474
1475         if (!become_authenticated_pipe_user(p->session_info)) {
1476                 DEBUG(1, ("Failed to become pipe user!\n"));
1477                 data_blob_free(&p->out_data.rdata);
1478                 TALLOC_FREE(frame);
1479                 return false;
1480         }
1481
1482         DEBUG(5, ("Requested %s rpc service\n", interface_name));
1483
1484         ret = api_rpcTNP(p, pkt, pipe_fns->cmds, pipe_fns->n_cmds,
1485                          &pipe_fns->syntax);
1486         unbecome_authenticated_pipe_user();
1487
1488         TALLOC_FREE(frame);
1489         return ret;
1490 }
1491
1492 /*******************************************************************
1493  Calls the underlying RPC function for a named pipe.
1494  ********************************************************************/
1495
1496 static bool api_rpcTNP(struct pipes_struct *p, struct ncacn_packet *pkt,
1497                        const struct api_struct *api_rpc_cmds, int n_cmds,
1498                        const struct ndr_syntax_id *syntax)
1499 {
1500         int fn_num;
1501         uint32_t offset1;
1502         const struct ndr_interface_table *table;
1503
1504         /* interpret the command */
1505         DEBUG(4,("api_rpcTNP: %s op 0x%x - ",
1506                  ndr_interface_name(&syntax->uuid, syntax->if_version),
1507                  pkt->u.request.opnum));
1508
1509         table = ndr_table_by_uuid(&syntax->uuid);
1510         if (table == NULL) {
1511                 DEBUG(0,("unknown interface\n"));
1512                 return false;
1513         }
1514
1515         if (DEBUGLEVEL >= 50) {
1516                 fstring name;
1517                 slprintf(name, sizeof(name)-1, "in_%s",
1518                          dcerpc_default_transport_endpoint(pkt, NCACN_NP, table));
1519                 dump_pdu_region(name, pkt->u.request.opnum,
1520                                 &p->in_data.data, 0,
1521                                 p->in_data.data.length);
1522         }
1523
1524         for (fn_num = 0; fn_num < n_cmds; fn_num++) {
1525                 if (api_rpc_cmds[fn_num].opnum == pkt->u.request.opnum &&
1526                     api_rpc_cmds[fn_num].fn != NULL) {
1527                         DEBUG(3, ("api_rpcTNP: rpc command: %s\n",
1528                                   api_rpc_cmds[fn_num].name));
1529                         break;
1530                 }
1531         }
1532
1533         if (fn_num == n_cmds) {
1534                 /*
1535                  * For an unknown RPC just return a fault PDU but
1536                  * return True to allow RPC's on the pipe to continue
1537                  * and not put the pipe into fault state. JRA.
1538                  */
1539                 DEBUG(4, ("unknown\n"));
1540                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1541                 return True;
1542         }
1543
1544         offset1 = p->out_data.rdata.length;
1545
1546         DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", 
1547                 fn_num, api_rpc_cmds[fn_num].fn));
1548         /* do the actual command */
1549         if(!api_rpc_cmds[fn_num].fn(p)) {
1550                 DEBUG(0,("api_rpcTNP: %s: %s failed.\n",
1551                          ndr_interface_name(&syntax->uuid, syntax->if_version),
1552                          api_rpc_cmds[fn_num].name));
1553                 data_blob_free(&p->out_data.rdata);
1554                 return False;
1555         }
1556
1557         if (p->fault_state) {
1558                 DEBUG(4,("api_rpcTNP: fault(%d) return.\n", p->fault_state));
1559                 setup_fault_pdu(p, NT_STATUS(p->fault_state));
1560                 p->fault_state = 0;
1561                 return true;
1562         }
1563
1564         if (DEBUGLEVEL >= 50) {
1565                 fstring name;
1566                 slprintf(name, sizeof(name)-1, "out_%s",
1567                          dcerpc_default_transport_endpoint(pkt, NCACN_NP, table));
1568                 dump_pdu_region(name, pkt->u.request.opnum,
1569                                 &p->out_data.rdata, offset1,
1570                                 p->out_data.rdata.length);
1571         }
1572
1573         DEBUG(5,("api_rpcTNP: called %s successfully\n",
1574                  ndr_interface_name(&syntax->uuid, syntax->if_version)));
1575
1576         /* Check for buffer underflow in rpc parsing */
1577         if ((DEBUGLEVEL >= 10) &&
1578             (pkt->frag_length < p->in_data.data.length)) {
1579                 DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n"));
1580                 dump_data(10, p->in_data.data.data + pkt->frag_length,
1581                               p->in_data.data.length - pkt->frag_length);
1582         }
1583
1584         return True;
1585 }
1586
1587 /****************************************************************************
1588  Initialise an outgoing packet.
1589 ****************************************************************************/
1590
1591 static bool pipe_init_outgoing_data(struct pipes_struct *p)
1592 {
1593         output_data *o_data = &p->out_data;
1594
1595         /* Reset the offset counters. */
1596         o_data->data_sent_length = 0;
1597         o_data->current_pdu_sent = 0;
1598
1599         data_blob_free(&o_data->frag);
1600
1601         /* Free any memory in the current return data buffer. */
1602         data_blob_free(&o_data->rdata);
1603
1604         return True;
1605 }
1606
1607 /****************************************************************************
1608  Sets the fault state on incoming packets.
1609 ****************************************************************************/
1610
1611 void set_incoming_fault(struct pipes_struct *p)
1612 {
1613         data_blob_free(&p->in_data.data);
1614         p->in_data.pdu_needed_len = 0;
1615         p->in_data.pdu.length = 0;
1616         p->fault_state = DCERPC_NCA_S_PROTO_ERROR;
1617
1618         p->allow_alter = false;
1619         p->allow_auth3 = false;
1620         p->pipe_bound = false;
1621
1622         DEBUG(10, ("Setting fault state\n"));
1623 }
1624
1625 static NTSTATUS dcesrv_auth_request(struct pipe_auth_data *auth,
1626                                     struct ncacn_packet *pkt,
1627                                     DATA_BLOB *raw_pkt)
1628 {
1629         NTSTATUS status;
1630         size_t hdr_size = DCERPC_REQUEST_LENGTH;
1631
1632         DEBUG(10, ("Checking request auth.\n"));
1633
1634         if (pkt->pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
1635                 hdr_size += 16;
1636         }
1637
1638         /* in case of sealing this function will unseal the data in place */
1639         status = dcerpc_check_auth(auth, pkt,
1640                                    &pkt->u.request.stub_and_verifier,
1641                                    hdr_size, raw_pkt);
1642         if (!NT_STATUS_IS_OK(status)) {
1643                 return status;
1644         }
1645
1646         return NT_STATUS_OK;
1647 }
1648
1649 /****************************************************************************
1650  Processes a request pdu. This will do auth processing if needed, and
1651  appends the data into the complete stream if the LAST flag is not set.
1652 ****************************************************************************/
1653
1654 static bool process_request_pdu(struct pipes_struct *p, struct ncacn_packet *pkt)
1655 {
1656         NTSTATUS status;
1657         DATA_BLOB data;
1658         struct dcerpc_sec_vt_header2 hdr2;
1659
1660         if (!p->pipe_bound) {
1661                 DEBUG(0,("process_request_pdu: rpc request with no bind.\n"));
1662                 set_incoming_fault(p);
1663                 return False;
1664         }
1665
1666         /*
1667          * We don't ignore DCERPC_PFC_FLAG_PENDING_CANCEL.
1668          * TODO: we can reject it with DCERPC_FAULT_NO_CALL_ACTIVE later.
1669          */
1670         status = dcerpc_verify_ncacn_packet_header(pkt,
1671                         DCERPC_PKT_REQUEST,
1672                         pkt->u.request.stub_and_verifier.length,
1673                         0, /* required_flags */
1674                         DCERPC_PFC_FLAG_FIRST |
1675                         DCERPC_PFC_FLAG_LAST |
1676                         0x08 | /* this is not defined, but should be ignored */
1677                         DCERPC_PFC_FLAG_CONC_MPX |
1678                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1679                         DCERPC_PFC_FLAG_MAYBE |
1680                         DCERPC_PFC_FLAG_OBJECT_UUID);
1681         if (!NT_STATUS_IS_OK(status)) {
1682                 DEBUG(1, ("process_request_pdu: invalid pdu: %s\n",
1683                           nt_errstr(status)));
1684                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
1685                 set_incoming_fault(p);
1686                 return false;
1687         }
1688
1689         hdr2 = dcerpc_sec_vt_header2_from_ncacn_packet(pkt);
1690         if (pkt->pfc_flags & DCERPC_PFC_FLAG_FIRST) {
1691                 p->header2 = hdr2;
1692         } else {
1693                 if (!dcerpc_sec_vt_header2_equal(&hdr2, &p->header2)) {
1694                         set_incoming_fault(p);
1695                         return false;
1696                 }
1697         }
1698
1699         /* Store the opnum */
1700         p->opnum = pkt->u.request.opnum;
1701
1702         status = dcesrv_auth_request(&p->auth, pkt, &p->in_data.pdu);
1703         if (!NT_STATUS_IS_OK(status)) {
1704                 DEBUG(0, ("Failed to check packet auth. (%s)\n",
1705                           nt_errstr(status)));
1706                 set_incoming_fault(p);
1707                 return false;
1708         }
1709
1710         data = pkt->u.request.stub_and_verifier;
1711
1712         /*
1713          * Check the data length doesn't go over the 15Mb limit.
1714          * increased after observing a bug in the Windows NT 4.0 SP6a
1715          * spoolsv.exe when the response to a GETPRINTERDRIVER2 RPC
1716          * will not fit in the initial buffer of size 0x1068   --jerry 22/01/2002
1717          */
1718
1719         if (p->in_data.data.length + data.length > MAX_RPC_DATA_SIZE) {
1720                 DEBUG(0, ("process_request_pdu: "
1721                           "rpc data buffer too large (%u) + (%u)\n",
1722                           (unsigned int)p->in_data.data.length,
1723                           (unsigned int)data.length));
1724                 set_incoming_fault(p);
1725                 return False;
1726         }
1727
1728         /*
1729          * Append the data portion into the buffer and return.
1730          */
1731
1732         if (data.length) {
1733                 if (!data_blob_append(p->mem_ctx, &p->in_data.data,
1734                                           data.data, data.length)) {
1735                         DEBUG(0, ("Unable to append data size %u "
1736                                   "to parse buffer of size %u.\n",
1737                                   (unsigned int)data.length,
1738                                   (unsigned int)p->in_data.data.length));
1739                         set_incoming_fault(p);
1740                         return False;
1741                 }
1742         }
1743
1744         if (!(pkt->pfc_flags & DCERPC_PFC_FLAG_LAST)) {
1745                 return true;
1746         }
1747
1748         /*
1749          * Ok - we finally have a complete RPC stream.
1750          * Call the rpc command to process it.
1751          */
1752
1753         return api_pipe_request(p, pkt);
1754 }
1755
1756 void process_complete_pdu(struct pipes_struct *p, struct ncacn_packet *pkt)
1757 {
1758         bool reply = false;
1759
1760         /* Store the call_id */
1761         p->call_id = pkt->call_id;
1762
1763         DEBUG(10, ("Processing packet type %u\n", (unsigned int)pkt->ptype));
1764
1765         if (!pipe_init_outgoing_data(p)) {
1766                 goto done;
1767         }
1768
1769         switch (pkt->ptype) {
1770         case DCERPC_PKT_REQUEST:
1771                 reply = process_request_pdu(p, pkt);
1772                 break;
1773
1774         case DCERPC_PKT_PING: /* CL request - ignore... */
1775                 DEBUG(0, ("Error - Connectionless packet type %u received\n",
1776                           (unsigned int)pkt->ptype));
1777                 break;
1778
1779         case DCERPC_PKT_RESPONSE: /* No responses here. */
1780                 DEBUG(0, ("Error - DCERPC_PKT_RESPONSE received from client"));
1781                 break;
1782
1783         case DCERPC_PKT_FAULT:
1784         case DCERPC_PKT_WORKING:
1785                 /* CL request - reply to a ping when a call in process. */
1786         case DCERPC_PKT_NOCALL:
1787                 /* CL - server reply to a ping call. */
1788         case DCERPC_PKT_REJECT:
1789         case DCERPC_PKT_ACK:
1790         case DCERPC_PKT_CL_CANCEL:
1791         case DCERPC_PKT_FACK:
1792         case DCERPC_PKT_CANCEL_ACK:
1793                 DEBUG(0, ("Error - Connectionless packet type %u received\n",
1794                           (unsigned int)pkt->ptype));
1795                 break;
1796
1797         case DCERPC_PKT_BIND:
1798                 /*
1799                  * We assume that a pipe bind is only in one pdu.
1800                  */
1801                 reply = api_pipe_bind_req(p, pkt);
1802                 break;
1803
1804         case DCERPC_PKT_BIND_ACK:
1805         case DCERPC_PKT_BIND_NAK:
1806                 DEBUG(0, ("Error - DCERPC_PKT_BINDACK/DCERPC_PKT_BINDNACK "
1807                           "packet type %u received.\n",
1808                           (unsigned int)pkt->ptype));
1809                 break;
1810
1811
1812         case DCERPC_PKT_ALTER:
1813                 /*
1814                  * We assume that a pipe bind is only in one pdu.
1815                  */
1816                 reply = api_pipe_alter_context(p, pkt);
1817                 break;
1818
1819         case DCERPC_PKT_ALTER_RESP:
1820                 DEBUG(0, ("Error - DCERPC_PKT_ALTER_RESP received: "
1821                           "Should only be server -> client.\n"));
1822                 break;
1823
1824         case DCERPC_PKT_AUTH3:
1825                 /*
1826                  * The third packet in an auth exchange.
1827                  */
1828                 reply = api_pipe_bind_auth3(p, pkt);
1829                 break;
1830
1831         case DCERPC_PKT_SHUTDOWN:
1832                 DEBUG(0, ("Error - DCERPC_PKT_SHUTDOWN received: "
1833                           "Should only be server -> client.\n"));
1834                 break;
1835
1836         case DCERPC_PKT_CO_CANCEL:
1837                 /* For now just free all client data and continue
1838                  * processing. */
1839                 DEBUG(3,("process_complete_pdu: DCERPC_PKT_CO_CANCEL."
1840                          " Abandoning rpc call.\n"));
1841                 /* As we never do asynchronous RPC serving, we can
1842                  * never cancel a call (as far as I know).
1843                  * If we ever did we'd have to send a cancel_ack reply.
1844                  * For now, just free all client data and continue
1845                  * processing. */
1846                 reply = True;
1847                 break;
1848
1849 #if 0
1850                 /* Enable this if we're doing async rpc. */
1851                 /* We must check the outstanding callid matches. */
1852                 if (pipe_init_outgoing_data(p)) {
1853                         /* Send a cancel_ack PDU reply. */
1854                         /* We should probably check the auth-verifier here. */
1855                         reply = setup_cancel_ack_reply(p, pkt);
1856                 }
1857                 break;
1858 #endif
1859
1860         case DCERPC_PKT_ORPHANED:
1861                 /* We should probably check the auth-verifier here.
1862                  * For now just free all client data and continue
1863                  * processing. */
1864                 DEBUG(3, ("process_complete_pdu: DCERPC_PKT_ORPHANED."
1865                           " Abandoning rpc call.\n"));
1866                 reply = True;
1867                 break;
1868
1869         default:
1870                 DEBUG(0, ("process_complete_pdu: "
1871                           "Unknown rpc type = %u received.\n",
1872                           (unsigned int)pkt->ptype));
1873                 break;
1874         }
1875
1876 done:
1877         if (!reply) {
1878                 DEBUG(3,("DCE/RPC fault sent!"));
1879                 set_incoming_fault(p);
1880                 setup_fault_pdu(p, NT_STATUS(DCERPC_NCA_S_PROTO_ERROR));
1881         }
1882         /* pkt and p->in_data.pdu.data freed by caller */
1883 }
1884