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