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