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