This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[samba.git] / source / rpc_server / srv_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                  1997-1998,
7  *  Copyright (C) Jeremy Allison                    1999,
8  *  Copyright (C) Anthony Liguori                   2003.
9  *  
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *  
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *  
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 /*  this module apparently provides an implementation of DCE/RPC over a
26  *  named pipe (IPC$ connection using SMBtrans).  details of DCE/RPC
27  *  documentation are available (in on-line form) from the X-Open group.
28  *
29  *  this module should provide a level of abstraction between SMB
30  *  and DCE/RPC, while minimising the amount of mallocs, unnecessary
31  *  data copies, and network traffic.
32  *
33  *  in this version, which takes a "let's learn what's going on and
34  *  get something running" approach, there is additional network
35  *  traffic generated, but the code should be easier to understand...
36  *
37  *  ... if you read the docs.  or stare at packets for weeks on end.
38  *
39  */
40
41 #include "includes.h"
42
43 #undef DBGC_CLASS
44 #define DBGC_CLASS DBGC_RPC_SRV
45
46 /*************************************************************
47  HACK Alert!
48  We need to transfer the session key from one rpc bind to the
49  next. This is the way the netlogon schannel works.
50 **************************************************************/
51 struct dcinfo last_dcinfo;
52
53 static void NTLMSSPcalc_p( pipes_struct *p, unsigned char *data, int len)
54 {
55     unsigned char *hash = p->ntlmssp_hash;
56     unsigned char index_i = hash[256];
57     unsigned char index_j = hash[257];
58     int ind;
59
60     for( ind = 0; ind < len; ind++) {
61         unsigned char tc;
62         unsigned char t;
63
64         index_i++;
65         index_j += hash[index_i];
66
67         tc = hash[index_i];
68         hash[index_i] = hash[index_j];
69         hash[index_j] = tc;
70
71         t = hash[index_i] + hash[index_j];
72         data[ind] = data[ind] ^ hash[t];
73     }
74
75     hash[256] = index_i;
76     hash[257] = index_j;
77 }
78
79 /*******************************************************************
80  Generate the next PDU to be returned from the data in p->rdata. 
81  We cheat here as this function doesn't handle the special auth
82  footers of the authenticated bind response reply.
83  ********************************************************************/
84
85 BOOL create_next_pdu(pipes_struct *p)
86 {
87         RPC_HDR_RESP hdr_resp;
88         BOOL auth_verify = ((p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SIGN) != 0);
89         BOOL auth_seal   = ((p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SEAL) != 0);
90         uint32 data_len;
91         uint32 data_space_available;
92         uint32 data_len_left;
93         prs_struct outgoing_pdu;
94         uint32 data_pos;
95
96         /*
97          * If we're in the fault state, keep returning fault PDU's until
98          * the pipe gets closed. JRA.
99          */
100
101         if(p->fault_state) {
102                 setup_fault_pdu(p, NT_STATUS(0x1c010002));
103                 return True;
104         }
105
106         memset((char *)&hdr_resp, '\0', sizeof(hdr_resp));
107
108         /* Change the incoming request header to a response. */
109         p->hdr.pkt_type = RPC_RESPONSE;
110
111         /* Set up rpc header flags. */
112         if (p->out_data.data_sent_length == 0)
113                 p->hdr.flags = RPC_FLG_FIRST;
114         else
115                 p->hdr.flags = 0;
116
117         /*
118          * Work out how much we can fit in a single PDU.
119          */
120
121         data_space_available = sizeof(p->out_data.current_pdu) - RPC_HEADER_LEN - RPC_HDR_RESP_LEN;
122         if(p->ntlmssp_auth_validated)
123                 data_space_available -= (RPC_HDR_AUTH_LEN + RPC_AUTH_NTLMSSP_CHK_LEN);
124
125         if(p->netsec_auth_validated)
126                 data_space_available -= (RPC_HDR_AUTH_LEN + RPC_AUTH_NETSEC_CHK_LEN);
127
128         /*
129          * The amount we send is the minimum of the available
130          * space and the amount left to send.
131          */
132
133         data_len_left = prs_offset(&p->out_data.rdata) - p->out_data.data_sent_length;
134
135         /*
136          * Ensure there really is data left to send.
137          */
138
139         if(!data_len_left) {
140                 DEBUG(0,("create_next_pdu: no data left to send !\n"));
141                 return False;
142         }
143
144         data_len = MIN(data_len_left, data_space_available);
145
146         /*
147          * Set up the alloc hint. This should be the data left to
148          * send.
149          */
150
151         hdr_resp.alloc_hint = data_len_left;
152
153         /*
154          * Set up the header lengths.
155          */
156
157         if (p->ntlmssp_auth_validated) {
158                 p->hdr.frag_len = RPC_HEADER_LEN + RPC_HDR_RESP_LEN + data_len +
159                                         RPC_HDR_AUTH_LEN + RPC_AUTH_NTLMSSP_CHK_LEN;
160                 p->hdr.auth_len = RPC_AUTH_NTLMSSP_CHK_LEN;
161         } else if (p->netsec_auth_validated) {
162                 p->hdr.frag_len = RPC_HEADER_LEN + RPC_HDR_RESP_LEN + data_len +
163                         RPC_HDR_AUTH_LEN + RPC_AUTH_NETSEC_CHK_LEN;
164                 p->hdr.auth_len = RPC_AUTH_NETSEC_CHK_LEN;
165         } else {
166                 p->hdr.frag_len = RPC_HEADER_LEN + RPC_HDR_RESP_LEN + data_len;
167                 p->hdr.auth_len = 0;
168         }
169
170         /*
171          * Work out if this PDU will be the last.
172          */
173
174         if(p->out_data.data_sent_length + data_len >= prs_offset(&p->out_data.rdata))
175                 p->hdr.flags |= RPC_FLG_LAST;
176
177         /*
178          * Init the parse struct to point at the outgoing
179          * data.
180          */
181
182         prs_init( &outgoing_pdu, 0, p->mem_ctx, MARSHALL);
183         prs_give_memory( &outgoing_pdu, (char *)p->out_data.current_pdu, sizeof(p->out_data.current_pdu), False);
184
185         /* Store the header in the data stream. */
186         if(!smb_io_rpc_hdr("hdr", &p->hdr, &outgoing_pdu, 0)) {
187                 DEBUG(0,("create_next_pdu: failed to marshall RPC_HDR.\n"));
188                 prs_mem_free(&outgoing_pdu);
189                 return False;
190         }
191
192         if(!smb_io_rpc_hdr_resp("resp", &hdr_resp, &outgoing_pdu, 0)) {
193                 DEBUG(0,("create_next_pdu: failed to marshall RPC_HDR_RESP.\n"));
194                 prs_mem_free(&outgoing_pdu);
195                 return False;
196         }
197
198         /* Store the current offset. */
199         data_pos = prs_offset(&outgoing_pdu);
200
201         /* Copy the data into the PDU. */
202
203         if(!prs_append_some_prs_data(&outgoing_pdu, &p->out_data.rdata, p->out_data.data_sent_length, data_len)) {
204                 DEBUG(0,("create_next_pdu: failed to copy %u bytes of data.\n", (unsigned int)data_len));
205                 prs_mem_free(&outgoing_pdu);
206                 return False;
207         }
208
209         if (p->ntlmssp_auth_validated) {
210                 uint32 crc32 = 0;
211                 char *data;
212
213                 DEBUG(5,("create_next_pdu: sign: %s seal: %s data %d auth %d\n",
214                          BOOLSTR(auth_verify), BOOLSTR(auth_seal), data_len, p->hdr.auth_len));
215
216                 /*
217                  * Set data to point to where we copied the data into.
218                  */
219
220                 data = prs_data_p(&outgoing_pdu) + data_pos;
221
222                 if (auth_seal) {
223                         crc32 = crc32_calc_buffer(data, data_len);
224                         NTLMSSPcalc_p(p, (uchar*)data, data_len);
225                 }
226
227                 if (auth_seal || auth_verify) {
228                         RPC_HDR_AUTH auth_info;
229
230                         init_rpc_hdr_auth(&auth_info, NTLMSSP_AUTH_TYPE, NTLMSSP_AUTH_LEVEL, 
231                                         (auth_verify ? RPC_HDR_AUTH_LEN : 0), (auth_verify ? 1 : 0));
232                         if(!smb_io_rpc_hdr_auth("hdr_auth", &auth_info, &outgoing_pdu, 0)) {
233                                 DEBUG(0,("create_next_pdu: failed to marshall RPC_HDR_AUTH.\n"));
234                                 prs_mem_free(&outgoing_pdu);
235                                 return False;
236                         }
237                 }
238
239                 if (auth_verify) {
240                         RPC_AUTH_NTLMSSP_CHK ntlmssp_chk;
241                         char *auth_data = prs_data_p(&outgoing_pdu);
242
243                         p->ntlmssp_seq_num++;
244                         init_rpc_auth_ntlmssp_chk(&ntlmssp_chk, NTLMSSP_SIGN_VERSION,
245                                         crc32, p->ntlmssp_seq_num++);
246                         auth_data = prs_data_p(&outgoing_pdu) + prs_offset(&outgoing_pdu) + 4;
247                         if(!smb_io_rpc_auth_ntlmssp_chk("auth_sign", &ntlmssp_chk, &outgoing_pdu, 0)) {
248                                 DEBUG(0,("create_next_pdu: failed to marshall RPC_AUTH_NTLMSSP_CHK.\n"));
249                                 prs_mem_free(&outgoing_pdu);
250                                 return False;
251                         }
252                         NTLMSSPcalc_p(p, (uchar*)auth_data, RPC_AUTH_NTLMSSP_CHK_LEN - 4);
253                 }
254         }
255
256         if (p->netsec_auth_validated) {
257                 char *data;
258                 RPC_HDR_AUTH auth_info;
259                 static const uchar netsec_sig[8] = NETSEC_SIGNATURE;
260                 static const uchar nullbytes[8] = { 0,0,0,0,0,0,0,0 };
261
262                 RPC_AUTH_NETSEC_CHK verf;
263                 prs_struct rverf;
264                 prs_struct rauth;
265
266                 uchar sign[8];
267
268                 data = prs_data_p(&outgoing_pdu) + data_pos;
269
270                 init_rpc_hdr_auth(&auth_info, NETSEC_AUTH_TYPE, NETSEC_AUTH_LEVEL, 
271                                   RPC_HDR_AUTH_LEN, 1);
272
273                 if(!smb_io_rpc_hdr_auth("hdr_auth", &auth_info, &outgoing_pdu, 0)) {
274                         DEBUG(0,("create_next_pdu: failed to marshall RPC_HDR_AUTH.\n"));
275                         prs_mem_free(&outgoing_pdu);
276                         return False;
277                 }
278
279                 prs_init(&rverf, 0, p->mem_ctx, MARSHALL);
280                 prs_init(&rauth, 0, p->mem_ctx, MARSHALL);
281
282                 memset(sign, 0, sizeof(sign));
283                 sign[3] = 0x01;
284
285                 init_rpc_auth_netsec_chk(&verf, netsec_sig, nullbytes, sign, nullbytes);
286
287                 if (!netsec_encode(&p->netsec_auth, &verf, data, data_len)) {
288                         DEBUG(0,("create_next_pdu: failed encode data.\n"));
289                         prs_mem_free(&outgoing_pdu);
290                         return False;
291                 }
292
293                 smb_io_rpc_auth_netsec_chk("", &verf, &outgoing_pdu, 0);
294                 p->netsec_auth.seq_num++;
295         }
296
297         /*
298          * Setup the counts for this PDU.
299          */
300
301         p->out_data.data_sent_length += data_len;
302         p->out_data.current_pdu_len = p->hdr.frag_len;
303         p->out_data.current_pdu_sent = 0;
304
305         prs_mem_free(&outgoing_pdu);
306         return True;
307 }
308
309 /*******************************************************************
310  Process an NTLMSSP authentication response.
311  If this function succeeds, the user has been authenticated
312  and their domain, name and calling workstation stored in
313  the pipe struct.
314  The initial challenge is stored in p->challenge.
315  *******************************************************************/
316
317 static BOOL api_pipe_ntlmssp_verify(pipes_struct *p, RPC_AUTH_NTLMSSP_RESP *ntlmssp_resp)
318 {
319         uchar lm_owf[24];
320         uchar nt_owf[128];
321         int nt_pw_len;
322         int lm_pw_len;
323         fstring user_name;
324         fstring domain;
325         fstring wks;
326
327         NTSTATUS nt_status;
328
329         struct auth_context *auth_context = NULL;
330         auth_usersupplied_info *user_info = NULL;
331         auth_serversupplied_info *server_info = NULL;
332
333         DEBUG(5,("api_pipe_ntlmssp_verify: checking user details\n"));
334
335         memset(p->user_name, '\0', sizeof(p->user_name));
336         memset(p->pipe_user_name, '\0', sizeof(p->pipe_user_name));
337         memset(p->domain, '\0', sizeof(p->domain));
338         memset(p->wks, '\0', sizeof(p->wks));
339
340         /* Set up for non-authenticated user. */
341         delete_nt_token(&p->pipe_user.nt_user_token);
342         p->pipe_user.ngroups = 0;
343         SAFE_FREE( p->pipe_user.groups);
344
345         /* 
346          * Setup an empty password for a guest user.
347          */
348
349         /*
350          * We always negotiate UNICODE.
351          */
352
353         if (p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_UNICODE) {
354                 rpcstr_pull(user_name, ntlmssp_resp->user, sizeof(fstring), ntlmssp_resp->hdr_usr.str_str_len*2, 0 );
355                 rpcstr_pull(domain, ntlmssp_resp->domain, sizeof(fstring), ntlmssp_resp->hdr_domain.str_str_len*2, 0);
356                 rpcstr_pull(wks, ntlmssp_resp->wks, sizeof(fstring), ntlmssp_resp->hdr_wks.str_str_len*2, 0);
357         } else {
358                 pull_ascii_fstring(user_name, ntlmssp_resp->user);
359                 pull_ascii_fstring(domain, ntlmssp_resp->domain);
360                 pull_ascii_fstring(wks, ntlmssp_resp->wks);
361         }
362
363         DEBUG(5,("user: %s domain: %s wks: %s\n", user_name, domain, wks));
364
365         nt_pw_len = MIN(sizeof(nt_owf), ntlmssp_resp->hdr_nt_resp.str_str_len);
366         lm_pw_len = MIN(sizeof(lm_owf), ntlmssp_resp->hdr_lm_resp.str_str_len);
367
368         memcpy(lm_owf, ntlmssp_resp->lm_resp, sizeof(lm_owf));
369         memcpy(nt_owf, ntlmssp_resp->nt_resp, nt_pw_len);
370
371 #ifdef DEBUG_PASSWORD
372         DEBUG(100,("lm, nt owfs, chal\n"));
373         dump_data(100, (char *)lm_owf, sizeof(lm_owf));
374         dump_data(100, (char *)nt_owf, nt_pw_len);
375         dump_data(100, (char *)p->challenge, 8);
376 #endif
377
378         /*
379          * Allow guest access. Patch from Shirish Kalele <kalele@veritas.com>.
380          */
381
382         if (*user_name) {
383
384                 /* 
385                  * Do the length checking only if user is not NULL.
386                  */
387
388                 if (ntlmssp_resp->hdr_lm_resp.str_str_len == 0)
389                         return False;
390                 if (ntlmssp_resp->hdr_nt_resp.str_str_len == 0)
391                         return False;
392                 if (ntlmssp_resp->hdr_usr.str_str_len == 0)
393                         return False;
394                 if (ntlmssp_resp->hdr_domain.str_str_len == 0)
395                         return False;
396                 if (ntlmssp_resp->hdr_wks.str_str_len == 0)
397                         return False;
398
399         }
400         
401         make_auth_context_fixed(&auth_context, (uchar*)p->challenge);
402
403         if (!make_user_info_netlogon_network(&user_info, 
404                                              user_name, domain, wks,
405                                              lm_owf, lm_pw_len, 
406                                              nt_owf, nt_pw_len)) {
407                 DEBUG(0,("make_user_info_netlogon_network failed!  Failing authenticaion.\n"));
408                 return False;
409         }
410         
411         nt_status = auth_context->check_ntlm_password(auth_context, user_info, &server_info); 
412         
413         (auth_context->free)(&auth_context);
414         free_user_info(&user_info);
415         
416         p->ntlmssp_auth_validated = NT_STATUS_IS_OK(nt_status);
417         
418         if (!p->ntlmssp_auth_validated) {
419                 DEBUG(1,("api_pipe_ntlmssp_verify: User [%s]\\[%s] from machine %s \
420 failed authentication on named pipe %s.\n", domain, user_name, wks, p->name ));
421                 free_server_info(&server_info);
422                 return False;
423         }
424
425         /*
426          * Set up the sign/seal data.
427          */
428
429         {
430                 uchar p24[24];
431                 NTLMSSPOWFencrypt(server_info->first_8_lm_hash, lm_owf, p24);
432                 {
433                         unsigned char j = 0;
434                         int ind;
435
436                         unsigned char k2[8];
437
438                         memcpy(k2, p24, 5);
439                         k2[5] = 0xe5;
440                         k2[6] = 0x38;
441                         k2[7] = 0xb0;
442
443                         for (ind = 0; ind < 256; ind++)
444                                 p->ntlmssp_hash[ind] = (unsigned char)ind;
445
446                         for( ind = 0; ind < 256; ind++) {
447                                 unsigned char tc;
448
449                                 j += (p->ntlmssp_hash[ind] + k2[ind%8]);
450
451                                 tc = p->ntlmssp_hash[ind];
452                                 p->ntlmssp_hash[ind] = p->ntlmssp_hash[j];
453                                 p->ntlmssp_hash[j] = tc;
454                         }
455
456                         p->ntlmssp_hash[256] = 0;
457                         p->ntlmssp_hash[257] = 0;
458                 }
459 /*              NTLMSSPhash(p->ntlmssp_hash, p24); */
460                 p->ntlmssp_seq_num = 0;
461
462         }
463
464         fstrcpy(p->user_name, user_name);
465         fstrcpy(p->pipe_user_name, pdb_get_username(server_info->sam_account));
466         fstrcpy(p->domain, domain);
467         fstrcpy(p->wks, wks);
468
469         /*
470          * Store the UNIX credential data (uid/gid pair) in the pipe structure.
471          */
472
473         if (!IS_SAM_UNIX_USER(server_info->sam_account)) {
474                 DEBUG(0,("Attempted authenticated pipe with invalid user.  No uid/gid in SAM_ACCOUNT\n"));
475                 free_server_info(&server_info);
476                 return False;
477         }
478         
479         memcpy(p->session_key, server_info->session_key, sizeof(p->session_key));
480
481         p->pipe_user.uid = pdb_get_uid(server_info->sam_account);
482         p->pipe_user.gid = pdb_get_gid(server_info->sam_account);
483         
484         p->pipe_user.ngroups = server_info->n_groups;
485         if (p->pipe_user.ngroups) {
486                 if (!(p->pipe_user.groups = memdup(server_info->groups, sizeof(gid_t) * p->pipe_user.ngroups))) {
487                         DEBUG(0,("failed to memdup group list to p->pipe_user.groups\n"));
488                         free_server_info(&server_info);
489                         return False;
490                 }
491         }
492
493         if (server_info->ptok)
494                 p->pipe_user.nt_user_token = dup_nt_token(server_info->ptok);
495         else {
496                 DEBUG(1,("Error: Authmodule failed to provide nt_user_token\n"));
497                 p->pipe_user.nt_user_token = NULL;
498                 free_server_info(&server_info);
499                 return False;
500         }
501
502         p->ntlmssp_auth_validated = True;
503
504         free_server_info(&server_info);
505         return True;
506 }
507
508 /*******************************************************************
509  The switch table for the pipe names and the functions to handle them.
510  *******************************************************************/
511
512 struct api_cmd
513 {
514   const char *name;
515   int (*init)(void);
516 };
517
518 static struct api_cmd api_fd_commands[] =
519 {
520 #ifndef RPC_LSA_DYNAMIC
521     { "lsarpc",   rpc_lsa_init },
522 #endif
523 #ifndef RPC_SAMR_DYNAMIC
524     { "samr",     rpc_samr_init },
525 #endif
526 #ifndef RPC_SVC_DYNAMIC
527     { "srvsvc",   rpc_srv_init },
528 #endif
529 #ifndef RPC_WKS_DYNAMIC
530     { "wkssvc",   rpc_wks_init },
531 #endif
532 #ifndef RPC_NETLOG_DYNAMIC
533     { "NETLOGON", rpc_net_init },
534 #endif
535 #ifndef RPC_REG_DYNAMIC
536     { "winreg",   rpc_reg_init },
537 #endif
538 #ifndef RPC_SPOOLSS_DYNAMIC
539     { "spoolss",  rpc_spoolss_init },
540 #endif
541 #ifndef RPC_DFS_DYNAMIC
542     { "netdfs",   rpc_dfs_init },
543 #endif
544     { NULL, NULL }
545 };
546
547 struct rpc_table
548 {
549   struct
550   {
551     const char *clnt;
552     const char *srv;
553   } pipe;
554   struct api_struct *cmds;
555   int n_cmds;
556 };
557
558 static struct rpc_table *rpc_lookup;
559 static int rpc_lookup_size;
560
561 /*******************************************************************
562  This is the client reply to our challenge for an authenticated 
563  bind request. The challenge we sent is in p->challenge.
564 *******************************************************************/
565
566 BOOL api_pipe_bind_auth_resp(pipes_struct *p, prs_struct *rpc_in_p)
567 {
568         RPC_HDR_AUTHA autha_info;
569         RPC_AUTH_VERIFIER auth_verifier;
570         RPC_AUTH_NTLMSSP_RESP ntlmssp_resp;
571
572         DEBUG(5,("api_pipe_bind_auth_resp: decode request. %d\n", __LINE__));
573
574         if (p->hdr.auth_len == 0) {
575                 DEBUG(0,("api_pipe_bind_auth_resp: No auth field sent !\n"));
576                 return False;
577         }
578
579         /*
580          * Decode the authentication verifier response.
581          */
582
583         if(!smb_io_rpc_hdr_autha("", &autha_info, rpc_in_p, 0)) {
584                 DEBUG(0,("api_pipe_bind_auth_resp: unmarshall of RPC_HDR_AUTHA failed.\n"));
585                 return False;
586         }
587
588         if (autha_info.auth_type != NTLMSSP_AUTH_TYPE || autha_info.auth_level != NTLMSSP_AUTH_LEVEL) {
589                 DEBUG(0,("api_pipe_bind_auth_resp: incorrect auth type (%d) or level (%d).\n",
590                         (int)autha_info.auth_type, (int)autha_info.auth_level ));
591                 return False;
592         }
593
594         if(!smb_io_rpc_auth_verifier("", &auth_verifier, rpc_in_p, 0)) {
595                 DEBUG(0,("api_pipe_bind_auth_resp: unmarshall of RPC_AUTH_VERIFIER failed.\n"));
596                 return False;
597         }
598
599         /*
600          * Ensure this is a NTLMSSP_AUTH packet type.
601          */
602
603         if (!rpc_auth_verifier_chk(&auth_verifier, "NTLMSSP", NTLMSSP_AUTH)) {
604                 DEBUG(0,("api_pipe_bind_auth_resp: rpc_auth_verifier_chk failed.\n"));
605                 return False;
606         }
607
608         if(!smb_io_rpc_auth_ntlmssp_resp("", &ntlmssp_resp, rpc_in_p, 0)) {
609                 DEBUG(0,("api_pipe_bind_auth_resp: Failed to unmarshall RPC_AUTH_NTLMSSP_RESP.\n"));
610                 return False;
611         }
612
613         /*
614          * The following call actually checks the challenge/response data.
615          * for correctness against the given DOMAIN\user name.
616          */
617         
618         if (!api_pipe_ntlmssp_verify(p, &ntlmssp_resp))
619                 return False;
620
621         p->pipe_bound = True
622 ;
623         return True;
624 }
625
626 /*******************************************************************
627  Marshall a bind_nak pdu.
628 *******************************************************************/
629
630 static BOOL setup_bind_nak(pipes_struct *p)
631 {
632         prs_struct outgoing_rpc;
633         RPC_HDR nak_hdr;
634         uint16 zero = 0;
635
636         /* Free any memory in the current return data buffer. */
637         prs_mem_free(&p->out_data.rdata);
638
639         /*
640          * Marshall directly into the outgoing PDU space. We
641          * must do this as we need to set to the bind response
642          * header and are never sending more than one PDU here.
643          */
644
645         prs_init( &outgoing_rpc, 0, p->mem_ctx, MARSHALL);
646         prs_give_memory( &outgoing_rpc, (char *)p->out_data.current_pdu, sizeof(p->out_data.current_pdu), False);
647
648
649         /*
650          * Initialize a bind_nak header.
651          */
652
653         init_rpc_hdr(&nak_hdr, RPC_BINDNACK, RPC_FLG_FIRST | RPC_FLG_LAST,
654             p->hdr.call_id, RPC_HEADER_LEN + sizeof(uint16), 0);
655
656         /*
657          * Marshall the header into the outgoing PDU.
658          */
659
660         if(!smb_io_rpc_hdr("", &nak_hdr, &outgoing_rpc, 0)) {
661                 DEBUG(0,("setup_bind_nak: marshalling of RPC_HDR failed.\n"));
662                 prs_mem_free(&outgoing_rpc);
663                 return False;
664         }
665
666         /*
667          * Now add the reject reason.
668          */
669
670         if(!prs_uint16("reject code", &outgoing_rpc, 0, &zero)) {
671                 prs_mem_free(&outgoing_rpc);
672         return False;
673         }
674
675         p->out_data.data_sent_length = 0;
676         p->out_data.current_pdu_len = prs_offset(&outgoing_rpc);
677         p->out_data.current_pdu_sent = 0;
678
679         p->pipe_bound = False;
680
681         return True;
682 }
683
684 /*******************************************************************
685  Marshall a fault pdu.
686 *******************************************************************/
687
688 BOOL setup_fault_pdu(pipes_struct *p, NTSTATUS status)
689 {
690         prs_struct outgoing_pdu;
691         RPC_HDR fault_hdr;
692         RPC_HDR_RESP hdr_resp;
693         RPC_HDR_FAULT fault_resp;
694
695         /* Free any memory in the current return data buffer. */
696         prs_mem_free(&p->out_data.rdata);
697
698         /*
699          * Marshall directly into the outgoing PDU space. We
700          * must do this as we need to set to the bind response
701          * header and are never sending more than one PDU here.
702          */
703
704         prs_init( &outgoing_pdu, 0, p->mem_ctx, MARSHALL);
705         prs_give_memory( &outgoing_pdu, (char *)p->out_data.current_pdu, sizeof(p->out_data.current_pdu), False);
706
707         /*
708          * Initialize a fault header.
709          */
710
711         init_rpc_hdr(&fault_hdr, RPC_FAULT, RPC_FLG_FIRST | RPC_FLG_LAST | RPC_FLG_NOCALL,
712             p->hdr.call_id, RPC_HEADER_LEN + RPC_HDR_RESP_LEN + RPC_HDR_FAULT_LEN, 0);
713
714         /*
715          * Initialize the HDR_RESP and FAULT parts of the PDU.
716          */
717
718         memset((char *)&hdr_resp, '\0', sizeof(hdr_resp));
719
720         fault_resp.status = status;
721         fault_resp.reserved = 0;
722
723         /*
724          * Marshall the header into the outgoing PDU.
725          */
726
727         if(!smb_io_rpc_hdr("", &fault_hdr, &outgoing_pdu, 0)) {
728                 DEBUG(0,("setup_fault_pdu: marshalling of RPC_HDR failed.\n"));
729                 prs_mem_free(&outgoing_pdu);
730                 return False;
731         }
732
733         if(!smb_io_rpc_hdr_resp("resp", &hdr_resp, &outgoing_pdu, 0)) {
734                 DEBUG(0,("setup_fault_pdu: failed to marshall RPC_HDR_RESP.\n"));
735                 prs_mem_free(&outgoing_pdu);
736                 return False;
737         }
738
739         if(!smb_io_rpc_hdr_fault("fault", &fault_resp, &outgoing_pdu, 0)) {
740                 DEBUG(0,("setup_fault_pdu: failed to marshall RPC_HDR_FAULT.\n"));
741                 prs_mem_free(&outgoing_pdu);
742                 return False;
743         }
744
745         p->out_data.data_sent_length = 0;
746         p->out_data.current_pdu_len = prs_offset(&outgoing_pdu);
747         p->out_data.current_pdu_sent = 0;
748
749         prs_mem_free(&outgoing_pdu);
750         return True;
751 }
752
753 /*******************************************************************
754  Ensure a bind request has the correct abstract & transfer interface.
755  Used to reject unknown binds from Win2k.
756 *******************************************************************/
757
758 BOOL check_bind_req(char* pipe_name, RPC_IFACE* abstract,
759                                         RPC_IFACE* transfer)
760 {
761         extern struct pipe_id_info pipe_names[];
762         int i=0;
763         fstring pname;
764         fstrcpy(pname,"\\PIPE\\");
765         fstrcat(pname,pipe_name);
766
767         DEBUG(3,("check_bind_req for %s\n", pname));
768
769 #ifndef SUPPORT_NEW_LSARPC_UUID
770
771         /* check for the first pipe matching the name */
772         
773         for ( i=0; pipe_names[i].client_pipe; i++ ) {
774                 if ( strequal(pipe_names[i].client_pipe, pname) )
775                         break;
776         }
777 #else
778         /* we have to check all now since win2k introduced a new UUID on the lsaprpc pipe */
779                 
780         for ( i=0; pipe_names[i].client_pipe; i++ ) 
781         {
782                 if ( strequal(pipe_names[i].client_pipe, pname)
783                         && (abstract->version == pipe_names[i].abstr_syntax.version) 
784                         && (memcmp(&abstract->uuid, &pipe_names[i].abstr_syntax.uuid, sizeof(RPC_UUID)) == 0)
785                         && (transfer->version == pipe_names[i].trans_syntax.version)
786                         && (memcmp(&transfer->uuid, &pipe_names[i].trans_syntax.uuid, sizeof(RPC_UUID)) == 0) )
787                 {
788                         break;
789                 }
790         }
791 #endif
792
793         if(pipe_names[i].client_pipe == NULL)
794                 return False;
795
796 #ifndef SUPPORT_NEW_LSARPC_UUID
797         /* check the abstract interface */
798         if ( (abstract->version != pipe_names[i].abstr_syntax.version) 
799                 || (memcmp(&abstract->uuid, &pipe_names[i].abstr_syntax.uuid, sizeof(RPC_UUID)) != 0) )
800         {
801                 return False;
802         }
803
804         /* check the transfer interface */
805         if ( (transfer->version != pipe_names[i].trans_syntax.version) 
806                 || (memcmp(&transfer->uuid, &pipe_names[i].trans_syntax.uuid, sizeof(RPC_UUID)) != 0) )
807         {
808                 return False;
809         }
810 #endif
811         return True;
812 }
813
814 /*******************************************************************
815  Register commands to an RPC pipe
816 *******************************************************************/
817 int rpc_pipe_register_commands(const char *clnt, const char *srv, const struct api_struct *cmds, int size)
818 {
819         struct rpc_table *rpc_entry;
820
821
822         /* We use a temporary variable because this call can fail and 
823            rpc_lookup will still be valid afterwards.  It could then succeed if
824            called again later */
825         rpc_entry = realloc(rpc_lookup, 
826                             ++rpc_lookup_size*sizeof(struct rpc_table));
827         if (NULL == rpc_entry) {
828                 rpc_lookup_size--;
829                 DEBUG(0, ("rpc_pipe_register_commands: memory allocation failed\n"));
830                 return 0;
831         } else {
832                 rpc_lookup = rpc_entry;
833         }
834         
835         rpc_entry = rpc_lookup + (rpc_lookup_size - 1);
836         ZERO_STRUCTP(rpc_entry);
837         rpc_entry->pipe.clnt = strdup(clnt);
838         rpc_entry->pipe.srv = strdup(srv);
839         rpc_entry->cmds = realloc(rpc_entry->cmds, 
840                                   (rpc_entry->n_cmds + size) *
841                                   sizeof(struct api_struct));
842         memcpy(rpc_entry->cmds + rpc_entry->n_cmds, cmds,
843                size * sizeof(struct api_struct));
844         rpc_entry->n_cmds += size;
845         
846         return size;
847 }
848
849 /*******************************************************************
850  Register commands to an RPC pipe
851 *******************************************************************/
852 int rpc_load_module(const char *module)
853 {
854 #ifdef HAVE_DLOPEN
855         void *handle;
856         int (*module_init)(void);
857         pstring full_path;
858         const char *error;
859         
860         pstrcpy(full_path, lib_path("rpc"));
861         pstrcat(full_path, "/librpc_");
862         pstrcat(full_path, module);
863         pstrcat(full_path, ".");
864         pstrcat(full_path, shlib_ext());
865
866         handle = sys_dlopen(full_path, RTLD_LAZY);
867         if (!handle) {
868                 DEBUG(0, ("Could not load requested pipe %s as %s\n", 
869                     module, full_path));
870                 DEBUG(0, (" Error: %s\n", dlerror()));
871                 return 0;
872         }
873         
874         DEBUG(3, ("Module '%s' loaded\n", full_path));
875         
876         module_init = sys_dlsym(handle, "rpc_pipe_init");
877         if ((error = sys_dlerror()) != NULL) {
878                 DEBUG(0, ("Error trying to resolve symbol 'rpc_pipe_init' in %s: %s\n",
879                           full_path, error));
880                 return 0;
881         }
882         
883         return module_init();
884 #else
885         DEBUG(0,("Attempting to load a dynamic RPC pipe when dlopen isn't available\n"));
886         return 0;
887 #endif
888 }
889
890 /*******************************************************************
891  Respond to a pipe bind request.
892 *******************************************************************/
893
894 BOOL api_pipe_bind_req(pipes_struct *p, prs_struct *rpc_in_p)
895 {
896         RPC_HDR_BA hdr_ba;
897         RPC_HDR_RB hdr_rb;
898         RPC_HDR_AUTH auth_info;
899         uint16 assoc_gid;
900         fstring ack_pipe_name;
901         prs_struct out_hdr_ba;
902         prs_struct out_auth;
903         prs_struct outgoing_rpc;
904         int i = 0;
905         int auth_len = 0;
906         enum RPC_PKT_TYPE reply_pkt_type;
907
908         p->ntlmssp_auth_requested = False;
909         p->netsec_auth_validated = False;
910
911         DEBUG(5,("api_pipe_bind_req: decode request. %d\n", __LINE__));
912
913         /*
914          * Try and find the correct pipe name to ensure
915          * that this is a pipe name we support.
916          */
917
918
919         for (i = 0; i < rpc_lookup_size; i++) {
920                 if (strequal(rpc_lookup[i].pipe.clnt, p->name)) {
921                   DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
922                             rpc_lookup[i].pipe.clnt, rpc_lookup[i].pipe.srv));
923                   fstrcpy(p->pipe_srv_name, rpc_lookup[i].pipe.srv);
924                   break;
925                 }
926         }
927
928         if (i == rpc_lookup_size) {
929                 for (i = 0; api_fd_commands[i].name; i++) {
930                        if (strequal(api_fd_commands[i].name, p->name)) {
931                                api_fd_commands[i].init();
932                                break;
933                        }
934                 }
935
936                 if (!api_fd_commands[i].name && !rpc_load_module(p->name)) {
937                        DEBUG(3,("api_pipe_bind_req: Unknown pipe name %s in bind request.\n",
938                                 p->name ));
939                        if(!setup_bind_nak(p))
940                                return False;
941                        return True;
942                 }
943
944                 for (i = 0; i < rpc_lookup_size; i++) {
945                        if (strequal(rpc_lookup[i].pipe.clnt, p->name)) {
946                                DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
947                                          rpc_lookup[i].pipe.clnt, rpc_lookup[i].pipe.srv));
948                                fstrcpy(p->pipe_srv_name, rpc_lookup[i].pipe.srv);
949                                break;
950                        }
951                 }
952         }
953
954         /* decode the bind request */
955         if(!smb_io_rpc_hdr_rb("", &hdr_rb, rpc_in_p, 0))  {
956                 DEBUG(0,("api_pipe_bind_req: unable to unmarshall RPC_HDR_RB struct.\n"));
957                 return False;
958         }
959
960         /*
961          * Check if this is an authenticated request.
962          */
963
964         if (p->hdr.auth_len != 0) {
965                 RPC_AUTH_VERIFIER auth_verifier;
966                 RPC_AUTH_NTLMSSP_NEG ntlmssp_neg;
967
968                 /* 
969                  * Decode the authentication verifier.
970                  */
971
972                 if(!smb_io_rpc_hdr_auth("", &auth_info, rpc_in_p, 0)) {
973                         DEBUG(0,("api_pipe_bind_req: unable to unmarshall RPC_HDR_AUTH struct.\n"));
974                         return False;
975                 }
976
977                 if(auth_info.auth_type == NTLMSSP_AUTH_TYPE) {
978
979                         if(!smb_io_rpc_auth_verifier("", &auth_verifier, rpc_in_p, 0)) {
980                                 DEBUG(0,("api_pipe_bind_req: unable to "
981                                          "unmarshall RPC_HDR_AUTH struct.\n"));
982                                 return False;
983                         }
984
985                         if(!strequal(auth_verifier.signature, "NTLMSSP")) {
986                                 DEBUG(0,("api_pipe_bind_req: "
987                                          "auth_verifier.signature != NTLMSSP\n"));
988                                 return False;
989                         }
990
991                         if(auth_verifier.msg_type != NTLMSSP_NEGOTIATE) {
992                                 DEBUG(0,("api_pipe_bind_req: "
993                                          "auth_verifier.msg_type (%d) != NTLMSSP_NEGOTIATE\n",
994                                          auth_verifier.msg_type));
995                                 return False;
996                         }
997
998                         if(!smb_io_rpc_auth_ntlmssp_neg("", &ntlmssp_neg, rpc_in_p, 0)) {
999                                 DEBUG(0,("api_pipe_bind_req: "
1000                                          "Failed to unmarshall RPC_AUTH_NTLMSSP_NEG.\n"));
1001                                 return False;
1002                         }
1003
1004                         p->ntlmssp_chal_flags = SMBD_NTLMSSP_NEG_FLAGS;
1005                         p->ntlmssp_auth_requested = True;
1006
1007                 } else if (auth_info.auth_type == NETSEC_AUTH_TYPE) {
1008
1009                         RPC_AUTH_NETSEC_NEG neg;
1010                         struct netsec_auth_struct *a = &(p->netsec_auth);
1011
1012                         if (!smb_io_rpc_auth_netsec_neg("", &neg, rpc_in_p, 0)) {
1013                                 DEBUG(0,("api_pipe_bind_req: "
1014                                          "Could not unmarshal SCHANNEL auth neg\n"));
1015                                 return False;
1016                         }
1017
1018                         p->netsec_auth_validated = True;
1019
1020                         memset(a->sess_key, 0, sizeof(a->sess_key));
1021                         memcpy(a->sess_key, last_dcinfo.sess_key, sizeof(last_dcinfo.sess_key));
1022
1023                         a->seq_num = 0;
1024
1025                         DEBUG(10,("schannel auth: domain [%s] myname [%s]\n",
1026                                   neg.domain, neg.myname));
1027
1028                 } else {
1029                         DEBUG(0,("api_pipe_bind_req: unknown auth type %x requested.\n",
1030                                  auth_info.auth_type ));
1031                         return False;
1032                 }
1033         }
1034
1035         switch(p->hdr.pkt_type) {
1036                 case RPC_BIND:
1037                         /* name has to be \PIPE\xxxxx */
1038                         fstrcpy(ack_pipe_name, "\\PIPE\\");
1039                         fstrcat(ack_pipe_name, p->pipe_srv_name);
1040                         reply_pkt_type = RPC_BINDACK;
1041                         break;
1042                 case RPC_ALTCONT:
1043                         /* secondary address CAN be NULL
1044                          * as the specs say it's ignored.
1045                          * It MUST NULL to have the spoolss working.
1046                          */
1047                         fstrcpy(ack_pipe_name,"");
1048                         reply_pkt_type = RPC_ALTCONTRESP;
1049                         break;
1050                 default:
1051                         return False;
1052         }
1053
1054         DEBUG(5,("api_pipe_bind_req: make response. %d\n", __LINE__));
1055
1056         /* 
1057          * Marshall directly into the outgoing PDU space. We
1058          * must do this as we need to set to the bind response
1059          * header and are never sending more than one PDU here.
1060          */
1061
1062         prs_init( &outgoing_rpc, 0, p->mem_ctx, MARSHALL);
1063         prs_give_memory( &outgoing_rpc, (char *)p->out_data.current_pdu, sizeof(p->out_data.current_pdu), False);
1064
1065         /*
1066          * Setup the memory to marshall the ba header, and the
1067          * auth footers.
1068          */
1069
1070         if(!prs_init(&out_hdr_ba, 1024, p->mem_ctx, MARSHALL)) {
1071                 DEBUG(0,("api_pipe_bind_req: malloc out_hdr_ba failed.\n"));
1072                 prs_mem_free(&outgoing_rpc);
1073                 return False;
1074         }
1075
1076         if(!prs_init(&out_auth, 1024, p->mem_ctx, MARSHALL)) {
1077                 DEBUG(0,("pi_pipe_bind_req: malloc out_auth failed.\n"));
1078                 prs_mem_free(&outgoing_rpc);
1079                 prs_mem_free(&out_hdr_ba);
1080                 return False;
1081         }
1082
1083         if (p->ntlmssp_auth_requested)
1084                 assoc_gid = 0x7a77;
1085         else
1086                 assoc_gid = hdr_rb.bba.assoc_gid ? hdr_rb.bba.assoc_gid : 0x53f0;
1087
1088         /*
1089          * Create the bind response struct.
1090          */
1091
1092         /* If the requested abstract synt uuid doesn't match our client pipe,
1093                 reject the bind_ack & set the transfer interface synt to all 0's,
1094                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1095                 unknown to NT4)
1096                 Needed when adding entries to a DACL from NT5 - SK */
1097
1098         if(check_bind_req(p->name, &hdr_rb.abstract, &hdr_rb.transfer)) {
1099                 init_rpc_hdr_ba(&hdr_ba,
1100                         MAX_PDU_FRAG_LEN,
1101                         MAX_PDU_FRAG_LEN,
1102                         assoc_gid,
1103                         ack_pipe_name,
1104                         0x1, 0x0, 0x0,
1105                         &hdr_rb.transfer);
1106         } else {
1107                 RPC_IFACE null_interface;
1108                 ZERO_STRUCT(null_interface);
1109                 /* Rejection reason: abstract syntax not supported */
1110                 init_rpc_hdr_ba(&hdr_ba, MAX_PDU_FRAG_LEN,
1111                                         MAX_PDU_FRAG_LEN, assoc_gid,
1112                                         ack_pipe_name, 0x1, 0x2, 0x1,
1113                                         &null_interface);
1114         }
1115
1116         /*
1117          * and marshall it.
1118          */
1119
1120         if(!smb_io_rpc_hdr_ba("", &hdr_ba, &out_hdr_ba, 0)) {
1121                 DEBUG(0,("api_pipe_bind_req: marshalling of RPC_HDR_BA failed.\n"));
1122                 goto err_exit;
1123         }
1124
1125         /*
1126          * Now the authentication.
1127          */
1128
1129         if (p->ntlmssp_auth_requested) {
1130                 RPC_AUTH_VERIFIER auth_verifier;
1131                 RPC_AUTH_NTLMSSP_CHAL ntlmssp_chal;
1132
1133                 generate_random_buffer(p->challenge, 8, False);
1134
1135                 /*** Authentication info ***/
1136
1137                 init_rpc_hdr_auth(&auth_info, NTLMSSP_AUTH_TYPE, NTLMSSP_AUTH_LEVEL, RPC_HDR_AUTH_LEN, 1);
1138                 if(!smb_io_rpc_hdr_auth("", &auth_info, &out_auth, 0)) {
1139                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_HDR_AUTH failed.\n"));
1140                         goto err_exit;
1141                 }
1142
1143                 /*** NTLMSSP verifier ***/
1144
1145                 init_rpc_auth_verifier(&auth_verifier, "NTLMSSP", NTLMSSP_CHALLENGE);
1146                 if(!smb_io_rpc_auth_verifier("", &auth_verifier, &out_auth, 0)) {
1147                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_AUTH_VERIFIER failed.\n"));
1148                         goto err_exit;
1149                 }
1150
1151                 /* NTLMSSP challenge ***/
1152
1153                 init_rpc_auth_ntlmssp_chal(&ntlmssp_chal, p->ntlmssp_chal_flags, p->challenge);
1154                 if(!smb_io_rpc_auth_ntlmssp_chal("", &ntlmssp_chal, &out_auth, 0)) {
1155                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_AUTH_NTLMSSP_CHAL failed.\n"));
1156                         goto err_exit;
1157                 }
1158
1159                 /* Auth len in the rpc header doesn't include auth_header. */
1160                 auth_len = prs_offset(&out_auth) - RPC_HDR_AUTH_LEN;
1161         }
1162
1163         if (p->netsec_auth_validated) {
1164                 RPC_AUTH_VERIFIER auth_verifier;
1165                 uint32 flags;
1166
1167                 init_rpc_hdr_auth(&auth_info, NETSEC_AUTH_TYPE, NETSEC_AUTH_LEVEL, RPC_HDR_AUTH_LEN, 1);
1168                 if(!smb_io_rpc_hdr_auth("", &auth_info, &out_auth, 0)) {
1169                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_HDR_AUTH failed.\n"));
1170                         goto err_exit;
1171                 }
1172
1173                 /*** NETSEC verifier ***/
1174
1175                 init_rpc_auth_verifier(&auth_verifier, "\001", 0x0);
1176                 if(!smb_io_rpc_netsec_verifier("", &auth_verifier, &out_auth, 0)) {
1177                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_AUTH_VERIFIER failed.\n"));
1178                         goto err_exit;
1179                 }
1180
1181                 prs_align(&out_auth);
1182
1183                 flags = 5;
1184                 if(!prs_uint32("flags ", &out_auth, 0, &flags))
1185                         goto err_exit;
1186
1187                 auth_len = prs_offset(&out_auth) - RPC_HDR_AUTH_LEN;
1188         }
1189
1190         /*
1191          * Create the header, now we know the length.
1192          */
1193
1194         init_rpc_hdr(&p->hdr, reply_pkt_type, RPC_FLG_FIRST | RPC_FLG_LAST,
1195                         p->hdr.call_id,
1196                         RPC_HEADER_LEN + prs_offset(&out_hdr_ba) + prs_offset(&out_auth),
1197                         auth_len);
1198
1199         /*
1200          * Marshall the header into the outgoing PDU.
1201          */
1202
1203         if(!smb_io_rpc_hdr("", &p->hdr, &outgoing_rpc, 0)) {
1204                 DEBUG(0,("pi_pipe_bind_req: marshalling of RPC_HDR failed.\n"));
1205                 goto err_exit;
1206         }
1207
1208         /*
1209          * Now add the RPC_HDR_BA and any auth needed.
1210          */
1211
1212         if(!prs_append_prs_data( &outgoing_rpc, &out_hdr_ba)) {
1213                 DEBUG(0,("api_pipe_bind_req: append of RPC_HDR_BA failed.\n"));
1214                 goto err_exit;
1215         }
1216
1217         if((p->ntlmssp_auth_requested|p->netsec_auth_validated) &&
1218            !prs_append_prs_data( &outgoing_rpc, &out_auth)) {
1219                 DEBUG(0,("api_pipe_bind_req: append of auth info failed.\n"));
1220                 goto err_exit;
1221         }
1222
1223         if(!p->ntlmssp_auth_requested)
1224                 p->pipe_bound = True;
1225
1226         /*
1227          * Setup the lengths for the initial reply.
1228          */
1229
1230         p->out_data.data_sent_length = 0;
1231         p->out_data.current_pdu_len = prs_offset(&outgoing_rpc);
1232         p->out_data.current_pdu_sent = 0;
1233
1234         prs_mem_free(&out_hdr_ba);
1235         prs_mem_free(&out_auth);
1236
1237         return True;
1238
1239   err_exit:
1240
1241         prs_mem_free(&outgoing_rpc);
1242         prs_mem_free(&out_hdr_ba);
1243         prs_mem_free(&out_auth);
1244         return False;
1245 }
1246
1247 /****************************************************************************
1248  Deal with sign & seal processing on an RPC request.
1249 ****************************************************************************/
1250
1251 BOOL api_pipe_auth_process(pipes_struct *p, prs_struct *rpc_in)
1252 {
1253         /*
1254          * We always negotiate the following two bits....
1255          */
1256         BOOL auth_verify = ((p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SIGN) != 0);
1257         BOOL auth_seal   = ((p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SEAL) != 0);
1258         int data_len;
1259         int auth_len;
1260         uint32 old_offset;
1261         uint32 crc32 = 0;
1262
1263         auth_len = p->hdr.auth_len;
1264
1265         if ((auth_len != RPC_AUTH_NTLMSSP_CHK_LEN) && auth_verify) {
1266                 DEBUG(0,("api_pipe_auth_process: Incorrect auth_len %d.\n", auth_len ));
1267                 return False;
1268         }
1269
1270         /*
1271          * The following is that length of the data we must verify or unseal.
1272          * This doesn't include the RPC headers or the auth_len or the RPC_HDR_AUTH_LEN
1273          * preceeding the auth_data.
1274          */
1275
1276         data_len = p->hdr.frag_len - RPC_HEADER_LEN - RPC_HDR_REQ_LEN - 
1277                         (auth_verify ? RPC_HDR_AUTH_LEN : 0) - auth_len;
1278         
1279         DEBUG(5,("api_pipe_auth_process: sign: %s seal: %s data %d auth %d\n",
1280                  BOOLSTR(auth_verify), BOOLSTR(auth_seal), data_len, auth_len));
1281
1282         if (auth_seal) {
1283                 /*
1284                  * The data in rpc_in doesn't contain the RPC_HEADER as this
1285                  * has already been consumed.
1286                  */
1287                 char *data = prs_data_p(rpc_in) + RPC_HDR_REQ_LEN;
1288                 NTLMSSPcalc_p(p, (uchar*)data, data_len);
1289                 crc32 = crc32_calc_buffer(data, data_len);
1290         }
1291
1292         old_offset = prs_offset(rpc_in);
1293
1294         if (auth_seal || auth_verify) {
1295                 RPC_HDR_AUTH auth_info;
1296
1297                 if(!prs_set_offset(rpc_in, old_offset + data_len)) {
1298                         DEBUG(0,("api_pipe_auth_process: cannot move offset to %u.\n",
1299                                 (unsigned int)old_offset + data_len ));
1300                         return False;
1301                 }
1302
1303                 if(!smb_io_rpc_hdr_auth("hdr_auth", &auth_info, rpc_in, 0)) {
1304                         DEBUG(0,("api_pipe_auth_process: failed to unmarshall RPC_HDR_AUTH.\n"));
1305                         return False;
1306                 }
1307         }
1308
1309         if (auth_verify) {
1310                 RPC_AUTH_NTLMSSP_CHK ntlmssp_chk;
1311                 char *req_data = prs_data_p(rpc_in) + prs_offset(rpc_in) + 4;
1312
1313                 DEBUG(5,("api_pipe_auth_process: auth %d\n", prs_offset(rpc_in) + 4));
1314
1315                 /*
1316                  * Ensure we have RPC_AUTH_NTLMSSP_CHK_LEN - 4 more bytes in the
1317                  * incoming buffer.
1318                  */
1319                 if(prs_mem_get(rpc_in, RPC_AUTH_NTLMSSP_CHK_LEN - 4) == NULL) {
1320                         DEBUG(0,("api_pipe_auth_process: missing %d bytes in buffer.\n",
1321                                 RPC_AUTH_NTLMSSP_CHK_LEN - 4 ));
1322                         return False;
1323                 }
1324
1325                 NTLMSSPcalc_p(p, (uchar*)req_data, RPC_AUTH_NTLMSSP_CHK_LEN - 4);
1326                 if(!smb_io_rpc_auth_ntlmssp_chk("auth_sign", &ntlmssp_chk, rpc_in, 0)) {
1327                         DEBUG(0,("api_pipe_auth_process: failed to unmarshall RPC_AUTH_NTLMSSP_CHK.\n"));
1328                         return False;
1329                 }
1330
1331                 if (!rpc_auth_ntlmssp_chk(&ntlmssp_chk, crc32, p->ntlmssp_seq_num)) {
1332                         DEBUG(0,("api_pipe_auth_process: NTLMSSP check failed.\n"));
1333                         return False;
1334                 }
1335         }
1336
1337         /*
1338          * Return the current pointer to the data offset.
1339          */
1340
1341         if(!prs_set_offset(rpc_in, old_offset)) {
1342                 DEBUG(0,("api_pipe_auth_process: failed to set offset back to %u\n",
1343                         (unsigned int)old_offset ));
1344                 return False;
1345         }
1346
1347         return True;
1348 }
1349
1350 static void netsechash(uchar * key, uchar * data, int data_len)
1351 {
1352         uchar hash[256];
1353         uchar index_i = 0;
1354         uchar index_j = 0;
1355         uchar j = 0;
1356         int ind;
1357
1358         for (ind = 0; ind < 256; ind++)
1359         {
1360                 hash[ind] = (uchar) ind;
1361         }
1362
1363         for (ind = 0; ind < 256; ind++)
1364         {
1365                 uchar tc;
1366
1367                 j += (hash[ind] + key[ind % 16]);
1368
1369                 tc = hash[ind];
1370                 hash[ind] = hash[j];
1371                 hash[j] = tc;
1372         }
1373
1374         for (ind = 0; ind < data_len; ind++)
1375         {
1376                 uchar tc;
1377                 uchar t;
1378
1379                 index_i++;
1380                 index_j += hash[index_i];
1381
1382                 tc = hash[index_i];
1383                 hash[index_i] = hash[index_j];
1384                 hash[index_j] = tc;
1385
1386                 t = hash[index_i] + hash[index_j];
1387                 data[ind] ^= hash[t];
1388         }
1389 }
1390
1391 void dump_data_pw(const char *msg, const uchar * data, size_t len)
1392 {
1393 #ifdef DEBUG_PASSWORD
1394         DEBUG(11, ("%s", msg));
1395         if (data != NULL && len > 0)
1396         {
1397                 dump_data(11, data, len);
1398         }
1399 #endif
1400 }
1401
1402 BOOL netsec_encode(struct netsec_auth_struct *a,
1403                    RPC_AUTH_NETSEC_CHK * verf, char *data, size_t data_len)
1404 {
1405         uchar dataN[4];
1406         uchar digest1[16];
1407         struct MD5Context ctx3;
1408         uchar sess_kf0[16];
1409         int i;
1410
1411         /* store the sequence number */
1412         SIVAL(dataN, 0, a->seq_num);
1413
1414         for (i = 0; i < sizeof(sess_kf0); i++)
1415         {
1416                 sess_kf0[i] = a->sess_key[i] ^ 0xf0;
1417         }
1418
1419         dump_data_pw("a->sess_key:\n", a->sess_key, sizeof(a->sess_key));
1420         dump_data_pw("a->seq_num :\n", dataN, sizeof(dataN));
1421
1422         MD5Init(&ctx3);
1423         MD5Update(&ctx3, dataN, 0x4);
1424         MD5Update(&ctx3, verf->sig, 8);
1425
1426         MD5Update(&ctx3, verf->data8, 8);
1427
1428         dump_data_pw("verf->data8:\n", verf->data8, sizeof(verf->data8));
1429         dump_data_pw("sess_kf0:\n", sess_kf0, sizeof(sess_kf0));
1430
1431         hmac_md5(sess_kf0, dataN, 0x4, digest1);
1432         dump_data_pw("digest1 (ebp-8):\n", digest1, sizeof(digest1));
1433         hmac_md5(digest1, verf->data3, 8, digest1);
1434         dump_data_pw("netsechashkey:\n", digest1, sizeof(digest1));
1435         netsechash(digest1, verf->data8, 8);
1436
1437         dump_data_pw("verf->data8:\n", verf->data8, sizeof(verf->data8));
1438
1439         dump_data_pw("data   :\n", data, data_len);
1440         MD5Update(&ctx3, data, data_len);
1441
1442         {
1443                 char digest_tmp[16];
1444                 char digest2[16];
1445                 MD5Final(digest_tmp, &ctx3);
1446                 hmac_md5(a->sess_key, digest_tmp, 16, digest2);
1447                 dump_data_pw("digest_tmp:\n", digest_tmp, sizeof(digest_tmp));
1448                 dump_data_pw("digest:\n", digest2, sizeof(digest2));
1449                 memcpy(verf->data1, digest2, sizeof(verf->data1));
1450         }
1451
1452         netsechash(digest1, data, data_len);
1453         dump_data_pw("data:\n", data, data_len);
1454
1455         hmac_md5(a->sess_key, dataN, 0x4, digest1);
1456         dump_data_pw("ctx:\n", digest1, sizeof(digest1));
1457
1458         hmac_md5(digest1, verf->data1, 8, digest1);
1459
1460         dump_data_pw("netsechashkey:\n", digest1, sizeof(digest1));
1461
1462         dump_data_pw("verf->data3:\n", verf->data3, sizeof(verf->data3));
1463         netsechash(digest1, verf->data3, 8);
1464         dump_data_pw("verf->data3:\n", verf->data3, sizeof(verf->data3));
1465
1466         return True;
1467 }
1468
1469 BOOL netsec_decode(struct netsec_auth_struct *a,
1470                    RPC_AUTH_NETSEC_CHK * verf, char *data, size_t data_len)
1471 {
1472         uchar dataN[4];
1473         uchar digest1[16];
1474         struct MD5Context ctx3;
1475         uchar sess_kf0[16];
1476         int i;
1477
1478         /* store the sequence number */
1479         SIVAL(dataN, 0, a->seq_num);
1480
1481         for (i = 0; i < sizeof(sess_kf0); i++)
1482         {
1483                 sess_kf0[i] = a->sess_key[i] ^ 0xf0;
1484         }
1485
1486         dump_data_pw("a->sess_key:\n", a->sess_key, sizeof(a->sess_key));
1487         dump_data_pw("a->seq_num :\n", dataN, sizeof(dataN));
1488         hmac_md5(a->sess_key, dataN, 0x4, digest1);
1489         dump_data_pw("ctx:\n", digest1, sizeof(digest1));
1490
1491         hmac_md5(digest1, verf->data1, 8, digest1);
1492
1493         dump_data_pw("netsechashkey:\n", digest1, sizeof(digest1));
1494         dump_data_pw("verf->data3:\n", verf->data3, sizeof(verf->data3));
1495         netsechash(digest1, verf->data3, 8);
1496         dump_data_pw("verf->data3_dec:\n", verf->data3, sizeof(verf->data3));
1497
1498         MD5Init(&ctx3);
1499         MD5Update(&ctx3, dataN, 0x4);
1500         MD5Update(&ctx3, verf->sig, 8);
1501
1502         dump_data_pw("sess_kf0:\n", sess_kf0, sizeof(sess_kf0));
1503
1504         hmac_md5(sess_kf0, dataN, 0x4, digest1);
1505         dump_data_pw("digest1 (ebp-8):\n", digest1, sizeof(digest1));
1506         hmac_md5(digest1, verf->data3, 8, digest1);
1507         dump_data_pw("netsechashkey:\n", digest1, sizeof(digest1));
1508
1509         dump_data_pw("verf->data8:\n", verf->data8, sizeof(verf->data8));
1510         netsechash(digest1, verf->data8, 8);
1511         dump_data_pw("verf->data8_dec:\n", verf->data8, sizeof(verf->data8));
1512         MD5Update(&ctx3, verf->data8, 8);
1513
1514         dump_data_pw("data   :\n", data, data_len);
1515         netsechash(digest1, data, data_len);
1516         dump_data_pw("datadec:\n", data, data_len);
1517
1518         MD5Update(&ctx3, data, data_len);
1519         {
1520                 uchar digest_tmp[16];
1521                 MD5Final(digest_tmp, &ctx3);
1522                 hmac_md5(a->sess_key, digest_tmp, 16, digest1);
1523                 dump_data_pw("digest_tmp:\n", digest_tmp, sizeof(digest_tmp));
1524         }
1525
1526         dump_data_pw("digest:\n", digest1, sizeof(digest1));
1527         dump_data_pw("verf->data1:\n", verf->data1, sizeof(verf->data1));
1528
1529         return memcmp(digest1, verf->data1, sizeof(verf->data1)) == 0;
1530 }
1531
1532 /****************************************************************************
1533  Deal with schannel processing on an RPC request.
1534 ****************************************************************************/
1535 BOOL api_pipe_netsec_process(pipes_struct *p, prs_struct *rpc_in)
1536 {
1537         /*
1538          * We always negotiate the following two bits....
1539          */
1540         int data_len;
1541         int auth_len;
1542         uint32 old_offset;
1543         RPC_HDR_AUTH auth_info;
1544         RPC_AUTH_NETSEC_CHK netsec_chk;
1545
1546
1547         auth_len = p->hdr.auth_len;
1548
1549         if (auth_len != RPC_AUTH_NETSEC_CHK_LEN) {
1550                 DEBUG(0,("Incorrect auth_len %d.\n", auth_len ));
1551                 return False;
1552         }
1553
1554         /*
1555          * The following is that length of the data we must verify or unseal.
1556          * This doesn't include the RPC headers or the auth_len or the RPC_HDR_AUTH_LEN
1557          * preceeding the auth_data.
1558          */
1559
1560         data_len = p->hdr.frag_len - RPC_HEADER_LEN - RPC_HDR_REQ_LEN - 
1561                 RPC_HDR_AUTH_LEN - auth_len;
1562         
1563         DEBUG(5,("data %d auth %d\n", data_len, auth_len));
1564
1565         old_offset = prs_offset(rpc_in);
1566
1567         if(!prs_set_offset(rpc_in, old_offset + data_len)) {
1568                 DEBUG(0,("cannot move offset to %u.\n",
1569                          (unsigned int)old_offset + data_len ));
1570                 return False;
1571         }
1572
1573         if(!smb_io_rpc_hdr_auth("hdr_auth", &auth_info, rpc_in, 0)) {
1574                 DEBUG(0,("failed to unmarshall RPC_HDR_AUTH.\n"));
1575                 return False;
1576         }
1577
1578         if ((auth_info.auth_type != NETSEC_AUTH_TYPE) ||
1579             (auth_info.auth_level != NETSEC_AUTH_LEVEL)) {
1580                 DEBUG(0,("Invalid auth info %d or level %d on schannel\n",
1581                          auth_info.auth_type, auth_info.auth_level));
1582                 return False;
1583         }
1584
1585         if(!smb_io_rpc_auth_netsec_chk("", &netsec_chk, rpc_in, 0)) {
1586                 DEBUG(0,("failed to unmarshal RPC_AUTH_NETSEC_CHK.\n"));
1587                 return False;
1588         }
1589
1590         if (!netsec_decode(&p->netsec_auth, &netsec_chk,
1591                            prs_data_p(rpc_in)+old_offset, data_len)) {
1592                 DEBUG(0,("failed to decode PDU\n"));
1593                 return False;
1594         }
1595
1596         /*
1597          * Return the current pointer to the data offset.
1598          */
1599
1600         if(!prs_set_offset(rpc_in, old_offset)) {
1601                 DEBUG(0,("failed to set offset back to %u\n",
1602                          (unsigned int)old_offset ));
1603                 return False;
1604         }
1605
1606         return True;
1607 }
1608
1609 /****************************************************************************
1610  Return a user struct for a pipe user.
1611 ****************************************************************************/
1612
1613 struct current_user *get_current_user(struct current_user *user, pipes_struct *p)
1614 {
1615         if (p->ntlmssp_auth_validated) {
1616                 memcpy(user, &p->pipe_user, sizeof(struct current_user));
1617         } else {
1618                 extern struct current_user current_user;
1619                 memcpy(user, &current_user, sizeof(struct current_user));
1620         }
1621
1622         return user;
1623 }
1624
1625 /****************************************************************************
1626  Find the correct RPC function to call for this request.
1627  If the pipe is authenticated then become the correct UNIX user
1628  before doing the call.
1629 ****************************************************************************/
1630
1631 BOOL api_pipe_request(pipes_struct *p)
1632 {
1633         int i = 0;
1634         BOOL ret = False;
1635
1636         if (p->ntlmssp_auth_validated) {
1637
1638                 if(!become_authenticated_pipe_user(p)) {
1639                         prs_mem_free(&p->out_data.rdata);
1640                         return False;
1641                 }
1642         }
1643
1644         DEBUG(5, ("Requested \\PIPE\\%s\n", p->name));
1645
1646         for (i = 0; i < rpc_lookup_size; i++) {
1647                 if (strequal(rpc_lookup[i].pipe.clnt, p->name)) {
1648                         DEBUG(3,("Doing \\PIPE\\%s\n", 
1649                                  rpc_lookup[i].pipe.clnt));
1650                         set_current_rpc_talloc(p->mem_ctx);
1651                         ret = api_rpcTNP(p, rpc_lookup[i].pipe.clnt,
1652                                          rpc_lookup[i].cmds,
1653                                          rpc_lookup[i].n_cmds);
1654                         set_current_rpc_talloc(NULL);
1655                         break;
1656                 }
1657         }
1658
1659
1660         if (i == rpc_lookup_size) {
1661                 for (i = 0; api_fd_commands[i].name; i++) {
1662                         if (strequal(api_fd_commands[i].name, p->name)) {
1663                                 api_fd_commands[i].init();
1664                                 break;
1665                         }
1666                 }
1667
1668                 if (!api_fd_commands[i].name) {
1669                        rpc_load_module(p->name);
1670                 }
1671
1672                 for (i = 0; i < rpc_lookup_size; i++) {
1673                         if (strequal(rpc_lookup[i].pipe.clnt, p->name)) {
1674                                 DEBUG(3,("Doing \\PIPE\\%s\n",
1675                                          rpc_lookup[i].pipe.clnt));
1676                                 set_current_rpc_talloc(p->mem_ctx);
1677                                 ret = api_rpcTNP(p, rpc_lookup[i].pipe.clnt,
1678                                                  rpc_lookup[i].cmds,
1679                                                  rpc_lookup[i].n_cmds);
1680                                 set_current_rpc_talloc(NULL);
1681                                 break;
1682                         }
1683                 }
1684         }
1685
1686         if(p->ntlmssp_auth_validated)
1687                 unbecome_authenticated_pipe_user();
1688
1689         return ret;
1690 }
1691
1692 /*******************************************************************
1693  Calls the underlying RPC function for a named pipe.
1694  ********************************************************************/
1695
1696 BOOL api_rpcTNP(pipes_struct *p, const char *rpc_name, 
1697                 const struct api_struct *api_rpc_cmds, int n_cmds)
1698 {
1699         int fn_num;
1700         fstring name;
1701         uint32 offset1, offset2;
1702  
1703         /* interpret the command */
1704         DEBUG(4,("api_rpcTNP: %s op 0x%x - ", rpc_name, p->hdr_req.opnum));
1705
1706         slprintf(name, sizeof(name)-1, "in_%s", rpc_name);
1707         prs_dump(name, p->hdr_req.opnum, &p->in_data.data);
1708
1709         for (fn_num = 0; fn_num < n_cmds; fn_num++) {
1710                 if (api_rpc_cmds[fn_num].opnum == p->hdr_req.opnum && api_rpc_cmds[fn_num].fn != NULL) {
1711                         DEBUG(3,("api_rpcTNP: rpc command: %s\n", api_rpc_cmds[fn_num].name));
1712                         break;
1713                 }
1714         }
1715
1716         if (fn_num == n_cmds) {
1717                 /*
1718                  * For an unknown RPC just return a fault PDU but
1719                  * return True to allow RPC's on the pipe to continue
1720                  * and not put the pipe into fault state. JRA.
1721                  */
1722                 DEBUG(4, ("unknown\n"));
1723                 setup_fault_pdu(p, NT_STATUS(0x1c010002));
1724                 return True;
1725         }
1726
1727         offset1 = prs_offset(&p->out_data.rdata);
1728
1729         DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", 
1730                 fn_num, api_rpc_cmds[fn_num].fn));
1731         /* do the actual command */
1732         if(!api_rpc_cmds[fn_num].fn(p)) {
1733                 DEBUG(0,("api_rpcTNP: %s: %s failed.\n", rpc_name, api_rpc_cmds[fn_num].name));
1734                 prs_mem_free(&p->out_data.rdata);
1735                 return False;
1736         }
1737
1738         if (p->bad_handle_fault_state) {
1739                 DEBUG(4,("api_rpcTNP: bad handle fault return.\n"));
1740                 p->bad_handle_fault_state = False;
1741                 setup_fault_pdu(p, NT_STATUS(0x1C00001A));
1742                 return True;
1743         }
1744
1745         slprintf(name, sizeof(name)-1, "out_%s", rpc_name);
1746         offset2 = prs_offset(&p->out_data.rdata);
1747         prs_set_offset(&p->out_data.rdata, offset1);
1748         prs_dump(name, p->hdr_req.opnum, &p->out_data.rdata);
1749         prs_set_offset(&p->out_data.rdata, offset2);
1750
1751         DEBUG(5,("api_rpcTNP: called %s successfully\n", rpc_name));
1752
1753         /* Check for buffer underflow in rpc parsing */
1754
1755         if ((DEBUGLEVEL >= 10) && 
1756             (prs_offset(&p->in_data.data) != prs_data_size(&p->in_data.data))) {
1757                 size_t data_len = prs_data_size(&p->in_data.data) - prs_offset(&p->in_data.data);
1758                 char *data;
1759
1760                 data = malloc(data_len);
1761
1762                 DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n"));
1763                 if (data) {
1764                         prs_uint8s(False, "", &p->in_data.data, 0, (unsigned char *)data, (uint32)data_len);
1765                         SAFE_FREE(data);
1766                 }
1767
1768         }
1769
1770         return True;
1771 }