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