s4:rpc_server: make it possible to specify ncacn_np_secondary_endpoint
[gd/samba-autobuild/.git] / source4 / rpc_server / dcerpc_server.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    server side dcerpc core code
5
6    Copyright (C) Andrew Tridgell 2003-2005
7    Copyright (C) Stefan (metze) Metzmacher 2004-2005
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "auth/auth.h"
25 #include "auth/gensec/gensec.h"
26 #include "../lib/util/dlinklist.h"
27 #include "rpc_server/dcerpc_server.h"
28 #include "rpc_server/dcerpc_server_proto.h"
29 #include "rpc_server/common/proto.h"
30 #include "librpc/rpc/dcerpc_proto.h"
31 #include "system/filesys.h"
32 #include "libcli/security/security.h"
33 #include "param/param.h"
34 #include "../lib/tsocket/tsocket.h"
35 #include "../libcli/named_pipe_auth/npa_tstream.h"
36 #include "smbd/service_stream.h"
37 #include "../lib/tsocket/tsocket.h"
38 #include "lib/socket/socket.h"
39 #include "smbd/process_model.h"
40 #include "lib/messaging/irpc.h"
41 #include "librpc/rpc/rpc_common.h"
42 #include "lib/util/samba_modules.h"
43 #include "librpc/gen_ndr/ndr_dcerpc.h"
44 #include "../lib/util/tevent_ntstatus.h"
45
46 static NTSTATUS dcesrv_negotiate_contexts(struct dcesrv_call_state *call,
47                                 const struct dcerpc_bind *b,
48                                 struct dcerpc_ack_ctx *ack_ctx_list);
49
50 /*
51   find an association group given a assoc_group_id
52  */
53 static struct dcesrv_assoc_group *dcesrv_assoc_group_find(struct dcesrv_context *dce_ctx,
54                                                           uint32_t id)
55 {
56         void *id_ptr;
57
58         id_ptr = idr_find(dce_ctx->assoc_groups_idr, id);
59         if (id_ptr == NULL) {
60                 return NULL;
61         }
62         return talloc_get_type_abort(id_ptr, struct dcesrv_assoc_group);
63 }
64
65 /*
66   take a reference to an existing association group
67  */
68 static struct dcesrv_assoc_group *dcesrv_assoc_group_reference(struct dcesrv_connection *conn,
69                                                                uint32_t id)
70 {
71         const struct dcesrv_endpoint *endpoint = conn->endpoint;
72         enum dcerpc_transport_t transport =
73                 dcerpc_binding_get_transport(endpoint->ep_description);
74         struct dcesrv_assoc_group *assoc_group;
75
76         assoc_group = dcesrv_assoc_group_find(conn->dce_ctx, id);
77         if (assoc_group == NULL) {
78                 DBG_NOTICE("Failed to find assoc_group 0x%08x\n", id);
79                 return NULL;
80         }
81         if (assoc_group->transport != transport) {
82                 const char *at =
83                         derpc_transport_string_by_transport(
84                                 assoc_group->transport);
85                 const char *ct =
86                         derpc_transport_string_by_transport(
87                                 transport);
88
89                 DBG_NOTICE("assoc_group 0x%08x (transport %s) "
90                            "is not available on transport %s",
91                            id, at, ct);
92                 return NULL;
93         }
94
95         return talloc_reference(conn, assoc_group);
96 }
97
98 static int dcesrv_assoc_group_destructor(struct dcesrv_assoc_group *assoc_group)
99 {
100         int ret;
101         ret = idr_remove(assoc_group->dce_ctx->assoc_groups_idr, assoc_group->id);
102         if (ret != 0) {
103                 DEBUG(0,(__location__ ": Failed to remove assoc_group 0x%08x\n",
104                          assoc_group->id));
105         }
106         return 0;
107 }
108
109 /*
110   allocate a new association group
111  */
112 static struct dcesrv_assoc_group *dcesrv_assoc_group_new(struct dcesrv_connection *conn)
113 {
114         struct dcesrv_context *dce_ctx = conn->dce_ctx;
115         const struct dcesrv_endpoint *endpoint = conn->endpoint;
116         enum dcerpc_transport_t transport =
117                 dcerpc_binding_get_transport(endpoint->ep_description);
118         struct dcesrv_assoc_group *assoc_group;
119         int id;
120
121         assoc_group = talloc_zero(conn, struct dcesrv_assoc_group);
122         if (assoc_group == NULL) {
123                 return NULL;
124         }
125         
126         id = idr_get_new_random(dce_ctx->assoc_groups_idr, assoc_group, UINT16_MAX);
127         if (id == -1) {
128                 talloc_free(assoc_group);
129                 DEBUG(0,(__location__ ": Out of association groups!\n"));
130                 return NULL;
131         }
132
133         assoc_group->transport = transport;
134         assoc_group->id = id;
135         assoc_group->dce_ctx = dce_ctx;
136
137         talloc_set_destructor(assoc_group, dcesrv_assoc_group_destructor);
138
139         return assoc_group;
140 }
141
142
143 /*
144   see if two endpoints match
145 */
146 static bool endpoints_match(const struct dcerpc_binding *ep1,
147                             const struct dcerpc_binding *ep2)
148 {
149         enum dcerpc_transport_t t1;
150         enum dcerpc_transport_t t2;
151         const char *e1;
152         const char *e2;
153
154         t1 = dcerpc_binding_get_transport(ep1);
155         t2 = dcerpc_binding_get_transport(ep2);
156
157         e1 = dcerpc_binding_get_string_option(ep1, "endpoint");
158         e2 = dcerpc_binding_get_string_option(ep2, "endpoint");
159
160         if (t1 != t2) {
161                 return false;
162         }
163
164         if (!e1 || !e2) {
165                 return e1 == e2;
166         }
167
168         if (strcasecmp(e1, e2) != 0) {
169                 return false;
170         }
171
172         return true;
173 }
174
175 /*
176   find an endpoint in the dcesrv_context
177 */
178 static struct dcesrv_endpoint *find_endpoint(struct dcesrv_context *dce_ctx,
179                                              const struct dcerpc_binding *ep_description)
180 {
181         struct dcesrv_endpoint *ep;
182         for (ep=dce_ctx->endpoint_list; ep; ep=ep->next) {
183                 if (endpoints_match(ep->ep_description, ep_description)) {
184                         return ep;
185                 }
186         }
187         return NULL;
188 }
189
190 /*
191   find a registered context_id from a bind or alter_context
192 */
193 static struct dcesrv_connection_context *dcesrv_find_context(struct dcesrv_connection *conn, 
194                                                              uint16_t context_id)
195 {
196         struct dcesrv_connection_context *c;
197         for (c=conn->contexts;c;c=c->next) {
198                 if (c->context_id == context_id) return c;
199         }
200         return NULL;
201 }
202
203 /*
204   see if a uuid and if_version match to an interface
205 */
206 static bool interface_match(const struct dcesrv_interface *if1,
207                                                         const struct dcesrv_interface *if2)
208 {
209         return (if1->syntax_id.if_version == if2->syntax_id.if_version && 
210                         GUID_equal(&if1->syntax_id.uuid, &if2->syntax_id.uuid));
211 }
212
213 /*
214   find the interface operations on any endpoint with this binding
215 */
216 static const struct dcesrv_interface *find_interface_by_binding(struct dcesrv_context *dce_ctx,
217                                                                 struct dcerpc_binding *binding,
218                                                                 const struct dcesrv_interface *iface)
219 {
220         struct dcesrv_endpoint *ep;
221         for (ep=dce_ctx->endpoint_list; ep; ep=ep->next) {
222                 if (endpoints_match(ep->ep_description, binding)) {
223                         struct dcesrv_if_list *ifl;
224                         for (ifl=ep->interface_list; ifl; ifl=ifl->next) {
225                                 if (interface_match(&(ifl->iface), iface)) {
226                                         return &(ifl->iface);
227                                 }
228                         }
229                 }
230         }
231         return NULL;
232 }
233
234 /*
235   see if a uuid and if_version match to an interface
236 */
237 static bool interface_match_by_uuid(const struct dcesrv_interface *iface,
238                                     const struct GUID *uuid, uint32_t if_version)
239 {
240         return (iface->syntax_id.if_version == if_version && 
241                         GUID_equal(&iface->syntax_id.uuid, uuid));
242 }
243
244 /*
245   find the interface operations on an endpoint by uuid
246 */
247 const struct dcesrv_interface *find_interface_by_uuid(const struct dcesrv_endpoint *endpoint,
248                                                       const struct GUID *uuid, uint32_t if_version)
249 {
250         struct dcesrv_if_list *ifl;
251         for (ifl=endpoint->interface_list; ifl; ifl=ifl->next) {
252                 if (interface_match_by_uuid(&(ifl->iface), uuid, if_version)) {
253                         return &(ifl->iface);
254                 }
255         }
256         return NULL;
257 }
258
259 /*
260   find the earlier parts of a fragmented call awaiting reassembily
261 */
262 static struct dcesrv_call_state *dcesrv_find_fragmented_call(struct dcesrv_connection *dce_conn, uint32_t call_id)
263 {
264         struct dcesrv_call_state *c;
265         for (c=dce_conn->incoming_fragmented_call_list;c;c=c->next) {
266                 if (c->pkt.call_id == call_id) {
267                         return c;
268                 }
269         }
270         return NULL;
271 }
272
273 /*
274   register an interface on an endpoint
275
276   An endpoint is one unix domain socket (for ncalrpc), one TCP port
277   (for ncacn_ip_tcp) or one (forwarded) named pipe (for ncacn_np).
278
279   Each endpoint can have many interfaces such as netlogon, lsa or
280   samr.  Some have essentially the full set.
281
282   This is driven from the set of interfaces listed in each IDL file
283   via the PIDL generated *__op_init_server() functions.
284 */
285 _PUBLIC_ NTSTATUS dcesrv_interface_register(struct dcesrv_context *dce_ctx,
286                                    const char *ep_name,
287                                    const char *ncacn_np_secondary_endpoint,
288                                    const struct dcesrv_interface *iface,
289                                    const struct security_descriptor *sd)
290 {
291         struct dcesrv_endpoint *ep;
292         struct dcesrv_if_list *ifl;
293         struct dcerpc_binding *binding;
294         struct dcerpc_binding *binding2 = NULL;
295         bool add_ep = false;
296         NTSTATUS status;
297         enum dcerpc_transport_t transport;
298         char *ep_string = NULL;
299         bool use_single_process = true;
300         const char *ep_process_string;
301
302         /*
303          * If we are not using handles, there is no need for force
304          * this service into using a single process.
305          *
306          * However, due to the way we listen for RPC packets, we can
307          * only do this if we have a single service per pipe or TCP
308          * port, so we still force a single combined process for
309          * ncalrpc.
310          */
311         if (iface->flags & DCESRV_INTERFACE_FLAGS_HANDLES_NOT_USED) {
312                 use_single_process = false;
313         }
314
315         status = dcerpc_parse_binding(dce_ctx, ep_name, &binding);
316
317         if (NT_STATUS_IS_ERR(status)) {
318                 DEBUG(0, ("Trouble parsing binding string '%s'\n", ep_name));
319                 return status;
320         }
321
322         transport = dcerpc_binding_get_transport(binding);
323         if (transport == NCACN_IP_TCP) {
324                 int port;
325                 char port_str[6];
326
327                 /* 
328                  * First check if there is already a port specified, eg
329                  * for epmapper on ncacn_ip_tcp:[135]
330                  */
331                 const char *endpoint
332                         = dcerpc_binding_get_string_option(binding,
333                                                            "endpoint");
334                 if (endpoint == NULL) {
335                         port = lpcfg_parm_int(dce_ctx->lp_ctx, NULL,
336                                               "rpc server port", iface->name, 0);
337                         
338                         /*
339                          * For RPC services that are not set to use a single
340                          * process, we do not default to using the 'rpc server
341                          * port' because that would cause a double-bind on
342                          * that port.
343                          */
344                         if (port == 0 && !use_single_process) {
345                                 port = lpcfg_rpc_server_port(dce_ctx->lp_ctx);
346                         }
347                         if (port != 0) {
348                                 snprintf(port_str, sizeof(port_str), "%u", port);
349                                 status = dcerpc_binding_set_string_option(binding,
350                                                                           "endpoint",
351                                                                           port_str);
352                                 if (!NT_STATUS_IS_OK(status)) {
353                                         return status;
354                                 }
355                         }
356                 }
357         }
358
359         if (transport == NCACN_NP && ncacn_np_secondary_endpoint != NULL) {
360                 enum dcerpc_transport_t transport2;
361
362                 status = dcerpc_parse_binding(dce_ctx,
363                                               ncacn_np_secondary_endpoint,
364                                               &binding2);
365                 if (!NT_STATUS_IS_OK(status)) {
366                         DEBUG(0, ("Trouble parsing 2nd binding string '%s'\n",
367                                   ncacn_np_secondary_endpoint));
368                         return status;
369                 }
370
371                 transport2 = dcerpc_binding_get_transport(binding2);
372                 SMB_ASSERT(transport2 == transport);
373         }
374
375         /* see if the interface is already registered on the endpoint */
376         if (find_interface_by_binding(dce_ctx, binding, iface)!=NULL) {
377                 DEBUG(0,("dcesrv_interface_register: interface '%s' already registered on endpoint '%s'\n",
378                          iface->name, ep_name));
379                 return NT_STATUS_OBJECT_NAME_COLLISION;
380         }
381
382         /* check if this endpoint exists
383          */
384         ep = find_endpoint(dce_ctx, binding);
385
386         if (ep != NULL) {
387                 /*
388                  * We want a new port on ncacn_ip_tcp for NETLOGON, so
389                  * it can be multi-process.  Other processes can also
390                  * listen on distinct ports, if they have one forced
391                  * in the code above with eg 'rpc server port:drsuapi = 1027'
392                  *
393                  * If we have mulitiple endpoints on port 0, they each
394                  * get an epemeral port (currently by walking up from
395                  * 1024).
396                  *
397                  * Because one endpoint can only have one process
398                  * model, we add a new IP_TCP endpoint for each model.
399                  *
400                  * This works in conjunction with the forced overwrite
401                  * of ep->use_single_process below.
402                  */
403                 if (ep->use_single_process != use_single_process
404                     && transport == NCACN_IP_TCP) {
405                         add_ep = true;
406                 }
407         }
408
409         if (ep == NULL || add_ep) {
410                 ep = talloc_zero(dce_ctx, struct dcesrv_endpoint);
411                 if (!ep) {
412                         return NT_STATUS_NO_MEMORY;
413                 }
414                 ZERO_STRUCTP(ep);
415                 ep->ep_description = talloc_move(ep, &binding);
416                 ep->ep_2nd_description = talloc_move(ep, &binding2);
417                 add_ep = true;
418
419                 /* add mgmt interface */
420                 ifl = talloc_zero(ep, struct dcesrv_if_list);
421                 if (!ifl) {
422                         return NT_STATUS_NO_MEMORY;
423                 }
424
425                 ifl->iface = dcesrv_get_mgmt_interface();
426
427                 DLIST_ADD(ep->interface_list, ifl);
428         }
429
430         /*
431          * By default don't force into a single process, but if any
432          * interface on this endpoint on this service uses handles
433          * (most do), then we must force into single process mode
434          *
435          * By overwriting this each time a new interface is added to
436          * this endpoint, we end up with the most restrictive setting.
437          */
438         if (use_single_process) {
439                 ep->use_single_process = true;
440         }
441
442         /* talloc a new interface list element */
443         ifl = talloc_zero(ep, struct dcesrv_if_list);
444         if (!ifl) {
445                 return NT_STATUS_NO_MEMORY;
446         }
447
448         /* copy the given interface struct to the one on the endpoints interface list */
449         memcpy(&(ifl->iface),iface, sizeof(struct dcesrv_interface));
450
451         /* if we have a security descriptor given,
452          * we should see if we can set it up on the endpoint
453          */
454         if (sd != NULL) {
455                 /* if there's currently no security descriptor given on the endpoint
456                  * we try to set it
457                  */
458                 if (ep->sd == NULL) {
459                         ep->sd = security_descriptor_copy(ep, sd);
460                 }
461
462                 /* if now there's no security descriptor given on the endpoint
463                  * something goes wrong, either we failed to copy the security descriptor
464                  * or there was already one on the endpoint
465                  */
466                 if (ep->sd != NULL) {
467                         DEBUG(0,("dcesrv_interface_register: interface '%s' failed to setup a security descriptor\n"
468                                  "                           on endpoint '%s'\n",
469                                 iface->name, ep_name));
470                         if (add_ep) free(ep);
471                         free(ifl);
472                         return NT_STATUS_OBJECT_NAME_COLLISION;
473                 }
474         }
475
476         /* finally add the interface on the endpoint */
477         DLIST_ADD(ep->interface_list, ifl);
478
479         /* if it's a new endpoint add it to the dcesrv_context */
480         if (add_ep) {
481                 DLIST_ADD(dce_ctx->endpoint_list, ep);
482         }
483
484         /* Re-get the string as we may have set a port */
485         ep_string = dcerpc_binding_string(dce_ctx, ep->ep_description);
486
487         if (use_single_process) {
488                 ep_process_string = "single process required";
489         } else {
490                 ep_process_string = "multi process compatible";
491         }
492
493         DBG_INFO("dcesrv_interface_register: interface '%s' "
494                  "registered on endpoint '%s' (%s)\n",
495                  iface->name, ep_string, ep_process_string);
496         TALLOC_FREE(ep_string);
497
498         return NT_STATUS_OK;
499 }
500
501 static NTSTATUS dcesrv_session_info_session_key(struct dcesrv_auth *auth,
502                                                 DATA_BLOB *session_key)
503 {
504         if (auth->session_info == NULL) {
505                 return NT_STATUS_NO_USER_SESSION_KEY;
506         }
507
508         if (auth->session_info->session_key.length == 0) {
509                 return NT_STATUS_NO_USER_SESSION_KEY;
510         }
511
512         *session_key = auth->session_info->session_key;
513         return NT_STATUS_OK;
514 }
515
516 static NTSTATUS dcesrv_remote_session_key(struct dcesrv_auth *auth,
517                                           DATA_BLOB *session_key)
518 {
519         if (auth->auth_type != DCERPC_AUTH_TYPE_NONE) {
520                 return NT_STATUS_NO_USER_SESSION_KEY;
521         }
522
523         return dcesrv_session_info_session_key(auth, session_key);
524 }
525
526 static NTSTATUS dcesrv_local_fixed_session_key(struct dcesrv_auth *auth,
527                                                DATA_BLOB *session_key)
528 {
529         return dcerpc_generic_session_key(NULL, session_key);
530 }
531
532 /*
533  * Fetch the authentication session key if available.
534  *
535  * This is the key generated by a gensec authentication.
536  *
537  */
538 _PUBLIC_ NTSTATUS dcesrv_auth_session_key(struct dcesrv_call_state *call,
539                                           DATA_BLOB *session_key)
540 {
541         struct dcesrv_auth *auth = call->auth_state;
542         SMB_ASSERT(auth->auth_finished);
543         return dcesrv_session_info_session_key(auth, session_key);
544 }
545
546 /*
547  * Fetch the transport session key if available.
548  * Typically this is the SMB session key
549  * or a fixed key for local transports.
550  *
551  * The key is always truncated to 16 bytes.
552 */
553 _PUBLIC_ NTSTATUS dcesrv_transport_session_key(struct dcesrv_call_state *call,
554                                                DATA_BLOB *session_key)
555 {
556         struct dcesrv_auth *auth = call->auth_state;
557         NTSTATUS status;
558
559         SMB_ASSERT(auth->auth_finished);
560
561         if (auth->session_key_fn == NULL) {
562                 return NT_STATUS_NO_USER_SESSION_KEY;
563         }
564
565         status = auth->session_key_fn(auth, session_key);
566         if (!NT_STATUS_IS_OK(status)) {
567                 return status;
568         }
569
570         session_key->length = MIN(session_key->length, 16);
571
572         return NT_STATUS_OK;
573 }
574
575 static struct dcesrv_auth *dcesrv_auth_create(struct dcesrv_connection *conn)
576 {
577         const struct dcesrv_endpoint *ep = conn->endpoint;
578         enum dcerpc_transport_t transport =
579                 dcerpc_binding_get_transport(ep->ep_description);
580         struct dcesrv_auth *auth = NULL;
581
582         auth = talloc_zero(conn, struct dcesrv_auth);
583         if (auth == NULL) {
584                 return NULL;
585         }
586
587         switch (transport) {
588         case NCACN_NP:
589                 auth->session_key_fn = dcesrv_remote_session_key;
590                 break;
591         case NCALRPC:
592         case NCACN_UNIX_STREAM:
593                 auth->session_key_fn = dcesrv_local_fixed_session_key;
594                 break;
595         default:
596                 /*
597                  * All other's get a NULL pointer, which
598                  * results in NT_STATUS_NO_USER_SESSION_KEY
599                  */
600                 break;
601         }
602
603         return auth;
604 }
605
606 /*
607   connect to a dcerpc endpoint
608 */
609 static NTSTATUS dcesrv_endpoint_connect(struct dcesrv_context *dce_ctx,
610                                  TALLOC_CTX *mem_ctx,
611                                  const struct dcesrv_endpoint *ep,
612                                  struct auth_session_info *session_info,
613                                  struct tevent_context *event_ctx,
614                                  struct imessaging_context *msg_ctx,
615                                  struct server_id server_id,
616                                  uint32_t state_flags,
617                                  struct dcesrv_connection **_p)
618 {
619         struct dcesrv_auth *auth = NULL;
620         struct dcesrv_connection *p;
621
622         if (!session_info) {
623                 return NT_STATUS_ACCESS_DENIED;
624         }
625
626         p = talloc_zero(mem_ctx, struct dcesrv_connection);
627         NT_STATUS_HAVE_NO_MEMORY(p);
628
629         p->dce_ctx = dce_ctx;
630         p->endpoint = ep;
631         p->packet_log_dir = lpcfg_lock_directory(dce_ctx->lp_ctx);
632         p->event_ctx = event_ctx;
633         p->msg_ctx = msg_ctx;
634         p->server_id = server_id;
635         p->state_flags = state_flags;
636         p->allow_bind = true;
637         p->max_recv_frag = 5840;
638         p->max_xmit_frag = 5840;
639         p->max_total_request_size = DCERPC_NCACN_REQUEST_DEFAULT_MAX_SIZE;
640
641         p->support_hdr_signing = lpcfg_parm_bool(dce_ctx->lp_ctx,
642                                                  NULL,
643                                                  "dcesrv",
644                                                  "header signing",
645                                                  true);
646
647         auth = dcesrv_auth_create(p);
648         if (auth == NULL) {
649                 talloc_free(p);
650                 return NT_STATUS_NO_MEMORY;
651         }
652
653         auth->session_info = talloc_reference(auth, session_info);
654         if (auth->session_info == NULL) {
655                 talloc_free(p);
656                 return NT_STATUS_NO_MEMORY;
657         }
658
659         p->default_auth_state = auth;
660
661         /*
662          * For now we only support NDR32.
663          */
664         p->preferred_transfer = &ndr_transfer_syntax_ndr;
665
666         *_p = p;
667         return NT_STATUS_OK;
668 }
669
670 /*
671   move a call from an existing linked list to the specified list. This
672   prevents bugs where we forget to remove the call from a previous
673   list when moving it.
674  */
675 static void dcesrv_call_set_list(struct dcesrv_call_state *call, 
676                                  enum dcesrv_call_list list)
677 {
678         switch (call->list) {
679         case DCESRV_LIST_NONE:
680                 break;
681         case DCESRV_LIST_CALL_LIST:
682                 DLIST_REMOVE(call->conn->call_list, call);
683                 break;
684         case DCESRV_LIST_FRAGMENTED_CALL_LIST:
685                 DLIST_REMOVE(call->conn->incoming_fragmented_call_list, call);
686                 break;
687         case DCESRV_LIST_PENDING_CALL_LIST:
688                 DLIST_REMOVE(call->conn->pending_call_list, call);
689                 break;
690         }
691         call->list = list;
692         switch (list) {
693         case DCESRV_LIST_NONE:
694                 break;
695         case DCESRV_LIST_CALL_LIST:
696                 DLIST_ADD_END(call->conn->call_list, call);
697                 break;
698         case DCESRV_LIST_FRAGMENTED_CALL_LIST:
699                 DLIST_ADD_END(call->conn->incoming_fragmented_call_list, call);
700                 break;
701         case DCESRV_LIST_PENDING_CALL_LIST:
702                 DLIST_ADD_END(call->conn->pending_call_list, call);
703                 break;
704         }
705 }
706
707 static void dcesrv_call_disconnect_after(struct dcesrv_call_state *call,
708                                          const char *reason)
709 {
710         if (call->conn->terminate != NULL) {
711                 return;
712         }
713
714         call->conn->allow_bind = false;
715         call->conn->allow_alter = false;
716
717         call->conn->default_auth_state->auth_invalid = true;
718
719         call->terminate_reason = talloc_strdup(call, reason);
720         if (call->terminate_reason == NULL) {
721                 call->terminate_reason = __location__;
722         }
723 }
724
725 /*
726   return a dcerpc bind_nak
727 */
728 static NTSTATUS dcesrv_bind_nak(struct dcesrv_call_state *call, uint32_t reason)
729 {
730         struct ncacn_packet pkt;
731         struct dcerpc_bind_nak_version version;
732         struct data_blob_list_item *rep;
733         NTSTATUS status;
734         static const uint8_t _pad[3] = { 0, };
735
736         /*
737          * We add the call to the pending_call_list
738          * in order to defer the termination.
739          */
740         dcesrv_call_disconnect_after(call, "dcesrv_bind_nak");
741
742         /* setup a bind_nak */
743         dcesrv_init_hdr(&pkt, lpcfg_rpc_big_endian(call->conn->dce_ctx->lp_ctx));
744         pkt.auth_length = 0;
745         pkt.call_id = call->pkt.call_id;
746         pkt.ptype = DCERPC_PKT_BIND_NAK;
747         pkt.pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST;
748         pkt.u.bind_nak.reject_reason = reason;
749         version.rpc_vers = 5;
750         version.rpc_vers_minor = 0;
751         pkt.u.bind_nak.num_versions = 1;
752         pkt.u.bind_nak.versions = &version;
753         pkt.u.bind_nak._pad = data_blob_const(_pad, sizeof(_pad));
754
755         rep = talloc_zero(call, struct data_blob_list_item);
756         if (!rep) {
757                 return NT_STATUS_NO_MEMORY;
758         }
759
760         status = ncacn_push_auth(&rep->blob, call, &pkt, NULL);
761         if (!NT_STATUS_IS_OK(status)) {
762                 return status;
763         }
764
765         dcerpc_set_frag_length(&rep->blob, rep->blob.length);
766
767         DLIST_ADD_END(call->replies, rep);
768         dcesrv_call_set_list(call, DCESRV_LIST_CALL_LIST);
769
770         if (call->conn->call_list && call->conn->call_list->replies) {
771                 if (call->conn->transport.report_output_data) {
772                         call->conn->transport.report_output_data(call->conn);
773                 }
774         }
775
776         return NT_STATUS_OK;    
777 }
778
779 static NTSTATUS dcesrv_fault_disconnect(struct dcesrv_call_state *call,
780                                  uint32_t fault_code)
781 {
782         /*
783          * We add the call to the pending_call_list
784          * in order to defer the termination.
785          */
786         dcesrv_call_disconnect_after(call, "dcesrv_fault_disconnect");
787
788         return dcesrv_fault_with_flags(call, fault_code,
789                                        DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
790 }
791
792 static int dcesrv_connection_context_destructor(struct dcesrv_connection_context *c)
793 {
794         DLIST_REMOVE(c->conn->contexts, c);
795
796         if (c->iface && c->iface->unbind) {
797                 c->iface->unbind(c, c->iface);
798                 c->iface = NULL;
799         }
800
801         return 0;
802 }
803
804 static void dcesrv_prepare_context_auth(struct dcesrv_call_state *dce_call)
805 {
806         struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
807         const struct dcesrv_endpoint *endpoint = dce_call->conn->endpoint;
808         enum dcerpc_transport_t transport =
809                 dcerpc_binding_get_transport(endpoint->ep_description);
810         struct dcesrv_connection_context *context = dce_call->context;
811         const struct dcesrv_interface *iface = context->iface;
812
813         context->min_auth_level = DCERPC_AUTH_LEVEL_NONE;
814
815         if (transport == NCALRPC) {
816                 context->allow_connect = true;
817                 return;
818         }
819
820         /*
821          * allow overwrite per interface
822          * allow dcerpc auth level connect:<interface>
823          */
824         context->allow_connect = lpcfg_allow_dcerpc_auth_level_connect(lp_ctx);
825         context->allow_connect = lpcfg_parm_bool(lp_ctx, NULL,
826                                         "allow dcerpc auth level connect",
827                                         iface->name,
828                                         context->allow_connect);
829 }
830
831 NTSTATUS dcesrv_interface_bind_require_integrity(struct dcesrv_connection_context *context,
832                                                  const struct dcesrv_interface *iface)
833 {
834         /*
835          * For connection oriented DCERPC DCERPC_AUTH_LEVEL_PACKET (4)
836          * has the same behavior as DCERPC_AUTH_LEVEL_INTEGRITY (5).
837          */
838         context->min_auth_level = DCERPC_AUTH_LEVEL_PACKET;
839         return NT_STATUS_OK;
840 }
841
842 NTSTATUS dcesrv_interface_bind_require_privacy(struct dcesrv_connection_context *context,
843                                                const struct dcesrv_interface *iface)
844 {
845         context->min_auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
846         return NT_STATUS_OK;
847 }
848
849 _PUBLIC_ NTSTATUS dcesrv_interface_bind_reject_connect(struct dcesrv_connection_context *context,
850                                                        const struct dcesrv_interface *iface)
851 {
852         struct loadparm_context *lp_ctx = context->conn->dce_ctx->lp_ctx;
853         const struct dcesrv_endpoint *endpoint = context->conn->endpoint;
854         enum dcerpc_transport_t transport =
855                 dcerpc_binding_get_transport(endpoint->ep_description);
856
857         if (transport == NCALRPC) {
858                 context->allow_connect = true;
859                 return NT_STATUS_OK;
860         }
861
862         /*
863          * allow overwrite per interface
864          * allow dcerpc auth level connect:<interface>
865          */
866         context->allow_connect = false;
867         context->allow_connect = lpcfg_parm_bool(lp_ctx, NULL,
868                                         "allow dcerpc auth level connect",
869                                         iface->name,
870                                         context->allow_connect);
871         return NT_STATUS_OK;
872 }
873
874 _PUBLIC_ NTSTATUS dcesrv_interface_bind_allow_connect(struct dcesrv_connection_context *context,
875                                                       const struct dcesrv_interface *iface)
876 {
877         struct loadparm_context *lp_ctx = context->conn->dce_ctx->lp_ctx;
878         const struct dcesrv_endpoint *endpoint = context->conn->endpoint;
879         enum dcerpc_transport_t transport =
880                 dcerpc_binding_get_transport(endpoint->ep_description);
881
882         if (transport == NCALRPC) {
883                 context->allow_connect = true;
884                 return NT_STATUS_OK;
885         }
886
887         /*
888          * allow overwrite per interface
889          * allow dcerpc auth level connect:<interface>
890          */
891         context->allow_connect = true;
892         context->allow_connect = lpcfg_parm_bool(lp_ctx, NULL,
893                                         "allow dcerpc auth level connect",
894                                         iface->name,
895                                         context->allow_connect);
896         return NT_STATUS_OK;
897 }
898
899 struct dcesrv_conn_auth_wait_context {
900         struct tevent_req *req;
901         bool done;
902         NTSTATUS status;
903 };
904
905 struct dcesrv_conn_auth_wait_state {
906         uint8_t dummy;
907 };
908
909 static struct tevent_req *dcesrv_conn_auth_wait_send(TALLOC_CTX *mem_ctx,
910                                                      struct tevent_context *ev,
911                                                      void *private_data)
912 {
913         struct dcesrv_conn_auth_wait_context *auth_wait =
914                 talloc_get_type_abort(private_data,
915                 struct dcesrv_conn_auth_wait_context);
916         struct tevent_req *req = NULL;
917         struct dcesrv_conn_auth_wait_state *state = NULL;
918
919         req = tevent_req_create(mem_ctx, &state,
920                                 struct dcesrv_conn_auth_wait_state);
921         if (req == NULL) {
922                 return NULL;
923         }
924         auth_wait->req = req;
925
926         tevent_req_defer_callback(req, ev);
927
928         if (!auth_wait->done) {
929                 return req;
930         }
931
932         if (tevent_req_nterror(req, auth_wait->status)) {
933                 return tevent_req_post(req, ev);
934         }
935
936         tevent_req_done(req);
937         return tevent_req_post(req, ev);
938 }
939
940 static NTSTATUS dcesrv_conn_auth_wait_recv(struct tevent_req *req)
941 {
942         return tevent_req_simple_recv_ntstatus(req);
943 }
944
945 static NTSTATUS dcesrv_conn_auth_wait_setup(struct dcesrv_connection *conn)
946 {
947         struct dcesrv_conn_auth_wait_context *auth_wait = NULL;
948
949         if (conn->wait_send != NULL) {
950                 return NT_STATUS_INTERNAL_ERROR;
951         }
952
953         auth_wait = talloc_zero(conn, struct dcesrv_conn_auth_wait_context);
954         if (auth_wait == NULL) {
955                 return NT_STATUS_NO_MEMORY;
956         }
957
958         conn->wait_private = auth_wait;
959         conn->wait_send = dcesrv_conn_auth_wait_send;
960         conn->wait_recv = dcesrv_conn_auth_wait_recv;
961         return NT_STATUS_OK;
962 }
963
964 static void dcesrv_conn_auth_wait_finished(struct dcesrv_connection *conn,
965                                            NTSTATUS status)
966 {
967         struct dcesrv_conn_auth_wait_context *auth_wait =
968                 talloc_get_type_abort(conn->wait_private,
969                 struct dcesrv_conn_auth_wait_context);
970
971         auth_wait->done = true;
972         auth_wait->status = status;
973
974         if (auth_wait->req == NULL) {
975                 return;
976         }
977
978         if (tevent_req_nterror(auth_wait->req, status)) {
979                 return;
980         }
981
982         tevent_req_done(auth_wait->req);
983 }
984
985 static NTSTATUS dcesrv_auth_reply(struct dcesrv_call_state *call);
986
987 static void dcesrv_bind_done(struct tevent_req *subreq);
988
989 /*
990   handle a bind request
991 */
992 static NTSTATUS dcesrv_bind(struct dcesrv_call_state *call)
993 {
994         struct dcesrv_connection *conn = call->conn;
995         struct ncacn_packet *pkt = &call->ack_pkt;
996         NTSTATUS status;
997         uint32_t extra_flags = 0;
998         uint16_t max_req = 0;
999         uint16_t max_rep = 0;
1000         struct dcerpc_binding *ep_2nd_description = NULL;
1001         const char *endpoint = NULL;
1002         struct dcesrv_auth *auth = call->auth_state;
1003         struct dcerpc_ack_ctx *ack_ctx_list = NULL;
1004         struct dcerpc_ack_ctx *ack_features = NULL;
1005         struct tevent_req *subreq = NULL;
1006         size_t i;
1007
1008         status = dcerpc_verify_ncacn_packet_header(&call->pkt,
1009                         DCERPC_PKT_BIND,
1010                         call->pkt.u.bind.auth_info.length,
1011                         0, /* required flags */
1012                         DCERPC_PFC_FLAG_FIRST |
1013                         DCERPC_PFC_FLAG_LAST |
1014                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1015                         0x08 | /* this is not defined, but should be ignored */
1016                         DCERPC_PFC_FLAG_CONC_MPX |
1017                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1018                         DCERPC_PFC_FLAG_MAYBE |
1019                         DCERPC_PFC_FLAG_OBJECT_UUID);
1020         if (!NT_STATUS_IS_OK(status)) {
1021                 return dcesrv_bind_nak(call,
1022                         DCERPC_BIND_NAK_REASON_PROTOCOL_VERSION_NOT_SUPPORTED);
1023         }
1024
1025         /* max_recv_frag and max_xmit_frag result always in the same value! */
1026         max_req = MIN(call->pkt.u.bind.max_xmit_frag,
1027                       call->pkt.u.bind.max_recv_frag);
1028         /*
1029          * The values are between 2048 and 5840 tested against Windows 2012R2
1030          * via ncacn_ip_tcp on port 135.
1031          */
1032         max_req = MAX(2048, max_req);
1033         max_rep = MIN(max_req, call->conn->max_recv_frag);
1034         /* They are truncated to an 8 byte boundary. */
1035         max_rep &= 0xFFF8;
1036
1037         /* max_recv_frag and max_xmit_frag result always in the same value! */
1038         call->conn->max_recv_frag = max_rep;
1039         call->conn->max_xmit_frag = max_rep;
1040
1041         /*
1042           if provided, check the assoc_group is valid
1043          */
1044         if (call->pkt.u.bind.assoc_group_id != 0) {
1045                 call->conn->assoc_group = dcesrv_assoc_group_reference(call->conn,
1046                                                                        call->pkt.u.bind.assoc_group_id);
1047         } else {
1048                 call->conn->assoc_group = dcesrv_assoc_group_new(call->conn);
1049         }
1050
1051         /*
1052          * The NETLOGON server does not use handles and so
1053          * there is no need to support association groups, but
1054          * we need to give back a number regardless.
1055          *
1056          * We have to do this when it is not run as a single process,
1057          * because then it can't see the other valid association
1058          * groups.  We handle this genericly for all endpoints not
1059          * running in single process mode.
1060          *
1061          * We know which endpoint we are on even before checking the
1062          * iface UUID, so for simplicity we enforce the same policy
1063          * for all interfaces on the endpoint.
1064          *
1065          * This means that where NETLOGON
1066          * shares an endpoint (such as ncalrpc or of 'lsa over
1067          * netlogon' is set) we will still check association groups.
1068          *
1069          */
1070
1071         if (call->conn->assoc_group == NULL &&
1072             !call->conn->endpoint->use_single_process) {
1073                 call->conn->assoc_group
1074                         = dcesrv_assoc_group_new(call->conn);
1075         }
1076         if (call->conn->assoc_group == NULL) {
1077                 return dcesrv_bind_nak(call, 0);
1078         }
1079
1080         if (call->pkt.u.bind.num_contexts < 1) {
1081                 return dcesrv_bind_nak(call, 0);
1082         }
1083
1084         ack_ctx_list = talloc_zero_array(call, struct dcerpc_ack_ctx,
1085                                          call->pkt.u.bind.num_contexts);
1086         if (ack_ctx_list == NULL) {
1087                 return dcesrv_bind_nak(call, 0);
1088         }
1089
1090         /*
1091          * Set some sane defaults (required by dcesrv_negotiate_contexts()/
1092          * dcesrv_check_or_create_context()) and do some protocol validation
1093          * and set sane defaults.
1094          */
1095         for (i = 0; i < call->pkt.u.bind.num_contexts; i++) {
1096                 const struct dcerpc_ctx_list *c = &call->pkt.u.bind.ctx_list[i];
1097                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1098                 bool is_feature = false;
1099                 uint64_t features = 0;
1100
1101                 if (c->num_transfer_syntaxes == 0) {
1102                         return dcesrv_bind_nak(call, 0);
1103                 }
1104
1105                 a->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1106                 a->reason.value = DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
1107
1108                 /*
1109                  * It's only treated as bind time feature request, if the first
1110                  * transfer_syntax matches, all others are ignored.
1111                  */
1112                 is_feature = dcerpc_extract_bind_time_features(c->transfer_syntaxes[0],
1113                                                                &features);
1114                 if (!is_feature) {
1115                         continue;
1116                 }
1117
1118                 if (ack_features != NULL) {
1119                         /*
1120                          * Only one bind time feature context is allowed.
1121                          */
1122                         return dcesrv_bind_nak(call, 0);
1123                 }
1124                 ack_features = a;
1125
1126                 a->result = DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK;
1127                 a->reason.negotiate = 0;
1128                 if (features & DCERPC_BIND_TIME_SECURITY_CONTEXT_MULTIPLEXING) {
1129                         /* not supported yet */
1130                 }
1131                 if (features & DCERPC_BIND_TIME_KEEP_CONNECTION_ON_ORPHAN) {
1132                         a->reason.negotiate |=
1133                                 DCERPC_BIND_TIME_KEEP_CONNECTION_ON_ORPHAN;
1134                 }
1135
1136                 call->conn->assoc_group->bind_time_features = a->reason.negotiate;
1137         }
1138
1139         /*
1140          * Try to negotiate one new presentation context.
1141          *
1142          * Deep in here we locate the iface (by uuid) that the client
1143          * requested, from the list of interfaces on the
1144          * call->conn->endpoint, and call iface->bind() on that iface.
1145          *
1146          * call->conn was set up at the accept() of the socket, and
1147          * call->conn->endpoint has a list of interfaces restricted to
1148          * this port or pipe.
1149          */
1150         status = dcesrv_negotiate_contexts(call, &call->pkt.u.bind, ack_ctx_list);
1151         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROTOCOL_ERROR)) {
1152                 return dcesrv_bind_nak(call, 0);
1153         }
1154         if (!NT_STATUS_IS_OK(status)) {
1155                 return status;
1156         }
1157
1158         /*
1159          * At this point we still don't know which interface (eg
1160          * netlogon, lsa, drsuapi) the caller requested in this bind!
1161          * The most recently added context is available as the first
1162          * element in the linked list at call->conn->contexts, that is
1163          * call->conn->contexts->iface, but they may not have
1164          * requested one at all!
1165          */
1166
1167         if ((call->pkt.pfc_flags & DCERPC_PFC_FLAG_CONC_MPX) &&
1168             (call->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
1169                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_MULTIPLEXED;
1170                 extra_flags |= DCERPC_PFC_FLAG_CONC_MPX;
1171         }
1172
1173         if (call->state_flags & DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL) {
1174                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL;
1175         }
1176
1177         /*
1178          * After finding the interface and setting up the NDR
1179          * transport negotiation etc, handle any authentication that
1180          * is being requested.
1181          */
1182         if (!dcesrv_auth_bind(call)) {
1183
1184                 if (auth->auth_level == DCERPC_AUTH_LEVEL_NONE) {
1185                         /*
1186                          * With DCERPC_AUTH_LEVEL_NONE, we get the
1187                          * reject_reason in auth->auth_context_id.
1188                          */
1189                         return dcesrv_bind_nak(call, auth->auth_context_id);
1190                 }
1191
1192                 /*
1193                  * This must a be a temporary failure e.g. talloc or invalid
1194                  * configuration, e.g. no machine account.
1195                  */
1196                 return dcesrv_bind_nak(call,
1197                                 DCERPC_BIND_NAK_REASON_TEMPORARY_CONGESTION);
1198         }
1199
1200         /* setup a bind_ack */
1201         dcesrv_init_hdr(pkt, lpcfg_rpc_big_endian(call->conn->dce_ctx->lp_ctx));
1202         pkt->auth_length = 0;
1203         pkt->call_id = call->pkt.call_id;
1204         pkt->ptype = DCERPC_PKT_BIND_ACK;
1205         pkt->pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST | extra_flags;
1206         pkt->u.bind_ack.max_xmit_frag = call->conn->max_xmit_frag;
1207         pkt->u.bind_ack.max_recv_frag = call->conn->max_recv_frag;
1208         pkt->u.bind_ack.assoc_group_id = call->conn->assoc_group->id;
1209
1210         ep_2nd_description = call->conn->endpoint->ep_2nd_description;
1211         if (ep_2nd_description == NULL) {
1212                 ep_2nd_description = call->conn->endpoint->ep_description;
1213         }
1214
1215         endpoint = dcerpc_binding_get_string_option(
1216                                 ep_2nd_description,
1217                                 "endpoint");
1218         if (endpoint == NULL) {
1219                 endpoint = "";
1220         }
1221
1222         pkt->u.bind_ack.secondary_address = endpoint;
1223         pkt->u.bind_ack.num_results = call->pkt.u.bind.num_contexts;
1224         pkt->u.bind_ack.ctx_list = ack_ctx_list;
1225         pkt->u.bind_ack.auth_info = data_blob_null;
1226
1227         status = dcesrv_auth_prepare_bind_ack(call, pkt);
1228         if (!NT_STATUS_IS_OK(status)) {
1229                 return dcesrv_bind_nak(call, 0);
1230         }
1231
1232         if (auth->auth_finished) {
1233                 return dcesrv_auth_reply(call);
1234         }
1235
1236         subreq = gensec_update_send(call, call->event_ctx,
1237                                     auth->gensec_security,
1238                                     call->in_auth_info.credentials);
1239         if (subreq == NULL) {
1240                 return NT_STATUS_NO_MEMORY;
1241         }
1242         tevent_req_set_callback(subreq, dcesrv_bind_done, call);
1243
1244         return dcesrv_conn_auth_wait_setup(conn);
1245 }
1246
1247 static void dcesrv_bind_done(struct tevent_req *subreq)
1248 {
1249         struct dcesrv_call_state *call =
1250                 tevent_req_callback_data(subreq,
1251                 struct dcesrv_call_state);
1252         struct dcesrv_connection *conn = call->conn;
1253         NTSTATUS status;
1254
1255         status = gensec_update_recv(subreq, call,
1256                                     &call->out_auth_info->credentials);
1257         TALLOC_FREE(subreq);
1258
1259         status = dcesrv_auth_complete(call, status);
1260         if (!NT_STATUS_IS_OK(status)) {
1261                 status = dcesrv_bind_nak(call, 0);
1262                 dcesrv_conn_auth_wait_finished(conn, status);
1263                 return;
1264         }
1265
1266         status = dcesrv_auth_reply(call);
1267         dcesrv_conn_auth_wait_finished(conn, status);
1268         return;
1269 }
1270
1271 static NTSTATUS dcesrv_auth_reply(struct dcesrv_call_state *call)
1272 {
1273         struct ncacn_packet *pkt = &call->ack_pkt;
1274         struct data_blob_list_item *rep = NULL;
1275         NTSTATUS status;
1276
1277         rep = talloc_zero(call, struct data_blob_list_item);
1278         if (!rep) {
1279                 return NT_STATUS_NO_MEMORY;
1280         }
1281
1282         status = ncacn_push_auth(&rep->blob, call, pkt,
1283                                  call->out_auth_info);
1284         if (!NT_STATUS_IS_OK(status)) {
1285                 return status;
1286         }
1287
1288         dcerpc_set_frag_length(&rep->blob, rep->blob.length);
1289
1290         DLIST_ADD_END(call->replies, rep);
1291         dcesrv_call_set_list(call, DCESRV_LIST_CALL_LIST);
1292
1293         if (call->conn->call_list && call->conn->call_list->replies) {
1294                 if (call->conn->transport.report_output_data) {
1295                         call->conn->transport.report_output_data(call->conn);
1296                 }
1297         }
1298
1299         return NT_STATUS_OK;
1300 }
1301
1302
1303 static void dcesrv_auth3_done(struct tevent_req *subreq);
1304
1305 /*
1306   handle a auth3 request
1307 */
1308 static NTSTATUS dcesrv_auth3(struct dcesrv_call_state *call)
1309 {
1310         struct dcesrv_connection *conn = call->conn;
1311         struct dcesrv_auth *auth = call->auth_state;
1312         struct tevent_req *subreq = NULL;
1313         NTSTATUS status;
1314
1315         if (!auth->auth_started) {
1316                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1317         }
1318
1319         if (auth->auth_finished) {
1320                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1321         }
1322
1323         status = dcerpc_verify_ncacn_packet_header(&call->pkt,
1324                         DCERPC_PKT_AUTH3,
1325                         call->pkt.u.auth3.auth_info.length,
1326                         0, /* required flags */
1327                         DCERPC_PFC_FLAG_FIRST |
1328                         DCERPC_PFC_FLAG_LAST |
1329                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1330                         0x08 | /* this is not defined, but should be ignored */
1331                         DCERPC_PFC_FLAG_CONC_MPX |
1332                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1333                         DCERPC_PFC_FLAG_MAYBE |
1334                         DCERPC_PFC_FLAG_OBJECT_UUID);
1335         if (!NT_STATUS_IS_OK(status)) {
1336                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1337         }
1338
1339         /* handle the auth3 in the auth code */
1340         if (!dcesrv_auth_prepare_auth3(call)) {
1341                 /*
1342                  * we don't send a reply to a auth3 request,
1343                  * except by a fault.
1344                  *
1345                  * In anycase we mark the connection as
1346                  * invalid.
1347                  */
1348                 auth->auth_invalid = true;
1349                 if (call->fault_code != 0) {
1350                         return dcesrv_fault_disconnect(call, call->fault_code);
1351                 }
1352                 TALLOC_FREE(call);
1353                 return NT_STATUS_OK;
1354         }
1355
1356         subreq = gensec_update_send(call, call->event_ctx,
1357                                     auth->gensec_security,
1358                                     call->in_auth_info.credentials);
1359         if (subreq == NULL) {
1360                 return NT_STATUS_NO_MEMORY;
1361         }
1362         tevent_req_set_callback(subreq, dcesrv_auth3_done, call);
1363
1364         return dcesrv_conn_auth_wait_setup(conn);
1365 }
1366
1367 static void dcesrv_auth3_done(struct tevent_req *subreq)
1368 {
1369         struct dcesrv_call_state *call =
1370                 tevent_req_callback_data(subreq,
1371                 struct dcesrv_call_state);
1372         struct dcesrv_connection *conn = call->conn;
1373         struct dcesrv_auth *auth = call->auth_state;
1374         NTSTATUS status;
1375
1376         status = gensec_update_recv(subreq, call,
1377                                     &call->out_auth_info->credentials);
1378         TALLOC_FREE(subreq);
1379
1380         status = dcesrv_auth_complete(call, status);
1381         if (!NT_STATUS_IS_OK(status)) {
1382                 /*
1383                  * we don't send a reply to a auth3 request,
1384                  * except by a fault.
1385                  *
1386                  * In anycase we mark the connection as
1387                  * invalid.
1388                  */
1389                 auth->auth_invalid = true;
1390                 if (call->fault_code != 0) {
1391                         status = dcesrv_fault_disconnect(call, call->fault_code);
1392                         dcesrv_conn_auth_wait_finished(conn, status);
1393                         return;
1394                 }
1395                 TALLOC_FREE(call);
1396                 dcesrv_conn_auth_wait_finished(conn, NT_STATUS_OK);
1397                 return;
1398         }
1399
1400         /*
1401          * we don't send a reply to a auth3 request.
1402          */
1403         TALLOC_FREE(call);
1404         dcesrv_conn_auth_wait_finished(conn, NT_STATUS_OK);
1405         return;
1406 }
1407
1408
1409 static NTSTATUS dcesrv_check_or_create_context(struct dcesrv_call_state *call,
1410                                 const struct dcerpc_bind *b,
1411                                 const struct dcerpc_ctx_list *ctx,
1412                                 struct dcerpc_ack_ctx *ack,
1413                                 bool validate_only,
1414                                 const struct ndr_syntax_id *supported_transfer)
1415 {
1416         uint32_t if_version;
1417         struct dcesrv_connection_context *context;
1418         const struct dcesrv_interface *iface;
1419         struct GUID uuid;
1420         NTSTATUS status;
1421         const struct ndr_syntax_id *selected_transfer = NULL;
1422         size_t i;
1423         bool ok;
1424
1425         if (b == NULL) {
1426                 return NT_STATUS_INTERNAL_ERROR;
1427         }
1428         if (ctx == NULL) {
1429                 return NT_STATUS_INTERNAL_ERROR;
1430         }
1431         if (ctx->num_transfer_syntaxes < 1) {
1432                 return NT_STATUS_INTERNAL_ERROR;
1433         }
1434         if (ack == NULL) {
1435                 return NT_STATUS_INTERNAL_ERROR;
1436         }
1437         if (supported_transfer == NULL) {
1438                 return NT_STATUS_INTERNAL_ERROR;
1439         }
1440
1441         switch (ack->result) {
1442         case DCERPC_BIND_ACK_RESULT_ACCEPTANCE:
1443         case DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK:
1444                 /*
1445                  * We is already completed.
1446                  */
1447                 return NT_STATUS_OK;
1448         default:
1449                 break;
1450         }
1451
1452         ack->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1453         ack->reason.value = DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
1454
1455         if_version = ctx->abstract_syntax.if_version;
1456         uuid = ctx->abstract_syntax.uuid;
1457
1458         iface = find_interface_by_uuid(call->conn->endpoint, &uuid, if_version);
1459         if (iface == NULL) {
1460                 char *uuid_str = GUID_string(call, &uuid);
1461                 DEBUG(2,("Request for unknown dcerpc interface %s/%d\n", uuid_str, if_version));
1462                 talloc_free(uuid_str);
1463                 /*
1464                  * We report this only via ack->result
1465                  */
1466                 return NT_STATUS_OK;
1467         }
1468
1469         ack->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1470         ack->reason.value = DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED;
1471
1472         if (validate_only) {
1473                 /*
1474                  * We report this only via ack->result
1475                  */
1476                 return NT_STATUS_OK;
1477         }
1478
1479         for (i = 0; i < ctx->num_transfer_syntaxes; i++) {
1480                 /*
1481                  * we only do NDR encoded dcerpc for now.
1482                  */
1483                 ok = ndr_syntax_id_equal(&ctx->transfer_syntaxes[i],
1484                                          supported_transfer);
1485                 if (ok) {
1486                         selected_transfer = supported_transfer;
1487                         break;
1488                 }
1489         }
1490
1491         context = dcesrv_find_context(call->conn, ctx->context_id);
1492         if (context != NULL) {
1493                 ok = ndr_syntax_id_equal(&context->iface->syntax_id,
1494                                          &ctx->abstract_syntax);
1495                 if (!ok) {
1496                         return NT_STATUS_RPC_PROTOCOL_ERROR;
1497                 }
1498
1499                 if (selected_transfer != NULL) {
1500                         ok = ndr_syntax_id_equal(&context->transfer_syntax,
1501                                                  selected_transfer);
1502                         if (!ok) {
1503                                 return NT_STATUS_RPC_PROTOCOL_ERROR;
1504                         }
1505
1506                         ack->result = DCERPC_BIND_ACK_RESULT_ACCEPTANCE;
1507                         ack->reason.value = DCERPC_BIND_ACK_REASON_NOT_SPECIFIED;
1508                         ack->syntax = context->transfer_syntax;
1509                 }
1510
1511                 /*
1512                  * We report this only via ack->result
1513                  */
1514                 return NT_STATUS_OK;
1515         }
1516
1517         if (selected_transfer == NULL) {
1518                 /*
1519                  * We report this only via ack->result
1520                  */
1521                 return NT_STATUS_OK;
1522         }
1523
1524         ack->result = DCERPC_BIND_ACK_RESULT_USER_REJECTION;
1525         ack->reason.value = DCERPC_BIND_ACK_REASON_LOCAL_LIMIT_EXCEEDED;
1526
1527         /* add this context to the list of available context_ids */
1528         context = talloc_zero(call->conn, struct dcesrv_connection_context);
1529         if (context == NULL) {
1530                 return NT_STATUS_NO_MEMORY;
1531         }
1532         context->conn = call->conn;
1533         context->context_id = ctx->context_id;
1534         context->iface = iface;
1535         context->transfer_syntax = *selected_transfer;
1536         DLIST_ADD(call->conn->contexts, context);
1537         call->context = context;
1538         talloc_set_destructor(context, dcesrv_connection_context_destructor);
1539
1540         dcesrv_prepare_context_auth(call);
1541
1542         /*
1543          * Multiplex is supported by default
1544          */
1545         call->state_flags |= DCESRV_CALL_STATE_FLAG_MULTIPLEXED;
1546
1547         status = iface->bind(context, iface);
1548         call->context = NULL;
1549         if (!NT_STATUS_IS_OK(status)) {
1550                 /* we don't want to trigger the iface->unbind() hook */
1551                 context->iface = NULL;
1552                 talloc_free(context);
1553                 /*
1554                  * We report this only via ack->result
1555                  */
1556                 return NT_STATUS_OK;
1557         }
1558
1559         ack->result = DCERPC_BIND_ACK_RESULT_ACCEPTANCE;
1560         ack->reason.value = DCERPC_BIND_ACK_REASON_NOT_SPECIFIED;
1561         ack->syntax = context->transfer_syntax;
1562         return NT_STATUS_OK;
1563 }
1564
1565 static NTSTATUS dcesrv_negotiate_contexts(struct dcesrv_call_state *call,
1566                                 const struct dcerpc_bind *b,
1567                                 struct dcerpc_ack_ctx *ack_ctx_list)
1568 {
1569         NTSTATUS status;
1570         size_t i;
1571         bool validate_only = false;
1572         bool preferred_ndr32;
1573
1574         /*
1575          * Try to negotiate one new presentation context,
1576          * using our preferred transfer syntax.
1577          */
1578         for (i = 0; i < b->num_contexts; i++) {
1579                 const struct dcerpc_ctx_list *c = &b->ctx_list[i];
1580                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1581
1582                 status = dcesrv_check_or_create_context(call, b, c, a,
1583                                                 validate_only,
1584                                                 call->conn->preferred_transfer);
1585                 if (!NT_STATUS_IS_OK(status)) {
1586                         return status;
1587                 }
1588
1589                 if (a->result == DCERPC_BIND_ACK_RESULT_ACCEPTANCE) {
1590                         /*
1591                          * We managed to negotiate one context.
1592                          *
1593                          * => we're done.
1594                          */
1595                         validate_only = true;
1596                 }
1597         }
1598
1599         preferred_ndr32 = ndr_syntax_id_equal(&ndr_transfer_syntax_ndr,
1600                                         call->conn->preferred_transfer);
1601         if (preferred_ndr32) {
1602                 /*
1603                  * We're done.
1604                  */
1605                 return NT_STATUS_OK;
1606         }
1607
1608         /*
1609          * Try to negotiate one new presentation context,
1610          * using NDR 32 as fallback.
1611          */
1612         for (i = 0; i < b->num_contexts; i++) {
1613                 const struct dcerpc_ctx_list *c = &b->ctx_list[i];
1614                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1615
1616                 status = dcesrv_check_or_create_context(call, b, c, a,
1617                                                 validate_only,
1618                                                 &ndr_transfer_syntax_ndr);
1619                 if (!NT_STATUS_IS_OK(status)) {
1620                         return status;
1621                 }
1622
1623                 if (a->result == DCERPC_BIND_ACK_RESULT_ACCEPTANCE) {
1624                         /*
1625                          * We managed to negotiate one context.
1626                          *
1627                          * => we're done.
1628                          */
1629                         validate_only = true;
1630                 }
1631         }
1632
1633         return NT_STATUS_OK;
1634 }
1635
1636 static void dcesrv_alter_done(struct tevent_req *subreq);
1637
1638 /*
1639   handle a alter context request
1640 */
1641 static NTSTATUS dcesrv_alter(struct dcesrv_call_state *call)
1642 {
1643         struct dcesrv_connection *conn = call->conn;
1644         NTSTATUS status;
1645         bool auth_ok = false;
1646         struct ncacn_packet *pkt = &call->ack_pkt;
1647         uint32_t extra_flags = 0;
1648         struct dcesrv_auth *auth = call->auth_state;
1649         struct dcerpc_ack_ctx *ack_ctx_list = NULL;
1650         struct tevent_req *subreq = NULL;
1651         size_t i;
1652
1653         if (!call->conn->allow_alter) {
1654                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1655         }
1656
1657         status = dcerpc_verify_ncacn_packet_header(&call->pkt,
1658                         DCERPC_PKT_ALTER,
1659                         call->pkt.u.alter.auth_info.length,
1660                         0, /* required flags */
1661                         DCERPC_PFC_FLAG_FIRST |
1662                         DCERPC_PFC_FLAG_LAST |
1663                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1664                         0x08 | /* this is not defined, but should be ignored */
1665                         DCERPC_PFC_FLAG_CONC_MPX |
1666                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1667                         DCERPC_PFC_FLAG_MAYBE |
1668                         DCERPC_PFC_FLAG_OBJECT_UUID);
1669         if (!NT_STATUS_IS_OK(status)) {
1670                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1671         }
1672
1673         auth_ok = dcesrv_auth_alter(call);
1674         if (!auth_ok) {
1675                 if (call->fault_code != 0) {
1676                         return dcesrv_fault_disconnect(call, call->fault_code);
1677                 }
1678         }
1679
1680         if (call->pkt.u.alter.num_contexts < 1) {
1681                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1682         }
1683
1684         ack_ctx_list = talloc_zero_array(call, struct dcerpc_ack_ctx,
1685                                          call->pkt.u.alter.num_contexts);
1686         if (ack_ctx_list == NULL) {
1687                 return NT_STATUS_NO_MEMORY;
1688         }
1689
1690         /*
1691          * Set some sane defaults (required by dcesrv_negotiate_contexts()/
1692          * dcesrv_check_or_create_context()) and do some protocol validation
1693          * and set sane defaults.
1694          */
1695         for (i = 0; i < call->pkt.u.alter.num_contexts; i++) {
1696                 const struct dcerpc_ctx_list *c = &call->pkt.u.alter.ctx_list[i];
1697                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1698
1699                 if (c->num_transfer_syntaxes == 0) {
1700                         return dcesrv_fault_disconnect(call,
1701                                         DCERPC_NCA_S_PROTO_ERROR);
1702                 }
1703
1704                 a->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1705                 a->reason.value = DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
1706         }
1707
1708         /*
1709          * Try to negotiate one new presentation context.
1710          */
1711         status = dcesrv_negotiate_contexts(call, &call->pkt.u.alter, ack_ctx_list);
1712         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROTOCOL_ERROR)) {
1713                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1714         }
1715         if (!NT_STATUS_IS_OK(status)) {
1716                 return status;
1717         }
1718
1719         if ((call->pkt.pfc_flags & DCERPC_PFC_FLAG_CONC_MPX) &&
1720             (call->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
1721                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_MULTIPLEXED;
1722                 extra_flags |= DCERPC_PFC_FLAG_CONC_MPX;
1723         }
1724
1725         if (call->state_flags & DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL) {
1726                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL;
1727         }
1728
1729         /* handle any authentication that is being requested */
1730         if (!auth_ok) {
1731                 if (call->in_auth_info.auth_type != auth->auth_type) {
1732                         return dcesrv_fault_disconnect(call,
1733                                         DCERPC_FAULT_SEC_PKG_ERROR);
1734                 }
1735                 return dcesrv_fault_disconnect(call, DCERPC_FAULT_ACCESS_DENIED);
1736         }
1737
1738         dcesrv_init_hdr(pkt, lpcfg_rpc_big_endian(call->conn->dce_ctx->lp_ctx));
1739         pkt->auth_length = 0;
1740         pkt->call_id = call->pkt.call_id;
1741         pkt->ptype = DCERPC_PKT_ALTER_RESP;
1742         pkt->pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST | extra_flags;
1743         pkt->u.alter_resp.max_xmit_frag = call->conn->max_xmit_frag;
1744         pkt->u.alter_resp.max_recv_frag = call->conn->max_recv_frag;
1745         pkt->u.alter_resp.assoc_group_id = call->conn->assoc_group->id;
1746         pkt->u.alter_resp.secondary_address = "";
1747         pkt->u.alter_resp.num_results = call->pkt.u.alter.num_contexts;
1748         pkt->u.alter_resp.ctx_list = ack_ctx_list;
1749         pkt->u.alter_resp.auth_info = data_blob_null;
1750
1751         status = dcesrv_auth_prepare_alter_ack(call, pkt);
1752         if (!NT_STATUS_IS_OK(status)) {
1753                 return dcesrv_fault_disconnect(call, DCERPC_FAULT_SEC_PKG_ERROR);
1754         }
1755
1756         if (auth->auth_finished) {
1757                 return dcesrv_auth_reply(call);
1758         }
1759
1760         subreq = gensec_update_send(call, call->event_ctx,
1761                                     auth->gensec_security,
1762                                     call->in_auth_info.credentials);
1763         if (subreq == NULL) {
1764                 return NT_STATUS_NO_MEMORY;
1765         }
1766         tevent_req_set_callback(subreq, dcesrv_alter_done, call);
1767
1768         return dcesrv_conn_auth_wait_setup(conn);
1769 }
1770
1771 static void dcesrv_alter_done(struct tevent_req *subreq)
1772 {
1773         struct dcesrv_call_state *call =
1774                 tevent_req_callback_data(subreq,
1775                 struct dcesrv_call_state);
1776         struct dcesrv_connection *conn = call->conn;
1777         NTSTATUS status;
1778
1779         status = gensec_update_recv(subreq, call,
1780                                     &call->out_auth_info->credentials);
1781         TALLOC_FREE(subreq);
1782
1783         status = dcesrv_auth_complete(call, status);
1784         if (!NT_STATUS_IS_OK(status)) {
1785                 status = dcesrv_fault_disconnect(call, DCERPC_FAULT_SEC_PKG_ERROR);
1786                 dcesrv_conn_auth_wait_finished(conn, status);
1787                 return;
1788         }
1789
1790         status = dcesrv_auth_reply(call);
1791         dcesrv_conn_auth_wait_finished(conn, status);
1792         return;
1793 }
1794
1795 /*
1796   possibly save the call for inspection with ndrdump
1797  */
1798 static void dcesrv_save_call(struct dcesrv_call_state *call, const char *why)
1799 {
1800 #ifdef DEVELOPER
1801         char *fname;
1802         const char *dump_dir;
1803         dump_dir = lpcfg_parm_string(call->conn->dce_ctx->lp_ctx, NULL, "dcesrv", "stubs directory");
1804         if (!dump_dir) {
1805                 return;
1806         }
1807         fname = talloc_asprintf(call, "%s/RPC-%s-%u-%s.dat",
1808                                 dump_dir,
1809                                 call->context->iface->name,
1810                                 call->pkt.u.request.opnum,
1811                                 why);
1812         if (file_save(fname, call->pkt.u.request.stub_and_verifier.data, call->pkt.u.request.stub_and_verifier.length)) {
1813                 DEBUG(0,("RPC SAVED %s\n", fname));
1814         }
1815         talloc_free(fname);
1816 #endif
1817 }
1818
1819 static NTSTATUS dcesrv_check_verification_trailer(struct dcesrv_call_state *call)
1820 {
1821         TALLOC_CTX *frame = talloc_stackframe();
1822         const uint32_t bitmask1 = call->conn->client_hdr_signing ?
1823                 DCERPC_SEC_VT_CLIENT_SUPPORTS_HEADER_SIGNING : 0;
1824         const struct dcerpc_sec_vt_pcontext pcontext = {
1825                 .abstract_syntax = call->context->iface->syntax_id,
1826                 .transfer_syntax = call->context->transfer_syntax,
1827         };
1828         const struct dcerpc_sec_vt_header2 header2 =
1829                 dcerpc_sec_vt_header2_from_ncacn_packet(&call->pkt);
1830         enum ndr_err_code ndr_err;
1831         struct dcerpc_sec_verification_trailer *vt = NULL;
1832         NTSTATUS status = NT_STATUS_OK;
1833         bool ok;
1834
1835         SMB_ASSERT(call->pkt.ptype == DCERPC_PKT_REQUEST);
1836
1837         ndr_err = ndr_pop_dcerpc_sec_verification_trailer(call->ndr_pull,
1838                                                           frame, &vt);
1839         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1840                 status = ndr_map_error2ntstatus(ndr_err);
1841                 goto done;
1842         }
1843
1844         ok = dcerpc_sec_verification_trailer_check(vt, &bitmask1,
1845                                                    &pcontext, &header2);
1846         if (!ok) {
1847                 status = NT_STATUS_ACCESS_DENIED;
1848                 goto done;
1849         }
1850 done:
1851         TALLOC_FREE(frame);
1852         return status;
1853 }
1854
1855 /*
1856   handle a dcerpc request packet
1857 */
1858 static NTSTATUS dcesrv_request(struct dcesrv_call_state *call)
1859 {
1860         const struct dcesrv_endpoint *endpoint = call->conn->endpoint;
1861         struct dcesrv_auth *auth = call->auth_state;
1862         enum dcerpc_transport_t transport =
1863                 dcerpc_binding_get_transport(endpoint->ep_description);
1864         struct ndr_pull *pull;
1865         NTSTATUS status;
1866
1867         if (!auth->auth_finished) {
1868                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1869         }
1870
1871         /* if authenticated, and the mech we use can't do async replies, don't use them... */
1872         if (auth->gensec_security != NULL &&
1873             !gensec_have_feature(auth->gensec_security, GENSEC_FEATURE_ASYNC_REPLIES)) {
1874                 call->state_flags &= ~DCESRV_CALL_STATE_FLAG_MAY_ASYNC;
1875         }
1876
1877         if (call->context == NULL) {
1878                 return dcesrv_fault_with_flags(call, DCERPC_NCA_S_UNKNOWN_IF,
1879                                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
1880         }
1881
1882         switch (auth->auth_level) {
1883         case DCERPC_AUTH_LEVEL_NONE:
1884         case DCERPC_AUTH_LEVEL_PACKET:
1885         case DCERPC_AUTH_LEVEL_INTEGRITY:
1886         case DCERPC_AUTH_LEVEL_PRIVACY:
1887                 break;
1888         default:
1889                 if (!call->context->allow_connect) {
1890                         char *addr;
1891
1892                         addr = tsocket_address_string(call->conn->remote_address,
1893                                                       call);
1894
1895                         DEBUG(2, ("%s: restrict auth_level_connect access "
1896                                   "to [%s] with auth[type=0x%x,level=0x%x] "
1897                                   "on [%s] from [%s]\n",
1898                                   __func__, call->context->iface->name,
1899                                   auth->auth_type,
1900                                   auth->auth_level,
1901                                   derpc_transport_string_by_transport(transport),
1902                                   addr));
1903                         return dcesrv_fault(call, DCERPC_FAULT_ACCESS_DENIED);
1904                 }
1905                 break;
1906         }
1907
1908         if (auth->auth_level < call->context->min_auth_level) {
1909                 char *addr;
1910
1911                 addr = tsocket_address_string(call->conn->remote_address, call);
1912
1913                 DEBUG(2, ("%s: restrict access by min_auth_level[0x%x] "
1914                           "to [%s] with auth[type=0x%x,level=0x%x] "
1915                           "on [%s] from [%s]\n",
1916                           __func__,
1917                           call->context->min_auth_level,
1918                           call->context->iface->name,
1919                           auth->auth_type,
1920                           auth->auth_level,
1921                           derpc_transport_string_by_transport(transport),
1922                           addr));
1923                 return dcesrv_fault(call, DCERPC_FAULT_ACCESS_DENIED);
1924         }
1925
1926         pull = ndr_pull_init_blob(&call->pkt.u.request.stub_and_verifier, call);
1927         NT_STATUS_HAVE_NO_MEMORY(pull);
1928
1929         pull->flags |= LIBNDR_FLAG_REF_ALLOC;
1930
1931         call->ndr_pull  = pull;
1932
1933         if (!(call->pkt.drep[0] & DCERPC_DREP_LE)) {
1934                 pull->flags |= LIBNDR_FLAG_BIGENDIAN;
1935         }
1936
1937         status = dcesrv_check_verification_trailer(call);
1938         if (!NT_STATUS_IS_OK(status)) {
1939                 uint32_t faultcode = DCERPC_FAULT_OTHER;
1940                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1941                         faultcode = DCERPC_FAULT_ACCESS_DENIED;
1942                 }
1943                 DEBUG(10, ("dcesrv_check_verification_trailer failed: %s\n",
1944                            nt_errstr(status)));
1945                 return dcesrv_fault(call, faultcode);
1946         }
1947
1948         /* unravel the NDR for the packet */
1949         status = call->context->iface->ndr_pull(call, call, pull, &call->r);
1950         if (!NT_STATUS_IS_OK(status)) {
1951                 uint8_t extra_flags = 0;
1952                 if (call->fault_code == DCERPC_FAULT_OP_RNG_ERROR) {
1953                         /* we got an unknown call */
1954                         DEBUG(3,(__location__ ": Unknown RPC call %u on %s\n",
1955                                  call->pkt.u.request.opnum,
1956                                  call->context->iface->name));
1957                         dcesrv_save_call(call, "unknown");
1958                         extra_flags |= DCERPC_PFC_FLAG_DID_NOT_EXECUTE;
1959                 } else {
1960                         dcesrv_save_call(call, "pullfail");
1961                 }
1962                 return dcesrv_fault_with_flags(call, call->fault_code, extra_flags);
1963         }
1964
1965         if (pull->offset != pull->data_size) {
1966                 dcesrv_save_call(call, "extrabytes");
1967                 DEBUG(3,("Warning: %d extra bytes in incoming RPC request\n", 
1968                          pull->data_size - pull->offset));
1969         }
1970
1971         /* call the dispatch function */
1972         status = call->context->iface->dispatch(call, call, call->r);
1973         if (!NT_STATUS_IS_OK(status)) {
1974                 DEBUG(5,("dcerpc fault in call %s:%02x - %s\n",
1975                          call->context->iface->name,
1976                          call->pkt.u.request.opnum,
1977                          dcerpc_errstr(pull, call->fault_code)));
1978                 return dcesrv_fault(call, call->fault_code);
1979         }
1980
1981         /* add the call to the pending list */
1982         dcesrv_call_set_list(call, DCESRV_LIST_PENDING_CALL_LIST);
1983
1984         if (call->state_flags & DCESRV_CALL_STATE_FLAG_ASYNC) {
1985                 return NT_STATUS_OK;
1986         }
1987
1988         return dcesrv_reply(call);
1989 }
1990
1991
1992 /*
1993   remove the call from the right list when freed
1994  */
1995 static int dcesrv_call_dequeue(struct dcesrv_call_state *call)
1996 {
1997         dcesrv_call_set_list(call, DCESRV_LIST_NONE);
1998         return 0;
1999 }
2000
2001 _PUBLIC_ const struct tsocket_address *dcesrv_connection_get_local_address(struct dcesrv_connection *conn)
2002 {
2003         return conn->local_address;
2004 }
2005
2006 _PUBLIC_ const struct tsocket_address *dcesrv_connection_get_remote_address(struct dcesrv_connection *conn)
2007 {
2008         return conn->remote_address;
2009 }
2010
2011 /*
2012   process some input to a dcerpc endpoint server.
2013 */
2014 static NTSTATUS dcesrv_process_ncacn_packet(struct dcesrv_connection *dce_conn,
2015                                             struct ncacn_packet *pkt,
2016                                             DATA_BLOB blob)
2017 {
2018         NTSTATUS status;
2019         struct dcesrv_call_state *call;
2020         struct dcesrv_call_state *existing = NULL;
2021
2022         call = talloc_zero(dce_conn, struct dcesrv_call_state);
2023         if (!call) {
2024                 data_blob_free(&blob);
2025                 talloc_free(pkt);
2026                 return NT_STATUS_NO_MEMORY;
2027         }
2028         call->conn              = dce_conn;
2029         call->event_ctx         = dce_conn->event_ctx;
2030         call->msg_ctx           = dce_conn->msg_ctx;
2031         call->state_flags       = call->conn->state_flags;
2032         call->time              = timeval_current();
2033         call->list              = DCESRV_LIST_NONE;
2034
2035         talloc_steal(call, pkt);
2036         talloc_steal(call, blob.data);
2037         call->pkt = *pkt;
2038
2039         call->auth_state = dce_conn->default_auth_state;
2040
2041         talloc_set_destructor(call, dcesrv_call_dequeue);
2042
2043         if (call->conn->allow_bind) {
2044                 /*
2045                  * Only one bind is possible per connection
2046                  */
2047                 call->conn->allow_bind = false;
2048                 return dcesrv_bind(call);
2049         }
2050
2051         /* we have to check the signing here, before combining the
2052            pdus */
2053         if (call->pkt.ptype == DCERPC_PKT_REQUEST) {
2054                 if (!call->auth_state->auth_finished) {
2055                         return dcesrv_fault_disconnect(call,
2056                                         DCERPC_NCA_S_PROTO_ERROR);
2057                 }
2058
2059                 status = dcerpc_verify_ncacn_packet_header(&call->pkt,
2060                                 DCERPC_PKT_REQUEST,
2061                                 call->pkt.u.request.stub_and_verifier.length,
2062                                 0, /* required_flags */
2063                                 DCERPC_PFC_FLAG_FIRST |
2064                                 DCERPC_PFC_FLAG_LAST |
2065                                 DCERPC_PFC_FLAG_PENDING_CANCEL |
2066                                 0x08 | /* this is not defined, but should be ignored */
2067                                 DCERPC_PFC_FLAG_CONC_MPX |
2068                                 DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
2069                                 DCERPC_PFC_FLAG_MAYBE |
2070                                 DCERPC_PFC_FLAG_OBJECT_UUID);
2071                 if (!NT_STATUS_IS_OK(status)) {
2072                         return dcesrv_fault_disconnect(call,
2073                                         DCERPC_NCA_S_PROTO_ERROR);
2074                 }
2075
2076                 if (call->pkt.frag_length > DCERPC_FRAG_MAX_SIZE) {
2077                         /*
2078                          * We don't use dcesrv_fault_disconnect()
2079                          * here, because we don't want to set
2080                          * DCERPC_PFC_FLAG_DID_NOT_EXECUTE
2081                          *
2082                          * Note that we don't check against the negotiated
2083                          * max_recv_frag, but a hard coded value.
2084                          */
2085                         dcesrv_call_disconnect_after(call,
2086                                 "dcesrv_auth_request - frag_length too large");
2087                         return dcesrv_fault(call,
2088                                         DCERPC_NCA_S_PROTO_ERROR);
2089                 }
2090
2091                 if (call->pkt.pfc_flags & DCERPC_PFC_FLAG_FIRST) {
2092                         if (dce_conn->pending_call_list != NULL) {
2093                                 /*
2094                                  * concurrent requests are only allowed
2095                                  * if DCERPC_PFC_FLAG_CONC_MPX was negotiated.
2096                                  */
2097                                 if (!(dce_conn->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
2098                                         dcesrv_call_disconnect_after(call,
2099                                                 "dcesrv_auth_request - "
2100                                                 "existing pending call without CONN_MPX");
2101                                         return dcesrv_fault(call,
2102                                                 DCERPC_NCA_S_PROTO_ERROR);
2103                                 }
2104                         }
2105                         /* only one request is possible in the fragmented list */
2106                         if (dce_conn->incoming_fragmented_call_list != NULL) {
2107                                 if (!(dce_conn->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
2108                                         /*
2109                                          * Without DCERPC_PFC_FLAG_CONC_MPX
2110                                          * we need to return the FAULT on the
2111                                          * already existing call.
2112                                          *
2113                                          * This is important to get the
2114                                          * call_id and context_id right.
2115                                          */
2116                                         TALLOC_FREE(call);
2117                                         call = dce_conn->incoming_fragmented_call_list;
2118                                 }
2119                                 dcesrv_call_disconnect_after(call,
2120                                         "dcesrv_auth_request - "
2121                                         "existing fragmented call");
2122                                 return dcesrv_fault(call,
2123                                                 DCERPC_NCA_S_PROTO_ERROR);
2124                         }
2125                         if (call->pkt.pfc_flags & DCERPC_PFC_FLAG_PENDING_CANCEL) {
2126                                 return dcesrv_fault_disconnect(call,
2127                                                 DCERPC_FAULT_NO_CALL_ACTIVE);
2128                         }
2129                         call->context = dcesrv_find_context(call->conn,
2130                                                 call->pkt.u.request.context_id);
2131                         if (call->context == NULL) {
2132                                 return dcesrv_fault_with_flags(call, DCERPC_NCA_S_UNKNOWN_IF,
2133                                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
2134                         }
2135                 } else {
2136                         const struct dcerpc_request *nr = &call->pkt.u.request;
2137                         const struct dcerpc_request *er = NULL;
2138                         int cmp;
2139
2140                         existing = dcesrv_find_fragmented_call(dce_conn,
2141                                                         call->pkt.call_id);
2142                         if (existing == NULL) {
2143                                 dcesrv_call_disconnect_after(call,
2144                                         "dcesrv_auth_request - "
2145                                         "no existing fragmented call");
2146                                 return dcesrv_fault(call,
2147                                                 DCERPC_NCA_S_PROTO_ERROR);
2148                         }
2149                         er = &existing->pkt.u.request;
2150
2151                         if (call->pkt.ptype != existing->pkt.ptype) {
2152                                 /* trying to play silly buggers are we? */
2153                                 return dcesrv_fault_disconnect(existing,
2154                                                 DCERPC_NCA_S_PROTO_ERROR);
2155                         }
2156                         cmp = memcmp(call->pkt.drep, existing->pkt.drep,
2157                                      sizeof(pkt->drep));
2158                         if (cmp != 0) {
2159                                 return dcesrv_fault_disconnect(existing,
2160                                                 DCERPC_NCA_S_PROTO_ERROR);
2161                         }
2162                         if (nr->context_id != er->context_id)  {
2163                                 return dcesrv_fault_disconnect(existing,
2164                                                 DCERPC_NCA_S_PROTO_ERROR);
2165                         }
2166                         if (nr->opnum != er->opnum)  {
2167                                 return dcesrv_fault_disconnect(existing,
2168                                                 DCERPC_NCA_S_PROTO_ERROR);
2169                         }
2170                 }
2171         }
2172
2173         if (call->pkt.ptype == DCERPC_PKT_REQUEST) {
2174                 bool ok;
2175                 uint8_t payload_offset = DCERPC_REQUEST_LENGTH;
2176
2177                 if (call->pkt.pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
2178                         payload_offset += 16;
2179                 }
2180
2181                 ok = dcesrv_auth_pkt_pull(call, &blob,
2182                                           0, /* required_flags */
2183                                           DCERPC_PFC_FLAG_FIRST |
2184                                           DCERPC_PFC_FLAG_LAST |
2185                                           DCERPC_PFC_FLAG_PENDING_CANCEL |
2186                                           0x08 | /* this is not defined, but should be ignored */
2187                                           DCERPC_PFC_FLAG_CONC_MPX |
2188                                           DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
2189                                           DCERPC_PFC_FLAG_MAYBE |
2190                                           DCERPC_PFC_FLAG_OBJECT_UUID,
2191                                           payload_offset,
2192                                           &call->pkt.u.request.stub_and_verifier);
2193                 if (!ok) {
2194                         /*
2195                          * We don't use dcesrv_fault_disconnect()
2196                          * here, because we don't want to set
2197                          * DCERPC_PFC_FLAG_DID_NOT_EXECUTE
2198                          */
2199                         dcesrv_call_disconnect_after(call,
2200                                                 "dcesrv_auth_request - failed");
2201                         if (call->fault_code == 0) {
2202                                 call->fault_code = DCERPC_FAULT_ACCESS_DENIED;
2203                         }
2204                         return dcesrv_fault(call, call->fault_code);
2205                 }
2206         }
2207
2208         /* see if this is a continued packet */
2209         if (existing != NULL) {
2210                 struct dcerpc_request *er = &existing->pkt.u.request;
2211                 const struct dcerpc_request *nr = &call->pkt.u.request;
2212                 size_t available;
2213                 size_t alloc_size;
2214                 size_t alloc_hint;
2215
2216                 /*
2217                  * Up to 4 MByte are allowed by all fragments
2218                  */
2219                 available = dce_conn->max_total_request_size;
2220                 if (er->stub_and_verifier.length > available) {
2221                         dcesrv_call_disconnect_after(existing,
2222                                 "dcesrv_auth_request - existing payload too large");
2223                         return dcesrv_fault(existing, DCERPC_FAULT_ACCESS_DENIED);
2224                 }
2225                 available -= er->stub_and_verifier.length;
2226                 if (nr->alloc_hint > available) {
2227                         dcesrv_call_disconnect_after(existing,
2228                                 "dcesrv_auth_request - alloc hint too large");
2229                         return dcesrv_fault(existing, DCERPC_FAULT_ACCESS_DENIED);
2230                 }
2231                 if (nr->stub_and_verifier.length > available) {
2232                         dcesrv_call_disconnect_after(existing,
2233                                 "dcesrv_auth_request - new payload too large");
2234                         return dcesrv_fault(existing, DCERPC_FAULT_ACCESS_DENIED);
2235                 }
2236                 alloc_hint = er->stub_and_verifier.length + nr->alloc_hint;
2237                 /* allocate at least 1 byte */
2238                 alloc_hint = MAX(alloc_hint, 1);
2239                 alloc_size = er->stub_and_verifier.length +
2240                              nr->stub_and_verifier.length;
2241                 alloc_size = MAX(alloc_size, alloc_hint);
2242
2243                 er->stub_and_verifier.data =
2244                         talloc_realloc(existing,
2245                                        er->stub_and_verifier.data,
2246                                        uint8_t, alloc_size);
2247                 if (er->stub_and_verifier.data == NULL) {
2248                         TALLOC_FREE(call);
2249                         return dcesrv_fault_with_flags(existing,
2250                                                        DCERPC_FAULT_OUT_OF_RESOURCES,
2251                                                        DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
2252                 }
2253                 memcpy(er->stub_and_verifier.data +
2254                        er->stub_and_verifier.length,
2255                        nr->stub_and_verifier.data,
2256                        nr->stub_and_verifier.length);
2257                 er->stub_and_verifier.length += nr->stub_and_verifier.length;
2258
2259                 existing->pkt.pfc_flags |= (call->pkt.pfc_flags & DCERPC_PFC_FLAG_LAST);
2260
2261                 TALLOC_FREE(call);
2262                 call = existing;
2263         }
2264
2265         /* this may not be the last pdu in the chain - if its isn't then
2266            just put it on the incoming_fragmented_call_list and wait for the rest */
2267         if (call->pkt.ptype == DCERPC_PKT_REQUEST &&
2268             !(call->pkt.pfc_flags & DCERPC_PFC_FLAG_LAST)) {
2269                 /*
2270                  * Up to 4 MByte are allowed by all fragments
2271                  */
2272                 if (call->pkt.u.request.alloc_hint > dce_conn->max_total_request_size) {
2273                         dcesrv_call_disconnect_after(call,
2274                                 "dcesrv_auth_request - initial alloc hint too large");
2275                         return dcesrv_fault(call, DCERPC_FAULT_ACCESS_DENIED);
2276                 }
2277                 dcesrv_call_set_list(call, DCESRV_LIST_FRAGMENTED_CALL_LIST);
2278                 return NT_STATUS_OK;
2279         } 
2280         
2281         /* This removes any fragments we may have had stashed away */
2282         dcesrv_call_set_list(call, DCESRV_LIST_NONE);
2283
2284         switch (call->pkt.ptype) {
2285         case DCERPC_PKT_BIND:
2286                 status = dcesrv_bind_nak(call,
2287                         DCERPC_BIND_NAK_REASON_NOT_SPECIFIED);
2288                 break;
2289         case DCERPC_PKT_AUTH3:
2290                 status = dcesrv_auth3(call);
2291                 break;
2292         case DCERPC_PKT_ALTER:
2293                 status = dcesrv_alter(call);
2294                 break;
2295         case DCERPC_PKT_REQUEST:
2296                 status = dcesrv_request(call);
2297                 break;
2298         case DCERPC_PKT_CO_CANCEL:
2299         case DCERPC_PKT_ORPHANED:
2300                 /*
2301                  * Window just ignores CO_CANCEL and ORPHANED,
2302                  * so we do...
2303                  */
2304                 status = NT_STATUS_OK;
2305                 TALLOC_FREE(call);
2306                 break;
2307         case DCERPC_PKT_BIND_ACK:
2308         case DCERPC_PKT_BIND_NAK:
2309         case DCERPC_PKT_ALTER_RESP:
2310         case DCERPC_PKT_RESPONSE:
2311         case DCERPC_PKT_FAULT:
2312         case DCERPC_PKT_SHUTDOWN:
2313         default:
2314                 status = dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
2315                 break;
2316         }
2317
2318         /* if we are going to be sending a reply then add
2319            it to the list of pending calls. We add it to the end to keep the call
2320            list in the order we will answer */
2321         if (!NT_STATUS_IS_OK(status)) {
2322                 talloc_free(call);
2323         }
2324
2325         return status;
2326 }
2327
2328 _PUBLIC_ NTSTATUS dcesrv_init_context(TALLOC_CTX *mem_ctx, 
2329                                       struct loadparm_context *lp_ctx,
2330                                       const char **endpoint_servers, struct dcesrv_context **_dce_ctx)
2331 {
2332         NTSTATUS status;
2333         struct dcesrv_context *dce_ctx;
2334         int i;
2335
2336         if (!endpoint_servers) {
2337                 DEBUG(0,("dcesrv_init_context: no endpoint servers configured\n"));
2338                 return NT_STATUS_INTERNAL_ERROR;
2339         }
2340
2341         dce_ctx = talloc_zero(mem_ctx, struct dcesrv_context);
2342         NT_STATUS_HAVE_NO_MEMORY(dce_ctx);
2343
2344         if (uid_wrapper_enabled()) {
2345                 setenv("UID_WRAPPER_MYUID", "1", 1);
2346         }
2347         dce_ctx->initial_euid = geteuid();
2348         if (uid_wrapper_enabled()) {
2349                 unsetenv("UID_WRAPPER_MYUID");
2350         }
2351
2352         dce_ctx->endpoint_list  = NULL;
2353         dce_ctx->lp_ctx = lp_ctx;
2354         dce_ctx->assoc_groups_idr = idr_init(dce_ctx);
2355         NT_STATUS_HAVE_NO_MEMORY(dce_ctx->assoc_groups_idr);
2356         dce_ctx->broken_connections = NULL;
2357
2358         for (i=0;endpoint_servers[i];i++) {
2359                 const struct dcesrv_endpoint_server *ep_server;
2360
2361                 ep_server = dcesrv_ep_server_byname(endpoint_servers[i]);
2362                 if (!ep_server) {
2363                         DEBUG(0,("dcesrv_init_context: failed to find endpoint server = '%s'\n", endpoint_servers[i]));
2364                         return NT_STATUS_INTERNAL_ERROR;
2365                 }
2366
2367                 status = ep_server->init_server(dce_ctx, ep_server);
2368                 if (!NT_STATUS_IS_OK(status)) {
2369                         DEBUG(0,("dcesrv_init_context: failed to init endpoint server = '%s': %s\n", endpoint_servers[i],
2370                                 nt_errstr(status)));
2371                         return status;
2372                 }
2373         }
2374
2375         *_dce_ctx = dce_ctx;
2376         return NT_STATUS_OK;
2377 }
2378
2379 /* the list of currently registered DCERPC endpoint servers.
2380  */
2381 static struct ep_server {
2382         struct dcesrv_endpoint_server *ep_server;
2383 } *ep_servers = NULL;
2384 static int num_ep_servers;
2385
2386 /*
2387   register a DCERPC endpoint server. 
2388
2389   The 'name' can be later used by other backends to find the operations
2390   structure for this backend.  
2391
2392 */
2393 _PUBLIC_ NTSTATUS dcerpc_register_ep_server(const struct dcesrv_endpoint_server *ep_server)
2394 {
2395         
2396         if (dcesrv_ep_server_byname(ep_server->name) != NULL) {
2397                 /* its already registered! */
2398                 DEBUG(0,("DCERPC endpoint server '%s' already registered\n", 
2399                          ep_server->name));
2400                 return NT_STATUS_OBJECT_NAME_COLLISION;
2401         }
2402
2403         ep_servers = realloc_p(ep_servers, struct ep_server, num_ep_servers+1);
2404         if (!ep_servers) {
2405                 smb_panic("out of memory in dcerpc_register");
2406         }
2407
2408         ep_servers[num_ep_servers].ep_server = smb_xmemdup(ep_server, sizeof(*ep_server));
2409         ep_servers[num_ep_servers].ep_server->name = smb_xstrdup(ep_server->name);
2410
2411         num_ep_servers++;
2412
2413         DEBUG(3,("DCERPC endpoint server '%s' registered\n", 
2414                  ep_server->name));
2415
2416         return NT_STATUS_OK;
2417 }
2418
2419 /*
2420   return the operations structure for a named backend of the specified type
2421 */
2422 const struct dcesrv_endpoint_server *dcesrv_ep_server_byname(const char *name)
2423 {
2424         int i;
2425
2426         for (i=0;i<num_ep_servers;i++) {
2427                 if (strcmp(ep_servers[i].ep_server->name, name) == 0) {
2428                         return ep_servers[i].ep_server;
2429                 }
2430         }
2431
2432         return NULL;
2433 }
2434
2435 void dcerpc_server_init(struct loadparm_context *lp_ctx)
2436 {
2437         static bool initialized;
2438 #define _MODULE_PROTO(init) extern NTSTATUS init(TALLOC_CTX *);
2439         STATIC_dcerpc_server_MODULES_PROTO;
2440         init_module_fn static_init[] = { STATIC_dcerpc_server_MODULES };
2441         init_module_fn *shared_init;
2442
2443         if (initialized) {
2444                 return;
2445         }
2446         initialized = true;
2447
2448         shared_init = load_samba_modules(NULL, "dcerpc_server");
2449
2450         run_init_functions(NULL, static_init);
2451         run_init_functions(NULL, shared_init);
2452
2453         talloc_free(shared_init);
2454 }
2455
2456 /*
2457   return the DCERPC module version, and the size of some critical types
2458   This can be used by endpoint server modules to either detect compilation errors, or provide
2459   multiple implementations for different smbd compilation options in one module
2460 */
2461 const struct dcesrv_critical_sizes *dcerpc_module_version(void)
2462 {
2463         static const struct dcesrv_critical_sizes critical_sizes = {
2464                 DCERPC_MODULE_VERSION,
2465                 sizeof(struct dcesrv_context),
2466                 sizeof(struct dcesrv_endpoint),
2467                 sizeof(struct dcesrv_endpoint_server),
2468                 sizeof(struct dcesrv_interface),
2469                 sizeof(struct dcesrv_if_list),
2470                 sizeof(struct dcesrv_connection),
2471                 sizeof(struct dcesrv_call_state),
2472                 sizeof(struct dcesrv_auth),
2473                 sizeof(struct dcesrv_handle)
2474         };
2475
2476         return &critical_sizes;
2477 }
2478
2479 static void dcesrv_terminate_connection(struct dcesrv_connection *dce_conn, const char *reason)
2480 {
2481         struct dcesrv_context *dce_ctx = dce_conn->dce_ctx;
2482         struct stream_connection *srv_conn;
2483         srv_conn = talloc_get_type(dce_conn->transport.private_data,
2484                                    struct stream_connection);
2485
2486         dce_conn->wait_send = NULL;
2487         dce_conn->wait_recv = NULL;
2488         dce_conn->wait_private = NULL;
2489
2490         dce_conn->allow_bind = false;
2491         dce_conn->allow_alter = false;
2492
2493         dce_conn->default_auth_state->auth_invalid = true;
2494
2495         if (dce_conn->pending_call_list == NULL) {
2496                 char *full_reason = talloc_asprintf(dce_conn, "dcesrv: %s", reason);
2497
2498                 DLIST_REMOVE(dce_ctx->broken_connections, dce_conn);
2499                 stream_terminate_connection(srv_conn, full_reason ? full_reason : reason);
2500                 return;
2501         }
2502
2503         if (dce_conn->terminate != NULL) {
2504                 return;
2505         }
2506
2507         DEBUG(3,("dcesrv: terminating connection due to '%s' deferred due to pending calls\n",
2508                  reason));
2509         dce_conn->terminate = talloc_strdup(dce_conn, reason);
2510         if (dce_conn->terminate == NULL) {
2511                 dce_conn->terminate = "dcesrv: deferred terminating connection - no memory";
2512         }
2513         DLIST_ADD_END(dce_ctx->broken_connections, dce_conn);
2514 }
2515
2516 static void dcesrv_cleanup_broken_connections(struct dcesrv_context *dce_ctx)
2517 {
2518         struct dcesrv_connection *cur, *next;
2519
2520         next = dce_ctx->broken_connections;
2521         while (next != NULL) {
2522                 cur = next;
2523                 next = cur->next;
2524
2525                 if (cur->state_flags & DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL) {
2526                         struct dcesrv_connection_context *context_cur, *context_next;
2527
2528                         context_next = cur->contexts;
2529                         while (context_next != NULL) {
2530                                 context_cur = context_next;
2531                                 context_next = context_cur->next;
2532
2533                                 dcesrv_connection_context_destructor(context_cur);
2534                         }
2535                 }
2536
2537                 dcesrv_terminate_connection(cur, cur->terminate);
2538         }
2539 }
2540
2541 /* We need this include to be able to compile on some plateforms
2542  * (ie. freebsd 7.2) as it seems that <sys/uio.h> is not included
2543  * correctly.
2544  * It has to be that deep because otherwise we have a conflict on
2545  * const struct dcesrv_interface declaration.
2546  * This is mostly due to socket_wrapper defining #define bind swrap_bind
2547  * which conflict with the bind used before.
2548  */
2549 #include "system/network.h"
2550
2551 struct dcesrv_sock_reply_state {
2552         struct dcesrv_connection *dce_conn;
2553         struct dcesrv_call_state *call;
2554         struct iovec iov;
2555 };
2556
2557 static void dcesrv_sock_reply_done(struct tevent_req *subreq);
2558 static void dcesrv_call_terminate_step1(struct tevent_req *subreq);
2559
2560 static void dcesrv_sock_report_output_data(struct dcesrv_connection *dce_conn)
2561 {
2562         struct dcesrv_call_state *call;
2563
2564         call = dce_conn->call_list;
2565         if (!call || !call->replies) {
2566                 return;
2567         }
2568
2569         while (call->replies) {
2570                 struct data_blob_list_item *rep = call->replies;
2571                 struct dcesrv_sock_reply_state *substate;
2572                 struct tevent_req *subreq;
2573
2574                 substate = talloc_zero(call, struct dcesrv_sock_reply_state);
2575                 if (!substate) {
2576                         dcesrv_terminate_connection(dce_conn, "no memory");
2577                         return;
2578                 }
2579
2580                 substate->dce_conn = dce_conn;
2581                 substate->call = NULL;
2582
2583                 DLIST_REMOVE(call->replies, rep);
2584
2585                 if (call->replies == NULL && call->terminate_reason == NULL) {
2586                         substate->call = call;
2587                 }
2588
2589                 substate->iov.iov_base = (void *) rep->blob.data;
2590                 substate->iov.iov_len = rep->blob.length;
2591
2592                 subreq = tstream_writev_queue_send(substate,
2593                                                    dce_conn->event_ctx,
2594                                                    dce_conn->stream,
2595                                                    dce_conn->send_queue,
2596                                                    &substate->iov, 1);
2597                 if (!subreq) {
2598                         dcesrv_terminate_connection(dce_conn, "no memory");
2599                         return;
2600                 }
2601                 tevent_req_set_callback(subreq, dcesrv_sock_reply_done,
2602                                         substate);
2603         }
2604
2605         if (call->terminate_reason != NULL) {
2606                 struct tevent_req *subreq;
2607
2608                 subreq = tevent_queue_wait_send(call,
2609                                                 dce_conn->event_ctx,
2610                                                 dce_conn->send_queue);
2611                 if (!subreq) {
2612                         dcesrv_terminate_connection(dce_conn, __location__);
2613                         return;
2614                 }
2615                 tevent_req_set_callback(subreq, dcesrv_call_terminate_step1,
2616                                         call);
2617         }
2618
2619         DLIST_REMOVE(call->conn->call_list, call);
2620         call->list = DCESRV_LIST_NONE;
2621 }
2622
2623 static void dcesrv_sock_reply_done(struct tevent_req *subreq)
2624 {
2625         struct dcesrv_sock_reply_state *substate = tevent_req_callback_data(subreq,
2626                                                 struct dcesrv_sock_reply_state);
2627         int ret;
2628         int sys_errno;
2629         NTSTATUS status;
2630         struct dcesrv_call_state *call = substate->call;
2631
2632         ret = tstream_writev_queue_recv(subreq, &sys_errno);
2633         TALLOC_FREE(subreq);
2634         if (ret == -1) {
2635                 status = map_nt_error_from_unix_common(sys_errno);
2636                 dcesrv_terminate_connection(substate->dce_conn, nt_errstr(status));
2637                 return;
2638         }
2639
2640         talloc_free(substate);
2641         if (call) {
2642                 talloc_free(call);
2643         }
2644 }
2645
2646 static void dcesrv_call_terminate_step2(struct tevent_req *subreq);
2647
2648 static void dcesrv_call_terminate_step1(struct tevent_req *subreq)
2649 {
2650         struct dcesrv_call_state *call = tevent_req_callback_data(subreq,
2651                                                 struct dcesrv_call_state);
2652         bool ok;
2653         struct timeval tv;
2654
2655         /* make sure we stop send queue before removing subreq */
2656         tevent_queue_stop(call->conn->send_queue);
2657
2658         ok = tevent_queue_wait_recv(subreq);
2659         TALLOC_FREE(subreq);
2660         if (!ok) {
2661                 dcesrv_terminate_connection(call->conn, __location__);
2662                 return;
2663         }
2664
2665         /* disconnect after 200 usecs */
2666         tv = timeval_current_ofs_usec(200);
2667         subreq = tevent_wakeup_send(call, call->conn->event_ctx, tv);
2668         if (subreq == NULL) {
2669                 dcesrv_terminate_connection(call->conn, __location__);
2670                 return;
2671         }
2672         tevent_req_set_callback(subreq, dcesrv_call_terminate_step2,
2673                                 call);
2674 }
2675
2676 static void dcesrv_call_terminate_step2(struct tevent_req *subreq)
2677 {
2678         struct dcesrv_call_state *call = tevent_req_callback_data(subreq,
2679                                                 struct dcesrv_call_state);
2680         bool ok;
2681
2682         ok = tevent_wakeup_recv(subreq);
2683         TALLOC_FREE(subreq);
2684         if (!ok) {
2685                 dcesrv_terminate_connection(call->conn, __location__);
2686                 return;
2687         }
2688
2689         dcesrv_terminate_connection(call->conn, call->terminate_reason);
2690 }
2691
2692 struct dcesrv_socket_context {
2693         const struct dcesrv_endpoint *endpoint;
2694         struct dcesrv_context *dcesrv_ctx;
2695 };
2696
2697
2698 static void dcesrv_read_fragment_done(struct tevent_req *subreq);
2699
2700 static void dcesrv_sock_accept(struct stream_connection *srv_conn)
2701 {
2702         NTSTATUS status;
2703         struct dcesrv_socket_context *dcesrv_sock = 
2704                 talloc_get_type(srv_conn->private_data, struct dcesrv_socket_context);
2705         enum dcerpc_transport_t transport =
2706                 dcerpc_binding_get_transport(dcesrv_sock->endpoint->ep_description);
2707         struct dcesrv_connection *dcesrv_conn = NULL;
2708         int ret;
2709         struct tevent_req *subreq;
2710         struct loadparm_context *lp_ctx = dcesrv_sock->dcesrv_ctx->lp_ctx;
2711
2712         dcesrv_cleanup_broken_connections(dcesrv_sock->dcesrv_ctx);
2713
2714         if (!srv_conn->session_info) {
2715                 status = auth_anonymous_session_info(srv_conn,
2716                                                      lp_ctx,
2717                                                      &srv_conn->session_info);
2718                 if (!NT_STATUS_IS_OK(status)) {
2719                         DEBUG(0,("dcesrv_sock_accept: auth_anonymous_session_info failed: %s\n",
2720                                 nt_errstr(status)));
2721                         stream_terminate_connection(srv_conn, nt_errstr(status));
2722                         return;
2723                 }
2724         }
2725
2726         /*
2727          * This fills in dcesrv_conn->endpoint with the endpoint
2728          * associated with the socket.  From this point on we know
2729          * which (group of) services we are handling, but not the
2730          * specific interface.
2731          */
2732
2733         status = dcesrv_endpoint_connect(dcesrv_sock->dcesrv_ctx,
2734                                          srv_conn,
2735                                          dcesrv_sock->endpoint,
2736                                          srv_conn->session_info,
2737                                          srv_conn->event.ctx,
2738                                          srv_conn->msg_ctx,
2739                                          srv_conn->server_id,
2740                                          DCESRV_CALL_STATE_FLAG_MAY_ASYNC,
2741                                          &dcesrv_conn);
2742         if (!NT_STATUS_IS_OK(status)) {
2743                 DEBUG(0,("dcesrv_sock_accept: dcesrv_endpoint_connect failed: %s\n", 
2744                         nt_errstr(status)));
2745                 stream_terminate_connection(srv_conn, nt_errstr(status));
2746                 return;
2747         }
2748
2749         dcesrv_conn->transport.private_data             = srv_conn;
2750         dcesrv_conn->transport.report_output_data       = dcesrv_sock_report_output_data;
2751
2752         TALLOC_FREE(srv_conn->event.fde);
2753
2754         dcesrv_conn->send_queue = tevent_queue_create(dcesrv_conn, "dcesrv send queue");
2755         if (!dcesrv_conn->send_queue) {
2756                 status = NT_STATUS_NO_MEMORY;
2757                 DEBUG(0,("dcesrv_sock_accept: tevent_queue_create(%s)\n",
2758                         nt_errstr(status)));
2759                 stream_terminate_connection(srv_conn, nt_errstr(status));
2760                 return;
2761         }
2762
2763         if (transport == NCACN_NP) {
2764                 dcesrv_conn->stream = talloc_move(dcesrv_conn,
2765                                                   &srv_conn->tstream);
2766         } else {
2767                 ret = tstream_bsd_existing_socket(dcesrv_conn,
2768                                                   socket_get_fd(srv_conn->socket),
2769                                                   &dcesrv_conn->stream);
2770                 if (ret == -1) {
2771                         status = map_nt_error_from_unix_common(errno);
2772                         DEBUG(0, ("dcesrv_sock_accept: "
2773                                   "failed to setup tstream: %s\n",
2774                                   nt_errstr(status)));
2775                         stream_terminate_connection(srv_conn, nt_errstr(status));
2776                         return;
2777                 }
2778                 socket_set_flags(srv_conn->socket, SOCKET_FLAG_NOCLOSE);
2779         }
2780
2781         dcesrv_conn->local_address = srv_conn->local_address;
2782         dcesrv_conn->remote_address = srv_conn->remote_address;
2783
2784         if (transport == NCALRPC) {
2785                 uid_t uid;
2786                 gid_t gid;
2787                 int sock_fd;
2788
2789                 sock_fd = socket_get_fd(srv_conn->socket);
2790                 if (sock_fd == -1) {
2791                         stream_terminate_connection(
2792                                 srv_conn, "socket_get_fd failed\n");
2793                         return;
2794                 }
2795
2796                 ret = getpeereid(sock_fd, &uid, &gid);
2797                 if (ret == -1) {
2798                         status = map_nt_error_from_unix_common(errno);
2799                         DEBUG(0, ("dcesrv_sock_accept: "
2800                                   "getpeereid() failed for NCALRPC: %s\n",
2801                                   nt_errstr(status)));
2802                         stream_terminate_connection(srv_conn, nt_errstr(status));
2803                         return;
2804                 }
2805                 if (uid == dcesrv_conn->dce_ctx->initial_euid) {
2806                         struct tsocket_address *r = NULL;
2807
2808                         ret = tsocket_address_unix_from_path(dcesrv_conn,
2809                                                              AS_SYSTEM_MAGIC_PATH_TOKEN,
2810                                                              &r);
2811                         if (ret == -1) {
2812                                 status = map_nt_error_from_unix_common(errno);
2813                                 DEBUG(0, ("dcesrv_sock_accept: "
2814                                           "tsocket_address_unix_from_path() failed for NCALRPC: %s\n",
2815                                           nt_errstr(status)));
2816                                 stream_terminate_connection(srv_conn, nt_errstr(status));
2817                                 return;
2818                         }
2819                         dcesrv_conn->remote_address = r;
2820                 }
2821         }
2822
2823         srv_conn->private_data = dcesrv_conn;
2824
2825         subreq = dcerpc_read_ncacn_packet_send(dcesrv_conn,
2826                                                dcesrv_conn->event_ctx,
2827                                                dcesrv_conn->stream);
2828         if (!subreq) {
2829                 status = NT_STATUS_NO_MEMORY;
2830                 DEBUG(0,("dcesrv_sock_accept: dcerpc_read_fragment_buffer_send(%s)\n",
2831                         nt_errstr(status)));
2832                 stream_terminate_connection(srv_conn, nt_errstr(status));
2833                 return;
2834         }
2835         tevent_req_set_callback(subreq, dcesrv_read_fragment_done, dcesrv_conn);
2836
2837         return;
2838 }
2839
2840 static void dcesrv_conn_wait_done(struct tevent_req *subreq);
2841
2842 static void dcesrv_read_fragment_done(struct tevent_req *subreq)
2843 {
2844         struct dcesrv_connection *dce_conn = tevent_req_callback_data(subreq,
2845                                              struct dcesrv_connection);
2846         struct dcesrv_context *dce_ctx = dce_conn->dce_ctx;
2847         struct ncacn_packet *pkt;
2848         DATA_BLOB buffer;
2849         NTSTATUS status;
2850
2851         if (dce_conn->terminate) {
2852                 /*
2853                  * if the current connection is broken
2854                  * we need to clean it up before any other connection
2855                  */
2856                 dcesrv_terminate_connection(dce_conn, dce_conn->terminate);
2857                 dcesrv_cleanup_broken_connections(dce_ctx);
2858                 return;
2859         }
2860
2861         dcesrv_cleanup_broken_connections(dce_ctx);
2862
2863         status = dcerpc_read_ncacn_packet_recv(subreq, dce_conn,
2864                                                &pkt, &buffer);
2865         TALLOC_FREE(subreq);
2866         if (!NT_STATUS_IS_OK(status)) {
2867                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2868                 return;
2869         }
2870
2871         status = dcesrv_process_ncacn_packet(dce_conn, pkt, buffer);
2872         if (!NT_STATUS_IS_OK(status)) {
2873                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2874                 return;
2875         }
2876
2877         /*
2878          * This is used to block the connection during
2879          * pending authentication.
2880          */
2881         if (dce_conn->wait_send != NULL) {
2882                 subreq = dce_conn->wait_send(dce_conn,
2883                                              dce_conn->event_ctx,
2884                                              dce_conn->wait_private);
2885                 if (!subreq) {
2886                         status = NT_STATUS_NO_MEMORY;
2887                         dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2888                         return;
2889                 }
2890                 tevent_req_set_callback(subreq, dcesrv_conn_wait_done, dce_conn);
2891                 return;
2892         }
2893
2894         subreq = dcerpc_read_ncacn_packet_send(dce_conn,
2895                                                dce_conn->event_ctx,
2896                                                dce_conn->stream);
2897         if (!subreq) {
2898                 status = NT_STATUS_NO_MEMORY;
2899                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2900                 return;
2901         }
2902         tevent_req_set_callback(subreq, dcesrv_read_fragment_done, dce_conn);
2903 }
2904
2905 static void dcesrv_conn_wait_done(struct tevent_req *subreq)
2906 {
2907         struct dcesrv_connection *dce_conn = tevent_req_callback_data(subreq,
2908                                              struct dcesrv_connection);
2909         struct dcesrv_context *dce_ctx = dce_conn->dce_ctx;
2910         NTSTATUS status;
2911
2912         if (dce_conn->terminate) {
2913                 /*
2914                  * if the current connection is broken
2915                  * we need to clean it up before any other connection
2916                  */
2917                 dcesrv_terminate_connection(dce_conn, dce_conn->terminate);
2918                 dcesrv_cleanup_broken_connections(dce_ctx);
2919                 return;
2920         }
2921
2922         dcesrv_cleanup_broken_connections(dce_ctx);
2923
2924         status = dce_conn->wait_recv(subreq);
2925         dce_conn->wait_send = NULL;
2926         dce_conn->wait_recv = NULL;
2927         dce_conn->wait_private = NULL;
2928         TALLOC_FREE(subreq);
2929         if (!NT_STATUS_IS_OK(status)) {
2930                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2931                 return;
2932         }
2933
2934         subreq = dcerpc_read_ncacn_packet_send(dce_conn,
2935                                                dce_conn->event_ctx,
2936                                                dce_conn->stream);
2937         if (!subreq) {
2938                 status = NT_STATUS_NO_MEMORY;
2939                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2940                 return;
2941         }
2942         tevent_req_set_callback(subreq, dcesrv_read_fragment_done, dce_conn);
2943 }
2944
2945 static void dcesrv_sock_recv(struct stream_connection *conn, uint16_t flags)
2946 {
2947         struct dcesrv_connection *dce_conn = talloc_get_type(conn->private_data,
2948                                              struct dcesrv_connection);
2949         dcesrv_terminate_connection(dce_conn, "dcesrv_sock_recv triggered");
2950 }
2951
2952 static void dcesrv_sock_send(struct stream_connection *conn, uint16_t flags)
2953 {
2954         struct dcesrv_connection *dce_conn = talloc_get_type(conn->private_data,
2955                                              struct dcesrv_connection);
2956         dcesrv_terminate_connection(dce_conn, "dcesrv_sock_send triggered");
2957 }
2958
2959
2960 static const struct stream_server_ops dcesrv_stream_ops = {
2961         .name                   = "rpc",
2962         .accept_connection      = dcesrv_sock_accept,
2963         .recv_handler           = dcesrv_sock_recv,
2964         .send_handler           = dcesrv_sock_send,
2965 };
2966
2967 static NTSTATUS dcesrv_add_ep_unix(struct dcesrv_context *dce_ctx, 
2968                                    struct loadparm_context *lp_ctx,
2969                                    struct dcesrv_endpoint *e,
2970                                    struct tevent_context *event_ctx,
2971                                    const struct model_ops