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