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