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