a56a6345cc4716dd14bfecd7e301cb154a7cdb68
[abartlet/samba.git/.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 "srv_pipe_internal.h"
32 #include "../librpc/gen_ndr/ndr_schannel.h"
33 #include "../libcli/auth/schannel.h"
34 #include "../libcli/auth/spnego.h"
35 #include "../libcli/auth/ntlmssp.h"
36 #include "rpc_server.h"
37
38 #undef DBGC_CLASS
39 #define DBGC_CLASS DBGC_RPC_SRV
40
41 /**
42  * Dump everything from the start of the end up of the provided data
43  * into a file, but only at debug level >= 50
44  **/
45 static void dump_pdu_region(const char *name, int v,
46                             DATA_BLOB *data, size_t start, size_t end)
47 {
48         int fd, i;
49         char *fname = NULL;
50         ssize_t sz;
51
52         if (DEBUGLEVEL < 50) return;
53
54         if (start > data->length || end > data->length || start > end) return;
55
56         for (i = 1; i < 100; i++) {
57                 if (v != -1) {
58                         fname = talloc_asprintf(talloc_tos(),
59                                                 "/tmp/%s_%d.%d.prs",
60                                                 name, v, i);
61                 } else {
62                         fname = talloc_asprintf(talloc_tos(),
63                                                 "/tmp/%s_%d.prs",
64                                                 name, i);
65                 }
66                 if (!fname) {
67                         return;
68                 }
69                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
70                 if (fd != -1 || errno != EEXIST) break;
71         }
72         if (fd != -1) {
73                 sz = write(fd, data->data + start, end - start);
74                 i = close(fd);
75                 if ((sz != end - start) || (i != 0) ) {
76                         DEBUG(0, ("Error writing/closing %s: %ld!=%ld %d\n",
77                                   fname, (unsigned long)sz,
78                                   (unsigned long)end - start, i));
79                 } else {
80                         DEBUG(0,("created %s\n", fname));
81                 }
82         }
83         TALLOC_FREE(fname);
84 }
85
86 static void free_pipe_ntlmssp_auth_data(struct pipe_auth_data *auth)
87 {
88         TALLOC_FREE(auth->a_u.auth_ntlmssp_state);
89 }
90
91 static DATA_BLOB generic_session_key(void)
92 {
93         return data_blob("SystemLibraryDTC", 16);
94 }
95
96 /*******************************************************************
97  Handle NTLMSSP.
98  ********************************************************************/
99
100 static bool add_ntlmssp_auth(pipes_struct *p)
101 {
102         enum dcerpc_AuthLevel auth_level = p->auth.auth_level;
103         DATA_BLOB auth_blob = data_blob_null;
104         NTSTATUS status;
105
106         /* FIXME: Is this right ?
107          * Keeping only to avoid changing semantics during refactoring
108          * --simo
109          */
110         if (auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
111                 auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
112         }
113
114         /* Generate the auth blob. */
115         switch (auth_level) {
116         case DCERPC_AUTH_LEVEL_PRIVACY:
117                 /* Data portion is encrypted. */
118                 status = auth_ntlmssp_seal_packet(
119                                 p->auth.a_u.auth_ntlmssp_state,
120                                 (TALLOC_CTX *)p->out_data.frag.data,
121                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
122                                 p->out_data.frag.length
123                                         - DCERPC_RESPONSE_LENGTH
124                                         - DCERPC_AUTH_TRAILER_LENGTH,
125                                 p->out_data.frag.data,
126                                 p->out_data.frag.length,
127                                 &auth_blob);
128                 break;
129
130         case DCERPC_AUTH_LEVEL_INTEGRITY:
131                 /* Data is signed. */
132                 status = auth_ntlmssp_sign_packet(
133                                 p->auth.a_u.auth_ntlmssp_state,
134                                 (TALLOC_CTX *)p->out_data.frag.data,
135                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
136                                 p->out_data.frag.length
137                                         - DCERPC_RESPONSE_LENGTH
138                                         - DCERPC_AUTH_TRAILER_LENGTH,
139                                 p->out_data.frag.data,
140                                 p->out_data.frag.length,
141                                 &auth_blob);
142                 break;
143
144         default:
145                 status = NT_STATUS_INTERNAL_ERROR;
146                 return false;
147         }
148
149         if (!NT_STATUS_IS_OK(status)) {
150                 DEBUG(0, ("Failed to add NTLMSSP auth blob: %s\n",
151                         nt_errstr(status)));
152                 data_blob_free(&p->out_data.frag);
153                 return false;
154         }
155
156         /* Finally append the auth blob. */
157         if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
158                                 auth_blob.data, auth_blob.length)) {
159                 DEBUG(0, ("Failed to add %u bytes auth blob.\n",
160                           (unsigned int)auth_blob.length));
161                 data_blob_free(&p->out_data.frag);
162                 return False;
163         }
164         data_blob_free(&auth_blob);
165
166         return true;
167 }
168
169 /*******************************************************************
170  Append a schannel authenticated fragment.
171  ********************************************************************/
172
173 static bool add_schannel_auth(pipes_struct *p)
174 {
175         DATA_BLOB auth_blob = data_blob_null;
176         NTSTATUS status;
177
178         /* Schannel processing. */
179         switch (p->auth.auth_level) {
180         case DCERPC_AUTH_LEVEL_PRIVACY:
181                 status = netsec_outgoing_packet(
182                                 p->auth.a_u.schannel_auth,
183                                 (TALLOC_CTX *)p->out_data.frag.data,
184                                 true,
185                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
186                                 p->out_data.frag.length
187                                         - DCERPC_RESPONSE_LENGTH
188                                         - DCERPC_AUTH_TRAILER_LENGTH,
189                                 &auth_blob);
190                 break;
191
192         case DCERPC_AUTH_LEVEL_INTEGRITY:
193                 status = netsec_outgoing_packet(
194                                 p->auth.a_u.schannel_auth,
195                                 (TALLOC_CTX *)p->out_data.frag.data,
196                                 false,
197                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
198                                 p->out_data.frag.length
199                                         - DCERPC_RESPONSE_LENGTH
200                                         - DCERPC_AUTH_TRAILER_LENGTH,
201                                 &auth_blob);
202                 break;
203
204         default:
205                 status = NT_STATUS_INTERNAL_ERROR;
206                 break;
207         }
208
209         if (!NT_STATUS_IS_OK(status)) {
210                 DEBUG(0, ("Failed to add SCHANNEL auth blob: %s\n",
211                         nt_errstr(status)));
212                 data_blob_free(&p->out_data.frag);
213                 return false;
214         }
215
216         if (DEBUGLEVEL >= 10) {
217                 dump_NL_AUTH_SIGNATURE(talloc_tos(), &auth_blob);
218         }
219
220         if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
221                                 auth_blob.data, auth_blob.length)) {
222                 DEBUG(0, ("Failed to add %u bytes auth blob.\n",
223                           (unsigned int)auth_blob.length));
224                 data_blob_free(&p->out_data.frag);
225                 return false;
226         }
227         data_blob_free(&auth_blob);
228
229         return true;
230 }
231
232 /*******************************************************************
233  Generate the next PDU to be returned from the data.
234 ********************************************************************/
235
236 static bool create_next_packet(pipes_struct *p,
237                                 enum dcerpc_AuthType auth_type,
238                                 enum dcerpc_AuthLevel auth_level,
239                                 size_t auth_length)
240 {
241         union dcerpc_payload u;
242         uint8_t pfc_flags;
243         size_t data_len_left;
244         size_t data_len;
245         size_t max_len;
246         size_t pad_len = 0;
247         NTSTATUS status;
248
249         ZERO_STRUCT(u.response);
250
251         /* Set up rpc packet pfc flags. */
252         if (p->out_data.data_sent_length == 0) {
253                 pfc_flags = DCERPC_PFC_FLAG_FIRST;
254         } else {
255                 pfc_flags = 0;
256         }
257
258         /* Work out how much we can fit in a single PDU. */
259         data_len_left = p->out_data.rdata.length -
260                                 p->out_data.data_sent_length;
261
262         /* Ensure there really is data left to send. */
263         if (!data_len_left) {
264                 DEBUG(0, ("No data left to send !\n"));
265                 return false;
266         }
267
268         /* Max space available - not including padding. */
269         if (auth_length) {
270                 max_len = RPC_MAX_PDU_FRAG_LEN
271                                 - DCERPC_RESPONSE_LENGTH
272                                 - DCERPC_AUTH_TRAILER_LENGTH
273                                 - auth_length;
274         } else {
275                 max_len = RPC_MAX_PDU_FRAG_LEN - DCERPC_RESPONSE_LENGTH;
276         }
277
278         /*
279          * The amount we send is the minimum of the max_len
280          * and the amount left to send.
281          */
282         data_len = MIN(data_len_left, max_len);
283
284         if (auth_length) {
285                 /* Work out any padding alignment requirements. */
286                 pad_len = (DCERPC_RESPONSE_LENGTH + data_len) %
287                                                 SERVER_NDR_PADDING_SIZE;
288                 if (pad_len) {
289                         pad_len = SERVER_NDR_PADDING_SIZE - pad_len;
290                         DEBUG(10, ("Padding size is: %d\n", (int)pad_len));
291                         /* If we're over filling the packet, we need to make
292                          * space for the padding at the end of the data. */
293                         if (data_len + pad_len > max_len) {
294                                 data_len -= SERVER_NDR_PADDING_SIZE;
295                         }
296                 }
297         }
298
299         /* Set up the alloc hint. This should be the data left to send. */
300         u.response.alloc_hint = data_len_left;
301
302         /* Work out if this PDU will be the last. */
303         if (p->out_data.data_sent_length
304                                 + data_len >= p->out_data.rdata.length) {
305                 pfc_flags |= DCERPC_PFC_FLAG_LAST;
306         }
307
308         /* Prepare data to be NDR encoded. */
309         u.response.stub_and_verifier =
310                 data_blob_const(p->out_data.rdata.data +
311                                 p->out_data.data_sent_length, data_len);
312
313         /* Store the packet in the data stream. */
314         status = dcerpc_push_ncacn_packet(p->mem_ctx,
315                                           DCERPC_PKT_RESPONSE,
316                                           pfc_flags,
317                                           auth_length,
318                                           p->call_id,
319                                           &u,
320                                           &p->out_data.frag);
321         if (!NT_STATUS_IS_OK(status)) {
322                 DEBUG(0, ("Failed to marshall RPC Packet.\n"));
323                 return false;
324         }
325
326         if (auth_length) {
327                 DATA_BLOB empty = data_blob_null;
328                 DATA_BLOB auth_hdr;
329
330                 /* Set the proper length on the pdu, including padding.
331                  * Only needed if an auth trailer will be appended. */
332                 dcerpc_set_frag_length(&p->out_data.frag,
333                                         p->out_data.frag.length
334                                                 + pad_len
335                                                 + DCERPC_AUTH_TRAILER_LENGTH
336                                                 + auth_length);
337
338                 if (pad_len) {
339                         size_t offset = p->out_data.frag.length;
340
341                         if (!data_blob_realloc(p->mem_ctx,
342                                                 &p->out_data.frag,
343                                                 offset + pad_len)) {
344                                 DEBUG(0, ("Failed to add padding!\n"));
345                                 data_blob_free(&p->out_data.frag);
346                                 return false;
347                         }
348                         memset(&p->out_data.frag.data[offset], '\0', pad_len);
349                 }
350
351                 /* auth blob is intentionally empty,
352                  * it will be appended later */
353                 status = dcerpc_push_dcerpc_auth(p->out_data.frag.data,
354                                                  auth_type,
355                                                  auth_level,
356                                                  pad_len,
357                                                  1, /* context id. */
358                                                  &empty,
359                                                  &auth_hdr);
360                 if (!NT_STATUS_IS_OK(status)) {
361                         DEBUG(0, ("Failed to marshall RPC Auth.\n"));
362                         return false;
363                 }
364
365                 /* Store auth header in the data stream. */
366                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
367                                         auth_hdr.data, auth_hdr.length)) {
368                         DEBUG(0, ("Out of memory.\n"));
369                         data_blob_free(&p->out_data.frag);
370                         return false;
371                 }
372                 data_blob_free(&auth_hdr);
373         }
374
375         /* Setup the counts for this PDU. */
376         p->out_data.data_sent_length += data_len;
377         p->out_data.current_pdu_sent = 0;
378         return true;
379 }
380
381 /*******************************************************************
382  Generate the next PDU to be returned from the data in p->rdata. 
383 ********************************************************************/
384
385 bool create_next_pdu(pipes_struct *p)
386 {
387         enum dcerpc_AuthType auth_type =
388                 map_pipe_auth_type_to_rpc_auth_type(p->auth.auth_type);
389
390         /*
391          * If we're in the fault state, keep returning fault PDU's until
392          * the pipe gets closed. JRA.
393          */
394         if (p->fault_state) {
395                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
396                 return true;
397         }
398
399         switch (p->auth.auth_level) {
400         case DCERPC_AUTH_LEVEL_NONE:
401         case DCERPC_AUTH_LEVEL_CONNECT:
402                 /* This is incorrect for auth level connect. Fixme. JRA */
403
404                 /* No authentication done. */
405                 return create_next_packet(p, auth_type,
406                                           p->auth.auth_level, 0);
407
408         case DCERPC_AUTH_LEVEL_CALL:
409         case DCERPC_AUTH_LEVEL_PACKET:
410         case DCERPC_AUTH_LEVEL_INTEGRITY:
411         case DCERPC_AUTH_LEVEL_PRIVACY:
412
413                 switch(p->auth.auth_type) {
414                 case PIPE_AUTH_TYPE_NTLMSSP:
415                 case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
416                         if (!create_next_packet(p, auth_type,
417                                                 p->auth.auth_level,
418                                                 NTLMSSP_SIG_SIZE)) {
419                                 return false;
420                         }
421                         return add_ntlmssp_auth(p);
422
423                 case PIPE_AUTH_TYPE_SCHANNEL:
424                         if (!create_next_packet(p, auth_type,
425                                                 p->auth.auth_level,
426                                                 NL_AUTH_SIGNATURE_SIZE)) {
427                                 return false;
428                         }
429                         return add_schannel_auth(p);
430                 default:
431                         break;
432                 }
433         default:
434                 break;
435         }
436
437         DEBUG(0, ("Invalid internal auth level %u / type %u\n",
438                   (unsigned int)p->auth.auth_level,
439                   (unsigned int)p->auth.auth_type));
440         return false;
441 }
442
443 /*******************************************************************
444  Process an NTLMSSP authentication response.
445  If this function succeeds, the user has been authenticated
446  and their domain, name and calling workstation stored in
447  the pipe struct.
448 *******************************************************************/
449
450 static bool pipe_ntlmssp_verify_final(pipes_struct *p, DATA_BLOB *p_resp_blob)
451 {
452         DATA_BLOB session_key, reply;
453         NTSTATUS status;
454         struct auth_ntlmssp_state *a = p->auth.a_u.auth_ntlmssp_state;
455         bool ret;
456
457         DEBUG(5,("pipe_ntlmssp_verify_final: pipe %s checking user details\n",
458                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
459
460         ZERO_STRUCT(reply);
461
462         /* this has to be done as root in order to verify the password */
463         become_root();
464         status = auth_ntlmssp_update(a, *p_resp_blob, &reply);
465         unbecome_root();
466
467         /* Don't generate a reply. */
468         data_blob_free(&reply);
469
470         if (!NT_STATUS_IS_OK(status)) {
471                 return False;
472         }
473
474         /* Finally - if the pipe negotiated integrity (sign) or privacy (seal)
475            ensure the underlying NTLMSSP flags are also set. If not we should
476            refuse the bind. */
477
478         if (p->auth.auth_level == DCERPC_AUTH_LEVEL_INTEGRITY) {
479                 if (!auth_ntlmssp_negotiated_sign(a)) {
480                         DEBUG(0,("pipe_ntlmssp_verify_final: pipe %s : packet integrity requested "
481                                 "but client declined signing.\n",
482                                  get_pipe_name_from_syntax(talloc_tos(),
483                                                            &p->syntax)));
484                         return False;
485                 }
486         }
487         if (p->auth.auth_level == DCERPC_AUTH_LEVEL_PRIVACY) {
488                 if (!auth_ntlmssp_negotiated_seal(a)) {
489                         DEBUG(0,("pipe_ntlmssp_verify_final: pipe %s : packet privacy requested "
490                                 "but client declined sealing.\n",
491                                  get_pipe_name_from_syntax(talloc_tos(),
492                                                            &p->syntax)));
493                         return False;
494                 }
495         }
496
497         DEBUG(5, ("pipe_ntlmssp_verify_final: OK: user: %s domain: %s "
498                   "workstation: %s\n",
499                   auth_ntlmssp_get_username(a),
500                   auth_ntlmssp_get_domain(a),
501                   auth_ntlmssp_get_client(a)));
502
503         TALLOC_FREE(p->server_info);
504
505         status = auth_ntlmssp_server_info(p, a, &p->server_info);
506         if (!NT_STATUS_IS_OK(status)) {
507                 DEBUG(0, ("auth_ntlmssp_server_info failed to obtain the server info for authenticated user: %s\n",
508                           nt_errstr(status)));
509                 return false;
510         }
511
512         if (p->server_info->ptok == NULL) {
513                 DEBUG(1,("Error: Authmodule failed to provide nt_user_token\n"));
514                 return False;
515         }
516
517         /*
518          * We're an authenticated bind over smb, so the session key needs to
519          * be set to "SystemLibraryDTC". Weird, but this is what Windows
520          * does. See the RPC-SAMBA3SESSIONKEY.
521          */
522
523         session_key = generic_session_key();
524         if (session_key.data == NULL) {
525                 return False;
526         }
527
528         ret = server_info_set_session_key(p->server_info, session_key);
529
530         data_blob_free(&session_key);
531
532         return True;
533 }
534
535 /*******************************************************************
536  This is the "stage3" NTLMSSP response after a bind request and reply.
537 *******************************************************************/
538
539 bool api_pipe_bind_auth3(pipes_struct *p, struct ncacn_packet *pkt)
540 {
541         struct dcerpc_auth auth_info;
542         NTSTATUS status;
543
544         DEBUG(5, ("api_pipe_bind_auth3: decode request. %d\n", __LINE__));
545
546         if (pkt->auth_length == 0) {
547                 DEBUG(0, ("No auth field sent for bind request!\n"));
548                 goto err;
549         }
550
551         /* Ensure there's enough data for an authenticated request. */
552         if (pkt->frag_length < RPC_HEADER_LEN
553                                 + DCERPC_AUTH_TRAILER_LENGTH
554                                 + pkt->auth_length) {
555                         DEBUG(0,("api_pipe_ntlmssp_auth_process: auth_len "
556                                 "%u is too large.\n",
557                         (unsigned int)pkt->auth_length));
558                 goto err;
559         }
560
561         /*
562          * Decode the authentication verifier response.
563          */
564
565         status = dcerpc_pull_dcerpc_auth(pkt,
566                                          &pkt->u.auth3.auth_info,
567                                          &auth_info, p->endian);
568         if (!NT_STATUS_IS_OK(status)) {
569                 DEBUG(0, ("Failed to unmarshall dcerpc_auth.\n"));
570                 goto err;
571         }
572
573         /* We must NEVER look at auth_info->auth_pad_len here,
574          * as old Samba client code gets it wrong and sends it
575          * as zero. JRA.
576          */
577
578         if (auth_info.auth_type != DCERPC_AUTH_TYPE_NTLMSSP) {
579                 DEBUG(0,("api_pipe_bind_auth3: incorrect auth type (%u).\n",
580                         (unsigned int)auth_info.auth_type ));
581                 return False;
582         }
583
584         /*
585          * The following call actually checks the challenge/response data.
586          * for correctness against the given DOMAIN\user name.
587          */
588
589         if (!pipe_ntlmssp_verify_final(p, &auth_info.credentials)) {
590                 goto err;
591         }
592
593         p->pipe_bound = True;
594
595         return True;
596
597  err:
598
599         free_pipe_ntlmssp_auth_data(&p->auth);
600         p->auth.a_u.auth_ntlmssp_state = NULL;
601
602         return False;
603 }
604
605 /*******************************************************************
606  Marshall a bind_nak pdu.
607 *******************************************************************/
608
609 static bool setup_bind_nak(pipes_struct *p, struct ncacn_packet *pkt)
610 {
611         NTSTATUS status;
612         union dcerpc_payload u;
613
614         /* Free any memory in the current return data buffer. */
615         data_blob_free(&p->out_data.rdata);
616
617         /*
618          * Initialize a bind_nak header.
619          */
620
621         ZERO_STRUCT(u);
622
623         u.bind_nak.reject_reason  = 0;
624
625         /*
626          * Marshall directly into the outgoing PDU space. We
627          * must do this as we need to set to the bind response
628          * header and are never sending more than one PDU here.
629          */
630
631         status = dcerpc_push_ncacn_packet(p->mem_ctx,
632                                           DCERPC_PKT_BIND_NAK,
633                                           DCERPC_PFC_FLAG_FIRST |
634                                                 DCERPC_PFC_FLAG_LAST,
635                                           0,
636                                           pkt->call_id,
637                                           &u,
638                                           &p->out_data.frag);
639         if (!NT_STATUS_IS_OK(status)) {
640                 return False;
641         }
642
643         p->out_data.data_sent_length = 0;
644         p->out_data.current_pdu_sent = 0;
645
646         if (p->auth.auth_data_free_func) {
647                 (*p->auth.auth_data_free_func)(&p->auth);
648         }
649         p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
650         p->auth.auth_type = PIPE_AUTH_TYPE_NONE;
651         p->pipe_bound = False;
652
653         return True;
654 }
655
656 /*******************************************************************
657  Marshall a fault pdu.
658 *******************************************************************/
659
660 bool setup_fault_pdu(pipes_struct *p, NTSTATUS fault_status)
661 {
662         NTSTATUS status;
663         union dcerpc_payload u;
664
665         /* Free any memory in the current return data buffer. */
666         data_blob_free(&p->out_data.rdata);
667
668         /*
669          * Initialize a fault header.
670          */
671
672         ZERO_STRUCT(u);
673
674         u.fault.status          = NT_STATUS_V(fault_status);
675         u.fault._pad            = data_blob_talloc_zero(p->mem_ctx, 4);
676
677         /*
678          * Marshall directly into the outgoing PDU space. We
679          * must do this as we need to set to the bind response
680          * header and are never sending more than one PDU here.
681          */
682
683         status = dcerpc_push_ncacn_packet(p->mem_ctx,
684                                           DCERPC_PKT_FAULT,
685                                           DCERPC_PFC_FLAG_FIRST |
686                                            DCERPC_PFC_FLAG_LAST |
687                                            DCERPC_PFC_FLAG_DID_NOT_EXECUTE,
688                                           0,
689                                           p->call_id,
690                                           &u,
691                                           &p->out_data.frag);
692         if (!NT_STATUS_IS_OK(status)) {
693                 return False;
694         }
695
696         p->out_data.data_sent_length = 0;
697         p->out_data.current_pdu_sent = 0;
698
699         return True;
700 }
701
702 /*******************************************************************
703  Ensure a bind request has the correct abstract & transfer interface.
704  Used to reject unknown binds from Win2k.
705 *******************************************************************/
706
707 static bool check_bind_req(struct pipes_struct *p,
708                            struct ndr_syntax_id* abstract,
709                            struct ndr_syntax_id* transfer,
710                            uint32 context_id)
711 {
712         struct pipe_rpc_fns *context_fns;
713
714         DEBUG(3,("check_bind_req for %s\n",
715                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
716
717         /* we have to check all now since win2k introduced a new UUID on the lsaprpc pipe */
718         if (rpc_srv_pipe_exists_by_id(abstract) &&
719            ndr_syntax_id_equal(transfer, &ndr_transfer_syntax)) {
720                 DEBUG(3, ("check_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
721                         rpc_srv_get_pipe_cli_name(abstract),
722                         rpc_srv_get_pipe_srv_name(abstract)));
723         } else {
724                 return false;
725         }
726
727         context_fns = SMB_MALLOC_P(struct pipe_rpc_fns);
728         if (context_fns == NULL) {
729                 DEBUG(0,("check_bind_req: malloc() failed!\n"));
730                 return False;
731         }
732
733         context_fns->n_cmds = rpc_srv_get_pipe_num_cmds(abstract);
734         context_fns->cmds = rpc_srv_get_pipe_cmds(abstract);
735         context_fns->context_id = context_id;
736
737         /* add to the list of open contexts */
738
739         DLIST_ADD( p->contexts, context_fns );
740
741         return True;
742 }
743
744 /**
745  * Is a named pipe known?
746  * @param[in] cli_filename      The pipe name requested by the client
747  * @result                      Do we want to serve this?
748  */
749 bool is_known_pipename(const char *cli_filename, struct ndr_syntax_id *syntax)
750 {
751         const char *pipename = cli_filename;
752         NTSTATUS status;
753
754         if (strnequal(pipename, "\\PIPE\\", 6)) {
755                 pipename += 5;
756         }
757
758         if (*pipename == '\\') {
759                 pipename += 1;
760         }
761
762         if (lp_disable_spoolss() && strequal(pipename, "spoolss")) {
763                 DEBUG(10, ("refusing spoolss access\n"));
764                 return false;
765         }
766
767         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
768                 return true;
769         }
770
771         status = smb_probe_module("rpc", pipename);
772         if (!NT_STATUS_IS_OK(status)) {
773                 DEBUG(10, ("is_known_pipename: %s unknown\n", cli_filename));
774                 return false;
775         }
776         DEBUG(10, ("is_known_pipename: %s loaded dynamically\n", pipename));
777
778         /*
779          * Scan the list again for the interface id
780          */
781         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
782                 return true;
783         }
784
785         DEBUG(10, ("is_known_pipename: pipe %s did not register itself!\n",
786                    pipename));
787
788         return false;
789 }
790
791 /*******************************************************************
792  Handle a SPNEGO krb5 bind auth.
793 *******************************************************************/
794
795 static bool pipe_spnego_auth_bind_kerberos(pipes_struct *p,
796                                            TALLOC_CTX *mem_ctx,
797                                            struct dcerpc_auth *pauth_info,
798                                            DATA_BLOB *psecblob,
799                                            DATA_BLOB *response)
800 {
801         return False;
802 }
803
804 /*******************************************************************
805  Handle the first part of a SPNEGO bind auth.
806 *******************************************************************/
807
808 static bool pipe_spnego_auth_bind_negotiate(pipes_struct *p,
809                                             TALLOC_CTX *mem_ctx,
810                                             struct dcerpc_auth *pauth_info,
811                                             DATA_BLOB *response)
812 {
813         DATA_BLOB secblob;
814         DATA_BLOB chal;
815         char *OIDs[ASN1_MAX_OIDS];
816         int i;
817         NTSTATUS status;
818         bool got_kerberos_mechanism = false;
819         struct auth_ntlmssp_state *a = NULL;
820
821         ZERO_STRUCT(secblob);
822         ZERO_STRUCT(chal);
823
824         if (pauth_info->credentials.data[0] != ASN1_APPLICATION(0)) {
825                 goto err;
826         }
827
828         /* parse out the OIDs and the first sec blob */
829         if (!parse_negTokenTarg(pauth_info->credentials, OIDs, &secblob)) {
830                 DEBUG(0,("pipe_spnego_auth_bind_negotiate: Failed to parse the security blob.\n"));
831                 goto err;
832         }
833
834         if (strcmp(OID_KERBEROS5, OIDs[0]) == 0 || strcmp(OID_KERBEROS5_OLD, OIDs[0]) == 0) {
835                 got_kerberos_mechanism = true;
836         }
837
838         for (i=0;OIDs[i];i++) {
839                 DEBUG(3,("pipe_spnego_auth_bind_negotiate: Got OID %s\n", OIDs[i]));
840                 TALLOC_FREE(OIDs[i]);
841         }
842         DEBUG(3,("pipe_spnego_auth_bind_negotiate: Got secblob of size %lu\n", (unsigned long)secblob.length));
843
844         if ( got_kerberos_mechanism && ((lp_security()==SEC_ADS) || USE_KERBEROS_KEYTAB) ) {
845                 bool ret;
846                 ret = pipe_spnego_auth_bind_kerberos(p, mem_ctx, pauth_info,
847                                                      &secblob, response);
848                 data_blob_free(&secblob);
849                 return ret;
850         }
851
852         if (p->auth.auth_type == PIPE_AUTH_TYPE_SPNEGO_NTLMSSP && p->auth.a_u.auth_ntlmssp_state) {
853                 /* Free any previous auth type. */
854                 free_pipe_ntlmssp_auth_data(&p->auth);
855         }
856
857         if (!got_kerberos_mechanism) {
858                 /* Initialize the NTLM engine. */
859                 status = auth_ntlmssp_start(&a);
860                 if (!NT_STATUS_IS_OK(status)) {
861                         goto err;
862                 }
863
864                 switch (pauth_info->auth_level) {
865                         case DCERPC_AUTH_LEVEL_INTEGRITY:
866                                 auth_ntlmssp_want_sign(a);
867                                 break;
868                         case DCERPC_AUTH_LEVEL_PRIVACY:
869                                 auth_ntlmssp_want_seal(a);
870                                 break;
871                         default:
872                                 break;
873                 }
874                 /*
875                  * Pass the first security blob of data to it.
876                  * This can return an error or NT_STATUS_MORE_PROCESSING_REQUIRED
877                  * which means we need another packet to complete the bind.
878                  */
879
880                 status = auth_ntlmssp_update(a, secblob, &chal);
881
882                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
883                         DEBUG(3,("pipe_spnego_auth_bind_negotiate: auth_ntlmssp_update failed.\n"));
884                         goto err;
885                 }
886
887                 /* Generate the response blob we need for step 2 of the bind. */
888                 *response = spnego_gen_auth_response(&chal, status, OID_NTLMSSP);
889         } else {
890                 /*
891                  * SPNEGO negotiate down to NTLMSSP. The subsequent
892                  * code to process follow-up packets is not complete
893                  * yet. JRA.
894                  */
895                 *response = spnego_gen_auth_response(NULL,
896                                         NT_STATUS_MORE_PROCESSING_REQUIRED,
897                                         OID_NTLMSSP);
898         }
899
900         /* Make sure data is bound to the memctx, to be freed the caller */
901         talloc_steal(mem_ctx, response->data);
902
903         /* auth_pad_len will be handled by the caller */
904
905         p->auth.a_u.auth_ntlmssp_state = a;
906         p->auth.auth_data_free_func = &free_pipe_ntlmssp_auth_data;
907         p->auth.auth_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
908
909         data_blob_free(&secblob);
910         data_blob_free(&chal);
911
912         /* We can't set pipe_bound True yet - we need an RPC_ALTER_CONTEXT response packet... */
913         return True;
914
915  err:
916
917         data_blob_free(&secblob);
918         data_blob_free(&chal);
919
920         p->auth.a_u.auth_ntlmssp_state = NULL;
921
922         return False;
923 }
924
925 /*******************************************************************
926  Handle the second part of a SPNEGO bind auth.
927 *******************************************************************/
928
929 static bool pipe_spnego_auth_bind_continue(pipes_struct *p,
930                                            TALLOC_CTX *mem_ctx,
931                                            struct dcerpc_auth *pauth_info,
932                                            DATA_BLOB *response)
933 {
934         DATA_BLOB auth_blob;
935         DATA_BLOB auth_reply;
936         struct auth_ntlmssp_state *a = p->auth.a_u.auth_ntlmssp_state;
937
938         ZERO_STRUCT(auth_blob);
939         ZERO_STRUCT(auth_reply);
940
941         /*
942          * NB. If we've negotiated down from krb5 to NTLMSSP we'll currently
943          * fail here as 'a' == NULL.
944          */
945         if (p->auth.auth_type != PIPE_AUTH_TYPE_SPNEGO_NTLMSSP || !a) {
946                 DEBUG(0,("pipe_spnego_auth_bind_continue: not in NTLMSSP auth state.\n"));
947                 goto err;
948         }
949
950         if (pauth_info->credentials.data[0] != ASN1_CONTEXT(1)) {
951                 DEBUG(0,("pipe_spnego_auth_bind_continue: invalid SPNEGO blob type.\n"));
952                 goto err;
953         }
954
955         if (!spnego_parse_auth(pauth_info->credentials, &auth_blob)) {
956                 DEBUG(0,("pipe_spnego_auth_bind_continue: invalid SPNEGO blob.\n"));
957                 goto err;
958         }
959
960         /*
961          * The following call actually checks the challenge/response data.
962          * for correctness against the given DOMAIN\user name.
963          */
964
965         if (!pipe_ntlmssp_verify_final(p, &auth_blob)) {
966                 goto err;
967         }
968
969         data_blob_free(&auth_blob);
970
971         /* Generate the spnego "accept completed" blob - no incoming data. */
972         *response = spnego_gen_auth_response(&auth_reply, NT_STATUS_OK, OID_NTLMSSP);
973
974         /* Make sure data is bound to the memctx, to be freed the caller */
975         talloc_steal(mem_ctx, response->data);
976
977         data_blob_free(&auth_reply);
978
979         p->pipe_bound = True;
980
981         return True;
982
983  err:
984
985         data_blob_free(&auth_blob);
986         data_blob_free(&auth_reply);
987
988         free_pipe_ntlmssp_auth_data(&p->auth);
989         p->auth.a_u.auth_ntlmssp_state = NULL;
990
991         return False;
992 }
993
994 /*******************************************************************
995  Handle an schannel bind auth.
996 *******************************************************************/
997
998 static bool pipe_schannel_auth_bind(pipes_struct *p,
999                                     TALLOC_CTX *mem_ctx,
1000                                     struct dcerpc_auth *auth_info,
1001                                     DATA_BLOB *response)
1002 {
1003         struct NL_AUTH_MESSAGE neg;
1004         struct NL_AUTH_MESSAGE reply;
1005         bool ret;
1006         NTSTATUS status;
1007         struct netlogon_creds_CredentialState *creds;
1008         DATA_BLOB session_key;
1009         enum ndr_err_code ndr_err;
1010
1011         ndr_err = ndr_pull_struct_blob(
1012                         &auth_info->credentials, mem_ctx, &neg,
1013                         (ndr_pull_flags_fn_t)ndr_pull_NL_AUTH_MESSAGE);
1014         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1015                 DEBUG(0,("pipe_schannel_auth_bind: Could not unmarshal SCHANNEL auth neg\n"));
1016                 return false;
1017         }
1018
1019         if (DEBUGLEVEL >= 10) {
1020                 NDR_PRINT_DEBUG(NL_AUTH_MESSAGE, &neg);
1021         }
1022
1023         if (!(neg.Flags & NL_FLAG_OEM_NETBIOS_COMPUTER_NAME)) {
1024                 DEBUG(0,("pipe_schannel_auth_bind: Did not receive netbios computer name\n"));
1025                 return false;
1026         }
1027
1028         /*
1029          * The neg.oem_netbios_computer.a key here must match the remote computer name
1030          * given in the DOM_CLNT_SRV.uni_comp_name used on all netlogon pipe
1031          * operations that use credentials.
1032          */
1033
1034         become_root();
1035         status = schannel_get_creds_state(p, lp_private_dir(),
1036                                             neg.oem_netbios_computer.a, &creds);
1037         unbecome_root();
1038
1039         if (!NT_STATUS_IS_OK(status)) {
1040                 DEBUG(0, ("pipe_schannel_auth_bind: Attempt to bind using schannel without successful serverauth2\n"));
1041                 return False;
1042         }
1043
1044         p->auth.a_u.schannel_auth = talloc(p, struct schannel_state);
1045         if (!p->auth.a_u.schannel_auth) {
1046                 TALLOC_FREE(creds);
1047                 return False;
1048         }
1049
1050         p->auth.a_u.schannel_auth->state = SCHANNEL_STATE_START;
1051         p->auth.a_u.schannel_auth->seq_num = 0;
1052         p->auth.a_u.schannel_auth->initiator = false;
1053         p->auth.a_u.schannel_auth->creds = creds;
1054
1055         /*
1056          * JRA. Should we also copy the schannel session key into the pipe session key p->session_key
1057          * here ? We do that for NTLMSSP, but the session key is already set up from the vuser
1058          * struct of the person who opened the pipe. I need to test this further. JRA.
1059          *
1060          * VL. As we are mapping this to guest set the generic key
1061          * "SystemLibraryDTC" key here. It's a bit difficult to test against
1062          * W2k3, as it does not allow schannel binds against SAMR and LSA
1063          * anymore.
1064          */
1065
1066         session_key = generic_session_key();
1067         if (session_key.data == NULL) {
1068                 DEBUG(0, ("pipe_schannel_auth_bind: Could not alloc session"
1069                           " key\n"));
1070                 return false;
1071         }
1072
1073         ret = server_info_set_session_key(p->server_info, session_key);
1074
1075         data_blob_free(&session_key);
1076
1077         if (!ret) {
1078                 DEBUG(0, ("server_info_set_session_key failed\n"));
1079                 return false;
1080         }
1081
1082         /*** SCHANNEL verifier ***/
1083
1084         reply.MessageType                       = NL_NEGOTIATE_RESPONSE;
1085         reply.Flags                             = 0;
1086         reply.Buffer.dummy                      = 5; /* ??? actually I don't think
1087                                                       * this has any meaning
1088                                                       * here - gd */
1089
1090         ndr_err = ndr_push_struct_blob(response, mem_ctx, &reply,
1091                        (ndr_push_flags_fn_t)ndr_push_NL_AUTH_MESSAGE);
1092         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1093                 DEBUG(0,("Failed to marshall NL_AUTH_MESSAGE.\n"));
1094                 return false;
1095         }
1096
1097         if (DEBUGLEVEL >= 10) {
1098                 NDR_PRINT_DEBUG(NL_AUTH_MESSAGE, &reply);
1099         }
1100
1101         DEBUG(10,("pipe_schannel_auth_bind: schannel auth: domain [%s] myname [%s]\n",
1102                 neg.oem_netbios_domain.a, neg.oem_netbios_computer.a));
1103
1104         /* We're finished with this bind - no more packets. */
1105         p->auth.auth_data_free_func = NULL;
1106         p->auth.auth_type = PIPE_AUTH_TYPE_SCHANNEL;
1107
1108         p->pipe_bound = True;
1109
1110         return True;
1111 }
1112
1113 /*******************************************************************
1114  Handle an NTLMSSP bind auth.
1115 *******************************************************************/
1116
1117 static bool pipe_ntlmssp_auth_bind(pipes_struct *p,
1118                                    TALLOC_CTX *mem_ctx,
1119                                    struct dcerpc_auth *auth_info,
1120                                    DATA_BLOB *response)
1121 {
1122         NTSTATUS status;
1123         struct auth_ntlmssp_state *a = NULL;
1124
1125         if (strncmp((char *)auth_info->credentials.data, "NTLMSSP", 7) != 0) {
1126                 DEBUG(0, ("Failed to read NTLMSSP in blob\n"));
1127                 goto err;
1128         }
1129
1130         /* We have an NTLMSSP blob. */
1131         status = auth_ntlmssp_start(&a);
1132         if (!NT_STATUS_IS_OK(status)) {
1133                 DEBUG(0,("pipe_ntlmssp_auth_bind: auth_ntlmssp_start failed: %s\n",
1134                         nt_errstr(status) ));
1135                 goto err;
1136         }
1137
1138         switch (auth_info->auth_level) {
1139         case DCERPC_AUTH_LEVEL_INTEGRITY:
1140                 auth_ntlmssp_want_sign(a);
1141                 break;
1142         case DCERPC_AUTH_LEVEL_PRIVACY:
1143                 auth_ntlmssp_want_seal(a);
1144                 break;
1145         default:
1146                 break;
1147         }
1148
1149         status = auth_ntlmssp_update(a, auth_info->credentials, response);
1150         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1151                 DEBUG(0,("pipe_ntlmssp_auth_bind: auth_ntlmssp_update failed: %s\n",
1152                         nt_errstr(status) ));
1153                 goto err;
1154         }
1155
1156         /* Make sure data is bound to the memctx, to be freed the caller */
1157         talloc_steal(mem_ctx, response->data);
1158
1159         p->auth.a_u.auth_ntlmssp_state = a;
1160         p->auth.auth_data_free_func = &free_pipe_ntlmssp_auth_data;
1161         p->auth.auth_type = PIPE_AUTH_TYPE_NTLMSSP;
1162
1163         DEBUG(10,("pipe_ntlmssp_auth_bind: NTLMSSP auth started\n"));
1164
1165         /* We can't set pipe_bound True yet - we need an DCERPC_PKT_AUTH3 response packet... */
1166         return True;
1167
1168   err:
1169
1170         free_pipe_ntlmssp_auth_data(&p->auth);
1171         p->auth.a_u.auth_ntlmssp_state = NULL;
1172         return False;
1173 }
1174
1175 /*******************************************************************
1176  Respond to a pipe bind request.
1177 *******************************************************************/
1178
1179 bool api_pipe_bind_req(pipes_struct *p, struct ncacn_packet *pkt)
1180 {
1181         struct dcerpc_auth auth_info;
1182         uint16 assoc_gid;
1183         unsigned int auth_type = DCERPC_AUTH_TYPE_NONE;
1184         NTSTATUS status;
1185         struct ndr_syntax_id id;
1186         union dcerpc_payload u;
1187         struct dcerpc_ack_ctx bind_ack_ctx;
1188         DATA_BLOB auth_resp = data_blob_null;
1189         DATA_BLOB auth_blob = data_blob_null;
1190
1191         /* No rebinds on a bound pipe - use alter context. */
1192         if (p->pipe_bound) {
1193                 DEBUG(2,("api_pipe_bind_req: rejecting bind request on bound "
1194                          "pipe %s.\n",
1195                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1196                 return setup_bind_nak(p, pkt);
1197         }
1198
1199         if (pkt->u.bind.num_contexts == 0) {
1200                 DEBUG(0, ("api_pipe_bind_req: no rpc contexts around\n"));
1201                 goto err_exit;
1202         }
1203
1204         /*
1205          * Try and find the correct pipe name to ensure
1206          * that this is a pipe name we support.
1207          */
1208         id = pkt->u.bind.ctx_list[0].abstract_syntax;
1209         if (rpc_srv_pipe_exists_by_id(&id)) {
1210                 DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
1211                         rpc_srv_get_pipe_cli_name(&id),
1212                         rpc_srv_get_pipe_srv_name(&id)));
1213         } else {
1214                 status = smb_probe_module(
1215                         "rpc", get_pipe_name_from_syntax(
1216                                 talloc_tos(),
1217                                 &pkt->u.bind.ctx_list[0].abstract_syntax));
1218
1219                 if (NT_STATUS_IS_ERR(status)) {
1220                        DEBUG(3,("api_pipe_bind_req: Unknown pipe name %s in bind request.\n",
1221                                 get_pipe_name_from_syntax(
1222                                         talloc_tos(),
1223                                         &pkt->u.bind.ctx_list[0].abstract_syntax)));
1224
1225                         return setup_bind_nak(p, pkt);
1226                 }
1227
1228                 if (rpc_srv_get_pipe_interface_by_cli_name(
1229                                 get_pipe_name_from_syntax(talloc_tos(),
1230                                                           &p->syntax),
1231                                 &id)) {
1232                         DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
1233                                 rpc_srv_get_pipe_cli_name(&id),
1234                                 rpc_srv_get_pipe_srv_name(&id)));
1235                 } else {
1236                         DEBUG(0, ("module %s doesn't provide functions for "
1237                                   "pipe %s!\n",
1238                                   get_pipe_name_from_syntax(talloc_tos(),
1239                                                             &p->syntax),
1240                                   get_pipe_name_from_syntax(talloc_tos(),
1241                                                             &p->syntax)));
1242                         return setup_bind_nak(p, pkt);
1243                 }
1244         }
1245
1246         DEBUG(5,("api_pipe_bind_req: make response. %d\n", __LINE__));
1247
1248         if (pkt->u.bind.assoc_group_id != 0) {
1249                 assoc_gid = pkt->u.bind.assoc_group_id;
1250         } else {
1251                 assoc_gid = 0x53f0;
1252         }
1253
1254         /*
1255          * Create the bind response struct.
1256          */
1257
1258         /* If the requested abstract synt uuid doesn't match our client pipe,
1259                 reject the bind_ack & set the transfer interface synt to all 0's,
1260                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1261                 unknown to NT4)
1262                 Needed when adding entries to a DACL from NT5 - SK */
1263
1264         if (check_bind_req(p,
1265                         &pkt->u.bind.ctx_list[0].abstract_syntax,
1266                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
1267                         pkt->u.bind.ctx_list[0].context_id)) {
1268
1269                 bind_ack_ctx.result = 0;
1270                 bind_ack_ctx.reason = 0;
1271                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
1272         } else {
1273                 p->pipe_bound = False;
1274                 /* Rejection reason: abstract syntax not supported */
1275                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1276                 bind_ack_ctx.reason = DCERPC_BIND_REASON_ASYNTAX;
1277                 bind_ack_ctx.syntax = null_ndr_syntax_id;
1278         }
1279
1280         /*
1281          * Check if this is an authenticated bind request.
1282          */
1283         if (pkt->auth_length) {
1284                 /* Quick length check. Won't catch a bad auth footer,
1285                  * prevents overrun. */
1286
1287                 if (pkt->frag_length < RPC_HEADER_LEN +
1288                                         DCERPC_AUTH_TRAILER_LENGTH +
1289                                         pkt->auth_length) {
1290                         DEBUG(0,("api_pipe_bind_req: auth_len (%u) "
1291                                 "too long for fragment %u.\n",
1292                                 (unsigned int)pkt->auth_length,
1293                                 (unsigned int)pkt->frag_length));
1294                         goto err_exit;
1295                 }
1296
1297                 /*
1298                  * Decode the authentication verifier.
1299                  */
1300                 status = dcerpc_pull_dcerpc_auth(pkt,
1301                                                  &pkt->u.bind.auth_info,
1302                                                  &auth_info, p->endian);
1303                 if (!NT_STATUS_IS_OK(status)) {
1304                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1305                         goto err_exit;
1306                 }
1307
1308                 auth_type = auth_info.auth_type;
1309
1310                 /* Work out if we have to sign or seal etc. */
1311                 switch (auth_info.auth_level) {
1312                 case DCERPC_AUTH_LEVEL_INTEGRITY:
1313                         p->auth.auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1314                         break;
1315                 case DCERPC_AUTH_LEVEL_PRIVACY:
1316                         p->auth.auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1317                         break;
1318                 default:
1319                         DEBUG(0, ("Unexpected auth level (%u).\n",
1320                                 (unsigned int)auth_info.auth_level ));
1321                         goto err_exit;
1322                 }
1323
1324                 switch (auth_type) {
1325                 case DCERPC_AUTH_TYPE_NTLMSSP:
1326                         if (!pipe_ntlmssp_auth_bind(p, pkt,
1327                                                 &auth_info, &auth_resp)) {
1328                                 goto err_exit;
1329                         }
1330                         assoc_gid = 0x7a77;
1331                         break;
1332
1333                 case DCERPC_AUTH_TYPE_SCHANNEL:
1334                         if (!pipe_schannel_auth_bind(p, pkt,
1335                                                 &auth_info, &auth_resp)) {
1336                                 goto err_exit;
1337                         }
1338                         break;
1339
1340                 case DCERPC_AUTH_TYPE_SPNEGO:
1341                         if (!pipe_spnego_auth_bind_negotiate(p, pkt,
1342                                                 &auth_info, &auth_resp)) {
1343                                 goto err_exit;
1344                         }
1345                         break;
1346
1347                 case DCERPC_AUTH_TYPE_NONE:
1348                         break;
1349
1350                 default:
1351                         DEBUG(0, ("Unknown auth type %x requested.\n", auth_type));
1352                         goto err_exit;
1353                 }
1354         }
1355
1356         if (auth_type == DCERPC_AUTH_TYPE_NONE) {
1357                 /* Unauthenticated bind request. */
1358                 /* We're finished - no more packets. */
1359                 p->auth.auth_type = PIPE_AUTH_TYPE_NONE;
1360                 /* We must set the pipe auth_level here also. */
1361                 p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
1362                 p->pipe_bound = True;
1363                 /* The session key was initialized from the SMB
1364                  * session in make_internal_rpc_pipe_p */
1365         }
1366
1367         ZERO_STRUCT(u.bind_ack);
1368         u.bind_ack.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1369         u.bind_ack.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1370         u.bind_ack.assoc_group_id = assoc_gid;
1371
1372         /* name has to be \PIPE\xxxxx */
1373         u.bind_ack.secondary_address =
1374                         talloc_asprintf(pkt, "\\PIPE\\%s",
1375                                         rpc_srv_get_pipe_srv_name(&id));
1376         if (!u.bind_ack.secondary_address) {
1377                 DEBUG(0, ("Out of memory!\n"));
1378                 goto err_exit;
1379         }
1380         u.bind_ack.secondary_address_size =
1381                                 strlen(u.bind_ack.secondary_address) + 1;
1382
1383         u.bind_ack.num_results = 1;
1384         u.bind_ack.ctx_list = &bind_ack_ctx;
1385
1386         /* NOTE: We leave the auth_info empty so we can calculate the padding
1387          * later and then append the auth_info --simo */
1388
1389         /*
1390          * Marshall directly into the outgoing PDU space. We
1391          * must do this as we need to set to the bind response
1392          * header and are never sending more than one PDU here.
1393          */
1394
1395         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1396                                           DCERPC_PKT_BIND_ACK,
1397                                           DCERPC_PFC_FLAG_FIRST |
1398                                                 DCERPC_PFC_FLAG_LAST,
1399                                           auth_resp.length,
1400                                           pkt->call_id,
1401                                           &u,
1402                                           &p->out_data.frag);
1403         if (!NT_STATUS_IS_OK(status)) {
1404                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
1405                           nt_errstr(status)));
1406         }
1407
1408         if (auth_resp.length) {
1409
1410                 status = dcerpc_push_dcerpc_auth(pkt,
1411                                                  auth_type,
1412                                                  auth_info.auth_level,
1413                                                  0,
1414                                                  1, /* auth_context_id */
1415                                                  &auth_resp,
1416                                                  &auth_blob);
1417                 if (!NT_STATUS_IS_OK(status)) {
1418                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1419                         goto err_exit;
1420                 }
1421         }
1422
1423         /* Now that we have the auth len store it into the right place in
1424          * the dcerpc header */
1425         dcerpc_set_frag_length(&p->out_data.frag,
1426                                 p->out_data.frag.length + auth_blob.length);
1427
1428         if (auth_blob.length) {
1429
1430                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1431                                         auth_blob.data, auth_blob.length)) {
1432                         DEBUG(0, ("Append of auth info failed.\n"));
1433                         goto err_exit;
1434                 }
1435         }
1436
1437         /*
1438          * Setup the lengths for the initial reply.
1439          */
1440
1441         p->out_data.data_sent_length = 0;
1442         p->out_data.current_pdu_sent = 0;
1443
1444         TALLOC_FREE(auth_blob.data);
1445         return True;
1446
1447   err_exit:
1448
1449         data_blob_free(&p->out_data.frag);
1450         TALLOC_FREE(auth_blob.data);
1451         return setup_bind_nak(p, pkt);
1452 }
1453
1454 /****************************************************************************
1455  Deal with an alter context call. Can be third part of 3 leg auth request for
1456  SPNEGO calls.
1457 ****************************************************************************/
1458
1459 bool api_pipe_alter_context(pipes_struct *p, struct ncacn_packet *pkt)
1460 {
1461         struct dcerpc_auth auth_info;
1462         uint16 assoc_gid;
1463         NTSTATUS status;
1464         union dcerpc_payload u;
1465         struct dcerpc_ack_ctx bind_ack_ctx;
1466         DATA_BLOB auth_resp = data_blob_null;
1467         DATA_BLOB auth_blob = data_blob_null;
1468         int pad_len = 0;
1469
1470         DEBUG(5,("api_pipe_alter_context: make response. %d\n", __LINE__));
1471
1472         if (pkt->u.bind.assoc_group_id != 0) {
1473                 assoc_gid = pkt->u.bind.assoc_group_id;
1474         } else {
1475                 assoc_gid = 0x53f0;
1476         }
1477
1478         /*
1479          * Create the bind response struct.
1480          */
1481
1482         /* If the requested abstract synt uuid doesn't match our client pipe,
1483                 reject the bind_ack & set the transfer interface synt to all 0's,
1484                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1485                 unknown to NT4)
1486                 Needed when adding entries to a DACL from NT5 - SK */
1487
1488         if (check_bind_req(p,
1489                         &pkt->u.bind.ctx_list[0].abstract_syntax,
1490                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
1491                         pkt->u.bind.ctx_list[0].context_id)) {
1492
1493                 bind_ack_ctx.result = 0;
1494                 bind_ack_ctx.reason = 0;
1495                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
1496         } else {
1497                 p->pipe_bound = False;
1498                 /* Rejection reason: abstract syntax not supported */
1499                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1500                 bind_ack_ctx.reason = DCERPC_BIND_REASON_ASYNTAX;
1501                 bind_ack_ctx.syntax = null_ndr_syntax_id;
1502         }
1503
1504         /*
1505          * Check if this is an authenticated alter context request.
1506          */
1507         if (pkt->auth_length) {
1508                 /* Quick length check. Won't catch a bad auth footer,
1509                  * prevents overrun. */
1510
1511                 if (pkt->frag_length < RPC_HEADER_LEN +
1512                                         DCERPC_AUTH_TRAILER_LENGTH +
1513                                         pkt->auth_length) {
1514                         DEBUG(0,("api_pipe_alter_context: auth_len (%u) "
1515                                 "too long for fragment %u.\n",
1516                                 (unsigned int)pkt->auth_length,
1517                                 (unsigned int)pkt->frag_length ));
1518                         goto err_exit;
1519                 }
1520
1521                 status = dcerpc_pull_dcerpc_auth(pkt,
1522                                                  &pkt->u.bind.auth_info,
1523                                                  &auth_info, p->endian);
1524                 if (!NT_STATUS_IS_OK(status)) {
1525                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1526                         goto err_exit;
1527                 }
1528
1529
1530                 /*
1531                  * Currently only the SPNEGO auth type uses the alter ctx
1532                  * response in place of the NTLMSSP auth3 type.
1533                  */
1534
1535                 if (auth_info.auth_type == DCERPC_AUTH_TYPE_SPNEGO) {
1536                         /* We can only finish if the pipe is unbound. */
1537                         if (!p->pipe_bound) {
1538                                 if (!pipe_spnego_auth_bind_continue(p, pkt,
1539                                                 &auth_info, &auth_resp)) {
1540                                         goto err_exit;
1541                                 }
1542
1543                         } else {
1544                                 goto err_exit;
1545                         }
1546                 }
1547         }
1548
1549         ZERO_STRUCT(u.alter_resp);
1550         u.alter_resp.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1551         u.alter_resp.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1552         u.alter_resp.assoc_group_id = assoc_gid;
1553
1554         /* secondary address CAN be NULL
1555          * as the specs say it's ignored.
1556          * It MUST be NULL to have the spoolss working.
1557          */
1558         u.alter_resp.secondary_address = "";
1559         u.alter_resp.secondary_address_size = 1;
1560
1561         u.alter_resp.num_results = 1;
1562         u.alter_resp.ctx_list = &bind_ack_ctx;
1563
1564         /* NOTE: We leave the auth_info empty so we can calculate the padding
1565          * later and then append the auth_info --simo */
1566
1567         /*
1568          * Marshall directly into the outgoing PDU space. We
1569          * must do this as we need to set to the bind response
1570          * header and are never sending more than one PDU here.
1571          */
1572
1573         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1574                                           DCERPC_PKT_ALTER_RESP,
1575                                           DCERPC_PFC_FLAG_FIRST |
1576                                                 DCERPC_PFC_FLAG_LAST,
1577                                           auth_resp.length,
1578                                           pkt->call_id,
1579                                           &u,
1580                                           &p->out_data.frag);
1581         if (!NT_STATUS_IS_OK(status)) {
1582                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
1583                           nt_errstr(status)));
1584         }
1585
1586         if (auth_resp.length) {
1587
1588                 /* Work out any padding needed before the auth footer. */
1589                 pad_len = p->out_data.frag.length % SERVER_NDR_PADDING_SIZE;
1590                 if (pad_len) {
1591                         pad_len = SERVER_NDR_PADDING_SIZE - pad_len;
1592                         DEBUG(10, ("auth pad_len = %u\n",
1593                                    (unsigned int)pad_len));
1594                 }
1595
1596                 status = dcerpc_push_dcerpc_auth(pkt,
1597                                                  auth_info.auth_type,
1598                                                  auth_info.auth_level,
1599                                                  pad_len,
1600                                                  1, /* auth_context_id */
1601                                                  &auth_resp,
1602                                                  &auth_blob);
1603                 if (!NT_STATUS_IS_OK(status)) {
1604                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1605                         goto err_exit;
1606                 }
1607         }
1608
1609         /* Now that we have the auth len store it into the right place in
1610          * the dcerpc header */
1611         dcerpc_set_frag_length(&p->out_data.frag,
1612                                 p->out_data.frag.length +
1613                                         pad_len + auth_blob.length);
1614
1615         if (auth_resp.length) {
1616                 if (pad_len) {
1617                         char pad[SERVER_NDR_PADDING_SIZE];
1618                         memset(pad, '\0', SERVER_NDR_PADDING_SIZE);
1619                         if (!data_blob_append(p->mem_ctx,
1620                                                 &p->out_data.frag,
1621                                                 pad, pad_len)) {
1622                                 DEBUG(0, ("api_pipe_bind_req: failed to add "
1623                                           "%u bytes of pad data.\n",
1624                                           (unsigned int)pad_len));
1625                                 goto err_exit;
1626                         }
1627                 }
1628
1629                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1630                                         auth_blob.data, auth_blob.length)) {
1631                         DEBUG(0, ("Append of auth info failed.\n"));
1632                         goto err_exit;
1633                 }
1634         }
1635
1636         /*
1637          * Setup the lengths for the initial reply.
1638          */
1639
1640         p->out_data.data_sent_length = 0;
1641         p->out_data.current_pdu_sent = 0;
1642
1643         TALLOC_FREE(auth_blob.data);
1644         return True;
1645
1646   err_exit:
1647
1648         data_blob_free(&p->out_data.frag);
1649         TALLOC_FREE(auth_blob.data);
1650         return setup_bind_nak(p, pkt);
1651 }
1652
1653 /****************************************************************************
1654  Find the set of RPC functions associated with this context_id
1655 ****************************************************************************/
1656
1657 static PIPE_RPC_FNS* find_pipe_fns_by_context( PIPE_RPC_FNS *list, uint32 context_id )
1658 {
1659         PIPE_RPC_FNS *fns = NULL;
1660
1661         if ( !list ) {
1662                 DEBUG(0,("find_pipe_fns_by_context: ERROR!  No context list for pipe!\n"));
1663                 return NULL;
1664         }
1665
1666         for (fns=list; fns; fns=fns->next ) {
1667                 if ( fns->context_id == context_id )
1668                         return fns;
1669         }
1670         return NULL;
1671 }
1672
1673 /****************************************************************************
1674  Memory cleanup.
1675 ****************************************************************************/
1676
1677 void free_pipe_rpc_context( PIPE_RPC_FNS *list )
1678 {
1679         PIPE_RPC_FNS *tmp = list;
1680         PIPE_RPC_FNS *tmp2;
1681
1682         while (tmp) {
1683                 tmp2 = tmp->next;
1684                 SAFE_FREE(tmp);
1685                 tmp = tmp2;
1686         }
1687
1688         return; 
1689 }
1690
1691 static bool api_rpcTNP(pipes_struct *p, struct ncacn_packet *pkt,
1692                        const struct api_struct *api_rpc_cmds, int n_cmds);
1693
1694 /****************************************************************************
1695  Find the correct RPC function to call for this request.
1696  If the pipe is authenticated then become the correct UNIX user
1697  before doing the call.
1698 ****************************************************************************/
1699
1700 bool api_pipe_request(pipes_struct *p, struct ncacn_packet *pkt)
1701 {
1702         bool ret = False;
1703         bool changed_user = False;
1704         PIPE_RPC_FNS *pipe_fns;
1705
1706         if (p->pipe_bound &&
1707                         ((p->auth.auth_type == PIPE_AUTH_TYPE_NTLMSSP) ||
1708                          (p->auth.auth_type == PIPE_AUTH_TYPE_SPNEGO_NTLMSSP))) {
1709                 if(!become_authenticated_pipe_user(p)) {
1710                         data_blob_free(&p->out_data.rdata);
1711                         return False;
1712                 }
1713                 changed_user = True;
1714         }
1715
1716         DEBUG(5, ("Requested \\PIPE\\%s\n",
1717                   get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1718
1719         /* get the set of RPC functions for this context */
1720
1721         pipe_fns = find_pipe_fns_by_context(p->contexts,
1722                                             pkt->u.request.context_id);
1723
1724         if ( pipe_fns ) {
1725                 TALLOC_CTX *frame = talloc_stackframe();
1726                 ret = api_rpcTNP(p, pkt, pipe_fns->cmds, pipe_fns->n_cmds);
1727                 TALLOC_FREE(frame);
1728         }
1729         else {
1730                 DEBUG(0, ("No rpc function table associated with context "
1731                           "[%d] on pipe [%s]\n",
1732                           pkt->u.request.context_id,
1733                           get_pipe_name_from_syntax(talloc_tos(),
1734                                                     &p->syntax)));
1735         }
1736
1737         if (changed_user) {
1738                 unbecome_authenticated_pipe_user();
1739         }
1740
1741         return ret;
1742 }
1743
1744 /*******************************************************************
1745  Calls the underlying RPC function for a named pipe.
1746  ********************************************************************/
1747
1748 static bool api_rpcTNP(pipes_struct *p, struct ncacn_packet *pkt,
1749                        const struct api_struct *api_rpc_cmds, int n_cmds)
1750 {
1751         int fn_num;
1752         uint32_t offset1;
1753
1754         /* interpret the command */
1755         DEBUG(4,("api_rpcTNP: %s op 0x%x - ",
1756                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax),
1757                  pkt->u.request.opnum));
1758
1759         if (DEBUGLEVEL >= 50) {
1760                 fstring name;
1761                 slprintf(name, sizeof(name)-1, "in_%s",
1762                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax));
1763                 dump_pdu_region(name, pkt->u.request.opnum,
1764                                 &p->in_data.data, 0,
1765                                 p->in_data.data.length);
1766         }
1767
1768         for (fn_num = 0; fn_num < n_cmds; fn_num++) {
1769                 if (api_rpc_cmds[fn_num].opnum == pkt->u.request.opnum &&
1770                     api_rpc_cmds[fn_num].fn != NULL) {
1771                         DEBUG(3, ("api_rpcTNP: rpc command: %s\n",
1772                                   api_rpc_cmds[fn_num].name));
1773                         break;
1774                 }
1775         }
1776
1777         if (fn_num == n_cmds) {
1778                 /*
1779                  * For an unknown RPC just return a fault PDU but
1780                  * return True to allow RPC's on the pipe to continue
1781                  * and not put the pipe into fault state. JRA.
1782                  */
1783                 DEBUG(4, ("unknown\n"));
1784                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1785                 return True;
1786         }
1787
1788         offset1 = p->out_data.rdata.length;
1789
1790         DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", 
1791                 fn_num, api_rpc_cmds[fn_num].fn));
1792         /* do the actual command */
1793         if(!api_rpc_cmds[fn_num].fn(p)) {
1794                 DEBUG(0,("api_rpcTNP: %s: %s failed.\n",
1795                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax),
1796                          api_rpc_cmds[fn_num].name));
1797                 data_blob_free(&p->out_data.rdata);
1798                 return False;
1799         }
1800
1801         if (p->bad_handle_fault_state) {
1802                 DEBUG(4,("api_rpcTNP: bad handle fault return.\n"));
1803                 p->bad_handle_fault_state = False;
1804                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_CONTEXT_MISMATCH));
1805                 return True;
1806         }
1807
1808         if (p->rng_fault_state) {
1809                 DEBUG(4, ("api_rpcTNP: rng fault return\n"));
1810                 p->rng_fault_state = False;
1811                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1812                 return True;
1813         }
1814
1815         if (DEBUGLEVEL >= 50) {
1816                 fstring name;
1817                 slprintf(name, sizeof(name)-1, "out_%s",
1818                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax));
1819                 dump_pdu_region(name, pkt->u.request.opnum,
1820                                 &p->out_data.rdata, offset1,
1821                                 p->out_data.rdata.length);
1822         }
1823
1824         DEBUG(5,("api_rpcTNP: called %s successfully\n",
1825                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1826
1827         /* Check for buffer underflow in rpc parsing */
1828         if ((DEBUGLEVEL >= 10) &&
1829             (pkt->frag_length < p->in_data.data.length)) {
1830                 DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n"));
1831                 dump_data(10, p->in_data.data.data + pkt->frag_length,
1832                               p->in_data.data.length - pkt->frag_length);
1833         }
1834
1835         return True;
1836 }
1837
1838 /****************************************************************************
1839  Initialise an outgoing packet.
1840 ****************************************************************************/
1841
1842 static bool pipe_init_outgoing_data(pipes_struct *p)
1843 {
1844         output_data *o_data = &p->out_data;
1845
1846         /* Reset the offset counters. */
1847         o_data->data_sent_length = 0;
1848         o_data->current_pdu_sent = 0;
1849
1850         data_blob_free(&o_data->frag);
1851
1852         /* Free any memory in the current return data buffer. */
1853         data_blob_free(&o_data->rdata);
1854
1855         return True;
1856 }
1857
1858 /****************************************************************************
1859  Sets the fault state on incoming packets.
1860 ****************************************************************************/
1861
1862 void set_incoming_fault(pipes_struct *p)
1863 {
1864         data_blob_free(&p->in_data.data);
1865         p->in_data.pdu_needed_len = 0;
1866         p->in_data.pdu.length = 0;
1867         p->fault_state = True;
1868         DEBUG(10, ("set_incoming_fault: Setting fault state on pipe %s\n",
1869                    get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1870 }
1871
1872 static bool dcesrv_auth_request(pipes_struct *p, struct ncacn_packet *pkt)
1873 {
1874         NTSTATUS status;
1875         size_t hdr_size = DCERPC_REQUEST_LENGTH;
1876         struct dcerpc_auth auth;
1877         uint32_t auth_length;
1878         DATA_BLOB data;
1879         DATA_BLOB full_pkt;
1880
1881         DEBUG(10, ("Checking request auth.\n"));
1882
1883         if (pkt->pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
1884                 hdr_size += 16;
1885         }
1886
1887         switch (p->auth.auth_level) {
1888         case DCERPC_AUTH_LEVEL_PRIVACY:
1889                 DEBUG(10, ("Requested Privacy.\n"));
1890                 break;
1891
1892         case DCERPC_AUTH_LEVEL_INTEGRITY:
1893                 DEBUG(10, ("Requested Integrity.\n"));
1894                 break;
1895
1896         case DCERPC_AUTH_LEVEL_CONNECT:
1897                 if (pkt->auth_length != 0) {
1898                         break;
1899                 }
1900                 return true;
1901         case DCERPC_AUTH_LEVEL_NONE:
1902                 if (pkt->auth_length != 0) {
1903                         return false;
1904                 }
1905                 return true;
1906
1907         default:
1908                 return false;
1909         }
1910
1911         status = dcerpc_pull_auth_trailer(pkt, pkt,
1912                                           &pkt->u.request.stub_and_verifier,
1913                                           &auth, &auth_length, false);
1914         if (!NT_STATUS_IS_OK(status)) {
1915                 return false;
1916         }
1917
1918         pkt->u.request.stub_and_verifier.length -= auth_length;
1919
1920         data.data = p->in_data.pdu.data + hdr_size;
1921         data.length = pkt->u.request.stub_and_verifier.length;
1922         full_pkt.data = p->in_data.pdu.data;
1923         full_pkt.length = p->in_data.pdu.length - auth.credentials.length;
1924
1925         switch (p->auth.auth_type) {
1926         case PIPE_AUTH_TYPE_NONE:
1927                 return true;
1928
1929         case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
1930         case PIPE_AUTH_TYPE_NTLMSSP:
1931
1932                 DEBUG(10, ("NTLMSSP auth\n"));
1933
1934                 if (!p->auth.a_u.auth_ntlmssp_state) {
1935                         DEBUG(0, ("Invalid auth level, "
1936                                   "failed to process packet auth.\n"));
1937                         return false;
1938                 }
1939
1940                 switch (p->auth.auth_level) {
1941                 case DCERPC_AUTH_LEVEL_PRIVACY:
1942                         status = auth_ntlmssp_unseal_packet(
1943                                         p->auth.a_u.auth_ntlmssp_state,
1944                                         data.data, data.length,
1945                                         full_pkt.data, full_pkt.length,
1946                                         &auth.credentials);
1947                         if (!NT_STATUS_IS_OK(status)) {
1948                                 return false;
1949                         }
1950                         memcpy(pkt->u.request.stub_and_verifier.data,
1951                                 data.data, data.length);
1952                         break;
1953
1954                 case DCERPC_AUTH_LEVEL_INTEGRITY:
1955                         status = auth_ntlmssp_check_packet(
1956                                         p->auth.a_u.auth_ntlmssp_state,
1957                                         data.data, data.length,
1958                                         full_pkt.data, full_pkt.length,
1959                                         &auth.credentials);
1960                         if (!NT_STATUS_IS_OK(status)) {
1961                                 return false;
1962                         }
1963                         break;
1964
1965                 default:
1966                         DEBUG(0, ("Invalid auth level, "
1967                                   "failed to process packet auth.\n"));
1968                         return false;
1969                 }
1970                 break;
1971
1972         case PIPE_AUTH_TYPE_SCHANNEL:
1973
1974                 DEBUG(10, ("SCHANNEL auth\n"));
1975
1976                 switch (p->auth.auth_level) {
1977                 case DCERPC_AUTH_LEVEL_PRIVACY:
1978                         status = netsec_incoming_packet(
1979                                         p->auth.a_u.schannel_auth,
1980                                         pkt, true,
1981                                         data.data, data.length,
1982                                         &auth.credentials);
1983                         if (!NT_STATUS_IS_OK(status)) {
1984                                 return false;
1985                         }
1986                         memcpy(pkt->u.request.stub_and_verifier.data,
1987                                 data.data, data.length);
1988                         break;
1989
1990                 case DCERPC_AUTH_LEVEL_INTEGRITY:
1991                         status = netsec_incoming_packet(
1992                                         p->auth.a_u.schannel_auth,
1993                                         pkt, false,
1994                                         data.data, data.length,
1995                                         &auth.credentials);
1996                         if (!NT_STATUS_IS_OK(status)) {
1997                                 return false;
1998                         }
1999                         break;
2000
2001                 default:
2002                         DEBUG(0, ("Invalid auth level, "
2003                                   "failed to process packet auth.\n"));
2004                         return false;
2005                 }
2006                 break;
2007
2008         default:
2009                 DEBUG(0, ("process_request_pdu: "
2010                           "unknown auth type %u set.\n",
2011                           (unsigned int)p->auth.auth_type));
2012                 set_incoming_fault(p);
2013                 return false;
2014         }
2015
2016         /* remove the indicated amount of padding */
2017         if (pkt->u.request.stub_and_verifier.length < auth.auth_pad_length) {
2018                 return false;
2019         }
2020         pkt->u.request.stub_and_verifier.length -= auth.auth_pad_length;
2021
2022         return true;
2023 }
2024
2025 /****************************************************************************
2026  Processes a request pdu. This will do auth processing if needed, and
2027  appends the data into the complete stream if the LAST flag is not set.
2028 ****************************************************************************/
2029
2030 static bool process_request_pdu(pipes_struct *p, struct ncacn_packet *pkt)
2031 {
2032         DATA_BLOB data;
2033
2034         if (!p->pipe_bound) {
2035                 DEBUG(0,("process_request_pdu: rpc request with no bind.\n"));
2036                 set_incoming_fault(p);
2037                 return False;
2038         }
2039
2040         /* Store the opnum */
2041         p->opnum = pkt->u.request.opnum;
2042
2043         if (!dcesrv_auth_request(p, pkt)) {
2044                 DEBUG(0,("Failed to check packet auth.\n"));
2045                 set_incoming_fault(p);
2046                 return false;
2047         }
2048
2049         data = pkt->u.request.stub_and_verifier;
2050
2051         /*
2052          * Check the data length doesn't go over the 15Mb limit.
2053          * increased after observing a bug in the Windows NT 4.0 SP6a
2054          * spoolsv.exe when the response to a GETPRINTERDRIVER2 RPC
2055          * will not fit in the initial buffer of size 0x1068   --jerry 22/01/2002
2056          */
2057
2058         if (p->in_data.data.length + data.length > MAX_RPC_DATA_SIZE) {
2059                 DEBUG(0, ("process_request_pdu: "
2060                           "rpc data buffer too large (%u) + (%u)\n",
2061                           (unsigned int)p->in_data.data.length,
2062                           (unsigned int)data.length));
2063                 set_incoming_fault(p);
2064                 return False;
2065         }
2066
2067         /*
2068          * Append the data portion into the buffer and return.
2069          */
2070
2071         if (data.length) {
2072                 if (!data_blob_append(p->mem_ctx, &p->in_data.data,
2073                                           data.data, data.length)) {
2074                         DEBUG(0, ("Unable to append data size %u "
2075                                   "to parse buffer of size %u.\n",
2076                                   (unsigned int)data.length,
2077                                   (unsigned int)p->in_data.data.length));
2078                         set_incoming_fault(p);
2079                         return False;
2080                 }
2081         }
2082
2083         if (pkt->pfc_flags & DCERPC_PFC_FLAG_LAST) {
2084                 bool ret = False;
2085                 /*
2086                  * Ok - we finally have a complete RPC stream.
2087                  * Call the rpc command to process it.
2088                  */
2089
2090                 /*
2091                  * Process the complete data stream here.
2092                  */
2093                 if (pipe_init_outgoing_data(p)) {
2094                         ret = api_pipe_request(p, pkt);
2095                 }
2096
2097                 return ret;
2098         }
2099
2100         return True;
2101 }
2102
2103 /****************************************************************************
2104  Processes a finished PDU stored in p->in_data.pdu.
2105 ****************************************************************************/
2106
2107 void process_complete_pdu(pipes_struct *p)
2108 {
2109         struct ncacn_packet *pkt = NULL;
2110         NTSTATUS status;
2111         bool reply = False;
2112
2113         if(p->fault_state) {
2114                 DEBUG(10,("process_complete_pdu: pipe %s in fault state.\n",
2115                           get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
2116                 goto done;
2117         }
2118
2119         pkt = talloc(p->mem_ctx, struct ncacn_packet);
2120         if (!pkt) {
2121                 DEBUG(0, ("Out of memory!\n"));
2122                 goto done;
2123         }
2124
2125         /*
2126          * Ensure we're using the corrent endianness for both the
2127          * RPC header flags and the raw data we will be reading from.
2128          */
2129         if (dcerpc_get_endian_flag(&p->in_data.pdu) & DCERPC_DREP_LE) {
2130                 p->endian = RPC_LITTLE_ENDIAN;
2131         } else {
2132                 p->endian = RPC_BIG_ENDIAN;
2133         }
2134         DEBUG(10, ("PDU is in %s Endian format!\n", p->endian?"Big":"Little"));
2135
2136         status = dcerpc_pull_ncacn_packet(pkt, &p->in_data.pdu,
2137                                           pkt, p->endian);
2138         if (!NT_STATUS_IS_OK(status)) {
2139                 DEBUG(0, ("Failed to unmarshal rpc packet: %s!\n",
2140                           nt_errstr(status)));
2141                 goto done;
2142         }
2143
2144         /* Store the call_id */
2145         p->call_id = pkt->call_id;
2146
2147         DEBUG(10, ("Processing packet type %d\n", (int)pkt->ptype));
2148
2149         switch (pkt->ptype) {
2150         case DCERPC_PKT_REQUEST:
2151                 reply = process_request_pdu(p, pkt);
2152                 break;
2153
2154         case DCERPC_PKT_PING: /* CL request - ignore... */
2155                 DEBUG(0, ("process_complete_pdu: Error. "
2156                           "Connectionless packet type %d received on "
2157                           "pipe %s.\n", (int)pkt->ptype,
2158                          get_pipe_name_from_syntax(talloc_tos(),
2159                                                    &p->syntax)));
2160                 break;
2161
2162         case DCERPC_PKT_RESPONSE: /* No responses here. */
2163                 DEBUG(0, ("process_complete_pdu: Error. "
2164                           "DCERPC_PKT_RESPONSE received from client "
2165                           "on pipe %s.\n",
2166                          get_pipe_name_from_syntax(talloc_tos(),
2167                                                    &p->syntax)));
2168                 break;
2169
2170         case DCERPC_PKT_FAULT:
2171         case DCERPC_PKT_WORKING:
2172                 /* CL request - reply to a ping when a call in process. */
2173         case DCERPC_PKT_NOCALL:
2174                 /* CL - server reply to a ping call. */
2175         case DCERPC_PKT_REJECT:
2176         case DCERPC_PKT_ACK:
2177         case DCERPC_PKT_CL_CANCEL:
2178         case DCERPC_PKT_FACK:
2179         case DCERPC_PKT_CANCEL_ACK:
2180                 DEBUG(0, ("process_complete_pdu: Error. "
2181                           "Connectionless packet type %u received on "
2182                           "pipe %s.\n", (unsigned int)pkt->ptype,
2183                          get_pipe_name_from_syntax(talloc_tos(),
2184                                                    &p->syntax)));
2185                 break;
2186
2187         case DCERPC_PKT_BIND:
2188                 /*
2189                  * We assume that a pipe bind is only in one pdu.
2190                  */
2191                 if (pipe_init_outgoing_data(p)) {
2192                         reply = api_pipe_bind_req(p, pkt);
2193                 }
2194                 break;
2195
2196         case DCERPC_PKT_BIND_ACK:
2197         case DCERPC_PKT_BIND_NAK:
2198                 DEBUG(0, ("process_complete_pdu: Error. "
2199                           "DCERPC_PKT_BINDACK/DCERPC_PKT_BINDNACK "
2200                           "packet type %u received on pipe %s.\n",
2201                           (unsigned int)pkt->ptype,
2202                          get_pipe_name_from_syntax(talloc_tos(),
2203                                                    &p->syntax)));
2204                 break;
2205
2206
2207         case DCERPC_PKT_ALTER:
2208                 /*
2209                  * We assume that a pipe bind is only in one pdu.
2210                  */
2211                 if (pipe_init_outgoing_data(p)) {
2212                         reply = api_pipe_alter_context(p, pkt);
2213                 }
2214                 break;
2215
2216         case DCERPC_PKT_ALTER_RESP:
2217                 DEBUG(0, ("process_complete_pdu: Error. "
2218                           "DCERPC_PKT_ALTER_RESP on pipe %s: "
2219                           "Should only be server -> client.\n",
2220                          get_pipe_name_from_syntax(talloc_tos(),
2221                                                    &p->syntax)));
2222                 break;
2223
2224         case DCERPC_PKT_AUTH3:
2225                 /*
2226                  * The third packet in an NTLMSSP auth exchange.
2227                  */
2228                 if (pipe_init_outgoing_data(p)) {
2229                         reply = api_pipe_bind_auth3(p, pkt);
2230                 }
2231                 break;
2232
2233         case DCERPC_PKT_SHUTDOWN:
2234                 DEBUG(0, ("process_complete_pdu: Error. "
2235                           "DCERPC_PKT_SHUTDOWN on pipe %s: "
2236                           "Should only be server -> client.\n",
2237                          get_pipe_name_from_syntax(talloc_tos(),
2238                                                    &p->syntax)));
2239                 break;
2240
2241         case DCERPC_PKT_CO_CANCEL:
2242                 /* For now just free all client data and continue
2243                  * processing. */
2244                 DEBUG(3,("process_complete_pdu: DCERPC_PKT_CO_CANCEL."
2245                          " Abandoning rpc call.\n"));
2246                 /* As we never do asynchronous RPC serving, we can
2247                  * never cancel a call (as far as I know).
2248                  * If we ever did we'd have to send a cancel_ack reply.
2249                  * For now, just free all client data and continue
2250                  * processing. */
2251                 reply = True;
2252                 break;
2253
2254 #if 0
2255                 /* Enable this if we're doing async rpc. */
2256                 /* We must check the outstanding callid matches. */
2257                 if (pipe_init_outgoing_data(p)) {
2258                         /* Send a cancel_ack PDU reply. */
2259                         /* We should probably check the auth-verifier here. */
2260                         reply = setup_cancel_ack_reply(p, pkt);
2261                 }
2262                 break;
2263 #endif
2264
2265         case DCERPC_PKT_ORPHANED:
2266                 /* We should probably check the auth-verifier here.
2267                  * For now just free all client data and continue
2268                  * processing. */
2269                 DEBUG(3, ("process_complete_pdu: DCERPC_PKT_ORPHANED."
2270                           " Abandoning rpc call.\n"));
2271                 reply = True;
2272                 break;
2273
2274         default:
2275                 DEBUG(0, ("process_complete_pdu: "
2276                           "Unknown rpc type = %u received.\n",
2277                           (unsigned int)pkt->ptype));
2278                 break;
2279         }
2280
2281 done:
2282         if (!reply) {
2283                 DEBUG(3,("process_complete_pdu: DCE/RPC fault sent on "
2284                          "pipe %s\n", get_pipe_name_from_syntax(talloc_tos(),
2285                                                                 &p->syntax)));
2286                 set_incoming_fault(p);
2287                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
2288                 TALLOC_FREE(pkt);
2289         } else {
2290                 /*
2291                  * Reset the lengths. We're ready for a new pdu.
2292                  */
2293                 TALLOC_FREE(p->in_data.pdu.data);
2294                 p->in_data.pdu_needed_len = 0;
2295                 p->in_data.pdu.length = 0;
2296         }
2297
2298         TALLOC_FREE(pkt);
2299 }
2300