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