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