s3-dcerpc: Use a local function to dump pdu regions
[kai/samba.git] / source3 / rpc_server / srv_pipe.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Almost completely rewritten by (C) Jeremy Allison 2005 - 2010
5  *  
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 3 of the License, or
9  *  (at your option) any later version.
10  *  
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *  
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*  this module apparently provides an implementation of DCE/RPC over a
21  *  named pipe (IPC$ connection using SMBtrans).  details of DCE/RPC
22  *  documentation are available (in on-line form) from the X-Open group.
23  *
24  *  this module should provide a level of abstraction between SMB
25  *  and DCE/RPC, while minimising the amount of mallocs, unnecessary
26  *  data copies, and network traffic.
27  *
28  */
29
30 #include "includes.h"
31 #include "srv_pipe_internal.h"
32 #include "../librpc/gen_ndr/ndr_schannel.h"
33 #include "../libcli/auth/schannel.h"
34 #include "../libcli/auth/spnego.h"
35 #include "../libcli/auth/ntlmssp.h"
36
37 #undef DBGC_CLASS
38 #define DBGC_CLASS DBGC_RPC_SRV
39
40 /**
41  * Dump everything from the start of the end up of the provided data
42  * into a file, but only at debug level >= 50
43  **/
44 static void dump_pdu_region(const char *name, int v,
45                             DATA_BLOB *data, size_t start, size_t end)
46 {
47         int fd, i;
48         char *fname = NULL;
49         ssize_t sz;
50
51         if (DEBUGLEVEL < 50) return;
52
53         if (start > data->length || end > data->length || start > end) return;
54
55         for (i = 1; i < 100; i++) {
56                 if (v != -1) {
57                         fname = talloc_asprintf(talloc_tos(),
58                                                 "/tmp/%s_%d.%d.prs",
59                                                 name, v, i);
60                 } else {
61                         fname = talloc_asprintf(talloc_tos(),
62                                                 "/tmp/%s_%d.prs",
63                                                 name, i);
64                 }
65                 if (!fname) {
66                         return;
67                 }
68                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
69                 if (fd != -1 || errno != EEXIST) break;
70         }
71         if (fd != -1) {
72                 sz = write(fd, data->data + start, end - start);
73                 i = close(fd);
74                 if ((sz != end - start) || (i != 0) ) {
75                         DEBUG(0, ("Error writing/closing %s: %ld!=%ld %d\n",
76                                   fname, (unsigned long)sz,
77                                   (unsigned long)end - start, i));
78                 } else {
79                         DEBUG(0,("created %s\n", fname));
80                 }
81         }
82         TALLOC_FREE(fname);
83 }
84
85 static void free_pipe_ntlmssp_auth_data(struct pipe_auth_data *auth)
86 {
87         struct auth_ntlmssp_state *a = auth->a_u.auth_ntlmssp_state;
88
89         if (a) {
90                 auth_ntlmssp_end(&a);
91         }
92         auth->a_u.auth_ntlmssp_state = NULL;
93 }
94
95 static DATA_BLOB generic_session_key(void)
96 {
97         return data_blob("SystemLibraryDTC", 16);
98 }
99
100 /*******************************************************************
101  Handle NTLMSSP.
102  ********************************************************************/
103
104 static bool add_ntlmssp_auth(pipes_struct *p)
105 {
106         enum dcerpc_AuthLevel auth_level = p->auth.auth_level;
107         DATA_BLOB auth_blob = data_blob_null;
108         NTSTATUS status;
109
110         /* FIXME: Is this right ?
111          * Keeping only to avoid changing semantics during refactoring
112          * --simo
113          */
114         if (auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
115                 auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
116         }
117
118         /* Generate the auth blob. */
119         switch (auth_level) {
120         case DCERPC_AUTH_LEVEL_PRIVACY:
121                 /* Data portion is encrypted. */
122                 status = auth_ntlmssp_seal_packet(
123                                 p->auth.a_u.auth_ntlmssp_state,
124                                 (TALLOC_CTX *)p->out_data.frag.data,
125                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
126                                 p->out_data.frag.length
127                                         - DCERPC_RESPONSE_LENGTH
128                                         - DCERPC_AUTH_TRAILER_LENGTH,
129                                 p->out_data.frag.data,
130                                 p->out_data.frag.length,
131                                 &auth_blob);
132                 break;
133
134         case DCERPC_AUTH_LEVEL_INTEGRITY:
135                 /* Data is signed. */
136                 status = auth_ntlmssp_sign_packet(
137                                 p->auth.a_u.auth_ntlmssp_state,
138                                 (TALLOC_CTX *)p->out_data.frag.data,
139                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
140                                 p->out_data.frag.length
141                                         - DCERPC_RESPONSE_LENGTH
142                                         - DCERPC_AUTH_TRAILER_LENGTH,
143                                 p->out_data.frag.data,
144                                 p->out_data.frag.length,
145                                 &auth_blob);
146                 break;
147
148         default:
149                 status = NT_STATUS_INTERNAL_ERROR;
150                 return false;
151         }
152
153         if (!NT_STATUS_IS_OK(status)) {
154                 DEBUG(0, ("Failed to add NTLMSSP auth blob: %s\n",
155                         nt_errstr(status)));
156                 data_blob_free(&p->out_data.frag);
157                 return false;
158         }
159
160         /* Finally append the auth blob. */
161         if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
162                                 auth_blob.data, auth_blob.length)) {
163                 DEBUG(0, ("Failed to add %u bytes auth blob.\n",
164                           (unsigned int)auth_blob.length));
165                 data_blob_free(&p->out_data.frag);
166                 return False;
167         }
168         data_blob_free(&auth_blob);
169
170         return true;
171 }
172
173 /*******************************************************************
174  Append a schannel authenticated fragment.
175  ********************************************************************/
176
177 static bool add_schannel_auth(pipes_struct *p)
178 {
179         DATA_BLOB auth_blob = data_blob_null;
180         NTSTATUS status;
181
182         /* Schannel processing. */
183         switch (p->auth.auth_level) {
184         case DCERPC_AUTH_LEVEL_PRIVACY:
185                 status = netsec_outgoing_packet(
186                                 p->auth.a_u.schannel_auth,
187                                 (TALLOC_CTX *)p->out_data.frag.data,
188                                 true,
189                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
190                                 p->out_data.frag.length
191                                         - DCERPC_RESPONSE_LENGTH
192                                         - DCERPC_AUTH_TRAILER_LENGTH,
193                                 &auth_blob);
194                 break;
195
196         case DCERPC_AUTH_LEVEL_INTEGRITY:
197                 status = netsec_outgoing_packet(
198                                 p->auth.a_u.schannel_auth,
199                                 (TALLOC_CTX *)p->out_data.frag.data,
200                                 false,
201                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
202                                 p->out_data.frag.length
203                                         - DCERPC_RESPONSE_LENGTH
204                                         - DCERPC_AUTH_TRAILER_LENGTH,
205                                 &auth_blob);
206                 break;
207
208         default:
209                 status = NT_STATUS_INTERNAL_ERROR;
210                 break;
211         }
212
213         if (!NT_STATUS_IS_OK(status)) {
214                 DEBUG(0, ("Failed to add SCHANNEL auth blob: %s\n",
215                         nt_errstr(status)));
216                 data_blob_free(&p->out_data.frag);
217                 return false;
218         }
219
220         if (DEBUGLEVEL >= 10) {
221                 dump_NL_AUTH_SIGNATURE(talloc_tos(), &auth_blob);
222         }
223
224         if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
225                                 auth_blob.data, auth_blob.length)) {
226                 DEBUG(0, ("Failed to add %u bytes auth blob.\n",
227                           (unsigned int)auth_blob.length));
228                 data_blob_free(&p->out_data.frag);
229                 return false;
230         }
231         data_blob_free(&auth_blob);
232
233         return true;
234 }
235
236 /*******************************************************************
237  Generate the next PDU to be returned from the data.
238 ********************************************************************/
239
240 static bool create_next_packet(pipes_struct *p,
241                                 enum dcerpc_AuthType auth_type,
242                                 enum dcerpc_AuthLevel auth_level,
243                                 size_t auth_length)
244 {
245         union dcerpc_payload u;
246         uint8_t pfc_flags;
247         size_t data_len_left;
248         size_t data_len;
249         size_t max_len;
250         size_t pad_len = 0;
251         NTSTATUS status;
252
253         ZERO_STRUCT(u.response);
254
255         /* Set up rpc packet pfc flags. */
256         if (p->out_data.data_sent_length == 0) {
257                 pfc_flags = DCERPC_PFC_FLAG_FIRST;
258         } else {
259                 pfc_flags = 0;
260         }
261
262         /* Work out how much we can fit in a single PDU. */
263         data_len_left = p->out_data.rdata.length -
264                                 p->out_data.data_sent_length;
265
266         /* Ensure there really is data left to send. */
267         if (!data_len_left) {
268                 DEBUG(0, ("No data left to send !\n"));
269                 return false;
270         }
271
272         /* Max space available - not including padding. */
273         if (auth_length) {
274                 max_len = RPC_MAX_PDU_FRAG_LEN
275                                 - DCERPC_RESPONSE_LENGTH
276                                 - DCERPC_AUTH_TRAILER_LENGTH
277                                 - auth_length;
278         } else {
279                 max_len = RPC_MAX_PDU_FRAG_LEN - DCERPC_RESPONSE_LENGTH;
280         }
281
282         /*
283          * The amount we send is the minimum of the max_len
284          * and the amount left to send.
285          */
286         data_len = MIN(data_len_left, max_len);
287
288         if (auth_length) {
289                 /* Work out any padding alignment requirements. */
290                 pad_len = (DCERPC_RESPONSE_LENGTH + data_len) %
291                                                 SERVER_NDR_PADDING_SIZE;
292                 if (pad_len) {
293                         pad_len = SERVER_NDR_PADDING_SIZE - pad_len;
294                         DEBUG(10, ("Padding size is: %d\n", (int)pad_len));
295                         /* If we're over filling the packet, we need to make
296                          * space for the padding at the end of the data. */
297                         if (data_len + pad_len > max_len) {
298                                 data_len -= SERVER_NDR_PADDING_SIZE;
299                         }
300                 }
301         }
302
303         /* Set up the alloc hint. This should be the data left to send. */
304         u.response.alloc_hint = data_len_left;
305
306         /* Work out if this PDU will be the last. */
307         if (p->out_data.data_sent_length
308                                 + data_len >= p->out_data.rdata.length) {
309                 pfc_flags |= DCERPC_PFC_FLAG_LAST;
310         }
311
312         /* Prepare data to be NDR encoded. */
313         u.response.stub_and_verifier =
314                 data_blob_const(p->out_data.rdata.data +
315                                 p->out_data.data_sent_length, data_len);
316
317         /* Store the packet in the data stream. */
318         status = dcerpc_push_ncacn_packet(p->mem_ctx,
319                                           DCERPC_PKT_RESPONSE,
320                                           pfc_flags,
321                                           auth_length,
322                                           p->call_id,
323                                           &u,
324                                           &p->out_data.frag);
325         if (!NT_STATUS_IS_OK(status)) {
326                 DEBUG(0, ("Failed to marshall RPC Packet.\n"));
327                 return false;
328         }
329
330         if (auth_length) {
331                 DATA_BLOB empty = data_blob_null;
332                 DATA_BLOB auth_hdr;
333
334                 /* Set the proper length on the pdu, including padding.
335                  * Only needed if an auth trailer will be appended. */
336                 dcerpc_set_frag_length(&p->out_data.frag,
337                                         p->out_data.frag.length
338                                                 + pad_len
339                                                 + DCERPC_AUTH_TRAILER_LENGTH
340                                                 + auth_length);
341
342                 if (pad_len) {
343                         size_t offset = p->out_data.frag.length;
344
345                         if (!data_blob_realloc(p->mem_ctx,
346                                                 &p->out_data.frag,
347                                                 offset + pad_len)) {
348                                 DEBUG(0, ("Failed to add padding!\n"));
349                                 data_blob_free(&p->out_data.frag);
350                                 return false;
351                         }
352                         memset(&p->out_data.frag.data[offset], '\0', pad_len);
353                 }
354
355                 /* auth blob is intentionally empty,
356                  * it will be appended later */
357                 status = dcerpc_push_dcerpc_auth(p->out_data.frag.data,
358                                                  auth_type,
359                                                  auth_level,
360                                                  pad_len,
361                                                  1, /* context id. */
362                                                  &empty,
363                                                  &auth_hdr);
364                 if (!NT_STATUS_IS_OK(status)) {
365                         DEBUG(0, ("Failed to marshall RPC Auth.\n"));
366                         return false;
367                 }
368
369                 /* Store auth header in the data stream. */
370                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
371                                         auth_hdr.data, auth_hdr.length)) {
372                         DEBUG(0, ("Out of memory.\n"));
373                         data_blob_free(&p->out_data.frag);
374                         return false;
375                 }
376                 data_blob_free(&auth_hdr);
377         }
378
379         /* Setup the counts for this PDU. */
380         p->out_data.data_sent_length += data_len;
381         p->out_data.current_pdu_sent = 0;
382         return true;
383 }
384
385 /*******************************************************************
386  Generate the next PDU to be returned from the data in p->rdata. 
387 ********************************************************************/
388
389 bool create_next_pdu(pipes_struct *p)
390 {
391         enum dcerpc_AuthType auth_type =
392                 map_pipe_auth_type_to_rpc_auth_type(p->auth.auth_type);
393
394         /*
395          * If we're in the fault state, keep returning fault PDU's until
396          * the pipe gets closed. JRA.
397          */
398         if (p->fault_state) {
399                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
400                 return true;
401         }
402
403         switch (p->auth.auth_level) {
404         case DCERPC_AUTH_LEVEL_NONE:
405         case DCERPC_AUTH_LEVEL_CONNECT:
406                 /* This is incorrect for auth level connect. Fixme. JRA */
407
408                 /* No authentication done. */
409                 return create_next_packet(p, auth_type,
410                                           p->auth.auth_level, 0);
411
412         case DCERPC_AUTH_LEVEL_CALL:
413         case DCERPC_AUTH_LEVEL_PACKET:
414         case DCERPC_AUTH_LEVEL_INTEGRITY:
415         case DCERPC_AUTH_LEVEL_PRIVACY:
416
417                 switch(p->auth.auth_type) {
418                 case PIPE_AUTH_TYPE_NTLMSSP:
419                 case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
420                         if (!create_next_packet(p, auth_type,
421                                                 p->auth.auth_level,
422                                                 NTLMSSP_SIG_SIZE)) {
423                                 return false;
424                         }
425                         return add_ntlmssp_auth(p);
426
427                 case PIPE_AUTH_TYPE_SCHANNEL:
428                         if (!create_next_packet(p, auth_type,
429                                                 p->auth.auth_level,
430                                                 SCHANNEL_SIG_SIZE)) {
431                                 return false;
432                         }
433                         return add_schannel_auth(p);
434                 default:
435                         break;
436                 }
437         default:
438                 break;
439         }
440
441         DEBUG(0, ("Invalid internal auth level %u / type %u\n",
442                   (unsigned int)p->auth.auth_level,
443                   (unsigned int)p->auth.auth_type));
444         return false;
445 }
446
447 /*******************************************************************
448  Process an NTLMSSP authentication response.
449  If this function succeeds, the user has been authenticated
450  and their domain, name and calling workstation stored in
451  the pipe struct.
452 *******************************************************************/
453
454 static bool pipe_ntlmssp_verify_final(pipes_struct *p, DATA_BLOB *p_resp_blob)
455 {
456         DATA_BLOB session_key, reply;
457         NTSTATUS status;
458         struct auth_ntlmssp_state *a = p->auth.a_u.auth_ntlmssp_state;
459         bool ret;
460
461         DEBUG(5,("pipe_ntlmssp_verify_final: pipe %s checking user details\n",
462                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
463
464         ZERO_STRUCT(reply);
465
466         /* this has to be done as root in order to verify the password */
467         become_root();
468         status = auth_ntlmssp_update(a, *p_resp_blob, &reply);
469         unbecome_root();
470
471         /* Don't generate a reply. */
472         data_blob_free(&reply);
473
474         if (!NT_STATUS_IS_OK(status)) {
475                 return False;
476         }
477
478         /* Finally - if the pipe negotiated integrity (sign) or privacy (seal)
479            ensure the underlying NTLMSSP flags are also set. If not we should
480            refuse the bind. */
481
482         if (p->auth.auth_level == DCERPC_AUTH_LEVEL_INTEGRITY) {
483                 if (!auth_ntlmssp_negotiated_sign(a)) {
484                         DEBUG(0,("pipe_ntlmssp_verify_final: pipe %s : packet integrity requested "
485                                 "but client declined signing.\n",
486                                  get_pipe_name_from_syntax(talloc_tos(),
487                                                            &p->syntax)));
488                         return False;
489                 }
490         }
491         if (p->auth.auth_level == DCERPC_AUTH_LEVEL_PRIVACY) {
492                 if (!auth_ntlmssp_negotiated_seal(a)) {
493                         DEBUG(0,("pipe_ntlmssp_verify_final: pipe %s : packet privacy requested "
494                                 "but client declined sealing.\n",
495                                  get_pipe_name_from_syntax(talloc_tos(),
496                                                            &p->syntax)));
497                         return False;
498                 }
499         }
500
501         DEBUG(5, ("pipe_ntlmssp_verify_final: OK: user: %s domain: %s "
502                   "workstation: %s\n",
503                   auth_ntlmssp_get_username(a),
504                   auth_ntlmssp_get_domain(a),
505                   auth_ntlmssp_get_client(a)));
506
507         TALLOC_FREE(p->server_info);
508
509         status = auth_ntlmssp_server_info(p, a, &p->server_info);
510         if (!NT_STATUS_IS_OK(status)) {
511                 DEBUG(0, ("auth_ntlmssp_server_info failed to obtain the server info for authenticated user: %s\n",
512                           nt_errstr(status)));
513                 return false;
514         }
515
516         if (p->server_info->ptok == NULL) {
517                 DEBUG(1,("Error: Authmodule failed to provide nt_user_token\n"));
518                 return False;
519         }
520
521         /*
522          * We're an authenticated bind over smb, so the session key needs to
523          * be set to "SystemLibraryDTC". Weird, but this is what Windows
524          * does. See the RPC-SAMBA3SESSIONKEY.
525          */
526
527         session_key = generic_session_key();
528         if (session_key.data == NULL) {
529                 return False;
530         }
531
532         ret = server_info_set_session_key(p->server_info, session_key);
533
534         data_blob_free(&session_key);
535
536         return True;
537 }
538
539 /*******************************************************************
540  This is the "stage3" NTLMSSP response after a bind request and reply.
541 *******************************************************************/
542
543 bool api_pipe_bind_auth3(pipes_struct *p, struct ncacn_packet *pkt)
544 {
545         struct dcerpc_auth auth_info;
546         NTSTATUS status;
547
548         DEBUG(5, ("api_pipe_bind_auth3: decode request. %d\n", __LINE__));
549
550         if (pkt->auth_length == 0) {
551                 DEBUG(0, ("No auth field sent for bind request!\n"));
552                 goto err;
553         }
554
555         /* Ensure there's enough data for an authenticated request. */
556         if (pkt->frag_length < RPC_HEADER_LEN
557                                 + DCERPC_AUTH_TRAILER_LENGTH
558                                 + pkt->auth_length) {
559                         DEBUG(0,("api_pipe_ntlmssp_auth_process: auth_len "
560                                 "%u is too large.\n",
561                         (unsigned int)pkt->auth_length));
562                 goto err;
563         }
564
565         /*
566          * Decode the authentication verifier response.
567          */
568
569         status = dcerpc_pull_dcerpc_auth(pkt,
570                                          &pkt->u.auth3.auth_info,
571                                          &auth_info);
572         if (!NT_STATUS_IS_OK(status)) {
573                 DEBUG(0, ("Failed to unmarshall dcerpc_auth.\n"));
574                 goto err;
575         }
576
577         /* We must NEVER look at auth_info->auth_pad_len here,
578          * as old Samba client code gets it wrong and sends it
579          * as zero. JRA.
580          */
581
582         if (auth_info.auth_type != DCERPC_AUTH_TYPE_NTLMSSP) {
583                 DEBUG(0,("api_pipe_bind_auth3: incorrect auth type (%u).\n",
584                         (unsigned int)auth_info.auth_type ));
585                 return False;
586         }
587
588         /*
589          * The following call actually checks the challenge/response data.
590          * for correctness against the given DOMAIN\user name.
591          */
592
593         if (!pipe_ntlmssp_verify_final(p, &auth_info.credentials)) {
594                 goto err;
595         }
596
597         p->pipe_bound = True;
598
599         return True;
600
601  err:
602
603         free_pipe_ntlmssp_auth_data(&p->auth);
604         p->auth.a_u.auth_ntlmssp_state = NULL;
605
606         return False;
607 }
608
609 /*******************************************************************
610  Marshall a bind_nak pdu.
611 *******************************************************************/
612
613 static bool setup_bind_nak(pipes_struct *p, struct ncacn_packet *pkt)
614 {
615         NTSTATUS status;
616         union dcerpc_payload u;
617
618         /* Free any memory in the current return data buffer. */
619         data_blob_free(&p->out_data.rdata);
620
621         /*
622          * Initialize a bind_nak header.
623          */
624
625         ZERO_STRUCT(u);
626
627         u.bind_nak.reject_reason  = 0;
628
629         /*
630          * Marshall directly into the outgoing PDU space. We
631          * must do this as we need to set to the bind response
632          * header and are never sending more than one PDU here.
633          */
634
635         status = dcerpc_push_ncacn_packet(p->mem_ctx,
636                                           DCERPC_PKT_BIND_NAK,
637                                           DCERPC_PFC_FLAG_FIRST |
638                                                 DCERPC_PFC_FLAG_LAST,
639                                           0,
640                                           pkt->call_id,
641                                           &u,
642                                           &p->out_data.frag);
643         if (!NT_STATUS_IS_OK(status)) {
644                 return False;
645         }
646
647         p->out_data.data_sent_length = 0;
648         p->out_data.current_pdu_sent = 0;
649
650         if (p->auth.auth_data_free_func) {
651                 (*p->auth.auth_data_free_func)(&p->auth);
652         }
653         p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
654         p->auth.auth_type = PIPE_AUTH_TYPE_NONE;
655         p->pipe_bound = False;
656
657         return True;
658 }
659
660 /*******************************************************************
661  Marshall a fault pdu.
662 *******************************************************************/
663
664 bool setup_fault_pdu(pipes_struct *p, NTSTATUS fault_status)
665 {
666         NTSTATUS status;
667         union dcerpc_payload u;
668
669         /* Free any memory in the current return data buffer. */
670         data_blob_free(&p->out_data.rdata);
671
672         /*
673          * Initialize a fault header.
674          */
675
676         ZERO_STRUCT(u);
677
678         u.fault.status          = NT_STATUS_V(fault_status);
679         u.fault._pad            = data_blob_talloc_zero(p->mem_ctx, 4);
680
681         /*
682          * Marshall directly into the outgoing PDU space. We
683          * must do this as we need to set to the bind response
684          * header and are never sending more than one PDU here.
685          */
686
687         status = dcerpc_push_ncacn_packet(p->mem_ctx,
688                                           DCERPC_PKT_FAULT,
689                                           DCERPC_PFC_FLAG_FIRST |
690                                            DCERPC_PFC_FLAG_LAST |
691                                            DCERPC_PFC_FLAG_DID_NOT_EXECUTE,
692                                           0,
693                                           p->call_id,
694                                           &u,
695                                           &p->out_data.frag);
696         if (!NT_STATUS_IS_OK(status)) {
697                 return False;
698         }
699
700         p->out_data.data_sent_length = 0;
701         p->out_data.current_pdu_sent = 0;
702
703         return True;
704 }
705
706 /*******************************************************************
707  Ensure a bind request has the correct abstract & transfer interface.
708  Used to reject unknown binds from Win2k.
709 *******************************************************************/
710
711 static bool check_bind_req(struct pipes_struct *p,
712                            struct ndr_syntax_id* abstract,
713                            struct ndr_syntax_id* transfer,
714                            uint32 context_id)
715 {
716         struct pipe_rpc_fns *context_fns;
717
718         DEBUG(3,("check_bind_req for %s\n",
719                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
720
721         /* we have to check all now since win2k introduced a new UUID on the lsaprpc pipe */
722         if (rpc_srv_pipe_exists_by_id(abstract) &&
723            ndr_syntax_id_equal(transfer, &ndr_transfer_syntax)) {
724                 DEBUG(3, ("check_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
725                         rpc_srv_get_pipe_cli_name(abstract),
726                         rpc_srv_get_pipe_srv_name(abstract)));
727         } else {
728                 return false;
729         }
730
731         context_fns = SMB_MALLOC_P(struct pipe_rpc_fns);
732         if (context_fns == NULL) {
733                 DEBUG(0,("check_bind_req: malloc() failed!\n"));
734                 return False;
735         }
736
737         context_fns->n_cmds = rpc_srv_get_pipe_num_cmds(abstract);
738         context_fns->cmds = rpc_srv_get_pipe_cmds(abstract);
739         context_fns->context_id = context_id;
740
741         /* add to the list of open contexts */
742
743         DLIST_ADD( p->contexts, context_fns );
744
745         return True;
746 }
747
748 /**
749  * Is a named pipe known?
750  * @param[in] cli_filename      The pipe name requested by the client
751  * @result                      Do we want to serve this?
752  */
753 bool is_known_pipename(const char *cli_filename, struct ndr_syntax_id *syntax)
754 {
755         const char *pipename = cli_filename;
756         NTSTATUS status;
757
758         if (strnequal(pipename, "\\PIPE\\", 6)) {
759                 pipename += 5;
760         }
761
762         if (*pipename == '\\') {
763                 pipename += 1;
764         }
765
766         if (lp_disable_spoolss() && strequal(pipename, "spoolss")) {
767                 DEBUG(10, ("refusing spoolss access\n"));
768                 return false;
769         }
770
771         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
772                 return true;
773         }
774
775         status = smb_probe_module("rpc", pipename);
776         if (!NT_STATUS_IS_OK(status)) {
777                 DEBUG(10, ("is_known_pipename: %s unknown\n", cli_filename));
778                 return false;
779         }
780         DEBUG(10, ("is_known_pipename: %s loaded dynamically\n", pipename));
781
782         /*
783          * Scan the list again for the interface id
784          */
785         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
786                 return true;
787         }
788
789         DEBUG(10, ("is_known_pipename: pipe %s did not register itself!\n",
790                    pipename));
791
792         return false;
793 }
794
795 /*******************************************************************
796  Handle a SPNEGO krb5 bind auth.
797 *******************************************************************/
798
799 static bool pipe_spnego_auth_bind_kerberos(pipes_struct *p,
800                                            TALLOC_CTX *mem_ctx,
801                                            struct dcerpc_auth *pauth_info,
802                                            DATA_BLOB *psecblob,
803                                            DATA_BLOB *response)
804 {
805         return False;
806 }
807
808 /*******************************************************************
809  Handle the first part of a SPNEGO bind auth.
810 *******************************************************************/
811
812 static bool pipe_spnego_auth_bind_negotiate(pipes_struct *p,
813                                             TALLOC_CTX *mem_ctx,
814                                             struct dcerpc_auth *pauth_info,
815                                             DATA_BLOB *response)
816 {
817         DATA_BLOB secblob;
818         DATA_BLOB chal;
819         char *OIDs[ASN1_MAX_OIDS];
820         int i;
821         NTSTATUS status;
822         bool got_kerberos_mechanism = false;
823         struct auth_ntlmssp_state *a = NULL;
824
825         ZERO_STRUCT(secblob);
826         ZERO_STRUCT(chal);
827
828         if (pauth_info->credentials.data[0] != ASN1_APPLICATION(0)) {
829                 goto err;
830         }
831
832         /* parse out the OIDs and the first sec blob */
833         if (!parse_negTokenTarg(pauth_info->credentials, OIDs, &secblob)) {
834                 DEBUG(0,("pipe_spnego_auth_bind_negotiate: Failed to parse the security blob.\n"));
835                 goto err;
836         }
837
838         if (strcmp(OID_KERBEROS5, OIDs[0]) == 0 || strcmp(OID_KERBEROS5_OLD, OIDs[0]) == 0) {
839                 got_kerberos_mechanism = true;
840         }
841
842         for (i=0;OIDs[i];i++) {
843                 DEBUG(3,("pipe_spnego_auth_bind_negotiate: Got OID %s\n", OIDs[i]));
844                 TALLOC_FREE(OIDs[i]);
845         }
846         DEBUG(3,("pipe_spnego_auth_bind_negotiate: Got secblob of size %lu\n", (unsigned long)secblob.length));
847
848         if ( got_kerberos_mechanism && ((lp_security()==SEC_ADS) || USE_KERBEROS_KEYTAB) ) {
849                 bool ret;
850                 ret = pipe_spnego_auth_bind_kerberos(p, mem_ctx, pauth_info,
851                                                      &secblob, response);
852                 data_blob_free(&secblob);
853                 return ret;
854         }
855
856         if (p->auth.auth_type == PIPE_AUTH_TYPE_SPNEGO_NTLMSSP && p->auth.a_u.auth_ntlmssp_state) {
857                 /* Free any previous auth type. */
858                 free_pipe_ntlmssp_auth_data(&p->auth);
859         }
860
861         if (!got_kerberos_mechanism) {
862                 /* Initialize the NTLM engine. */
863                 status = auth_ntlmssp_start(&a);
864                 if (!NT_STATUS_IS_OK(status)) {
865                         goto err;
866                 }
867
868                 switch (pauth_info->auth_level) {
869                         case DCERPC_AUTH_LEVEL_INTEGRITY:
870                                 auth_ntlmssp_want_sign(a);
871                                 break;
872                         case DCERPC_AUTH_LEVEL_PRIVACY:
873                                 auth_ntlmssp_want_seal(a);
874                                 break;
875                         default:
876                                 break;
877                 }
878                 /*
879                  * Pass the first security blob of data to it.
880                  * This can return an error or NT_STATUS_MORE_PROCESSING_REQUIRED
881                  * which means we need another packet to complete the bind.
882                  */
883
884                 status = auth_ntlmssp_update(a, secblob, &chal);
885
886                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
887                         DEBUG(3,("pipe_spnego_auth_bind_negotiate: auth_ntlmssp_update failed.\n"));
888                         goto err;
889                 }
890
891                 /* Generate the response blob we need for step 2 of the bind. */
892                 *response = spnego_gen_auth_response(&chal, status, OID_NTLMSSP);
893         } else {
894                 /*
895                  * SPNEGO negotiate down to NTLMSSP. The subsequent
896                  * code to process follow-up packets is not complete
897                  * yet. JRA.
898                  */
899                 *response = spnego_gen_auth_response(NULL,
900                                         NT_STATUS_MORE_PROCESSING_REQUIRED,
901                                         OID_NTLMSSP);
902         }
903
904         /* Make sure data is bound to the memctx, to be freed the caller */
905         talloc_steal(mem_ctx, response->data);
906
907         /* auth_pad_len will be handled by the caller */
908
909         p->auth.a_u.auth_ntlmssp_state = a;
910         p->auth.auth_data_free_func = &free_pipe_ntlmssp_auth_data;
911         p->auth.auth_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
912
913         data_blob_free(&secblob);
914         data_blob_free(&chal);
915
916         /* We can't set pipe_bound True yet - we need an RPC_ALTER_CONTEXT response packet... */
917         return True;
918
919  err:
920
921         data_blob_free(&secblob);
922         data_blob_free(&chal);
923
924         p->auth.a_u.auth_ntlmssp_state = NULL;
925
926         return False;
927 }
928
929 /*******************************************************************
930  Handle the second part of a SPNEGO bind auth.
931 *******************************************************************/
932
933 static bool pipe_spnego_auth_bind_continue(pipes_struct *p,
934                                            TALLOC_CTX *mem_ctx,
935                                            struct dcerpc_auth *pauth_info,
936                                            DATA_BLOB *response)
937 {
938         DATA_BLOB auth_blob;
939         DATA_BLOB auth_reply;
940         struct auth_ntlmssp_state *a = p->auth.a_u.auth_ntlmssp_state;
941
942         ZERO_STRUCT(auth_blob);
943         ZERO_STRUCT(auth_reply);
944
945         /*
946          * NB. If we've negotiated down from krb5 to NTLMSSP we'll currently
947          * fail here as 'a' == NULL.
948          */
949         if (p->auth.auth_type != PIPE_AUTH_TYPE_SPNEGO_NTLMSSP || !a) {
950                 DEBUG(0,("pipe_spnego_auth_bind_continue: not in NTLMSSP auth state.\n"));
951                 goto err;
952         }
953
954         if (pauth_info->credentials.data[0] != ASN1_CONTEXT(1)) {
955                 DEBUG(0,("pipe_spnego_auth_bind_continue: invalid SPNEGO blob type.\n"));
956                 goto err;
957         }
958
959         if (!spnego_parse_auth(pauth_info->credentials, &auth_blob)) {
960                 DEBUG(0,("pipe_spnego_auth_bind_continue: invalid SPNEGO blob.\n"));
961                 goto err;
962         }
963
964         /*
965          * The following call actually checks the challenge/response data.
966          * for correctness against the given DOMAIN\user name.
967          */
968
969         if (!pipe_ntlmssp_verify_final(p, &auth_blob)) {
970                 goto err;
971         }
972
973         data_blob_free(&auth_blob);
974
975         /* Generate the spnego "accept completed" blob - no incoming data. */
976         *response = spnego_gen_auth_response(&auth_reply, NT_STATUS_OK, OID_NTLMSSP);
977
978         /* Make sure data is bound to the memctx, to be freed the caller */
979         talloc_steal(mem_ctx, response->data);
980
981         data_blob_free(&auth_reply);
982
983         p->pipe_bound = True;
984
985         return True;
986
987  err:
988
989         data_blob_free(&auth_blob);
990         data_blob_free(&auth_reply);
991
992         free_pipe_ntlmssp_auth_data(&p->auth);
993         p->auth.a_u.auth_ntlmssp_state = NULL;
994
995         return False;
996 }
997
998 /*******************************************************************
999  Handle an schannel bind auth.
1000 *******************************************************************/
1001
1002 static bool pipe_schannel_auth_bind(pipes_struct *p,
1003                                     TALLOC_CTX *mem_ctx,
1004                                     struct dcerpc_auth *auth_info,
1005                                     DATA_BLOB *response)
1006 {
1007         struct NL_AUTH_MESSAGE neg;
1008         struct NL_AUTH_MESSAGE reply;
1009         bool ret;
1010         NTSTATUS status;
1011         struct netlogon_creds_CredentialState *creds;
1012         DATA_BLOB session_key;
1013         enum ndr_err_code ndr_err;
1014
1015         ndr_err = ndr_pull_struct_blob(
1016                         &auth_info->credentials, mem_ctx, &neg,
1017                         (ndr_pull_flags_fn_t)ndr_pull_NL_AUTH_MESSAGE);
1018         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1019                 DEBUG(0,("pipe_schannel_auth_bind: Could not unmarshal SCHANNEL auth neg\n"));
1020                 return false;
1021         }
1022
1023         if (DEBUGLEVEL >= 10) {
1024                 NDR_PRINT_DEBUG(NL_AUTH_MESSAGE, &neg);
1025         }
1026
1027         if (!(neg.Flags & NL_FLAG_OEM_NETBIOS_COMPUTER_NAME)) {
1028                 DEBUG(0,("pipe_schannel_auth_bind: Did not receive netbios computer name\n"));
1029                 return false;
1030         }
1031
1032         /*
1033          * The neg.oem_netbios_computer.a key here must match the remote computer name
1034          * given in the DOM_CLNT_SRV.uni_comp_name used on all netlogon pipe
1035          * operations that use credentials.
1036          */
1037
1038         become_root();
1039         status = schannel_get_creds_state(p, lp_private_dir(),
1040                                             neg.oem_netbios_computer.a, &creds);
1041         unbecome_root();
1042
1043         if (!NT_STATUS_IS_OK(status)) {
1044                 DEBUG(0, ("pipe_schannel_auth_bind: Attempt to bind using schannel without successful serverauth2\n"));
1045                 return False;
1046         }
1047
1048         p->auth.a_u.schannel_auth = talloc(p, struct schannel_state);
1049         if (!p->auth.a_u.schannel_auth) {
1050                 TALLOC_FREE(creds);
1051                 return False;
1052         }
1053
1054         p->auth.a_u.schannel_auth->state = SCHANNEL_STATE_START;
1055         p->auth.a_u.schannel_auth->seq_num = 0;
1056         p->auth.a_u.schannel_auth->initiator = false;
1057         p->auth.a_u.schannel_auth->creds = creds;
1058
1059         /*
1060          * JRA. Should we also copy the schannel session key into the pipe session key p->session_key
1061          * here ? We do that for NTLMSSP, but the session key is already set up from the vuser
1062          * struct of the person who opened the pipe. I need to test this further. JRA.
1063          *
1064          * VL. As we are mapping this to guest set the generic key
1065          * "SystemLibraryDTC" key here. It's a bit difficult to test against
1066          * W2k3, as it does not allow schannel binds against SAMR and LSA
1067          * anymore.
1068          */
1069
1070         session_key = generic_session_key();
1071         if (session_key.data == NULL) {
1072                 DEBUG(0, ("pipe_schannel_auth_bind: Could not alloc session"
1073                           " key\n"));
1074                 return false;
1075         }
1076
1077         ret = server_info_set_session_key(p->server_info, session_key);
1078
1079         data_blob_free(&session_key);
1080
1081         if (!ret) {
1082                 DEBUG(0, ("server_info_set_session_key failed\n"));
1083                 return false;
1084         }
1085
1086         /*** SCHANNEL verifier ***/
1087
1088         reply.MessageType                       = NL_NEGOTIATE_RESPONSE;
1089         reply.Flags                             = 0;
1090         reply.Buffer.dummy                      = 5; /* ??? actually I don't think
1091                                                       * this has any meaning
1092                                                       * here - gd */
1093
1094         ndr_err = ndr_push_struct_blob(response, mem_ctx, &reply,
1095                        (ndr_push_flags_fn_t)ndr_push_NL_AUTH_MESSAGE);
1096         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1097                 DEBUG(0,("Failed to marshall NL_AUTH_MESSAGE.\n"));
1098                 return false;
1099         }
1100
1101         if (DEBUGLEVEL >= 10) {
1102                 NDR_PRINT_DEBUG(NL_AUTH_MESSAGE, &reply);
1103         }
1104
1105         DEBUG(10,("pipe_schannel_auth_bind: schannel auth: domain [%s] myname [%s]\n",
1106                 neg.oem_netbios_domain.a, neg.oem_netbios_computer.a));
1107
1108         /* We're finished with this bind - no more packets. */
1109         p->auth.auth_data_free_func = NULL;
1110         p->auth.auth_type = PIPE_AUTH_TYPE_SCHANNEL;
1111
1112         p->pipe_bound = True;
1113
1114         return True;
1115 }
1116
1117 /*******************************************************************
1118  Handle an NTLMSSP bind auth.
1119 *******************************************************************/
1120
1121 static bool pipe_ntlmssp_auth_bind(pipes_struct *p,
1122                                    TALLOC_CTX *mem_ctx,
1123                                    struct dcerpc_auth *auth_info,
1124                                    DATA_BLOB *response)
1125 {
1126         NTSTATUS status;
1127         struct auth_ntlmssp_state *a = NULL;
1128
1129         if (strncmp((char *)auth_info->credentials.data, "NTLMSSP", 7) != 0) {
1130                 DEBUG(0, ("Failed to read NTLMSSP in blob\n"));
1131                 goto err;
1132         }
1133
1134         /* We have an NTLMSSP blob. */
1135         status = auth_ntlmssp_start(&a);
1136         if (!NT_STATUS_IS_OK(status)) {
1137                 DEBUG(0,("pipe_ntlmssp_auth_bind: auth_ntlmssp_start failed: %s\n",
1138                         nt_errstr(status) ));
1139                 goto err;
1140         }
1141
1142         switch (auth_info->auth_level) {
1143         case DCERPC_AUTH_LEVEL_INTEGRITY:
1144                 auth_ntlmssp_want_sign(a);
1145                 break;
1146         case DCERPC_AUTH_LEVEL_PRIVACY:
1147                 auth_ntlmssp_want_seal(a);
1148                 break;
1149         default:
1150                 break;
1151         }
1152
1153         status = auth_ntlmssp_update(a, auth_info->credentials, response);
1154         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1155                 DEBUG(0,("pipe_ntlmssp_auth_bind: auth_ntlmssp_update failed: %s\n",
1156                         nt_errstr(status) ));
1157                 goto err;
1158         }
1159
1160         /* Make sure data is bound to the memctx, to be freed the caller */
1161         talloc_steal(mem_ctx, response->data);
1162
1163         p->auth.a_u.auth_ntlmssp_state = a;
1164         p->auth.auth_data_free_func = &free_pipe_ntlmssp_auth_data;
1165         p->auth.auth_type = PIPE_AUTH_TYPE_NTLMSSP;
1166
1167         DEBUG(10,("pipe_ntlmssp_auth_bind: NTLMSSP auth started\n"));
1168
1169         /* We can't set pipe_bound True yet - we need an DCERPC_PKT_AUTH3 response packet... */
1170         return True;
1171
1172   err:
1173
1174         free_pipe_ntlmssp_auth_data(&p->auth);
1175         p->auth.a_u.auth_ntlmssp_state = NULL;
1176         return False;
1177 }
1178
1179 /*******************************************************************
1180  Respond to a pipe bind request.
1181 *******************************************************************/
1182
1183 bool api_pipe_bind_req(pipes_struct *p, struct ncacn_packet *pkt)
1184 {
1185         struct dcerpc_auth auth_info;
1186         uint16 assoc_gid;
1187         unsigned int auth_type = DCERPC_AUTH_TYPE_NONE;
1188         NTSTATUS status;
1189         struct ndr_syntax_id id;
1190         union dcerpc_payload u;
1191         struct dcerpc_ack_ctx bind_ack_ctx;
1192         DATA_BLOB auth_resp = data_blob_null;
1193         DATA_BLOB auth_blob = data_blob_null;
1194
1195         /* No rebinds on a bound pipe - use alter context. */
1196         if (p->pipe_bound) {
1197                 DEBUG(2,("api_pipe_bind_req: rejecting bind request on bound "
1198                          "pipe %s.\n",
1199                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1200                 return setup_bind_nak(p, pkt);
1201         }
1202
1203         if (pkt->u.bind.num_contexts == 0) {
1204                 DEBUG(0, ("api_pipe_bind_req: no rpc contexts around\n"));
1205                 goto err_exit;
1206         }
1207
1208         /*
1209          * Try and find the correct pipe name to ensure
1210          * that this is a pipe name we support.
1211          */
1212         id = pkt->u.bind.ctx_list[0].abstract_syntax;
1213         if (rpc_srv_pipe_exists_by_id(&id)) {
1214                 DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
1215                         rpc_srv_get_pipe_cli_name(&id),
1216                         rpc_srv_get_pipe_srv_name(&id)));
1217         } else {
1218                 status = smb_probe_module(
1219                         "rpc", get_pipe_name_from_syntax(
1220                                 talloc_tos(),
1221                                 &pkt->u.bind.ctx_list[0].abstract_syntax));
1222
1223                 if (NT_STATUS_IS_ERR(status)) {
1224                        DEBUG(3,("api_pipe_bind_req: Unknown pipe name %s in bind request.\n",
1225                                 get_pipe_name_from_syntax(
1226                                         talloc_tos(),
1227                                         &pkt->u.bind.ctx_list[0].abstract_syntax)));
1228
1229                         return setup_bind_nak(p, pkt);
1230                 }
1231
1232                 if (rpc_srv_get_pipe_interface_by_cli_name(
1233                                 get_pipe_name_from_syntax(talloc_tos(),
1234                                                           &p->syntax),
1235                                 &id)) {
1236                         DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
1237                                 rpc_srv_get_pipe_cli_name(&id),
1238                                 rpc_srv_get_pipe_srv_name(&id)));
1239                 } else {
1240                         DEBUG(0, ("module %s doesn't provide functions for "
1241                                   "pipe %s!\n",
1242                                   get_pipe_name_from_syntax(talloc_tos(),
1243                                                             &p->syntax),
1244                                   get_pipe_name_from_syntax(talloc_tos(),
1245                                                             &p->syntax)));
1246                         return setup_bind_nak(p, pkt);
1247                 }
1248         }
1249
1250         DEBUG(5,("api_pipe_bind_req: make response. %d\n", __LINE__));
1251
1252         if (pkt->u.bind.assoc_group_id != 0) {
1253                 assoc_gid = pkt->u.bind.assoc_group_id;
1254         } else {
1255                 assoc_gid = 0x53f0;
1256         }
1257
1258         /*
1259          * Create the bind response struct.
1260          */
1261
1262         /* If the requested abstract synt uuid doesn't match our client pipe,
1263                 reject the bind_ack & set the transfer interface synt to all 0's,
1264                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1265                 unknown to NT4)
1266                 Needed when adding entries to a DACL from NT5 - SK */
1267
1268         if (check_bind_req(p,
1269                         &pkt->u.bind.ctx_list[0].abstract_syntax,
1270                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
1271                         pkt->u.bind.ctx_list[0].context_id)) {
1272
1273                 bind_ack_ctx.result = 0;
1274                 bind_ack_ctx.reason = 0;
1275                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
1276         } else {
1277                 p->pipe_bound = False;
1278                 /* Rejection reason: abstract syntax not supported */
1279                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1280                 bind_ack_ctx.reason = DCERPC_BIND_REASON_ASYNTAX;
1281                 bind_ack_ctx.syntax = null_ndr_syntax_id;
1282         }
1283
1284         /*
1285          * Check if this is an authenticated bind request.
1286          */
1287         if (pkt->auth_length) {
1288                 /* Quick length check. Won't catch a bad auth footer,
1289                  * prevents overrun. */
1290
1291                 if (pkt->frag_length < RPC_HEADER_LEN +
1292                                         DCERPC_AUTH_TRAILER_LENGTH +
1293                                         pkt->auth_length) {
1294                         DEBUG(0,("api_pipe_bind_req: auth_len (%u) "
1295                                 "too long for fragment %u.\n",
1296                                 (unsigned int)pkt->auth_length,
1297                                 (unsigned int)pkt->frag_length));
1298                         goto err_exit;
1299                 }
1300
1301                 /*
1302                  * Decode the authentication verifier.
1303                  */
1304                 status = dcerpc_pull_dcerpc_auth(pkt,
1305                                                  &pkt->u.bind.auth_info,
1306                                                  &auth_info);
1307                 if (!NT_STATUS_IS_OK(status)) {
1308                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1309                         goto err_exit;
1310                 }
1311
1312                 auth_type = auth_info.auth_type;
1313
1314                 /* Work out if we have to sign or seal etc. */
1315                 switch (auth_info.auth_level) {
1316                 case DCERPC_AUTH_LEVEL_INTEGRITY:
1317                         p->auth.auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1318                         break;
1319                 case DCERPC_AUTH_LEVEL_PRIVACY:
1320                         p->auth.auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1321                         break;
1322                 default:
1323                         DEBUG(0, ("Unexpected auth level (%u).\n",
1324                                 (unsigned int)auth_info.auth_level ));
1325                         goto err_exit;
1326                 }
1327
1328                 switch (auth_type) {
1329                 case DCERPC_AUTH_TYPE_NTLMSSP:
1330                         if (!pipe_ntlmssp_auth_bind(p, pkt,
1331                                                 &auth_info, &auth_resp)) {
1332                                 goto err_exit;
1333                         }
1334                         assoc_gid = 0x7a77;
1335                         break;
1336
1337                 case DCERPC_AUTH_TYPE_SCHANNEL:
1338                         if (!pipe_schannel_auth_bind(p, pkt,
1339                                                 &auth_info, &auth_resp)) {
1340                                 goto err_exit;
1341                         }
1342                         break;
1343
1344                 case DCERPC_AUTH_TYPE_SPNEGO:
1345                         if (!pipe_spnego_auth_bind_negotiate(p, pkt,
1346                                                 &auth_info, &auth_resp)) {
1347                                 goto err_exit;
1348                         }
1349                         break;
1350
1351                 case DCERPC_AUTH_TYPE_NONE:
1352                         break;
1353
1354                 default:
1355                         DEBUG(0, ("Unknown auth type %x requested.\n", auth_type));
1356                         goto err_exit;
1357                 }
1358         }
1359
1360         if (auth_type == DCERPC_AUTH_TYPE_NONE) {
1361                 /* Unauthenticated bind request. */
1362                 /* We're finished - no more packets. */
1363                 p->auth.auth_type = PIPE_AUTH_TYPE_NONE;
1364                 /* We must set the pipe auth_level here also. */
1365                 p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
1366                 p->pipe_bound = True;
1367                 /* The session key was initialized from the SMB
1368                  * session in make_internal_rpc_pipe_p */
1369         }
1370
1371         ZERO_STRUCT(u.bind_ack);
1372         u.bind_ack.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1373         u.bind_ack.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1374         u.bind_ack.assoc_group_id = assoc_gid;
1375
1376         /* name has to be \PIPE\xxxxx */
1377         u.bind_ack.secondary_address =
1378                         talloc_asprintf(pkt, "\\PIPE\\%s",
1379                                         rpc_srv_get_pipe_srv_name(&id));
1380         if (!u.bind_ack.secondary_address) {
1381                 DEBUG(0, ("Out of memory!\n"));
1382                 goto err_exit;
1383         }
1384         u.bind_ack.secondary_address_size =
1385                                 strlen(u.bind_ack.secondary_address) + 1;
1386
1387         u.bind_ack.num_results = 1;
1388         u.bind_ack.ctx_list = &bind_ack_ctx;
1389
1390         /* NOTE: We leave the auth_info empty so we can calculate the padding
1391          * later and then append the auth_info --simo */
1392
1393         /*
1394          * Marshall directly into the outgoing PDU space. We
1395          * must do this as we need to set to the bind response
1396          * header and are never sending more than one PDU here.
1397          */
1398
1399         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1400                                           DCERPC_PKT_BIND_ACK,
1401                                           DCERPC_PFC_FLAG_FIRST |
1402                                                 DCERPC_PFC_FLAG_LAST,
1403                                           auth_resp.length,
1404                                           pkt->call_id,
1405                                           &u,
1406                                           &p->out_data.frag);
1407         if (!NT_STATUS_IS_OK(status)) {
1408                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
1409                           nt_errstr(status)));
1410         }
1411
1412         if (auth_resp.length) {
1413
1414                 status = dcerpc_push_dcerpc_auth(pkt,
1415                                                  auth_type,
1416                                                  auth_info.auth_level,
1417                                                  0,
1418                                                  1, /* auth_context_id */
1419                                                  &auth_resp,
1420                                                  &auth_blob);
1421                 if (!NT_STATUS_IS_OK(status)) {
1422                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1423                         goto err_exit;
1424                 }
1425         }
1426
1427         /* Now that we have the auth len store it into the right place in
1428          * the dcerpc header */
1429         dcerpc_set_frag_length(&p->out_data.frag,
1430                                 p->out_data.frag.length + auth_blob.length);
1431
1432         if (auth_blob.length) {
1433
1434                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1435                                         auth_blob.data, auth_blob.length)) {
1436                         DEBUG(0, ("Append of auth info failed.\n"));
1437                         goto err_exit;
1438                 }
1439         }
1440
1441         /*
1442          * Setup the lengths for the initial reply.
1443          */
1444
1445         p->out_data.data_sent_length = 0;
1446         p->out_data.current_pdu_sent = 0;
1447
1448         TALLOC_FREE(auth_blob.data);
1449         return True;
1450
1451   err_exit:
1452
1453         data_blob_free(&p->out_data.frag);
1454         TALLOC_FREE(auth_blob.data);
1455         return setup_bind_nak(p, pkt);
1456 }
1457
1458 /****************************************************************************
1459  Deal with an alter context call. Can be third part of 3 leg auth request for
1460  SPNEGO calls.
1461 ****************************************************************************/
1462
1463 bool api_pipe_alter_context(pipes_struct *p, struct ncacn_packet *pkt)
1464 {
1465         struct dcerpc_auth auth_info;
1466         uint16 assoc_gid;
1467         NTSTATUS status;
1468         union dcerpc_payload u;
1469         struct dcerpc_ack_ctx bind_ack_ctx;
1470         DATA_BLOB auth_resp = data_blob_null;
1471         DATA_BLOB auth_blob = data_blob_null;
1472         int pad_len = 0;
1473
1474         DEBUG(5,("api_pipe_alter_context: make response. %d\n", __LINE__));
1475
1476         if (pkt->u.bind.assoc_group_id != 0) {
1477                 assoc_gid = pkt->u.bind.assoc_group_id;
1478         } else {
1479                 assoc_gid = 0x53f0;
1480         }
1481
1482         /*
1483          * Create the bind response struct.
1484          */
1485
1486         /* If the requested abstract synt uuid doesn't match our client pipe,
1487                 reject the bind_ack & set the transfer interface synt to all 0's,
1488                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1489                 unknown to NT4)
1490                 Needed when adding entries to a DACL from NT5 - SK */
1491
1492         if (check_bind_req(p,
1493                         &pkt->u.bind.ctx_list[0].abstract_syntax,
1494                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
1495                         pkt->u.bind.ctx_list[0].context_id)) {
1496
1497                 bind_ack_ctx.result = 0;
1498                 bind_ack_ctx.reason = 0;
1499                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
1500         } else {
1501                 p->pipe_bound = False;
1502                 /* Rejection reason: abstract syntax not supported */
1503                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1504                 bind_ack_ctx.reason = DCERPC_BIND_REASON_ASYNTAX;
1505                 bind_ack_ctx.syntax = null_ndr_syntax_id;
1506         }
1507
1508         /*
1509          * Check if this is an authenticated alter context request.
1510          */
1511         if (pkt->auth_length) {
1512                 /* Quick length check. Won't catch a bad auth footer,
1513                  * prevents overrun. */
1514
1515                 if (pkt->frag_length < RPC_HEADER_LEN +
1516                                         DCERPC_AUTH_TRAILER_LENGTH +
1517                                         pkt->auth_length) {
1518                         DEBUG(0,("api_pipe_alter_context: auth_len (%u) "
1519                                 "too long for fragment %u.\n",
1520                                 (unsigned int)pkt->auth_length,
1521                                 (unsigned int)pkt->frag_length ));
1522                         goto err_exit;
1523                 }
1524
1525                 status = dcerpc_pull_dcerpc_auth(pkt,
1526                                                  &pkt->u.bind.auth_info,
1527                                                  &auth_info);
1528                 if (!NT_STATUS_IS_OK(status)) {
1529                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1530                         goto err_exit;
1531                 }
1532
1533
1534                 /*
1535                  * Currently only the SPNEGO auth type uses the alter ctx
1536                  * response in place of the NTLMSSP auth3 type.
1537                  */
1538
1539                 if (auth_info.auth_type == DCERPC_AUTH_TYPE_SPNEGO) {
1540                         /* We can only finish if the pipe is unbound. */
1541                         if (!p->pipe_bound) {
1542                                 if (!pipe_spnego_auth_bind_continue(p, pkt,
1543                                                 &auth_info, &auth_resp)) {
1544                                         goto err_exit;
1545                                 }
1546
1547                         } else {
1548                                 goto err_exit;
1549                         }
1550                 }
1551         }
1552
1553         ZERO_STRUCT(u.alter_resp);
1554         u.alter_resp.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1555         u.alter_resp.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1556         u.alter_resp.assoc_group_id = assoc_gid;
1557
1558         /* secondary address CAN be NULL
1559          * as the specs say it's ignored.
1560          * It MUST be NULL to have the spoolss working.
1561          */
1562         u.alter_resp.secondary_address = "";
1563         u.alter_resp.secondary_address_size = 1;
1564
1565         u.alter_resp.num_results = 1;
1566         u.alter_resp.ctx_list = &bind_ack_ctx;
1567
1568         /* NOTE: We leave the auth_info empty so we can calculate the padding
1569          * later and then append the auth_info --simo */
1570
1571         /*
1572          * Marshall directly into the outgoing PDU space. We
1573          * must do this as we need to set to the bind response
1574          * header and are never sending more than one PDU here.
1575          */
1576
1577         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1578                                           DCERPC_PKT_ALTER_RESP,
1579                                           DCERPC_PFC_FLAG_FIRST |
1580                                                 DCERPC_PFC_FLAG_LAST,
1581                                           auth_resp.length,
1582                                           pkt->call_id,
1583                                           &u,
1584                                           &p->out_data.frag);
1585         if (!NT_STATUS_IS_OK(status)) {
1586                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
1587                           nt_errstr(status)));
1588         }
1589
1590         if (auth_resp.length) {
1591
1592                 /* Work out any padding needed before the auth footer. */
1593                 pad_len = p->out_data.frag.length % SERVER_NDR_PADDING_SIZE;
1594                 if (pad_len) {
1595                         pad_len = SERVER_NDR_PADDING_SIZE - pad_len;
1596                         DEBUG(10, ("auth pad_len = %u\n",
1597                                    (unsigned int)pad_len));
1598                 }
1599
1600                 status = dcerpc_push_dcerpc_auth(pkt,
1601                                                  auth_info.auth_type,
1602                                                  auth_info.auth_level,
1603                                                  pad_len,
1604                                                  1, /* auth_context_id */
1605                                                  &auth_resp,
1606                                                  &auth_blob);
1607                 if (!NT_STATUS_IS_OK(status)) {
1608                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1609                         goto err_exit;
1610                 }
1611         }
1612
1613         /* Now that we have the auth len store it into the right place in
1614          * the dcerpc header */
1615         dcerpc_set_frag_length(&p->out_data.frag,
1616                                 p->out_data.frag.length +
1617                                         pad_len + auth_blob.length);
1618
1619         if (auth_resp.length) {
1620                 if (pad_len) {
1621                         char pad[SERVER_NDR_PADDING_SIZE];
1622                         memset(pad, '\0', SERVER_NDR_PADDING_SIZE);
1623                         if (!data_blob_append(p->mem_ctx,
1624                                                 &p->out_data.frag,
1625                                                 pad, pad_len)) {
1626                                 DEBUG(0, ("api_pipe_bind_req: failed to add "
1627                                           "%u bytes of pad data.\n",
1628                                           (unsigned int)pad_len));
1629                                 goto err_exit;
1630                         }
1631                 }
1632
1633                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1634                                         auth_blob.data, auth_blob.length)) {
1635                         DEBUG(0, ("Append of auth info failed.\n"));
1636                         goto err_exit;
1637                 }
1638         }
1639
1640         /*
1641          * Setup the lengths for the initial reply.
1642          */
1643
1644         p->out_data.data_sent_length = 0;
1645         p->out_data.current_pdu_sent = 0;
1646
1647         TALLOC_FREE(auth_blob.data);
1648         return True;
1649
1650   err_exit:
1651
1652         data_blob_free(&p->out_data.frag);
1653         TALLOC_FREE(auth_blob.data);
1654         return setup_bind_nak(p, pkt);
1655 }
1656
1657 /****************************************************************************
1658  Find the set of RPC functions associated with this context_id
1659 ****************************************************************************/
1660
1661 static PIPE_RPC_FNS* find_pipe_fns_by_context( PIPE_RPC_FNS *list, uint32 context_id )
1662 {
1663         PIPE_RPC_FNS *fns = NULL;
1664
1665         if ( !list ) {
1666                 DEBUG(0,("find_pipe_fns_by_context: ERROR!  No context list for pipe!\n"));
1667                 return NULL;
1668         }
1669
1670         for (fns=list; fns; fns=fns->next ) {
1671                 if ( fns->context_id == context_id )
1672                         return fns;
1673         }
1674         return NULL;
1675 }
1676
1677 /****************************************************************************
1678  Memory cleanup.
1679 ****************************************************************************/
1680
1681 void free_pipe_rpc_context( PIPE_RPC_FNS *list )
1682 {
1683         PIPE_RPC_FNS *tmp = list;
1684         PIPE_RPC_FNS *tmp2;
1685
1686         while (tmp) {
1687                 tmp2 = tmp->next;
1688                 SAFE_FREE(tmp);
1689                 tmp = tmp2;
1690         }
1691
1692         return; 
1693 }
1694
1695 static bool api_rpcTNP(pipes_struct *p, struct ncacn_packet *pkt,
1696                        const struct api_struct *api_rpc_cmds, int n_cmds);
1697
1698 /****************************************************************************
1699  Find the correct RPC function to call for this request.
1700  If the pipe is authenticated then become the correct UNIX user
1701  before doing the call.
1702 ****************************************************************************/
1703
1704 bool api_pipe_request(pipes_struct *p, struct ncacn_packet *pkt)
1705 {
1706         bool ret = False;
1707         bool changed_user = False;
1708         PIPE_RPC_FNS *pipe_fns;
1709
1710         if (p->pipe_bound &&
1711                         ((p->auth.auth_type == PIPE_AUTH_TYPE_NTLMSSP) ||
1712                          (p->auth.auth_type == PIPE_AUTH_TYPE_SPNEGO_NTLMSSP))) {
1713                 if(!become_authenticated_pipe_user(p)) {
1714                         data_blob_free(&p->out_data.rdata);
1715                         return False;
1716                 }
1717                 changed_user = True;
1718         }
1719
1720         DEBUG(5, ("Requested \\PIPE\\%s\n",
1721                   get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1722
1723         /* get the set of RPC functions for this context */
1724
1725         pipe_fns = find_pipe_fns_by_context(p->contexts,
1726                                             pkt->u.request.context_id);
1727
1728         if ( pipe_fns ) {
1729                 TALLOC_CTX *frame = talloc_stackframe();
1730                 ret = api_rpcTNP(p, pkt, pipe_fns->cmds, pipe_fns->n_cmds);
1731                 TALLOC_FREE(frame);
1732         }
1733         else {
1734                 DEBUG(0, ("No rpc function table associated with context "
1735                           "[%d] on pipe [%s]\n",
1736                           pkt->u.request.context_id,
1737                           get_pipe_name_from_syntax(talloc_tos(),
1738                                                     &p->syntax)));
1739         }
1740
1741         if (changed_user) {
1742                 unbecome_authenticated_pipe_user();
1743         }
1744
1745         return ret;
1746 }
1747
1748 /*******************************************************************
1749  Calls the underlying RPC function for a named pipe.
1750  ********************************************************************/
1751
1752 static bool api_rpcTNP(pipes_struct *p, struct ncacn_packet *pkt,
1753                        const struct api_struct *api_rpc_cmds, int n_cmds)
1754 {
1755         int fn_num;
1756         uint32_t offset1;
1757
1758         /* interpret the command */
1759         DEBUG(4,("api_rpcTNP: %s op 0x%x - ",
1760                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax),
1761                  pkt->u.request.opnum));
1762
1763         if (DEBUGLEVEL >= 50) {
1764                 fstring name;
1765                 slprintf(name, sizeof(name)-1, "in_%s",
1766                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax));
1767                 dump_pdu_region(name, pkt->u.request.opnum,
1768                                 &p->in_data.data, 0,
1769                                 p->in_data.data.length);
1770         }
1771
1772         for (fn_num = 0; fn_num < n_cmds; fn_num++) {
1773                 if (api_rpc_cmds[fn_num].opnum == pkt->u.request.opnum &&
1774                     api_rpc_cmds[fn_num].fn != NULL) {
1775                         DEBUG(3, ("api_rpcTNP: rpc command: %s\n",
1776                                   api_rpc_cmds[fn_num].name));
1777                         break;
1778                 }
1779         }
1780
1781         if (fn_num == n_cmds) {
1782                 /*
1783                  * For an unknown RPC just return a fault PDU but
1784                  * return True to allow RPC's on the pipe to continue
1785                  * and not put the pipe into fault state. JRA.
1786                  */
1787                 DEBUG(4, ("unknown\n"));
1788                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1789                 return True;
1790         }
1791
1792         offset1 = p->out_data.rdata.length;
1793
1794         DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", 
1795                 fn_num, api_rpc_cmds[fn_num].fn));
1796         /* do the actual command */
1797         if(!api_rpc_cmds[fn_num].fn(p)) {
1798                 DEBUG(0,("api_rpcTNP: %s: %s failed.\n",
1799                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax),
1800                          api_rpc_cmds[fn_num].name));
1801                 data_blob_free(&p->out_data.rdata);
1802                 return False;
1803         }
1804
1805         if (p->bad_handle_fault_state) {
1806                 DEBUG(4,("api_rpcTNP: bad handle fault return.\n"));
1807                 p->bad_handle_fault_state = False;
1808                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_CONTEXT_MISMATCH));
1809                 return True;
1810         }
1811
1812         if (p->rng_fault_state) {
1813                 DEBUG(4, ("api_rpcTNP: rng fault return\n"));
1814                 p->rng_fault_state = False;
1815                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1816                 return True;
1817         }
1818
1819         if (DEBUGLEVEL >= 50) {
1820                 fstring name;
1821                 slprintf(name, sizeof(name)-1, "out_%s",
1822                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax));
1823                 dump_pdu_region(name, pkt->u.request.opnum,
1824                                 &p->out_data.rdata, offset1,
1825                                 p->out_data.rdata.length);
1826         }
1827
1828         DEBUG(5,("api_rpcTNP: called %s successfully\n",
1829                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1830
1831         /* Check for buffer underflow in rpc parsing */
1832         if ((DEBUGLEVEL >= 10) &&
1833             (pkt->frag_length < p->in_data.data.length)) {
1834                 DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n"));
1835                 dump_data(10, p->in_data.data.data + pkt->frag_length,
1836                               p->in_data.data.length - pkt->frag_length);
1837         }
1838
1839         return True;
1840 }