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