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