s3-rpc_server read and write the unix_token and unix_info across named_pipe_auth
[amitay/samba.git] / source3 / rpc_server / rpc_server.c
1 /*
2    Unix SMB/Netbios implementation.
3    Generic infrstructure for RPC Daemons
4    Copyright (C) Simo Sorce 2010
5    Copyright (C) Andrew Bartlett 2011
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "ntdomain.h"
23 #include "rpc_server/rpc_server.h"
24 #include "rpc_dce.h"
25 #include "librpc/gen_ndr/netlogon.h"
26 #include "librpc/gen_ndr/auth.h"
27 #include "lib/tsocket/tsocket.h"
28 #include "libcli/named_pipe_auth/npa_tstream.h"
29 #include "../auth/auth_sam_reply.h"
30 #include "auth.h"
31 #include "rpc_server/rpc_ncacn_np.h"
32 #include "rpc_server/srv_pipe_hnd.h"
33 #include "rpc_server/srv_pipe.h"
34
35 #define SERVER_TCP_LOW_PORT  1024
36 #define SERVER_TCP_HIGH_PORT 1300
37
38 static NTSTATUS auth_anonymous_session_info(TALLOC_CTX *mem_ctx,
39                                             struct auth_session_info **session_info)
40 {
41         struct auth_session_info *i;
42         struct auth3_session_info *s;
43         struct auth_user_info_dc *u;
44         union netr_Validation val;
45         NTSTATUS status;
46
47         i = talloc_zero(mem_ctx, struct auth_session_info);
48         if (i == NULL) {
49                 return NT_STATUS_NO_MEMORY;
50         }
51
52         status = make_session_info_guest(i, &s);
53         if (!NT_STATUS_IS_OK(status)) {
54                 return status;
55         }
56
57         i->security_token = s->security_token;
58         i->session_key    = s->session_key;
59
60         val.sam3 = s->info3;
61
62         status = make_user_info_dc_netlogon_validation(mem_ctx,
63                                                        "",
64                                                        3,
65                                                        &val,
66                                                        &u);
67         if (!NT_STATUS_IS_OK(status)) {
68                 DEBUG(0, ("conversion of info3 into user_info_dc failed!\n"));
69                 return status;
70         }
71         i->info = talloc_move(i, &u->info);
72         talloc_free(u);
73
74         *session_info = i;
75
76         return NT_STATUS_OK;
77 }
78
79 /* Creates a pipes_struct and initializes it with the information
80  * sent from the client */
81 static int make_server_pipes_struct(TALLOC_CTX *mem_ctx,
82                                     const char *pipe_name,
83                                     enum dcerpc_transport_t transport,
84                                     bool ncalrpc_as_system,
85                                     const struct tsocket_address *local_address,
86                                     const struct tsocket_address *remote_address,
87                                     struct auth_session_info *session_info,
88                                     struct pipes_struct **_p,
89                                     int *perrno)
90 {
91         struct netr_SamInfo3 *info3;
92         struct auth_user_info_dc *auth_user_info_dc;
93         struct pipes_struct *p;
94         NTSTATUS status;
95
96         p = talloc_zero(mem_ctx, struct pipes_struct);
97         if (!p) {
98                 *perrno = ENOMEM;
99                 return -1;
100         }
101
102         p->transport = transport;
103         p->ncalrpc_as_system = ncalrpc_as_system;
104
105         p->mem_ctx = talloc_named(p, 0, "pipe %s %p", pipe_name, p);
106         if (!p->mem_ctx) {
107                 TALLOC_FREE(p);
108                 *perrno = ENOMEM;
109                 return -1;
110         }
111
112         data_blob_free(&p->in_data.data);
113         data_blob_free(&p->in_data.pdu);
114
115         p->endian = RPC_LITTLE_ENDIAN;
116
117         /* Fake up an auth_user_info_dc for now, to make an info3, to make the session_info structure */
118         auth_user_info_dc = talloc_zero(p, struct auth_user_info_dc);
119         if (!auth_user_info_dc) {
120                 TALLOC_FREE(p);
121                 *perrno = ENOMEM;
122                 return -1;
123         }
124
125         auth_user_info_dc->num_sids = session_info->security_token->num_sids;
126         auth_user_info_dc->sids = session_info->security_token->sids;
127         auth_user_info_dc->info = session_info->info;
128         auth_user_info_dc->user_session_key = session_info->session_key;
129
130         /* This creates the input structure that make_server_info_info3 is looking for */
131         status = auth_convert_user_info_dc_saminfo3(p, auth_user_info_dc,
132                                                     &info3);
133
134         if (!NT_STATUS_IS_OK(status)) {
135                 DEBUG(1, ("Failed to convert auth_user_info_dc into netr_SamInfo3\n"));
136                 TALLOC_FREE(p);
137                 *perrno = EINVAL;
138                 return -1;
139         }
140
141         if (session_info->unix_token && session_info->unix_info && session_info->security_token) {
142                 /* Don't call create_local_token(), we already have the full details here */
143                 p->session_info = talloc_zero(p, struct auth3_session_info);
144                 if (p->session_info == NULL) {
145                         TALLOC_FREE(p);
146                         *perrno = ENOMEM;
147                         return -1;
148                 }
149                 p->session_info->security_token = talloc_move(p->session_info, &session_info->security_token);
150                 p->session_info->unix_token = talloc_move(p->session_info, &session_info->unix_token);
151                 p->session_info->unix_info = talloc_move(p->session_info, &session_info->unix_info);
152                 p->session_info->info3 = talloc_move(p->session_info, &info3);
153                 p->session_info->session_key = session_info->session_key;
154                 p->session_info->session_key.data = talloc_move(p->session_info, &session_info->session_key.data);
155
156         } else {
157                 struct auth_serversupplied_info *server_info;
158
159                 status = make_server_info_info3(p,
160                                                 info3->base.account_name.string,
161                                                 info3->base.domain.string,
162                                                 &server_info, info3);
163                 if (!NT_STATUS_IS_OK(status)) {
164                         DEBUG(1, ("Failed to init server info\n"));
165                         TALLOC_FREE(p);
166                         *perrno = EINVAL;
167                         return -1;
168                 }
169
170                 /*
171                  * Some internal functions need a local token to determine access to
172                  * resources.
173                  */
174                 status = create_local_token(p, server_info, &session_info->session_key, &p->session_info);
175                 talloc_free(server_info);
176                 if (!NT_STATUS_IS_OK(status)) {
177                         DEBUG(1, ("Failed to init local auth token\n"));
178                         TALLOC_FREE(p);
179                         *perrno = EINVAL;
180                         return -1;
181                 }
182         }
183
184         p->remote_address = tsocket_address_copy(remote_address, p);
185         if (p->remote_address == NULL) {
186                 TALLOC_FREE(p);
187                 *perrno = ENOMEM;
188                 return -1;
189         }
190
191         if (local_address != NULL) {
192                 p->local_address = tsocket_address_copy(local_address, p);
193                 if (p->local_address == NULL) {
194                         TALLOC_FREE(p);
195                         *perrno = ENOMEM;
196                         return -1;
197                 }
198         }
199
200         talloc_set_destructor(p, close_internal_rpc_pipe_hnd);
201
202         *_p = p;
203         return 0;
204 }
205
206 /* Start listening on the appropriate unix socket and setup all is needed to
207  * dispatch requests to the pipes rpc implementation */
208
209 struct dcerpc_ncacn_listen_state {
210         struct ndr_syntax_id syntax_id;
211
212         int fd;
213         union {
214                 char *name;
215                 uint16_t port;
216         } ep;
217
218         struct tevent_context *ev_ctx;
219         struct messaging_context *msg_ctx;
220         dcerpc_ncacn_disconnect_fn disconnect_fn;
221 };
222
223 static void named_pipe_listener(struct tevent_context *ev,
224                                 struct tevent_fd *fde,
225                                 uint16_t flags,
226                                 void *private_data);
227
228 bool setup_named_pipe_socket(const char *pipe_name,
229                              struct tevent_context *ev_ctx,
230                              struct messaging_context *msg_ctx)
231 {
232         struct dcerpc_ncacn_listen_state *state;
233         struct tevent_fd *fde;
234         char *np_dir;
235
236         state = talloc(ev_ctx, struct dcerpc_ncacn_listen_state);
237         if (!state) {
238                 DEBUG(0, ("Out of memory\n"));
239                 return false;
240         }
241         state->ep.name = talloc_strdup(state, pipe_name);
242         if (state->ep.name == NULL) {
243                 DEBUG(0, ("Out of memory\n"));
244                 goto out;
245         }
246         state->fd = -1;
247
248         state->ev_ctx = ev_ctx;
249         state->msg_ctx = msg_ctx;
250
251         /*
252          * As lp_ncalrpc_dir() should have 0755, but
253          * lp_ncalrpc_dir()/np should have 0700, we need to
254          * create lp_ncalrpc_dir() first.
255          */
256         if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
257                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
258                           lp_ncalrpc_dir(), strerror(errno)));
259                 goto out;
260         }
261
262         np_dir = talloc_asprintf(state, "%s/np", lp_ncalrpc_dir());
263         if (!np_dir) {
264                 DEBUG(0, ("Out of memory\n"));
265                 goto out;
266         }
267
268         if (!directory_create_or_exist(np_dir, geteuid(), 0700)) {
269                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
270                           np_dir, strerror(errno)));
271                 goto out;
272         }
273
274         state->fd = create_pipe_sock(np_dir, pipe_name, 0700);
275         if (state->fd == -1) {
276                 DEBUG(0, ("Failed to create pipe socket! [%s/%s]\n",
277                           np_dir, pipe_name));
278                 goto out;
279         }
280
281         DEBUG(10, ("Openened pipe socket fd %d for %s\n",
282                    state->fd, pipe_name));
283
284         fde = tevent_add_fd(ev_ctx,
285                             state, state->fd, TEVENT_FD_READ,
286                             named_pipe_listener, state);
287         if (!fde) {
288                 DEBUG(0, ("Failed to add event handler!\n"));
289                 goto out;
290         }
291
292         tevent_fd_set_auto_close(fde);
293         return true;
294
295 out:
296         if (state->fd != -1) {
297                 close(state->fd);
298         }
299         TALLOC_FREE(state);
300         return false;
301 }
302
303 static void named_pipe_accept_function(struct tevent_context *ev_ctx,
304                                        struct messaging_context *msg_ctx,
305                                        const char *pipe_name,
306                                        int fd);
307
308 static void named_pipe_listener(struct tevent_context *ev,
309                                 struct tevent_fd *fde,
310                                 uint16_t flags,
311                                 void *private_data)
312 {
313         struct dcerpc_ncacn_listen_state *state =
314                         talloc_get_type_abort(private_data,
315                                               struct dcerpc_ncacn_listen_state);
316         struct sockaddr_un sunaddr;
317         socklen_t len;
318         int sd = -1;
319
320         /* TODO: should we have a limit to the number of clients ? */
321
322         len = sizeof(sunaddr);
323
324         sd = accept(state->fd,
325                     (struct sockaddr *)(void *)&sunaddr, &len);
326
327         if (sd == -1) {
328                 if (errno != EINTR) {
329                         DEBUG(6, ("Failed to get a valid socket [%s]\n",
330                                   strerror(errno)));
331                 }
332                 return;
333         }
334
335         DEBUG(6, ("Accepted socket %d\n", sd));
336
337         named_pipe_accept_function(state->ev_ctx,
338                                    state->msg_ctx,
339                                    state->ep.name,
340                                    sd);
341 }
342
343
344 /* This is the core of the rpc server.
345  * Accepts connections from clients and process requests using the appropriate
346  * dispatcher table. */
347
348 struct named_pipe_client {
349         const char *pipe_name;
350
351         struct tevent_context *ev;
352         struct messaging_context *msg_ctx;
353
354         uint16_t file_type;
355         uint16_t device_state;
356         uint64_t allocation_size;
357
358         struct tstream_context *tstream;
359
360         struct tsocket_address *client;
361         char *client_name;
362         struct tsocket_address *server;
363         char *server_name;
364
365         struct auth_session_info *session_info;
366
367         struct pipes_struct *p;
368
369         struct tevent_queue *write_queue;
370
371         struct iovec *iov;
372         size_t count;
373 };
374
375 static void named_pipe_accept_done(struct tevent_req *subreq);
376
377 static void named_pipe_accept_function(struct tevent_context *ev_ctx,
378                                        struct messaging_context *msg_ctx,
379                                        const char *pipe_name,
380                                        int fd)
381 {
382         struct named_pipe_client *npc;
383         struct tstream_context *plain;
384         struct tevent_req *subreq;
385         int ret;
386
387         npc = talloc_zero(NULL, struct named_pipe_client);
388         if (!npc) {
389                 DEBUG(0, ("Out of memory!\n"));
390                 close(fd);
391                 return;
392         }
393         npc->pipe_name = pipe_name;
394         npc->ev = ev_ctx;
395         npc->msg_ctx = msg_ctx;
396
397         /* make sure socket is in NON blocking state */
398         ret = set_blocking(fd, false);
399         if (ret != 0) {
400                 DEBUG(2, ("Failed to make socket non-blocking\n"));
401                 TALLOC_FREE(npc);
402                 close(fd);
403                 return;
404         }
405
406         ret = tstream_bsd_existing_socket(npc, fd, &plain);
407         if (ret != 0) {
408                 DEBUG(2, ("Failed to create tstream socket\n"));
409                 TALLOC_FREE(npc);
410                 close(fd);
411                 return;
412         }
413
414         npc->file_type = FILE_TYPE_MESSAGE_MODE_PIPE;
415         npc->device_state = 0xff | 0x0400 | 0x0100;
416         npc->allocation_size = 4096;
417
418         subreq = tstream_npa_accept_existing_send(npc, npc->ev, plain,
419                                                   npc->file_type,
420                                                   npc->device_state,
421                                                   npc->allocation_size);
422         if (!subreq) {
423                 DEBUG(2, ("Failed to start async accept procedure\n"));
424                 TALLOC_FREE(npc);
425                 close(fd);
426                 return;
427         }
428         tevent_req_set_callback(subreq, named_pipe_accept_done, npc);
429 }
430
431 static void named_pipe_packet_process(struct tevent_req *subreq);
432 static void named_pipe_packet_done(struct tevent_req *subreq);
433
434 static void named_pipe_accept_done(struct tevent_req *subreq)
435 {
436         struct auth_session_info_transport *session_info_transport;
437         struct named_pipe_client *npc =
438                 tevent_req_callback_data(subreq, struct named_pipe_client);
439         int error;
440         int ret;
441
442         ret = tstream_npa_accept_existing_recv(subreq, &error, npc,
443                                                 &npc->tstream,
444                                                 &npc->client,
445                                                 &npc->client_name,
446                                                 &npc->server,
447                                                 &npc->server_name,
448                                                 &session_info_transport);
449
450         npc->session_info = talloc_move(npc, &session_info_transport->session_info);
451
452         TALLOC_FREE(subreq);
453         if (ret != 0) {
454                 DEBUG(2, ("Failed to accept named pipe connection! (%s)\n",
455                           strerror(error)));
456                 TALLOC_FREE(npc);
457                 return;
458         }
459
460         ret = make_server_pipes_struct(npc,
461                                        npc->pipe_name, NCACN_NP,
462                                         false, npc->server, npc->client, npc->session_info,
463                                         &npc->p, &error);
464         if (ret != 0) {
465                 DEBUG(2, ("Failed to create pipes_struct! (%s)\n",
466                           strerror(error)));
467                 goto fail;
468         }
469         npc->p->msg_ctx = npc->msg_ctx;
470
471         npc->write_queue = tevent_queue_create(npc, "np_server_write_queue");
472         if (!npc->write_queue) {
473                 DEBUG(2, ("Failed to set up write queue!\n"));
474                 goto fail;
475         }
476
477         /* And now start receiving and processing packets */
478         subreq = dcerpc_read_ncacn_packet_send(npc, npc->ev, npc->tstream);
479         if (!subreq) {
480                 DEBUG(2, ("Failed to start receving packets\n"));
481                 goto fail;
482         }
483         tevent_req_set_callback(subreq, named_pipe_packet_process, npc);
484         return;
485
486 fail:
487         DEBUG(2, ("Fatal error. Terminating client(%s) connection!\n",
488                   npc->client_name));
489         /* terminate client connection */
490         talloc_free(npc);
491         return;
492 }
493
494 static void named_pipe_packet_process(struct tevent_req *subreq)
495 {
496         struct named_pipe_client *npc =
497                 tevent_req_callback_data(subreq, struct named_pipe_client);
498         struct _output_data *out = &npc->p->out_data;
499         DATA_BLOB recv_buffer = data_blob_null;
500         struct ncacn_packet *pkt;
501         NTSTATUS status;
502         ssize_t data_left;
503         ssize_t data_used;
504         char *data;
505         uint32_t to_send;
506         bool ok;
507
508         status = dcerpc_read_ncacn_packet_recv(subreq, npc, &pkt, &recv_buffer);
509         TALLOC_FREE(subreq);
510         if (!NT_STATUS_IS_OK(status)) {
511                 goto fail;
512         }
513
514         data_left = recv_buffer.length;
515         data = (char *)recv_buffer.data;
516
517         while (data_left) {
518
519                 data_used = process_incoming_data(npc->p, data, data_left);
520                 if (data_used < 0) {
521                         DEBUG(3, ("Failed to process dceprc request!\n"));
522                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
523                         goto fail;
524                 }
525
526                 data_left -= data_used;
527                 data += data_used;
528         }
529
530         /* Do not leak this buffer, npc is a long lived context */
531         talloc_free(recv_buffer.data);
532         talloc_free(pkt);
533
534         /* this is needed because of the way DCERPC Binds work in
535          * the RPC marshalling code */
536         to_send = out->frag.length - out->current_pdu_sent;
537         if (to_send > 0) {
538
539                 DEBUG(10, ("Current_pdu_len = %u, "
540                            "current_pdu_sent = %u "
541                            "Returning %u bytes\n",
542                            (unsigned int)out->frag.length,
543                            (unsigned int)out->current_pdu_sent,
544                            (unsigned int)to_send));
545
546                 npc->iov = talloc_zero(npc, struct iovec);
547                 if (!npc->iov) {
548                         status = NT_STATUS_NO_MEMORY;
549                         goto fail;
550                 }
551                 npc->count = 1;
552
553                 npc->iov[0].iov_base = out->frag.data
554                                         + out->current_pdu_sent;
555                 npc->iov[0].iov_len = to_send;
556
557                 out->current_pdu_sent += to_send;
558         }
559
560         /* this condition is false for bind packets, or when we haven't
561          * yet got a full request, and need to wait for more data from
562          * the client */
563         while (out->data_sent_length < out->rdata.length) {
564
565                 ok = create_next_pdu(npc->p);
566                 if (!ok) {
567                         DEBUG(3, ("Failed to create next PDU!\n"));
568                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
569                         goto fail;
570                 }
571
572                 npc->iov = talloc_realloc(npc, npc->iov,
573                                             struct iovec, npc->count + 1);
574                 if (!npc->iov) {
575                         status = NT_STATUS_NO_MEMORY;
576                         goto fail;
577                 }
578
579                 npc->iov[npc->count].iov_base = out->frag.data;
580                 npc->iov[npc->count].iov_len = out->frag.length;
581
582                 DEBUG(10, ("PDU number: %d, PDU Length: %u\n",
583                            (unsigned int)npc->count,
584                            (unsigned int)npc->iov[npc->count].iov_len));
585                 dump_data(11, (const uint8_t *)npc->iov[npc->count].iov_base,
586                                 npc->iov[npc->count].iov_len);
587                 npc->count++;
588         }
589
590         /* we still don't have a complete request, go back and wait for more
591          * data */
592         if (npc->count == 0) {
593                 /* Wait for the next packet */
594                 subreq = dcerpc_read_ncacn_packet_send(npc, npc->ev, npc->tstream);
595                 if (!subreq) {
596                         DEBUG(2, ("Failed to start receving packets\n"));
597                         status = NT_STATUS_NO_MEMORY;
598                         goto fail;
599                 }
600                 tevent_req_set_callback(subreq, named_pipe_packet_process, npc);
601                 return;
602         }
603
604         DEBUG(10, ("Sending a total of %u bytes\n",
605                    (unsigned int)npc->p->out_data.data_sent_length));
606
607         subreq = tstream_writev_queue_send(npc, npc->ev,
608                                            npc->tstream,
609                                            npc->write_queue,
610                                            npc->iov, npc->count);
611         if (!subreq) {
612                 DEBUG(2, ("Failed to send packet\n"));
613                 status = NT_STATUS_NO_MEMORY;
614                 goto fail;
615         }
616         tevent_req_set_callback(subreq, named_pipe_packet_done, npc);
617         return;
618
619 fail:
620         DEBUG(2, ("Fatal error(%s). "
621                   "Terminating client(%s) connection!\n",
622                   nt_errstr(status), npc->client_name));
623         /* terminate client connection */
624         talloc_free(npc);
625         return;
626 }
627
628 static void named_pipe_packet_done(struct tevent_req *subreq)
629 {
630         struct named_pipe_client *npc =
631                 tevent_req_callback_data(subreq, struct named_pipe_client);
632         int sys_errno;
633         int ret;
634
635         ret = tstream_writev_queue_recv(subreq, &sys_errno);
636         TALLOC_FREE(subreq);
637         if (ret == -1) {
638                 DEBUG(2, ("Writev failed!\n"));
639                 goto fail;
640         }
641
642         /* clear out any data that may have been left around */
643         npc->count = 0;
644         TALLOC_FREE(npc->iov);
645         data_blob_free(&npc->p->in_data.data);
646         data_blob_free(&npc->p->out_data.frag);
647         data_blob_free(&npc->p->out_data.rdata);
648
649         /* Wait for the next packet */
650         subreq = dcerpc_read_ncacn_packet_send(npc, npc->ev, npc->tstream);
651         if (!subreq) {
652                 DEBUG(2, ("Failed to start receving packets\n"));
653                 sys_errno = ENOMEM;
654                 goto fail;
655         }
656         tevent_req_set_callback(subreq, named_pipe_packet_process, npc);
657         return;
658
659 fail:
660         DEBUG(2, ("Fatal error(%s). "
661                   "Terminating client(%s) connection!\n",
662                   strerror(sys_errno), npc->client_name));
663         /* terminate client connection */
664         talloc_free(npc);
665         return;
666 }
667
668 static void dcerpc_ncacn_accept(struct tevent_context *ev_ctx,
669                                 struct messaging_context *msg_ctx,
670                                 enum dcerpc_transport_t transport,
671                                 const char *name,
672                                 uint16_t port,
673                                 struct tsocket_address *cli_addr,
674                                 struct tsocket_address *srv_addr,
675                                 int s,
676                                 dcerpc_ncacn_disconnect_fn fn);
677
678 /********************************************************************
679  * Start listening on the tcp/ip socket
680  ********************************************************************/
681
682 static void dcerpc_ncacn_tcpip_listener(struct tevent_context *ev,
683                                         struct tevent_fd *fde,
684                                         uint16_t flags,
685                                         void *private_data);
686
687 uint16_t setup_dcerpc_ncacn_tcpip_socket(struct tevent_context *ev_ctx,
688                                          struct messaging_context *msg_ctx,
689                                          const struct sockaddr_storage *ifss,
690                                          uint16_t port)
691 {
692         struct dcerpc_ncacn_listen_state *state;
693         struct tevent_fd *fde;
694         int rc;
695
696         state = talloc(ev_ctx, struct dcerpc_ncacn_listen_state);
697         if (state == NULL) {
698                 DEBUG(0, ("setup_dcerpc_ncacn_tcpip_socket: Out of memory\n"));
699                 return 0;
700         }
701
702         state->fd = -1;
703         state->ep.port = port;
704         state->disconnect_fn = NULL;
705
706         if (state->ep.port == 0) {
707                 uint16_t i;
708
709                 for (i = SERVER_TCP_LOW_PORT; i <= SERVER_TCP_HIGH_PORT; i++) {
710                         state->fd = open_socket_in(SOCK_STREAM,
711                                                    i,
712                                                    0,
713                                                    ifss,
714                                                    false);
715                         if (state->fd > 0) {
716                                 state->ep.port = i;
717                                 break;
718                         }
719                 }
720         } else {
721                 state->fd = open_socket_in(SOCK_STREAM,
722                                            state->ep.port,
723                                            0,
724                                            ifss,
725                                            true);
726         }
727         if (state->fd == -1) {
728                 DEBUG(0, ("setup_dcerpc_ncacn_tcpip_socket: Failed to create "
729                           "socket on port %u!\n", state->ep.port));
730                 goto out;
731         }
732
733         state->ev_ctx = ev_ctx;
734         state->msg_ctx = msg_ctx;
735
736         /* ready to listen */
737         set_socket_options(state->fd, "SO_KEEPALIVE");
738         set_socket_options(state->fd, lp_socket_options());
739
740         /* Set server socket to non-blocking for the accept. */
741         set_blocking(state->fd, false);
742
743         rc = listen(state->fd, SMBD_LISTEN_BACKLOG);
744         if (rc == -1) {
745                 DEBUG(0,("setup_tcpip_socket: listen - %s\n", strerror(errno)));
746                 goto out;
747         }
748
749         DEBUG(10, ("setup_tcpip_socket: openened socket fd %d for port %u\n",
750                    state->fd, state->ep.port));
751
752         fde = tevent_add_fd(state->ev_ctx,
753                             state,
754                             state->fd,
755                             TEVENT_FD_READ,
756                             dcerpc_ncacn_tcpip_listener,
757                             state);
758         if (fde == NULL) {
759                 DEBUG(0, ("setup_tcpip_socket: Failed to add event handler!\n"));
760                 goto out;
761         }
762
763         tevent_fd_set_auto_close(fde);
764
765         return state->ep.port;
766 out:
767         if (state->fd != -1) {
768                 close(state->fd);
769         }
770         TALLOC_FREE(state);
771
772         return 0;
773 }
774
775 static void dcerpc_ncacn_tcpip_listener(struct tevent_context *ev,
776                                         struct tevent_fd *fde,
777                                         uint16_t flags,
778                                         void *private_data)
779 {
780         struct dcerpc_ncacn_listen_state *state =
781                         talloc_get_type_abort(private_data,
782                                               struct dcerpc_ncacn_listen_state);
783         struct tsocket_address *cli_addr = NULL;
784         struct tsocket_address *srv_addr = NULL;
785         struct sockaddr_storage addr;
786         socklen_t in_addrlen = sizeof(addr);
787         int s = -1;
788         int rc;
789
790         s = accept(state->fd, (struct sockaddr *)(void *) &addr, &in_addrlen);
791         if (s == -1) {
792                 if (errno != EINTR) {
793                         DEBUG(0,("tcpip_listener accept: %s\n",
794                                  strerror(errno)));
795                 }
796                 return;
797         }
798
799         rc = tsocket_address_bsd_from_sockaddr(state,
800                                                (struct sockaddr *)(void *) &addr,
801                                                in_addrlen,
802                                                &cli_addr);
803         if (rc < 0) {
804                 close(s);
805                 return;
806         }
807
808         rc = getsockname(s, (struct sockaddr *)(void *) &addr, &in_addrlen);
809         if (rc < 0) {
810                 close(s);
811                 return;
812         }
813
814         rc = tsocket_address_bsd_from_sockaddr(state,
815                                                (struct sockaddr *)(void *) &addr,
816                                                in_addrlen,
817                                                &srv_addr);
818         if (rc < 0) {
819                 close(s);
820                 return;
821         }
822
823         DEBUG(6, ("tcpip_listener: Accepted socket %d\n", s));
824
825         dcerpc_ncacn_accept(state->ev_ctx,
826                             state->msg_ctx,
827                             NCACN_IP_TCP,
828                             NULL,
829                             state->ep.port,
830                             cli_addr,
831                             srv_addr,
832                             s,
833                             NULL);
834 }
835
836 /********************************************************************
837  * Start listening on the ncalrpc socket
838  ********************************************************************/
839
840 static void dcerpc_ncalrpc_listener(struct tevent_context *ev,
841                                     struct tevent_fd *fde,
842                                     uint16_t flags,
843                                     void *private_data);
844
845 bool setup_dcerpc_ncalrpc_socket(struct tevent_context *ev_ctx,
846                                  struct messaging_context *msg_ctx,
847                                  const char *name,
848                                  dcerpc_ncacn_disconnect_fn fn)
849 {
850         struct dcerpc_ncacn_listen_state *state;
851         struct tevent_fd *fde;
852
853         state = talloc(ev_ctx, struct dcerpc_ncacn_listen_state);
854         if (state == NULL) {
855                 DEBUG(0, ("Out of memory\n"));
856                 return false;
857         }
858
859         state->fd = -1;
860         state->disconnect_fn = fn;
861
862         if (name == NULL) {
863                 name = "DEFAULT";
864         }
865         state->ep.name = talloc_strdup(state, name);
866
867         if (state->ep.name == NULL) {
868                 DEBUG(0, ("Out of memory\n"));
869                 talloc_free(state);
870                 return false;
871         }
872
873         if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
874                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
875                           lp_ncalrpc_dir(), strerror(errno)));
876                 goto out;
877         }
878
879         state->fd = create_pipe_sock(lp_ncalrpc_dir(), name, 0755);
880         if (state->fd == -1) {
881                 DEBUG(0, ("Failed to create pipe socket! [%s/%s]\n",
882                           lp_ncalrpc_dir(), name));
883                 goto out;
884         }
885
886         DEBUG(10, ("Openened pipe socket fd %d for %s\n", state->fd, name));
887
888         state->ev_ctx = ev_ctx;
889         state->msg_ctx = msg_ctx;
890
891         /* Set server socket to non-blocking for the accept. */
892         set_blocking(state->fd, false);
893
894         fde = tevent_add_fd(state->ev_ctx,
895                             state,
896                             state->fd,
897                             TEVENT_FD_READ,
898                             dcerpc_ncalrpc_listener,
899                             state);
900         if (fde == NULL) {
901                 DEBUG(0, ("Failed to add event handler for ncalrpc!\n"));
902                 goto out;
903         }
904
905         tevent_fd_set_auto_close(fde);
906
907         return true;
908 out:
909         if (state->fd != -1) {
910                 close(state->fd);
911         }
912         TALLOC_FREE(state);
913
914         return 0;
915 }
916
917 static void dcerpc_ncalrpc_listener(struct tevent_context *ev,
918                                         struct tevent_fd *fde,
919                                         uint16_t flags,
920                                         void *private_data)
921 {
922         struct dcerpc_ncacn_listen_state *state =
923                         talloc_get_type_abort(private_data,
924                                               struct dcerpc_ncacn_listen_state);
925         struct tsocket_address *cli_addr = NULL;
926         struct sockaddr_un sunaddr;
927         struct sockaddr *addr = (struct sockaddr *)(void *)&sunaddr;
928         socklen_t len = sizeof(sunaddr);
929         int sd = -1;
930         int rc;
931
932         ZERO_STRUCT(sunaddr);
933
934         sd = accept(state->fd, addr, &len);
935         if (sd == -1) {
936                 if (errno != EINTR) {
937                         DEBUG(0, ("ncalrpc accept() failed: %s\n", strerror(errno)));
938                 }
939                 return;
940         }
941
942         rc = tsocket_address_bsd_from_sockaddr(state,
943                                                addr, len,
944                                                &cli_addr);
945         if (rc < 0) {
946                 close(sd);
947                 return;
948         }
949
950         DEBUG(10, ("Accepted ncalrpc socket %d\n", sd));
951
952         dcerpc_ncacn_accept(state->ev_ctx,
953                             state->msg_ctx,
954                             NCALRPC,
955                             state->ep.name, 0,
956                             cli_addr, NULL, sd,
957                             state->disconnect_fn);
958 }
959
960 struct dcerpc_ncacn_conn {
961         enum dcerpc_transport_t transport;
962
963         union {
964                 const char *name;
965                 uint16_t port;
966         } ep;
967
968         int sock;
969
970         struct pipes_struct *p;
971         dcerpc_ncacn_disconnect_fn disconnect_fn;
972
973         struct tevent_context *ev_ctx;
974         struct messaging_context *msg_ctx;
975
976         struct tstream_context *tstream;
977         struct tevent_queue *send_queue;
978
979         struct tsocket_address *client;
980         char *client_name;
981         struct tsocket_address *server;
982         char *server_name;
983         struct auth_session_info *session_info;
984
985         struct iovec *iov;
986         size_t count;
987 };
988
989 static void dcerpc_ncacn_packet_process(struct tevent_req *subreq);
990 static void dcerpc_ncacn_packet_done(struct tevent_req *subreq);
991
992 static void dcerpc_ncacn_accept(struct tevent_context *ev_ctx,
993                                 struct messaging_context *msg_ctx,
994                                 enum dcerpc_transport_t transport,
995                                 const char *name,
996                                 uint16_t port,
997                                 struct tsocket_address *cli_addr,
998                                 struct tsocket_address *srv_addr,
999                                 int s,
1000                                 dcerpc_ncacn_disconnect_fn fn) {
1001         struct dcerpc_ncacn_conn *ncacn_conn;
1002         struct tevent_req *subreq;
1003         const char *cli_str;
1004         const char *srv_str = NULL;
1005         bool system_user = false;
1006         char *pipe_name;
1007         NTSTATUS status;
1008         int sys_errno;
1009         uid_t uid;
1010         int rc;
1011
1012         DEBUG(10, ("dcerpc_ncacn_accept\n"));
1013
1014         ncacn_conn = talloc_zero(ev_ctx, struct dcerpc_ncacn_conn);
1015         if (ncacn_conn == NULL) {
1016                 DEBUG(0, ("Out of memory!\n"));
1017                 close(s);
1018                 return;
1019         }
1020
1021         ncacn_conn->transport = transport;
1022         ncacn_conn->ev_ctx = ev_ctx;
1023         ncacn_conn->msg_ctx = msg_ctx;
1024         ncacn_conn->sock = s;
1025         ncacn_conn->disconnect_fn = fn;
1026
1027         ncacn_conn->client = talloc_move(ncacn_conn, &cli_addr);
1028         if (tsocket_address_is_inet(ncacn_conn->client, "ip")) {
1029                 ncacn_conn->client_name =
1030                         tsocket_address_inet_addr_string(ncacn_conn->client,
1031                                                          ncacn_conn);
1032         } else {
1033                 ncacn_conn->client_name =
1034                         tsocket_address_unix_path(ncacn_conn->client,
1035                                                   ncacn_conn);
1036         }
1037         if (ncacn_conn->client_name == NULL) {
1038                 DEBUG(0, ("Out of memory!\n"));
1039                 talloc_free(ncacn_conn);
1040                 close(s);
1041                 return;
1042         }
1043
1044         if (srv_addr != NULL) {
1045                 ncacn_conn->server = talloc_move(ncacn_conn, &srv_addr);
1046
1047                 ncacn_conn->server_name =
1048                         tsocket_address_inet_addr_string(ncacn_conn->server,
1049                                                          ncacn_conn);
1050                 if (ncacn_conn->server_name == NULL) {
1051                         DEBUG(0, ("Out of memory!\n"));
1052                         talloc_free(ncacn_conn);
1053                         close(s);
1054                         return;
1055                 }
1056         }
1057
1058         switch (transport) {
1059                 case NCACN_IP_TCP:
1060                         ncacn_conn->ep.port = port;
1061
1062                         pipe_name = tsocket_address_string(ncacn_conn->client,
1063                                                            ncacn_conn);
1064                         if (pipe_name == NULL) {
1065                                 close(s);
1066                                 talloc_free(ncacn_conn);
1067                                 return;
1068                         }
1069
1070                         break;
1071                 case NCALRPC:
1072                         rc = sys_getpeereid(s, &uid);
1073                         if (rc < 0) {
1074                                 DEBUG(2, ("Failed to get ncalrpc connecting uid!"));
1075                         } else {
1076                                 if (uid == sec_initial_uid()) {
1077                                         system_user = true;
1078                                 }
1079                         }
1080                 case NCACN_NP:
1081                         ncacn_conn->ep.name = talloc_strdup(ncacn_conn, name);
1082                         if (ncacn_conn->ep.name == NULL) {
1083                                 close(s);
1084                                 talloc_free(ncacn_conn);
1085                                 return;
1086                         }
1087
1088                         pipe_name = talloc_strdup(ncacn_conn,
1089                                                   name);
1090                         if (pipe_name == NULL) {
1091                                 close(s);
1092                                 talloc_free(ncacn_conn);
1093                                 return;
1094                         }
1095                         break;
1096                 default:
1097                         DEBUG(0, ("unknown dcerpc transport: %u!\n",
1098                                   transport));
1099                         talloc_free(ncacn_conn);
1100                         close(s);
1101                         return;
1102         }
1103
1104         rc = set_blocking(s, false);
1105         if (rc < 0) {
1106                 DEBUG(2, ("Failed to set dcerpc socket to non-blocking\n"));
1107                 talloc_free(ncacn_conn);
1108                 close(s);
1109                 return;
1110         }
1111
1112         /*
1113          * As soon as we have tstream_bsd_existing_socket set up it will
1114          * take care of closing the socket.
1115          */
1116         rc = tstream_bsd_existing_socket(ncacn_conn, s, &ncacn_conn->tstream);
1117         if (rc < 0) {
1118                 DEBUG(2, ("Failed to create tstream socket for dcerpc\n"));
1119                 talloc_free(ncacn_conn);
1120                 close(s);
1121                 return;
1122         }
1123
1124         if (tsocket_address_is_inet(ncacn_conn->client, "ip")) {
1125                 cli_str = ncacn_conn->client_name;
1126         } else {
1127                 cli_str = "";
1128         }
1129
1130         if (ncacn_conn->server != NULL) {
1131                 if (tsocket_address_is_inet(ncacn_conn->server, "ip")) {
1132                         srv_str = ncacn_conn->server_name;
1133                 } else {
1134                         srv_str = NULL;
1135                 }
1136         }
1137
1138         if (ncacn_conn->session_info == NULL) {
1139                 status = auth_anonymous_session_info(ncacn_conn,
1140                                                      &ncacn_conn->session_info);
1141                 if (!NT_STATUS_IS_OK(status)) {
1142                         DEBUG(2, ("Failed to create "
1143                                   "auth_anonymous_session_info - %s\n",
1144                                   nt_errstr(status)));
1145                         talloc_free(ncacn_conn);
1146                         return;
1147                 }
1148         }
1149
1150         rc = make_server_pipes_struct(ncacn_conn,
1151                                       pipe_name,
1152                                       ncacn_conn->transport,
1153                                       system_user,
1154                                       ncacn_conn->server,
1155                                       ncacn_conn->client,
1156                                       ncacn_conn->session_info,
1157                                       &ncacn_conn->p,
1158                                       &sys_errno);
1159         if (rc < 0) {
1160                 DEBUG(2, ("Failed to create pipe struct - %s",
1161                           strerror(sys_errno)));
1162                 talloc_free(ncacn_conn);
1163                 return;
1164         }
1165
1166         ncacn_conn->send_queue = tevent_queue_create(ncacn_conn,
1167                                                         "dcerpc send queue");
1168         if (ncacn_conn->send_queue == NULL) {
1169                 DEBUG(0, ("Out of memory!\n"));
1170                 talloc_free(ncacn_conn);
1171                 return;
1172         }
1173
1174         subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1175                                                ncacn_conn->ev_ctx,
1176                                                ncacn_conn->tstream);
1177         if (subreq == NULL) {
1178                 DEBUG(2, ("Failed to send ncacn packet\n"));
1179                 talloc_free(ncacn_conn);
1180                 return;
1181         }
1182
1183         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1184
1185         DEBUG(10, ("dcerpc_ncacn_accept done\n"));
1186
1187         return;
1188 }
1189
1190 static void dcerpc_ncacn_packet_process(struct tevent_req *subreq)
1191 {
1192         struct dcerpc_ncacn_conn *ncacn_conn =
1193                 tevent_req_callback_data(subreq, struct dcerpc_ncacn_conn);
1194
1195         struct _output_data *out = &ncacn_conn->p->out_data;
1196         DATA_BLOB recv_buffer = data_blob_null;
1197         struct ncacn_packet *pkt;
1198         ssize_t data_left;
1199         ssize_t data_used;
1200         uint32_t to_send;
1201         char *data;
1202         NTSTATUS status;
1203         bool ok;
1204
1205         status = dcerpc_read_ncacn_packet_recv(subreq, ncacn_conn, &pkt, &recv_buffer);
1206         TALLOC_FREE(subreq);
1207         if (!NT_STATUS_IS_OK(status)) {
1208                 if (ncacn_conn->disconnect_fn != NULL) {
1209                         ok = ncacn_conn->disconnect_fn(ncacn_conn->p);
1210                         if (!ok) {
1211                                 DEBUG(3, ("Failed to call disconnect function\n"));
1212                         }
1213                 }
1214                 goto fail;
1215         }
1216
1217         data_left = recv_buffer.length;
1218         data = (char *) recv_buffer.data;
1219
1220         while (data_left) {
1221                 data_used = process_incoming_data(ncacn_conn->p, data, data_left);
1222                 if (data_used < 0) {
1223                         DEBUG(3, ("Failed to process dcerpc request!\n"));
1224                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
1225                         goto fail;
1226                 }
1227
1228                 data_left -= data_used;
1229                 data += data_used;
1230         }
1231
1232         /* Do not leak this buffer */
1233         talloc_free(recv_buffer.data);
1234         talloc_free(pkt);
1235
1236         /*
1237          * This is needed because of the way DCERPC binds work in the RPC
1238          * marshalling code
1239          */
1240         to_send = out->frag.length - out->current_pdu_sent;
1241         if (to_send > 0) {
1242
1243                 DEBUG(10, ("Current_pdu_len = %u, "
1244                            "current_pdu_sent = %u "
1245                            "Returning %u bytes\n",
1246                            (unsigned int)out->frag.length,
1247                            (unsigned int)out->current_pdu_sent,
1248                            (unsigned int)to_send));
1249
1250                 ncacn_conn->iov = talloc_zero(ncacn_conn, struct iovec);
1251                 if (ncacn_conn->iov == NULL) {
1252                         status = NT_STATUS_NO_MEMORY;
1253                         DEBUG(3, ("Out of memory!\n"));
1254                         goto fail;
1255                 }
1256                 ncacn_conn->count = 1;
1257
1258                 ncacn_conn->iov[0].iov_base = out->frag.data
1259                                             + out->current_pdu_sent;
1260                 ncacn_conn->iov[0].iov_len = to_send;
1261
1262                 out->current_pdu_sent += to_send;
1263         }
1264
1265         /*
1266          * This condition is false for bind packets, or when we haven't yet got
1267          * a full request, and need to wait for more data from the client
1268          */
1269         while (out->data_sent_length < out->rdata.length) {
1270                 ok = create_next_pdu(ncacn_conn->p);
1271                 if (!ok) {
1272                         DEBUG(3, ("Failed to create next PDU!\n"));
1273                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
1274                         goto fail;
1275                 }
1276
1277                 ncacn_conn->iov = talloc_realloc(ncacn_conn,
1278                                                  ncacn_conn->iov,
1279                                                  struct iovec,
1280                                                  ncacn_conn->count + 1);
1281                 if (ncacn_conn->iov == NULL) {
1282                         DEBUG(3, ("Out of memory!\n"));
1283                         status = NT_STATUS_NO_MEMORY;
1284                         goto fail;
1285                 }
1286
1287                 ncacn_conn->iov[ncacn_conn->count].iov_base = out->frag.data;
1288                 ncacn_conn->iov[ncacn_conn->count].iov_len = out->frag.length;
1289
1290                 DEBUG(10, ("PDU number: %d, PDU Length: %u\n",
1291                            (unsigned int) ncacn_conn->count,
1292                            (unsigned int) ncacn_conn->iov[ncacn_conn->count].iov_len));
1293                 dump_data(11, (const uint8_t *) ncacn_conn->iov[ncacn_conn->count].iov_base,
1294                               ncacn_conn->iov[ncacn_conn->count].iov_len);
1295                 ncacn_conn->count++;
1296         }
1297
1298         /*
1299          * We still don't have a complete request, go back and wait for more
1300          * data.
1301          */
1302         if (ncacn_conn->count == 0) {
1303                 /* Wait for the next packet */
1304                 subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1305                                                        ncacn_conn->ev_ctx,
1306                                                        ncacn_conn->tstream);
1307                 if (subreq == NULL) {
1308                         DEBUG(2, ("Failed to start receving packets\n"));
1309                         status = NT_STATUS_NO_MEMORY;
1310                         goto fail;
1311                 }
1312                 tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1313                 return;
1314         }
1315
1316         DEBUG(10, ("Sending a total of %u bytes\n",
1317                    (unsigned int)ncacn_conn->p->out_data.data_sent_length));
1318
1319         subreq = tstream_writev_queue_send(ncacn_conn,
1320                                            ncacn_conn->ev_ctx,
1321                                            ncacn_conn->tstream,
1322                                            ncacn_conn->send_queue,
1323                                            ncacn_conn->iov,
1324                                            ncacn_conn->count);
1325         if (subreq == NULL) {
1326                 DEBUG(2, ("Failed to send packet\n"));
1327                 status = NT_STATUS_NO_MEMORY;
1328                 goto fail;
1329         }
1330
1331         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_done, ncacn_conn);
1332         return;
1333
1334 fail:
1335         DEBUG(3, ("Terminating client(%s) connection! - '%s'\n",
1336                   ncacn_conn->client_name, nt_errstr(status)));
1337
1338         /* Terminate client connection */
1339         talloc_free(ncacn_conn);
1340         return;
1341 }
1342
1343 static void dcerpc_ncacn_packet_done(struct tevent_req *subreq)
1344 {
1345         struct dcerpc_ncacn_conn *ncacn_conn =
1346                 tevent_req_callback_data(subreq, struct dcerpc_ncacn_conn);
1347         NTSTATUS status = NT_STATUS_OK;
1348         int sys_errno;
1349         int rc;
1350
1351         rc = tstream_writev_queue_recv(subreq, &sys_errno);
1352         TALLOC_FREE(subreq);
1353         if (rc < 0) {
1354                 DEBUG(2, ("Writev failed!\n"));
1355                 status = map_nt_error_from_unix(sys_errno);
1356                 goto fail;
1357         }
1358
1359         /* clear out any data that may have been left around */
1360         ncacn_conn->count = 0;
1361         TALLOC_FREE(ncacn_conn->iov);
1362         data_blob_free(&ncacn_conn->p->in_data.data);
1363         data_blob_free(&ncacn_conn->p->out_data.frag);
1364         data_blob_free(&ncacn_conn->p->out_data.rdata);
1365
1366         /* Wait for the next packet */
1367         subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1368                                                ncacn_conn->ev_ctx,
1369                                                ncacn_conn->tstream);
1370         if (subreq == NULL) {
1371                 DEBUG(2, ("Failed to start receving packets\n"));
1372                 status = NT_STATUS_NO_MEMORY;
1373                 goto fail;
1374         }
1375
1376         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1377         return;
1378
1379 fail:
1380         DEBUG(3, ("Terminating client(%s) connection! - '%s'\n",
1381                   ncacn_conn->client_name, nt_errstr(status)));
1382
1383         /* Terminate client connection */
1384         talloc_free(ncacn_conn);
1385         return;
1386 }
1387
1388 /* vim: set ts=8 sw=8 noet cindent syntax=c.doxygen: */