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