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