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