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