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