CVE-2015-5370: s3:rpc_server: make use of pipe_auth_data->auth_context_id
[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         u.fault._pad            = data_blob_talloc_zero(p->mem_ctx, 4);
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         /* add to the list of open contexts */
464
465         DLIST_ADD( p->contexts, context_fns );
466
467         return True;
468 }
469
470 /**
471  * Is a named pipe known?
472  * @param[in] pipename          Just the filename
473  * @result                      Do we want to serve this?
474  */
475 bool is_known_pipename(const char *pipename, struct ndr_syntax_id *syntax)
476 {
477         NTSTATUS status;
478
479         if (lp_disable_spoolss() && strequal(pipename, "spoolss")) {
480                 DEBUG(10, ("refusing spoolss access\n"));
481                 return false;
482         }
483
484         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
485                 return true;
486         }
487
488         status = smb_probe_module("rpc", pipename);
489         if (!NT_STATUS_IS_OK(status)) {
490                 DEBUG(10, ("is_known_pipename: %s unknown\n", pipename));
491                 return false;
492         }
493         DEBUG(10, ("is_known_pipename: %s loaded dynamically\n", pipename));
494
495         /*
496          * Scan the list again for the interface id
497          */
498         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
499                 return true;
500         }
501
502         DEBUG(10, ("is_known_pipename: pipe %s did not register itself!\n",
503                    pipename));
504
505         return false;
506 }
507
508 /*******************************************************************
509  Handle an NTLMSSP bind auth.
510 *******************************************************************/
511
512 static bool pipe_auth_generic_bind(struct pipes_struct *p,
513                                    struct ncacn_packet *pkt,
514                                    struct dcerpc_auth *auth_info,
515                                    DATA_BLOB *response)
516 {
517         TALLOC_CTX *mem_ctx = pkt;
518         struct gensec_security *gensec_security = NULL;
519         NTSTATUS status;
520
521         status = auth_generic_server_authtype_start(p,
522                                                     auth_info->auth_type,
523                                                     auth_info->auth_level,
524                                                     &auth_info->credentials,
525                                                     response,
526                                                     p->remote_address,
527                                                     &gensec_security);
528         if (!NT_STATUS_IS_OK(status) &&
529             !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED))
530         {
531                 DEBUG(0, (__location__ ": auth_generic_server_authtype_start[%u/%u] failed: %s\n",
532                           auth_info->auth_type, auth_info->auth_level, nt_errstr(status)));
533                 return false;
534         }
535
536         /* Make sure data is bound to the memctx, to be freed the caller */
537         talloc_steal(mem_ctx, response->data);
538
539         p->auth.auth_ctx = gensec_security;
540         p->auth.auth_type = auth_info->auth_type;
541         p->auth.auth_level = auth_info->auth_level;
542         p->auth.auth_context_id = auth_info->auth_context_id;
543
544         if (pkt->pfc_flags & DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN) {
545                 p->auth.client_hdr_signing = true;
546                 p->auth.hdr_signing = gensec_have_feature(gensec_security,
547                                                 GENSEC_FEATURE_SIGN_PKT_HEADER);
548         }
549
550         if (p->auth.hdr_signing) {
551                 gensec_want_feature(gensec_security,
552                                     GENSEC_FEATURE_SIGN_PKT_HEADER);
553         }
554
555         if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
556                 return true;
557         }
558
559         status = pipe_auth_verify_final(p);
560         if (!NT_STATUS_IS_OK(status)) {
561                 DEBUG(0, ("pipe_auth_verify_final failed: %s\n",
562                           nt_errstr(status)));
563                 return false;
564         }
565
566         return true;
567 }
568
569 /*******************************************************************
570  Process an NTLMSSP authentication response.
571  If this function succeeds, the user has been authenticated
572  and their domain, name and calling workstation stored in
573  the pipe struct.
574 *******************************************************************/
575
576 static bool pipe_auth_generic_verify_final(TALLOC_CTX *mem_ctx,
577                                 struct gensec_security *gensec_security,
578                                 enum dcerpc_AuthLevel auth_level,
579                                 struct auth_session_info **session_info)
580 {
581         NTSTATUS status;
582         bool ret;
583
584         DEBUG(5, (__location__ ": checking user details\n"));
585
586         /* Finally - if the pipe negotiated integrity (sign) or privacy (seal)
587            ensure the underlying NTLMSSP flags are also set. If not we should
588            refuse the bind. */
589
590         status = auth_generic_server_check_flags(gensec_security,
591                                             (auth_level ==
592                                                 DCERPC_AUTH_LEVEL_INTEGRITY),
593                                             (auth_level ==
594                                                 DCERPC_AUTH_LEVEL_PRIVACY));
595         if (!NT_STATUS_IS_OK(status)) {
596                 DEBUG(0, (__location__ ": Client failed to negotatie proper "
597                           "security for rpc connection\n"));
598                 return false;
599         }
600
601         TALLOC_FREE(*session_info);
602
603         status = auth_generic_server_get_user_info(gensec_security,
604                                                 mem_ctx, session_info);
605         if (!NT_STATUS_IS_OK(status)) {
606                 DEBUG(0, (__location__ ": failed to obtain the server info "
607                           "for authenticated user: %s\n", nt_errstr(status)));
608                 return false;
609         }
610
611         if ((*session_info)->security_token == NULL) {
612                 DEBUG(1, ("Auth module failed to provide nt_user_token\n"));
613                 return false;
614         }
615
616         if ((*session_info)->unix_token == NULL) {
617                 DEBUG(1, ("Auth module failed to provide unix_token\n"));
618                 return false;
619         }
620
621         /*
622          * We're an authenticated bind over smb, so the session key needs to
623          * be set to "SystemLibraryDTC". Weird, but this is what Windows
624          * does. See the RPC-SAMBA3SESSIONKEY.
625          */
626
627         ret = session_info_set_session_key((*session_info), generic_session_key());
628         if (!ret) {
629                 DEBUG(0, ("Failed to set session key!\n"));
630                 return false;
631         }
632
633         return true;
634 }
635
636 static NTSTATUS pipe_auth_verify_final(struct pipes_struct *p)
637 {
638         struct gensec_security *gensec_security;
639         bool ok;
640
641         if (p->auth.auth_type == DCERPC_AUTH_TYPE_NONE) {
642                 p->pipe_bound = true;
643                 return NT_STATUS_OK;
644         }
645
646         gensec_security = p->auth.auth_ctx;
647
648         ok = pipe_auth_generic_verify_final(p, gensec_security,
649                                             p->auth.auth_level,
650                                             &p->session_info);
651         if (!ok) {
652                 return NT_STATUS_ACCESS_DENIED;
653         }
654
655         p->pipe_bound = true;
656
657         return NT_STATUS_OK;
658 }
659
660 /*******************************************************************
661  Respond to a pipe bind request.
662 *******************************************************************/
663
664 static bool api_pipe_bind_req(struct pipes_struct *p,
665                                 struct ncacn_packet *pkt)
666 {
667         struct dcerpc_auth auth_info = {0};
668         uint16_t assoc_gid;
669         NTSTATUS status;
670         struct ndr_syntax_id id;
671         uint8_t pfc_flags = 0;
672         union dcerpc_payload u;
673         struct dcerpc_ack_ctx bind_ack_ctx;
674         DATA_BLOB auth_resp = data_blob_null;
675         DATA_BLOB auth_blob = data_blob_null;
676         const struct ndr_interface_table *table;
677
678         if (!p->allow_bind) {
679                 DEBUG(2,("Pipe not in allow bind state\n"));
680                 return setup_bind_nak(p, pkt);
681         }
682         p->allow_bind = false;
683
684         status = dcerpc_verify_ncacn_packet_header(pkt,
685                         DCERPC_PKT_BIND,
686                         pkt->u.bind.auth_info.length,
687                         0, /* required flags */
688                         DCERPC_PFC_FLAG_FIRST |
689                         DCERPC_PFC_FLAG_LAST |
690                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
691                         0x08 | /* this is not defined, but should be ignored */
692                         DCERPC_PFC_FLAG_CONC_MPX |
693                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
694                         DCERPC_PFC_FLAG_MAYBE |
695                         DCERPC_PFC_FLAG_OBJECT_UUID);
696         if (!NT_STATUS_IS_OK(status)) {
697                 DEBUG(1, ("api_pipe_bind_req: invalid pdu: %s\n",
698                           nt_errstr(status)));
699                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
700                 goto err_exit;
701         }
702
703         if (pkt->u.bind.num_contexts == 0) {
704                 DEBUG(1, ("api_pipe_bind_req: no rpc contexts around\n"));
705                 goto err_exit;
706         }
707
708         if (pkt->u.bind.ctx_list[0].num_transfer_syntaxes == 0) {
709                 DEBUG(1, ("api_pipe_bind_req: no transfer syntaxes around\n"));
710                 goto err_exit;
711         }
712
713         /*
714          * Try and find the correct pipe name to ensure
715          * that this is a pipe name we support.
716          */
717         id = pkt->u.bind.ctx_list[0].abstract_syntax;
718
719         table = ndr_table_by_uuid(&id.uuid);
720         if (table == NULL) {
721                 DEBUG(0,("unknown interface\n"));
722                 return false;
723         }
724
725         if (rpc_srv_pipe_exists_by_id(&id)) {
726                 DEBUG(3, ("api_pipe_bind_req: %s -> %s rpc service\n",
727                           rpc_srv_get_pipe_cli_name(&id),
728                           rpc_srv_get_pipe_srv_name(&id)));
729         } else {
730                 status = smb_probe_module(
731                         "rpc", dcerpc_default_transport_endpoint(pkt,
732                                 NCACN_NP, table));
733
734                 if (NT_STATUS_IS_ERR(status)) {
735                         DEBUG(3,("api_pipe_bind_req: Unknown rpc service name "
736                                  "%s in bind request.\n",
737                                  ndr_interface_name(&id.uuid,
738                                                     id.if_version)));
739
740                         return setup_bind_nak(p, pkt);
741                 }
742
743                 if (rpc_srv_get_pipe_interface_by_cli_name(
744                                 dcerpc_default_transport_endpoint(pkt,
745                                         NCACN_NP, table),
746                                 &id)) {
747                         DEBUG(3, ("api_pipe_bind_req: %s -> %s rpc service\n",
748                                   rpc_srv_get_pipe_cli_name(&id),
749                                   rpc_srv_get_pipe_srv_name(&id)));
750                 } else {
751                         DEBUG(0, ("module %s doesn't provide functions for "
752                                   "pipe %s!\n",
753                                   ndr_interface_name(&id.uuid,
754                                                      id.if_version),
755                                   ndr_interface_name(&id.uuid,
756                                                      id.if_version)));
757                         return setup_bind_nak(p, pkt);
758                 }
759         }
760
761         DEBUG(5,("api_pipe_bind_req: make response. %d\n", __LINE__));
762
763         if (pkt->u.bind.assoc_group_id != 0) {
764                 assoc_gid = pkt->u.bind.assoc_group_id;
765         } else {
766                 assoc_gid = 0x53f0;
767         }
768
769         /*
770          * Create the bind response struct.
771          */
772
773         /* If the requested abstract synt uuid doesn't match our client pipe,
774                 reject the bind_ack & set the transfer interface synt to all 0's,
775                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
776                 unknown to NT4)
777                 Needed when adding entries to a DACL from NT5 - SK */
778
779         if (check_bind_req(p,
780                         &pkt->u.bind.ctx_list[0].abstract_syntax,
781                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
782                         pkt->u.bind.ctx_list[0].context_id)) {
783
784                 bind_ack_ctx.result = 0;
785                 bind_ack_ctx.reason.value = 0;
786                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
787         } else {
788                 /* Rejection reason: abstract syntax not supported */
789                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
790                 bind_ack_ctx.reason.value = DCERPC_BIND_REASON_ASYNTAX;
791                 bind_ack_ctx.syntax = ndr_syntax_id_null;
792         }
793
794         /*
795          * Check if this is an authenticated bind request.
796          */
797         if (pkt->auth_length) {
798                 /*
799                  * Decode the authentication verifier.
800                  */
801                 status = dcerpc_pull_auth_trailer(pkt, pkt,
802                                                   &pkt->u.bind.auth_info,
803                                                   &auth_info, NULL, true);
804                 if (!NT_STATUS_IS_OK(status)) {
805                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
806                         goto err_exit;
807                 }
808
809                 if (!pipe_auth_generic_bind(p, pkt,
810                                             &auth_info, &auth_resp)) {
811                         goto err_exit;
812                 }
813         } else {
814                 p->auth.auth_type = DCERPC_AUTH_TYPE_NONE;
815                 p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
816                 p->auth.auth_context_id = 0;
817         }
818
819         ZERO_STRUCT(u.bind_ack);
820         u.bind_ack.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
821         u.bind_ack.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
822         u.bind_ack.assoc_group_id = assoc_gid;
823
824         /* name has to be \PIPE\xxxxx */
825         u.bind_ack.secondary_address =
826                         talloc_asprintf(pkt, "\\PIPE\\%s",
827                                         rpc_srv_get_pipe_srv_name(&id));
828         if (!u.bind_ack.secondary_address) {
829                 DEBUG(0, ("Out of memory!\n"));
830                 goto err_exit;
831         }
832         u.bind_ack.secondary_address_size =
833                                 strlen(u.bind_ack.secondary_address) + 1;
834
835         u.bind_ack.num_results = 1;
836         u.bind_ack.ctx_list = &bind_ack_ctx;
837
838         /* NOTE: We leave the auth_info empty so we can calculate the padding
839          * later and then append the auth_info --simo */
840
841         /*
842          * Marshall directly into the outgoing PDU space. We
843          * must do this as we need to set to the bind response
844          * header and are never sending more than one PDU here.
845          */
846
847         pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST;
848
849         if (p->auth.hdr_signing) {
850                 pfc_flags |= DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN;
851         }
852
853         status = dcerpc_push_ncacn_packet(p->mem_ctx,
854                                           DCERPC_PKT_BIND_ACK,
855                                           pfc_flags,
856                                           auth_resp.length,
857                                           pkt->call_id,
858                                           &u,
859                                           &p->out_data.frag);
860         if (!NT_STATUS_IS_OK(status)) {
861                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
862                           nt_errstr(status)));
863                 goto err_exit;
864         }
865
866         if (auth_resp.length) {
867                 status = dcerpc_push_dcerpc_auth(pkt,
868                                                  p->auth.auth_type,
869                                                  p->auth.auth_level,
870                                                  0, /* pad_len */
871                                                  p->auth.auth_context_id,
872                                                  &auth_resp,
873                                                  &auth_blob);
874                 if (!NT_STATUS_IS_OK(status)) {
875                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
876                         goto err_exit;
877                 }
878         }
879
880         /* Now that we have the auth len store it into the right place in
881          * the dcerpc header */
882         dcerpc_set_frag_length(&p->out_data.frag,
883                                 p->out_data.frag.length + auth_blob.length);
884
885         if (auth_blob.length) {
886
887                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
888                                         auth_blob.data, auth_blob.length)) {
889                         DEBUG(0, ("Append of auth info failed.\n"));
890                         goto err_exit;
891                 }
892         }
893
894         /*
895          * Setup the lengths for the initial reply.
896          */
897
898         p->out_data.data_sent_length = 0;
899         p->out_data.current_pdu_sent = 0;
900
901         TALLOC_FREE(auth_blob.data);
902
903         if (bind_ack_ctx.result == 0) {
904                 p->allow_alter = true;
905                 p->allow_auth3 = true;
906                 if (p->auth.auth_type == DCERPC_AUTH_TYPE_NONE) {
907                         status = pipe_auth_verify_final(p);
908                         if (!NT_STATUS_IS_OK(status)) {
909                                 DEBUG(0, ("pipe_auth_verify_final failed: %s\n",
910                                           nt_errstr(status)));
911                                 goto err_exit;
912                         }
913                 }
914         } else {
915                 goto err_exit;
916         }
917
918         return True;
919
920   err_exit:
921
922         data_blob_free(&p->out_data.frag);
923         TALLOC_FREE(auth_blob.data);
924         return setup_bind_nak(p, pkt);
925 }
926
927 /*******************************************************************
928  This is the "stage3" response after a bind request and reply.
929 *******************************************************************/
930
931 bool api_pipe_bind_auth3(struct pipes_struct *p, struct ncacn_packet *pkt)
932 {
933         struct dcerpc_auth auth_info;
934         DATA_BLOB response = data_blob_null;
935         struct gensec_security *gensec_security;
936         NTSTATUS status;
937
938         DEBUG(5, ("api_pipe_bind_auth3: decode request. %d\n", __LINE__));
939
940         if (!p->allow_auth3) {
941                 DEBUG(1, ("Pipe not in allow auth3 state.\n"));
942                 goto err;
943         }
944
945         status = dcerpc_verify_ncacn_packet_header(pkt,
946                         DCERPC_PKT_AUTH3,
947                         pkt->u.auth3.auth_info.length,
948                         0, /* required flags */
949                         DCERPC_PFC_FLAG_FIRST |
950                         DCERPC_PFC_FLAG_LAST |
951                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
952                         0x08 | /* this is not defined, but should be ignored */
953                         DCERPC_PFC_FLAG_CONC_MPX |
954                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
955                         DCERPC_PFC_FLAG_MAYBE |
956                         DCERPC_PFC_FLAG_OBJECT_UUID);
957         if (!NT_STATUS_IS_OK(status)) {
958                 DEBUG(1, ("api_pipe_bind_auth3: invalid pdu: %s\n",
959                           nt_errstr(status)));
960                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
961                 goto err;
962         }
963
964         /* We can only finish if the pipe is unbound for now */
965         if (p->pipe_bound) {
966                 DEBUG(0, (__location__ ": Pipe already bound, "
967                           "AUTH3 not supported!\n"));
968                 goto err;
969         }
970
971         if (pkt->auth_length == 0) {
972                 DEBUG(1, ("No auth field sent for auth3 request!\n"));
973                 goto err;
974         }
975
976         /*
977          * Decode the authentication verifier response.
978          */
979
980         status = dcerpc_pull_auth_trailer(pkt, pkt,
981                                           &pkt->u.auth3.auth_info,
982                                           &auth_info, NULL, true);
983         if (!NT_STATUS_IS_OK(status)) {
984                 DEBUG(1, ("Failed to unmarshall dcerpc_auth.\n"));
985                 goto err;
986         }
987
988         /* We must NEVER look at auth_info->auth_pad_len here,
989          * as old Samba client code gets it wrong and sends it
990          * as zero. JRA.
991          */
992
993         if (auth_info.auth_type != p->auth.auth_type) {
994                 DEBUG(1, ("Auth type mismatch! Client sent %d, "
995                           "but auth was started as type %d!\n",
996                           auth_info.auth_type, p->auth.auth_type));
997                 goto err;
998         }
999
1000         if (auth_info.auth_level != p->auth.auth_level) {
1001                 DEBUG(1, ("Auth level mismatch! Client sent %d, "
1002                           "but auth was started as level %d!\n",
1003                           auth_info.auth_level, p->auth.auth_level));
1004                 goto err;
1005         }
1006
1007         gensec_security = p->auth.auth_ctx;
1008
1009         status = auth_generic_server_step(gensec_security,
1010                                           pkt, &auth_info.credentials,
1011                                           &response);
1012
1013         if (NT_STATUS_EQUAL(status,
1014                             NT_STATUS_MORE_PROCESSING_REQUIRED) ||
1015             response.length) {
1016                 DEBUG(1, (__location__ ": This was supposed to be the final "
1017                           "leg, but crypto machinery claims a response is "
1018                           "needed, aborting auth!\n"));
1019                 data_blob_free(&response);
1020                 goto err;
1021         }
1022         if (!NT_STATUS_IS_OK(status)) {
1023                 DEBUG(2, ("Auth failed (%s)\n", nt_errstr(status)));
1024                 goto err;
1025         }
1026
1027         /* Now verify auth was indeed successful and extract server info */
1028         status = pipe_auth_verify_final(p);
1029         if (!NT_STATUS_IS_OK(status)) {
1030                 DEBUG(2, ("Auth Verify failed (%s)\n", nt_errstr(status)));
1031                 goto err;
1032         }
1033
1034         return true;
1035
1036 err:
1037         p->pipe_bound = false;
1038         p->allow_bind = false;
1039         p->allow_alter = false;
1040         p->allow_auth3 = false;
1041
1042         TALLOC_FREE(p->auth.auth_ctx);
1043         return false;
1044 }
1045
1046 /****************************************************************************
1047  Deal with an alter context call. Can be third part of 3 leg auth request for
1048  SPNEGO calls.
1049 ****************************************************************************/
1050
1051 static bool api_pipe_alter_context(struct pipes_struct *p,
1052                                         struct ncacn_packet *pkt)
1053 {
1054         struct dcerpc_auth auth_info = {0};
1055         uint16_t assoc_gid;
1056         NTSTATUS status;
1057         union dcerpc_payload u;
1058         struct dcerpc_ack_ctx alter_ack_ctx;
1059         DATA_BLOB auth_resp = data_blob_null;
1060         DATA_BLOB auth_blob = data_blob_null;
1061         struct gensec_security *gensec_security;
1062
1063         DEBUG(5,("api_pipe_alter_context: make response. %d\n", __LINE__));
1064
1065         if (!p->allow_alter) {
1066                 DEBUG(1, ("Pipe not in allow alter state.\n"));
1067                 goto err_exit;
1068         }
1069
1070         status = dcerpc_verify_ncacn_packet_header(pkt,
1071                         DCERPC_PKT_ALTER,
1072                         pkt->u.alter.auth_info.length,
1073                         0, /* required flags */
1074                         DCERPC_PFC_FLAG_FIRST |
1075                         DCERPC_PFC_FLAG_LAST |
1076                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1077                         0x08 | /* this is not defined, but should be ignored */
1078                         DCERPC_PFC_FLAG_CONC_MPX |
1079                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1080                         DCERPC_PFC_FLAG_MAYBE |
1081                         DCERPC_PFC_FLAG_OBJECT_UUID);
1082         if (!NT_STATUS_IS_OK(status)) {
1083                 DEBUG(1, ("api_pipe_alter_context: invalid pdu: %s\n",
1084                           nt_errstr(status)));
1085                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
1086                 goto err_exit;
1087         }
1088
1089         if (pkt->u.alter.num_contexts == 0) {
1090                 DEBUG(1, ("api_pipe_alter_context: no rpc contexts around\n"));
1091                 goto err_exit;
1092         }
1093
1094         if (pkt->u.alter.ctx_list[0].num_transfer_syntaxes == 0) {
1095                 DEBUG(1, ("api_pipe_alter_context: no transfer syntaxes around\n"));
1096                 goto err_exit;
1097         }
1098
1099         if (pkt->u.alter.assoc_group_id != 0) {
1100                 assoc_gid = pkt->u.alter.assoc_group_id;
1101         } else {
1102                 assoc_gid = 0x53f0;
1103         }
1104
1105         /*
1106          * Create the bind response struct.
1107          */
1108
1109         /* If the requested abstract synt uuid doesn't match our client pipe,
1110                 reject the alter_ack & set the transfer interface synt to all 0's,
1111                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1112                 unknown to NT4)
1113                 Needed when adding entries to a DACL from NT5 - SK */
1114
1115         if (check_bind_req(p,
1116                         &pkt->u.alter.ctx_list[0].abstract_syntax,
1117                         &pkt->u.alter.ctx_list[0].transfer_syntaxes[0],
1118                         pkt->u.alter.ctx_list[0].context_id)) {
1119
1120                 alter_ack_ctx.result = 0;
1121                 alter_ack_ctx.reason.value = 0;
1122                 alter_ack_ctx.syntax = pkt->u.alter.ctx_list[0].transfer_syntaxes[0];
1123         } else {
1124                 /* Rejection reason: abstract syntax not supported */
1125                 alter_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1126                 alter_ack_ctx.reason.value = DCERPC_BIND_REASON_ASYNTAX;
1127                 alter_ack_ctx.syntax = ndr_syntax_id_null;
1128         }
1129
1130         /*
1131          * Check if this is an authenticated alter context request.
1132          */
1133         if (pkt->auth_length) {
1134                 /* We can only finish if the pipe is unbound for now */
1135                 if (p->pipe_bound) {
1136                         DEBUG(0, (__location__ ": Pipe already bound, "
1137                                   "Altering Context not yet supported!\n"));
1138                         goto err_exit;
1139                 }
1140
1141                 status = dcerpc_pull_auth_trailer(pkt, pkt,
1142                                                   &pkt->u.alter.auth_info,
1143                                                   &auth_info, NULL, true);
1144                 if (!NT_STATUS_IS_OK(status)) {
1145                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1146                         goto err_exit;
1147                 }
1148
1149                 if (auth_info.auth_type != p->auth.auth_type) {
1150                         DEBUG(0, ("Auth type mismatch! Client sent %d, "
1151                                   "but auth was started as type %d!\n",
1152                                   auth_info.auth_type, p->auth.auth_type));
1153                         goto err_exit;
1154                 }
1155
1156                 if (auth_info.auth_level != p->auth.auth_level) {
1157                         DEBUG(0, ("Auth level mismatch! Client sent %d, "
1158                                   "but auth was started as level %d!\n",
1159                                   auth_info.auth_level, p->auth.auth_level));
1160                         goto err_exit;
1161                 }
1162
1163                 gensec_security = p->auth.auth_ctx;
1164                 status = auth_generic_server_step(gensec_security,
1165                                                   pkt,
1166                                                   &auth_info.credentials,
1167                                                   &auth_resp);
1168                 if (NT_STATUS_IS_OK(status)) {
1169                         /* third leg of auth, verify auth info */
1170                         status = pipe_auth_verify_final(p);
1171                         if (!NT_STATUS_IS_OK(status)) {
1172                                 DEBUG(0, ("Auth Verify failed (%s)\n",
1173                                           nt_errstr(status)));
1174                                 goto err_exit;
1175                         }
1176                 } else if (NT_STATUS_EQUAL(status,
1177                                         NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1178                         DEBUG(10, ("More auth legs required.\n"));
1179                 } else {
1180                         DEBUG(0, ("Auth step returned an error (%s)\n",
1181                                   nt_errstr(status)));
1182                         goto err_exit;
1183                 }
1184         }
1185
1186         ZERO_STRUCT(u.alter_resp);
1187         u.alter_resp.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1188         u.alter_resp.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1189         u.alter_resp.assoc_group_id = assoc_gid;
1190
1191         /* secondary address CAN be NULL
1192          * as the specs say it's ignored.
1193          * It MUST be NULL to have the spoolss working.
1194          */
1195         u.alter_resp.secondary_address = "";
1196         u.alter_resp.secondary_address_size = 1;
1197
1198         u.alter_resp.num_results = 1;
1199         u.alter_resp.ctx_list = &alter_ack_ctx;
1200
1201         /* NOTE: We leave the auth_info empty so we can calculate the padding
1202          * later and then append the auth_info --simo */
1203
1204         /*
1205          * Marshall directly into the outgoing PDU space. We
1206          * must do this as we need to set to the bind response
1207          * header and are never sending more than one PDU here.
1208          */
1209
1210         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1211                                           DCERPC_PKT_ALTER_RESP,
1212                                           DCERPC_PFC_FLAG_FIRST |
1213                                                 DCERPC_PFC_FLAG_LAST,
1214                                           auth_resp.length,
1215                                           pkt->call_id,
1216                                           &u,
1217                                           &p->out_data.frag);
1218         if (!NT_STATUS_IS_OK(status)) {
1219                 DEBUG(0, ("Failed to marshall alter_resp packet. (%s)\n",
1220                           nt_errstr(status)));
1221                 goto err_exit;
1222         }
1223
1224         if (auth_resp.length) {
1225                 status = dcerpc_push_dcerpc_auth(pkt,
1226                                                  p->auth.auth_type,
1227                                                  p->auth.auth_level,
1228                                                  0, /* pad_len */
1229                                                  p->auth.auth_context_id,
1230                                                  &auth_resp,
1231                                                  &auth_blob);
1232                 if (!NT_STATUS_IS_OK(status)) {
1233                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1234                         goto err_exit;
1235                 }
1236         }
1237
1238         /* Now that we have the auth len store it into the right place in
1239          * the dcerpc header */
1240         dcerpc_set_frag_length(&p->out_data.frag,
1241                                 p->out_data.frag.length +
1242                                 auth_blob.length);
1243
1244         if (auth_resp.length) {
1245                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1246                                         auth_blob.data, auth_blob.length)) {
1247                         DEBUG(0, ("Append of auth info failed.\n"));
1248                         goto err_exit;
1249                 }
1250         }
1251
1252         /*
1253          * Setup the lengths for the initial reply.
1254          */
1255
1256         p->out_data.data_sent_length = 0;
1257         p->out_data.current_pdu_sent = 0;
1258
1259         TALLOC_FREE(auth_blob.data);
1260         return True;
1261
1262   err_exit:
1263
1264         data_blob_free(&p->out_data.frag);
1265         TALLOC_FREE(auth_blob.data);
1266         return setup_bind_nak(p, pkt);
1267 }
1268
1269 static bool api_rpcTNP(struct pipes_struct *p, struct ncacn_packet *pkt,
1270                        const struct api_struct *api_rpc_cmds, int n_cmds,
1271                        const struct ndr_syntax_id *syntax);
1272
1273 static bool srv_pipe_check_verification_trailer(struct pipes_struct *p,
1274                                                 struct ncacn_packet *pkt,
1275                                                 struct pipe_rpc_fns *pipe_fns)
1276 {
1277         TALLOC_CTX *frame = talloc_stackframe();
1278         struct dcerpc_sec_verification_trailer *vt = NULL;
1279         const uint32_t bitmask1 =
1280                 p->auth.client_hdr_signing ? DCERPC_SEC_VT_CLIENT_SUPPORTS_HEADER_SIGNING : 0;
1281         const struct dcerpc_sec_vt_pcontext pcontext = {
1282                 .abstract_syntax = pipe_fns->syntax,
1283                 .transfer_syntax = ndr_transfer_syntax_ndr,
1284         };
1285         const struct dcerpc_sec_vt_header2 header2 =
1286                dcerpc_sec_vt_header2_from_ncacn_packet(pkt);
1287         struct ndr_pull *ndr;
1288         enum ndr_err_code ndr_err;
1289         bool ret = false;
1290
1291         ndr = ndr_pull_init_blob(&p->in_data.data, frame);
1292         if (ndr == NULL) {
1293                 goto done;
1294         }
1295
1296         ndr_err = ndr_pop_dcerpc_sec_verification_trailer(ndr, frame, &vt);
1297         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1298                 goto done;
1299         }
1300
1301         ret = dcerpc_sec_verification_trailer_check(vt, &bitmask1,
1302                                                     &pcontext, &header2);
1303 done:
1304         TALLOC_FREE(frame);
1305         return ret;
1306 }
1307
1308 /****************************************************************************
1309  Find the correct RPC function to call for this request.
1310  If the pipe is authenticated then become the correct UNIX user
1311  before doing the call.
1312 ****************************************************************************/
1313
1314 static bool api_pipe_request(struct pipes_struct *p,
1315                                 struct ncacn_packet *pkt)
1316 {
1317         TALLOC_CTX *frame = talloc_stackframe();
1318         bool ret = False;
1319         struct pipe_rpc_fns *pipe_fns;
1320         const char *interface_name = NULL;
1321
1322         if (!p->pipe_bound) {
1323                 DEBUG(1, ("Pipe not bound!\n"));
1324                 data_blob_free(&p->out_data.rdata);
1325                 TALLOC_FREE(frame);
1326                 return false;
1327         }
1328
1329         /* get the set of RPC functions for this context */
1330         pipe_fns = find_pipe_fns_by_context(p->contexts,
1331                                             pkt->u.request.context_id);
1332         if (pipe_fns == NULL) {
1333                 DEBUG(0, ("No rpc function table associated with context "
1334                           "[%d]\n",
1335                           pkt->u.request.context_id));
1336                 data_blob_free(&p->out_data.rdata);
1337                 TALLOC_FREE(frame);
1338                 return false;
1339         }
1340
1341         interface_name = ndr_interface_name(&pipe_fns->syntax.uuid,
1342                                             pipe_fns->syntax.if_version);
1343         SMB_ASSERT(interface_name != NULL);
1344
1345         switch (p->auth.auth_level) {
1346         case DCERPC_AUTH_LEVEL_NONE:
1347         case DCERPC_AUTH_LEVEL_INTEGRITY:
1348         case DCERPC_AUTH_LEVEL_PRIVACY:
1349                 break;
1350         default:
1351                 if (!pipe_fns->allow_connect) {
1352                         char *addr;
1353
1354                         addr = tsocket_address_string(p->remote_address, frame);
1355
1356                         DEBUG(1, ("%s: restrict auth_level_connect access "
1357                                   "to [%s] with auth[type=0x%x,level=0x%x] "
1358                                   "on [%s] from [%s]\n",
1359                                   __func__, interface_name,
1360                                   p->auth.auth_type,
1361                                   p->auth.auth_level,
1362                                   derpc_transport_string_by_transport(p->transport),
1363                                   addr));
1364
1365                         setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_ACCESS_DENIED));
1366                         TALLOC_FREE(frame);
1367                         return true;
1368                 }
1369                 break;
1370         }
1371
1372         if (!srv_pipe_check_verification_trailer(p, pkt, pipe_fns)) {
1373                 DEBUG(1, ("srv_pipe_check_verification_trailer: failed\n"));
1374                 set_incoming_fault(p);
1375                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_ACCESS_DENIED));
1376                 data_blob_free(&p->out_data.rdata);
1377                 TALLOC_FREE(frame);
1378                 return true;
1379         }
1380
1381         if (!become_authenticated_pipe_user(p->session_info)) {
1382                 DEBUG(1, ("Failed to become pipe user!\n"));
1383                 data_blob_free(&p->out_data.rdata);
1384                 TALLOC_FREE(frame);
1385                 return false;
1386         }
1387
1388         DEBUG(5, ("Requested %s rpc service\n", interface_name));
1389
1390         ret = api_rpcTNP(p, pkt, pipe_fns->cmds, pipe_fns->n_cmds,
1391                          &pipe_fns->syntax);
1392         unbecome_authenticated_pipe_user();
1393
1394         TALLOC_FREE(frame);
1395         return ret;
1396 }
1397
1398 /*******************************************************************
1399  Calls the underlying RPC function for a named pipe.
1400  ********************************************************************/
1401
1402 static bool api_rpcTNP(struct pipes_struct *p, struct ncacn_packet *pkt,
1403                        const struct api_struct *api_rpc_cmds, int n_cmds,
1404                        const struct ndr_syntax_id *syntax)
1405 {
1406         int fn_num;
1407         uint32_t offset1;
1408         const struct ndr_interface_table *table;
1409
1410         /* interpret the command */
1411         DEBUG(4,("api_rpcTNP: %s op 0x%x - ",
1412                  ndr_interface_name(&syntax->uuid, syntax->if_version),
1413                  pkt->u.request.opnum));
1414
1415         table = ndr_table_by_uuid(&syntax->uuid);
1416         if (table == NULL) {
1417                 DEBUG(0,("unknown interface\n"));
1418                 return false;
1419         }
1420
1421         if (DEBUGLEVEL >= 50) {
1422                 fstring name;
1423                 slprintf(name, sizeof(name)-1, "in_%s",
1424                          dcerpc_default_transport_endpoint(pkt, NCACN_NP, table));
1425                 dump_pdu_region(name, pkt->u.request.opnum,
1426                                 &p->in_data.data, 0,
1427                                 p->in_data.data.length);
1428         }
1429
1430         for (fn_num = 0; fn_num < n_cmds; fn_num++) {
1431                 if (api_rpc_cmds[fn_num].opnum == pkt->u.request.opnum &&
1432                     api_rpc_cmds[fn_num].fn != NULL) {
1433                         DEBUG(3, ("api_rpcTNP: rpc command: %s\n",
1434                                   api_rpc_cmds[fn_num].name));
1435                         break;
1436                 }
1437         }
1438
1439         if (fn_num == n_cmds) {
1440                 /*
1441                  * For an unknown RPC just return a fault PDU but
1442                  * return True to allow RPC's on the pipe to continue
1443                  * and not put the pipe into fault state. JRA.
1444                  */
1445                 DEBUG(4, ("unknown\n"));
1446                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1447                 return True;
1448         }
1449
1450         offset1 = p->out_data.rdata.length;
1451
1452         DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", 
1453                 fn_num, api_rpc_cmds[fn_num].fn));
1454         /* do the actual command */
1455         if(!api_rpc_cmds[fn_num].fn(p)) {
1456                 DEBUG(0,("api_rpcTNP: %s: %s failed.\n",
1457                          ndr_interface_name(&syntax->uuid, syntax->if_version),
1458                          api_rpc_cmds[fn_num].name));
1459                 data_blob_free(&p->out_data.rdata);
1460                 return False;
1461         }
1462
1463         if (p->fault_state) {
1464                 DEBUG(4,("api_rpcTNP: fault(%d) return.\n", p->fault_state));
1465                 setup_fault_pdu(p, NT_STATUS(p->fault_state));
1466                 p->fault_state = 0;
1467                 return true;
1468         }
1469
1470         if (DEBUGLEVEL >= 50) {
1471                 fstring name;
1472                 slprintf(name, sizeof(name)-1, "out_%s",
1473                          dcerpc_default_transport_endpoint(pkt, NCACN_NP, table));
1474                 dump_pdu_region(name, pkt->u.request.opnum,
1475                                 &p->out_data.rdata, offset1,
1476                                 p->out_data.rdata.length);
1477         }
1478
1479         DEBUG(5,("api_rpcTNP: called %s successfully\n",
1480                  ndr_interface_name(&syntax->uuid, syntax->if_version)));
1481
1482         /* Check for buffer underflow in rpc parsing */
1483         if ((DEBUGLEVEL >= 10) &&
1484             (pkt->frag_length < p->in_data.data.length)) {
1485                 DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n"));
1486                 dump_data(10, p->in_data.data.data + pkt->frag_length,
1487                               p->in_data.data.length - pkt->frag_length);
1488         }
1489
1490         return True;
1491 }
1492
1493 /****************************************************************************
1494  Initialise an outgoing packet.
1495 ****************************************************************************/
1496
1497 static bool pipe_init_outgoing_data(struct pipes_struct *p)
1498 {
1499         output_data *o_data = &p->out_data;
1500
1501         /* Reset the offset counters. */
1502         o_data->data_sent_length = 0;
1503         o_data->current_pdu_sent = 0;
1504
1505         data_blob_free(&o_data->frag);
1506
1507         /* Free any memory in the current return data buffer. */
1508         data_blob_free(&o_data->rdata);
1509
1510         return True;
1511 }
1512
1513 /****************************************************************************
1514  Sets the fault state on incoming packets.
1515 ****************************************************************************/
1516
1517 void set_incoming_fault(struct pipes_struct *p)
1518 {
1519         data_blob_free(&p->in_data.data);
1520         p->in_data.pdu_needed_len = 0;
1521         p->in_data.pdu.length = 0;
1522         p->fault_state = DCERPC_NCA_S_PROTO_ERROR;
1523
1524         p->allow_alter = false;
1525         p->allow_auth3 = false;
1526         p->pipe_bound = false;
1527
1528         DEBUG(10, ("Setting fault state\n"));
1529 }
1530
1531 static NTSTATUS dcesrv_auth_request(struct pipe_auth_data *auth,
1532                                     struct ncacn_packet *pkt,
1533                                     DATA_BLOB *raw_pkt)
1534 {
1535         NTSTATUS status;
1536         size_t hdr_size = DCERPC_REQUEST_LENGTH;
1537
1538         DEBUG(10, ("Checking request auth.\n"));
1539
1540         if (pkt->pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
1541                 hdr_size += 16;
1542         }
1543
1544         /* in case of sealing this function will unseal the data in place */
1545         status = dcerpc_check_auth(auth, pkt,
1546                                    &pkt->u.request.stub_and_verifier,
1547                                    hdr_size, raw_pkt);
1548         if (!NT_STATUS_IS_OK(status)) {
1549                 return status;
1550         }
1551
1552         return NT_STATUS_OK;
1553 }
1554
1555 /****************************************************************************
1556  Processes a request pdu. This will do auth processing if needed, and
1557  appends the data into the complete stream if the LAST flag is not set.
1558 ****************************************************************************/
1559
1560 static bool process_request_pdu(struct pipes_struct *p, struct ncacn_packet *pkt)
1561 {
1562         NTSTATUS status;
1563         DATA_BLOB data;
1564         struct dcerpc_sec_vt_header2 hdr2;
1565
1566         if (!p->pipe_bound) {
1567                 DEBUG(0,("process_request_pdu: rpc request with no bind.\n"));
1568                 set_incoming_fault(p);
1569                 return False;
1570         }
1571
1572         /*
1573          * We don't ignore DCERPC_PFC_FLAG_PENDING_CANCEL.
1574          * TODO: we can reject it with DCERPC_FAULT_NO_CALL_ACTIVE later.
1575          */
1576         status = dcerpc_verify_ncacn_packet_header(pkt,
1577                         DCERPC_PKT_REQUEST,
1578                         pkt->u.request.stub_and_verifier.length,
1579                         0, /* required_flags */
1580                         DCERPC_PFC_FLAG_FIRST |
1581                         DCERPC_PFC_FLAG_LAST |
1582                         0x08 | /* this is not defined, but should be ignored */
1583                         DCERPC_PFC_FLAG_CONC_MPX |
1584                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1585                         DCERPC_PFC_FLAG_MAYBE |
1586                         DCERPC_PFC_FLAG_OBJECT_UUID);
1587         if (!NT_STATUS_IS_OK(status)) {
1588                 DEBUG(1, ("process_request_pdu: invalid pdu: %s\n",
1589                           nt_errstr(status)));
1590                 NDR_PRINT_DEBUG(ncacn_packet, pkt);
1591                 set_incoming_fault(p);
1592                 return false;
1593         }
1594
1595         hdr2 = dcerpc_sec_vt_header2_from_ncacn_packet(pkt);
1596         if (pkt->pfc_flags & DCERPC_PFC_FLAG_FIRST) {
1597                 p->header2 = hdr2;
1598         } else {
1599                 if (!dcerpc_sec_vt_header2_equal(&hdr2, &p->header2)) {
1600                         set_incoming_fault(p);
1601                         return false;
1602                 }
1603         }
1604
1605         /* Store the opnum */
1606         p->opnum = pkt->u.request.opnum;
1607
1608         status = dcesrv_auth_request(&p->auth, pkt, &p->in_data.pdu);
1609         if (!NT_STATUS_IS_OK(status)) {
1610                 DEBUG(0, ("Failed to check packet auth. (%s)\n",
1611                           nt_errstr(status)));
1612                 set_incoming_fault(p);
1613                 return false;
1614         }
1615
1616         data = pkt->u.request.stub_and_verifier;
1617
1618         /*
1619          * Check the data length doesn't go over the 15Mb limit.
1620          * increased after observing a bug in the Windows NT 4.0 SP6a
1621          * spoolsv.exe when the response to a GETPRINTERDRIVER2 RPC
1622          * will not fit in the initial buffer of size 0x1068   --jerry 22/01/2002
1623          */
1624
1625         if (p->in_data.data.length + data.length > MAX_RPC_DATA_SIZE) {
1626                 DEBUG(0, ("process_request_pdu: "
1627                           "rpc data buffer too large (%u) + (%u)\n",
1628                           (unsigned int)p->in_data.data.length,
1629                           (unsigned int)data.length));
1630                 set_incoming_fault(p);
1631                 return False;
1632         }
1633
1634         /*
1635          * Append the data portion into the buffer and return.
1636          */
1637
1638         if (data.length) {
1639                 if (!data_blob_append(p->mem_ctx, &p->in_data.data,
1640                                           data.data, data.length)) {
1641                         DEBUG(0, ("Unable to append data size %u "
1642                                   "to parse buffer of size %u.\n",
1643                                   (unsigned int)data.length,
1644                                   (unsigned int)p->in_data.data.length));
1645                         set_incoming_fault(p);
1646                         return False;
1647                 }
1648         }
1649
1650         if (!(pkt->pfc_flags & DCERPC_PFC_FLAG_LAST)) {
1651                 return true;
1652         }
1653
1654         /*
1655          * Ok - we finally have a complete RPC stream.
1656          * Call the rpc command to process it.
1657          */
1658
1659         return api_pipe_request(p, pkt);
1660 }
1661
1662 void process_complete_pdu(struct pipes_struct *p, struct ncacn_packet *pkt)
1663 {
1664         bool reply = false;
1665
1666         /* Store the call_id */
1667         p->call_id = pkt->call_id;
1668
1669         DEBUG(10, ("Processing packet type %u\n", (unsigned int)pkt->ptype));
1670
1671         if (!pipe_init_outgoing_data(p)) {
1672                 goto done;
1673         }
1674
1675         switch (pkt->ptype) {
1676         case DCERPC_PKT_REQUEST:
1677                 reply = process_request_pdu(p, pkt);
1678                 break;
1679
1680         case DCERPC_PKT_PING: /* CL request - ignore... */
1681                 DEBUG(0, ("Error - Connectionless packet type %u received\n",
1682                           (unsigned int)pkt->ptype));
1683                 break;
1684
1685         case DCERPC_PKT_RESPONSE: /* No responses here. */
1686                 DEBUG(0, ("Error - DCERPC_PKT_RESPONSE received from client"));
1687                 break;
1688
1689         case DCERPC_PKT_FAULT:
1690         case DCERPC_PKT_WORKING:
1691                 /* CL request - reply to a ping when a call in process. */
1692         case DCERPC_PKT_NOCALL:
1693                 /* CL - server reply to a ping call. */
1694         case DCERPC_PKT_REJECT:
1695         case DCERPC_PKT_ACK:
1696         case DCERPC_PKT_CL_CANCEL:
1697         case DCERPC_PKT_FACK:
1698         case DCERPC_PKT_CANCEL_ACK:
1699                 DEBUG(0, ("Error - Connectionless packet type %u received\n",
1700                           (unsigned int)pkt->ptype));
1701                 break;
1702
1703         case DCERPC_PKT_BIND:
1704                 /*
1705                  * We assume that a pipe bind is only in one pdu.
1706                  */
1707                 reply = api_pipe_bind_req(p, pkt);
1708                 break;
1709
1710         case DCERPC_PKT_BIND_ACK:
1711         case DCERPC_PKT_BIND_NAK:
1712                 DEBUG(0, ("Error - DCERPC_PKT_BINDACK/DCERPC_PKT_BINDNACK "
1713                           "packet type %u received.\n",
1714                           (unsigned int)pkt->ptype));
1715                 break;
1716
1717
1718         case DCERPC_PKT_ALTER:
1719                 /*
1720                  * We assume that a pipe bind is only in one pdu.
1721                  */
1722                 reply = api_pipe_alter_context(p, pkt);
1723                 break;
1724
1725         case DCERPC_PKT_ALTER_RESP:
1726                 DEBUG(0, ("Error - DCERPC_PKT_ALTER_RESP received: "
1727                           "Should only be server -> client.\n"));
1728                 break;
1729
1730         case DCERPC_PKT_AUTH3:
1731                 /*
1732                  * The third packet in an auth exchange.
1733                  */
1734                 reply = api_pipe_bind_auth3(p, pkt);
1735                 break;
1736
1737         case DCERPC_PKT_SHUTDOWN:
1738                 DEBUG(0, ("Error - DCERPC_PKT_SHUTDOWN received: "
1739                           "Should only be server -> client.\n"));
1740                 break;
1741
1742         case DCERPC_PKT_CO_CANCEL:
1743                 /* For now just free all client data and continue
1744                  * processing. */
1745                 DEBUG(3,("process_complete_pdu: DCERPC_PKT_CO_CANCEL."
1746                          " Abandoning rpc call.\n"));
1747                 /* As we never do asynchronous RPC serving, we can
1748                  * never cancel a call (as far as I know).
1749                  * If we ever did we'd have to send a cancel_ack reply.
1750                  * For now, just free all client data and continue
1751                  * processing. */
1752                 reply = True;
1753                 break;
1754
1755 #if 0
1756                 /* Enable this if we're doing async rpc. */
1757                 /* We must check the outstanding callid matches. */
1758                 if (pipe_init_outgoing_data(p)) {
1759                         /* Send a cancel_ack PDU reply. */
1760                         /* We should probably check the auth-verifier here. */
1761                         reply = setup_cancel_ack_reply(p, pkt);
1762                 }
1763                 break;
1764 #endif
1765
1766         case DCERPC_PKT_ORPHANED:
1767                 /* We should probably check the auth-verifier here.
1768                  * For now just free all client data and continue
1769                  * processing. */
1770                 DEBUG(3, ("process_complete_pdu: DCERPC_PKT_ORPHANED."
1771                           " Abandoning rpc call.\n"));
1772                 reply = True;
1773                 break;
1774
1775         default:
1776                 DEBUG(0, ("process_complete_pdu: "
1777                           "Unknown rpc type = %u received.\n",
1778                           (unsigned int)pkt->ptype));
1779                 break;
1780         }
1781
1782 done:
1783         if (!reply) {
1784                 DEBUG(3,("DCE/RPC fault sent!"));
1785                 set_incoming_fault(p);
1786                 setup_fault_pdu(p, NT_STATUS(DCERPC_NCA_S_PROTO_ERROR));
1787         }
1788         /* pkt and p->in_data.pdu.data freed by caller */
1789 }
1790