This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[tprouty/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) Jim McDonough <jmcd@us.ibm.com>   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, RPC_PIPE_AUTH_SEAL_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                 int auth_type, auth_level;
258                 char *data;
259                 RPC_HDR_AUTH auth_info;
260
261                 RPC_AUTH_NETSEC_CHK verf;
262                 prs_struct rverf;
263                 prs_struct rauth;
264
265                 data = prs_data_p(&outgoing_pdu) + data_pos;
266                 /* Check it's the type of reply we were expecting to decode */
267
268                 get_auth_type_level(p->netsec_auth.auth_flags, &auth_type, &auth_level);
269                 init_rpc_hdr_auth(&auth_info, auth_type, auth_level, 
270                                   RPC_HDR_AUTH_LEN, 1);
271
272                 if(!smb_io_rpc_hdr_auth("hdr_auth", &auth_info, &outgoing_pdu, 0)) {
273                         DEBUG(0,("create_next_pdu: failed to marshall RPC_HDR_AUTH.\n"));
274                         prs_mem_free(&outgoing_pdu);
275                         return False;
276                 }
277
278                 prs_init(&rverf, 0, p->mem_ctx, MARSHALL);
279                 prs_init(&rauth, 0, p->mem_ctx, MARSHALL);
280
281                 netsec_encode(&p->netsec_auth, 
282                               p->netsec_auth.auth_flags,
283                               SENDER_IS_ACCEPTOR,
284                               &verf, data, data_len);
285
286                 smb_io_rpc_auth_netsec_chk("", &verf, &outgoing_pdu, 0);
287
288                 p->netsec_auth.seq_num++;
289         }
290
291         /*
292          * Setup the counts for this PDU.
293          */
294
295         p->out_data.data_sent_length += data_len;
296         p->out_data.current_pdu_len = p->hdr.frag_len;
297         p->out_data.current_pdu_sent = 0;
298
299         prs_mem_free(&outgoing_pdu);
300         return True;
301 }
302
303 /*******************************************************************
304  Process an NTLMSSP authentication response.
305  If this function succeeds, the user has been authenticated
306  and their domain, name and calling workstation stored in
307  the pipe struct.
308  The initial challenge is stored in p->challenge.
309  *******************************************************************/
310
311 static BOOL api_pipe_ntlmssp_verify(pipes_struct *p, RPC_AUTH_NTLMSSP_RESP *ntlmssp_resp)
312 {
313         uchar lm_owf[24];
314         uchar nt_owf[128];
315         int nt_pw_len;
316         int lm_pw_len;
317         fstring user_name;
318         fstring domain;
319         fstring wks;
320
321         NTSTATUS nt_status;
322
323         struct auth_context *auth_context = NULL;
324         auth_usersupplied_info *user_info = NULL;
325         auth_serversupplied_info *server_info = NULL;
326
327         DEBUG(5,("api_pipe_ntlmssp_verify: checking user details\n"));
328
329         memset(p->user_name, '\0', sizeof(p->user_name));
330         memset(p->pipe_user_name, '\0', sizeof(p->pipe_user_name));
331         memset(p->domain, '\0', sizeof(p->domain));
332         memset(p->wks, '\0', sizeof(p->wks));
333
334         /* Set up for non-authenticated user. */
335         delete_nt_token(&p->pipe_user.nt_user_token);
336         p->pipe_user.ngroups = 0;
337         SAFE_FREE( p->pipe_user.groups);
338
339         /* 
340          * Setup an empty password for a guest user.
341          */
342
343         /*
344          * We always negotiate UNICODE.
345          */
346
347         if (p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_UNICODE) {
348                 rpcstr_pull(user_name, ntlmssp_resp->user, sizeof(fstring), ntlmssp_resp->hdr_usr.str_str_len*2, 0 );
349                 rpcstr_pull(domain, ntlmssp_resp->domain, sizeof(fstring), ntlmssp_resp->hdr_domain.str_str_len*2, 0);
350                 rpcstr_pull(wks, ntlmssp_resp->wks, sizeof(fstring), ntlmssp_resp->hdr_wks.str_str_len*2, 0);
351         } else {
352                 pull_ascii_fstring(user_name, ntlmssp_resp->user);
353                 pull_ascii_fstring(domain, ntlmssp_resp->domain);
354                 pull_ascii_fstring(wks, ntlmssp_resp->wks);
355         }
356
357         DEBUG(5,("user: %s domain: %s wks: %s\n", user_name, domain, wks));
358
359         nt_pw_len = MIN(sizeof(nt_owf), ntlmssp_resp->hdr_nt_resp.str_str_len);
360         lm_pw_len = MIN(sizeof(lm_owf), ntlmssp_resp->hdr_lm_resp.str_str_len);
361
362         memcpy(lm_owf, ntlmssp_resp->lm_resp, sizeof(lm_owf));
363         memcpy(nt_owf, ntlmssp_resp->nt_resp, nt_pw_len);
364
365 #ifdef DEBUG_PASSWORD
366         DEBUG(100,("lm, nt owfs, chal\n"));
367         dump_data(100, (char *)lm_owf, sizeof(lm_owf));
368         dump_data(100, (char *)nt_owf, nt_pw_len);
369         dump_data(100, (char *)p->challenge, 8);
370 #endif
371
372         /*
373          * Allow guest access. Patch from Shirish Kalele <kalele@veritas.com>.
374          */
375
376         if (*user_name) {
377
378                 /* 
379                  * Do the length checking only if user is not NULL.
380                  */
381
382                 if (ntlmssp_resp->hdr_lm_resp.str_str_len == 0)
383                         return False;
384                 if (ntlmssp_resp->hdr_nt_resp.str_str_len == 0)
385                         return False;
386                 if (ntlmssp_resp->hdr_usr.str_str_len == 0)
387                         return False;
388                 if (ntlmssp_resp->hdr_domain.str_str_len == 0)
389                         return False;
390                 if (ntlmssp_resp->hdr_wks.str_str_len == 0)
391                         return False;
392
393         }
394         
395         make_auth_context_fixed(&auth_context, (uchar*)p->challenge);
396
397         if (!make_user_info_netlogon_network(&user_info, 
398                                              user_name, domain, wks,
399                                              lm_owf, lm_pw_len, 
400                                              nt_owf, nt_pw_len)) {
401                 DEBUG(0,("make_user_info_netlogon_network failed!  Failing authenticaion.\n"));
402                 return False;
403         }
404         
405         nt_status = auth_context->check_ntlm_password(auth_context, user_info, &server_info); 
406         
407         (auth_context->free)(&auth_context);
408         free_user_info(&user_info);
409         
410         p->ntlmssp_auth_validated = NT_STATUS_IS_OK(nt_status);
411         
412         if (!p->ntlmssp_auth_validated) {
413                 DEBUG(1,("api_pipe_ntlmssp_verify: User [%s]\\[%s] from machine %s \
414 failed authentication on named pipe %s.\n", domain, user_name, wks, p->name ));
415                 free_server_info(&server_info);
416                 return False;
417         }
418
419         /*
420          * Set up the sign/seal data.
421          */
422
423         if (server_info->lm_session_key.length != 16) {
424                 DEBUG(1,("api_pipe_ntlmssp_verify: User [%s]\\[%s] from machine %s \
425 succeeded authentication on named pipe %s, but session key was of incorrect length [%u].\n", 
426                          domain, user_name, wks, p->name, server_info->lm_session_key.length));
427                 free_server_info(&server_info);
428                 return False;
429         } else {
430                 uchar p24[24];
431                 NTLMSSPOWFencrypt(server_info->lm_session_key.data, 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
460                 dump_data_pw("NTLMSSP hash (v1)\n", p->ntlmssp_hash, 
461                              sizeof(p->ntlmssp_hash));
462
463 /*              NTLMSSPhash(p->ntlmssp_hash, p24); */
464                 p->ntlmssp_seq_num = 0;
465
466         }
467
468         fstrcpy(p->user_name, user_name);
469         fstrcpy(p->pipe_user_name, server_info->unix_name);
470         fstrcpy(p->domain, domain);
471         fstrcpy(p->wks, wks);
472
473         /*
474          * Store the UNIX credential data (uid/gid pair) in the pipe structure.
475          */
476
477         p->session_key = data_blob(server_info->lm_session_key.data, server_info->lm_session_key.length);
478
479         p->pipe_user.uid = server_info->uid;
480         p->pipe_user.gid = server_info->gid;
481         
482         p->pipe_user.ngroups = server_info->n_groups;
483         if (p->pipe_user.ngroups) {
484                 if (!(p->pipe_user.groups = memdup(server_info->groups, sizeof(gid_t) * p->pipe_user.ngroups))) {
485                         DEBUG(0,("failed to memdup group list to p->pipe_user.groups\n"));
486                         free_server_info(&server_info);
487                         return False;
488                 }
489         }
490
491         if (server_info->ptok)
492                 p->pipe_user.nt_user_token = dup_nt_token(server_info->ptok);
493         else {
494                 DEBUG(1,("Error: Authmodule failed to provide nt_user_token\n"));
495                 p->pipe_user.nt_user_token = NULL;
496                 free_server_info(&server_info);
497                 return False;
498         }
499
500         p->ntlmssp_auth_validated = True;
501
502         free_server_info(&server_info);
503         return True;
504 }
505
506 /*******************************************************************
507  The switch table for the pipe names and the functions to handle them.
508  *******************************************************************/
509
510 struct rpc_table
511 {
512   struct
513   {
514     const char *clnt;
515     const char *srv;
516   } pipe;
517   struct api_struct *cmds;
518   int n_cmds;
519 };
520
521 static struct rpc_table *rpc_lookup;
522 static int rpc_lookup_size;
523
524 /*******************************************************************
525  This is the client reply to our challenge for an authenticated 
526  bind request. The challenge we sent is in p->challenge.
527 *******************************************************************/
528
529 BOOL api_pipe_bind_auth_resp(pipes_struct *p, prs_struct *rpc_in_p)
530 {
531         RPC_HDR_AUTHA autha_info;
532         RPC_AUTH_VERIFIER auth_verifier;
533         RPC_AUTH_NTLMSSP_RESP ntlmssp_resp;
534
535         DEBUG(5,("api_pipe_bind_auth_resp: decode request. %d\n", __LINE__));
536
537         if (p->hdr.auth_len == 0) {
538                 DEBUG(0,("api_pipe_bind_auth_resp: No auth field sent !\n"));
539                 return False;
540         }
541
542         /*
543          * Decode the authentication verifier response.
544          */
545
546         if(!smb_io_rpc_hdr_autha("", &autha_info, rpc_in_p, 0)) {
547                 DEBUG(0,("api_pipe_bind_auth_resp: unmarshall of RPC_HDR_AUTHA failed.\n"));
548                 return False;
549         }
550
551         if (autha_info.auth_type != NTLMSSP_AUTH_TYPE || autha_info.auth_level != RPC_PIPE_AUTH_SEAL_LEVEL) {
552                 DEBUG(0,("api_pipe_bind_auth_resp: incorrect auth type (%d) or level (%d).\n",
553                         (int)autha_info.auth_type, (int)autha_info.auth_level ));
554                 return False;
555         }
556
557         if(!smb_io_rpc_auth_verifier("", &auth_verifier, rpc_in_p, 0)) {
558                 DEBUG(0,("api_pipe_bind_auth_resp: unmarshall of RPC_AUTH_VERIFIER failed.\n"));
559                 return False;
560         }
561
562         /*
563          * Ensure this is a NTLMSSP_AUTH packet type.
564          */
565
566         if (!rpc_auth_verifier_chk(&auth_verifier, "NTLMSSP", NTLMSSP_AUTH)) {
567                 DEBUG(0,("api_pipe_bind_auth_resp: rpc_auth_verifier_chk failed.\n"));
568                 return False;
569         }
570
571         if(!smb_io_rpc_auth_ntlmssp_resp("", &ntlmssp_resp, rpc_in_p, 0)) {
572                 DEBUG(0,("api_pipe_bind_auth_resp: Failed to unmarshall RPC_AUTH_NTLMSSP_RESP.\n"));
573                 return False;
574         }
575
576         /*
577          * The following call actually checks the challenge/response data.
578          * for correctness against the given DOMAIN\user name.
579          */
580         
581         if (!api_pipe_ntlmssp_verify(p, &ntlmssp_resp))
582                 return False;
583
584         p->pipe_bound = True
585 ;
586         return True;
587 }
588
589 /*******************************************************************
590  Marshall a bind_nak pdu.
591 *******************************************************************/
592
593 static BOOL setup_bind_nak(pipes_struct *p)
594 {
595         prs_struct outgoing_rpc;
596         RPC_HDR nak_hdr;
597         uint16 zero = 0;
598
599         /* Free any memory in the current return data buffer. */
600         prs_mem_free(&p->out_data.rdata);
601
602         /*
603          * Marshall directly into the outgoing PDU space. We
604          * must do this as we need to set to the bind response
605          * header and are never sending more than one PDU here.
606          */
607
608         prs_init( &outgoing_rpc, 0, p->mem_ctx, MARSHALL);
609         prs_give_memory( &outgoing_rpc, (char *)p->out_data.current_pdu, sizeof(p->out_data.current_pdu), False);
610
611
612         /*
613          * Initialize a bind_nak header.
614          */
615
616         init_rpc_hdr(&nak_hdr, RPC_BINDNACK, RPC_FLG_FIRST | RPC_FLG_LAST,
617             p->hdr.call_id, RPC_HEADER_LEN + sizeof(uint16), 0);
618
619         /*
620          * Marshall the header into the outgoing PDU.
621          */
622
623         if(!smb_io_rpc_hdr("", &nak_hdr, &outgoing_rpc, 0)) {
624                 DEBUG(0,("setup_bind_nak: marshalling of RPC_HDR failed.\n"));
625                 prs_mem_free(&outgoing_rpc);
626                 return False;
627         }
628
629         /*
630          * Now add the reject reason.
631          */
632
633         if(!prs_uint16("reject code", &outgoing_rpc, 0, &zero)) {
634                 prs_mem_free(&outgoing_rpc);
635         return False;
636         }
637
638         p->out_data.data_sent_length = 0;
639         p->out_data.current_pdu_len = prs_offset(&outgoing_rpc);
640         p->out_data.current_pdu_sent = 0;
641
642         p->pipe_bound = False;
643
644         return True;
645 }
646
647 /*******************************************************************
648  Marshall a fault pdu.
649 *******************************************************************/
650
651 BOOL setup_fault_pdu(pipes_struct *p, NTSTATUS status)
652 {
653         prs_struct outgoing_pdu;
654         RPC_HDR fault_hdr;
655         RPC_HDR_RESP hdr_resp;
656         RPC_HDR_FAULT fault_resp;
657
658         /* Free any memory in the current return data buffer. */
659         prs_mem_free(&p->out_data.rdata);
660
661         /*
662          * Marshall directly into the outgoing PDU space. We
663          * must do this as we need to set to the bind response
664          * header and are never sending more than one PDU here.
665          */
666
667         prs_init( &outgoing_pdu, 0, p->mem_ctx, MARSHALL);
668         prs_give_memory( &outgoing_pdu, (char *)p->out_data.current_pdu, sizeof(p->out_data.current_pdu), False);
669
670         /*
671          * Initialize a fault header.
672          */
673
674         init_rpc_hdr(&fault_hdr, RPC_FAULT, RPC_FLG_FIRST | RPC_FLG_LAST | RPC_FLG_NOCALL,
675             p->hdr.call_id, RPC_HEADER_LEN + RPC_HDR_RESP_LEN + RPC_HDR_FAULT_LEN, 0);
676
677         /*
678          * Initialize the HDR_RESP and FAULT parts of the PDU.
679          */
680
681         memset((char *)&hdr_resp, '\0', sizeof(hdr_resp));
682
683         fault_resp.status = status;
684         fault_resp.reserved = 0;
685
686         /*
687          * Marshall the header into the outgoing PDU.
688          */
689
690         if(!smb_io_rpc_hdr("", &fault_hdr, &outgoing_pdu, 0)) {
691                 DEBUG(0,("setup_fault_pdu: marshalling of RPC_HDR failed.\n"));
692                 prs_mem_free(&outgoing_pdu);
693                 return False;
694         }
695
696         if(!smb_io_rpc_hdr_resp("resp", &hdr_resp, &outgoing_pdu, 0)) {
697                 DEBUG(0,("setup_fault_pdu: failed to marshall RPC_HDR_RESP.\n"));
698                 prs_mem_free(&outgoing_pdu);
699                 return False;
700         }
701
702         if(!smb_io_rpc_hdr_fault("fault", &fault_resp, &outgoing_pdu, 0)) {
703                 DEBUG(0,("setup_fault_pdu: failed to marshall RPC_HDR_FAULT.\n"));
704                 prs_mem_free(&outgoing_pdu);
705                 return False;
706         }
707
708         p->out_data.data_sent_length = 0;
709         p->out_data.current_pdu_len = prs_offset(&outgoing_pdu);
710         p->out_data.current_pdu_sent = 0;
711
712         prs_mem_free(&outgoing_pdu);
713         return True;
714 }
715
716 /*******************************************************************
717  Ensure a bind request has the correct abstract & transfer interface.
718  Used to reject unknown binds from Win2k.
719 *******************************************************************/
720
721 BOOL check_bind_req(struct pipes_struct *p, RPC_IFACE* abstract,
722                     RPC_IFACE* transfer, uint32 context_id)
723 {
724         extern struct pipe_id_info pipe_names[];
725         char *pipe_name = p->name;
726         int i=0;
727         fstring pname;
728         
729         fstrcpy(pname,"\\PIPE\\");
730         fstrcat(pname,pipe_name);
731
732         DEBUG(3,("check_bind_req for %s\n", pname));
733
734         /* we have to check all now since win2k introduced a new UUID on the lsaprpc pipe */
735                 
736         for ( i=0; pipe_names[i].client_pipe; i++ ) 
737         {
738                 if ( strequal(pipe_names[i].client_pipe, pname)
739                         && (abstract->version == pipe_names[i].abstr_syntax.version) 
740                         && (memcmp(&abstract->uuid, &pipe_names[i].abstr_syntax.uuid, sizeof(RPC_UUID)) == 0)
741                         && (transfer->version == pipe_names[i].trans_syntax.version)
742                         && (memcmp(&transfer->uuid, &pipe_names[i].trans_syntax.uuid, sizeof(RPC_UUID)) == 0) )
743                 {
744                         struct api_struct       *fns = NULL;
745                         int                     n_fns = 0;
746                         PIPE_RPC_FNS            *context_fns;
747                         
748                         if ( !(context_fns = malloc(sizeof(PIPE_RPC_FNS))) ) {
749                                 DEBUG(0,("check_bind_req: malloc() failed!\n"));
750                                 return False;
751                         }
752                         
753                         /* save the RPC function table associated with this bind */
754                         
755                         get_pipe_fns(i, &fns, &n_fns);
756                         
757                         context_fns->cmds = fns;
758                         context_fns->n_cmds = n_fns;
759                         context_fns->context_id = context_id;
760                         
761                         /* add to the list of open contexts */
762                         
763                         DLIST_ADD( p->contexts, context_fns );
764                         
765                         break;
766                 }
767         }
768
769         if(pipe_names[i].client_pipe == NULL)
770                 return False;
771
772         return True;
773 }
774
775 /*******************************************************************
776  Register commands to an RPC pipe
777 *******************************************************************/
778 NTSTATUS rpc_pipe_register_commands(int version, const char *clnt, const char *srv, const struct api_struct *cmds, int size)
779 {
780         struct rpc_table *rpc_entry;
781
782         if (!clnt || !srv || !cmds) {
783                 return NT_STATUS_INVALID_PARAMETER;
784         }
785
786         if (version != SMB_RPC_INTERFACE_VERSION) {
787                 DEBUG(0,("Can't register rpc commands!\n"
788                          "You tried to register a rpc module with SMB_RPC_INTERFACE_VERSION %d"
789                          ", while this version of samba uses version %d!\n", 
790                          version,SMB_RPC_INTERFACE_VERSION));
791                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
792         }
793
794         /* TODO: 
795          *
796          * we still need to make sure that don't register the same commands twice!!!
797          * 
798          * --metze
799          */
800
801         /* We use a temporary variable because this call can fail and 
802            rpc_lookup will still be valid afterwards.  It could then succeed if
803            called again later */
804         rpc_entry = realloc(rpc_lookup, 
805                             ++rpc_lookup_size*sizeof(struct rpc_table));
806         if (NULL == rpc_entry) {
807                 rpc_lookup_size--;
808                 DEBUG(0, ("rpc_pipe_register_commands: memory allocation failed\n"));
809                 return NT_STATUS_NO_MEMORY;
810         } else {
811                 rpc_lookup = rpc_entry;
812         }
813         
814         rpc_entry = rpc_lookup + (rpc_lookup_size - 1);
815         ZERO_STRUCTP(rpc_entry);
816         rpc_entry->pipe.clnt = strdup(clnt);
817         rpc_entry->pipe.srv = strdup(srv);
818         rpc_entry->cmds = realloc(rpc_entry->cmds, 
819                                   (rpc_entry->n_cmds + size) *
820                                   sizeof(struct api_struct));
821         memcpy(rpc_entry->cmds + rpc_entry->n_cmds, cmds,
822                size * sizeof(struct api_struct));
823         rpc_entry->n_cmds += size;
824         
825         return NT_STATUS_OK;
826 }
827
828 /*******************************************************************
829  Respond to a pipe bind request.
830 *******************************************************************/
831
832 BOOL api_pipe_bind_req(pipes_struct *p, prs_struct *rpc_in_p)
833 {
834         RPC_HDR_BA hdr_ba;
835         RPC_HDR_RB hdr_rb;
836         RPC_HDR_AUTH auth_info;
837         uint16 assoc_gid;
838         fstring ack_pipe_name;
839         prs_struct out_hdr_ba;
840         prs_struct out_auth;
841         prs_struct outgoing_rpc;
842         int i = 0;
843         int auth_len = 0;
844         enum RPC_PKT_TYPE reply_pkt_type;
845
846         p->ntlmssp_auth_requested = False;
847         p->netsec_auth_validated = False;
848
849         DEBUG(5,("api_pipe_bind_req: decode request. %d\n", __LINE__));
850
851         /*
852          * Try and find the correct pipe name to ensure
853          * that this is a pipe name we support.
854          */
855
856
857         for (i = 0; i < rpc_lookup_size; i++) {
858                 if (strequal(rpc_lookup[i].pipe.clnt, p->name)) {
859                   DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
860                             rpc_lookup[i].pipe.clnt, rpc_lookup[i].pipe.srv));
861                   fstrcpy(p->pipe_srv_name, rpc_lookup[i].pipe.srv);
862                   break;
863                 }
864         }
865
866         if (i == rpc_lookup_size) {
867                 if (NT_STATUS_IS_ERR(smb_probe_module("rpc", p->name))) {
868                        DEBUG(3,("api_pipe_bind_req: Unknown pipe name %s in bind request.\n",
869                                 p->name ));
870                        if(!setup_bind_nak(p))
871                                return False;
872                        return True;
873                 }
874
875                 for (i = 0; i < rpc_lookup_size; i++) {
876                        if (strequal(rpc_lookup[i].pipe.clnt, p->name)) {
877                                DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
878                                          rpc_lookup[i].pipe.clnt, rpc_lookup[i].pipe.srv));
879                                fstrcpy(p->pipe_srv_name, rpc_lookup[i].pipe.srv);
880                                break;
881                        }
882                 }
883
884                 if (i == rpc_lookup_size) {
885                         DEBUG(0, ("module %s doesn't provide functions for pipe %s!\n", p->name, p->name));
886                         return False;
887                 }
888         }
889
890         /* decode the bind request */
891         if(!smb_io_rpc_hdr_rb("", &hdr_rb, rpc_in_p, 0))  {
892                 DEBUG(0,("api_pipe_bind_req: unable to unmarshall RPC_HDR_RB struct.\n"));
893                 return False;
894         }
895
896         /*
897          * Check if this is an authenticated request.
898          */
899
900         if (p->hdr.auth_len != 0) {
901                 RPC_AUTH_VERIFIER auth_verifier;
902                 RPC_AUTH_NTLMSSP_NEG ntlmssp_neg;
903
904                 /* 
905                  * Decode the authentication verifier.
906                  */
907
908                 if(!smb_io_rpc_hdr_auth("", &auth_info, rpc_in_p, 0)) {
909                         DEBUG(0,("api_pipe_bind_req: unable to unmarshall RPC_HDR_AUTH struct.\n"));
910                         return False;
911                 }
912
913                 if(auth_info.auth_type == NTLMSSP_AUTH_TYPE) {
914
915                         if(!smb_io_rpc_auth_verifier("", &auth_verifier, rpc_in_p, 0)) {
916                                 DEBUG(0,("api_pipe_bind_req: unable to "
917                                          "unmarshall RPC_HDR_AUTH struct.\n"));
918                                 return False;
919                         }
920
921                         if(!strequal(auth_verifier.signature, "NTLMSSP")) {
922                                 DEBUG(0,("api_pipe_bind_req: "
923                                          "auth_verifier.signature != NTLMSSP\n"));
924                                 return False;
925                         }
926
927                         if(auth_verifier.msg_type != NTLMSSP_NEGOTIATE) {
928                                 DEBUG(0,("api_pipe_bind_req: "
929                                          "auth_verifier.msg_type (%d) != NTLMSSP_NEGOTIATE\n",
930                                          auth_verifier.msg_type));
931                                 return False;
932                         }
933
934                         if(!smb_io_rpc_auth_ntlmssp_neg("", &ntlmssp_neg, rpc_in_p, 0)) {
935                                 DEBUG(0,("api_pipe_bind_req: "
936                                          "Failed to unmarshall RPC_AUTH_NTLMSSP_NEG.\n"));
937                                 return False;
938                         }
939
940                         p->ntlmssp_chal_flags = SMBD_NTLMSSP_NEG_FLAGS;
941                         p->ntlmssp_auth_requested = True;
942
943                 } else if (auth_info.auth_type == NETSEC_AUTH_TYPE) {
944
945                         RPC_AUTH_NETSEC_NEG neg;
946                         struct netsec_auth_struct *a = &(p->netsec_auth);
947
948                         if (!smb_io_rpc_auth_netsec_neg("", &neg, rpc_in_p, 0)) {
949                                 DEBUG(0,("api_pipe_bind_req: "
950                                          "Could not unmarshal SCHANNEL auth neg\n"));
951                                 return False;
952                         }
953
954                         p->netsec_auth_validated = True;
955
956                         memset(a->sess_key, 0, sizeof(a->sess_key));
957                         memcpy(a->sess_key, last_dcinfo.sess_key, sizeof(last_dcinfo.sess_key));
958
959                         a->seq_num = 0;
960
961                         DEBUG(10,("schannel auth: domain [%s] myname [%s]\n",
962                                   neg.domain, neg.myname));
963
964                 } else {
965                         DEBUG(0,("api_pipe_bind_req: unknown auth type %x requested.\n",
966                                  auth_info.auth_type ));
967                         return False;
968                 }
969         }
970
971         switch(p->hdr.pkt_type) {
972                 case RPC_BIND:
973                         /* name has to be \PIPE\xxxxx */
974                         fstrcpy(ack_pipe_name, "\\PIPE\\");
975                         fstrcat(ack_pipe_name, p->pipe_srv_name);
976                         reply_pkt_type = RPC_BINDACK;
977                         break;
978                 case RPC_ALTCONT:
979                         /* secondary address CAN be NULL
980                          * as the specs say it's ignored.
981                          * It MUST NULL to have the spoolss working.
982                          */
983                         fstrcpy(ack_pipe_name,"");
984                         reply_pkt_type = RPC_ALTCONTRESP;
985                         break;
986                 default:
987                         return False;
988         }
989
990         DEBUG(5,("api_pipe_bind_req: make response. %d\n", __LINE__));
991
992         /* 
993          * Marshall directly into the outgoing PDU space. We
994          * must do this as we need to set to the bind response
995          * header and are never sending more than one PDU here.
996          */
997
998         prs_init( &outgoing_rpc, 0, p->mem_ctx, MARSHALL);
999         prs_give_memory( &outgoing_rpc, (char *)p->out_data.current_pdu, sizeof(p->out_data.current_pdu), False);
1000
1001         /*
1002          * Setup the memory to marshall the ba header, and the
1003          * auth footers.
1004          */
1005
1006         if(!prs_init(&out_hdr_ba, 1024, p->mem_ctx, MARSHALL)) {
1007                 DEBUG(0,("api_pipe_bind_req: malloc out_hdr_ba failed.\n"));
1008                 prs_mem_free(&outgoing_rpc);
1009                 return False;
1010         }
1011
1012         if(!prs_init(&out_auth, 1024, p->mem_ctx, MARSHALL)) {
1013                 DEBUG(0,("pi_pipe_bind_req: malloc out_auth failed.\n"));
1014                 prs_mem_free(&outgoing_rpc);
1015                 prs_mem_free(&out_hdr_ba);
1016                 return False;
1017         }
1018
1019         if (p->ntlmssp_auth_requested)
1020                 assoc_gid = 0x7a77;
1021         else
1022                 assoc_gid = hdr_rb.bba.assoc_gid ? hdr_rb.bba.assoc_gid : 0x53f0;
1023
1024         /*
1025          * Create the bind response struct.
1026          */
1027
1028         /* If the requested abstract synt uuid doesn't match our client pipe,
1029                 reject the bind_ack & set the transfer interface synt to all 0's,
1030                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1031                 unknown to NT4)
1032                 Needed when adding entries to a DACL from NT5 - SK */
1033
1034         if(check_bind_req(p, &hdr_rb.abstract, &hdr_rb.transfer, hdr_rb.context_id )) 
1035         {
1036                 init_rpc_hdr_ba(&hdr_ba,
1037                         MAX_PDU_FRAG_LEN,
1038                         MAX_PDU_FRAG_LEN,
1039                         assoc_gid,
1040                         ack_pipe_name,
1041                         0x1, 0x0, 0x0,
1042                         &hdr_rb.transfer);
1043         } else {
1044                 RPC_IFACE null_interface;
1045                 ZERO_STRUCT(null_interface);
1046                 /* Rejection reason: abstract syntax not supported */
1047                 init_rpc_hdr_ba(&hdr_ba, MAX_PDU_FRAG_LEN,
1048                                         MAX_PDU_FRAG_LEN, assoc_gid,
1049                                         ack_pipe_name, 0x1, 0x2, 0x1,
1050                                         &null_interface);
1051         }
1052
1053         /*
1054          * and marshall it.
1055          */
1056
1057         if(!smb_io_rpc_hdr_ba("", &hdr_ba, &out_hdr_ba, 0)) {
1058                 DEBUG(0,("api_pipe_bind_req: marshalling of RPC_HDR_BA failed.\n"));
1059                 goto err_exit;
1060         }
1061
1062         /*
1063          * Now the authentication.
1064          */
1065
1066         if (p->ntlmssp_auth_requested) {
1067                 RPC_AUTH_VERIFIER auth_verifier;
1068                 RPC_AUTH_NTLMSSP_CHAL ntlmssp_chal;
1069
1070                 generate_random_buffer(p->challenge, 8, False);
1071
1072                 /*** Authentication info ***/
1073
1074                 init_rpc_hdr_auth(&auth_info, NTLMSSP_AUTH_TYPE, RPC_PIPE_AUTH_SEAL_LEVEL, RPC_HDR_AUTH_LEN, 1);
1075                 if(!smb_io_rpc_hdr_auth("", &auth_info, &out_auth, 0)) {
1076                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_HDR_AUTH failed.\n"));
1077                         goto err_exit;
1078                 }
1079
1080                 /*** NTLMSSP verifier ***/
1081
1082                 init_rpc_auth_verifier(&auth_verifier, "NTLMSSP", NTLMSSP_CHALLENGE);
1083                 if(!smb_io_rpc_auth_verifier("", &auth_verifier, &out_auth, 0)) {
1084                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_AUTH_VERIFIER failed.\n"));
1085                         goto err_exit;
1086                 }
1087
1088                 /* NTLMSSP challenge ***/
1089
1090                 init_rpc_auth_ntlmssp_chal(&ntlmssp_chal, p->ntlmssp_chal_flags, p->challenge);
1091                 if(!smb_io_rpc_auth_ntlmssp_chal("", &ntlmssp_chal, &out_auth, 0)) {
1092                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_AUTH_NTLMSSP_CHAL failed.\n"));
1093                         goto err_exit;
1094                 }
1095
1096                 /* Auth len in the rpc header doesn't include auth_header. */
1097                 auth_len = prs_offset(&out_auth) - RPC_HDR_AUTH_LEN;
1098         }
1099
1100         if (p->netsec_auth_validated) {
1101                 RPC_AUTH_VERIFIER auth_verifier;
1102                 uint32 flags;
1103
1104                 /* The client opens a second RPC NETLOGON pipe without
1105                    doing a auth2. The credentials for the schannel are
1106                    re-used from the auth2 the client did before. */
1107                 p->dc = last_dcinfo;
1108
1109                 init_rpc_hdr_auth(&auth_info, NETSEC_AUTH_TYPE, RPC_PIPE_AUTH_SEAL_LEVEL, RPC_HDR_AUTH_LEN, 1);
1110                 if(!smb_io_rpc_hdr_auth("", &auth_info, &out_auth, 0)) {
1111                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_HDR_AUTH failed.\n"));
1112                         goto err_exit;
1113                 }
1114
1115                 /*** NETSEC verifier ***/
1116
1117                 init_rpc_auth_verifier(&auth_verifier, "\001", 0x0);
1118                 if(!smb_io_rpc_netsec_verifier("", &auth_verifier, &out_auth, 0)) {
1119                         DEBUG(0,("api_pipe_bind_req: marshalling of RPC_AUTH_VERIFIER failed.\n"));
1120                         goto err_exit;
1121                 }
1122
1123                 prs_align(&out_auth);
1124
1125                 flags = 5;
1126                 if(!prs_uint32("flags ", &out_auth, 0, &flags))
1127                         goto err_exit;
1128
1129                 auth_len = prs_offset(&out_auth) - RPC_HDR_AUTH_LEN;
1130         }
1131
1132         /*
1133          * Create the header, now we know the length.
1134          */
1135
1136         init_rpc_hdr(&p->hdr, reply_pkt_type, RPC_FLG_FIRST | RPC_FLG_LAST,
1137                         p->hdr.call_id,
1138                         RPC_HEADER_LEN + prs_offset(&out_hdr_ba) + prs_offset(&out_auth),
1139                         auth_len);
1140
1141         /*
1142          * Marshall the header into the outgoing PDU.
1143          */
1144
1145         if(!smb_io_rpc_hdr("", &p->hdr, &outgoing_rpc, 0)) {
1146                 DEBUG(0,("pi_pipe_bind_req: marshalling of RPC_HDR failed.\n"));
1147                 goto err_exit;
1148         }
1149
1150         /*
1151          * Now add the RPC_HDR_BA and any auth needed.
1152          */
1153
1154         if(!prs_append_prs_data( &outgoing_rpc, &out_hdr_ba)) {
1155                 DEBUG(0,("api_pipe_bind_req: append of RPC_HDR_BA failed.\n"));
1156                 goto err_exit;
1157         }
1158
1159         if((p->ntlmssp_auth_requested|p->netsec_auth_validated) &&
1160            !prs_append_prs_data( &outgoing_rpc, &out_auth)) {
1161                 DEBUG(0,("api_pipe_bind_req: append of auth info failed.\n"));
1162                 goto err_exit;
1163         }
1164
1165         if(!p->ntlmssp_auth_requested)
1166                 p->pipe_bound = True;
1167
1168         /*
1169          * Setup the lengths for the initial reply.
1170          */
1171
1172         p->out_data.data_sent_length = 0;
1173         p->out_data.current_pdu_len = prs_offset(&outgoing_rpc);
1174         p->out_data.current_pdu_sent = 0;
1175
1176         prs_mem_free(&out_hdr_ba);
1177         prs_mem_free(&out_auth);
1178
1179         return True;
1180
1181   err_exit:
1182
1183         prs_mem_free(&outgoing_rpc);
1184         prs_mem_free(&out_hdr_ba);
1185         prs_mem_free(&out_auth);
1186         return False;
1187 }
1188
1189 /****************************************************************************
1190  Deal with sign & seal processing on an RPC request.
1191 ****************************************************************************/
1192
1193 BOOL api_pipe_auth_process(pipes_struct *p, prs_struct *rpc_in)
1194 {
1195         /*
1196          * We always negotiate the following two bits....
1197          */
1198         BOOL auth_verify = ((p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SIGN) != 0);
1199         BOOL auth_seal   = ((p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SEAL) != 0);
1200         int data_len;
1201         int auth_len;
1202         uint32 old_offset;
1203         uint32 crc32 = 0;
1204
1205         auth_len = p->hdr.auth_len;
1206
1207         if ((auth_len != RPC_AUTH_NTLMSSP_CHK_LEN) && auth_verify) {
1208                 DEBUG(0,("api_pipe_auth_process: Incorrect auth_len %d.\n", auth_len ));
1209                 return False;
1210         }
1211
1212         /*
1213          * The following is that length of the data we must verify or unseal.
1214          * This doesn't include the RPC headers or the auth_len or the RPC_HDR_AUTH_LEN
1215          * preceeding the auth_data.
1216          */
1217
1218         data_len = p->hdr.frag_len - RPC_HEADER_LEN - RPC_HDR_REQ_LEN - 
1219                         (auth_verify ? RPC_HDR_AUTH_LEN : 0) - auth_len;
1220         
1221         DEBUG(5,("api_pipe_auth_process: sign: %s seal: %s data %d auth %d\n",
1222                  BOOLSTR(auth_verify), BOOLSTR(auth_seal), data_len, auth_len));
1223
1224         if (auth_seal) {
1225                 /*
1226                  * The data in rpc_in doesn't contain the RPC_HEADER as this
1227                  * has already been consumed.
1228                  */
1229                 char *data = prs_data_p(rpc_in) + RPC_HDR_REQ_LEN;
1230                 dump_data_pw("NTLMSSP hash (v1)\n", p->ntlmssp_hash, 
1231                              sizeof(p->ntlmssp_hash));
1232
1233                 dump_data_pw("Incoming RPC PDU (NTLMSSP sealed)\n", 
1234                              (const unsigned char *)data, data_len);
1235                 NTLMSSPcalc_p(p, (uchar*)data, data_len);
1236                 dump_data_pw("Incoming RPC PDU (NTLMSSP unsealed)\n", 
1237                              (const unsigned char *)data, data_len);
1238                 crc32 = crc32_calc_buffer(data, data_len);
1239         }
1240
1241         old_offset = prs_offset(rpc_in);
1242
1243         if (auth_seal || auth_verify) {
1244                 RPC_HDR_AUTH auth_info;
1245
1246                 if(!prs_set_offset(rpc_in, old_offset + data_len)) {
1247                         DEBUG(0,("api_pipe_auth_process: cannot move offset to %u.\n",
1248                                 (unsigned int)old_offset + data_len ));
1249                         return False;
1250                 }
1251
1252                 if(!smb_io_rpc_hdr_auth("hdr_auth", &auth_info, rpc_in, 0)) {
1253                         DEBUG(0,("api_pipe_auth_process: failed to unmarshall RPC_HDR_AUTH.\n"));
1254                         return False;
1255                 }
1256         }
1257
1258         if (auth_verify) {
1259                 RPC_AUTH_NTLMSSP_CHK ntlmssp_chk;
1260                 char *req_data = prs_data_p(rpc_in) + prs_offset(rpc_in) + 4;
1261
1262                 DEBUG(5,("api_pipe_auth_process: auth %d\n", prs_offset(rpc_in) + 4));
1263
1264                 /*
1265                  * Ensure we have RPC_AUTH_NTLMSSP_CHK_LEN - 4 more bytes in the
1266                  * incoming buffer.
1267                  */
1268                 if(prs_mem_get(rpc_in, RPC_AUTH_NTLMSSP_CHK_LEN - 4) == NULL) {
1269                         DEBUG(0,("api_pipe_auth_process: missing %d bytes in buffer.\n",
1270                                 RPC_AUTH_NTLMSSP_CHK_LEN - 4 ));
1271                         return False;
1272                 }
1273
1274                 NTLMSSPcalc_p(p, (uchar*)req_data, RPC_AUTH_NTLMSSP_CHK_LEN - 4);
1275                 if(!smb_io_rpc_auth_ntlmssp_chk("auth_sign", &ntlmssp_chk, rpc_in, 0)) {
1276                         DEBUG(0,("api_pipe_auth_process: failed to unmarshall RPC_AUTH_NTLMSSP_CHK.\n"));
1277                         return False;
1278                 }
1279
1280                 if (!rpc_auth_ntlmssp_chk(&ntlmssp_chk, crc32, p->ntlmssp_seq_num)) {
1281                         DEBUG(0,("api_pipe_auth_process: NTLMSSP check failed.\n"));
1282                         return False;
1283                 }
1284         }
1285
1286         /*
1287          * Return the current pointer to the data offset.
1288          */
1289
1290         if(!prs_set_offset(rpc_in, old_offset)) {
1291                 DEBUG(0,("api_pipe_auth_process: failed to set offset back to %u\n",
1292                         (unsigned int)old_offset ));
1293                 return False;
1294         }
1295
1296         return True;
1297 }
1298
1299 /****************************************************************************
1300  Deal with schannel processing on an RPC request.
1301 ****************************************************************************/
1302 BOOL api_pipe_netsec_process(pipes_struct *p, prs_struct *rpc_in)
1303 {
1304         /*
1305          * We always negotiate the following two bits....
1306          */
1307         int data_len;
1308         int auth_len;
1309         uint32 old_offset;
1310         RPC_HDR_AUTH auth_info;
1311         RPC_AUTH_NETSEC_CHK netsec_chk;
1312
1313
1314         auth_len = p->hdr.auth_len;
1315
1316         if (auth_len != RPC_AUTH_NETSEC_CHK_LEN) {
1317                 DEBUG(0,("Incorrect auth_len %d.\n", auth_len ));
1318                 return False;
1319         }
1320
1321         /*
1322          * The following is that length of the data we must verify or unseal.
1323          * This doesn't include the RPC headers or the auth_len or the RPC_HDR_AUTH_LEN
1324          * preceeding the auth_data.
1325          */
1326
1327         data_len = p->hdr.frag_len - RPC_HEADER_LEN - RPC_HDR_REQ_LEN - 
1328                 RPC_HDR_AUTH_LEN - auth_len;
1329         
1330         DEBUG(5,("data %d auth %d\n", data_len, auth_len));
1331
1332         old_offset = prs_offset(rpc_in);
1333
1334         if(!prs_set_offset(rpc_in, old_offset + data_len)) {
1335                 DEBUG(0,("cannot move offset to %u.\n",
1336                          (unsigned int)old_offset + data_len ));
1337                 return False;
1338         }
1339
1340         if(!smb_io_rpc_hdr_auth("hdr_auth", &auth_info, rpc_in, 0)) {
1341                 DEBUG(0,("failed to unmarshall RPC_HDR_AUTH.\n"));
1342                 return False;
1343         }
1344
1345         if (auth_info.auth_type != NETSEC_AUTH_TYPE) {
1346                 DEBUG(0,("Invalid auth info %d on schannel\n",
1347                          auth_info.auth_type));
1348                 return False;
1349         }
1350
1351         if (auth_info.auth_level == RPC_PIPE_AUTH_SEAL_LEVEL) {
1352                 p->netsec_auth.auth_flags = AUTH_PIPE_NETSEC|AUTH_PIPE_SIGN|AUTH_PIPE_SEAL;
1353         } else if (auth_info.auth_level == RPC_PIPE_AUTH_SIGN_LEVEL) {
1354                 p->netsec_auth.auth_flags = AUTH_PIPE_NETSEC|AUTH_PIPE_SIGN;
1355         } else {
1356                 DEBUG(0,("Invalid auth level %d on schannel\n",
1357                          auth_info.auth_level));
1358                 return False;
1359         }
1360
1361         if(!smb_io_rpc_auth_netsec_chk("", &netsec_chk, rpc_in, 0)) {
1362                 DEBUG(0,("failed to unmarshal RPC_AUTH_NETSEC_CHK.\n"));
1363                 return False;
1364         }
1365
1366         if (!netsec_decode(&p->netsec_auth,
1367                            p->netsec_auth.auth_flags,
1368                            SENDER_IS_INITIATOR,
1369                            &netsec_chk,
1370                            prs_data_p(rpc_in)+old_offset, data_len)) {
1371                 DEBUG(0,("failed to decode PDU\n"));
1372                 return False;
1373         }
1374
1375         /*
1376          * Return the current pointer to the data offset.
1377          */
1378
1379         if(!prs_set_offset(rpc_in, old_offset)) {
1380                 DEBUG(0,("failed to set offset back to %u\n",
1381                          (unsigned int)old_offset ));
1382                 return False;
1383         }
1384
1385         /* The sequence number gets incremented on both send and receive. */
1386         p->netsec_auth.seq_num++;
1387
1388         return True;
1389 }
1390
1391 /****************************************************************************
1392  Return a user struct for a pipe user.
1393 ****************************************************************************/
1394
1395 struct current_user *get_current_user(struct current_user *user, pipes_struct *p)
1396 {
1397         if (p->ntlmssp_auth_validated) {
1398                 memcpy(user, &p->pipe_user, sizeof(struct current_user));
1399         } else {
1400                 extern struct current_user current_user;
1401                 memcpy(user, &current_user, sizeof(struct current_user));
1402         }
1403
1404         return user;
1405 }
1406
1407 /****************************************************************************
1408  Find the set of RPC functions associated with this context_id
1409 ****************************************************************************/
1410
1411 static PIPE_RPC_FNS* find_pipe_fns_by_context( PIPE_RPC_FNS *list, uint32 context_id )
1412 {
1413         PIPE_RPC_FNS *fns = NULL;
1414         PIPE_RPC_FNS *tmp = NULL;
1415         
1416         if ( !list ) {
1417                 DEBUG(0,("find_pipe_fns_by_context: ERROR!  No context list for pipe!\n"));
1418                 return NULL;
1419         }
1420         
1421         for (tmp=list; tmp; tmp=tmp->next ) {
1422                 if ( tmp->context_id == context_id )
1423                         break;
1424         }
1425         
1426         fns = tmp;
1427         
1428         return fns;
1429 }
1430
1431 /****************************************************************************
1432  memory cleanup
1433 ****************************************************************************/
1434
1435 void free_pipe_rpc_context( PIPE_RPC_FNS *list )
1436 {
1437         PIPE_RPC_FNS *tmp = list;
1438         PIPE_RPC_FNS *tmp2;
1439                 
1440         while (tmp) {
1441                 tmp2 = tmp->next;
1442                 SAFE_FREE(tmp);
1443                 tmp = tmp2;
1444         }
1445
1446         return; 
1447 }
1448
1449 /****************************************************************************
1450  Find the correct RPC function to call for this request.
1451  If the pipe is authenticated then become the correct UNIX user
1452  before doing the call.
1453 ****************************************************************************/
1454
1455 BOOL api_pipe_request(pipes_struct *p)
1456 {
1457         BOOL ret = False;
1458         PIPE_RPC_FNS *pipe_fns;
1459         
1460         if (p->ntlmssp_auth_validated) {
1461
1462                 if(!become_authenticated_pipe_user(p)) {
1463                         prs_mem_free(&p->out_data.rdata);
1464                         return False;
1465                 }
1466         }
1467
1468         DEBUG(5, ("Requested \\PIPE\\%s\n", p->name));
1469         
1470         /* get the set of RPC functions for this context */
1471         
1472         pipe_fns = find_pipe_fns_by_context(p->contexts, p->hdr_req.context_id);
1473         
1474         if ( pipe_fns ) {
1475                 set_current_rpc_talloc(p->mem_ctx);
1476                 ret = api_rpcTNP(p, p->name, pipe_fns->cmds, pipe_fns->n_cmds);
1477                 set_current_rpc_talloc(NULL);   
1478         }
1479         else {
1480                 DEBUG(0,("api_pipe_request: No rpc function table associated with context [%d] on pipe [%s]\n",
1481                         p->hdr_req.context_id, p->name));
1482         }
1483
1484         if(p->ntlmssp_auth_validated)
1485                 unbecome_authenticated_pipe_user();
1486
1487         return ret;
1488 }
1489
1490 /*******************************************************************
1491  Calls the underlying RPC function for a named pipe.
1492  ********************************************************************/
1493
1494 BOOL api_rpcTNP(pipes_struct *p, const char *rpc_name, 
1495                 const struct api_struct *api_rpc_cmds, int n_cmds)
1496 {
1497         int fn_num;
1498         fstring name;
1499         uint32 offset1, offset2;
1500  
1501         /* interpret the command */
1502         DEBUG(4,("api_rpcTNP: %s op 0x%x - ", rpc_name, p->hdr_req.opnum));
1503
1504         slprintf(name, sizeof(name)-1, "in_%s", rpc_name);
1505         prs_dump(name, p->hdr_req.opnum, &p->in_data.data);
1506
1507         for (fn_num = 0; fn_num < n_cmds; fn_num++) {
1508                 if (api_rpc_cmds[fn_num].opnum == p->hdr_req.opnum && api_rpc_cmds[fn_num].fn != NULL) {
1509                         DEBUG(3,("api_rpcTNP: rpc command: %s\n", api_rpc_cmds[fn_num].name));
1510                         break;
1511                 }
1512         }
1513
1514         if (fn_num == n_cmds) {
1515                 /*
1516                  * For an unknown RPC just return a fault PDU but
1517                  * return True to allow RPC's on the pipe to continue
1518                  * and not put the pipe into fault state. JRA.
1519                  */
1520                 DEBUG(4, ("unknown\n"));
1521                 setup_fault_pdu(p, NT_STATUS(0x1c010002));
1522                 return True;
1523         }
1524
1525         offset1 = prs_offset(&p->out_data.rdata);
1526
1527         DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", 
1528                 fn_num, api_rpc_cmds[fn_num].fn));
1529         /* do the actual command */
1530         if(!api_rpc_cmds[fn_num].fn(p)) {
1531                 DEBUG(0,("api_rpcTNP: %s: %s failed.\n", rpc_name, api_rpc_cmds[fn_num].name));
1532                 prs_mem_free(&p->out_data.rdata);
1533                 return False;
1534         }
1535
1536         if (p->bad_handle_fault_state) {
1537                 DEBUG(4,("api_rpcTNP: bad handle fault return.\n"));
1538                 p->bad_handle_fault_state = False;
1539                 setup_fault_pdu(p, NT_STATUS(0x1C00001A));
1540                 return True;
1541         }
1542
1543         slprintf(name, sizeof(name)-1, "out_%s", rpc_name);
1544         offset2 = prs_offset(&p->out_data.rdata);
1545         prs_set_offset(&p->out_data.rdata, offset1);
1546         prs_dump(name, p->hdr_req.opnum, &p->out_data.rdata);
1547         prs_set_offset(&p->out_data.rdata, offset2);
1548
1549         DEBUG(5,("api_rpcTNP: called %s successfully\n", rpc_name));
1550
1551         /* Check for buffer underflow in rpc parsing */
1552
1553         if ((DEBUGLEVEL >= 10) && 
1554             (prs_offset(&p->in_data.data) != prs_data_size(&p->in_data.data))) {
1555                 size_t data_len = prs_data_size(&p->in_data.data) - prs_offset(&p->in_data.data);
1556                 char *data;
1557
1558                 data = malloc(data_len);
1559
1560                 DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n"));
1561                 if (data) {
1562                         prs_uint8s(False, "", &p->in_data.data, 0, (unsigned char *)data, (uint32)data_len);
1563                         SAFE_FREE(data);
1564                 }
1565
1566         }
1567
1568         return True;
1569 }
1570
1571 /*******************************************************************
1572 *******************************************************************/
1573
1574 void get_pipe_fns( int idx, struct api_struct **fns, int *n_fns )
1575 {
1576         struct api_struct *cmds = NULL;
1577         int               n_cmds = 0;
1578
1579         switch ( idx ) {
1580                 case PI_LSARPC:
1581                         lsa_get_pipe_fns( &cmds, &n_cmds );
1582                         break;
1583                 case PI_LSARPC_DS:
1584                         lsa_ds_get_pipe_fns( &cmds, &n_cmds );
1585                         break;
1586                 case PI_SAMR:
1587                         samr_get_pipe_fns( &cmds, &n_cmds );
1588                         break;
1589                 case PI_NETLOGON:
1590                         netlog_get_pipe_fns( &cmds, &n_cmds );
1591                         break;
1592                 case PI_SRVSVC:
1593                         srvsvc_get_pipe_fns( &cmds, &n_cmds );
1594                         break;
1595                 case PI_WKSSVC:
1596                         wkssvc_get_pipe_fns( &cmds, &n_cmds );
1597                         break;
1598                 case PI_WINREG:
1599                         reg_get_pipe_fns( &cmds, &n_cmds );
1600                         break;
1601                 case PI_SPOOLSS:
1602                         spoolss_get_pipe_fns( &cmds, &n_cmds );
1603                         break;
1604                 case PI_NETDFS:
1605                         netdfs_get_pipe_fns( &cmds, &n_cmds );
1606                         break;
1607 #ifdef DEVELOPER
1608                 case PI_ECHO:
1609                         echo_get_pipe_fns( &cmds, &n_cmds );
1610                         break;
1611 #endif
1612                 default:
1613                         DEBUG(0,("get_pipe_fns: Unknown pipe index! [%d]\n", idx));
1614         }
1615
1616         *fns = cmds;
1617         *n_fns = n_cmds;
1618
1619         return;
1620 }
1621
1622