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