fix schannel processing on fragmented PDUs. 'net rpc vampire' works again.
[ira/wip.git] / source3 / rpc_client / cli_pipe.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-1998,
5  *  Copyright (C) Luke Kenneth Casson Leighton 1996-1998,
6  *  Copyright (C) Paul Ashton                       1998.
7  *  Copyright (C) Jeremy Allison                    1999.
8  *  
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *  
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *  
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  */
23
24 #include "includes.h"
25
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_RPC_CLI
28
29 extern struct pipe_id_info pipe_names[];
30
31 static void get_auth_type_level(int pipe_auth_flags, int *auth_type, int *auth_level) 
32 {
33         *auth_type = 0;
34         *auth_level = 0;
35         if (pipe_auth_flags & AUTH_PIPE_SEAL) {
36                 *auth_level = RPC_PIPE_AUTH_SEAL_LEVEL;
37         } else if (pipe_auth_flags & AUTH_PIPE_SIGN) {
38                 *auth_level = RPC_PIPE_AUTH_SIGN_LEVEL;
39         }
40         
41         if (pipe_auth_flags & AUTH_PIPE_NETSEC) {
42                 *auth_type = NETSEC_AUTH_TYPE;
43         } else if (pipe_auth_flags & AUTH_PIPE_NTLMSSP) {
44                 *auth_type = NTLMSSP_AUTH_TYPE;
45         }
46 }
47
48 /********************************************************************
49  Rpc pipe call id.
50  ********************************************************************/
51
52 static uint32 get_rpc_call_id(void)
53 {
54         static uint32 call_id = 0;
55         return ++call_id;
56 }
57
58 /*******************************************************************
59  Use SMBreadX to get rest of one fragment's worth of rpc data.
60  ********************************************************************/
61
62 static BOOL rpc_read(struct cli_state *cli, prs_struct *rdata, uint32 data_to_read, uint32 *rdata_offset)
63 {
64         size_t size = (size_t)cli->max_recv_frag;
65         int stream_offset = 0;
66         int num_read;
67         char *pdata;
68         int extra_data_size = ((int)*rdata_offset) + ((int)data_to_read) - (int)prs_data_size(rdata);
69
70         DEBUG(5,("rpc_read: data_to_read: %u rdata offset: %u extra_data_size: %d\n",
71                 (int)data_to_read, (unsigned int)*rdata_offset, extra_data_size));
72
73         /*
74          * Grow the buffer if needed to accommodate the data to be read.
75          */
76
77         if (extra_data_size > 0) {
78                 if(!prs_force_grow(rdata, (uint32)extra_data_size)) {
79                         DEBUG(0,("rpc_read: Failed to grow parse struct by %d bytes.\n", extra_data_size ));
80                         return False;
81                 }
82                 DEBUG(5,("rpc_read: grew buffer by %d bytes to %u\n", extra_data_size, prs_data_size(rdata) ));
83         }
84
85         pdata = prs_data_p(rdata) + *rdata_offset;
86
87         do /* read data using SMBreadX */
88         {
89                 uint32 ecode;
90                 uint8 eclass;
91
92                 if (size > (size_t)data_to_read)
93                         size = (size_t)data_to_read;
94
95                 num_read = (int)cli_read(cli, cli->nt_pipe_fnum, pdata, (off_t)stream_offset, size);
96
97                 DEBUG(5,("rpc_read: num_read = %d, read offset: %d, to read: %d\n",
98                           num_read, stream_offset, data_to_read));
99
100                 if (cli_is_dos_error(cli)) {
101                         cli_dos_error(cli, &eclass, &ecode);
102                         if (eclass != ERRDOS && ecode != ERRmoredata) {
103                                 DEBUG(0,("rpc_read: Error %d/%u in cli_read\n",
104                                          eclass, (unsigned int)ecode));
105                                 return False;
106                         }
107                 }
108
109                 data_to_read -= num_read;
110                 stream_offset += num_read;
111                 pdata += num_read;
112
113         } while (num_read > 0 && data_to_read > 0);
114         /* && err == (0x80000000 | STATUS_BUFFER_OVERFLOW)); */
115
116         /*
117          * Update the current offset into rdata by the amount read.
118          */
119         *rdata_offset += stream_offset;
120
121         return True;
122 }
123
124 /****************************************************************************
125  Checks the header. This will set the endian bit in the rdata prs_struct. JRA.
126  ****************************************************************************/
127
128 static BOOL rpc_check_hdr(prs_struct *rdata, RPC_HDR *rhdr, 
129                           BOOL *first, BOOL *last, uint32 *len)
130 {
131         DEBUG(5,("rpc_check_hdr: rdata->data_size = %u\n", (uint32)prs_data_size(rdata) ));
132
133         /* Next call sets endian bit. */
134
135         if(!smb_io_rpc_hdr("rpc_hdr   ", rhdr, rdata, 0)) {
136                 DEBUG(0,("rpc_check_hdr: Failed to unmarshall RPC_HDR.\n"));
137                 return False;
138         }
139
140         if (prs_offset(rdata) != RPC_HEADER_LEN) {
141                 DEBUG(0,("rpc_check_hdr: offset was %x, should be %x.\n", prs_offset(rdata), RPC_HEADER_LEN));
142                 return False;
143         }
144
145         (*first) = ((rhdr->flags & RPC_FLG_FIRST) != 0);
146         (*last) = ((rhdr->flags & RPC_FLG_LAST ) != 0);
147         (*len) = (uint32)rhdr->frag_len - prs_data_size(rdata);
148
149         return (rhdr->pkt_type != RPC_FAULT);
150 }
151
152 /****************************************************************************
153  Verify data on an rpc pipe.
154  The VERIFY & SEAL code is only executed on packets that look like this :
155
156  Request/Response PDU's look like the following...
157
158  |<------------------PDU len----------------------------------------------->|
159  |<-HDR_LEN-->|<--REQ LEN------>|.............|<-AUTH_HDRLEN->|<-AUTH_LEN-->|
160
161  +------------+-----------------+-------------+---------------+-------------+
162  | RPC HEADER | REQ/RESP HEADER | DATA ...... | AUTH_HDR      | AUTH DATA   |
163  +------------+-----------------+-------------+---------------+-------------+
164
165  Never on bind requests/responses.
166  ****************************************************************************/
167
168 static BOOL rpc_auth_pipe(struct cli_state *cli, prs_struct *rdata,
169                           uint32 fragment_start, int len, int auth_len, uint8 pkt_type,
170                           int *pauth_padding_len)
171 {
172         
173         /*
174          * The following is that length of the data we must sign or seal.
175          * This doesn't include the RPC headers or the auth_len or the RPC_HDR_AUTH_LEN
176          * preceeding the auth_data.
177          */
178
179         int data_len = len - RPC_HEADER_LEN - RPC_HDR_RESP_LEN - RPC_HDR_AUTH_LEN - auth_len;
180
181         /*
182          * The start of the data to sign/seal is just after the RPC headers.
183          */
184         char *reply_data = prs_data_p(rdata) + fragment_start + RPC_HEADER_LEN + RPC_HDR_REQ_LEN;
185
186         RPC_HDR_AUTH rhdr_auth; 
187
188         *pauth_padding_len = 0;
189
190         if (auth_len == 0) {
191                 if (cli->pipe_auth_flags == 0) {
192                         /* move along, nothing to see here */
193                         return True;
194                 }
195
196                 DEBUG(2, ("No authenticaton header recienved on reply, but this pipe is authenticated\n"));
197                 return False;
198         }
199
200         DEBUG(5,("rpc_auth_pipe: pkt_type: %d len: %d auth_len: %d NTLMSSP %s schannel %s sign %s seal %s \n",
201                  pkt_type, len, auth_len, 
202                  BOOLSTR(cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP), 
203                  BOOLSTR(cli->pipe_auth_flags & AUTH_PIPE_NETSEC), 
204                  BOOLSTR(cli->pipe_auth_flags & AUTH_PIPE_SIGN), 
205                  BOOLSTR(cli->pipe_auth_flags & AUTH_PIPE_SEAL)));
206
207         {
208                 int auth_type;
209                 int auth_level;
210                 char *dp = prs_data_p(rdata) + fragment_start + len -
211                                         RPC_HDR_AUTH_LEN - auth_len;
212                 prs_struct auth_verf;
213
214                 if (dp - prs_data_p(rdata) > prs_data_size(rdata)) {
215                         DEBUG(0,("rpc_auth_pipe: schannel auth data > data size !\n"));
216                         return False;
217                 }
218
219                 DEBUG(10,("rpc_auth_pipe: packet:\n"));
220                 dump_data(100, dp, auth_len);
221
222                 prs_init(&auth_verf, RPC_HDR_AUTH_LEN, cli->mem_ctx, UNMARSHALL);
223
224                 /* The endinness must be preserved. JRA. */
225                 prs_set_endian_data( &auth_verf, rdata->bigendian_data);
226
227                 prs_copy_data_in(&auth_verf, dp, RPC_HDR_AUTH_LEN);
228                 prs_set_offset(&auth_verf, 0);
229
230
231                 if (!smb_io_rpc_hdr_auth("auth_hdr", &rhdr_auth, &auth_verf, 0)) {
232                         DEBUG(0, ("rpc_auth_pipe: Could not parse auth header\n"));
233                         return False;
234                 }
235
236                 /* Let the caller know how much padding at the end of the data */
237                 *pauth_padding_len = rhdr_auth.padding;
238                 
239                 /* Check it's the type of reply we were expecting to decode */
240
241                 get_auth_type_level(cli->pipe_auth_flags, &auth_type, &auth_level);
242                 if (rhdr_auth.auth_type != auth_type) {
243                         DEBUG(0, ("BAD auth type %d (should be %d)\n",
244                                   rhdr_auth.auth_type, auth_type));
245                         return False;
246                 }
247                 
248                 if (rhdr_auth.auth_level != auth_level) {
249                         DEBUG(0, ("BAD auth level %d (should be %d)\n", 
250                                   rhdr_auth.auth_level, auth_level));
251                         return False;
252                 }
253         }
254
255         if (pkt_type == RPC_BINDACK) {
256                 if (cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP) {
257                         char *dp = prs_data_p(rdata) + len - auth_len;
258                         
259                         if(dp - prs_data_p(rdata) > prs_data_size(rdata)) {
260                                 DEBUG(0,("rpc_auth_pipe: auth data > data size !\n"));
261                                 return False;
262                         }
263                         
264                         /* save the reply away, for use a little later */
265                         return (NT_STATUS_IS_OK(ntlmssp_client_store_response(cli->ntlmssp_pipe_state, 
266                                                                               data_blob(dp, auth_len))));
267                 }
268                 if (cli->pipe_auth_flags & AUTH_PIPE_NETSEC) {
269                         /* nothing to do here - we don't seem to be able to validate the
270                            bindack based on VL's comments */
271                         return True;
272                 }
273         }
274         
275         if (cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP) {
276                 NTSTATUS nt_status;
277                 DATA_BLOB sig;
278                 if ((cli->pipe_auth_flags & AUTH_PIPE_SIGN) ||
279                     (cli->pipe_auth_flags & AUTH_PIPE_SEAL)) {
280                         char *dp = prs_data_p(rdata) + len - auth_len;
281                         
282                         if(dp - prs_data_p(rdata) > prs_data_size(rdata)) {
283                                 DEBUG(0,("rpc_auth_pipe: auth data > data size !\n"));
284                                 return False;
285                         }
286                         
287                         if (auth_len != RPC_AUTH_NTLMSSP_CHK_LEN) {
288                                 DEBUG(0,("rpc_auth_pipe: wrong ntlmssp auth len %d\n", auth_len));
289                                 return False;
290                         }
291                         
292                         sig = data_blob(dp, auth_len);
293                 }
294         
295                 /*
296                  * Unseal any sealed data in the PDU, not including the
297                  * 8 byte auth_header or the auth_data.
298                  */
299
300                 /*
301                  * Now unseal and check the auth verifier in the auth_data at
302                  * the end of the packet. 
303                  */
304
305                 if (cli->pipe_auth_flags & AUTH_PIPE_SEAL) {
306                         if (data_len < 0) {
307                                 DEBUG(1, ("Can't unseal - data_len < 0!!\n"));
308                                 return False;
309                         }
310                         nt_status = ntlmssp_client_unseal_packet(cli->ntlmssp_pipe_state, 
311                                                      reply_data, data_len,
312                                                      &sig);
313                 } 
314                 else if (cli->pipe_auth_flags & AUTH_PIPE_SIGN) {
315                         nt_status = ntlmssp_client_check_packet(cli->ntlmssp_pipe_state, 
316                                                                 reply_data, data_len,
317                                                                 &sig);
318                 }
319
320                 data_blob_free(&sig);
321
322                 if (!NT_STATUS_IS_OK(nt_status)) {
323                         DEBUG(0, ("rpc_auth_pipe: could not validate "
324                                   "incoming NTLMSSP packet!\n"));
325                         return False;
326                 }
327         }
328
329         if (cli->pipe_auth_flags & AUTH_PIPE_NETSEC) {
330                 RPC_AUTH_NETSEC_CHK chk;
331                 prs_struct netsec_verf;
332
333                 char *dp = prs_data_p(rdata) + fragment_start + len - auth_len;
334                 
335                 if(dp - prs_data_p(rdata) > prs_data_size(rdata)) {
336                         DEBUG(0,("rpc_auth_pipe: auth data > data size !\n"));
337                         return False;
338                 }
339
340                 if (auth_len != RPC_AUTH_NETSEC_CHK_LEN) {
341                         DEBUG(0,("rpc_auth_pipe: wrong schannel auth len %d\n", auth_len));
342                         return False;
343                 }
344
345                 prs_init(&netsec_verf, RPC_AUTH_NETSEC_CHK_LEN, 
346                          cli->mem_ctx, UNMARSHALL);
347
348                 /* The endinness must be preserved. JRA. */
349                 prs_set_endian_data( &netsec_verf, rdata->bigendian_data);
350
351                 prs_copy_data_in(&netsec_verf, dp, auth_len);
352                 prs_set_offset(&netsec_verf, 0);
353
354                 if (!smb_io_rpc_auth_netsec_chk("schannel_auth_sign", 
355                                                 &chk, &netsec_verf, 0)) {
356                         DEBUG(0, ("rpc_auth_pipe: schannel unmarshalling "
357                                   "RPC_AUTH_NETSECK_CHK failed\n"));
358                         prs_mem_free(&netsec_verf);
359                         return False;
360                 }
361
362                 if (!netsec_decode(&cli->auth_info,
363                                    cli->pipe_auth_flags,
364                                    SENDER_IS_ACCEPTOR,
365                                    &chk, reply_data, data_len)) {
366                         DEBUG(0, ("rpc_auth_pipe: Could not decode schannel\n"));
367                         prs_mem_free(&netsec_verf);
368                         return False;
369                 }
370
371                 cli->auth_info.seq_num++;
372
373                 prs_mem_free(&netsec_verf);
374         }
375         return True;
376 }
377
378
379 /****************************************************************************
380  Send data on an rpc pipe via trans, which *must* be the last fragment.
381  receive response data from an rpc pipe, which may be large...
382
383  Read the first fragment: unfortunately have to use SMBtrans for the first
384  bit, then SMBreadX for subsequent bits.
385
386  If first fragment received also wasn't the last fragment, continue
387  getting fragments until we _do_ receive the last fragment.
388
389  Request/Response PDU's look like the following...
390
391  |<------------------PDU len----------------------------------------------->|
392  |<-HDR_LEN-->|<--REQ LEN------>|.............|<-AUTH_HDRLEN->|<-AUTH_LEN-->|
393
394  +------------+-----------------+-------------+---------------+-------------+
395  | RPC HEADER | REQ/RESP HEADER | DATA ...... | AUTH_HDR      | AUTH DATA   |
396  +------------+-----------------+-------------+---------------+-------------+
397
398  Where the presence of the AUTH_HDR and AUTH are dependent on the
399  signing & sealing being negotiated.
400
401  ****************************************************************************/
402
403 static BOOL rpc_api_pipe(struct cli_state *cli, prs_struct *data, prs_struct *rdata,
404                          uint8 expected_pkt_type)
405 {
406         uint32 len;
407         char *rparam = NULL;
408         uint32 rparam_len = 0;
409         uint16 setup[2];
410         BOOL first = True;
411         BOOL last  = True;
412         RPC_HDR rhdr;
413         char *pdata = data ? prs_data_p(data) : NULL;
414         uint32 data_len = data ? prs_offset(data) : 0;
415         char *prdata = NULL;
416         uint32 rdata_len = 0;
417         uint32 current_offset = 0;
418         uint32 fragment_start = 0;
419         uint32 max_data = cli->max_xmit_frag ? cli->max_xmit_frag : 1024;
420         int auth_padding_len = 0;
421
422         /* Create setup parameters - must be in native byte order. */
423
424         setup[0] = TRANSACT_DCERPCCMD; 
425         setup[1] = cli->nt_pipe_fnum; /* Pipe file handle. */
426
427         DEBUG(5,("rpc_api_pipe: fnum:%x\n", (int)cli->nt_pipe_fnum));
428
429         /* Send the RPC request and receive a response.  For short RPC
430            calls (about 1024 bytes or so) the RPC request and response
431            appears in a SMBtrans request and response.  Larger RPC
432            responses are received further on. */
433
434         if (!cli_api_pipe(cli, "\\PIPE\\",
435                   setup, 2, 0,                     /* Setup, length, max */
436                   NULL, 0, 0,                      /* Params, length, max */
437                   pdata, data_len, max_data,       /* data, length, max */
438                   &rparam, &rparam_len,            /* return params, len */
439                   &prdata, &rdata_len))            /* return data, len */
440         {
441                 DEBUG(0, ("cli_pipe: return critical error. Error was %s\n", cli_errstr(cli)));
442                 return False;
443         }
444
445         /* Throw away returned params - we know we won't use them. */
446
447         SAFE_FREE(rparam);
448
449         if (prdata == NULL) {
450                 DEBUG(0,("rpc_api_pipe: pipe %x failed to return data.\n",
451                         (int)cli->nt_pipe_fnum));
452                 return False;
453         }
454
455         /*
456          * Give this memory as dynamically allocated to the return parse
457          * struct.  
458          */
459
460         prs_give_memory(rdata, prdata, rdata_len, True);
461         current_offset = rdata_len;
462
463         /* This next call sets the endian bit correctly in rdata. */
464
465         if (!rpc_check_hdr(rdata, &rhdr, &first, &last, &len)) {
466                 prs_mem_free(rdata);
467                 return False;
468         }
469
470         if (rhdr.pkt_type == RPC_BINDACK) {
471                 if (!last && !first) {
472                         DEBUG(5,("rpc_api_pipe: bug in server (AS/U?), setting fragment first/last ON.\n"));
473                         first = True;
474                         last = True;
475                 }
476         }
477
478         if (rhdr.pkt_type == RPC_BINDNACK) {
479                 DEBUG(3, ("Bind NACK received on pipe %x!\n", (int)cli->nt_pipe_fnum));
480                 prs_mem_free(rdata);
481                 return False;
482         }
483
484         if (rhdr.pkt_type == RPC_RESPONSE) {
485                 RPC_HDR_RESP rhdr_resp;
486                 if(!smb_io_rpc_hdr_resp("rpc_hdr_resp", &rhdr_resp, rdata, 0)) {
487                         DEBUG(5,("rpc_api_pipe: failed to unmarshal RPC_HDR_RESP.\n"));
488                         prs_mem_free(rdata);
489                         return False;
490                 }
491         }
492
493         if (rhdr.pkt_type != expected_pkt_type) {
494                 DEBUG(3, ("Connection to pipe %x got an unexpected RPC packet type - %d, not %d\n", (int)cli->nt_pipe_fnum, rhdr.pkt_type, expected_pkt_type));
495                 prs_mem_free(rdata);
496                 return False;
497         }
498
499         DEBUG(5,("rpc_api_pipe: len left: %u smbtrans read: %u\n",
500                   (unsigned int)len, (unsigned int)rdata_len ));
501
502         /* check if data to be sent back was too large for one SMBtrans */
503         /* err status is only informational: the _real_ check is on the
504            length */
505
506         if (len > 0) { 
507                 /* || err == (0x80000000 | STATUS_BUFFER_OVERFLOW)) */
508
509                 /* Read the remaining part of the first response fragment */
510
511                 if (!rpc_read(cli, rdata, len, &current_offset)) {
512                         prs_mem_free(rdata);
513                         return False;
514                 }
515         }
516
517         /*
518          * Now we have a complete PDU, check the auth struct if any was sent.
519          */
520
521         if(!rpc_auth_pipe(cli, rdata, fragment_start, rhdr.frag_len,
522                           rhdr.auth_len, rhdr.pkt_type, &auth_padding_len)) {
523                 prs_mem_free(rdata);
524                 return False;
525         }
526
527         if (rhdr.auth_len != 0) {
528                 /*
529                  * Drop the auth footers from the current offset.
530                  * We need this if there are more fragments.
531                  * The auth footers consist of the auth_data and the
532                  * preceeding 8 byte auth_header.
533                  */
534                 current_offset -= (auth_padding_len + RPC_HDR_AUTH_LEN + rhdr.auth_len);
535         }
536         
537         /* 
538          * Only one rpc fragment, and it has been read.
539          */
540
541         if (first && last) {
542                 DEBUG(6,("rpc_api_pipe: fragment first and last both set\n"));
543                 return True;
544         }
545
546         /*
547          * Read more fragments using SMBreadX until we get one with the
548          * last bit set.
549          */
550
551         while (!last) {
552                 RPC_HDR_RESP rhdr_resp;
553                 int num_read;
554                 char hdr_data[RPC_HEADER_LEN+RPC_HDR_RESP_LEN];
555                 prs_struct hps;
556                 uint8 eclass;
557                 uint32 ecode;
558                 
559                 /*
560                  * First read the header of the next PDU.
561                  */
562
563                 prs_init(&hps, 0, cli->mem_ctx, UNMARSHALL);
564                 prs_give_memory(&hps, hdr_data, sizeof(hdr_data), False);
565
566                 num_read = cli_read(cli, cli->nt_pipe_fnum, hdr_data, 0, RPC_HEADER_LEN+RPC_HDR_RESP_LEN);
567                 if (cli_is_dos_error(cli)) {
568                         cli_dos_error(cli, &eclass, &ecode);
569                         if (eclass != ERRDOS && ecode != ERRmoredata) {
570                                 DEBUG(0,("rpc_api_pipe: cli_read error : %d/%d\n", eclass, ecode));
571                                 return False;
572                         }
573                 }
574
575                 DEBUG(5,("rpc_api_pipe: read header (size:%d)\n", num_read));
576
577                 if (num_read != RPC_HEADER_LEN+RPC_HDR_RESP_LEN) {
578                         DEBUG(0,("rpc_api_pipe: Error : requested %d bytes, got %d.\n",
579                                 RPC_HEADER_LEN+RPC_HDR_RESP_LEN, num_read ));
580                         return False;
581                 }
582
583                 /* This call sets the endianness in hps. */
584
585                 if (!rpc_check_hdr(&hps, &rhdr, &first, &last, &len))
586                         return False;
587
588                 /* Ensure the endianness in rdata is set correctly - must be same as hps. */
589
590                 if (hps.bigendian_data != rdata->bigendian_data) {
591                         DEBUG(0,("rpc_api_pipe: Error : Endianness changed from %s to %s\n",
592                                 rdata->bigendian_data ? "big" : "little",
593                                 hps.bigendian_data ? "big" : "little" ));
594                         return False;
595                 }
596
597                 if(!smb_io_rpc_hdr_resp("rpc_hdr_resp", &rhdr_resp, &hps, 0)) {
598                         DEBUG(0,("rpc_api_pipe: Error in unmarshalling RPC_HDR_RESP.\n"));
599                         return False;
600                 }
601
602                 if (first) {
603                         DEBUG(0,("rpc_api_pipe: secondary PDU rpc header has 'first' set !\n"));
604                         return False;
605                 }
606
607                 /*
608                  * Now read the rest of the PDU.
609                  */
610
611                 if (!rpc_read(cli, rdata, len, &current_offset)) {
612                         prs_mem_free(rdata);
613                         return False;
614                 }
615
616                 fragment_start = current_offset - len - RPC_HEADER_LEN - RPC_HDR_RESP_LEN;
617
618                 /*
619                  * Verify any authentication footer.
620                  */
621
622                 
623                 if(!rpc_auth_pipe(cli, rdata, fragment_start, rhdr.frag_len,
624                                   rhdr.auth_len, rhdr.pkt_type, &auth_padding_len)) {
625                         prs_mem_free(rdata);
626                         return False;
627                 }
628                 
629                 if (rhdr.auth_len != 0 ) {
630                         
631                         /*
632                          * Drop the auth footers from the current offset.
633                          * The auth footers consist of the auth_data and the
634                          * preceeding 8 byte auth_header.
635                          * We need this if there are more fragments.
636                          */
637                         current_offset -= (auth_padding_len + RPC_HDR_AUTH_LEN + rhdr.auth_len);
638                 }
639         }
640
641         return True;
642 }
643
644 /*******************************************************************
645  creates a DCE/RPC bind request
646
647  - initialises the parse structure.
648  - dynamically allocates the header data structure
649  - caller is expected to free the header data structure once used.
650
651  ********************************************************************/
652
653 static NTSTATUS create_rpc_bind_req(struct cli_state *cli, prs_struct *rpc_out, 
654                                     uint32 rpc_call_id,
655                                     RPC_IFACE *abstract, RPC_IFACE *transfer,
656                                     const char *my_name, const char *domain)
657 {
658         RPC_HDR hdr;
659         RPC_HDR_RB hdr_rb;
660         RPC_HDR_AUTH hdr_auth;
661         int auth_len = 0;
662         int auth_type, auth_level;
663         size_t saved_hdr_offset;
664
665         prs_struct auth_info;
666         prs_init(&auth_info, RPC_HDR_AUTH_LEN, /* we will need at least this much */
667                 prs_get_mem_context(rpc_out), MARSHALL);
668
669         if (cli->pipe_auth_flags) {
670                 get_auth_type_level(cli->pipe_auth_flags, &auth_type, &auth_level);
671                 
672                 /*
673                  * Create the auth structs we will marshall.
674                  */
675                 
676                 init_rpc_hdr_auth(&hdr_auth, auth_type, auth_level, 0x00, 1);
677                 
678                 /*
679                  * Now marshall the data into the temporary parse_struct.
680                  */
681                 
682                 if(!smb_io_rpc_hdr_auth("hdr_auth", &hdr_auth, &auth_info, 0)) {
683                         DEBUG(0,("create_rpc_bind_req: failed to marshall RPC_HDR_AUTH.\n"));
684                         prs_mem_free(&auth_info);
685                         return NT_STATUS_NO_MEMORY;
686                 }
687                 saved_hdr_offset = prs_offset(&auth_info);
688         }
689         
690         if (cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP) {
691
692                 NTSTATUS nt_status;
693                 DATA_BLOB null_blob = data_blob(NULL, 0);
694                 DATA_BLOB request;
695
696                 DEBUG(5, ("Processing NTLMSSP Negotiate\n"));
697                 nt_status = ntlmssp_client_update(cli->ntlmssp_pipe_state,
698                                                   null_blob,
699                                                   &request);
700
701                 if (!NT_STATUS_EQUAL(nt_status, 
702                                      NT_STATUS_MORE_PROCESSING_REQUIRED)) {
703                         prs_mem_free(&auth_info);
704                         return nt_status;
705                 }
706
707                 /* Auth len in the rpc header doesn't include auth_header. */
708                 auth_len = request.length;
709                 prs_copy_data_in(&auth_info, request.data, request.length);
710
711                 DEBUG(5, ("NTLMSSP Negotiate:\n"));
712                 dump_data(5, request.data, request.length);
713
714                 data_blob_free(&request);
715
716         } 
717         else if (cli->pipe_auth_flags & AUTH_PIPE_NETSEC) {
718                 RPC_AUTH_NETSEC_NEG netsec_neg;
719
720                 /* Use lp_workgroup() if domain not specified */
721
722                 if (!domain || !domain[0])
723                         domain = lp_workgroup();
724
725                 init_rpc_auth_netsec_neg(&netsec_neg, domain, my_name);
726
727                 /*
728                  * Now marshall the data into the temporary parse_struct.
729                  */
730
731                 if(!smb_io_rpc_auth_netsec_neg("netsec_neg",
732                                                &netsec_neg, &auth_info, 0)) {
733                         DEBUG(0,("Failed to marshall RPC_AUTH_NETSEC_NEG.\n"));
734                         prs_mem_free(&auth_info);
735                         return NT_STATUS_NO_MEMORY;
736                 }
737
738                 /* Auth len in the rpc header doesn't include auth_header. */
739                 auth_len = prs_offset(&auth_info) - saved_hdr_offset;
740         }
741         /* create the request RPC_HDR */
742         init_rpc_hdr(&hdr, RPC_BIND, 0x3, rpc_call_id, 
743                 RPC_HEADER_LEN + RPC_HDR_RB_LEN + prs_offset(&auth_info),
744                 auth_len);
745
746         if(!smb_io_rpc_hdr("hdr"   , &hdr, rpc_out, 0)) {
747                 DEBUG(0,("create_rpc_bind_req: failed to marshall RPC_HDR.\n"));
748                 prs_mem_free(&auth_info);
749                 return NT_STATUS_NO_MEMORY;
750         }
751
752         /* create the bind request RPC_HDR_RB */
753         init_rpc_hdr_rb(&hdr_rb, MAX_PDU_FRAG_LEN, MAX_PDU_FRAG_LEN, 0x0,
754                         0x1, 0x0, 0x1, abstract, transfer);
755
756         /* Marshall the bind request data */
757         if(!smb_io_rpc_hdr_rb("", &hdr_rb, rpc_out, 0)) {
758                 DEBUG(0,("create_rpc_bind_req: failed to marshall RPC_HDR_RB.\n"));
759                 prs_mem_free(&auth_info);
760                 return NT_STATUS_NO_MEMORY;
761         }
762
763         /*
764          * Grow the outgoing buffer to store any auth info.
765          */
766
767         if(auth_len != 0) {
768                 if(!prs_append_prs_data( rpc_out, &auth_info)) {
769                         DEBUG(0,("create_rpc_bind_req: failed to grow parse struct to add auth.\n"));
770                         prs_mem_free(&auth_info);
771                         return NT_STATUS_NO_MEMORY;
772                 }
773         }
774         return NT_STATUS_OK;
775 }
776
777 /*******************************************************************
778  Creates a DCE/RPC bind authentication response.
779  This is the packet that is sent back to the server once we
780  have received a BIND-ACK, to finish the third leg of
781  the authentication handshake.
782  ********************************************************************/
783
784 static NTSTATUS create_rpc_bind_resp(struct cli_state *cli,
785                                  uint32 rpc_call_id,
786                                  prs_struct *rpc_out)
787 {
788         NTSTATUS nt_status;
789         RPC_HDR hdr;
790         RPC_HDR_AUTHA hdr_autha;
791         DATA_BLOB ntlmssp_null_response = data_blob(NULL, 0);
792         DATA_BLOB ntlmssp_reply;
793         int auth_type, auth_level;
794
795         /* The response is picked up from the internal cache,
796            where it was placed by the rpc_auth_pipe() code */
797         nt_status = ntlmssp_client_update(cli->ntlmssp_pipe_state,
798                                           ntlmssp_null_response,
799                                           &ntlmssp_reply);
800         
801         if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
802                 return nt_status;
803         }
804
805         /* Create the request RPC_HDR */
806         init_rpc_hdr(&hdr, RPC_BINDRESP, 0x0, rpc_call_id,
807                      RPC_HEADER_LEN + RPC_HDR_AUTHA_LEN + ntlmssp_reply.length,
808                      ntlmssp_reply.length );
809         
810         /* Marshall it. */
811         if(!smb_io_rpc_hdr("hdr", &hdr, rpc_out, 0)) {
812                 DEBUG(0,("create_rpc_bind_resp: failed to marshall RPC_HDR.\n"));
813                 data_blob_free(&ntlmssp_reply);
814                 return NT_STATUS_NO_MEMORY;
815         }
816
817         get_auth_type_level(cli->pipe_auth_flags, &auth_type, &auth_level);
818         
819         /* Create the request RPC_HDR_AUTHA */
820         init_rpc_hdr_autha(&hdr_autha, MAX_PDU_FRAG_LEN, MAX_PDU_FRAG_LEN,
821                            auth_type, auth_level, 0x00);
822
823         if(!smb_io_rpc_hdr_autha("hdr_autha", &hdr_autha, rpc_out, 0)) {
824                 DEBUG(0,("create_rpc_bind_resp: failed to marshall RPC_HDR_AUTHA.\n"));
825                 data_blob_free(&ntlmssp_reply);
826                 return NT_STATUS_NO_MEMORY;
827         }
828
829         /*
830          * Append the auth data to the outgoing buffer.
831          */
832
833         if(!prs_copy_data_in(rpc_out, ntlmssp_reply.data, ntlmssp_reply.length)) {
834                 DEBUG(0,("create_rpc_bind_req: failed to grow parse struct to add auth.\n"));
835                 data_blob_free(&ntlmssp_reply);
836                 return NT_STATUS_NO_MEMORY;
837         }
838
839         if (cli->pipe_auth_flags & AUTH_PIPE_SIGN) {
840                 nt_status = ntlmssp_client_sign_init(cli->ntlmssp_pipe_state);
841                 
842                 if (!NT_STATUS_IS_OK(nt_status)) {
843                         return nt_status;
844                 }
845         }
846
847         data_blob_free(&ntlmssp_reply);
848         return NT_STATUS_OK;
849 }
850
851
852 /*******************************************************************
853  Creates a DCE/RPC request.
854  ********************************************************************/
855
856 static uint32 create_rpc_request(prs_struct *rpc_out, uint8 op_num, int data_len, int auth_len, uint8 flags, uint32 oldid, uint32 data_left)
857 {
858         uint32 alloc_hint;
859         RPC_HDR     hdr;
860         RPC_HDR_REQ hdr_req;
861         uint32 callid = oldid ? oldid : get_rpc_call_id();
862
863         DEBUG(5,("create_rpc_request: opnum: 0x%x data_len: 0x%x\n", op_num, data_len));
864
865         /* create the rpc header RPC_HDR */
866         init_rpc_hdr(&hdr, RPC_REQUEST, flags,
867                      callid, data_len, auth_len);
868
869         /*
870          * The alloc hint should be the amount of data, not including 
871          * RPC headers & footers.
872          */
873
874         if (auth_len != 0)
875                 alloc_hint = data_len - RPC_HEADER_LEN - RPC_HDR_AUTH_LEN - auth_len;
876         else
877                 alloc_hint = data_len - RPC_HEADER_LEN;
878
879         DEBUG(10,("create_rpc_request: data_len: %x auth_len: %x alloc_hint: %x\n",
880                    data_len, auth_len, alloc_hint));
881
882         /* Create the rpc request RPC_HDR_REQ */
883         init_rpc_hdr_req(&hdr_req, alloc_hint, op_num);
884
885         /* stream-time... */
886         if(!smb_io_rpc_hdr("hdr    ", &hdr, rpc_out, 0))
887                 return 0;
888
889         if(!smb_io_rpc_hdr_req("hdr_req", &hdr_req, rpc_out, 0))
890                 return 0;
891
892         if (prs_offset(rpc_out) != RPC_HEADER_LEN + RPC_HDR_REQ_LEN)
893                 return 0;
894
895         return callid;
896 }
897
898 /*******************************************************************
899  Puts an auth header into an rpc request.
900  ********************************************************************/
901
902 static BOOL create_auth_hdr(prs_struct *outgoing_packet, 
903                             int auth_type, 
904                             int auth_level, int padding)
905 {
906         RPC_HDR_AUTH hdr_auth;
907
908         init_rpc_hdr_auth(&hdr_auth, auth_type, auth_level,
909                           padding, 1);
910         if(!smb_io_rpc_hdr_auth("hdr_auth", &hdr_auth, 
911                                 outgoing_packet, 0)) {
912                 DEBUG(0,("create_auth_hdr:Failed to marshal RPC_HDR_AUTH.\n"));
913                 return False;
914         }
915         return True;
916 }
917
918 /**
919  * Send a request on an RPC pipe and get a response.
920  *
921  * @param data NDR contents of the request to be sent.
922  * @param rdata Unparsed NDR response data.
923 **/
924
925 BOOL rpc_api_pipe_req(struct cli_state *cli, uint8 op_num,
926                       prs_struct *data, prs_struct *rdata)
927 {
928         uint32 auth_len, real_auth_len, auth_hdr_len, max_data, data_left, data_sent;
929         NTSTATUS nt_status;
930         BOOL ret = False;
931         uint32 callid = 0;
932         fstring dump_name;
933
934         auth_len = 0;
935         real_auth_len = 0;
936         auth_hdr_len = 0;
937
938         if (cli->pipe_auth_flags & AUTH_PIPE_SIGN) {    
939                 if (cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP) { 
940                         auth_len = RPC_AUTH_NTLMSSP_CHK_LEN;
941                 }
942                 if (cli->pipe_auth_flags & AUTH_PIPE_NETSEC) {  
943                         auth_len = RPC_AUTH_NETSEC_CHK_LEN;
944                 }
945                 auth_hdr_len = RPC_HDR_AUTH_LEN;
946         }
947
948         /*
949          * calc how much actual data we can send in a PDU fragment
950          */
951         max_data = cli->max_xmit_frag - RPC_HEADER_LEN - RPC_HDR_REQ_LEN -
952                 auth_hdr_len - auth_len - 8;
953         
954         for (data_left = prs_offset(data), data_sent = 0; data_left > 0;) {
955                 prs_struct outgoing_packet;
956                 prs_struct sec_blob;
957                 uint32 data_len, send_size;
958                 uint8 flags = 0;
959                 uint32 auth_padding = 0;
960                 RPC_AUTH_NETSEC_CHK verf;
961                 DATA_BLOB sign_blob;
962
963                 /*
964                  * how much will we send this time
965                  */
966                 send_size = MIN(data_left, max_data);
967
968                 if (!prs_init(&sec_blob, send_size, /* will need at least this much */
969                               cli->mem_ctx, MARSHALL)) {
970                         DEBUG(0,("Could not malloc %u bytes",
971                                  send_size+auth_padding));
972                         return False;
973                 }
974
975                 if(!prs_append_some_prs_data(&sec_blob, data, 
976                                              data_sent, send_size)) {
977                         DEBUG(0,("Failed to append data to netsec blob\n"));
978                         prs_mem_free(&sec_blob);
979                         return False;
980                 }
981
982                 /*
983                  * NT expects the data that is sealed to be 8-byte
984                  * aligned. The padding must be encrypted as well and
985                  * taken into account when generating the
986                  * authentication verifier. The amount of padding must
987                  * be stored in the auth header.
988                  */
989
990                 if (cli->pipe_auth_flags) {
991                         size_t data_and_padding_size;
992                         int auth_type;
993                         int auth_level;
994                         prs_align_uint64(&sec_blob);
995
996                         get_auth_type_level(cli->pipe_auth_flags, &auth_type, &auth_level);
997
998                         data_and_padding_size = prs_offset(&sec_blob);
999                         auth_padding = data_and_padding_size - send_size;
1000
1001                         /* insert the auth header */
1002                         
1003                         if(!create_auth_hdr(&sec_blob, auth_type, auth_level, auth_padding)) {
1004                                 prs_mem_free(&sec_blob);
1005                                 return False;
1006                         }
1007                         
1008                         /* create an NTLMSSP signature */
1009                         if (cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP) {
1010                                 /*
1011                                  * Seal the outgoing data if requested.
1012                                  */
1013                                 if (cli->pipe_auth_flags & AUTH_PIPE_SEAL) {
1014                                         
1015                                         nt_status = ntlmssp_client_seal_packet(cli->ntlmssp_pipe_state,
1016                                                                                (unsigned char*)prs_data_p(&sec_blob),
1017                                                                                data_and_padding_size,
1018                                                                                &sign_blob);
1019                                         if (!NT_STATUS_IS_OK(nt_status)) {
1020                                                 prs_mem_free(&sec_blob);
1021                                                 return False;
1022                                         }
1023                                 } 
1024                                 else if (cli->pipe_auth_flags & AUTH_PIPE_SIGN) {
1025                                         
1026                                         nt_status = ntlmssp_client_sign_packet(cli->ntlmssp_pipe_state,
1027                                                                                (unsigned char*)prs_data_p(&sec_blob),
1028                                                                                data_and_padding_size, &sign_blob);
1029                                         if (!NT_STATUS_IS_OK(nt_status)) {
1030                                                 prs_mem_free(&sec_blob);
1031                                                 return False;
1032                                         }
1033                                 }
1034                                 
1035
1036                                 /* write auth footer onto the packet */
1037                                 real_auth_len = sign_blob.length;
1038                                 
1039                                 prs_copy_data_in(&sec_blob, sign_blob.data, sign_blob.length);
1040                                 data_blob_free(&sign_blob);
1041
1042                         }
1043                         else if (cli->pipe_auth_flags & AUTH_PIPE_NETSEC) {     
1044                                 static const uchar netsec_sig[8] = NETSEC_SIGNATURE;
1045                                 static const uchar nullbytes[8] = { 0,0,0,0,0,0,0,0 };
1046                                 size_t parse_offset_marker;
1047                                 if ((cli->auth_info.seq_num & 1) != 0) {
1048                                         DEBUG(0,("SCHANNEL ERROR: seq_num must be even in client (seq_num=%d)\n",
1049                                                  cli->auth_info.seq_num));
1050                                 }
1051                                 
1052                                 DEBUG(10,("SCHANNEL seq_num=%d\n", cli->auth_info.seq_num));
1053                                 
1054                                 init_rpc_auth_netsec_chk(&verf, netsec_sig, nullbytes,
1055                                                          nullbytes, nullbytes);
1056                                 
1057                                 netsec_encode(&cli->auth_info, 
1058                                               cli->pipe_auth_flags,
1059                                               SENDER_IS_INITIATOR,
1060                                               &verf,
1061                                               prs_data_p(&sec_blob),
1062                                               data_and_padding_size);
1063
1064                                 cli->auth_info.seq_num++;
1065
1066                                 /* write auth footer onto the packet */
1067                                 
1068                                 parse_offset_marker = prs_offset(&sec_blob);
1069                                 if (!smb_io_rpc_auth_netsec_chk("", &verf,
1070                                                                 &sec_blob, 0)) {
1071                                         prs_mem_free(&sec_blob);
1072                                         return False;
1073                                 }
1074                                 real_auth_len = prs_offset(&sec_blob) - parse_offset_marker;
1075                         }
1076                 }
1077
1078                 data_len = RPC_HEADER_LEN + RPC_HDR_REQ_LEN + prs_offset(&sec_blob);
1079
1080                 /*
1081                  * Malloc parse struct to hold it (and enough for alignments).
1082                  */
1083                 if(!prs_init(&outgoing_packet, data_len + 8, 
1084                              cli->mem_ctx, MARSHALL)) {
1085                         DEBUG(0,("rpc_api_pipe_req: Failed to malloc %u bytes.\n", (unsigned int)data_len ));
1086                         return False;
1087                 }
1088
1089                 if (data_left == prs_offset(data))
1090                         flags |= RPC_FLG_FIRST;
1091
1092                 if (data_left <= max_data)
1093                         flags |= RPC_FLG_LAST;
1094                 /*
1095                  * Write out the RPC header and the request header.
1096                  */
1097                 if(!(callid = create_rpc_request(&outgoing_packet, op_num, 
1098                                                  data_len, real_auth_len, flags, 
1099                                                  callid, data_left))) {
1100                         DEBUG(0,("rpc_api_pipe_req: Failed to create RPC request.\n"));
1101                         prs_mem_free(&outgoing_packet);
1102                         prs_mem_free(&sec_blob);
1103                         return False;
1104                 }
1105
1106                 prs_append_prs_data(&outgoing_packet, &sec_blob);
1107                 prs_mem_free(&sec_blob);
1108
1109                 DEBUG(100,("data_len: %x data_calc_len: %x\n", data_len, 
1110                            prs_offset(&outgoing_packet)));
1111                 
1112                 if (flags & RPC_FLG_LAST)
1113                         ret = rpc_api_pipe(cli, &outgoing_packet, 
1114                                            rdata, RPC_RESPONSE);
1115                 else {
1116                         cli_write(cli, cli->nt_pipe_fnum, 0x0008,
1117                                    prs_data_p(&outgoing_packet),
1118                                    data_sent, data_len);
1119                 }
1120                 prs_mem_free(&outgoing_packet);
1121                 data_sent += send_size;
1122                 data_left -= send_size;
1123         }
1124         /* Also capture received data */
1125         slprintf(dump_name, sizeof(dump_name) - 1, "reply_%s",
1126                  cli_pipe_get_name(cli));
1127         prs_dump(dump_name, op_num, rdata);
1128
1129         return ret;
1130 }
1131
1132 /****************************************************************************
1133  Set the handle state.
1134 ****************************************************************************/
1135
1136 static BOOL rpc_pipe_set_hnd_state(struct cli_state *cli, const char *pipe_name, uint16 device_state)
1137 {
1138         BOOL state_set = False;
1139         char param[2];
1140         uint16 setup[2]; /* only need 2 uint16 setup parameters */
1141         char *rparam = NULL;
1142         char *rdata = NULL;
1143         uint32 rparam_len, rdata_len;
1144
1145         if (pipe_name == NULL)
1146                 return False;
1147
1148         DEBUG(5,("Set Handle state Pipe[%x]: %s - device state:%x\n",
1149         cli->nt_pipe_fnum, pipe_name, device_state));
1150
1151         /* create parameters: device state */
1152         SSVAL(param, 0, device_state);
1153
1154         /* create setup parameters. */
1155         setup[0] = 0x0001; 
1156         setup[1] = cli->nt_pipe_fnum; /* pipe file handle.  got this from an SMBOpenX. */
1157
1158         /* send the data on \PIPE\ */
1159         if (cli_api_pipe(cli, "\\PIPE\\",
1160                     setup, 2, 0,                /* setup, length, max */
1161                     param, 2, 0,                /* param, length, max */
1162                     NULL, 0, 1024,              /* data, length, max */
1163                     &rparam, &rparam_len,        /* return param, length */
1164                     &rdata, &rdata_len))         /* return data, length */
1165         {
1166                 DEBUG(5, ("Set Handle state: return OK\n"));
1167                 state_set = True;
1168         }
1169
1170         SAFE_FREE(rparam);
1171         SAFE_FREE(rdata);
1172
1173         return state_set;
1174 }
1175
1176 /****************************************************************************
1177  check the rpc bind acknowledge response
1178 ****************************************************************************/
1179
1180 int get_pipe_index( const char *pipe_name )
1181 {
1182         int pipe_idx = 0;
1183
1184         while (pipe_names[pipe_idx].client_pipe != NULL) {
1185                 if (strequal(pipe_name, pipe_names[pipe_idx].client_pipe )) 
1186                         return pipe_idx;
1187                 pipe_idx++;
1188         };
1189
1190         return -1;
1191 }
1192
1193
1194 /****************************************************************************
1195  check the rpc bind acknowledge response
1196 ****************************************************************************/
1197
1198 const char* get_pipe_name_from_index( const int pipe_index )
1199 {
1200
1201         if ( (pipe_index < 0) || (pipe_index >= PI_MAX_PIPES) )
1202                 return NULL;
1203
1204         return pipe_names[pipe_index].client_pipe;              
1205 }
1206
1207 /****************************************************************************
1208  Check to see if this pipe index points to one of 
1209  the pipes only supported by Win2k
1210  ****************************************************************************/
1211
1212 BOOL is_win2k_pipe( const int pipe_idx )
1213 {
1214         switch ( pipe_idx )
1215         {
1216                 case PI_LSARPC_DS:
1217                         return True;
1218         }
1219         
1220         return False;
1221 }
1222
1223 /****************************************************************************
1224  check the rpc bind acknowledge response
1225 ****************************************************************************/
1226
1227 static BOOL valid_pipe_name(const int pipe_idx, RPC_IFACE *abstract, RPC_IFACE *transfer)
1228 {
1229         if ( pipe_idx >= PI_MAX_PIPES ) {
1230                 DEBUG(0,("valid_pipe_name: Programmer error!  Invalid pipe index [%d]\n",
1231                         pipe_idx));
1232                 return False;
1233         }
1234
1235         DEBUG(5,("Bind Abstract Syntax: "));    
1236         dump_data(5, (char*)&(pipe_names[pipe_idx].abstr_syntax), 
1237                   sizeof(pipe_names[pipe_idx].abstr_syntax));
1238         DEBUG(5,("Bind Transfer Syntax: "));
1239         dump_data(5, (char*)&(pipe_names[pipe_idx].trans_syntax),
1240                   sizeof(pipe_names[pipe_idx].trans_syntax));
1241
1242         /* copy the required syntaxes out so we can do the right bind */
1243         
1244         *transfer = pipe_names[pipe_idx].trans_syntax;
1245         *abstract = pipe_names[pipe_idx].abstr_syntax;
1246
1247         return True;
1248 }
1249
1250 /****************************************************************************
1251  check the rpc bind acknowledge response
1252 ****************************************************************************/
1253
1254 static BOOL check_bind_response(RPC_HDR_BA *hdr_ba, const int pipe_idx, RPC_IFACE *transfer)
1255 {
1256         int i = 0;
1257
1258         if ( hdr_ba->addr.len <= 0)
1259                 return False;
1260                 
1261         if ( !strequal(hdr_ba->addr.str, pipe_names[pipe_idx].server_pipe )) 
1262         {
1263                 DEBUG(4,("bind_rpc_pipe: pipe_name %s != expected pipe %s.  oh well!\n",
1264                          pipe_names[i].server_pipe ,hdr_ba->addr.str));
1265                 return False;
1266         }
1267         
1268         DEBUG(5,("bind_rpc_pipe: server pipe_name found: %s\n", pipe_names[i].server_pipe ));
1269
1270         if (pipe_names[pipe_idx].server_pipe == NULL) {
1271                 DEBUG(2,("bind_rpc_pipe: pipe name %s unsupported\n", hdr_ba->addr.str));
1272                 return False;
1273         }
1274
1275         /* check the transfer syntax */
1276         if ((hdr_ba->transfer.version != transfer->version) ||
1277              (memcmp(&hdr_ba->transfer.uuid, &transfer->uuid, sizeof(transfer->uuid)) !=0)) {
1278                 DEBUG(2,("bind_rpc_pipe: transfer syntax differs\n"));
1279                 return False;
1280         }
1281
1282         /* lkclXXXX only accept one result: check the result(s) */
1283         if (hdr_ba->res.num_results != 0x1 || hdr_ba->res.result != 0) {
1284                 DEBUG(2,("bind_rpc_pipe: bind denied results: %d reason: %x\n",
1285                           hdr_ba->res.num_results, hdr_ba->res.reason));
1286         }
1287
1288         DEBUG(5,("bind_rpc_pipe: accepted!\n"));
1289         return True;
1290 }
1291
1292 /****************************************************************************
1293  Create and send the third packet in an RPC auth.
1294 ****************************************************************************/
1295
1296 static BOOL rpc_send_auth_reply(struct cli_state *cli, prs_struct *rdata, uint32 rpc_call_id)
1297 {
1298         prs_struct rpc_out;
1299         ssize_t ret;
1300
1301         prs_init(&rpc_out, RPC_HEADER_LEN + RPC_HDR_AUTHA_LEN, /* need at least this much */ 
1302                  cli->mem_ctx, MARSHALL);
1303
1304         create_rpc_bind_resp(cli, rpc_call_id,
1305                              &rpc_out);
1306
1307         if ((ret = cli_write(cli, cli->nt_pipe_fnum, 0x8, prs_data_p(&rpc_out), 
1308                         0, (size_t)prs_offset(&rpc_out))) != (ssize_t)prs_offset(&rpc_out)) {
1309                 DEBUG(0,("rpc_send_auth_reply: cli_write failed. Return was %d\n", (int)ret));
1310                 prs_mem_free(&rpc_out);
1311                 return False;
1312         }
1313
1314         prs_mem_free(&rpc_out);
1315         return True;
1316 }
1317
1318 /****************************************************************************
1319  Do an rpc bind.
1320 ****************************************************************************/
1321
1322 static BOOL rpc_pipe_bind(struct cli_state *cli, int pipe_idx, const char *my_name)
1323 {
1324         RPC_IFACE abstract;
1325         RPC_IFACE transfer;
1326         prs_struct rpc_out;
1327         prs_struct rdata;
1328         uint32 rpc_call_id;
1329         char buffer[MAX_PDU_FRAG_LEN];
1330
1331         if ( (pipe_idx < 0) || (pipe_idx >= PI_MAX_PIPES) )
1332                 return False;
1333
1334         DEBUG(5,("Bind RPC Pipe[%x]: %s\n", cli->nt_pipe_fnum, pipe_names[pipe_idx].client_pipe));
1335
1336         if (!valid_pipe_name(pipe_idx, &abstract, &transfer))
1337                 return False;
1338
1339         prs_init(&rpc_out, 0, cli->mem_ctx, MARSHALL);
1340
1341         /*
1342          * Use the MAX_PDU_FRAG_LEN buffer to store the bind request.
1343          */
1344
1345         prs_give_memory( &rpc_out, buffer, sizeof(buffer), False);
1346
1347         rpc_call_id = get_rpc_call_id();
1348
1349         if (cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP) {
1350                 NTSTATUS nt_status;
1351                 fstring password;
1352
1353                 DEBUG(5, ("NTLMSSP authenticated pipe selected\n"));
1354
1355                 nt_status = ntlmssp_client_start(&cli->ntlmssp_pipe_state);
1356                 
1357                 if (!NT_STATUS_IS_OK(nt_status))
1358                         return False;
1359
1360                 nt_status = ntlmssp_set_username(cli->ntlmssp_pipe_state, 
1361                                                  cli->user_name);
1362                 if (!NT_STATUS_IS_OK(nt_status))
1363                         return False;
1364
1365                 nt_status = ntlmssp_set_domain(cli->ntlmssp_pipe_state, 
1366                                                cli->domain);    
1367                 if (!NT_STATUS_IS_OK(nt_status))
1368                         return False;
1369
1370                 pwd_get_cleartext(&cli->pwd, password);
1371                 nt_status = ntlmssp_set_password(cli->ntlmssp_pipe_state, 
1372                                                  password);
1373                 if (!NT_STATUS_IS_OK(nt_status))
1374                         return False;
1375
1376                 if (cli->pipe_auth_flags & AUTH_PIPE_SIGN) {
1377                         cli->ntlmssp_pipe_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1378                 }
1379
1380                 if (cli->pipe_auth_flags & AUTH_PIPE_SEAL) {
1381                         cli->ntlmssp_pipe_state->neg_flags |= NTLMSSP_NEGOTIATE_SEAL;
1382                 }
1383         } else if (cli->pipe_auth_flags & AUTH_PIPE_NETSEC) {
1384                 cli->auth_info.seq_num = 0;
1385         }
1386
1387         /* Marshall the outgoing data. */
1388         create_rpc_bind_req(cli, &rpc_out, rpc_call_id,
1389                             &abstract, &transfer,
1390                             global_myname(), cli->domain);
1391
1392         /* Initialize the incoming data struct. */
1393         prs_init(&rdata, 0, cli->mem_ctx, UNMARSHALL);
1394
1395         /* send data on \PIPE\.  receive a response */
1396         if (rpc_api_pipe(cli, &rpc_out, &rdata, RPC_BINDACK)) {
1397                 RPC_HDR_BA   hdr_ba;
1398
1399                 DEBUG(5, ("rpc_pipe_bind: rpc_api_pipe returned OK.\n"));
1400
1401                 if(!smb_io_rpc_hdr_ba("", &hdr_ba, &rdata, 0)) {
1402                         DEBUG(0,("rpc_pipe_bind: Failed to unmarshall RPC_HDR_BA.\n"));
1403                         prs_mem_free(&rdata);
1404                         return False;
1405                 }
1406
1407                 if(!check_bind_response(&hdr_ba, pipe_idx, &transfer)) {
1408                         DEBUG(2,("rpc_pipe_bind: check_bind_response failed.\n"));
1409                         prs_mem_free(&rdata);
1410                         return False;
1411                 }
1412
1413                 cli->max_xmit_frag = hdr_ba.bba.max_tsize;
1414                 cli->max_recv_frag = hdr_ba.bba.max_rsize;
1415
1416                 /*
1417                  * If we're doing NTLMSSP auth we need to send a reply to
1418                  * the bind-ack to complete the 3-way challenge response
1419                  * handshake.
1420                  */
1421
1422                 if ((cli->pipe_auth_flags & AUTH_PIPE_NTLMSSP) 
1423                     && !rpc_send_auth_reply(cli, &rdata, rpc_call_id)) {
1424                         DEBUG(0,("rpc_pipe_bind: rpc_send_auth_reply failed.\n"));
1425                         prs_mem_free(&rdata);
1426                         return False;
1427                 }
1428                 prs_mem_free(&rdata);
1429                 return True;
1430         }
1431
1432         return False;
1433 }
1434
1435 /****************************************************************************
1436  Open a session.
1437  ****************************************************************************/
1438
1439 BOOL cli_nt_session_open(struct cli_state *cli, const int pipe_idx)
1440 {
1441         int fnum;
1442
1443         /* At the moment we can't have more than one pipe open over
1444            a cli connection. )-: */
1445
1446         SMB_ASSERT(cli->nt_pipe_fnum == 0);
1447         
1448         /* The pipe index must fall within our array */
1449
1450         SMB_ASSERT((pipe_idx >= 0) && (pipe_idx < PI_MAX_PIPES));
1451
1452         if (cli->capabilities & CAP_NT_SMBS) {
1453                 if ((fnum = cli_nt_create(cli, &pipe_names[pipe_idx].client_pipe[5], DESIRED_ACCESS_PIPE)) == -1) {
1454                         DEBUG(0,("cli_nt_session_open: cli_nt_create failed on pipe %s to machine %s.  Error was %s\n",
1455                                  &pipe_names[pipe_idx].client_pipe[5], cli->desthost, cli_errstr(cli)));
1456                         return False;
1457                 }
1458
1459                 cli->nt_pipe_fnum = (uint16)fnum;
1460         } else {
1461                 if ((fnum = cli_open(cli, pipe_names[pipe_idx].client_pipe, O_CREAT|O_RDWR, DENY_NONE)) == -1) {
1462                         DEBUG(0,("cli_nt_session_open: cli_open failed on pipe %s to machine %s.  Error was %s\n",
1463                                  pipe_names[pipe_idx].client_pipe, cli->desthost, cli_errstr(cli)));
1464                         return False;
1465                 }
1466
1467                 cli->nt_pipe_fnum = (uint16)fnum;
1468
1469                 /**************** Set Named Pipe State ***************/
1470                 if (!rpc_pipe_set_hnd_state(cli, pipe_names[pipe_idx].client_pipe, 0x4300)) {
1471                         DEBUG(0,("cli_nt_session_open: pipe hnd state failed.  Error was %s\n",
1472                                   cli_errstr(cli)));
1473                         cli_close(cli, cli->nt_pipe_fnum);
1474                         return False;
1475                 }
1476         }
1477
1478         /******************* bind request on pipe *****************/
1479
1480         if (!rpc_pipe_bind(cli, pipe_idx, global_myname())) {
1481                 DEBUG(2,("cli_nt_session_open: rpc bind to %s failed\n",
1482                          get_pipe_name_from_index(pipe_idx)));
1483                 cli_close(cli, cli->nt_pipe_fnum);
1484                 return False;
1485         }
1486
1487         /* 
1488          * Setup the remote server name prefixed by \ and the machine account name.
1489          */
1490
1491         fstrcpy(cli->srv_name_slash, "\\\\");
1492         fstrcat(cli->srv_name_slash, cli->desthost);
1493         strupper_m(cli->srv_name_slash);
1494
1495         fstrcpy(cli->clnt_name_slash, "\\\\");
1496         fstrcat(cli->clnt_name_slash, global_myname());
1497         strupper_m(cli->clnt_name_slash);
1498
1499         fstrcpy(cli->mach_acct, global_myname());
1500         fstrcat(cli->mach_acct, "$");
1501         strupper_m(cli->mach_acct);
1502
1503         /* Remember which pipe we're talking to */
1504         fstrcpy(cli->pipe_name, pipe_names[pipe_idx].client_pipe);
1505
1506         return True;
1507 }
1508
1509
1510 /****************************************************************************
1511  Open a session to the NETLOGON pipe using schannel.
1512
1513  (Assumes that the netlogon pipe is already open)
1514  ****************************************************************************/
1515
1516 NTSTATUS cli_nt_establish_netlogon(struct cli_state *cli, int sec_chan,
1517                                    const uchar trust_password[16])
1518 {
1519         NTSTATUS result;        
1520         uint32 neg_flags = 0x000001ff;
1521         int fnum;
1522
1523         cli_nt_netlogon_netsec_session_close(cli);
1524
1525         if (lp_client_schannel() != False)
1526                 neg_flags |= NETLOGON_NEG_SCHANNEL;
1527
1528         result = cli_nt_setup_creds(cli, sec_chan, trust_password,
1529                                     &neg_flags, 2);
1530
1531         if (!NT_STATUS_IS_OK(result)) {
1532                 cli_nt_session_close(cli);
1533                 return result;
1534         }
1535
1536         if ((lp_client_schannel() == True) &&
1537             ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
1538
1539                 DEBUG(3, ("Server did not offer schannel\n"));
1540                 cli_nt_session_close(cli);
1541                 return NT_STATUS_UNSUCCESSFUL;
1542         }
1543
1544         if ((lp_client_schannel() == False) ||
1545             ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
1546                 return NT_STATUS_OK;
1547                 
1548                 /* keep the existing connection to NETLOGON open */
1549
1550         }
1551
1552         /* Server offered schannel, so try it. */
1553
1554         memcpy(cli->auth_info.sess_key, cli->sess_key,
1555                sizeof(cli->auth_info.sess_key));
1556
1557         cli->saved_netlogon_pipe_fnum = cli->nt_pipe_fnum;
1558
1559         cli->pipe_auth_flags = AUTH_PIPE_NETSEC;
1560         cli->pipe_auth_flags |= AUTH_PIPE_SIGN;
1561         cli->pipe_auth_flags |= AUTH_PIPE_SEAL;
1562
1563         if (cli->capabilities & CAP_NT_SMBS) {
1564
1565                 /* The secure channel connection must be opened on the same 
1566                    session (TCP connection) as the one the challenge was
1567                    requested from. */
1568                 if ((fnum = cli_nt_create(cli, PIPE_NETLOGON_PLAIN,
1569                                           DESIRED_ACCESS_PIPE)) == -1) {
1570                         DEBUG(0,("cli_nt_create failed to %s machine %s. "
1571                                  "Error was %s\n",
1572                                  PIPE_NETLOGON, cli->desthost,
1573                                  cli_errstr(cli)));
1574                         return NT_STATUS_UNSUCCESSFUL;
1575                 }
1576                 
1577                 cli->nt_pipe_fnum = (uint16)fnum;
1578         } else {
1579                 if ((fnum = cli_open(cli, PIPE_NETLOGON,
1580                                      O_CREAT|O_RDWR, DENY_NONE)) == -1) {
1581                         DEBUG(0,("cli_open failed on pipe %s to machine %s. "
1582                                  "Error was %s\n",
1583                                  PIPE_NETLOGON, cli->desthost,
1584                                  cli_errstr(cli)));
1585                         return NT_STATUS_UNSUCCESSFUL;
1586                 }
1587
1588                 cli->nt_pipe_fnum = (uint16)fnum;
1589
1590                 /**************** Set Named Pipe State ***************/
1591                 if (!rpc_pipe_set_hnd_state(cli, PIPE_NETLOGON, 0x4300)) {
1592                         DEBUG(0,("Pipe hnd state failed.  Error was %s\n",
1593                                   cli_errstr(cli)));
1594                         cli_close(cli, cli->nt_pipe_fnum);
1595                         return NT_STATUS_UNSUCCESSFUL;
1596                 }
1597         }
1598         
1599         /* doing schannel, not per-user auth */
1600         cli->pipe_auth_flags = AUTH_PIPE_NETSEC | AUTH_PIPE_SIGN | AUTH_PIPE_SEAL;
1601         
1602         if (!rpc_pipe_bind(cli, PI_NETLOGON, global_myname())) {
1603                 DEBUG(2,("rpc bind to %s failed\n", PIPE_NETLOGON));
1604                 cli_close(cli, cli->nt_pipe_fnum);
1605                 return NT_STATUS_UNSUCCESSFUL;
1606         }
1607
1608         return NT_STATUS_OK;
1609 }
1610
1611
1612 const char *cli_pipe_get_name(struct cli_state *cli)
1613 {
1614         return cli->pipe_name;
1615 }
1616
1617