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