s3-dcerpc: Fix potential memleak
[mat/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 #include "ntlmssp_wrap.h"
37 #include "rpc_server.h"
38
39 #undef DBGC_CLASS
40 #define DBGC_CLASS DBGC_RPC_SRV
41
42 /**
43  * Dump everything from the start of the end up of the provided data
44  * into a file, but only at debug level >= 50
45  **/
46 static void dump_pdu_region(const char *name, int v,
47                             DATA_BLOB *data, size_t start, size_t end)
48 {
49         int fd, i;
50         char *fname = NULL;
51         ssize_t sz;
52
53         if (DEBUGLEVEL < 50) return;
54
55         if (start > data->length || end > data->length || start > end) return;
56
57         for (i = 1; i < 100; i++) {
58                 if (v != -1) {
59                         fname = talloc_asprintf(talloc_tos(),
60                                                 "/tmp/%s_%d.%d.prs",
61                                                 name, v, i);
62                 } else {
63                         fname = talloc_asprintf(talloc_tos(),
64                                                 "/tmp/%s_%d.prs",
65                                                 name, i);
66                 }
67                 if (!fname) {
68                         return;
69                 }
70                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
71                 if (fd != -1 || errno != EEXIST) break;
72         }
73         if (fd != -1) {
74                 sz = write(fd, data->data + start, end - start);
75                 i = close(fd);
76                 if ((sz != end - start) || (i != 0) ) {
77                         DEBUG(0, ("Error writing/closing %s: %ld!=%ld %d\n",
78                                   fname, (unsigned long)sz,
79                                   (unsigned long)end - start, i));
80                 } else {
81                         DEBUG(0,("created %s\n", fname));
82                 }
83         }
84         TALLOC_FREE(fname);
85 }
86
87 static void free_pipe_ntlmssp_auth_data(struct pipe_auth_data *auth)
88 {
89         TALLOC_FREE(auth->a_u.auth_ntlmssp_state);
90 }
91
92 static void free_pipe_schannel_auth_data(struct pipe_auth_data *auth)
93 {
94         TALLOC_FREE(auth->a_u.schannel_auth);
95 }
96
97 static DATA_BLOB generic_session_key(void)
98 {
99         return data_blob("SystemLibraryDTC", 16);
100 }
101
102 /*******************************************************************
103  Handle NTLMSSP.
104  ********************************************************************/
105
106 static bool add_ntlmssp_auth(pipes_struct *p)
107 {
108         enum dcerpc_AuthLevel auth_level = p->auth.auth_level;
109         DATA_BLOB auth_blob = data_blob_null;
110         NTSTATUS status;
111
112         /* FIXME: Is this right ?
113          * Keeping only to avoid changing semantics during refactoring
114          * --simo
115          */
116         if (auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
117                 auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
118         }
119
120         /* Generate the auth blob. */
121         switch (auth_level) {
122         case DCERPC_AUTH_LEVEL_PRIVACY:
123                 /* Data portion is encrypted. */
124                 status = auth_ntlmssp_seal_packet(
125                                 p->auth.a_u.auth_ntlmssp_state,
126                                 (TALLOC_CTX *)p->out_data.frag.data,
127                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
128                                 p->out_data.frag.length
129                                         - DCERPC_RESPONSE_LENGTH
130                                         - DCERPC_AUTH_TRAILER_LENGTH,
131                                 p->out_data.frag.data,
132                                 p->out_data.frag.length,
133                                 &auth_blob);
134                 break;
135
136         case DCERPC_AUTH_LEVEL_INTEGRITY:
137                 /* Data is signed. */
138                 status = auth_ntlmssp_sign_packet(
139                                 p->auth.a_u.auth_ntlmssp_state,
140                                 (TALLOC_CTX *)p->out_data.frag.data,
141                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
142                                 p->out_data.frag.length
143                                         - DCERPC_RESPONSE_LENGTH
144                                         - DCERPC_AUTH_TRAILER_LENGTH,
145                                 p->out_data.frag.data,
146                                 p->out_data.frag.length,
147                                 &auth_blob);
148                 break;
149
150         default:
151                 status = NT_STATUS_INTERNAL_ERROR;
152                 return false;
153         }
154
155         if (!NT_STATUS_IS_OK(status)) {
156                 DEBUG(0, ("Failed to add NTLMSSP auth blob: %s\n",
157                         nt_errstr(status)));
158                 data_blob_free(&p->out_data.frag);
159                 return false;
160         }
161
162         /* Finally append the auth blob. */
163         if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
164                                 auth_blob.data, auth_blob.length)) {
165                 DEBUG(0, ("Failed to add %u bytes auth blob.\n",
166                           (unsigned int)auth_blob.length));
167                 data_blob_free(&p->out_data.frag);
168                 return False;
169         }
170         data_blob_free(&auth_blob);
171
172         return true;
173 }
174
175 /*******************************************************************
176  Append a schannel authenticated fragment.
177  ********************************************************************/
178
179 static bool add_schannel_auth(pipes_struct *p)
180 {
181         DATA_BLOB auth_blob = data_blob_null;
182         NTSTATUS status;
183
184         /* Schannel processing. */
185         switch (p->auth.auth_level) {
186         case DCERPC_AUTH_LEVEL_PRIVACY:
187                 status = netsec_outgoing_packet(
188                                 p->auth.a_u.schannel_auth,
189                                 (TALLOC_CTX *)p->out_data.frag.data,
190                                 true,
191                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
192                                 p->out_data.frag.length
193                                         - DCERPC_RESPONSE_LENGTH
194                                         - DCERPC_AUTH_TRAILER_LENGTH,
195                                 &auth_blob);
196                 break;
197
198         case DCERPC_AUTH_LEVEL_INTEGRITY:
199                 status = netsec_outgoing_packet(
200                                 p->auth.a_u.schannel_auth,
201                                 (TALLOC_CTX *)p->out_data.frag.data,
202                                 false,
203                                 &p->out_data.frag.data[DCERPC_RESPONSE_LENGTH],
204                                 p->out_data.frag.length
205                                         - DCERPC_RESPONSE_LENGTH
206                                         - DCERPC_AUTH_TRAILER_LENGTH,
207                                 &auth_blob);
208                 break;
209
210         default:
211                 status = NT_STATUS_INTERNAL_ERROR;
212                 break;
213         }
214
215         if (!NT_STATUS_IS_OK(status)) {
216                 DEBUG(0, ("Failed to add SCHANNEL auth blob: %s\n",
217                         nt_errstr(status)));
218                 data_blob_free(&p->out_data.frag);
219                 return false;
220         }
221
222         if (DEBUGLEVEL >= 10) {
223                 dump_NL_AUTH_SIGNATURE(talloc_tos(), &auth_blob);
224         }
225
226         if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
227                                 auth_blob.data, auth_blob.length)) {
228                 DEBUG(0, ("Failed to add %u bytes auth blob.\n",
229                           (unsigned int)auth_blob.length));
230                 data_blob_free(&p->out_data.frag);
231                 return false;
232         }
233         data_blob_free(&auth_blob);
234
235         return true;
236 }
237
238 /*******************************************************************
239  Generate the next PDU to be returned from the data.
240 ********************************************************************/
241
242 static bool create_next_packet(pipes_struct *p,
243                                 enum dcerpc_AuthType auth_type,
244                                 enum dcerpc_AuthLevel auth_level,
245                                 size_t auth_length)
246 {
247         union dcerpc_payload u;
248         uint8_t pfc_flags;
249         size_t data_len_left;
250         size_t data_len;
251         size_t max_len;
252         size_t pad_len = 0;
253         NTSTATUS status;
254
255         ZERO_STRUCT(u.response);
256
257         /* Set up rpc packet pfc flags. */
258         if (p->out_data.data_sent_length == 0) {
259                 pfc_flags = DCERPC_PFC_FLAG_FIRST;
260         } else {
261                 pfc_flags = 0;
262         }
263
264         /* Work out how much we can fit in a single PDU. */
265         data_len_left = p->out_data.rdata.length -
266                                 p->out_data.data_sent_length;
267
268         /* Ensure there really is data left to send. */
269         if (!data_len_left) {
270                 DEBUG(0, ("No data left to send !\n"));
271                 return false;
272         }
273
274         /* Max space available - not including padding. */
275         if (auth_length) {
276                 max_len = RPC_MAX_PDU_FRAG_LEN
277                                 - DCERPC_RESPONSE_LENGTH
278                                 - DCERPC_AUTH_TRAILER_LENGTH
279                                 - auth_length;
280         } else {
281                 max_len = RPC_MAX_PDU_FRAG_LEN - DCERPC_RESPONSE_LENGTH;
282         }
283
284         /*
285          * The amount we send is the minimum of the max_len
286          * and the amount left to send.
287          */
288         data_len = MIN(data_len_left, max_len);
289
290         if (auth_length) {
291                 /* Work out any padding alignment requirements. */
292                 pad_len = (DCERPC_RESPONSE_LENGTH + data_len) %
293                                                 SERVER_NDR_PADDING_SIZE;
294                 if (pad_len) {
295                         pad_len = SERVER_NDR_PADDING_SIZE - pad_len;
296                         DEBUG(10, ("Padding size is: %d\n", (int)pad_len));
297                         /* If we're over filling the packet, we need to make
298                          * space for the padding at the end of the data. */
299                         if (data_len + pad_len > max_len) {
300                                 data_len -= SERVER_NDR_PADDING_SIZE;
301                         }
302                 }
303         }
304
305         /* Set up the alloc hint. This should be the data left to send. */
306         u.response.alloc_hint = data_len_left;
307
308         /* Work out if this PDU will be the last. */
309         if (p->out_data.data_sent_length
310                                 + data_len >= p->out_data.rdata.length) {
311                 pfc_flags |= DCERPC_PFC_FLAG_LAST;
312         }
313
314         /* Prepare data to be NDR encoded. */
315         u.response.stub_and_verifier =
316                 data_blob_const(p->out_data.rdata.data +
317                                 p->out_data.data_sent_length, data_len);
318
319         /* Store the packet in the data stream. */
320         status = dcerpc_push_ncacn_packet(p->mem_ctx,
321                                           DCERPC_PKT_RESPONSE,
322                                           pfc_flags,
323                                           auth_length,
324                                           p->call_id,
325                                           &u,
326                                           &p->out_data.frag);
327         if (!NT_STATUS_IS_OK(status)) {
328                 DEBUG(0, ("Failed to marshall RPC Packet.\n"));
329                 return false;
330         }
331
332         if (auth_length) {
333                 DATA_BLOB empty = data_blob_null;
334                 DATA_BLOB auth_hdr;
335
336                 /* Set the proper length on the pdu, including padding.
337                  * Only needed if an auth trailer will be appended. */
338                 dcerpc_set_frag_length(&p->out_data.frag,
339                                         p->out_data.frag.length
340                                                 + pad_len
341                                                 + DCERPC_AUTH_TRAILER_LENGTH
342                                                 + auth_length);
343
344                 if (pad_len) {
345                         size_t offset = p->out_data.frag.length;
346
347                         if (!data_blob_realloc(p->mem_ctx,
348                                                 &p->out_data.frag,
349                                                 offset + pad_len)) {
350                                 DEBUG(0, ("Failed to add padding!\n"));
351                                 data_blob_free(&p->out_data.frag);
352                                 return false;
353                         }
354                         memset(&p->out_data.frag.data[offset], '\0', pad_len);
355                 }
356
357                 /* auth blob is intentionally empty,
358                  * it will be appended later */
359                 status = dcerpc_push_dcerpc_auth(p->out_data.frag.data,
360                                                  auth_type,
361                                                  auth_level,
362                                                  pad_len,
363                                                  1, /* context id. */
364                                                  &empty,
365                                                  &auth_hdr);
366                 if (!NT_STATUS_IS_OK(status)) {
367                         DEBUG(0, ("Failed to marshall RPC Auth.\n"));
368                         return false;
369                 }
370
371                 /* Store auth header in the data stream. */
372                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
373                                         auth_hdr.data, auth_hdr.length)) {
374                         DEBUG(0, ("Out of memory.\n"));
375                         data_blob_free(&p->out_data.frag);
376                         return false;
377                 }
378                 data_blob_free(&auth_hdr);
379         }
380
381         /* Setup the counts for this PDU. */
382         p->out_data.data_sent_length += data_len;
383         p->out_data.current_pdu_sent = 0;
384         return true;
385 }
386
387 /*******************************************************************
388  Generate the next PDU to be returned from the data in p->rdata. 
389 ********************************************************************/
390
391 bool create_next_pdu(pipes_struct *p)
392 {
393         enum dcerpc_AuthType auth_type =
394                 map_pipe_auth_type_to_rpc_auth_type(p->auth.auth_type);
395
396         /*
397          * If we're in the fault state, keep returning fault PDU's until
398          * the pipe gets closed. JRA.
399          */
400         if (p->fault_state) {
401                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
402                 return true;
403         }
404
405         switch (p->auth.auth_level) {
406         case DCERPC_AUTH_LEVEL_NONE:
407         case DCERPC_AUTH_LEVEL_CONNECT:
408                 /* This is incorrect for auth level connect. Fixme. JRA */
409
410                 /* No authentication done. */
411                 return create_next_packet(p, auth_type,
412                                           p->auth.auth_level, 0);
413
414         case DCERPC_AUTH_LEVEL_CALL:
415         case DCERPC_AUTH_LEVEL_PACKET:
416         case DCERPC_AUTH_LEVEL_INTEGRITY:
417         case DCERPC_AUTH_LEVEL_PRIVACY:
418
419                 switch(p->auth.auth_type) {
420                 case PIPE_AUTH_TYPE_NTLMSSP:
421                 case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
422                         if (!create_next_packet(p, auth_type,
423                                                 p->auth.auth_level,
424                                                 NTLMSSP_SIG_SIZE)) {
425                                 return false;
426                         }
427                         return add_ntlmssp_auth(p);
428
429                 case PIPE_AUTH_TYPE_SCHANNEL:
430                         if (!create_next_packet(p, auth_type,
431                                                 p->auth.auth_level,
432                                                 NL_AUTH_SIGNATURE_SIZE)) {
433                                 return false;
434                         }
435                         return add_schannel_auth(p);
436                 default:
437                         break;
438                 }
439         default:
440                 break;
441         }
442
443         DEBUG(0, ("Invalid internal auth level %u / type %u\n",
444                   (unsigned int)p->auth.auth_level,
445                   (unsigned int)p->auth.auth_type));
446         return false;
447 }
448
449 /*******************************************************************
450  Process an NTLMSSP authentication response.
451  If this function succeeds, the user has been authenticated
452  and their domain, name and calling workstation stored in
453  the pipe struct.
454 *******************************************************************/
455
456 static bool pipe_ntlmssp_verify_final(pipes_struct *p, DATA_BLOB *p_resp_blob)
457 {
458         DATA_BLOB session_key, reply;
459         NTSTATUS status;
460         struct auth_ntlmssp_state *a = p->auth.a_u.auth_ntlmssp_state;
461         bool ret;
462
463         DEBUG(5,("pipe_ntlmssp_verify_final: pipe %s checking user details\n",
464                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
465
466         ZERO_STRUCT(reply);
467
468         /* this has to be done as root in order to verify the password */
469         become_root();
470         status = auth_ntlmssp_update(a, *p_resp_blob, &reply);
471         unbecome_root();
472
473         /* Don't generate a reply. */
474         data_blob_free(&reply);
475
476         if (!NT_STATUS_IS_OK(status)) {
477                 return False;
478         }
479
480         /* Finally - if the pipe negotiated integrity (sign) or privacy (seal)
481            ensure the underlying NTLMSSP flags are also set. If not we should
482            refuse the bind. */
483
484         if (p->auth.auth_level == DCERPC_AUTH_LEVEL_INTEGRITY) {
485                 if (!auth_ntlmssp_negotiated_sign(a)) {
486                         DEBUG(0,("pipe_ntlmssp_verify_final: pipe %s : packet integrity requested "
487                                 "but client declined signing.\n",
488                                  get_pipe_name_from_syntax(talloc_tos(),
489                                                            &p->syntax)));
490                         return False;
491                 }
492         }
493         if (p->auth.auth_level == DCERPC_AUTH_LEVEL_PRIVACY) {
494                 if (!auth_ntlmssp_negotiated_seal(a)) {
495                         DEBUG(0,("pipe_ntlmssp_verify_final: pipe %s : packet privacy requested "
496                                 "but client declined sealing.\n",
497                                  get_pipe_name_from_syntax(talloc_tos(),
498                                                            &p->syntax)));
499                         return False;
500                 }
501         }
502
503         DEBUG(5, ("pipe_ntlmssp_verify_final: OK: user: %s domain: %s "
504                   "workstation: %s\n",
505                   auth_ntlmssp_get_username(a),
506                   auth_ntlmssp_get_domain(a),
507                   auth_ntlmssp_get_client(a)));
508
509         TALLOC_FREE(p->server_info);
510
511         status = auth_ntlmssp_steal_server_info(p, a, &p->server_info);
512         if (!NT_STATUS_IS_OK(status)) {
513                 DEBUG(0, ("auth_ntlmssp_server_info failed to obtain the server info for authenticated user: %s\n",
514                           nt_errstr(status)));
515                 return false;
516         }
517
518         if (p->server_info->ptok == NULL) {
519                 DEBUG(1,("Error: Authmodule failed to provide nt_user_token\n"));
520                 return False;
521         }
522
523         /*
524          * We're an authenticated bind over smb, so the session key needs to
525          * be set to "SystemLibraryDTC". Weird, but this is what Windows
526          * does. See the RPC-SAMBA3SESSIONKEY.
527          */
528
529         session_key = generic_session_key();
530         if (session_key.data == NULL) {
531                 return False;
532         }
533
534         ret = server_info_set_session_key(p->server_info, session_key);
535
536         data_blob_free(&session_key);
537
538         return True;
539 }
540
541 /*******************************************************************
542  This is the "stage3" NTLMSSP response after a bind request and reply.
543 *******************************************************************/
544
545 bool api_pipe_bind_auth3(pipes_struct *p, struct ncacn_packet *pkt)
546 {
547         struct dcerpc_auth auth_info;
548         NTSTATUS status;
549
550         DEBUG(5, ("api_pipe_bind_auth3: decode request. %d\n", __LINE__));
551
552         if (pkt->auth_length == 0) {
553                 DEBUG(0, ("No auth field sent for bind request!\n"));
554                 goto err;
555         }
556
557         /* Ensure there's enough data for an authenticated request. */
558         if (pkt->frag_length < RPC_HEADER_LEN
559                                 + DCERPC_AUTH_TRAILER_LENGTH
560                                 + pkt->auth_length) {
561                         DEBUG(0,("api_pipe_ntlmssp_auth_process: auth_len "
562                                 "%u is too large.\n",
563                         (unsigned int)pkt->auth_length));
564                 goto err;
565         }
566
567         /*
568          * Decode the authentication verifier response.
569          */
570
571         status = dcerpc_pull_dcerpc_auth(pkt,
572                                          &pkt->u.auth3.auth_info,
573                                          &auth_info, p->endian);
574         if (!NT_STATUS_IS_OK(status)) {
575                 DEBUG(0, ("Failed to unmarshall dcerpc_auth.\n"));
576                 goto err;
577         }
578
579         /* We must NEVER look at auth_info->auth_pad_len here,
580          * as old Samba client code gets it wrong and sends it
581          * as zero. JRA.
582          */
583
584         if (auth_info.auth_type != DCERPC_AUTH_TYPE_NTLMSSP) {
585                 DEBUG(0,("api_pipe_bind_auth3: incorrect auth type (%u).\n",
586                         (unsigned int)auth_info.auth_type ));
587                 return False;
588         }
589
590         /*
591          * The following call actually checks the challenge/response data.
592          * for correctness against the given DOMAIN\user name.
593          */
594
595         if (!pipe_ntlmssp_verify_final(p, &auth_info.credentials)) {
596                 goto err;
597         }
598
599         p->pipe_bound = True;
600
601         return True;
602
603  err:
604
605         free_pipe_ntlmssp_auth_data(&p->auth);
606         p->auth.a_u.auth_ntlmssp_state = NULL;
607
608         return False;
609 }
610
611 static bool pipe_init_outgoing_data(pipes_struct *p);
612
613 /*******************************************************************
614  Marshall a bind_nak pdu.
615 *******************************************************************/
616
617 static bool setup_bind_nak(pipes_struct *p, struct ncacn_packet *pkt)
618 {
619         NTSTATUS status;
620         union dcerpc_payload u;
621
622         /* Free any memory in the current return data buffer. */
623         pipe_init_outgoing_data(p);
624
625         /*
626          * Initialize a bind_nak header.
627          */
628
629         ZERO_STRUCT(u);
630
631         u.bind_nak.reject_reason  = 0;
632
633         /*
634          * Marshall directly into the outgoing PDU space. We
635          * must do this as we need to set to the bind response
636          * header and are never sending more than one PDU here.
637          */
638
639         status = dcerpc_push_ncacn_packet(p->mem_ctx,
640                                           DCERPC_PKT_BIND_NAK,
641                                           DCERPC_PFC_FLAG_FIRST |
642                                                 DCERPC_PFC_FLAG_LAST,
643                                           0,
644                                           pkt->call_id,
645                                           &u,
646                                           &p->out_data.frag);
647         if (!NT_STATUS_IS_OK(status)) {
648                 return False;
649         }
650
651         p->out_data.data_sent_length = 0;
652         p->out_data.current_pdu_sent = 0;
653
654         if (p->auth.auth_data_free_func) {
655                 (*p->auth.auth_data_free_func)(&p->auth);
656         }
657         p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
658         p->auth.auth_type = PIPE_AUTH_TYPE_NONE;
659         p->pipe_bound = False;
660
661         return True;
662 }
663
664 /*******************************************************************
665  Marshall a fault pdu.
666 *******************************************************************/
667
668 bool setup_fault_pdu(pipes_struct *p, NTSTATUS fault_status)
669 {
670         NTSTATUS status;
671         union dcerpc_payload u;
672
673         /* Free any memory in the current return data buffer. */
674         pipe_init_outgoing_data(p);
675
676         /*
677          * Initialize a fault header.
678          */
679
680         ZERO_STRUCT(u);
681
682         u.fault.status          = NT_STATUS_V(fault_status);
683         u.fault._pad            = data_blob_talloc_zero(p->mem_ctx, 4);
684
685         /*
686          * Marshall directly into the outgoing PDU space. We
687          * must do this as we need to set to the bind response
688          * header and are never sending more than one PDU here.
689          */
690
691         status = dcerpc_push_ncacn_packet(p->mem_ctx,
692                                           DCERPC_PKT_FAULT,
693                                           DCERPC_PFC_FLAG_FIRST |
694                                            DCERPC_PFC_FLAG_LAST |
695                                            DCERPC_PFC_FLAG_DID_NOT_EXECUTE,
696                                           0,
697                                           p->call_id,
698                                           &u,
699                                           &p->out_data.frag);
700         if (!NT_STATUS_IS_OK(status)) {
701                 return False;
702         }
703
704         p->out_data.data_sent_length = 0;
705         p->out_data.current_pdu_sent = 0;
706
707         return True;
708 }
709
710 /*******************************************************************
711  Ensure a bind request has the correct abstract & transfer interface.
712  Used to reject unknown binds from Win2k.
713 *******************************************************************/
714
715 static bool check_bind_req(struct pipes_struct *p,
716                            struct ndr_syntax_id* abstract,
717                            struct ndr_syntax_id* transfer,
718                            uint32 context_id)
719 {
720         struct pipe_rpc_fns *context_fns;
721
722         DEBUG(3,("check_bind_req for %s\n",
723                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
724
725         /* we have to check all now since win2k introduced a new UUID on the lsaprpc pipe */
726         if (rpc_srv_pipe_exists_by_id(abstract) &&
727            ndr_syntax_id_equal(transfer, &ndr_transfer_syntax)) {
728                 DEBUG(3, ("check_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
729                         rpc_srv_get_pipe_cli_name(abstract),
730                         rpc_srv_get_pipe_srv_name(abstract)));
731         } else {
732                 return false;
733         }
734
735         context_fns = SMB_MALLOC_P(struct pipe_rpc_fns);
736         if (context_fns == NULL) {
737                 DEBUG(0,("check_bind_req: malloc() failed!\n"));
738                 return False;
739         }
740
741         context_fns->n_cmds = rpc_srv_get_pipe_num_cmds(abstract);
742         context_fns->cmds = rpc_srv_get_pipe_cmds(abstract);
743         context_fns->context_id = context_id;
744
745         /* add to the list of open contexts */
746
747         DLIST_ADD( p->contexts, context_fns );
748
749         return True;
750 }
751
752 /**
753  * Is a named pipe known?
754  * @param[in] cli_filename      The pipe name requested by the client
755  * @result                      Do we want to serve this?
756  */
757 bool is_known_pipename(const char *cli_filename, struct ndr_syntax_id *syntax)
758 {
759         const char *pipename = cli_filename;
760         NTSTATUS status;
761
762         if (strnequal(pipename, "\\PIPE\\", 6)) {
763                 pipename += 5;
764         }
765
766         if (*pipename == '\\') {
767                 pipename += 1;
768         }
769
770         if (lp_disable_spoolss() && strequal(pipename, "spoolss")) {
771                 DEBUG(10, ("refusing spoolss access\n"));
772                 return false;
773         }
774
775         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
776                 return true;
777         }
778
779         status = smb_probe_module("rpc", pipename);
780         if (!NT_STATUS_IS_OK(status)) {
781                 DEBUG(10, ("is_known_pipename: %s unknown\n", cli_filename));
782                 return false;
783         }
784         DEBUG(10, ("is_known_pipename: %s loaded dynamically\n", pipename));
785
786         /*
787          * Scan the list again for the interface id
788          */
789         if (rpc_srv_get_pipe_interface_by_cli_name(pipename, syntax)) {
790                 return true;
791         }
792
793         DEBUG(10, ("is_known_pipename: pipe %s did not register itself!\n",
794                    pipename));
795
796         return false;
797 }
798
799 /*******************************************************************
800  Handle a SPNEGO krb5 bind auth.
801 *******************************************************************/
802
803 static bool pipe_spnego_auth_bind_kerberos(pipes_struct *p,
804                                            TALLOC_CTX *mem_ctx,
805                                            struct dcerpc_auth *pauth_info,
806                                            DATA_BLOB *psecblob,
807                                            DATA_BLOB *response)
808 {
809         return False;
810 }
811
812 /*******************************************************************
813  Handle the first part of a SPNEGO bind auth.
814 *******************************************************************/
815
816 static bool pipe_spnego_auth_bind_negotiate(pipes_struct *p,
817                                             TALLOC_CTX *mem_ctx,
818                                             struct dcerpc_auth *pauth_info,
819                                             DATA_BLOB *response)
820 {
821         DATA_BLOB secblob;
822         DATA_BLOB chal;
823         char *OIDs[ASN1_MAX_OIDS];
824         int i;
825         NTSTATUS status;
826         bool got_kerberos_mechanism = false;
827         struct auth_ntlmssp_state *a = NULL;
828
829         ZERO_STRUCT(secblob);
830         ZERO_STRUCT(chal);
831
832         if (pauth_info->credentials.data[0] != ASN1_APPLICATION(0)) {
833                 goto err;
834         }
835
836         /* parse out the OIDs and the first sec blob */
837         if (!spnego_parse_negTokenInit(talloc_tos(),
838                         pauth_info->credentials, OIDs, NULL, &secblob)) {
839                 DEBUG(0,("pipe_spnego_auth_bind_negotiate: Failed to parse the security blob.\n"));
840                 goto err;
841         }
842
843         if (strcmp(OID_KERBEROS5, OIDs[0]) == 0 || strcmp(OID_KERBEROS5_OLD, OIDs[0]) == 0) {
844                 got_kerberos_mechanism = true;
845         }
846
847         for (i=0;OIDs[i];i++) {
848                 DEBUG(3,("pipe_spnego_auth_bind_negotiate: Got OID %s\n", OIDs[i]));
849                 TALLOC_FREE(OIDs[i]);
850         }
851         DEBUG(3,("pipe_spnego_auth_bind_negotiate: Got secblob of size %lu\n", (unsigned long)secblob.length));
852
853         if ( got_kerberos_mechanism && ((lp_security()==SEC_ADS) || USE_KERBEROS_KEYTAB) ) {
854                 bool ret;
855                 ret = pipe_spnego_auth_bind_kerberos(p, mem_ctx, pauth_info,
856                                                      &secblob, response);
857                 data_blob_free(&secblob);
858                 return ret;
859         }
860
861         if (p->auth.auth_type == PIPE_AUTH_TYPE_SPNEGO_NTLMSSP && p->auth.a_u.auth_ntlmssp_state) {
862                 /* Free any previous auth type. */
863                 free_pipe_ntlmssp_auth_data(&p->auth);
864         }
865
866         if (!got_kerberos_mechanism) {
867                 /* Initialize the NTLM engine. */
868                 status = auth_ntlmssp_start(&a);
869                 if (!NT_STATUS_IS_OK(status)) {
870                         goto err;
871                 }
872
873                 switch (pauth_info->auth_level) {
874                         case DCERPC_AUTH_LEVEL_INTEGRITY:
875                                 auth_ntlmssp_want_sign(a);
876                                 break;
877                         case DCERPC_AUTH_LEVEL_PRIVACY:
878                                 auth_ntlmssp_want_seal(a);
879                                 break;
880                         default:
881                                 break;
882                 }
883                 /*
884                  * Pass the first security blob of data to it.
885                  * This can return an error or NT_STATUS_MORE_PROCESSING_REQUIRED
886                  * which means we need another packet to complete the bind.
887                  */
888
889                 status = auth_ntlmssp_update(a, secblob, &chal);
890
891                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
892                         DEBUG(3,("pipe_spnego_auth_bind_negotiate: auth_ntlmssp_update failed.\n"));
893                         goto err;
894                 }
895
896                 /* Generate the response blob we need for step 2 of the bind. */
897                 *response = spnego_gen_auth_response(mem_ctx, &chal, status, OID_NTLMSSP);
898         } else {
899                 /*
900                  * SPNEGO negotiate down to NTLMSSP. The subsequent
901                  * code to process follow-up packets is not complete
902                  * yet. JRA.
903                  */
904                 *response = spnego_gen_auth_response(mem_ctx, NULL,
905                                         NT_STATUS_MORE_PROCESSING_REQUIRED,
906                                         OID_NTLMSSP);
907         }
908
909         /* auth_pad_len will be handled by the caller */
910
911         p->auth.a_u.auth_ntlmssp_state = a;
912         p->auth.auth_data_free_func = &free_pipe_ntlmssp_auth_data;
913         p->auth.auth_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
914
915         data_blob_free(&secblob);
916         data_blob_free(&chal);
917
918         /* We can't set pipe_bound True yet - we need an RPC_ALTER_CONTEXT response packet... */
919         return True;
920
921  err:
922
923         data_blob_free(&secblob);
924         data_blob_free(&chal);
925
926         p->auth.a_u.auth_ntlmssp_state = NULL;
927
928         return False;
929 }
930
931 /*******************************************************************
932  Handle the second part of a SPNEGO bind auth.
933 *******************************************************************/
934
935 static bool pipe_spnego_auth_bind_continue(pipes_struct *p,
936                                            TALLOC_CTX *mem_ctx,
937                                            struct dcerpc_auth *pauth_info,
938                                            DATA_BLOB *response)
939 {
940         DATA_BLOB auth_blob;
941         DATA_BLOB auth_reply;
942         struct auth_ntlmssp_state *a = p->auth.a_u.auth_ntlmssp_state;
943
944         ZERO_STRUCT(auth_blob);
945         ZERO_STRUCT(auth_reply);
946
947         /*
948          * NB. If we've negotiated down from krb5 to NTLMSSP we'll currently
949          * fail here as 'a' == NULL.
950          */
951         if (p->auth.auth_type != PIPE_AUTH_TYPE_SPNEGO_NTLMSSP || !a) {
952                 DEBUG(0,("pipe_spnego_auth_bind_continue: not in NTLMSSP auth state.\n"));
953                 goto err;
954         }
955
956         if (pauth_info->credentials.data[0] != ASN1_CONTEXT(1)) {
957                 DEBUG(0,("pipe_spnego_auth_bind_continue: invalid SPNEGO blob type.\n"));
958                 goto err;
959         }
960
961         if (!spnego_parse_auth(talloc_tos(), pauth_info->credentials, &auth_blob)) {
962                 DEBUG(0,("pipe_spnego_auth_bind_continue: invalid SPNEGO blob.\n"));
963                 goto err;
964         }
965
966         /*
967          * The following call actually checks the challenge/response data.
968          * for correctness against the given DOMAIN\user name.
969          */
970
971         if (!pipe_ntlmssp_verify_final(p, &auth_blob)) {
972                 goto err;
973         }
974
975         data_blob_free(&auth_blob);
976
977         /* Generate the spnego "accept completed" blob - no incoming data. */
978         *response = spnego_gen_auth_response(mem_ctx, &auth_reply, NT_STATUS_OK, OID_NTLMSSP);
979
980         data_blob_free(&auth_reply);
981
982         p->pipe_bound = True;
983
984         return True;
985
986  err:
987
988         data_blob_free(&auth_blob);
989         data_blob_free(&auth_reply);
990
991         free_pipe_ntlmssp_auth_data(&p->auth);
992         p->auth.a_u.auth_ntlmssp_state = NULL;
993
994         return False;
995 }
996
997 /*******************************************************************
998  Handle an schannel bind auth.
999 *******************************************************************/
1000
1001 static bool pipe_schannel_auth_bind(pipes_struct *p,
1002                                     TALLOC_CTX *mem_ctx,
1003                                     struct dcerpc_auth *auth_info,
1004                                     DATA_BLOB *response)
1005 {
1006         struct NL_AUTH_MESSAGE neg;
1007         struct NL_AUTH_MESSAGE reply;
1008         bool ret;
1009         NTSTATUS status;
1010         struct netlogon_creds_CredentialState *creds;
1011         DATA_BLOB session_key;
1012         enum ndr_err_code ndr_err;
1013
1014         ndr_err = ndr_pull_struct_blob(
1015                         &auth_info->credentials, mem_ctx, &neg,
1016                         (ndr_pull_flags_fn_t)ndr_pull_NL_AUTH_MESSAGE);
1017         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1018                 DEBUG(0,("pipe_schannel_auth_bind: Could not unmarshal SCHANNEL auth neg\n"));
1019                 return false;
1020         }
1021
1022         if (DEBUGLEVEL >= 10) {
1023                 NDR_PRINT_DEBUG(NL_AUTH_MESSAGE, &neg);
1024         }
1025
1026         if (!(neg.Flags & NL_FLAG_OEM_NETBIOS_COMPUTER_NAME)) {
1027                 DEBUG(0,("pipe_schannel_auth_bind: Did not receive netbios computer name\n"));
1028                 return false;
1029         }
1030
1031         /*
1032          * The neg.oem_netbios_computer.a key here must match the remote computer name
1033          * given in the DOM_CLNT_SRV.uni_comp_name used on all netlogon pipe
1034          * operations that use credentials.
1035          */
1036
1037         become_root();
1038         status = schannel_get_creds_state(p, lp_private_dir(),
1039                                             neg.oem_netbios_computer.a, &creds);
1040         unbecome_root();
1041
1042         if (!NT_STATUS_IS_OK(status)) {
1043                 DEBUG(0, ("pipe_schannel_auth_bind: Attempt to bind using schannel without successful serverauth2\n"));
1044                 return False;
1045         }
1046
1047         p->auth.a_u.schannel_auth = talloc(p, struct schannel_state);
1048         if (!p->auth.a_u.schannel_auth) {
1049                 TALLOC_FREE(creds);
1050                 return False;
1051         }
1052
1053         p->auth.a_u.schannel_auth->state = SCHANNEL_STATE_START;
1054         p->auth.a_u.schannel_auth->seq_num = 0;
1055         p->auth.a_u.schannel_auth->initiator = false;
1056         p->auth.a_u.schannel_auth->creds = creds;
1057
1058         /*
1059          * JRA. Should we also copy the schannel session key into the pipe session key p->session_key
1060          * here ? We do that for NTLMSSP, but the session key is already set up from the vuser
1061          * struct of the person who opened the pipe. I need to test this further. JRA.
1062          *
1063          * VL. As we are mapping this to guest set the generic key
1064          * "SystemLibraryDTC" key here. It's a bit difficult to test against
1065          * W2k3, as it does not allow schannel binds against SAMR and LSA
1066          * anymore.
1067          */
1068
1069         session_key = generic_session_key();
1070         if (session_key.data == NULL) {
1071                 DEBUG(0, ("pipe_schannel_auth_bind: Could not alloc session"
1072                           " key\n"));
1073                 return false;
1074         }
1075
1076         ret = server_info_set_session_key(p->server_info, session_key);
1077
1078         data_blob_free(&session_key);
1079
1080         if (!ret) {
1081                 DEBUG(0, ("server_info_set_session_key failed\n"));
1082                 return false;
1083         }
1084
1085         /*** SCHANNEL verifier ***/
1086
1087         reply.MessageType                       = NL_NEGOTIATE_RESPONSE;
1088         reply.Flags                             = 0;
1089         reply.Buffer.dummy                      = 5; /* ??? actually I don't think
1090                                                       * this has any meaning
1091                                                       * here - gd */
1092
1093         ndr_err = ndr_push_struct_blob(response, mem_ctx, &reply,
1094                        (ndr_push_flags_fn_t)ndr_push_NL_AUTH_MESSAGE);
1095         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1096                 DEBUG(0,("Failed to marshall NL_AUTH_MESSAGE.\n"));
1097                 return false;
1098         }
1099
1100         if (DEBUGLEVEL >= 10) {
1101                 NDR_PRINT_DEBUG(NL_AUTH_MESSAGE, &reply);
1102         }
1103
1104         DEBUG(10,("pipe_schannel_auth_bind: schannel auth: domain [%s] myname [%s]\n",
1105                 neg.oem_netbios_domain.a, neg.oem_netbios_computer.a));
1106
1107         /* We're finished with this bind - no more packets. */
1108         p->auth.auth_data_free_func = &free_pipe_schannel_auth_data;
1109         p->auth.auth_type = PIPE_AUTH_TYPE_SCHANNEL;
1110
1111         p->pipe_bound = True;
1112
1113         return True;
1114 }
1115
1116 /*******************************************************************
1117  Handle an NTLMSSP bind auth.
1118 *******************************************************************/
1119
1120 static bool pipe_ntlmssp_auth_bind(pipes_struct *p,
1121                                    TALLOC_CTX *mem_ctx,
1122                                    struct dcerpc_auth *auth_info,
1123                                    DATA_BLOB *response)
1124 {
1125         NTSTATUS status;
1126         struct auth_ntlmssp_state *a = NULL;
1127
1128         if (strncmp((char *)auth_info->credentials.data, "NTLMSSP", 7) != 0) {
1129                 DEBUG(0, ("Failed to read NTLMSSP in blob\n"));
1130                 goto err;
1131         }
1132
1133         /* We have an NTLMSSP blob. */
1134         status = auth_ntlmssp_start(&a);
1135         if (!NT_STATUS_IS_OK(status)) {
1136                 DEBUG(0,("pipe_ntlmssp_auth_bind: auth_ntlmssp_start failed: %s\n",
1137                         nt_errstr(status) ));
1138                 goto err;
1139         }
1140
1141         switch (auth_info->auth_level) {
1142         case DCERPC_AUTH_LEVEL_INTEGRITY:
1143                 auth_ntlmssp_want_sign(a);
1144                 break;
1145         case DCERPC_AUTH_LEVEL_PRIVACY:
1146                 auth_ntlmssp_want_seal(a);
1147                 break;
1148         default:
1149                 break;
1150         }
1151
1152         status = auth_ntlmssp_update(a, auth_info->credentials, response);
1153         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1154                 DEBUG(0,("pipe_ntlmssp_auth_bind: auth_ntlmssp_update failed: %s\n",
1155                         nt_errstr(status) ));
1156                 goto err;
1157         }
1158
1159         /* Make sure data is bound to the memctx, to be freed the caller */
1160         talloc_steal(mem_ctx, response->data);
1161
1162         p->auth.a_u.auth_ntlmssp_state = a;
1163         p->auth.auth_data_free_func = &free_pipe_ntlmssp_auth_data;
1164         p->auth.auth_type = PIPE_AUTH_TYPE_NTLMSSP;
1165
1166         DEBUG(10,("pipe_ntlmssp_auth_bind: NTLMSSP auth started\n"));
1167
1168         /* We can't set pipe_bound True yet - we need an DCERPC_PKT_AUTH3 response packet... */
1169         return True;
1170
1171   err:
1172
1173         free_pipe_ntlmssp_auth_data(&p->auth);
1174         p->auth.a_u.auth_ntlmssp_state = NULL;
1175         return False;
1176 }
1177
1178 /*******************************************************************
1179  Respond to a pipe bind request.
1180 *******************************************************************/
1181
1182 bool api_pipe_bind_req(pipes_struct *p, struct ncacn_packet *pkt)
1183 {
1184         struct dcerpc_auth auth_info;
1185         uint16 assoc_gid;
1186         unsigned int auth_type = DCERPC_AUTH_TYPE_NONE;
1187         NTSTATUS status;
1188         struct ndr_syntax_id id;
1189         union dcerpc_payload u;
1190         struct dcerpc_ack_ctx bind_ack_ctx;
1191         DATA_BLOB auth_resp = data_blob_null;
1192         DATA_BLOB auth_blob = data_blob_null;
1193
1194         /* No rebinds on a bound pipe - use alter context. */
1195         if (p->pipe_bound) {
1196                 DEBUG(2,("api_pipe_bind_req: rejecting bind request on bound "
1197                          "pipe %s.\n",
1198                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1199                 return setup_bind_nak(p, pkt);
1200         }
1201
1202         if (pkt->u.bind.num_contexts == 0) {
1203                 DEBUG(0, ("api_pipe_bind_req: no rpc contexts around\n"));
1204                 goto err_exit;
1205         }
1206
1207         /*
1208          * Try and find the correct pipe name to ensure
1209          * that this is a pipe name we support.
1210          */
1211         id = pkt->u.bind.ctx_list[0].abstract_syntax;
1212         if (rpc_srv_pipe_exists_by_id(&id)) {
1213                 DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
1214                         rpc_srv_get_pipe_cli_name(&id),
1215                         rpc_srv_get_pipe_srv_name(&id)));
1216         } else {
1217                 status = smb_probe_module(
1218                         "rpc", get_pipe_name_from_syntax(
1219                                 talloc_tos(),
1220                                 &pkt->u.bind.ctx_list[0].abstract_syntax));
1221
1222                 if (NT_STATUS_IS_ERR(status)) {
1223                        DEBUG(3,("api_pipe_bind_req: Unknown pipe name %s in bind request.\n",
1224                                 get_pipe_name_from_syntax(
1225                                         talloc_tos(),
1226                                         &pkt->u.bind.ctx_list[0].abstract_syntax)));
1227
1228                         return setup_bind_nak(p, pkt);
1229                 }
1230
1231                 if (rpc_srv_get_pipe_interface_by_cli_name(
1232                                 get_pipe_name_from_syntax(talloc_tos(),
1233                                                           &p->syntax),
1234                                 &id)) {
1235                         DEBUG(3, ("api_pipe_bind_req: \\PIPE\\%s -> \\PIPE\\%s\n",
1236                                 rpc_srv_get_pipe_cli_name(&id),
1237                                 rpc_srv_get_pipe_srv_name(&id)));
1238                 } else {
1239                         DEBUG(0, ("module %s doesn't provide functions for "
1240                                   "pipe %s!\n",
1241                                   get_pipe_name_from_syntax(talloc_tos(),
1242                                                             &p->syntax),
1243                                   get_pipe_name_from_syntax(talloc_tos(),
1244                                                             &p->syntax)));
1245                         return setup_bind_nak(p, pkt);
1246                 }
1247         }
1248
1249         DEBUG(5,("api_pipe_bind_req: make response. %d\n", __LINE__));
1250
1251         if (pkt->u.bind.assoc_group_id != 0) {
1252                 assoc_gid = pkt->u.bind.assoc_group_id;
1253         } else {
1254                 assoc_gid = 0x53f0;
1255         }
1256
1257         /*
1258          * Create the bind response struct.
1259          */
1260
1261         /* If the requested abstract synt uuid doesn't match our client pipe,
1262                 reject the bind_ack & set the transfer interface synt to all 0's,
1263                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1264                 unknown to NT4)
1265                 Needed when adding entries to a DACL from NT5 - SK */
1266
1267         if (check_bind_req(p,
1268                         &pkt->u.bind.ctx_list[0].abstract_syntax,
1269                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
1270                         pkt->u.bind.ctx_list[0].context_id)) {
1271
1272                 bind_ack_ctx.result = 0;
1273                 bind_ack_ctx.reason = 0;
1274                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
1275         } else {
1276                 p->pipe_bound = False;
1277                 /* Rejection reason: abstract syntax not supported */
1278                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1279                 bind_ack_ctx.reason = DCERPC_BIND_REASON_ASYNTAX;
1280                 bind_ack_ctx.syntax = null_ndr_syntax_id;
1281         }
1282
1283         /*
1284          * Check if this is an authenticated bind request.
1285          */
1286         if (pkt->auth_length) {
1287                 /* Quick length check. Won't catch a bad auth footer,
1288                  * prevents overrun. */
1289
1290                 if (pkt->frag_length < RPC_HEADER_LEN +
1291                                         DCERPC_AUTH_TRAILER_LENGTH +
1292                                         pkt->auth_length) {
1293                         DEBUG(0,("api_pipe_bind_req: auth_len (%u) "
1294                                 "too long for fragment %u.\n",
1295                                 (unsigned int)pkt->auth_length,
1296                                 (unsigned int)pkt->frag_length));
1297                         goto err_exit;
1298                 }
1299
1300                 /*
1301                  * Decode the authentication verifier.
1302                  */
1303                 status = dcerpc_pull_dcerpc_auth(pkt,
1304                                                  &pkt->u.bind.auth_info,
1305                                                  &auth_info, p->endian);
1306                 if (!NT_STATUS_IS_OK(status)) {
1307                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1308                         goto err_exit;
1309                 }
1310
1311                 auth_type = auth_info.auth_type;
1312
1313                 /* Work out if we have to sign or seal etc. */
1314                 switch (auth_info.auth_level) {
1315                 case DCERPC_AUTH_LEVEL_INTEGRITY:
1316                         p->auth.auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1317                         break;
1318                 case DCERPC_AUTH_LEVEL_PRIVACY:
1319                         p->auth.auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1320                         break;
1321                 default:
1322                         DEBUG(0, ("Unexpected auth level (%u).\n",
1323                                 (unsigned int)auth_info.auth_level ));
1324                         goto err_exit;
1325                 }
1326
1327                 switch (auth_type) {
1328                 case DCERPC_AUTH_TYPE_NTLMSSP:
1329                         if (!pipe_ntlmssp_auth_bind(p, pkt,
1330                                                 &auth_info, &auth_resp)) {
1331                                 goto err_exit;
1332                         }
1333                         assoc_gid = 0x7a77;
1334                         break;
1335
1336                 case DCERPC_AUTH_TYPE_SCHANNEL:
1337                         if (!pipe_schannel_auth_bind(p, pkt,
1338                                                 &auth_info, &auth_resp)) {
1339                                 goto err_exit;
1340                         }
1341                         break;
1342
1343                 case DCERPC_AUTH_TYPE_SPNEGO:
1344                         if (!pipe_spnego_auth_bind_negotiate(p, pkt,
1345                                                 &auth_info, &auth_resp)) {
1346                                 goto err_exit;
1347                         }
1348                         break;
1349
1350                 case DCERPC_AUTH_TYPE_NONE:
1351                         break;
1352
1353                 default:
1354                         DEBUG(0, ("Unknown auth type %x requested.\n", auth_type));
1355                         goto err_exit;
1356                 }
1357         }
1358
1359         if (auth_type == DCERPC_AUTH_TYPE_NONE) {
1360                 /* Unauthenticated bind request. */
1361                 /* We're finished - no more packets. */
1362                 p->auth.auth_type = PIPE_AUTH_TYPE_NONE;
1363                 /* We must set the pipe auth_level here also. */
1364                 p->auth.auth_level = DCERPC_AUTH_LEVEL_NONE;
1365                 p->pipe_bound = True;
1366                 /* The session key was initialized from the SMB
1367                  * session in make_internal_rpc_pipe_p */
1368         }
1369
1370         ZERO_STRUCT(u.bind_ack);
1371         u.bind_ack.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1372         u.bind_ack.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1373         u.bind_ack.assoc_group_id = assoc_gid;
1374
1375         /* name has to be \PIPE\xxxxx */
1376         u.bind_ack.secondary_address =
1377                         talloc_asprintf(pkt, "\\PIPE\\%s",
1378                                         rpc_srv_get_pipe_srv_name(&id));
1379         if (!u.bind_ack.secondary_address) {
1380                 DEBUG(0, ("Out of memory!\n"));
1381                 goto err_exit;
1382         }
1383         u.bind_ack.secondary_address_size =
1384                                 strlen(u.bind_ack.secondary_address) + 1;
1385
1386         u.bind_ack.num_results = 1;
1387         u.bind_ack.ctx_list = &bind_ack_ctx;
1388
1389         /* NOTE: We leave the auth_info empty so we can calculate the padding
1390          * later and then append the auth_info --simo */
1391
1392         /*
1393          * Marshall directly into the outgoing PDU space. We
1394          * must do this as we need to set to the bind response
1395          * header and are never sending more than one PDU here.
1396          */
1397
1398         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1399                                           DCERPC_PKT_BIND_ACK,
1400                                           DCERPC_PFC_FLAG_FIRST |
1401                                                 DCERPC_PFC_FLAG_LAST,
1402                                           auth_resp.length,
1403                                           pkt->call_id,
1404                                           &u,
1405                                           &p->out_data.frag);
1406         if (!NT_STATUS_IS_OK(status)) {
1407                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
1408                           nt_errstr(status)));
1409         }
1410
1411         if (auth_resp.length) {
1412
1413                 status = dcerpc_push_dcerpc_auth(pkt,
1414                                                  auth_type,
1415                                                  auth_info.auth_level,
1416                                                  0,
1417                                                  1, /* auth_context_id */
1418                                                  &auth_resp,
1419                                                  &auth_blob);
1420                 if (!NT_STATUS_IS_OK(status)) {
1421                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1422                         goto err_exit;
1423                 }
1424         }
1425
1426         /* Now that we have the auth len store it into the right place in
1427          * the dcerpc header */
1428         dcerpc_set_frag_length(&p->out_data.frag,
1429                                 p->out_data.frag.length + auth_blob.length);
1430
1431         if (auth_blob.length) {
1432
1433                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1434                                         auth_blob.data, auth_blob.length)) {
1435                         DEBUG(0, ("Append of auth info failed.\n"));
1436                         goto err_exit;
1437                 }
1438         }
1439
1440         /*
1441          * Setup the lengths for the initial reply.
1442          */
1443
1444         p->out_data.data_sent_length = 0;
1445         p->out_data.current_pdu_sent = 0;
1446
1447         TALLOC_FREE(auth_blob.data);
1448         return True;
1449
1450   err_exit:
1451
1452         data_blob_free(&p->out_data.frag);
1453         TALLOC_FREE(auth_blob.data);
1454         return setup_bind_nak(p, pkt);
1455 }
1456
1457 /****************************************************************************
1458  Deal with an alter context call. Can be third part of 3 leg auth request for
1459  SPNEGO calls.
1460 ****************************************************************************/
1461
1462 bool api_pipe_alter_context(pipes_struct *p, struct ncacn_packet *pkt)
1463 {
1464         struct dcerpc_auth auth_info;
1465         uint16 assoc_gid;
1466         NTSTATUS status;
1467         union dcerpc_payload u;
1468         struct dcerpc_ack_ctx bind_ack_ctx;
1469         DATA_BLOB auth_resp = data_blob_null;
1470         DATA_BLOB auth_blob = data_blob_null;
1471         int pad_len = 0;
1472
1473         DEBUG(5,("api_pipe_alter_context: make response. %d\n", __LINE__));
1474
1475         if (pkt->u.bind.assoc_group_id != 0) {
1476                 assoc_gid = pkt->u.bind.assoc_group_id;
1477         } else {
1478                 assoc_gid = 0x53f0;
1479         }
1480
1481         /*
1482          * Create the bind response struct.
1483          */
1484
1485         /* If the requested abstract synt uuid doesn't match our client pipe,
1486                 reject the bind_ack & set the transfer interface synt to all 0's,
1487                 ver 0 (observed when NT5 attempts to bind to abstract interfaces
1488                 unknown to NT4)
1489                 Needed when adding entries to a DACL from NT5 - SK */
1490
1491         if (check_bind_req(p,
1492                         &pkt->u.bind.ctx_list[0].abstract_syntax,
1493                         &pkt->u.bind.ctx_list[0].transfer_syntaxes[0],
1494                         pkt->u.bind.ctx_list[0].context_id)) {
1495
1496                 bind_ack_ctx.result = 0;
1497                 bind_ack_ctx.reason = 0;
1498                 bind_ack_ctx.syntax = pkt->u.bind.ctx_list[0].transfer_syntaxes[0];
1499         } else {
1500                 p->pipe_bound = False;
1501                 /* Rejection reason: abstract syntax not supported */
1502                 bind_ack_ctx.result = DCERPC_BIND_PROVIDER_REJECT;
1503                 bind_ack_ctx.reason = DCERPC_BIND_REASON_ASYNTAX;
1504                 bind_ack_ctx.syntax = null_ndr_syntax_id;
1505         }
1506
1507         /*
1508          * Check if this is an authenticated alter context request.
1509          */
1510         if (pkt->auth_length) {
1511                 /* Quick length check. Won't catch a bad auth footer,
1512                  * prevents overrun. */
1513
1514                 if (pkt->frag_length < RPC_HEADER_LEN +
1515                                         DCERPC_AUTH_TRAILER_LENGTH +
1516                                         pkt->auth_length) {
1517                         DEBUG(0,("api_pipe_alter_context: auth_len (%u) "
1518                                 "too long for fragment %u.\n",
1519                                 (unsigned int)pkt->auth_length,
1520                                 (unsigned int)pkt->frag_length ));
1521                         goto err_exit;
1522                 }
1523
1524                 status = dcerpc_pull_dcerpc_auth(pkt,
1525                                                  &pkt->u.bind.auth_info,
1526                                                  &auth_info, p->endian);
1527                 if (!NT_STATUS_IS_OK(status)) {
1528                         DEBUG(0, ("Unable to unmarshall dcerpc_auth.\n"));
1529                         goto err_exit;
1530                 }
1531
1532
1533                 /*
1534                  * Currently only the SPNEGO auth type uses the alter ctx
1535                  * response in place of the NTLMSSP auth3 type.
1536                  */
1537
1538                 if (auth_info.auth_type == DCERPC_AUTH_TYPE_SPNEGO) {
1539                         /* We can only finish if the pipe is unbound. */
1540                         if (!p->pipe_bound) {
1541                                 if (!pipe_spnego_auth_bind_continue(p, pkt,
1542                                                 &auth_info, &auth_resp)) {
1543                                         goto err_exit;
1544                                 }
1545
1546                         } else {
1547                                 goto err_exit;
1548                         }
1549                 }
1550         }
1551
1552         ZERO_STRUCT(u.alter_resp);
1553         u.alter_resp.max_xmit_frag = RPC_MAX_PDU_FRAG_LEN;
1554         u.alter_resp.max_recv_frag = RPC_MAX_PDU_FRAG_LEN;
1555         u.alter_resp.assoc_group_id = assoc_gid;
1556
1557         /* secondary address CAN be NULL
1558          * as the specs say it's ignored.
1559          * It MUST be NULL to have the spoolss working.
1560          */
1561         u.alter_resp.secondary_address = "";
1562         u.alter_resp.secondary_address_size = 1;
1563
1564         u.alter_resp.num_results = 1;
1565         u.alter_resp.ctx_list = &bind_ack_ctx;
1566
1567         /* NOTE: We leave the auth_info empty so we can calculate the padding
1568          * later and then append the auth_info --simo */
1569
1570         /*
1571          * Marshall directly into the outgoing PDU space. We
1572          * must do this as we need to set to the bind response
1573          * header and are never sending more than one PDU here.
1574          */
1575
1576         status = dcerpc_push_ncacn_packet(p->mem_ctx,
1577                                           DCERPC_PKT_ALTER_RESP,
1578                                           DCERPC_PFC_FLAG_FIRST |
1579                                                 DCERPC_PFC_FLAG_LAST,
1580                                           auth_resp.length,
1581                                           pkt->call_id,
1582                                           &u,
1583                                           &p->out_data.frag);
1584         if (!NT_STATUS_IS_OK(status)) {
1585                 DEBUG(0, ("Failed to marshall bind_ack packet. (%s)\n",
1586                           nt_errstr(status)));
1587         }
1588
1589         if (auth_resp.length) {
1590
1591                 /* Work out any padding needed before the auth footer. */
1592                 pad_len = p->out_data.frag.length % SERVER_NDR_PADDING_SIZE;
1593                 if (pad_len) {
1594                         pad_len = SERVER_NDR_PADDING_SIZE - pad_len;
1595                         DEBUG(10, ("auth pad_len = %u\n",
1596                                    (unsigned int)pad_len));
1597                 }
1598
1599                 status = dcerpc_push_dcerpc_auth(pkt,
1600                                                  auth_info.auth_type,
1601                                                  auth_info.auth_level,
1602                                                  pad_len,
1603                                                  1, /* auth_context_id */
1604                                                  &auth_resp,
1605                                                  &auth_blob);
1606                 if (!NT_STATUS_IS_OK(status)) {
1607                         DEBUG(0, ("Marshalling of dcerpc_auth failed.\n"));
1608                         goto err_exit;
1609                 }
1610         }
1611
1612         /* Now that we have the auth len store it into the right place in
1613          * the dcerpc header */
1614         dcerpc_set_frag_length(&p->out_data.frag,
1615                                 p->out_data.frag.length +
1616                                         pad_len + auth_blob.length);
1617
1618         if (auth_resp.length) {
1619                 if (pad_len) {
1620                         char pad[SERVER_NDR_PADDING_SIZE];
1621                         memset(pad, '\0', SERVER_NDR_PADDING_SIZE);
1622                         if (!data_blob_append(p->mem_ctx,
1623                                                 &p->out_data.frag,
1624                                                 pad, pad_len)) {
1625                                 DEBUG(0, ("api_pipe_bind_req: failed to add "
1626                                           "%u bytes of pad data.\n",
1627                                           (unsigned int)pad_len));
1628                                 goto err_exit;
1629                         }
1630                 }
1631
1632                 if (!data_blob_append(p->mem_ctx, &p->out_data.frag,
1633                                         auth_blob.data, auth_blob.length)) {
1634                         DEBUG(0, ("Append of auth info failed.\n"));
1635                         goto err_exit;
1636                 }
1637         }
1638
1639         /*
1640          * Setup the lengths for the initial reply.
1641          */
1642
1643         p->out_data.data_sent_length = 0;
1644         p->out_data.current_pdu_sent = 0;
1645
1646         TALLOC_FREE(auth_blob.data);
1647         return True;
1648
1649   err_exit:
1650
1651         data_blob_free(&p->out_data.frag);
1652         TALLOC_FREE(auth_blob.data);
1653         return setup_bind_nak(p, pkt);
1654 }
1655
1656 /****************************************************************************
1657  Find the set of RPC functions associated with this context_id
1658 ****************************************************************************/
1659
1660 static PIPE_RPC_FNS* find_pipe_fns_by_context( PIPE_RPC_FNS *list, uint32 context_id )
1661 {
1662         PIPE_RPC_FNS *fns = NULL;
1663
1664         if ( !list ) {
1665                 DEBUG(0,("find_pipe_fns_by_context: ERROR!  No context list for pipe!\n"));
1666                 return NULL;
1667         }
1668
1669         for (fns=list; fns; fns=fns->next ) {
1670                 if ( fns->context_id == context_id )
1671                         return fns;
1672         }
1673         return NULL;
1674 }
1675
1676 /****************************************************************************
1677  Memory cleanup.
1678 ****************************************************************************/
1679
1680 void free_pipe_rpc_context( PIPE_RPC_FNS *list )
1681 {
1682         PIPE_RPC_FNS *tmp = list;
1683         PIPE_RPC_FNS *tmp2;
1684
1685         while (tmp) {
1686                 tmp2 = tmp->next;
1687                 SAFE_FREE(tmp);
1688                 tmp = tmp2;
1689         }
1690
1691         return; 
1692 }
1693
1694 static bool api_rpcTNP(pipes_struct *p, struct ncacn_packet *pkt,
1695                        const struct api_struct *api_rpc_cmds, int n_cmds);
1696
1697 /****************************************************************************
1698  Find the correct RPC function to call for this request.
1699  If the pipe is authenticated then become the correct UNIX user
1700  before doing the call.
1701 ****************************************************************************/
1702
1703 bool api_pipe_request(pipes_struct *p, struct ncacn_packet *pkt)
1704 {
1705         bool ret = False;
1706         bool changed_user = False;
1707         PIPE_RPC_FNS *pipe_fns;
1708
1709         if (p->pipe_bound &&
1710                         ((p->auth.auth_type == PIPE_AUTH_TYPE_NTLMSSP) ||
1711                          (p->auth.auth_type == PIPE_AUTH_TYPE_SPNEGO_NTLMSSP))) {
1712                 if(!become_authenticated_pipe_user(p)) {
1713                         data_blob_free(&p->out_data.rdata);
1714                         return False;
1715                 }
1716                 changed_user = True;
1717         }
1718
1719         DEBUG(5, ("Requested \\PIPE\\%s\n",
1720                   get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1721
1722         /* get the set of RPC functions for this context */
1723
1724         pipe_fns = find_pipe_fns_by_context(p->contexts,
1725                                             pkt->u.request.context_id);
1726
1727         if ( pipe_fns ) {
1728                 TALLOC_CTX *frame = talloc_stackframe();
1729                 ret = api_rpcTNP(p, pkt, pipe_fns->cmds, pipe_fns->n_cmds);
1730                 TALLOC_FREE(frame);
1731         }
1732         else {
1733                 DEBUG(0, ("No rpc function table associated with context "
1734                           "[%d] on pipe [%s]\n",
1735                           pkt->u.request.context_id,
1736                           get_pipe_name_from_syntax(talloc_tos(),
1737                                                     &p->syntax)));
1738         }
1739
1740         if (changed_user) {
1741                 unbecome_authenticated_pipe_user();
1742         }
1743
1744         return ret;
1745 }
1746
1747 /*******************************************************************
1748  Calls the underlying RPC function for a named pipe.
1749  ********************************************************************/
1750
1751 static bool api_rpcTNP(pipes_struct *p, struct ncacn_packet *pkt,
1752                        const struct api_struct *api_rpc_cmds, int n_cmds)
1753 {
1754         int fn_num;
1755         uint32_t offset1;
1756
1757         /* interpret the command */
1758         DEBUG(4,("api_rpcTNP: %s op 0x%x - ",
1759                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax),
1760                  pkt->u.request.opnum));
1761
1762         if (DEBUGLEVEL >= 50) {
1763                 fstring name;
1764                 slprintf(name, sizeof(name)-1, "in_%s",
1765                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax));
1766                 dump_pdu_region(name, pkt->u.request.opnum,
1767                                 &p->in_data.data, 0,
1768                                 p->in_data.data.length);
1769         }
1770
1771         for (fn_num = 0; fn_num < n_cmds; fn_num++) {
1772                 if (api_rpc_cmds[fn_num].opnum == pkt->u.request.opnum &&
1773                     api_rpc_cmds[fn_num].fn != NULL) {
1774                         DEBUG(3, ("api_rpcTNP: rpc command: %s\n",
1775                                   api_rpc_cmds[fn_num].name));
1776                         break;
1777                 }
1778         }
1779
1780         if (fn_num == n_cmds) {
1781                 /*
1782                  * For an unknown RPC just return a fault PDU but
1783                  * return True to allow RPC's on the pipe to continue
1784                  * and not put the pipe into fault state. JRA.
1785                  */
1786                 DEBUG(4, ("unknown\n"));
1787                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1788                 return True;
1789         }
1790
1791         offset1 = p->out_data.rdata.length;
1792
1793         DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", 
1794                 fn_num, api_rpc_cmds[fn_num].fn));
1795         /* do the actual command */
1796         if(!api_rpc_cmds[fn_num].fn(p)) {
1797                 DEBUG(0,("api_rpcTNP: %s: %s failed.\n",
1798                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax),
1799                          api_rpc_cmds[fn_num].name));
1800                 data_blob_free(&p->out_data.rdata);
1801                 return False;
1802         }
1803
1804         if (p->bad_handle_fault_state) {
1805                 DEBUG(4,("api_rpcTNP: bad handle fault return.\n"));
1806                 p->bad_handle_fault_state = False;
1807                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_CONTEXT_MISMATCH));
1808                 return True;
1809         }
1810
1811         if (p->rng_fault_state) {
1812                 DEBUG(4, ("api_rpcTNP: rng fault return\n"));
1813                 p->rng_fault_state = False;
1814                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
1815                 return True;
1816         }
1817
1818         if (DEBUGLEVEL >= 50) {
1819                 fstring name;
1820                 slprintf(name, sizeof(name)-1, "out_%s",
1821                          get_pipe_name_from_syntax(talloc_tos(), &p->syntax));
1822                 dump_pdu_region(name, pkt->u.request.opnum,
1823                                 &p->out_data.rdata, offset1,
1824                                 p->out_data.rdata.length);
1825         }
1826
1827         DEBUG(5,("api_rpcTNP: called %s successfully\n",
1828                  get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1829
1830         /* Check for buffer underflow in rpc parsing */
1831         if ((DEBUGLEVEL >= 10) &&
1832             (pkt->frag_length < p->in_data.data.length)) {
1833                 DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n"));
1834                 dump_data(10, p->in_data.data.data + pkt->frag_length,
1835                               p->in_data.data.length - pkt->frag_length);
1836         }
1837
1838         return True;
1839 }
1840
1841 /****************************************************************************
1842  Initialise an outgoing packet.
1843 ****************************************************************************/
1844
1845 static bool pipe_init_outgoing_data(pipes_struct *p)
1846 {
1847         output_data *o_data = &p->out_data;
1848
1849         /* Reset the offset counters. */
1850         o_data->data_sent_length = 0;
1851         o_data->current_pdu_sent = 0;
1852
1853         data_blob_free(&o_data->frag);
1854
1855         /* Free any memory in the current return data buffer. */
1856         data_blob_free(&o_data->rdata);
1857
1858         return True;
1859 }
1860
1861 /****************************************************************************
1862  Sets the fault state on incoming packets.
1863 ****************************************************************************/
1864
1865 void set_incoming_fault(pipes_struct *p)
1866 {
1867         data_blob_free(&p->in_data.data);
1868         p->in_data.pdu_needed_len = 0;
1869         p->in_data.pdu.length = 0;
1870         p->fault_state = True;
1871         DEBUG(10, ("set_incoming_fault: Setting fault state on pipe %s\n",
1872                    get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
1873 }
1874
1875 static bool dcesrv_auth_request(pipes_struct *p, struct ncacn_packet *pkt)
1876 {
1877         NTSTATUS status;
1878         size_t hdr_size = DCERPC_REQUEST_LENGTH;
1879         struct dcerpc_auth auth;
1880         uint32_t auth_length;
1881         DATA_BLOB data;
1882         DATA_BLOB full_pkt;
1883
1884         DEBUG(10, ("Checking request auth.\n"));
1885
1886         if (pkt->pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
1887                 hdr_size += 16;
1888         }
1889
1890         switch (p->auth.auth_level) {
1891         case DCERPC_AUTH_LEVEL_PRIVACY:
1892                 DEBUG(10, ("Requested Privacy.\n"));
1893                 break;
1894
1895         case DCERPC_AUTH_LEVEL_INTEGRITY:
1896                 DEBUG(10, ("Requested Integrity.\n"));
1897                 break;
1898
1899         case DCERPC_AUTH_LEVEL_CONNECT:
1900                 if (pkt->auth_length != 0) {
1901                         break;
1902                 }
1903                 return true;
1904         case DCERPC_AUTH_LEVEL_NONE:
1905                 if (pkt->auth_length != 0) {
1906                         return false;
1907                 }
1908                 return true;
1909
1910         default:
1911                 return false;
1912         }
1913
1914         status = dcerpc_pull_auth_trailer(pkt, pkt,
1915                                           &pkt->u.request.stub_and_verifier,
1916                                           &auth, &auth_length, false);
1917         if (!NT_STATUS_IS_OK(status)) {
1918                 return false;
1919         }
1920
1921         pkt->u.request.stub_and_verifier.length -= auth_length;
1922
1923         data.data = p->in_data.pdu.data + hdr_size;
1924         data.length = pkt->u.request.stub_and_verifier.length;
1925         full_pkt.data = p->in_data.pdu.data;
1926         full_pkt.length = p->in_data.pdu.length - auth.credentials.length;
1927
1928         switch (p->auth.auth_type) {
1929         case PIPE_AUTH_TYPE_NONE:
1930                 return true;
1931
1932         case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
1933         case PIPE_AUTH_TYPE_NTLMSSP:
1934
1935                 DEBUG(10, ("NTLMSSP auth\n"));
1936
1937                 if (!p->auth.a_u.auth_ntlmssp_state) {
1938                         DEBUG(0, ("Invalid auth level, "
1939                                   "failed to process packet auth.\n"));
1940                         return false;
1941                 }
1942
1943                 switch (p->auth.auth_level) {
1944                 case DCERPC_AUTH_LEVEL_PRIVACY:
1945                         status = auth_ntlmssp_unseal_packet(
1946                                         p->auth.a_u.auth_ntlmssp_state,
1947                                         data.data, data.length,
1948                                         full_pkt.data, full_pkt.length,
1949                                         &auth.credentials);
1950                         if (!NT_STATUS_IS_OK(status)) {
1951                                 return false;
1952                         }
1953                         memcpy(pkt->u.request.stub_and_verifier.data,
1954                                 data.data, data.length);
1955                         break;
1956
1957                 case DCERPC_AUTH_LEVEL_INTEGRITY:
1958                         status = auth_ntlmssp_check_packet(
1959                                         p->auth.a_u.auth_ntlmssp_state,
1960                                         data.data, data.length,
1961                                         full_pkt.data, full_pkt.length,
1962                                         &auth.credentials);
1963                         if (!NT_STATUS_IS_OK(status)) {
1964                                 return false;
1965                         }
1966                         break;
1967
1968                 default:
1969                         DEBUG(0, ("Invalid auth level, "
1970                                   "failed to process packet auth.\n"));
1971                         return false;
1972                 }
1973                 break;
1974
1975         case PIPE_AUTH_TYPE_SCHANNEL:
1976
1977                 DEBUG(10, ("SCHANNEL auth\n"));
1978
1979                 switch (p->auth.auth_level) {
1980                 case DCERPC_AUTH_LEVEL_PRIVACY:
1981                         status = netsec_incoming_packet(
1982                                         p->auth.a_u.schannel_auth,
1983                                         pkt, true,
1984                                         data.data, data.length,
1985                                         &auth.credentials);
1986                         if (!NT_STATUS_IS_OK(status)) {
1987                                 return false;
1988                         }
1989                         memcpy(pkt->u.request.stub_and_verifier.data,
1990                                 data.data, data.length);
1991                         break;
1992
1993                 case DCERPC_AUTH_LEVEL_INTEGRITY:
1994                         status = netsec_incoming_packet(
1995                                         p->auth.a_u.schannel_auth,
1996                                         pkt, false,
1997                                         data.data, data.length,
1998                                         &auth.credentials);
1999                         if (!NT_STATUS_IS_OK(status)) {
2000                                 return false;
2001                         }
2002                         break;
2003
2004                 default:
2005                         DEBUG(0, ("Invalid auth level, "
2006                                   "failed to process packet auth.\n"));
2007                         return false;
2008                 }
2009                 break;
2010
2011         default:
2012                 DEBUG(0, ("process_request_pdu: "
2013                           "unknown auth type %u set.\n",
2014                           (unsigned int)p->auth.auth_type));
2015                 set_incoming_fault(p);
2016                 return false;
2017         }
2018
2019         /* remove the indicated amount of padding */
2020         if (pkt->u.request.stub_and_verifier.length < auth.auth_pad_length) {
2021                 return false;
2022         }
2023         pkt->u.request.stub_and_verifier.length -= auth.auth_pad_length;
2024
2025         return true;
2026 }
2027
2028 /****************************************************************************
2029  Processes a request pdu. This will do auth processing if needed, and
2030  appends the data into the complete stream if the LAST flag is not set.
2031 ****************************************************************************/
2032
2033 static bool process_request_pdu(pipes_struct *p, struct ncacn_packet *pkt)
2034 {
2035         DATA_BLOB data;
2036
2037         if (!p->pipe_bound) {
2038                 DEBUG(0,("process_request_pdu: rpc request with no bind.\n"));
2039                 set_incoming_fault(p);
2040                 return False;
2041         }
2042
2043         /* Store the opnum */
2044         p->opnum = pkt->u.request.opnum;
2045
2046         if (!dcesrv_auth_request(p, pkt)) {
2047                 DEBUG(0,("Failed to check packet auth.\n"));
2048                 set_incoming_fault(p);
2049                 return false;
2050         }
2051
2052         data = pkt->u.request.stub_and_verifier;
2053
2054         /*
2055          * Check the data length doesn't go over the 15Mb limit.
2056          * increased after observing a bug in the Windows NT 4.0 SP6a
2057          * spoolsv.exe when the response to a GETPRINTERDRIVER2 RPC
2058          * will not fit in the initial buffer of size 0x1068   --jerry 22/01/2002
2059          */
2060
2061         if (p->in_data.data.length + data.length > MAX_RPC_DATA_SIZE) {
2062                 DEBUG(0, ("process_request_pdu: "
2063                           "rpc data buffer too large (%u) + (%u)\n",
2064                           (unsigned int)p->in_data.data.length,
2065                           (unsigned int)data.length));
2066                 set_incoming_fault(p);
2067                 return False;
2068         }
2069
2070         /*
2071          * Append the data portion into the buffer and return.
2072          */
2073
2074         if (data.length) {
2075                 if (!data_blob_append(p->mem_ctx, &p->in_data.data,
2076                                           data.data, data.length)) {
2077                         DEBUG(0, ("Unable to append data size %u "
2078                                   "to parse buffer of size %u.\n",
2079                                   (unsigned int)data.length,
2080                                   (unsigned int)p->in_data.data.length));
2081                         set_incoming_fault(p);
2082                         return False;
2083                 }
2084         }
2085
2086         if (pkt->pfc_flags & DCERPC_PFC_FLAG_LAST) {
2087                 bool ret = False;
2088                 /*
2089                  * Ok - we finally have a complete RPC stream.
2090                  * Call the rpc command to process it.
2091                  */
2092
2093                 /*
2094                  * Process the complete data stream here.
2095                  */
2096                 if (pipe_init_outgoing_data(p)) {
2097                         ret = api_pipe_request(p, pkt);
2098                 }
2099
2100                 return ret;
2101         }
2102
2103         return True;
2104 }
2105
2106 /****************************************************************************
2107  Processes a finished PDU stored in p->in_data.pdu.
2108 ****************************************************************************/
2109
2110 void process_complete_pdu(pipes_struct *p)
2111 {
2112         struct ncacn_packet *pkt = NULL;
2113         NTSTATUS status;
2114         bool reply = False;
2115
2116         if(p->fault_state) {
2117                 DEBUG(10,("process_complete_pdu: pipe %s in fault state.\n",
2118                           get_pipe_name_from_syntax(talloc_tos(), &p->syntax)));
2119                 goto done;
2120         }
2121
2122         pkt = talloc(p->mem_ctx, struct ncacn_packet);
2123         if (!pkt) {
2124                 DEBUG(0, ("Out of memory!\n"));
2125                 goto done;
2126         }
2127
2128         /*
2129          * Ensure we're using the corrent endianness for both the
2130          * RPC header flags and the raw data we will be reading from.
2131          */
2132         if (dcerpc_get_endian_flag(&p->in_data.pdu) & DCERPC_DREP_LE) {
2133                 p->endian = RPC_LITTLE_ENDIAN;
2134         } else {
2135                 p->endian = RPC_BIG_ENDIAN;
2136         }
2137         DEBUG(10, ("PDU is in %s Endian format!\n", p->endian?"Big":"Little"));
2138
2139         status = dcerpc_pull_ncacn_packet(pkt, &p->in_data.pdu,
2140                                           pkt, p->endian);
2141         if (!NT_STATUS_IS_OK(status)) {
2142                 DEBUG(0, ("Failed to unmarshal rpc packet: %s!\n",
2143                           nt_errstr(status)));
2144                 goto done;
2145         }
2146
2147         /* Store the call_id */
2148         p->call_id = pkt->call_id;
2149
2150         DEBUG(10, ("Processing packet type %d\n", (int)pkt->ptype));
2151
2152         switch (pkt->ptype) {
2153         case DCERPC_PKT_REQUEST:
2154                 reply = process_request_pdu(p, pkt);
2155                 break;
2156
2157         case DCERPC_PKT_PING: /* CL request - ignore... */
2158                 DEBUG(0, ("process_complete_pdu: Error. "
2159                           "Connectionless packet type %d received on "
2160                           "pipe %s.\n", (int)pkt->ptype,
2161                          get_pipe_name_from_syntax(talloc_tos(),
2162                                                    &p->syntax)));
2163                 break;
2164
2165         case DCERPC_PKT_RESPONSE: /* No responses here. */
2166                 DEBUG(0, ("process_complete_pdu: Error. "
2167                           "DCERPC_PKT_RESPONSE received from client "
2168                           "on pipe %s.\n",
2169                          get_pipe_name_from_syntax(talloc_tos(),
2170                                                    &p->syntax)));
2171                 break;
2172
2173         case DCERPC_PKT_FAULT:
2174         case DCERPC_PKT_WORKING:
2175                 /* CL request - reply to a ping when a call in process. */
2176         case DCERPC_PKT_NOCALL:
2177                 /* CL - server reply to a ping call. */
2178         case DCERPC_PKT_REJECT:
2179         case DCERPC_PKT_ACK:
2180         case DCERPC_PKT_CL_CANCEL:
2181         case DCERPC_PKT_FACK:
2182         case DCERPC_PKT_CANCEL_ACK:
2183                 DEBUG(0, ("process_complete_pdu: Error. "
2184                           "Connectionless packet type %u received on "
2185                           "pipe %s.\n", (unsigned int)pkt->ptype,
2186                          get_pipe_name_from_syntax(talloc_tos(),
2187                                                    &p->syntax)));
2188                 break;
2189
2190         case DCERPC_PKT_BIND:
2191                 /*
2192                  * We assume that a pipe bind is only in one pdu.
2193                  */
2194                 if (pipe_init_outgoing_data(p)) {
2195                         reply = api_pipe_bind_req(p, pkt);
2196                 }
2197                 break;
2198
2199         case DCERPC_PKT_BIND_ACK:
2200         case DCERPC_PKT_BIND_NAK:
2201                 DEBUG(0, ("process_complete_pdu: Error. "
2202                           "DCERPC_PKT_BINDACK/DCERPC_PKT_BINDNACK "
2203                           "packet type %u received on pipe %s.\n",
2204                           (unsigned int)pkt->ptype,
2205                          get_pipe_name_from_syntax(talloc_tos(),
2206                                                    &p->syntax)));
2207                 break;
2208
2209
2210         case DCERPC_PKT_ALTER:
2211                 /*
2212                  * We assume that a pipe bind is only in one pdu.
2213                  */
2214                 if (pipe_init_outgoing_data(p)) {
2215                         reply = api_pipe_alter_context(p, pkt);
2216                 }
2217                 break;
2218
2219         case DCERPC_PKT_ALTER_RESP:
2220                 DEBUG(0, ("process_complete_pdu: Error. "
2221                           "DCERPC_PKT_ALTER_RESP on pipe %s: "
2222                           "Should only be server -> client.\n",
2223                          get_pipe_name_from_syntax(talloc_tos(),
2224                                                    &p->syntax)));
2225                 break;
2226
2227         case DCERPC_PKT_AUTH3:
2228                 /*
2229                  * The third packet in an NTLMSSP auth exchange.
2230                  */
2231                 if (pipe_init_outgoing_data(p)) {
2232                         reply = api_pipe_bind_auth3(p, pkt);
2233                 }
2234                 break;
2235
2236         case DCERPC_PKT_SHUTDOWN:
2237                 DEBUG(0, ("process_complete_pdu: Error. "
2238                           "DCERPC_PKT_SHUTDOWN on pipe %s: "
2239                           "Should only be server -> client.\n",
2240                          get_pipe_name_from_syntax(talloc_tos(),
2241                                                    &p->syntax)));
2242                 break;
2243
2244         case DCERPC_PKT_CO_CANCEL:
2245                 /* For now just free all client data and continue
2246                  * processing. */
2247                 DEBUG(3,("process_complete_pdu: DCERPC_PKT_CO_CANCEL."
2248                          " Abandoning rpc call.\n"));
2249                 /* As we never do asynchronous RPC serving, we can
2250                  * never cancel a call (as far as I know).
2251                  * If we ever did we'd have to send a cancel_ack reply.
2252                  * For now, just free all client data and continue
2253                  * processing. */
2254                 reply = True;
2255                 break;
2256
2257 #if 0
2258                 /* Enable this if we're doing async rpc. */
2259                 /* We must check the outstanding callid matches. */
2260                 if (pipe_init_outgoing_data(p)) {
2261                         /* Send a cancel_ack PDU reply. */
2262                         /* We should probably check the auth-verifier here. */
2263                         reply = setup_cancel_ack_reply(p, pkt);
2264                 }
2265                 break;
2266 #endif
2267
2268         case DCERPC_PKT_ORPHANED:
2269                 /* We should probably check the auth-verifier here.
2270                  * For now just free all client data and continue
2271                  * processing. */
2272                 DEBUG(3, ("process_complete_pdu: DCERPC_PKT_ORPHANED."
2273                           " Abandoning rpc call.\n"));
2274                 reply = True;
2275                 break;
2276
2277         default:
2278                 DEBUG(0, ("process_complete_pdu: "
2279                           "Unknown rpc type = %u received.\n",
2280                           (unsigned int)pkt->ptype));
2281                 break;
2282         }
2283
2284 done:
2285         if (!reply) {
2286                 DEBUG(3,("process_complete_pdu: DCE/RPC fault sent on "
2287                          "pipe %s\n", get_pipe_name_from_syntax(talloc_tos(),
2288                                                                 &p->syntax)));
2289                 set_incoming_fault(p);
2290                 setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR));
2291                 TALLOC_FREE(pkt);
2292         } else {
2293                 /*
2294                  * Reset the lengths. We're ready for a new pdu.
2295                  */
2296                 TALLOC_FREE(p->in_data.pdu.data);
2297                 p->in_data.pdu_needed_len = 0;
2298                 p->in_data.pdu.length = 0;
2299         }
2300
2301         TALLOC_FREE(pkt);
2302 }
2303