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