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