Cleanup references to module objects returned from PyImport_ImportModule
[gd/samba-autobuild/.git] / source4 / librpc / rpc / dcerpc_util.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    dcerpc utility functions
5
6    Copyright (C) Andrew Tridgell 2003
7    Copyright (C) Jelmer Vernooij 2004
8    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
9    Copyright (C) Rafal Szczesniak 2006
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "lib/events/events.h"
27 #include "libcli/composite/composite.h"
28 #include "librpc/gen_ndr/ndr_epmapper_c.h"
29 #include "librpc/gen_ndr/ndr_dcerpc.h"
30 #include "librpc/gen_ndr/ndr_misc.h"
31 #include "librpc/rpc/dcerpc_proto.h"
32 #include "auth/credentials/credentials.h"
33 #include "auth/gensec/gensec.h"
34 #include "param/param.h"
35 #include "librpc/rpc/rpc_common.h"
36
37 /*
38   find a dcerpc call on an interface by name
39 */
40 const struct ndr_interface_call *dcerpc_iface_find_call(const struct ndr_interface_table *iface,
41                                                         const char *name)
42 {
43         int i;
44         for (i=0;i<iface->num_calls;i++) {
45                 if (strcmp(iface->calls[i].name, name) == 0) {
46                         return &iface->calls[i];
47                 }
48         }
49         return NULL;
50 }
51
52 /* 
53    push a ncacn_packet into a blob, potentially with auth info
54 */
55 NTSTATUS ncacn_push_auth(DATA_BLOB *blob, TALLOC_CTX *mem_ctx, 
56                          struct ncacn_packet *pkt,
57                          struct dcerpc_auth *auth_info)
58 {
59         struct ndr_push *ndr;
60         enum ndr_err_code ndr_err;
61
62         ndr = ndr_push_init_ctx(mem_ctx);
63         if (!ndr) {
64                 return NT_STATUS_NO_MEMORY;
65         }
66
67         if (auth_info) {
68                 pkt->auth_length = auth_info->credentials.length;
69         } else {
70                 pkt->auth_length = 0;
71         }
72
73         ndr_err = ndr_push_ncacn_packet(ndr, NDR_SCALARS|NDR_BUFFERS, pkt);
74         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
75                 return ndr_map_error2ntstatus(ndr_err);
76         }
77
78         if (auth_info) {
79 #if 0
80                 /* the s3 rpc server doesn't handle auth padding in
81                    bind requests. Use zero auth padding to keep us
82                    working with old servers */
83                 uint32_t offset = ndr->offset;
84                 ndr_err = ndr_push_align(ndr, 16);
85                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
86                         return ndr_map_error2ntstatus(ndr_err);
87                 }
88                 auth_info->auth_pad_length = ndr->offset - offset;
89 #else
90                 auth_info->auth_pad_length = 0;
91 #endif
92                 ndr_err = ndr_push_dcerpc_auth(ndr, NDR_SCALARS|NDR_BUFFERS, auth_info);
93                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
94                         return ndr_map_error2ntstatus(ndr_err);
95                 }
96         }
97
98         *blob = ndr_push_blob(ndr);
99
100         /* fill in the frag length */
101         dcerpc_set_frag_length(blob, blob->length);
102
103         return NT_STATUS_OK;
104 }
105
106
107 struct epm_map_binding_state {
108         struct dcerpc_binding *binding;
109         const struct ndr_interface_table *table;
110         struct dcerpc_pipe *pipe;
111         struct policy_handle handle;
112         struct GUID object;
113         struct epm_twr_t twr;
114         struct epm_twr_t *twr_r;
115         uint32_t num_towers;
116         struct epm_Map r;
117 };
118
119
120 static void continue_epm_recv_binding(struct composite_context *ctx);
121 static void continue_epm_map(struct tevent_req *subreq);
122
123
124 /*
125   Stage 2 of epm_map_binding: Receive connected rpc pipe and send endpoint
126   mapping rpc request
127 */
128 static void continue_epm_recv_binding(struct composite_context *ctx)
129 {
130         struct composite_context *c = talloc_get_type(ctx->async.private_data,
131                                                       struct composite_context);
132         struct epm_map_binding_state *s = talloc_get_type(c->private_data,
133                                                           struct epm_map_binding_state);
134         struct tevent_req *subreq;
135
136         /* receive result of rpc pipe connect request */
137         c->status = dcerpc_pipe_connect_b_recv(ctx, c, &s->pipe);
138         if (!composite_is_ok(c)) return;
139
140         c->status = dcerpc_binding_build_tower(s->pipe, s->binding, &s->twr.tower);
141         if (!composite_is_ok(c)) return;
142         
143         /* with some nice pretty paper around it of course */
144         s->r.in.object        = &s->object;
145         s->r.in.map_tower     = &s->twr;
146         s->r.in.entry_handle  = &s->handle;
147         s->r.in.max_towers    = 1;
148         s->r.out.entry_handle = &s->handle;
149         s->r.out.num_towers   = &s->num_towers;
150
151         /* send request for an endpoint mapping - a rpc request on connected pipe */
152         subreq = dcerpc_epm_Map_r_send(s, c->event_ctx,
153                                        s->pipe->binding_handle,
154                                        &s->r);
155         if (composite_nomem(subreq, c)) return;
156         
157         tevent_req_set_callback(subreq, continue_epm_map, c);
158 }
159
160
161 /*
162   Stage 3 of epm_map_binding: Receive endpoint mapping and provide binding details
163 */
164 static void continue_epm_map(struct tevent_req *subreq)
165 {
166         struct composite_context *c = tevent_req_callback_data(subreq,
167                                       struct composite_context);
168         struct epm_map_binding_state *s = talloc_get_type(c->private_data,
169                                                           struct epm_map_binding_state);
170         const char *endpoint;
171
172         /* receive result of a rpc request */
173         c->status = dcerpc_epm_Map_r_recv(subreq, s);
174         TALLOC_FREE(subreq);
175         if (!composite_is_ok(c)) return;
176
177         /* check the details */
178         if (s->r.out.result != 0 || *s->r.out.num_towers != 1) {
179                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
180                 return;
181         }
182         
183         s->twr_r = s->r.out.towers[0].twr;
184         if (s->twr_r == NULL) {
185                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
186                 return;
187         }
188
189         if (s->twr_r->tower.num_floors != s->twr.tower.num_floors ||
190             s->twr_r->tower.floors[3].lhs.protocol != s->twr.tower.floors[3].lhs.protocol) {
191                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
192                 return;
193         }
194
195         /* get received endpoint */
196         endpoint = dcerpc_floor_get_rhs_data(s, &s->twr_r->tower.floors[3]);
197         if (composite_nomem(endpoint, c)) return;
198
199         c->status = dcerpc_binding_set_string_option(s->binding,
200                                                      "endpoint",
201                                                      endpoint);
202         if (!composite_is_ok(c)) {
203                 return;
204         }
205
206         composite_done(c);
207 }
208
209
210 /*
211   Request for endpoint mapping of dcerpc binding - try to request for endpoint
212   unless there is default one.
213 */
214 struct composite_context *dcerpc_epm_map_binding_send(TALLOC_CTX *mem_ctx,
215                                                       struct dcerpc_binding *binding,
216                                                       const struct ndr_interface_table *table,
217                                                       struct cli_credentials *creds,
218                                                       struct tevent_context *ev,
219                                                       struct loadparm_context *lp_ctx)
220 {
221         struct composite_context *c;
222         struct epm_map_binding_state *s;
223         struct composite_context *pipe_connect_req;
224         NTSTATUS status;
225         struct dcerpc_binding *epmapper_binding;
226         int i;
227
228         if (ev == NULL) {
229                 return NULL;
230         }
231
232         /* composite context allocation and setup */
233         c = composite_create(mem_ctx, ev);
234         if (c == NULL) {
235                 return NULL;
236         }
237
238         s = talloc_zero(c, struct epm_map_binding_state);
239         if (composite_nomem(s, c)) return c;
240         c->private_data = s;
241
242         s->binding = binding;
243         s->object  = dcerpc_binding_get_object(binding);
244         s->table   = table;
245
246         c->status = dcerpc_binding_set_abstract_syntax(binding,
247                                                        &table->syntax_id);
248         if (!composite_is_ok(c)) {
249                 return c;
250         }
251
252         /*
253           First, check if there is a default endpoint specified in the IDL
254         */
255         for (i = 0; i < table->endpoints->count; i++) {
256                 struct dcerpc_binding *default_binding;
257                 enum dcerpc_transport_t transport;
258                 enum dcerpc_transport_t dtransport;
259                 const char *dendpoint = NULL;
260
261                 status = dcerpc_parse_binding(s,
262                                               table->endpoints->names[i],
263                                               &default_binding);
264                 if (!NT_STATUS_IS_OK(status)) {
265                         continue;
266                 }
267
268                 transport = dcerpc_binding_get_transport(binding);
269                 dtransport = dcerpc_binding_get_transport(default_binding);
270                 if (transport == NCA_UNKNOWN) {
271                         c->status = dcerpc_binding_set_transport(binding,
272                                                                  dtransport);
273                         if (!composite_is_ok(c)) {
274                                 return c;
275                         }
276                         transport = dtransport;
277                 }
278
279                 if (transport != dtransport) {
280                         TALLOC_FREE(default_binding);
281                         continue;
282                 }
283
284                 dendpoint = dcerpc_binding_get_string_option(default_binding,
285                                                              "endpoint");
286                 if (dendpoint == NULL) {
287                         TALLOC_FREE(default_binding);
288                         continue;
289                 }
290
291                 c->status = dcerpc_binding_set_string_option(binding,
292                                                              "endpoint",
293                                                              dendpoint);
294                 if (!composite_is_ok(c)) {
295                         return c;
296                 }
297
298                 TALLOC_FREE(default_binding);
299                 composite_done(c);
300                 return c;
301         }
302
303         epmapper_binding = dcerpc_binding_dup(s, binding);
304         if (composite_nomem(epmapper_binding, c)) return c;
305
306         /* basic endpoint mapping data */
307         c->status = dcerpc_binding_set_string_option(epmapper_binding,
308                                                      "endpoint", NULL);
309         if (!composite_is_ok(c)) {
310                 return c;
311         }
312         c->status = dcerpc_binding_set_flags(epmapper_binding, 0, UINT32_MAX);
313         if (!composite_is_ok(c)) {
314                 return c;
315         }
316         c->status = dcerpc_binding_set_assoc_group_id(epmapper_binding, 0);
317         if (!composite_is_ok(c)) {
318                 return c;
319         }
320         c->status = dcerpc_binding_set_object(epmapper_binding, GUID_zero());
321         if (!composite_is_ok(c)) {
322                 return c;
323         }
324
325         /* initiate rpc pipe connection */
326         pipe_connect_req = dcerpc_pipe_connect_b_send(s, epmapper_binding,
327                                                       &ndr_table_epmapper,
328                                                       creds, c->event_ctx,
329                                                       lp_ctx);
330         if (composite_nomem(pipe_connect_req, c)) return c;
331         
332         composite_continue(c, pipe_connect_req, continue_epm_recv_binding, c);
333         return c;
334 }
335
336
337 /*
338   Receive result of endpoint mapping request
339  */
340 NTSTATUS dcerpc_epm_map_binding_recv(struct composite_context *c)
341 {
342         NTSTATUS status = composite_wait(c);
343         
344         talloc_free(c);
345         return status;
346 }
347
348
349 /*
350   Get endpoint mapping for rpc connection
351 */
352 _PUBLIC_ NTSTATUS dcerpc_epm_map_binding(TALLOC_CTX *mem_ctx, struct dcerpc_binding *binding,
353                                 const struct ndr_interface_table *table, struct tevent_context *ev,
354                                 struct loadparm_context *lp_ctx)
355 {
356         struct composite_context *c;
357         struct cli_credentials *epm_creds;
358
359         epm_creds = cli_credentials_init_anon(mem_ctx);
360         if (epm_creds == NULL) {
361                 return NT_STATUS_NO_MEMORY;
362         }
363         c = dcerpc_epm_map_binding_send(mem_ctx, binding, table, epm_creds, ev, lp_ctx);
364         if (c == NULL) {
365                 talloc_free(epm_creds);
366                 return NT_STATUS_NO_MEMORY;
367         }
368         talloc_steal(c, epm_creds);
369         return dcerpc_epm_map_binding_recv(c);
370 }
371
372
373 struct pipe_auth_state {
374         struct dcerpc_pipe *pipe;
375         const struct dcerpc_binding *binding;
376         const struct ndr_interface_table *table;
377         struct loadparm_context *lp_ctx;
378         struct cli_credentials *credentials;
379         unsigned int logon_retries;
380 };
381
382
383 static void continue_auth_schannel(struct composite_context *ctx);
384 static void continue_auth(struct composite_context *ctx);
385 static void continue_auth_none(struct composite_context *ctx);
386 static void continue_ntlmssp_connection(struct composite_context *ctx);
387 static void continue_spnego_after_wrong_pass(struct composite_context *ctx);
388
389
390 /*
391   Stage 2 of pipe_auth: Receive result of schannel bind request
392 */
393 static void continue_auth_schannel(struct composite_context *ctx)
394 {
395         struct composite_context *c = talloc_get_type(ctx->async.private_data,
396                                                       struct composite_context);
397
398         c->status = dcerpc_bind_auth_schannel_recv(ctx);
399         if (!composite_is_ok(c)) return;
400
401         composite_done(c);
402 }
403
404
405 /*
406   Stage 2 of pipe_auth: Receive result of authenticated bind request
407 */
408 static void continue_auth(struct composite_context *ctx)
409 {
410         struct composite_context *c = talloc_get_type(ctx->async.private_data,
411                                                       struct composite_context);
412
413         c->status = dcerpc_bind_auth_recv(ctx);
414         if (!composite_is_ok(c)) return;
415         
416         composite_done(c);
417 }
418 /*
419   Stage 2 of pipe_auth: Receive result of authenticated bind request, but handle fallbacks:
420   SPNEGO -> NTLMSSP
421 */
422 static void continue_auth_auto(struct composite_context *ctx)
423 {
424         struct composite_context *c = talloc_get_type(ctx->async.private_data,
425                                                       struct composite_context);
426         struct pipe_auth_state *s = talloc_get_type(c->private_data, struct pipe_auth_state);
427         struct composite_context *sec_conn_req;
428
429         c->status = dcerpc_bind_auth_recv(ctx);
430         if (NT_STATUS_EQUAL(c->status, NT_STATUS_INVALID_PARAMETER)) {
431                 /*
432                  * Retry with NTLMSSP auth as fallback
433                  * send a request for secondary rpc connection
434                  */
435                 sec_conn_req = dcerpc_secondary_connection_send(s->pipe,
436                                                                 s->binding);
437                 composite_continue(c, sec_conn_req, continue_ntlmssp_connection, c);
438                 return;
439         } else if (NT_STATUS_EQUAL(c->status, NT_STATUS_LOGON_FAILURE) ||
440                    NT_STATUS_EQUAL(c->status, NT_STATUS_UNSUCCESSFUL)) {
441                 /*
442                   try a second time on any error. We don't just do it
443                   on LOGON_FAILURE as some servers will give a
444                   NT_STATUS_UNSUCCESSFUL on a authentication error on RPC
445                  */
446                 const char *principal;
447                 const char *endpoint;
448
449                 principal = gensec_get_target_principal(s->pipe->conn->security_state.generic_state);
450                 if (principal == NULL) {
451                         const char *hostname = gensec_get_target_hostname(s->pipe->conn->security_state.generic_state);
452                         const char *service  = gensec_get_target_service(s->pipe->conn->security_state.generic_state);
453                         if (hostname != NULL && service != NULL) {
454                                 principal = talloc_asprintf(c, "%s/%s", service, hostname);
455                         }
456                 }
457
458                 endpoint = dcerpc_binding_get_string_option(s->binding, "endpoint");
459
460                 if ((cli_credentials_failed_kerberos_login(s->credentials, principal, &s->logon_retries) ||
461                      cli_credentials_wrong_password(s->credentials)) &&
462                     endpoint != NULL) {
463                         /*
464                          * Retry SPNEGO with a better password
465                          * send a request for secondary rpc connection
466                          */
467                         sec_conn_req = dcerpc_secondary_connection_send(s->pipe,
468                                                                         s->binding);
469                         composite_continue(c, sec_conn_req, continue_spnego_after_wrong_pass, c);
470                         return;
471                 }
472         }
473
474         if (!composite_is_ok(c)) return;
475
476         composite_done(c);
477 }
478
479 /*
480   Stage 3 of pipe_auth (fallback to NTLMSSP case): Receive secondary
481   rpc connection (the first one can't be used any more, due to the
482   bind nak) and perform authenticated bind request
483 */
484 static void continue_ntlmssp_connection(struct composite_context *ctx)
485 {
486         struct composite_context *c;
487         struct pipe_auth_state *s;
488         struct composite_context *auth_req;
489         struct dcerpc_pipe *p2;
490         void *pp;
491
492         c = talloc_get_type(ctx->async.private_data, struct composite_context);
493         s = talloc_get_type(c->private_data, struct pipe_auth_state);
494
495         /* receive secondary rpc connection */
496         c->status = dcerpc_secondary_connection_recv(ctx, &p2);
497         if (!composite_is_ok(c)) return;
498
499
500         /* this is a rather strange situation. When
501            we come into the routine, s is a child of s->pipe, and
502            when we created p2 above, it also became a child of
503            s->pipe.
504
505            Now we want p2 to be a parent of s->pipe, and we want s to
506            be a parent of both of them! If we don't do this very
507            carefully we end up creating a talloc loop
508         */
509
510         /* we need the new contexts to hang off the same context
511            that s->pipe is on, but the only way to get that is
512            via talloc_parent() */
513         pp = talloc_parent(s->pipe);
514
515         /* promote s to be at the top */
516         talloc_steal(pp, s);
517
518         /* and put p2 under s */
519         talloc_steal(s, p2);
520
521         /* now put s->pipe under p2 */
522         talloc_steal(p2, s->pipe);
523
524         s->pipe = p2;
525
526         /* initiate a authenticated bind */
527         auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
528                                          s->credentials, 
529                                          lpcfg_gensec_settings(c, s->lp_ctx),
530                                          DCERPC_AUTH_TYPE_NTLMSSP,
531                                          dcerpc_auth_level(s->pipe->conn),
532                                          s->table->authservices->names[0]);
533         composite_continue(c, auth_req, continue_auth, c);
534 }
535
536 /*
537   Stage 3 of pipe_auth (retry on wrong password): Receive secondary
538   rpc connection (the first one can't be used any more, due to the
539   bind nak) and perform authenticated bind request
540 */
541 static void continue_spnego_after_wrong_pass(struct composite_context *ctx)
542 {
543         struct composite_context *c;
544         struct pipe_auth_state *s;
545         struct composite_context *auth_req;
546         struct dcerpc_pipe *p2;
547
548         c = talloc_get_type(ctx->async.private_data, struct composite_context);
549         s = talloc_get_type(c->private_data, struct pipe_auth_state);
550
551         /* receive secondary rpc connection */
552         c->status = dcerpc_secondary_connection_recv(ctx, &p2);
553         if (!composite_is_ok(c)) return;
554
555         talloc_steal(s, p2);
556         talloc_steal(p2, s->pipe);
557         s->pipe = p2;
558
559         /* initiate a authenticated bind */
560         auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
561                                          s->credentials, 
562                                          lpcfg_gensec_settings(c, s->lp_ctx),
563                                          DCERPC_AUTH_TYPE_SPNEGO,
564                                          dcerpc_auth_level(s->pipe->conn),
565                                          s->table->authservices->names[0]);
566         composite_continue(c, auth_req, continue_auth, c);
567 }
568
569
570 /*
571   Stage 2 of pipe_auth: Receive result of non-authenticated bind request
572 */
573 static void continue_auth_none(struct composite_context *ctx)
574 {
575         struct composite_context *c = talloc_get_type(ctx->async.private_data,
576                                                       struct composite_context);
577
578         c->status = dcerpc_bind_auth_none_recv(ctx);
579         if (!composite_is_ok(c)) return;
580         
581         composite_done(c);
582 }
583
584
585 /*
586   Request to perform an authenticated bind if required. Authentication
587   is determined using credentials passed and binding flags.
588 */
589 struct composite_context *dcerpc_pipe_auth_send(struct dcerpc_pipe *p, 
590                                                 const struct dcerpc_binding *binding,
591                                                 const struct ndr_interface_table *table,
592                                                 struct cli_credentials *credentials,
593                                                 struct loadparm_context *lp_ctx)
594 {
595         struct composite_context *c;
596         struct pipe_auth_state *s;
597         struct composite_context *auth_schannel_req;
598         struct composite_context *auth_req;
599         struct composite_context *auth_none_req;
600         struct dcecli_connection *conn;
601         uint8_t auth_type;
602
603         /* composite context allocation and setup */
604         c = composite_create(p, p->conn->event_ctx);
605         if (c == NULL) return NULL;
606
607         s = talloc_zero(c, struct pipe_auth_state);
608         if (composite_nomem(s, c)) return c;
609         c->private_data = s;
610
611         /* store parameters in state structure */
612         s->binding      = binding;
613         s->table        = table;
614         s->credentials  = credentials;
615         s->pipe         = p;
616         s->lp_ctx       = lp_ctx;
617
618         conn = s->pipe->conn;
619         conn->flags = dcerpc_binding_get_flags(binding);
620
621         if (DEBUGLVL(100)) {
622                 conn->flags |= DCERPC_DEBUG_PRINT_BOTH;
623         }
624
625         if (conn->transport.transport == NCALRPC) {
626                 const char *v = dcerpc_binding_get_string_option(binding,
627                                                         "auth_type");
628
629                 if (v != NULL && strcmp(v, "ncalrpc_as_system") == 0) {
630                         auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
631                                                  s->credentials,
632                                                  lpcfg_gensec_settings(c, s->lp_ctx),
633                                                  DCERPC_AUTH_TYPE_NCALRPC_AS_SYSTEM,
634                                                  DCERPC_AUTH_LEVEL_CONNECT,
635                                                  s->table->authservices->names[0]);
636                         composite_continue(c, auth_req, continue_auth, c);
637                         return c;
638                 }
639         }
640
641         if (cli_credentials_is_anonymous(s->credentials)) {
642                 auth_none_req = dcerpc_bind_auth_none_send(c, s->pipe, s->table);
643                 composite_continue(c, auth_none_req, continue_auth_none, c);
644                 return c;
645         }
646
647         if ((conn->flags & DCERPC_SCHANNEL) &&
648             !cli_credentials_get_netlogon_creds(s->credentials)) {
649                 /* If we don't already have netlogon credentials for
650                  * the schannel bind, then we have to get these
651                  * first */
652                 auth_schannel_req = dcerpc_bind_auth_schannel_send(c, s->pipe, s->table,
653                                                                    s->credentials, s->lp_ctx,
654                                                                    dcerpc_auth_level(conn));
655                 composite_continue(c, auth_schannel_req, continue_auth_schannel, c);
656                 return c;
657         }
658
659         /*
660          * we rely on the already authenticated CIFS connection
661          * if not doing sign or seal
662          */
663         if (conn->transport.transport == NCACN_NP &&
664             !(conn->flags & (DCERPC_PACKET|DCERPC_SIGN|DCERPC_SEAL))) {
665                 auth_none_req = dcerpc_bind_auth_none_send(c, s->pipe, s->table);
666                 composite_continue(c, auth_none_req, continue_auth_none, c);
667                 return c;
668         }
669
670
671         /* Perform an authenticated DCE-RPC bind
672          */
673         if (!(conn->flags & (DCERPC_CONNECT|DCERPC_SEAL|DCERPC_PACKET))) {
674                 /*
675                   we are doing an authenticated connection,
676                   which needs to use [connect], [sign] or [seal].
677                   If nothing is specified, we default to [sign] now.
678                   This give roughly the same protection as
679                   ncacn_np with smb signing.
680                 */
681                 conn->flags |= DCERPC_SIGN;
682         }
683
684         if (conn->flags & DCERPC_AUTH_SPNEGO) {
685                 auth_type = DCERPC_AUTH_TYPE_SPNEGO;
686
687         } else if (conn->flags & DCERPC_AUTH_KRB5) {
688                 auth_type = DCERPC_AUTH_TYPE_KRB5;
689
690         } else if (conn->flags & DCERPC_SCHANNEL) {
691                 auth_type = DCERPC_AUTH_TYPE_SCHANNEL;
692
693         } else if (conn->flags & DCERPC_AUTH_NTLM) {
694                 auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
695
696         } else {
697                 /* try SPNEGO with fallback to NTLMSSP */
698                 auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
699                                                  s->credentials, 
700                                                  lpcfg_gensec_settings(c, s->lp_ctx),
701                                                  DCERPC_AUTH_TYPE_SPNEGO,
702                                                  dcerpc_auth_level(conn),
703                                                  s->table->authservices->names[0]);
704                 composite_continue(c, auth_req, continue_auth_auto, c);
705                 return c;
706         }
707
708         auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
709                                          s->credentials, 
710                                          lpcfg_gensec_settings(c, s->lp_ctx),
711                                          auth_type,
712                                          dcerpc_auth_level(conn),
713                                          s->table->authservices->names[0]);
714         composite_continue(c, auth_req, continue_auth, c);
715         return c;
716 }
717
718
719 /*
720   Receive result of authenticated bind request on dcerpc pipe
721
722   This returns *p, which may be different to the one originally
723   supllied, as it rebinds to a new pipe due to authentication fallback
724
725 */
726 NTSTATUS dcerpc_pipe_auth_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, 
727                                struct dcerpc_pipe **p)
728 {
729         NTSTATUS status;
730
731         struct pipe_auth_state *s = talloc_get_type(c->private_data,
732                                                     struct pipe_auth_state);
733         status = composite_wait(c);
734         if (!NT_STATUS_IS_OK(status)) {
735                 char *uuid_str = GUID_string(s->pipe, &s->table->syntax_id.uuid);
736                 DEBUG(0, ("Failed to bind to uuid %s for %s %s\n", uuid_str,
737                           dcerpc_binding_string(uuid_str, s->binding), nt_errstr(status)));
738                 talloc_free(uuid_str);
739         } else {
740                 talloc_steal(mem_ctx, s->pipe);
741                 *p = s->pipe;
742         }
743
744         talloc_free(c);
745         return status;
746 }
747
748
749 /* 
750    Perform an authenticated bind if needed - sync version
751
752    This may change *p, as it rebinds to a new pipe due to authentication fallback
753 */
754 _PUBLIC_ NTSTATUS dcerpc_pipe_auth(TALLOC_CTX *mem_ctx,
755                           struct dcerpc_pipe **p, 
756                           const struct dcerpc_binding *binding,
757                           const struct ndr_interface_table *table,
758                           struct cli_credentials *credentials,
759                           struct loadparm_context *lp_ctx)
760 {
761         struct composite_context *c;
762
763         c = dcerpc_pipe_auth_send(*p, binding, table, credentials, lp_ctx);
764         return dcerpc_pipe_auth_recv(c, mem_ctx, p);
765 }
766
767
768 NTSTATUS dcerpc_generic_session_key(struct dcecli_connection *c,
769                                     DATA_BLOB *session_key)
770 {
771         *session_key = data_blob_null;
772
773         if (c != NULL) {
774                 if (c->transport.transport != NCALRPC &&
775                     c->transport.transport != NCACN_UNIX_STREAM)
776                 {
777                         return NT_STATUS_LOCAL_USER_SESSION_KEY;
778                 }
779         }
780
781         /* this took quite a few CPU cycles to find ... */
782         session_key->data = discard_const_p(unsigned char, "SystemLibraryDTC");
783         session_key->length = 16;
784         return NT_STATUS_OK;
785 }
786
787 /*
788   fetch the user session key - may be default (above) or the SMB session key
789
790   The key is always truncated to 16 bytes 
791 */
792 _PUBLIC_ NTSTATUS dcerpc_fetch_session_key(struct dcerpc_pipe *p,
793                                            DATA_BLOB *session_key)
794 {
795         NTSTATUS status;
796         status = p->conn->security_state.session_key(p->conn, session_key);
797         if (!NT_STATUS_IS_OK(status)) {
798                 return status;
799         }
800
801         session_key->length = MIN(session_key->length, 16);
802
803         return NT_STATUS_OK;
804 }
805
806
807 /*
808   log a rpc packet in a format suitable for ndrdump. This is especially useful
809   for sealed packets, where ethereal cannot easily see the contents
810
811   this triggers on a debug level of >= 10
812 */
813 _PUBLIC_ void dcerpc_log_packet(const char *lockdir,
814                                 const struct ndr_interface_table *ndr,
815                                 uint32_t opnum, uint32_t flags,
816                                 const DATA_BLOB *pkt)
817 {
818         const int num_examples = 20;
819         int i;
820
821         if (lockdir == NULL) return;
822
823         for (i=0;i<num_examples;i++) {
824                 char *name=NULL;
825                 int ret;
826                 ret = asprintf(&name, "%s/rpclog/%s-%u.%d.%s",
827                                lockdir, ndr->name, opnum, i,
828                                (flags&NDR_IN)?"in":"out");
829                 if (ret == -1) {
830                         return;
831                 }
832                 if (!file_exist(name)) {
833                         if (file_save(name, pkt->data, pkt->length)) {
834                                 DEBUG(10,("Logged rpc packet to %s\n", name));
835                         }
836                         free(name);
837                         break;
838                 }
839                 free(name);
840         }
841 }
842
843
844
845 /*
846   create a secondary context from a primary connection
847
848   this uses dcerpc_alter_context() to create a new dcerpc context_id
849 */
850 _PUBLIC_ NTSTATUS dcerpc_secondary_context(struct dcerpc_pipe *p, 
851                                   struct dcerpc_pipe **pp2,
852                                   const struct ndr_interface_table *table)
853 {
854         NTSTATUS status;
855         struct dcerpc_pipe *p2;
856         struct GUID *object = NULL;
857         
858         p2 = talloc_zero(p, struct dcerpc_pipe);
859         if (p2 == NULL) {
860                 return NT_STATUS_NO_MEMORY;
861         }
862         p2->conn = talloc_reference(p2, p->conn);
863         p2->request_timeout = p->request_timeout;
864
865         p2->context_id = ++p->conn->next_context_id;
866
867         p2->syntax = table->syntax_id;
868
869         p2->transfer_syntax = p->transfer_syntax;
870
871         p2->binding = dcerpc_binding_dup(p2, p->binding);
872         if (p2->binding == NULL) {
873                 talloc_free(p2);
874                 return NT_STATUS_NO_MEMORY;
875         }
876
877         p2->object = dcerpc_binding_get_object(p2->binding);
878         if (!GUID_all_zero(&p2->object)) {
879                 object = &p2->object;
880         }
881
882         p2->binding_handle = dcerpc_pipe_binding_handle(p2, object, table);
883         if (p2->binding_handle == NULL) {
884                 talloc_free(p2);
885                 return NT_STATUS_NO_MEMORY;
886         }
887
888         status = dcerpc_alter_context(p2, p2, &p2->syntax, &p2->transfer_syntax);
889         if (!NT_STATUS_IS_OK(status)) {
890                 talloc_free(p2);
891                 return status;
892         }
893
894         *pp2 = p2;
895
896         return NT_STATUS_OK;
897 }