selftest: Test sids-to-xids with one failing sid
[gd/samba-autobuild/.git] / nsswitch / wb_common.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    winbind client common code
5
6    Copyright (C) Tim Potter 2000
7    Copyright (C) Andrew Tridgell 2000
8    Copyright (C) Andrew Bartlett 2002
9    Copyright (C) Matthew Newton 2015
10
11
12    This library is free software; you can redistribute it and/or
13    modify it under the terms of the GNU Lesser General Public
14    License as published by the Free Software Foundation; either
15    version 3 of the License, or (at your option) any later version.
16
17    This library is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20    Library General Public License for more details.
21
22    You should have received a copy of the GNU Lesser General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "replace.h"
27 #include "system/select.h"
28 #include "winbind_client.h"
29
30 #ifdef HAVE_PTHREAD_H
31 #include <pthread.h>
32 #endif
33
34 static char client_name[32];
35
36 /* Global context */
37
38 struct winbindd_context {
39         int winbindd_fd;        /* winbind file descriptor */
40         bool is_privileged;     /* using the privileged socket? */
41         pid_t our_pid;          /* calling process pid */
42 };
43
44 #ifdef HAVE_PTHREAD
45 static pthread_mutex_t wb_global_ctx_mutex = PTHREAD_MUTEX_INITIALIZER;
46 #endif
47
48 static struct winbindd_context *get_wb_global_ctx(void)
49 {
50         static struct winbindd_context wb_global_ctx = {
51                 .winbindd_fd = -1,
52                 .is_privileged = false,
53                 .our_pid = 0
54         };
55
56 #ifdef HAVE_PTHREAD
57         pthread_mutex_lock(&wb_global_ctx_mutex);
58 #endif
59         return &wb_global_ctx;
60 }
61
62 static void put_wb_global_ctx(void)
63 {
64 #ifdef HAVE_PTHREAD
65         pthread_mutex_unlock(&wb_global_ctx_mutex);
66 #endif
67         return;
68 }
69
70 /* Free a response structure */
71
72 void winbindd_free_response(struct winbindd_response *response)
73 {
74         /* Free any allocated extra_data */
75
76         if (response)
77                 SAFE_FREE(response->extra_data.data);
78 }
79
80 void winbind_set_client_name(const char *name)
81 {
82         if (name == NULL || strlen(name) == 0) {
83                 return;
84         }
85
86         (void)snprintf(client_name, sizeof(client_name), "%s", name);
87 }
88
89 static const char *winbind_get_client_name(void)
90 {
91         if (client_name[0] == '\0') {
92                 const char *progname = getprogname();
93                 int len;
94
95                 if (progname == NULL) {
96                         progname = "<unknown>";
97                 }
98
99                 len = snprintf(client_name,
100                                sizeof(client_name),
101                                "%s",
102                                progname);
103                 if (len <= 0) {
104                         return progname;
105                 }
106         }
107
108         return client_name;
109 }
110
111 /* Initialise a request structure */
112
113 static void winbindd_init_request(struct winbindd_request *request,
114                                   int request_type)
115 {
116         request->length = sizeof(struct winbindd_request);
117
118         request->cmd = (enum winbindd_cmd)request_type;
119         request->pid = getpid();
120
121         (void)snprintf(request->client_name,
122                        sizeof(request->client_name),
123                        "%s",
124                        winbind_get_client_name());
125 }
126
127 /* Initialise a response structure */
128
129 static void init_response(struct winbindd_response *response)
130 {
131         /* Initialise return value */
132
133         response->result = WINBINDD_ERROR;
134 }
135
136 /* Close established socket */
137
138 static void winbind_close_sock(struct winbindd_context *ctx)
139 {
140         if (!ctx) {
141                 return;
142         }
143
144         if (ctx->winbindd_fd != -1) {
145                 close(ctx->winbindd_fd);
146                 ctx->winbindd_fd = -1;
147         }
148 }
149
150 /* Destructor for global context to ensure fd is closed */
151
152 #ifdef HAVE_DESTRUCTOR_ATTRIBUTE
153 __attribute__((destructor))
154 #endif
155 static void winbind_destructor(void)
156 {
157         struct winbindd_context *ctx;
158
159         ctx = get_wb_global_ctx();
160         winbind_close_sock(ctx);
161         put_wb_global_ctx();
162 }
163
164 #define CONNECT_TIMEOUT 30
165
166 /* Make sure socket handle isn't stdin, stdout or stderr */
167 #define RECURSION_LIMIT 3
168
169 static int make_nonstd_fd_internals(int fd, int limit /* Recursion limiter */)
170 {
171         int new_fd;
172         if (fd >= 0 && fd <= 2) {
173 #ifdef F_DUPFD
174                 if ((new_fd = fcntl(fd, F_DUPFD, 3)) == -1) {
175                         return -1;
176                 }
177                 /* Paranoia */
178                 if (new_fd < 3) {
179                         close(new_fd);
180                         return -1;
181                 }
182                 close(fd);
183                 return new_fd;
184 #else
185                 if (limit <= 0)
186                         return -1;
187
188                 new_fd = dup(fd);
189                 if (new_fd == -1)
190                         return -1;
191
192                 /* use the program stack to hold our list of FDs to close */
193                 new_fd = make_nonstd_fd_internals(new_fd, limit - 1);
194                 close(fd);
195                 return new_fd;
196 #endif
197         }
198         return fd;
199 }
200
201 /****************************************************************************
202  Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
203  else
204  if SYSV use O_NDELAY
205  if BSD use FNDELAY
206  Set close on exec also.
207 ****************************************************************************/
208
209 static int make_safe_fd(int fd)
210 {
211         int result, flags;
212         int new_fd = make_nonstd_fd_internals(fd, RECURSION_LIMIT);
213         if (new_fd == -1) {
214                 close(fd);
215                 return -1;
216         }
217
218         /* Socket should be nonblocking. */
219 #ifdef O_NONBLOCK
220 #define FLAG_TO_SET O_NONBLOCK
221 #else
222 #ifdef SYSV
223 #define FLAG_TO_SET O_NDELAY
224 #else /* BSD */
225 #define FLAG_TO_SET FNDELAY
226 #endif
227 #endif
228
229         if ((flags = fcntl(new_fd, F_GETFL)) == -1) {
230                 close(new_fd);
231                 return -1;
232         }
233
234         flags |= FLAG_TO_SET;
235         if (fcntl(new_fd, F_SETFL, flags) == -1) {
236                 close(new_fd);
237                 return -1;
238         }
239
240 #undef FLAG_TO_SET
241
242         /* Socket should be closed on exec() */
243 #ifdef FD_CLOEXEC
244         result = flags = fcntl(new_fd, F_GETFD, 0);
245         if (flags >= 0) {
246                 flags |= FD_CLOEXEC;
247                 result = fcntl( new_fd, F_SETFD, flags );
248         }
249         if (result < 0) {
250                 close(new_fd);
251                 return -1;
252         }
253 #endif
254         return new_fd;
255 }
256
257 /**
258  * @internal
259  *
260  * @brief Check if we talk to the priviliged pipe which should be owned by root.
261  *
262  * This checks if we have uid_wrapper running and if this is the case it will
263  * allow one to connect to the winbind privileged pipe even it is not owned by root.
264  *
265  * @param[in]  uid      The uid to check if we can safely talk to the pipe.
266  *
267  * @return              If we have access it returns true, else false.
268  */
269 static bool winbind_privileged_pipe_is_root(uid_t uid)
270 {
271         if (uid == 0) {
272                 return true;
273         }
274
275         if (uid_wrapper_enabled()) {
276                 return true;
277         }
278
279         return false;
280 }
281
282 /* Connect to winbindd socket */
283
284 static int winbind_named_pipe_sock(const char *dir)
285 {
286         struct sockaddr_un sunaddr;
287         struct stat st;
288         int fd;
289         int wait_time;
290         int slept;
291         int ret;
292
293         /* Check permissions on unix socket directory */
294
295         if (lstat(dir, &st) == -1) {
296                 errno = ENOENT;
297                 return -1;
298         }
299
300         /*
301          * This tells us that the pipe is owned by a privileged
302          * process, as we will be sending passwords to it.
303          */
304         if (!S_ISDIR(st.st_mode) ||
305             !winbind_privileged_pipe_is_root(st.st_uid)) {
306                 errno = ENOENT;
307                 return -1;
308         }
309
310         /* Connect to socket */
311
312         sunaddr = (struct sockaddr_un) { .sun_family = AF_UNIX };
313
314         ret = snprintf(sunaddr.sun_path, sizeof(sunaddr.sun_path),
315                        "%s/%s", dir, WINBINDD_SOCKET_NAME);
316         if ((ret == -1) || (ret >= sizeof(sunaddr.sun_path))) {
317                 errno = ENAMETOOLONG;
318                 return -1;
319         }
320
321         /* If socket file doesn't exist, don't bother trying to connect
322            with retry.  This is an attempt to make the system usable when
323            the winbindd daemon is not running. */
324
325         if (lstat(sunaddr.sun_path, &st) == -1) {
326                 errno = ENOENT;
327                 return -1;
328         }
329
330         /* Check permissions on unix socket file */
331
332         /*
333          * This tells us that the pipe is owned by a privileged
334          * process, as we will be sending passwords to it.
335          */
336         if (!S_ISSOCK(st.st_mode) ||
337             !winbind_privileged_pipe_is_root(st.st_uid)) {
338                 errno = ENOENT;
339                 return -1;
340         }
341
342         /* Connect to socket */
343
344         if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
345                 return -1;
346         }
347
348         /* Set socket non-blocking and close on exec. */
349
350         if ((fd = make_safe_fd( fd)) == -1) {
351                 return fd;
352         }
353
354         for (wait_time = 0; connect(fd, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1;
355                         wait_time += slept) {
356                 struct pollfd pfd;
357                 int connect_errno = 0;
358                 socklen_t errnosize;
359
360                 if (wait_time >= CONNECT_TIMEOUT)
361                         goto error_out;
362
363                 switch (errno) {
364                         case EINPROGRESS:
365                                 pfd.fd = fd;
366                                 pfd.events = POLLOUT;
367
368                                 ret = poll(&pfd, 1, (CONNECT_TIMEOUT - wait_time) * 1000);
369
370                                 if (ret > 0) {
371                                         errnosize = sizeof(connect_errno);
372
373                                         ret = getsockopt(fd, SOL_SOCKET,
374                                                         SO_ERROR, &connect_errno, &errnosize);
375
376                                         if (ret >= 0 && connect_errno == 0) {
377                                                 /* Connect succeed */
378                                                 goto out;
379                                         }
380                                 }
381
382                                 slept = CONNECT_TIMEOUT;
383                                 break;
384                         case EAGAIN:
385                                 slept = rand() % 3 + 1;
386                                 sleep(slept);
387                                 break;
388                         default:
389                                 goto error_out;
390                 }
391
392         }
393
394   out:
395
396         return fd;
397
398   error_out:
399
400         close(fd);
401         return -1;
402 }
403
404 static const char *winbindd_socket_dir(void)
405 {
406         if (nss_wrapper_enabled()) {
407                 const char *env_dir;
408
409                 env_dir = getenv("SELFTEST_WINBINDD_SOCKET_DIR");
410                 if (env_dir != NULL) {
411                         return env_dir;
412                 }
413         }
414
415         return WINBINDD_SOCKET_DIR;
416 }
417
418 /* Connect to winbindd socket */
419
420 static int winbind_open_pipe_sock(struct winbindd_context *ctx,
421                                   int recursing, int need_priv)
422 {
423 #ifdef HAVE_UNIXSOCKET
424         struct winbindd_request request;
425         struct winbindd_response response;
426
427         ZERO_STRUCT(request);
428         ZERO_STRUCT(response);
429
430         if (!ctx) {
431                 return -1;
432         }
433
434         if (ctx->our_pid != getpid()) {
435                 winbind_close_sock(ctx);
436                 ctx->our_pid = getpid();
437         }
438
439         if ((need_priv != 0) && !ctx->is_privileged) {
440                 winbind_close_sock(ctx);
441         }
442
443         if (ctx->winbindd_fd != -1) {
444                 return ctx->winbindd_fd;
445         }
446
447         if (recursing) {
448                 return -1;
449         }
450
451         ctx->winbindd_fd = winbind_named_pipe_sock(winbindd_socket_dir());
452
453         if (ctx->winbindd_fd == -1) {
454                 return -1;
455         }
456
457         ctx->is_privileged = false;
458
459         /* version-check the socket */
460
461         request.wb_flags = WBFLAG_RECURSE;
462         if ((winbindd_request_response(ctx, WINBINDD_INTERFACE_VERSION, &request,
463                                        &response) != NSS_STATUS_SUCCESS) ||
464             (response.data.interface_version != WINBIND_INTERFACE_VERSION)) {
465                 winbind_close_sock(ctx);
466                 return -1;
467         }
468
469         if (need_priv == 0) {
470                 return ctx->winbindd_fd;
471         }
472
473         /* try and get priv pipe */
474
475         request.wb_flags = WBFLAG_RECURSE;
476
477         /* Note that response needs to be initialized to avoid
478          * crashing on clean up after WINBINDD_PRIV_PIPE_DIR call failed
479          * as interface version (from the first request) returned as a fstring,
480          * thus response.extra_data.data will not be NULL even though
481          * winbindd response did not write over it due to a failure */
482         ZERO_STRUCT(response);
483         if (winbindd_request_response(ctx, WINBINDD_PRIV_PIPE_DIR, &request,
484                                       &response) == NSS_STATUS_SUCCESS) {
485                 int fd;
486                 fd = winbind_named_pipe_sock((char *)response.extra_data.data);
487                 if (fd != -1) {
488                         close(ctx->winbindd_fd);
489                         ctx->winbindd_fd = fd;
490                         ctx->is_privileged = true;
491                 }
492
493                 SAFE_FREE(response.extra_data.data);
494         }
495
496         if (!ctx->is_privileged) {
497                 return -1;
498         }
499
500         return ctx->winbindd_fd;
501 #else
502         return -1;
503 #endif /* HAVE_UNIXSOCKET */
504 }
505
506 /* Write data to winbindd socket */
507
508 static int winbind_write_sock(struct winbindd_context *ctx, void *buffer,
509                               int count, int recursing, int need_priv)
510 {
511         int fd, result, nwritten;
512
513         /* Open connection to winbind daemon */
514
515  restart:
516
517         fd = winbind_open_pipe_sock(ctx, recursing, need_priv);
518         if (fd == -1) {
519                 errno = ENOENT;
520                 return -1;
521         }
522
523         /* Write data to socket */
524
525         nwritten = 0;
526
527         while(nwritten < count) {
528                 struct pollfd pfd;
529                 int ret;
530
531                 /* Catch pipe close on other end by checking if a read()
532                    call would not block by calling poll(). */
533
534                 pfd.fd = fd;
535                 pfd.events = POLLIN|POLLOUT|POLLHUP;
536
537                 ret = poll(&pfd, 1, -1);
538                 if (ret == -1) {
539                         winbind_close_sock(ctx);
540                         return -1;                   /* poll error */
541                 }
542
543                 /* Write should be OK if fd not available for reading */
544
545                 if ((ret == 1) && (pfd.revents & (POLLIN|POLLHUP|POLLERR))) {
546
547                         /* Pipe has closed on remote end */
548
549                         winbind_close_sock(ctx);
550                         goto restart;
551                 }
552
553                 /* Do the write */
554
555                 result = write(fd, (char *)buffer + nwritten,
556                                count - nwritten);
557
558                 if ((result == -1) || (result == 0)) {
559
560                         /* Write failed */
561
562                         winbind_close_sock(ctx);
563                         return -1;
564                 }
565
566                 nwritten += result;
567         }
568
569         return nwritten;
570 }
571
572 /* Read data from winbindd socket */
573
574 static int winbind_read_sock(struct winbindd_context *ctx,
575                              void *buffer, int count)
576 {
577         int fd;
578         int nread = 0;
579         int total_time = 0;
580
581         fd = winbind_open_pipe_sock(ctx, false, false);
582         if (fd == -1) {
583                 return -1;
584         }
585
586         /* Read data from socket */
587         while(nread < count) {
588                 struct pollfd pfd;
589                 int ret;
590
591                 /* Catch pipe close on other end by checking if a read()
592                    call would not block by calling poll(). */
593
594                 pfd.fd = fd;
595                 pfd.events = POLLIN|POLLHUP;
596
597                 /* Wait for 5 seconds for a reply. May need to parameterise this... */
598
599                 ret = poll(&pfd, 1, 5000);
600                 if (ret == -1) {
601                         winbind_close_sock(ctx);
602                         return -1;                   /* poll error */
603                 }
604
605                 if (ret == 0) {
606                         /* Not ready for read yet... */
607                         if (total_time >= 300) {
608                                 /* Timeout */
609                                 winbind_close_sock(ctx);
610                                 return -1;
611                         }
612                         total_time += 5;
613                         continue;
614                 }
615
616                 if ((ret == 1) && (pfd.revents & (POLLIN|POLLHUP|POLLERR))) {
617
618                         /* Do the Read */
619
620                         int result = read(fd, (char *)buffer + nread,
621                               count - nread);
622
623                         if ((result == -1) || (result == 0)) {
624
625                                 /* Read failed.  I think the only useful thing we
626                                    can do here is just return -1 and fail since the
627                                    transaction has failed half way through. */
628
629                                 winbind_close_sock(ctx);
630                                 return -1;
631                         }
632
633                         nread += result;
634
635                 }
636         }
637
638         return nread;
639 }
640
641 /* Read reply */
642
643 static int winbindd_read_reply(struct winbindd_context *ctx,
644                                struct winbindd_response *response)
645 {
646         int result1, result2 = 0;
647
648         if (!response) {
649                 return -1;
650         }
651
652         /* Read fixed length response */
653
654         result1 = winbind_read_sock(ctx, response,
655                                     sizeof(struct winbindd_response));
656
657         /* We actually send the pointer value of the extra_data field from
658            the server.  This has no meaning in the client's address space
659            so we clear it out. */
660
661         response->extra_data.data = NULL;
662
663         if (result1 == -1) {
664                 return -1;
665         }
666
667         if (response->length < sizeof(struct winbindd_response)) {
668                 return -1;
669         }
670
671         /* Read variable length response */
672
673         if (response->length > sizeof(struct winbindd_response)) {
674                 int extra_data_len = response->length -
675                         sizeof(struct winbindd_response);
676
677                 /* Mallocate memory for extra data */
678
679                 if (!(response->extra_data.data = malloc(extra_data_len))) {
680                         return -1;
681                 }
682
683                 result2 = winbind_read_sock(ctx, response->extra_data.data,
684                                             extra_data_len);
685                 if (result2 == -1) {
686                         winbindd_free_response(response);
687                         return -1;
688                 }
689         }
690
691         /* Return total amount of data read */
692
693         return result1 + result2;
694 }
695
696 /*
697  * send simple types of requests
698  */
699
700 static NSS_STATUS winbindd_send_request(
701         struct winbindd_context *ctx,
702         int req_type,
703         int need_priv,
704         struct winbindd_request *request)
705 {
706         struct winbindd_request lrequest;
707
708         /* Check for our tricky environment variable */
709
710         if (winbind_env_set()) {
711                 return NSS_STATUS_NOTFOUND;
712         }
713
714         if (!request) {
715                 ZERO_STRUCT(lrequest);
716                 request = &lrequest;
717         }
718
719         /* Fill in request and send down pipe */
720
721         winbindd_init_request(request, req_type);
722
723         if (winbind_write_sock(ctx, request, sizeof(*request),
724                                request->wb_flags & WBFLAG_RECURSE,
725                                need_priv) == -1)
726         {
727                 /* Set ENOENT for consistency.  Required by some apps */
728                 errno = ENOENT;
729
730                 return NSS_STATUS_UNAVAIL;
731         }
732
733         if ((request->extra_len != 0) &&
734             (winbind_write_sock(ctx, request->extra_data.data,
735                                 request->extra_len,
736                                 request->wb_flags & WBFLAG_RECURSE,
737                                 need_priv) == -1))
738         {
739                 /* Set ENOENT for consistency.  Required by some apps */
740                 errno = ENOENT;
741
742                 return NSS_STATUS_UNAVAIL;
743         }
744
745         return NSS_STATUS_SUCCESS;
746 }
747
748 /*
749  * Get results from winbindd request
750  */
751
752 static NSS_STATUS winbindd_get_response(struct winbindd_context *ctx,
753                                         struct winbindd_response *response)
754 {
755         struct winbindd_response lresponse;
756
757         if (!response) {
758                 ZERO_STRUCT(lresponse);
759                 response = &lresponse;
760         }
761
762         init_response(response);
763
764         /* Wait for reply */
765         if (winbindd_read_reply(ctx, response) == -1) {
766                 /* Set ENOENT for consistency.  Required by some apps */
767                 errno = ENOENT;
768
769                 return NSS_STATUS_UNAVAIL;
770         }
771
772         /* Throw away extra data if client didn't request it */
773         if (response == &lresponse) {
774                 winbindd_free_response(response);
775         }
776
777         /* Copy reply data from socket */
778         if (response->result != WINBINDD_OK) {
779                 return NSS_STATUS_NOTFOUND;
780         }
781
782         return NSS_STATUS_SUCCESS;
783 }
784
785 /* Handle simple types of requests */
786
787 NSS_STATUS winbindd_request_response(struct winbindd_context *ctx,
788                                      int req_type,
789                                      struct winbindd_request *request,
790                                      struct winbindd_response *response)
791 {
792         NSS_STATUS status = NSS_STATUS_UNAVAIL;
793         bool release_global_ctx = false;
794
795         if (ctx == NULL) {
796                 ctx = get_wb_global_ctx();
797                 release_global_ctx = true;
798         }
799
800         status = winbindd_send_request(ctx, req_type, 0, request);
801         if (status != NSS_STATUS_SUCCESS) {
802                 goto out;
803         }
804         status = winbindd_get_response(ctx, response);
805
806 out:
807         if (release_global_ctx) {
808                 put_wb_global_ctx();
809         }
810         return status;
811 }
812
813 NSS_STATUS winbindd_priv_request_response(struct winbindd_context *ctx,
814                                           int req_type,
815                                           struct winbindd_request *request,
816                                           struct winbindd_response *response)
817 {
818         NSS_STATUS status = NSS_STATUS_UNAVAIL;
819         bool release_global_ctx = false;
820
821         if (ctx == NULL) {
822                 ctx = get_wb_global_ctx();
823                 release_global_ctx = true;
824         }
825
826         status = winbindd_send_request(ctx, req_type, 1, request);
827         if (status != NSS_STATUS_SUCCESS) {
828                 goto out;
829         }
830         status = winbindd_get_response(ctx, response);
831
832 out:
833         if (release_global_ctx) {
834                 put_wb_global_ctx();
835         }
836         return status;
837 }
838
839 /* Create and free winbindd context */
840
841 struct winbindd_context *winbindd_ctx_create(void)
842 {
843         struct winbindd_context *ctx;
844
845         ctx = calloc(1, sizeof(struct winbindd_context));
846
847         if (!ctx) {
848                 return NULL;
849         }
850
851         ctx->winbindd_fd = -1;
852
853         return ctx;
854 }
855
856 void winbindd_ctx_free(struct winbindd_context *ctx)
857 {
858         winbind_close_sock(ctx);
859         free(ctx);
860 }