671d58fc919b6c1412008c1667380ee85b8f10ee
[cifs-utils.git] / mount.cifs.c
1 /*
2  * Mount helper utility for Linux CIFS VFS (virtual filesystem) client
3  * Copyright (C) 2003,2010 Steve French  (sfrench@us.ibm.com)
4  * Copyright (C) 2008 Jeremy Allison (jra@samba.org)
5  * Copyright (C) 2010 Jeff Layton (jlayton@samba.org)
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 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif /* HAVE_CONFIG_H */
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <pwd.h>
29 #include <grp.h>
30 #include <ctype.h>
31 #include <sys/types.h>
32 #include <sys/mount.h>
33 #include <sys/stat.h>
34 #include <sys/utsname.h>
35 #include <sys/socket.h>
36 #include <arpa/inet.h>
37 #include <getopt.h>
38 #include <errno.h>
39 #include <netdb.h>
40 #include <string.h>
41 #include <mntent.h>
42 #include <fcntl.h>
43 #include <limits.h>
44 #include <stdbool.h>
45 #include <paths.h>
46 #include <libgen.h>
47 #include <time.h>
48 #include <sys/mman.h>
49 #include <sys/wait.h>
50 #ifdef HAVE_SYS_FSUID_H
51 #include <sys/fsuid.h>
52 #endif /* HAVE_SYS_FSUID_H */
53 #ifdef HAVE_LIBCAP_NG
54 #include <cap-ng.h>
55 #else /* HAVE_LIBCAP_NG */
56 #ifdef HAVE_PRCTL
57 #include <sys/prctl.h>
58 #endif /* HAVE_PRCTL */
59 #ifdef HAVE_LIBCAP
60 #include <sys/capability.h>
61 #endif /* HAVE_LIBCAP */
62 #endif /* HAVE_LIBCAP_NG */
63 #include "mount.h"
64 #include "util.h"
65 #include "resolve_host.h"
66 #include "build_assert.h"
67
68 #ifndef MS_MOVE 
69 #define MS_MOVE 8192 
70 #endif 
71
72 #ifndef MS_BIND
73 #define MS_BIND 4096
74 #endif
75
76 /* private flags - clear these before passing to kernel */
77 #define MS_USERS        0x40000000
78 #define MS_USER         0x80000000
79
80 #define MAX_UNC_LEN 1024
81
82 /* I believe that the kernel limits options data to a page */
83 #define MAX_OPTIONS_LEN 4096
84
85 /* max length of mtab options */
86 #define MTAB_OPTIONS_LEN 220
87
88 /*
89  * Max share name, username, password and domain sizes match the kernel's
90  * allowances for these string sizes which in turn match Microsoft's
91  * documentation.
92  */
93
94 /* Max length of the share name portion of a UNC. Share names over 80
95  * characters cannot be accessed via commandline in Windows 2000/XP. */
96 #define MAX_SHARE_LEN 256
97
98 /* Max user name length. */
99 #define MAX_USERNAME_SIZE 256
100
101 /* Max domain size. */
102 #define MAX_DOMAIN_SIZE 256
103
104 /* Max password size. */
105 #define MOUNT_PASSWD_SIZE 512
106
107 /*
108  * mount.cifs has been the subject of many "security" bugs that have arisen
109  * because of users and distributions installing it as a setuid root program
110  * before it had been audited for security holes. The default behavior is
111  * now to allow mount.cifs to be run as a setuid root program. Some admins
112  * may want to disable this fully, so this switch remains in place.
113  */
114 #define CIFS_DISABLE_SETUID_CAPABILITY 0
115
116 /*
117  * When an unprivileged user runs a setuid mount.cifs, we set certain mount
118  * flags by default. These defaults can be changed here.
119  */
120 #define CIFS_SETUID_FLAGS (MS_NOSUID|MS_NODEV)
121
122 /*
123  * Values for parsing a credentials file.
124  */
125 #define CRED_UNPARSEABLE 0
126 #define CRED_USER        1
127 #define CRED_PASS        2
128 #define CRED_DOM         4
129 #define CRED_PASS2               5
130
131 /*
132  * Values for parsing command line options.
133  */
134 #define OPT_ERROR       -1
135 #define OPT_IGNORE      0
136 #define OPT_USERS       1
137 #define OPT_USER        2
138 #define OPT_USER_XATTR  3
139 #define OPT_PASS        4
140 #define OPT_SEC         5
141 #define OPT_IP          6
142 #define OPT_UNC         7
143 #define OPT_CRED        8
144 #define OPT_UID         9
145 #define OPT_GID        10
146 #define OPT_FMASK      11
147 #define OPT_FILE_MODE  12
148 #define OPT_DMASK      13
149 #define OPT_DIR_MODE   14
150 #define OPT_DOM        15
151 #define OPT_NO_SUID    16
152 #define OPT_SUID       17
153 #define OPT_NO_DEV     18
154 #define OPT_DEV        19
155 #define OPT_NO_LOCK    20
156 #define OPT_NO_EXEC    21
157 #define OPT_EXEC       22
158 #define OPT_GUEST      23
159 #define OPT_RO         24
160 #define OPT_RW         25
161 #define OPT_REMOUNT    26
162 #define OPT_MAND       27
163 #define OPT_NOMAND     28
164 #define OPT_CRUID      29
165 #define OPT_BKUPUID    30
166 #define OPT_BKUPGID    31
167 #define OPT_NOFAIL     32
168 #define OPT_SNAPSHOT   33
169 #define OPT_PASS2          34
170
171 #define MNT_TMP_FILE "/.mtab.cifs.XXXXXX"
172
173 #define GMT_NAME_LEN 24 /* length of a @GMT- name */
174 #define GMT_FORMAT "@GMT-%Y.%m.%d-%H.%M.%S"
175
176 #define NTFS_TIME_OFFSET ((unsigned long long)(369*365 + 89) * 24 * 3600 * 10000000)
177
178 /*
179 * struct for holding parsed mount info for use by privileged process.
180 * Please do not keep pointers in this struct.
181 * That way, reinit of this struct is a simple memset.
182 */
183 struct parsed_mount_info {
184         unsigned long flags;
185         char host[NI_MAXHOST + 1];
186         char share[MAX_SHARE_LEN + 1];
187         char prefix[PATH_MAX + 1];
188         char options[MAX_OPTIONS_LEN];
189         char domain[MAX_DOMAIN_SIZE + 1];
190         char username[MAX_USERNAME_SIZE + 1];
191         char password[MOUNT_PASSWD_SIZE + 1];
192         char password2[MOUNT_PASSWD_SIZE + 1];
193         char addrlist[MAX_ADDR_LIST_LEN];
194         unsigned int got_user:1;
195         unsigned int got_password:1;
196         unsigned int got_password2:1;
197         unsigned int fakemnt:1;
198         unsigned int nomtab:1;
199         unsigned int verboseflag:1;
200         unsigned int nofail:1;
201         unsigned int got_domain:1;
202         unsigned int is_krb5:1;
203         unsigned int is_noauth:1;
204         unsigned int is_guest:1;
205         uid_t sudo_uid;
206 };
207
208 static const char *thisprogram;
209 static const char *cifs_fstype;
210
211 static int parse_unc(const char *unc_name, struct parsed_mount_info *parsed_info, const char *progname);
212
213 static int check_setuid(void)
214 {
215         if (geteuid()) {
216                 fprintf(stderr, "This program is not installed setuid root - "
217                         " \"user\" CIFS mounts not supported.\n");
218                 return EX_USAGE;
219         }
220
221 #if CIFS_DISABLE_SETUID_CAPABILITY
222         if (getuid() && !geteuid()) {
223                 printf("This program has been built with the "
224                        "ability to run as a setuid root program disabled.\n");
225                 return EX_USAGE;
226         }
227 #endif /* CIFS_DISABLE_SETUID_CAPABILITY */
228
229         return 0;
230 }
231
232 static int
233 check_fstab(const char *progname, const char *mountpoint, const char *devname,
234             char **options)
235 {
236         FILE *fstab;
237         struct mntent *mnt;
238         size_t len;
239
240         /* make sure this mount is listed in /etc/fstab */
241         fstab = setmntent(_PATH_MNTTAB, "r");
242         if (!fstab) {
243                 fprintf(stderr, "Couldn't open %s for reading!\n", _PATH_MNTTAB);
244                 return EX_FILEIO;
245         }
246
247         while ((mnt = getmntent(fstab))) {
248                 len = strlen(mnt->mnt_dir);
249                 while (len > 1) {
250                         if (mnt->mnt_dir[len - 1] == '/')
251                                 mnt->mnt_dir[len - 1] = '\0';
252                         else
253                                 break;
254                         len--;
255                 }
256                 if (!strcmp(mountpoint, mnt->mnt_dir))
257                         break;
258         }
259         endmntent(fstab);
260
261         if (mnt == NULL || strcmp(mnt->mnt_fsname, devname)) {
262                 fprintf(stderr, "%s: permission denied: no match for "
263                         "%s found in %s\n", progname, mountpoint, _PATH_MNTTAB);
264                 return EX_USAGE;
265         }
266
267         /*
268          * 'mount' munges the options from fstab before passing them
269          * to us. It is non-trivial to test that we have the correct
270          * set of options. We don't want to trust what the user
271          * gave us, so just take whatever is in /etc/fstab.
272          */
273         *options = strdup(mnt->mnt_opts);
274         return 0;
275 }
276
277 /* BB finish BB
278
279         cifs_umount
280         open nofollow - avoid symlink exposure? 
281         get owner of dir see if matches self or if root
282         call system(umount argv) etc.
283
284 BB end finish BB */
285
286 static int mount_usage(FILE * stream)
287 {
288         fprintf(stream, "\nUsage:  %s <remotetarget> <dir> -o <options>\n",
289                 thisprogram);
290         fprintf(stream, "\nMount the remote target, specified as a UNC name,");
291         fprintf(stream, " to a local directory.\n\nOptions:\n");
292         fprintf(stream, "\tuser=<arg>\n\tpass=<arg>\n\tdom=<arg>\n");
293         fprintf(stream, "\nLess commonly used options:");
294         fprintf(stream,
295                 "\n\tcredentials=<filename>,guest,perm,noperm,setuids,nosetuids,rw,ro,");
296         fprintf(stream,
297                 "\n\tsep=<char>,iocharset=<codepage>,suid,nosuid,exec,noexec,serverino,");
298         fprintf(stream,
299                 "\n\tnoserverino,mapchars,nomapchars,nolock,servernetbiosname=<SRV_RFC1001NAME>");
300         fprintf(stream,
301                 "\n\tcache=<strict|none|loose>,nounix,cifsacl,sec=<authentication mechanism>,");
302         fprintf(stream,
303                 "\n\tsign,seal,fsc,snapshot=<token|time>,nosharesock,persistenthandles,");
304         fprintf(stream,
305                 "\n\tresilienthandles,rdma,vers=<smb_dialect>,cruid,password2=<alt password>");
306         fprintf(stream,
307                 "\n\nOptions not needed for servers supporting CIFS Unix extensions");
308         fprintf(stream,
309                 "\n\t(e.g. unneeded for mounts to most Samba versions):");
310         fprintf(stream,
311                 "\n\tuid=<uid>,gid=<gid>,dir_mode=<mode>,file_mode=<mode>,sfu,");
312         fprintf(stream,
313                 "\n\tmfsymlinks,idsfromsid");
314         fprintf(stream, "\n\nRarely used options:");
315         fprintf(stream,
316                 "\n\tport=<tcpport>,rsize=<size>,wsize=<size>,unc=<unc_name>,ip=<ip_address>,");
317         fprintf(stream,
318                 "\n\tdev,nodev,nouser_xattr,netbiosname=<OUR_RFC1001NAME>,hard,soft,intr,");
319         fprintf(stream,
320                 "\n\tnointr,ignorecase,noposixpaths,noacl,prefixpath=<path>,nobrl,");
321         fprintf(stream,
322                 "\n\techo_interval=<seconds>,actimeo=<seconds>,max_credits=<credits>,");
323         fprintf(stream,
324                 "\n\tbsize=<size>");
325         fprintf(stream,
326                 "\n\nOptions are described in more detail in the manual page");
327         fprintf(stream, "\n\tman 8 %s\n", thisprogram);
328         fprintf(stream, "\nTo display the version number of the mount helper:");
329         fprintf(stream, "\n\t%s -V\n", thisprogram);
330
331         if (stream == stderr)
332                 return EX_USAGE;
333         return 0;
334 }
335
336 /*
337  * CIFS has to "escape" commas in the password field so that they don't
338  * end up getting confused for option delimiters. Copy password into pw
339  * field, turning any commas into double commas.
340  */
341 static int
342 set_password(struct parsed_mount_info *parsed_info, const char *src,
343                            const int which_pass)
344 {
345         int is_pass2 = which_pass == OPT_PASS2 || which_pass == CRED_PASS2;
346
347         char *dst = is_pass2 ? parsed_info->password2 : parsed_info->password;
348         unsigned int i = 0, j = 0;
349         BUILD_ASSERT(sizeof(parsed_info->password) == sizeof(parsed_info->password2));
350
351         while (src[i]) {
352                 if (j + 2 >= sizeof(parsed_info->password)) {
353                         fprintf(stderr, "Converted password too long!\n");
354                         return EX_USAGE;
355                 }
356                 if (src[i] == ',')
357                         dst[j++] = ',';
358                 dst[j++] = src[i++];
359         }
360         dst[j] = '\0';
361         if (is_pass2)
362                 parsed_info->got_password2 = 1;
363         else
364                 parsed_info->got_password = 1;
365
366         return 0;
367 }
368
369 #ifdef HAVE_LIBCAP_NG
370 static int
371 drop_capabilities(int parent)
372 {
373         capng_select_t set = CAPNG_SELECT_CAPS;
374
375         capng_setpid(getpid());
376         capng_clear(CAPNG_SELECT_BOTH);
377         if (parent) {
378                 if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_READ_SEARCH, CAP_DAC_OVERRIDE, -1)) {
379                         fprintf(stderr, "Unable to update capability set.\n");
380                         return EX_SYSERR;
381                 }
382                 if (capng_update(CAPNG_ADD, CAPNG_PERMITTED|CAPNG_EFFECTIVE, CAP_SYS_ADMIN)) {
383                         fprintf(stderr, "Unable to update capability set.\n");
384                         return EX_SYSERR;
385                 }
386         } else {
387                 if (capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_READ_SEARCH)) {
388                         fprintf(stderr, "Unable to update capability set.\n");
389                         return EX_SYSERR;
390                 }
391         }
392         if (capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) {
393                 set = CAPNG_SELECT_BOTH;
394         }
395         if (capng_apply(set)) {
396                 fprintf(stderr, "Unable to apply new capability set.\n");
397                 return EX_SYSERR;
398         }
399         return 0;
400 }
401
402 static int
403 toggle_dac_capability(int writable, int enable)
404 {
405         unsigned int capability = writable ? CAP_DAC_OVERRIDE : CAP_DAC_READ_SEARCH;
406
407         if (capng_update(enable ? CAPNG_ADD : CAPNG_DROP, CAPNG_EFFECTIVE, capability)) {
408                 fprintf(stderr, "Unable to update capability set.\n");
409                 return EX_SYSERR;
410         }
411         if (capng_apply(CAPNG_SELECT_CAPS)) {
412                 fprintf(stderr, "Unable to apply new capability set.\n");
413                 return EX_SYSERR;
414         }
415         return 0;
416 }
417 #else /* HAVE_LIBCAP_NG */
418 #ifdef HAVE_LIBCAP
419 #ifdef HAVE_PRCTL
420 static int
421 prune_bounding_set(void)
422 {
423         int i, rc = 0;
424         static int bounding_set_cleared;
425
426         if (bounding_set_cleared)
427                 return 0;
428
429         for (i = 0; i <= CAP_LAST_CAP && rc == 0; ++i)
430                 rc = prctl(PR_CAPBSET_DROP, i);
431
432         if (rc != 0) {
433                 fprintf(stderr, "Unable to clear capability bounding set: %d\n", rc);
434                 return EX_SYSERR;
435         }
436
437         ++bounding_set_cleared;
438         return 0;
439 }
440 #else /* HAVE_PRCTL */
441 static int
442 prune_bounding_set(void)
443 {
444         return 0;
445 }
446 #endif /* HAVE_PRCTL */
447 static int
448 drop_capabilities(int parent)
449 {
450         int rc, ncaps;
451         cap_t caps;
452         cap_value_t cap_list[3];
453
454         rc = prune_bounding_set();
455         if (rc)
456                 return rc;
457
458         caps = cap_get_proc();
459         if (caps == NULL) {
460                 fprintf(stderr, "Unable to get current capability set: %s\n",
461                         strerror(errno));
462                 return EX_SYSERR;
463         }
464
465         if (cap_clear(caps) == -1) {
466                 fprintf(stderr, "Unable to clear capability set: %s\n",
467                         strerror(errno));
468                 rc = EX_SYSERR;
469                 goto free_caps;
470         }
471
472         if (parent || getuid() == 0) {
473                 ncaps = 1;
474                 cap_list[0] = CAP_DAC_READ_SEARCH;
475                 if (parent) {
476                         cap_list[1] = CAP_DAC_OVERRIDE;
477                         cap_list[2] = CAP_SYS_ADMIN;
478                         ncaps += 2;
479                 }
480                 if (cap_set_flag(caps, CAP_PERMITTED, ncaps, cap_list, CAP_SET) == -1) {
481                         fprintf(stderr, "Unable to set permitted capabilities: %s\n",
482                                 strerror(errno));
483                         rc = EX_SYSERR;
484                         goto free_caps;
485                 }
486                 if (parent) {
487                         cap_list[0] = CAP_SYS_ADMIN;
488                         if (cap_set_flag(caps, CAP_EFFECTIVE, 1, cap_list, CAP_SET) == -1) {
489                                 fprintf(stderr, "Unable to set effective capabilities: %s\n",
490                                         strerror(errno));
491                                 rc = EX_SYSERR;
492                                 goto free_caps;
493                         }
494                 }
495         }
496
497         if (cap_set_proc(caps) != 0) {
498                 fprintf(stderr, "Unable to set current process capabilities: %s\n",
499                         strerror(errno));
500                 rc = EX_SYSERR;
501         }
502 free_caps:
503         cap_free(caps);
504         return rc;
505 }
506
507 static int
508 toggle_dac_capability(int writable, int enable)
509 {
510         int rc = 0;
511         cap_t caps;
512         cap_value_t capability = writable ? CAP_DAC_OVERRIDE : CAP_DAC_READ_SEARCH;
513
514         caps = cap_get_proc();
515         if (caps == NULL) {
516                 fprintf(stderr, "Unable to get current capability set: %s\n",
517                         strerror(errno));
518                 return EX_SYSERR;
519         }
520
521         if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &capability,
522                          enable ? CAP_SET : CAP_CLEAR) == -1) {
523                 fprintf(stderr, "Unable to %s effective capabilities: %s\n",
524                         enable ? "set" : "clear", strerror(errno));
525                 rc = EX_SYSERR;
526                 goto free_caps;
527         }
528
529         if (cap_set_proc(caps) != 0) {
530                 fprintf(stderr, "Unable to set current process capabilities: %s\n",
531                         strerror(errno));
532                 rc = EX_SYSERR;
533         }
534 free_caps:
535         cap_free(caps);
536         return rc;
537 }
538 #else /* HAVE_LIBCAP */
539 static int
540 drop_capabilities(int parent __attribute((unused)))
541 {
542         return 0;
543 }
544
545 static int
546 toggle_dac_capability(int writable __attribute((unused)), int enable __attribute((unused)))
547 {
548         return 0;
549 }
550 #endif /* HAVE_LIBCAP */
551 #endif /* HAVE_LIBCAP_NG */
552
553 static void null_terminate_endl(char *source)
554 {
555         char *newline = strchr(source, '\n');
556         if (newline)
557                 *newline = '\0';
558 }
559
560 /*
561  * Parse a line from the credentials file.  Changes target to first
562  * character after '=' on 'line' and returns the value type of the line
563  * Returns CRED_UNPARSEABLE on failure or if either parameter is NULL.
564  */
565 static int parse_cred_line(char *line, char **target)
566 {
567         if (line == NULL || target == NULL)
568                 goto parsing_err;
569
570         /* position target at first char of value */
571         *target = strchr(line, '=');
572         if (!*target)
573                 goto parsing_err;
574         *target += 1;
575
576         /* tell the caller which value target points to */
577         if (strncasecmp("user", line, 4) == 0)
578                 return CRED_USER;
579         if (strncasecmp("pass2", line, 5) == 0 ||
580                 strncasecmp("password2", line, 9) == 0)
581                 return CRED_PASS2;
582         if (strncasecmp("pass", line, 4) == 0)
583                 return CRED_PASS;
584         if (strncasecmp("dom", line, 3) == 0)
585                 return CRED_DOM;
586
587 parsing_err:
588         return CRED_UNPARSEABLE;
589 }
590
591 static int check_creds_field(const char *v)
592 {
593         return strpbrk(v, ",=\r\n") != NULL;
594 }
595
596 static int open_cred_file(char *file_name,
597                         struct parsed_mount_info *parsed_info)
598 {
599         char *line_buf = NULL;
600         char *temp_val = NULL;
601         FILE *fs = NULL;
602         int i;
603         const int line_buf_size = 4096;
604         const int min_non_white = 10;
605
606         i = toggle_dac_capability(0, 1);
607         if (i)
608                 goto return_i;
609
610         i = access(file_name, R_OK);
611         if (i) {
612                 toggle_dac_capability(0, 0);
613                 i = errno;
614                 goto return_i;
615         }
616
617         fs = fopen(file_name, "r");
618         if (fs == NULL) {
619                 toggle_dac_capability(0, 0);
620                 i = errno;
621                 goto return_i;
622         }
623
624         i = toggle_dac_capability(0, 0);
625         if (i)
626                 goto return_i;
627
628         line_buf = (char *)malloc(line_buf_size);
629         if (line_buf == NULL) {
630                 i = EX_SYSERR;
631                 goto return_i;
632         }
633
634         /* parse line from credentials file */
635         while (fgets(line_buf, line_buf_size, fs)) {
636                 /* eat leading white space */
637                 for (i = 0; i < line_buf_size - min_non_white + 1; i++) {
638                         if ((line_buf[i] != ' ') && (line_buf[i] != '\t'))
639                                 break;
640                 }
641                 null_terminate_endl(line_buf);
642
643                 /* parse next token */
644                 switch (parse_cred_line(line_buf + i, &temp_val)) {
645                 case CRED_USER:
646                         if (check_creds_field(temp_val)) {
647                                 fprintf(stderr, "Invalid username in credentials file\n");
648                                 i = EX_USAGE;
649                                 goto return_i;
650                         }
651                         strlcpy(parsed_info->username, temp_val,
652                                 sizeof(parsed_info->username));
653                         parsed_info->got_user = 1;
654                         break;
655                 case CRED_PASS:
656                         i = set_password(parsed_info, temp_val, CRED_PASS);
657                         if (i)
658                                 goto return_i;
659                         break;
660                 case CRED_PASS2:
661                         i = set_password(parsed_info, temp_val, CRED_PASS2);
662                         if (i)
663                                 goto return_i;
664                         break;
665                 case CRED_DOM:
666                         if (check_creds_field(temp_val)) {
667                                 fprintf(stderr, "Invalid domain in credentials file\n");
668                                 i = EX_USAGE;
669                                 goto return_i;
670                         }
671                         strlcpy(parsed_info->domain, temp_val,
672                                 sizeof(parsed_info->domain));
673                         break;
674                 case CRED_UNPARSEABLE:
675                         if (parsed_info->verboseflag)
676                                 fprintf(stderr, "Credential formatted "
677                                         "incorrectly\n");
678                         break;
679                 }
680         }
681         i = 0;
682 return_i:
683         if (fs != NULL)
684                 fclose(fs);
685
686         /* make sure passwords are scrubbed from memory */
687         if (line_buf != NULL)
688                 memset(line_buf, 0, line_buf_size);
689         free(line_buf);
690         return i;
691 }
692
693 static int
694 get_password_from_file(int file_descript, char *filename,
695                        struct parsed_mount_info *parsed_info, const char *program,
696                            const int which_pass)
697 {
698         int rc = 0;
699         char buf[sizeof(parsed_info->password)];
700         BUILD_ASSERT(sizeof(parsed_info->password) == sizeof(parsed_info->password2));
701
702         if (filename != NULL) {
703                 rc = toggle_dac_capability(0, 1);
704                 if (rc)
705                         return rc;
706
707                 rc = access(filename, R_OK);
708                 if (rc) {
709                         fprintf(stderr,
710                                 "%s failed: access check of %s failed: %s\n",
711                                 program, filename, strerror(errno));
712                         toggle_dac_capability(0, 0);
713                         return EX_SYSERR;
714                 }
715
716                 file_descript = open(filename, O_RDONLY);
717                 if (file_descript < 0) {
718                         fprintf(stderr,
719                                 "%s failed. %s attempting to open password file %s\n",
720                                 program, strerror(errno), filename);
721                         toggle_dac_capability(0, 0);
722                         return EX_SYSERR;
723                 }
724
725                 rc = toggle_dac_capability(0, 0);
726                 if (rc) {
727                         rc = EX_SYSERR;
728                         goto get_pw_exit;
729                 }
730         }
731
732         memset(buf, 0, sizeof(buf));
733         rc = read(file_descript, buf, sizeof(buf) - 1);
734         if (rc < 0) {
735                 fprintf(stderr,
736                         "%s failed. Error %s reading password file\n",
737                         program, strerror(errno));
738                 rc = EX_SYSERR;
739                 goto get_pw_exit;
740         }
741
742         rc = set_password(parsed_info, buf, which_pass);
743
744 get_pw_exit:
745         if (filename != NULL)
746                 close(file_descript);
747         return rc;
748 }
749
750 /*
751  * Returns OPT_ERROR on unparsable token.
752  */
753 static int parse_opt_token(const char *token)
754 {
755         if (token == NULL)
756                 return OPT_ERROR;
757
758         /*
759          * token is NULL terminated and contains exactly the
760          * keyword so we can match exactly
761          */
762         if (strcmp(token, "users") == 0)
763                 return OPT_USERS;
764         if (strcmp(token, "user_xattr") == 0)
765                 return OPT_USER_XATTR;
766         if (strcmp(token, "user") == 0 ||
767                 strcmp(token, "username") == 0)
768                 return OPT_USER;
769         if (strcmp(token, "pass") == 0 ||
770                 strcmp(token, "password") == 0)
771                 return OPT_PASS;
772         if (strcmp(token, "pass2") == 0 ||
773                 strcmp(token, "password2") == 0)
774                 return OPT_PASS2;
775         if (strcmp(token, "sec") == 0)
776                 return OPT_SEC;
777         if (strcmp(token, "ip") == 0 ||
778                 strcmp(token, "addr") == 0)
779                 return OPT_IP;
780         if (strcmp(token, "unc") == 0 ||
781                 strcmp(token, "target") == 0 ||
782                 strcmp(token, "path") == 0)
783                 return OPT_UNC;
784         if (strcmp(token, "dom") == 0 ||
785                 strcmp(token, "domain") == 0 ||
786                 strcmp(token, "workgroup") == 0)
787                 return OPT_DOM;
788         if (strcmp(token, "cred") == 0 || /* undocumented */
789                 strcmp(token, "credentials") == 0)
790                 return OPT_CRED;
791         if (strcmp(token, "uid") == 0)
792                 return OPT_UID;
793         if (strcmp(token, "cruid") == 0)
794                 return OPT_CRUID;
795         if (strcmp(token, "gid") == 0)
796                 return OPT_GID;
797         if (strcmp(token, "fmask") == 0)
798                 return OPT_FMASK;
799         if (strcmp(token, "file_mode") == 0)
800                 return OPT_FILE_MODE;
801         if (strcmp(token, "dmask") == 0)
802                 return OPT_DMASK;
803         if (strcmp(token, "dir_mode") == 0 ||
804                 strcmp(token, "dirm") == 0)
805                 return OPT_DIR_MODE;
806         if (strcmp(token, "nosuid") == 0)
807                 return OPT_NO_SUID;
808         if (strcmp(token, "suid") == 0)
809                 return OPT_SUID;
810         if (strcmp(token, "nodev") == 0)
811                 return OPT_NO_DEV;
812         if (strcmp(token, "nobrl") == 0 ||
813                 strcmp(token, "nolock") == 0)
814                 return OPT_NO_LOCK;
815         if (strcmp(token, "mand") == 0)
816                 return OPT_MAND;
817         if (strcmp(token, "nomand") == 0)
818                 return OPT_NOMAND;
819         if (strcmp(token, "dev") == 0)
820                 return OPT_DEV;
821         if (strcmp(token, "noexec") == 0)
822                 return OPT_NO_EXEC;
823         if (strcmp(token, "exec") == 0)
824                 return OPT_EXEC;
825         if (strcmp(token, "guest") == 0)
826                 return OPT_GUEST;
827         if (strcmp(token, "ro") == 0)
828                 return OPT_RO;
829         if (strcmp(token, "rw") == 0)
830                 return OPT_RW;
831         if (strcmp(token, "remount") == 0)
832                 return OPT_REMOUNT;
833         if (strcmp(token, "_netdev") == 0)
834                 return OPT_IGNORE;
835         if (strcmp(token, "backupuid") == 0)
836                 return OPT_BKUPUID;
837         if (strcmp(token, "backupgid") == 0)
838                 return OPT_BKUPGID;
839         if (strcmp(token, "nofail") == 0)
840                 return OPT_NOFAIL;
841         if (strcmp(token, "comment") == 0)
842                 return OPT_IGNORE;
843         if (strncmp(token, "x-", 2) == 0)
844                 return OPT_IGNORE;
845         if (strncmp(token, "snapshot", 8) == 0)
846                 return OPT_SNAPSHOT;
847
848         return OPT_ERROR;
849 }
850
851 static int
852 parse_options(char *data, struct parsed_mount_info *parsed_info)
853 {
854         char *value = NULL;
855         char *equals = NULL;
856         char *next_keyword = NULL;
857         char *out = parsed_info->options;
858         unsigned long *filesys_flags = &parsed_info->flags;
859         int out_len = 0;
860         int word_len;
861         int rc = 0;
862         int got_bkupuid = 0;
863         int got_bkupgid = 0;
864         int got_uid = 0;
865         int got_cruid = 0;
866         int got_gid = 0;
867         int got_snapshot = 0;
868         uid_t uid, cruid = 0, bkupuid = 0;
869         gid_t gid, bkupgid = 0;
870         char *ep;
871         struct passwd *pw;
872         struct group *gr;
873         /*
874          * max 64-bit uint in decimal is 18446744073709551615 which is 20 chars
875          * wide +1 for NULL, and +1 for good measure
876          */
877         char txtbuf[22];
878         unsigned long long snapshot = 0;
879         struct tm tm;
880
881         /* make sure we're starting from beginning */
882         out[0] = '\0';
883
884         /* BB fixme check for separator override BB */
885         uid = getuid();
886         if (uid != 0)
887                 got_uid = 1;
888
889         gid = getgid();
890         if (gid != 0)
891                 got_gid = 1;
892
893         if (!data)
894                 return EX_USAGE;
895
896         /*
897          * format is keyword,keyword2=value2,keyword3=value3... 
898          * data  = next keyword
899          * value = next value ie stuff after equal sign
900          */
901         while (data && *data) {
902                 next_keyword = strchr(data, ',');       /* BB handle sep= */
903
904                 /* temporarily null terminate end of keyword=value pair */
905                 if (next_keyword)
906                         *next_keyword++ = 0;
907
908                 /* temporarily null terminate keyword if there's a value */
909                 value = NULL;
910                 if ((equals = strchr(data, '=')) != NULL) {
911                         *equals = '\0';
912                         value = equals + 1;
913                 }
914
915                 switch(parse_opt_token(data)) {
916                 case OPT_USERS:
917                         if (!value || !*value) {
918                                 *filesys_flags |= MS_USERS;
919                                 goto nocopy;
920                         }
921                         break;
922
923                 case OPT_USER:
924                         if (!value || !*value) {
925                                 if (data[4] == '\0') {
926                                         *filesys_flags |= MS_USER;
927                                         goto nocopy;
928                                 } else {
929                                         fprintf(stderr,
930                                                 "username specified with no parameter\n");
931                                         return EX_USAGE;
932                                 }
933                         } else {
934                                 strlcpy(parsed_info->username, value,
935                                         sizeof(parsed_info->username));
936                                 parsed_info->got_user = 1;
937                                 goto nocopy;
938                         }
939
940                 case OPT_PASS:
941                         if (parsed_info->got_password) {
942                                 fprintf(stderr,
943                                         "password specified twice, ignoring second\n");
944                                 goto nocopy;
945                         }
946                         if (!value || !*value) {
947                                 parsed_info->got_password = 1;
948                                 goto nocopy;
949                         }
950                         rc = set_password(parsed_info, value, OPT_PASS);
951                         if (rc)
952                                 return rc;
953                         goto nocopy;
954
955                 case OPT_PASS2:
956                 if (parsed_info->got_password2) {
957                                 fprintf(stderr,
958                                         "password2 specified twice, ignoring second\n");
959                                 goto nocopy;
960                         }
961                         if (!value || !*value) {
962                                 parsed_info->got_password2 = 1;
963                                 goto nocopy;
964                         }
965                         rc = set_password(parsed_info, value, OPT_PASS2);
966                         if (rc)
967                                 return rc;
968                         goto nocopy;
969
970                 case OPT_SEC:
971                         if (value) {
972                                 if (!strncmp(value, "none", 4)) {
973                                         parsed_info->is_noauth = 1;
974                                         parsed_info->got_password = 1;
975                                         parsed_info->got_password2 = 1;
976                                 }
977                                 if (!strncmp(value, "krb5", 4)) {
978                                         parsed_info->is_krb5 = 1;
979                                         parsed_info->got_password = 1;
980                                         parsed_info->got_password2 = 1;
981                                 }
982                         }
983                         break;
984
985                 case OPT_IP:
986                         if (!value || !*value) {
987                                 fprintf(stderr,
988                                         "target ip address argument missing\n");
989                         } else if (strnlen(value, MAX_ADDRESS_LEN) <
990                                 MAX_ADDRESS_LEN) {
991                                 strlcpy(parsed_info->addrlist, value,
992                                         MAX_ADDRESS_LEN);
993                                 if (parsed_info->verboseflag)
994                                         fprintf(stderr,
995                                                 "ip address %s override specified\n",
996                                                 value);
997                                 goto nocopy;
998                         } else {
999                                 fprintf(stderr, "ip address too long\n");
1000                                 return EX_USAGE;
1001
1002                         }
1003                         break;
1004
1005                 /* unc || target || path */
1006                 case OPT_UNC:
1007                         if (!value || !*value) {
1008                                 fprintf(stderr,
1009                                         "invalid path to network resource\n");
1010                                 return EX_USAGE;
1011                         }
1012                         rc = parse_unc(value, parsed_info, thisprogram);
1013                         if (rc)
1014                                 return rc;
1015                         break;
1016
1017                 /* dom || workgroup */
1018                 case OPT_DOM:
1019                         if (!value) {
1020                                 /*
1021                                  * An empty domain has been passed
1022                                  */
1023                                 /* not necessary but better safe than.. */
1024                                 parsed_info->domain[0] = '\0';
1025                                 parsed_info->got_domain = 1;
1026                                 goto nocopy;
1027                         }
1028                         if (strnlen(value, sizeof(parsed_info->domain)) >=
1029                             sizeof(parsed_info->domain)) {
1030                                 fprintf(stderr, "domain name too long\n");
1031                                 return EX_USAGE;
1032                         }
1033                         strlcpy(parsed_info->domain, value,
1034                                 sizeof(parsed_info->domain));
1035                         goto nocopy;
1036
1037                 case OPT_CRED:
1038                         if (!value || !*value) {
1039                                 fprintf(stderr,
1040                                         "invalid credential file name specified\n");
1041                                 return EX_USAGE;
1042                         }
1043                         rc = open_cred_file(value, parsed_info);
1044                         if (rc) {
1045                                 fprintf(stderr,
1046                                         "error %d (%s) opening credential file %s\n",
1047                                         rc, strerror(rc), value);
1048                                 return rc;
1049                         }
1050                         goto nocopy;
1051
1052                 case OPT_UID:
1053                         if (!value || !*value)
1054                                 goto nocopy;
1055
1056                         got_uid = 1;
1057                         pw = getpwnam(value);
1058                         if (pw) {
1059                                 uid = pw->pw_uid;
1060                                 goto nocopy;
1061                         }
1062
1063                         errno = 0;
1064                         uid = strtoul(value, &ep, 10);
1065                         if (errno == 0 && *ep == '\0')
1066                                 goto nocopy;
1067
1068                         fprintf(stderr, "bad option uid=\"%s\"\n", value);
1069                         return EX_USAGE;
1070                 case OPT_CRUID:
1071                         if (!value || !*value)
1072                                 goto nocopy;
1073
1074                         got_cruid = 1;
1075                         pw = getpwnam(value);
1076                         if (pw) {
1077                                 cruid = pw->pw_uid;
1078                                 goto nocopy;
1079                         }
1080
1081                         errno = 0;
1082                         cruid = strtoul(value, &ep, 10);
1083                         if (errno == 0 && *ep == '\0')
1084                                 goto nocopy;
1085
1086                         fprintf(stderr, "bad option: cruid=\"%s\"\n", value);
1087                         return EX_USAGE;
1088                 case OPT_GID:
1089                         if (!value || !*value)
1090                                 goto nocopy;
1091
1092                         got_gid = 1;
1093                         gr = getgrnam(value);
1094                         if (gr) {
1095                                 gid = gr->gr_gid;
1096                                 goto nocopy;
1097                         }
1098
1099                         errno = 0;
1100                         gid = strtoul(value, &ep, 10);
1101                         if (errno == 0 && *ep == '\0')
1102                                 goto nocopy;
1103
1104                         fprintf(stderr, "bad option: gid=\"%s\"\n", value);
1105                         return EX_USAGE;
1106                 /* fmask falls through to file_mode */
1107                 case OPT_FMASK:
1108                         fprintf(stderr,
1109                                 "WARNING: CIFS mount option 'fmask' is\
1110                                  deprecated. Use 'file_mode' instead.\n");
1111                         data = "file_mode";     /* BB fix this */
1112                         /* Fallthrough */
1113                 case OPT_FILE_MODE:
1114                         if (!value || !*value) {
1115                                 fprintf(stderr,
1116                                         "Option '%s' requires a numerical argument\n",
1117                                         data);
1118                                 return EX_USAGE;
1119                         }
1120
1121                         if (value[0] != '0')
1122                                 fprintf(stderr,
1123                                         "WARNING: '%s' not expressed in octal.\n",
1124                                         data);
1125                         break;
1126
1127                 /* dmask falls through to dir_mode */
1128                 case OPT_DMASK:
1129                         fprintf(stderr,
1130                                 "WARNING: CIFS mount option 'dmask' is\
1131                                  deprecated. Use 'dir_mode' instead.\n");
1132                         data = "dir_mode";
1133                         /* Fallthrough */
1134                 case OPT_DIR_MODE:
1135                         if (!value || !*value) {
1136                                 fprintf(stderr,
1137                                         "Option '%s' requires a numerical argument\n",
1138                                         data);
1139                                 return EX_USAGE;
1140                         }
1141
1142                         if (value[0] != '0')
1143                                 fprintf(stderr,
1144                                         "WARNING: '%s' not expressed in octal.\n",
1145                                         data);
1146                         break;
1147                 case OPT_NO_SUID:
1148                         *filesys_flags |= MS_NOSUID;
1149                         goto nocopy;
1150                 case OPT_SUID:
1151                         *filesys_flags &= ~MS_NOSUID;
1152                         goto nocopy;
1153                 case OPT_NO_DEV:
1154                         *filesys_flags |= MS_NODEV;
1155                         goto nocopy;
1156                 case OPT_NO_LOCK:
1157                         *filesys_flags &= ~MS_MANDLOCK;
1158                         break;
1159                 case OPT_MAND:
1160                         *filesys_flags |= MS_MANDLOCK;
1161                         goto nocopy;
1162                 case OPT_NOMAND:
1163                         *filesys_flags &= ~MS_MANDLOCK;
1164                         goto nocopy;
1165                 case OPT_DEV:
1166                         *filesys_flags &= ~MS_NODEV;
1167                         goto nocopy;
1168                 case OPT_NO_EXEC:
1169                         *filesys_flags |= MS_NOEXEC;
1170                         goto nocopy;
1171                 case OPT_EXEC:
1172                         *filesys_flags &= ~MS_NOEXEC;
1173                         goto nocopy;
1174                 case OPT_GUEST:
1175                         parsed_info->is_guest = 1;
1176                         parsed_info->got_user = 1;
1177                         parsed_info->got_password = 1;
1178                         parsed_info->got_password2 = 1;
1179                         goto nocopy;
1180                 case OPT_RO:
1181                         *filesys_flags |= MS_RDONLY;
1182                         goto nocopy;
1183                 case OPT_RW:
1184                         *filesys_flags &= ~MS_RDONLY;
1185                         goto nocopy;
1186                 case OPT_REMOUNT:
1187                         *filesys_flags |= MS_REMOUNT;
1188                         goto nocopy;
1189                 case OPT_IGNORE:
1190                         goto nocopy;
1191                 case OPT_BKUPUID:
1192                         if (!value || !*value)
1193                                 goto nocopy;
1194
1195                         got_bkupuid = 1;
1196                         errno = 0;
1197                         bkupuid = strtoul(value, &ep, 10);
1198                         if (errno == 0 && *ep == '\0')
1199                                 goto nocopy;
1200
1201                         pw = getpwnam(value);
1202                         if (pw == NULL) {
1203                                 fprintf(stderr,
1204                                         "bad user name \"%s\"\n", value);
1205                                 return EX_USAGE;
1206                         }
1207
1208                         bkupuid = pw->pw_uid;
1209                         goto nocopy;
1210                 case OPT_BKUPGID:
1211                         if (!value || !*value)
1212                                 goto nocopy;
1213
1214                         got_bkupgid = 1;
1215                         errno = 0;
1216                         bkupgid = strtoul(value, &ep, 10);
1217                         if (errno == 0 && *ep == '\0')
1218                                 goto nocopy;
1219
1220                         gr = getgrnam(value);
1221                         if (gr == NULL) {
1222                                 fprintf(stderr,
1223                                         "bad group name \"%s\"\n", value);
1224                                 return EX_USAGE;
1225                         }
1226
1227                         bkupgid = gr->gr_gid;
1228                         goto nocopy;
1229                 case OPT_NOFAIL:
1230                         parsed_info->nofail = 1;
1231                         goto nocopy;
1232                 case OPT_SNAPSHOT:
1233                         if (!value || !*value)
1234                                 goto nocopy;
1235                         if (strncmp(value, "@GMT-", 5))
1236                                 break;
1237                         if ((strlen(value) != GMT_NAME_LEN) ||
1238                             (strptime(value, GMT_FORMAT, &tm) == NULL)) {
1239                                 fprintf(stderr, "bad snapshot token\n");
1240                                 return EX_USAGE;
1241                         }
1242                         snapshot = timegm(&tm) * 10000000 + NTFS_TIME_OFFSET;
1243                         got_snapshot = 1;
1244                         goto nocopy;
1245                 }
1246
1247                 /* check size before copying option to buffer */
1248                 word_len = strlen(data);
1249                 if (value)
1250                         word_len += 1 + strlen(value);
1251
1252                 /* need 2 extra bytes for comma and null byte */
1253                 if (out_len + word_len + 2 > MAX_OPTIONS_LEN) {
1254                         fprintf(stderr, "Options string too long\n");
1255                         return EX_USAGE;
1256                 }
1257
1258                 /* put back equals sign, if any */
1259                 if (equals)
1260                         *equals = '=';
1261
1262                 /* go ahead and copy */
1263                 if (out_len)
1264                         strlcat(out, ",", MAX_OPTIONS_LEN);
1265
1266                 strlcat(out, data, MAX_OPTIONS_LEN);
1267                 out_len = strlen(out);
1268 nocopy:
1269                 data = next_keyword;
1270         }
1271
1272
1273         /* special-case the uid and gid */
1274         if (got_uid) {
1275                 word_len = snprintf(txtbuf, sizeof(txtbuf), "%u", uid);
1276
1277                 /* comma + "uid=" + terminating NULL == 6 */
1278                 if (out_len + word_len + 6 > MAX_OPTIONS_LEN) {
1279                         fprintf(stderr, "Options string too long\n");
1280                         return EX_USAGE;
1281                 }
1282
1283                 if (out_len) {
1284                         strlcat(out, ",", MAX_OPTIONS_LEN);
1285                         out_len++;
1286                 }
1287                 rc = snprintf(out + out_len, word_len + 5, "uid=%s", txtbuf);
1288                 if (rc < 0) {
1289                         fprintf(stderr, "Error in creating mount string\n");
1290                         return EX_SYSERR;
1291                 }
1292                 out_len = strlen(out);
1293         }
1294         if (parsed_info->is_krb5 && parsed_info->sudo_uid) {
1295                 cruid = parsed_info->sudo_uid;
1296                 got_cruid = 1;
1297         }
1298         if (got_cruid) {
1299                 word_len = snprintf(txtbuf, sizeof(txtbuf), "%u", cruid);
1300
1301                 /* comma + "cruid=" + terminating NULL == 8 */
1302                 if (out_len + word_len + 8 > MAX_OPTIONS_LEN) {
1303                         fprintf(stderr, "Options string too long\n");
1304                         return EX_USAGE;
1305                 }
1306
1307                 if (out_len) {
1308                         strlcat(out, ",", MAX_OPTIONS_LEN);
1309                         out_len++;
1310                 }
1311                 rc = snprintf(out + out_len, word_len + 7, "cruid=%s", txtbuf);
1312                 if (rc < 0) {
1313                         fprintf(stderr, "Error in creating mount string\n");
1314                         return EX_SYSERR;
1315                 }
1316                 out_len = strlen(out);
1317         }
1318         if (got_gid) {
1319                 word_len = snprintf(txtbuf, sizeof(txtbuf), "%u", gid);
1320
1321                 /* comma + "gid=" + terminating NULL == 6 */
1322                 if (out_len + word_len + 6 > MAX_OPTIONS_LEN) {
1323                         fprintf(stderr, "Options string too long\n");
1324                         return EX_USAGE;
1325                 }
1326
1327                 if (out_len) {
1328                         strlcat(out, ",", MAX_OPTIONS_LEN);
1329                         out_len++;
1330                 }
1331                 rc = snprintf(out + out_len, word_len + 5, "gid=%s", txtbuf);
1332                 if (rc < 0) {
1333                         fprintf(stderr, "Error in creating mount string\n");
1334                         return EX_SYSERR;
1335                 }
1336                 out_len = strlen(out);
1337         }
1338         if (got_bkupuid) {
1339                 word_len = snprintf(txtbuf, sizeof(txtbuf), "%u", bkupuid);
1340
1341                 /* comma + "backupuid=" + terminating NULL == 12 */
1342                 if (out_len + word_len + 12 > MAX_OPTIONS_LEN) {
1343                         fprintf(stderr, "Options string too long\n");
1344                         return EX_USAGE;
1345                 }
1346
1347                 if (out_len) {
1348                         strlcat(out, ",", MAX_OPTIONS_LEN);
1349                         out_len++;
1350                 }
1351                 rc = snprintf(out + out_len, word_len + 11, "backupuid=%s", txtbuf);
1352                 if (rc < 0) {
1353                         fprintf(stderr, "Error in creating mount string\n");
1354                         return EX_SYSERR;
1355                 }
1356                 out_len = strlen(out);
1357         }
1358         if (got_bkupgid) {
1359                 word_len = snprintf(txtbuf, sizeof(txtbuf), "%u", bkupgid);
1360
1361                 /* comma + "backupgid=" + terminating NULL == 12 */
1362                 if (out_len + word_len + 12 > MAX_OPTIONS_LEN) {
1363                         fprintf(stderr, "Options string too long\n");
1364                         return EX_USAGE;
1365                 }
1366
1367                 if (out_len) {
1368                         strlcat(out, ",", MAX_OPTIONS_LEN);
1369                         out_len++;
1370                 }
1371                 rc = snprintf(out + out_len, word_len + 11, "backupgid=%s", txtbuf);
1372                 if (rc < 0) {
1373                         fprintf(stderr, "Error in creating mount string\n");
1374                         return EX_SYSERR;
1375                 }
1376                 out_len = strlen(out);
1377         }
1378         if (got_snapshot) {
1379                 word_len = snprintf(txtbuf, sizeof(txtbuf), "%llu", snapshot);
1380
1381                 /* comma + "snapshot=" + terminating NULL == 11 */
1382                 if (out_len + word_len + 11 > MAX_OPTIONS_LEN) {
1383                         fprintf(stderr, "Options string too long\n");
1384                         return EX_USAGE;
1385                 }
1386
1387                 if (out_len) {
1388                         strlcat(out, ",", MAX_OPTIONS_LEN);
1389                         out_len++;
1390                 }
1391                 rc = snprintf(out + out_len, word_len + 10, "snapshot=%s", txtbuf);
1392                 if (rc < 0) {
1393                         fprintf(stderr, "Error in creating mount string\n");
1394                         return EX_SYSERR;
1395                 }
1396                 out_len = strlen(out);
1397         }
1398
1399         return 0;
1400 }
1401
1402 static int parse_unc(const char *unc_name, struct parsed_mount_info *parsed_info, const char *progname)
1403 {
1404         int length = strnlen(unc_name, MAX_UNC_LEN);
1405         const char *host, *share, *prepath;
1406         size_t hostlen, sharelen, prepathlen;
1407
1408         if (length > (MAX_UNC_LEN - 1)) {
1409                 fprintf(stderr, "mount error: UNC name too long\n");
1410                 return EX_USAGE;
1411         }
1412
1413         if (length < 3) {
1414                 fprintf(stderr, "mount error: UNC name too short\n");
1415                 return EX_USAGE;
1416         }
1417
1418         if ((strncasecmp("cifs://", unc_name, 7) == 0) ||
1419             (strncasecmp("smb://", unc_name, 6) == 0)) {
1420                 fprintf(stderr,
1421                         "Mounting cifs URL not implemented yet. Attempt to mount %s\n",
1422                         unc_name);
1423                 return EX_USAGE;
1424         }
1425
1426         if (strncmp(unc_name, "//", 2) && strncmp(unc_name, "\\\\", 2)) {
1427                 fprintf(stderr, "%s: bad UNC (%s)\n", progname, unc_name);
1428                 return EX_USAGE;
1429         }
1430
1431         host = unc_name + 2;
1432         hostlen = strcspn(host, "/\\");
1433         if (!hostlen) {
1434                 fprintf(stderr, "%s: bad UNC (%s)\n", progname, unc_name);
1435                 return EX_USAGE;
1436         }
1437         share = host + hostlen + 1;
1438
1439         if (hostlen + 1 > sizeof(parsed_info->host)) {
1440                 fprintf(stderr, "%s: host portion of UNC too long\n", progname);
1441                 return EX_USAGE;
1442         }
1443
1444         sharelen = strcspn(share, "/\\");
1445         if (sharelen + 1 > sizeof(parsed_info->share)) {
1446                 fprintf(stderr, "%s: share portion of UNC too long\n", progname);
1447                 return EX_USAGE;
1448         }
1449
1450         prepath = share + sharelen;
1451         if (*prepath != '\0')
1452                 prepath++;
1453
1454         prepathlen = strlen(prepath);
1455
1456         if (prepathlen + 1 > sizeof(parsed_info->prefix)) {
1457                 fprintf(stderr, "%s: UNC prefixpath too long\n", progname);
1458                 return EX_USAGE;
1459         }
1460
1461         /* copy pieces into their resepective buffers */
1462         memcpy(parsed_info->host, host, hostlen);
1463         memcpy(parsed_info->share, share, sharelen);
1464         memcpy(parsed_info->prefix, prepath, prepathlen);
1465
1466         return 0;
1467 }
1468
1469 static int get_pw_from_env(struct parsed_mount_info *parsed_info, const char *program)
1470 {
1471         int rc = 0;
1472
1473         if (getenv("PASSWD"))
1474                 rc = set_password(parsed_info, getenv("PASSWD"), OPT_PASS);
1475         else if (getenv("PASSWD_FD"))
1476                 rc = get_password_from_file(atoi(getenv("PASSWD_FD")), NULL,
1477                                             parsed_info, program, OPT_PASS);
1478         else if (getenv("PASSWD_FILE"))
1479                 rc = get_password_from_file(0, getenv("PASSWD_FILE"),
1480                                             parsed_info, program, OPT_PASS);
1481
1482         if (rc < 0)
1483                 return rc;
1484
1485         if (getenv("PASSWD2"))
1486                 rc = set_password(parsed_info, getenv("PASSWD2"), OPT_PASS2);
1487         else if (getenv("PASSWD2_FD"))
1488                 rc = get_password_from_file(atoi(getenv("PASSWD2_FD")), NULL,
1489                                             parsed_info, program, OPT_PASS2);
1490         else if (getenv("PASSWD2_FILE"))
1491                 rc = get_password_from_file(0, getenv("PASSWD2_FILE"),
1492                                             parsed_info, program, OPT_PASS2);
1493
1494         return rc;
1495 }
1496
1497 static struct option longopts[] = {
1498         {"all", 0, NULL, 'a'},
1499         {"help", 0, NULL, 'h'},
1500         {"move", 0, NULL, 'm'},
1501         {"bind", 0, NULL, 'b'},
1502         {"read-only", 0, NULL, 'r'},
1503         {"ro", 0, NULL, 'r'},
1504         {"verbose", 0, NULL, 'v'},
1505         {"version", 0, NULL, 'V'},
1506         {"read-write", 0, NULL, 'w'},
1507         {"rw", 0, NULL, 'w'},
1508         {"options", 1, NULL, 'o'},
1509         {"type", 1, NULL, 't'},
1510         {"uid", 1, NULL, '1'},
1511         {"gid", 1, NULL, '2'},
1512         {"user", 1, NULL, 'u'},
1513         {"username", 1, NULL, 'u'},
1514         {"dom", 1, NULL, 'd'},
1515         {"domain", 1, NULL, 'd'},
1516         {"password", 1, NULL, 'p'},
1517         {"pass", 1, NULL, 'p'},
1518         {"password2", 1, NULL, 0},
1519         {"pass2", 1, NULL, 0},
1520         {"credentials", 1, NULL, 'c'},
1521         {"port", 1, NULL, 'P'},
1522         {"sloppy", 0, NULL, 's'},
1523         {NULL, 0, NULL, 0}
1524 };
1525
1526 /* convert a string to uppercase. return false if the string
1527  * wasn't ASCII. Return success on a NULL ptr */
1528 static int uppercase_string(char *string)
1529 {
1530         if (!string)
1531                 return 1;
1532
1533         while (*string) {
1534                 /* check for unicode */
1535                 if ((unsigned char)string[0] & 0x80)
1536                         return 0;
1537                 *string = toupper((unsigned char)*string);
1538                 string++;
1539         }
1540
1541         return 1;
1542 }
1543
1544 static void print_cifs_mount_version(const char *progname)
1545 {
1546         printf("%s version: %s\n", progname, VERSION);
1547 }
1548
1549 /*
1550  * This function borrowed from fuse-utils...
1551  *
1552  * glibc's addmntent (at least as of 2.10 or so) doesn't properly encode
1553  * newlines embedded within the text fields. To make sure no one corrupts
1554  * the mtab, fail the mount if there are embedded newlines.
1555  */
1556 static int check_newline(const char *progname, const char *name)
1557 {
1558         const char *s;
1559         for (s = "\n"; *s; s++) {
1560                 if (strchr(name, *s)) {
1561                         fprintf(stderr,
1562                                 "%s: illegal character 0x%02x in mount entry\n",
1563                                 progname, *s);
1564                         return EX_USAGE;
1565                 }
1566         }
1567         return 0;
1568 }
1569
1570 static int check_mtab(const char *progname, const char *devname,
1571                       const char *dir)
1572 {
1573         if (check_newline(progname, devname) || check_newline(progname, dir))
1574                 return EX_USAGE;
1575         return 0;
1576 }
1577
1578 static int
1579 add_mtab(char *devname, char *mountpoint, unsigned long flags, const char *fstype)
1580 {
1581         int rc = 0, tmprc, fd;
1582         uid_t uid;
1583         char *mount_user = NULL;
1584         struct mntent mountent;
1585         struct stat statbuf;
1586         FILE *pmntfile;
1587         sigset_t mask, oldmask;
1588
1589         uid = getuid();
1590         if (uid != 0)
1591                 mount_user = getusername(uid);
1592
1593         /*
1594          * Set the real uid to the effective uid. This prevents unprivileged
1595          * users from sending signals to this process, though ^c on controlling
1596          * terminal should still work.
1597          */
1598         rc = setreuid(geteuid(), -1);
1599         if (rc != 0) {
1600                 fprintf(stderr, "Unable to set real uid to effective uid: %s\n",
1601                                 strerror(errno));
1602                 return EX_FILEIO;
1603         }
1604
1605         rc = sigfillset(&mask);
1606         if (rc) {
1607                 fprintf(stderr, "Unable to set filled signal mask\n");
1608                 return EX_FILEIO;
1609         }
1610
1611         rc = sigprocmask(SIG_SETMASK, &mask, &oldmask);
1612         if (rc) {
1613                 fprintf(stderr, "Unable to make process ignore signals\n");
1614                 return EX_FILEIO;
1615         }
1616
1617         rc = toggle_dac_capability(1, 1);
1618         if (rc)
1619                 return EX_FILEIO;
1620
1621         atexit(unlock_mtab);
1622         rc = lock_mtab();
1623         if (rc) {
1624                 fprintf(stderr, "cannot lock mtab");
1625                 rc = EX_FILEIO;
1626                 goto add_mtab_exit;
1627         }
1628
1629         pmntfile = setmntent(MOUNTED, "a+");
1630         if (!pmntfile) {
1631                 fprintf(stderr, "could not update mount table\n");
1632                 unlock_mtab();
1633                 rc = EX_FILEIO;
1634                 goto add_mtab_exit;
1635         }
1636
1637         fd = fileno(pmntfile);
1638         if (fd < 0) {
1639                 fprintf(stderr, "mntent does not appear to be valid\n");
1640                 unlock_mtab();
1641                 rc = EX_FILEIO;
1642                 goto add_mtab_exit;
1643         }
1644
1645         rc = fstat(fd, &statbuf);
1646         if (rc != 0) {
1647                 fprintf(stderr, "unable to fstat open mtab\n");
1648                 endmntent(pmntfile);
1649                 unlock_mtab();
1650                 rc = EX_FILEIO;
1651                 goto add_mtab_exit;
1652         }
1653
1654         mountent.mnt_fsname = devname;
1655         mountent.mnt_dir = mountpoint;
1656         mountent.mnt_type = (char *)(void *)fstype;
1657         mountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1);
1658         if (mountent.mnt_opts) {
1659                 if (flags & MS_RDONLY)
1660                         strlcat(mountent.mnt_opts, "ro", MTAB_OPTIONS_LEN);
1661                 else
1662                         strlcat(mountent.mnt_opts, "rw", MTAB_OPTIONS_LEN);
1663
1664                 if (flags & MS_MANDLOCK)
1665                         strlcat(mountent.mnt_opts, ",mand", MTAB_OPTIONS_LEN);
1666                 if (flags & MS_NOEXEC)
1667                         strlcat(mountent.mnt_opts, ",noexec", MTAB_OPTIONS_LEN);
1668                 if (flags & MS_NOSUID)
1669                         strlcat(mountent.mnt_opts, ",nosuid", MTAB_OPTIONS_LEN);
1670                 if (flags & MS_NODEV)
1671                         strlcat(mountent.mnt_opts, ",nodev", MTAB_OPTIONS_LEN);
1672                 if (flags & MS_SYNCHRONOUS)
1673                         strlcat(mountent.mnt_opts, ",sync", MTAB_OPTIONS_LEN);
1674                 if (mount_user) {
1675                         strlcat(mountent.mnt_opts, ",user=", MTAB_OPTIONS_LEN);
1676                         strlcat(mountent.mnt_opts, mount_user,
1677                                 MTAB_OPTIONS_LEN);
1678                 }
1679         }
1680         mountent.mnt_freq = 0;
1681         mountent.mnt_passno = 0;
1682         rc = addmntent(pmntfile, &mountent);
1683         if (rc) {
1684                 int ignore __attribute__((unused));
1685
1686                 fprintf(stderr, "unable to add mount entry to mtab\n");
1687                 ignore = ftruncate(fd, statbuf.st_size);
1688                 rc = EX_FILEIO;
1689         }
1690         tmprc = my_endmntent(pmntfile, statbuf.st_size);
1691         if (tmprc) {
1692                 fprintf(stderr, "error %d detected on close of mtab\n", tmprc);
1693                 rc = EX_FILEIO;
1694         }
1695         unlock_mtab();
1696         free(mountent.mnt_opts);
1697 add_mtab_exit:
1698         toggle_dac_capability(1, 0);
1699         sigprocmask(SIG_SETMASK, &oldmask, NULL);
1700
1701         return rc;
1702 }
1703
1704 static int
1705 del_mtab(char *mountpoint)
1706 {
1707         int len, tmprc, rc = 0, tmpfd;
1708         FILE *mnttmp, *mntmtab;
1709         struct mntent *mountent;
1710         char *mtabfile, *mtabdir, *mtabtmpfile = NULL;
1711
1712         mtabfile = strdup(MOUNTED);
1713         if (!mtabfile) {
1714                 fprintf(stderr, "del_mtab: cannot strdup MOUNTED\n");
1715                 rc = EX_FILEIO;
1716                 goto del_mtab_exit;
1717         }
1718
1719         mtabdir = dirname(mtabfile);
1720         len = strlen(mtabdir) + strlen(MNT_TMP_FILE);
1721         mtabtmpfile = malloc(len + 1);
1722         if (!mtabtmpfile) {
1723                 fprintf(stderr, "del_mtab: cannot allocate memory to tmp file\n");
1724                 rc = EX_FILEIO;
1725                 goto del_mtab_exit;
1726         }
1727
1728         if (sprintf(mtabtmpfile, "%s%s", mtabdir, MNT_TMP_FILE) != len) {
1729                 fprintf(stderr, "del_mtab: error writing new string\n");
1730                 rc = EX_FILEIO;
1731                 goto del_mtab_exit;
1732         }
1733
1734         atexit(unlock_mtab);
1735         rc = lock_mtab();
1736         if (rc) {
1737                 fprintf(stderr, "del_mtab: cannot lock mtab\n");
1738                 rc = EX_FILEIO;
1739                 goto del_mtab_exit;
1740         }
1741
1742         // Use mkstemp instead of mktemp
1743         tmpfd = mkstemp(mtabtmpfile);
1744         if (tmpfd == -1) {
1745                 fprintf(stderr, "del_mtab: cannot setup tmp file destination\n");
1746                 rc = EX_FILEIO;
1747                 goto del_mtab_exit;
1748         }
1749
1750         mntmtab = setmntent(MOUNTED, "r");
1751         if (!mntmtab) {
1752                 fprintf(stderr, "del_mtab: could not update mount table\n");
1753                 rc = EX_FILEIO;
1754                 close(tmpfd);
1755                 goto del_mtab_exit;
1756         }
1757
1758         mnttmp = fdopen(tmpfd, "w");
1759         if (!mnttmp) {
1760                 fprintf(stderr, "del_mtab: could not update mount table\n");
1761                 endmntent(mntmtab);
1762                 close(tmpfd);
1763                 rc = EX_FILEIO;
1764                 goto del_mtab_exit;
1765         }
1766
1767         while ((mountent = getmntent(mntmtab)) != NULL) {
1768                 if (!strcmp(mountent->mnt_dir, mountpoint))
1769                         continue;
1770                 rc = addmntent(mnttmp, mountent);
1771                 if (rc) {
1772                         fprintf(stderr, "del_mtab: unable to add mount entry to mtab\n");
1773                         rc = EX_FILEIO;
1774                         goto del_mtab_error;
1775                 }
1776         }
1777
1778         endmntent(mntmtab);
1779
1780         tmprc = my_endmntent(mnttmp, 0);
1781         if (tmprc) {
1782                 fprintf(stderr, "del_mtab: error %d detected on close of tmp file\n", tmprc);
1783                 rc = EX_FILEIO;
1784                 goto del_mtab_error;
1785         }
1786
1787         if (rename(mtabtmpfile, MOUNTED)) {
1788                 fprintf(stderr, "del_mtab: error %d when renaming mtab in place\n", errno);
1789                 rc = EX_FILEIO;
1790                 goto del_mtab_error;
1791         }
1792
1793 del_mtab_exit:
1794         unlock_mtab();
1795         free(mtabtmpfile);
1796         free(mtabfile);
1797         return rc;
1798
1799 del_mtab_error:
1800         if (unlink(mtabtmpfile))
1801                 fprintf(stderr, "del_mtab: failed to delete tmp file - %s\n",
1802                                 strerror(errno));
1803         goto del_mtab_exit;
1804 }
1805
1806 /* have the child drop root privileges */
1807 static int
1808 drop_child_privs(void)
1809 {
1810         int rc;
1811         uid_t uid = getuid();
1812         gid_t gid = getgid();
1813
1814         if (gid) {
1815                 rc = setgid(gid);
1816                 if (rc) {
1817                         fprintf(stderr, "Unable set group identity: %s\n",
1818                                         strerror(errno));
1819                         return EX_SYSERR;
1820                 }
1821         }
1822         if (uid) {
1823                 rc = setuid(uid);
1824                 if (rc) {
1825                         fprintf(stderr, "Unable set user identity: %s\n",
1826                                         strerror(errno));
1827                         return EX_SYSERR;
1828                 }
1829         }
1830
1831         return 0;
1832 }
1833
1834 #ifdef ENABLE_SYSTEMD
1835 static int get_passwd_by_systemd(const char *prompt, char *input, int capacity)
1836 {
1837         int fd[2];
1838         pid_t pid;
1839         int offs = 0;
1840         int rc = 1;
1841
1842         if (pipe(fd) == -1) {
1843                 fprintf(stderr, "Failed to create pipe: %s\n", strerror(errno));
1844                 return 1;
1845         }
1846
1847         pid = fork();
1848         if (pid == -1) {
1849                 fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
1850                 close(fd[0]);
1851                 close(fd[1]);
1852                 return 1;
1853         }
1854         if (pid == 0) {
1855                 close(fd[0]);
1856                 dup2(fd[1], STDOUT_FILENO);
1857                 if (execlp("systemd-ask-password", "systemd-ask-password", prompt, NULL) == -1) {
1858                         fprintf(stderr, "Failed to execute systemd-ask-password: %s\n",
1859                                 strerror(errno));
1860                 }
1861                 exit(1);
1862         }
1863
1864         close(fd[1]);
1865         for (;;) {
1866                 if (offs+1 >= capacity) {
1867                         fprintf(stderr, "Password too long.\n");
1868                         kill(pid, SIGTERM);
1869                         rc = 1;
1870                         break;
1871                 }
1872                 rc = read(fd[0], input + offs, capacity - offs);
1873                 if (rc == -1) {
1874                         fprintf(stderr, "Failed to read from pipe: %s\n", strerror(errno));
1875                         rc = 1;
1876                         break;
1877                 }
1878                 if (!rc)
1879                         break;
1880                 offs += rc;
1881                 input[offs] = '\0';
1882         }
1883         if (wait(&rc) == -1) {
1884                 fprintf(stderr, "Failed to wait child: %s\n", strerror(errno));
1885                 rc = 1;
1886                 goto out;
1887         }
1888         if (!WIFEXITED(rc) || WEXITSTATUS(rc)) {
1889                 rc = 1;
1890                 goto out;
1891         }
1892
1893         rc = 0;
1894
1895 out:
1896         close(fd[0]);
1897         return rc;
1898 }
1899 #endif
1900
1901 /*
1902  * If systemd is running and systemd-ask-password --
1903  * is available, then use that else fallback on getpass(..)
1904  *
1905  * Returns: @input or NULL on error
1906  */
1907 static char*
1908 get_password(const char *prompt, char *input, int capacity)
1909 {
1910 #ifdef ENABLE_SYSTEMD
1911         int is_systemd_running;
1912         struct stat a, b;
1913
1914         memset(input, 0, capacity);
1915
1916         /* We simply test whether the systemd cgroup hierarchy is
1917          * mounted */
1918         is_systemd_running = (lstat("/sys/fs/cgroup", &a) == 0)
1919                 && (lstat("/sys/fs/cgroup/systemd", &b) == 0)
1920                 && (a.st_dev != b.st_dev);
1921
1922         if (is_systemd_running && !get_passwd_by_systemd(prompt, input, capacity)) {
1923                 int len = strlen(input);
1924                 if (input[len - 1] == '\n')
1925                         input[len - 1] = '\0';
1926                 return input;
1927         }
1928 #endif
1929         memset(input, 0, capacity);
1930
1931         /*
1932          * Falling back to getpass(..)
1933          * getpass is obsolete, but there's apparently nothing that replaces it
1934          */
1935         char *tmp_pass = getpass(prompt);
1936         if (!tmp_pass)
1937                 return NULL;
1938
1939         strncpy(input, tmp_pass, capacity - 1);
1940         input[capacity - 1] = '\0';
1941
1942         /* zero-out the static buffer */
1943         memset(tmp_pass, 0, strlen(tmp_pass));
1944
1945         return input;
1946 }
1947
1948 static int
1949 assemble_mountinfo(struct parsed_mount_info *parsed_info,
1950                    const char *thisprogram, const char *mountpoint,
1951                    const char *orig_dev, char *orgoptions)
1952 {
1953         int rc;
1954         char *newopts = NULL;
1955
1956         rc = drop_capabilities(0);
1957         if (rc)
1958                 goto assemble_exit;
1959
1960         rc = drop_child_privs();
1961         if (rc)
1962                 goto assemble_exit;
1963
1964         if (getuid()) {
1965                 rc = check_fstab(thisprogram, mountpoint, orig_dev,
1966                                  &newopts);
1967                 if (rc)
1968                         goto assemble_exit;
1969
1970                 orgoptions = newopts;
1971                 /* enable any default user mount flags */
1972                 parsed_info->flags |= CIFS_SETUID_FLAGS;
1973         }
1974
1975         rc = get_pw_from_env(parsed_info, thisprogram);
1976         if (rc)
1977                 goto assemble_exit;
1978
1979         if (orgoptions) {
1980                 rc = parse_options(orgoptions, parsed_info);
1981                 if (rc)
1982                         goto assemble_exit;
1983         }
1984
1985         if (getuid()) {
1986                 if (!(parsed_info->flags & (MS_USERS | MS_USER))) {
1987                         fprintf(stderr, "%s: permission denied\n", thisprogram);
1988                         rc = EX_USAGE;
1989                         goto assemble_exit;
1990                 }
1991         }
1992
1993         parsed_info->flags &= ~(MS_USERS | MS_USER);
1994
1995         rc = parse_unc(orig_dev, parsed_info, thisprogram);
1996         if (rc)
1997                 goto assemble_exit;
1998
1999         if (parsed_info->addrlist[0] == '\0') {
2000                 rc = resolve_host(parsed_info->host, parsed_info->addrlist);
2001                 if (rc == 0 && parsed_info->verboseflag)
2002                         fprintf(stderr, "Host \"%s\" resolved to the following IP addresses: %s\n", parsed_info->host, parsed_info->addrlist);
2003         }
2004
2005         switch (rc) {
2006         case EX_USAGE:
2007                 fprintf(stderr, "mount error: could not resolve address for "
2008                         "%s: %s\n", parsed_info->host,
2009                         rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
2010                 goto assemble_exit;
2011
2012         case EX_SYSERR:
2013                 fprintf(stderr, "mount error: problem parsing address "
2014                         "list: %s\n", strerror(errno));
2015                 goto assemble_exit;
2016         }
2017
2018         if (!parsed_info->got_user) {
2019                 /*
2020                  * Note that the password will not be retrieved from the
2021                  * USER env variable (ie user%password form) as there is
2022                  * already a PASSWD environment varaible
2023                  */
2024                 if (getenv("USER")) {
2025                         if (check_creds_field(getenv("USER"))) {
2026                                 fprintf(stderr, "Invalid username in USER environment variable\n");
2027                                 rc = EX_USAGE;
2028                                 goto assemble_exit;
2029                         }
2030                         strlcpy(parsed_info->username, getenv("USER"),
2031                                 sizeof(parsed_info->username));
2032                 } else {
2033                         char *username = getusername(getuid());
2034
2035                         if (username) {
2036                                 if (check_creds_field(username)) {
2037                                         fprintf(stderr, "Invalid username for uid %u\n",
2038                                                 (unsigned int)getuid());
2039                                         rc = EX_USAGE;
2040                                         goto assemble_exit;
2041                                 }
2042                                 strlcpy(parsed_info->username, username,
2043                                         sizeof(parsed_info->username));
2044                         }
2045                 }
2046                 parsed_info->got_user = 1;
2047         }
2048
2049         // no need to prompt for password2
2050         if (!parsed_info->got_password && !(parsed_info->flags & MS_REMOUNT)) {
2051                 char tmp_pass[MOUNT_PASSWD_SIZE + 1];
2052                 char *prompt = NULL;
2053
2054                 if(asprintf(&prompt, "Password for %s@%s: ", parsed_info->username, orig_dev) < 0)
2055                         prompt = NULL;
2056
2057                 if (get_password(prompt ? prompt : "Password: ", tmp_pass, MOUNT_PASSWD_SIZE + 1)) {
2058                         rc = set_password(parsed_info, tmp_pass, OPT_PASS);
2059                 } else {
2060                         fprintf(stderr, "Error reading password, exiting\n");
2061                         rc = EX_SYSERR;
2062                 }
2063
2064                 free(prompt);
2065                 if (rc)
2066                         goto assemble_exit;
2067         }
2068
2069         /* copy in user= string */
2070         if (parsed_info->got_user) {
2071                 if (*parsed_info->options)
2072                         strlcat(parsed_info->options, ",",
2073                                 sizeof(parsed_info->options));
2074                 strlcat(parsed_info->options, "user=",
2075                         sizeof(parsed_info->options));
2076                 strlcat(parsed_info->options, parsed_info->username,
2077                         sizeof(parsed_info->options));
2078         }
2079
2080         if (*parsed_info->domain) {
2081                 if (*parsed_info->options)
2082                         strlcat(parsed_info->options, ",",
2083                                 sizeof(parsed_info->options));
2084                 strlcat(parsed_info->options, "domain=",
2085                         sizeof(parsed_info->options));
2086                 strlcat(parsed_info->options, parsed_info->domain,
2087                         sizeof(parsed_info->options));
2088         } else if (parsed_info->got_domain) {
2089                 strlcat(parsed_info->options, ",domain=",
2090                         sizeof(parsed_info->options));
2091         }
2092
2093 assemble_exit:
2094         free(newopts);
2095         return rc;
2096 }
2097
2098 /*
2099  * chdir() into the mountpoint and determine "realpath". We assume here that
2100  * "mountpoint" is a statically allocated string and does not need to be freed.
2101  */
2102 static int
2103 acquire_mountpoint(char **mountpointp)
2104 {
2105         int rc, dacrc;
2106         uid_t realuid, oldfsuid;
2107         gid_t oldfsgid;
2108         char *mountpoint = NULL;
2109
2110         /*
2111          * Acquire the necessary privileges to chdir to the mountpoint. If
2112          * the real uid is root, then we reacquire CAP_DAC_READ_SEARCH. If
2113          * it's not, then we change the fsuid to the real uid to ensure that
2114          * the mounting user actually has access to the mountpoint.
2115          *
2116          * The mount(8) manpage does not state that users must be able to
2117          * chdir into the mountpoint in order to mount onto it, but if we
2118          * allow that, then an unprivileged user could use this program to
2119          * "probe" into directories to which he does not have access.
2120          */
2121         realuid = getuid();
2122         if (realuid == 0) {
2123                 rc = toggle_dac_capability(0, 1);
2124                 if (rc)
2125                         goto out;
2126         } else {
2127                 oldfsuid = setfsuid(realuid);
2128                 oldfsgid = setfsgid(getgid());
2129         }
2130
2131         rc = chdir(*mountpointp);
2132         if (rc) {
2133                 fprintf(stderr, "Couldn't chdir to %s: %s\n", *mountpointp,
2134                         strerror(errno));
2135                 rc = EX_USAGE;
2136                 goto restore_privs;
2137         }
2138
2139         mountpoint = realpath(".", NULL);
2140         if (!mountpoint) {
2141                 fprintf(stderr, "Unable to resolve %s to canonical path: %s\n",
2142                         *mountpointp, strerror(errno));
2143                 rc = EX_SYSERR;
2144         }
2145
2146 restore_privs:
2147         if (realuid == 0) {
2148                 dacrc = toggle_dac_capability(0, 0);
2149                 if (dacrc)
2150                         rc = rc ? rc : dacrc;
2151         } else {
2152                 uid_t __attribute__((unused)) uignore = setfsuid(oldfsuid);
2153                 gid_t __attribute__((unused)) gignore = setfsgid(oldfsgid);
2154         }
2155
2156 out:
2157         if (rc) {
2158                 free(mountpoint);
2159                 mountpoint = NULL;
2160         }
2161
2162         *mountpointp = mountpoint;
2163         return rc;
2164 }
2165
2166 int main(int argc, char **argv)
2167 {
2168         int c;
2169         char *orgoptions = NULL;
2170         char *mountpoint = NULL;
2171         char *options = NULL;
2172         char *orig_dev = NULL;
2173         char *currentaddress, *nextaddress;
2174         char *value = NULL;
2175         char *ep = NULL;
2176         int rc = 0;
2177         int already_uppercased = 0;
2178         int sloppy = 0;
2179         int fallback_sudo_uid = geteuid() || getuid();
2180         size_t options_size = MAX_OPTIONS_LEN;
2181         struct parsed_mount_info *parsed_info = NULL;
2182         struct parsed_mount_info *reinit_parsed_info = NULL;
2183         pid_t pid;
2184         uid_t sudo_uid = 0;
2185
2186         rc = check_setuid();
2187         if (rc)
2188                 return rc;
2189
2190         rc = drop_capabilities(1);
2191         if (rc)
2192                 return EX_SYSERR;
2193
2194         /* setlocale(LC_ALL, "");
2195            bindtextdomain(PACKAGE, LOCALEDIR);
2196            textdomain(PACKAGE); */
2197
2198         if (!argc || !argv) {
2199                 rc = mount_usage(stderr);
2200                 goto mount_exit;
2201         }
2202
2203         thisprogram = basename(argv[0]);
2204         if (thisprogram == NULL)
2205                 thisprogram = "mount.cifs";
2206
2207         if(strcmp(thisprogram, "mount.cifs") == 0)
2208                 cifs_fstype = "cifs";
2209
2210         if(strcmp(thisprogram, "mount.smb3") == 0)
2211                 cifs_fstype = "smb3";
2212
2213         /* allocate parsed_info as shared anonymous memory range */
2214         parsed_info = mmap((void *)0, sizeof(*parsed_info), PROT_READ | PROT_WRITE,
2215                            MAP_ANONYMOUS | MAP_SHARED, -1, 0);
2216         if (parsed_info == (struct parsed_mount_info *) -1) {
2217                 parsed_info = NULL;
2218                 fprintf(stderr, "Unable to allocate memory: %s\n",
2219                                 strerror(errno));
2220                 rc = EX_SYSERR;
2221                 goto mount_exit;
2222         }
2223
2224         reinit_parsed_info = malloc(sizeof(*reinit_parsed_info));
2225         if (reinit_parsed_info == NULL) {
2226                 fprintf(stderr, "Unable to allocate memory: %s\n",
2227                                 strerror(errno));
2228                 rc = EX_SYSERR;
2229                 goto mount_exit;
2230         }
2231
2232         options = calloc(options_size, 1);
2233         if (!options) {
2234                 fprintf(stderr, "Unable to allocate memory.\n");
2235                 rc = EX_SYSERR;
2236                 goto mount_exit;
2237         }
2238
2239         /* add sharename in opts string as unc= parm */
2240         while ((c = getopt_long(argc, argv, "?fhno:rsvVw",
2241                                 longopts, NULL)) != -1) {
2242                 switch (c) {
2243                 case '?':
2244                 case 'h':       /* help */
2245                         rc = mount_usage(stdout);
2246                         goto mount_exit;
2247                 case 'n':
2248                         ++parsed_info->nomtab;
2249                         break;
2250                 case 'o':
2251                         orgoptions = strndup(optarg, MAX_OPTIONS_LEN);
2252                         if (!orgoptions) {
2253                                 rc = EX_SYSERR;
2254                                 goto mount_exit;
2255                         }
2256                         break;
2257                 case 'r':       /* mount readonly */
2258                         parsed_info->flags |= MS_RDONLY;
2259                         break;
2260                 case 'v':
2261                         ++parsed_info->verboseflag;
2262                         break;
2263                 case 'V':
2264                         print_cifs_mount_version(thisprogram);
2265                         exit(0);
2266                 case 'w':
2267                         parsed_info->flags &= ~MS_RDONLY;
2268                         break;
2269                 case 'f':
2270                         ++parsed_info->fakemnt;
2271                         break;
2272                 case 's':
2273                         ++sloppy;
2274                         break;
2275                 default:
2276                         fprintf(stderr, "unknown command-line option: %c\n", c);
2277                         rc = mount_usage(stderr);
2278                         goto mount_exit;
2279                 }
2280         }
2281
2282         if (argc < optind + 2) {
2283                 rc = mount_usage(stderr);
2284                 goto mount_exit;
2285         }
2286
2287         orig_dev = argv[optind];
2288         mountpoint = argv[optind + 1];
2289
2290         /* chdir into mountpoint as soon as possible */
2291         rc = acquire_mountpoint(&mountpoint);
2292         if (rc) {
2293                 goto mount_exit;
2294         }
2295
2296         /* Before goto assemble_retry, reinitialize parsed_info with reinit_parsed_info */
2297         memcpy(reinit_parsed_info, parsed_info, sizeof(*reinit_parsed_info));
2298
2299 assemble_retry:
2300         /*
2301          * mount.cifs does privilege separation. Most of the code to handle
2302          * assembling the mount info is done in a child process that drops
2303          * privileges. The info is assembled in parsed_info which is a
2304          * shared, mmaped memory segment. The parent waits for the child to
2305          * exit and checks the return code. If it's anything but "0", then
2306          * the process exits without attempting anything further.
2307          */
2308         pid = fork();
2309         if (pid == -1) {
2310                 fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
2311                 rc = EX_SYSERR;
2312                 goto mount_exit;
2313         } else if (!pid) {
2314                 /* child */
2315                 rc = assemble_mountinfo(parsed_info, thisprogram, mountpoint,
2316                                         orig_dev, orgoptions);
2317                 goto mount_child_exit;
2318         } else {
2319                 /* parent */
2320                 pid = wait(&rc);
2321                 if (!WIFEXITED(rc)) {
2322                         fprintf(stderr, "Child process terminated abnormally.\n");
2323                         rc = EX_SYSERR;
2324                         goto mount_exit;
2325                 }
2326                 rc = WEXITSTATUS(rc);
2327                 if (rc)
2328                         goto mount_exit;
2329         }
2330
2331         currentaddress = parsed_info->addrlist;
2332         nextaddress = strchr(currentaddress, ',');
2333         if (nextaddress)
2334                 *nextaddress++ = '\0';
2335
2336 mount_retry:
2337         options[0] = '\0';
2338         if (!currentaddress) {
2339                 fprintf(stderr, "Unable to find suitable address.\n");
2340                 rc = parsed_info->nofail ? 0 : EX_FAIL;
2341                 goto mount_exit;
2342         }
2343         strlcpy(options, "ip=", options_size);
2344         strlcat(options, currentaddress, options_size);
2345
2346         strlcat(options, ",unc=\\\\", options_size);
2347         strlcat(options, parsed_info->host, options_size);
2348         strlcat(options, "\\", options_size);
2349         strlcat(options, parsed_info->share, options_size);
2350
2351         if (*parsed_info->options) {
2352                 strlcat(options, ",", options_size);
2353                 strlcat(options, parsed_info->options, options_size);
2354         }
2355
2356         if (*parsed_info->prefix) {
2357                 strlcat(options, ",prefixpath=", options_size);
2358                 strlcat(options, parsed_info->prefix, options_size);
2359         }
2360
2361         if (sloppy)
2362                 strlcat(options, ",sloppy", options_size);
2363
2364         if (parsed_info->verboseflag)
2365                 fprintf(stderr, "%s kernel mount options: %s",
2366                         thisprogram, options);
2367
2368         if (parsed_info->got_password &&
2369                 !(parsed_info->is_krb5 || parsed_info->is_noauth || parsed_info->is_guest)) {
2370                 /*
2371                  * Commas have to be doubled, or else they will
2372                  * look like the parameter separator
2373                  */
2374                 strlcat(options, ",pass=", options_size);
2375                 strlcat(options, parsed_info->password, options_size);
2376                 if (parsed_info->verboseflag)
2377                         fprintf(stderr, ",pass=********");
2378         }
2379
2380         if (parsed_info->got_password2 &&
2381                 !(parsed_info->is_krb5 || parsed_info->is_noauth || parsed_info->is_guest)) {
2382                 strlcat(options, ",password2=", options_size);
2383                 strlcat(options, parsed_info->password2, options_size);
2384                 if (parsed_info->verboseflag)
2385                         fprintf(stderr, ",password2=********");
2386         }
2387
2388         if (parsed_info->verboseflag)
2389                 fprintf(stderr, "\n");
2390
2391         rc = check_mtab(thisprogram, orig_dev, mountpoint);
2392         if (rc)
2393                 goto mount_exit;
2394
2395         if (!parsed_info->fakemnt) {
2396                 toggle_dac_capability(0, 1);
2397                 rc = mount(orig_dev, ".", cifs_fstype, parsed_info->flags, options);
2398                 toggle_dac_capability(0, 0);
2399                 if (rc == 0)
2400                         goto do_mtab;
2401
2402                 switch (errno) {
2403                 case ECONNREFUSED:
2404                 case EHOSTUNREACH:
2405                 case EINPROGRESS:
2406                         if (currentaddress) {
2407                                 fprintf(stderr, "mount error(%d): could not connect to %s",
2408                                         errno, currentaddress);
2409                         }
2410                         currentaddress = nextaddress;
2411                         if (currentaddress) {
2412                                 nextaddress = strchr(currentaddress, ',');
2413                                 if (nextaddress)
2414                                         *nextaddress++ = '\0';
2415                         }
2416                         goto mount_retry;
2417                 case ENODEV:
2418                         fprintf(stderr,
2419                                 "mount error: %s filesystem not supported by the system\n", cifs_fstype);
2420                         break;
2421                 case EHOSTDOWN:
2422                         fprintf(stderr,
2423                                 "mount error: Server abruptly closed the connection.\n"
2424                                 "This can happen if the server does not support the SMB version you are trying to use.\n"
2425                                 "The default SMB version recently changed from SMB1 to SMB2.1 and above. Try mounting with vers=1.0.\n");
2426                         break;
2427                 case ENXIO:
2428                         if (!already_uppercased &&
2429                             uppercase_string(parsed_info->host) &&
2430                             uppercase_string(parsed_info->share) &&
2431                             uppercase_string(parsed_info->prefix) &&
2432                             uppercase_string(orig_dev)) {
2433                                 fprintf(stderr,
2434                                         "Retrying with upper case share name\n");
2435                                 already_uppercased = 1;
2436                                 goto mount_retry;
2437                         }
2438                         break;
2439                 case ENOKEY:
2440                         if (!fallback_sudo_uid && parsed_info->is_krb5) {
2441                                 /* mount could have failed because cruid option was not passed when triggered with sudo */
2442                                 value = getenv("SUDO_UID");
2443                                 if (value) {
2444                                         errno = 0;
2445                                         sudo_uid = strtoul(value, &ep, 10);
2446                                         if (errno == 0 && *ep == '\0' && sudo_uid) {
2447                                                 /* Reinitialize parsed_info and assemble options again with sudo_uid */
2448                                                 memcpy(parsed_info, reinit_parsed_info, sizeof(*parsed_info));
2449                                                 parsed_info->sudo_uid = sudo_uid;
2450                                                 fallback_sudo_uid = 1;
2451                                                 goto assemble_retry;
2452                                         }
2453                                 }
2454                         }
2455                         break;
2456                 }
2457                 fprintf(stderr, "mount error(%d): %s\n", errno,
2458                         strerror(errno));
2459                 fprintf(stderr,
2460                         "Refer to the %s(8) manual page (e.g. man "
2461                         "%s) and kernel log messages (dmesg)\n", thisprogram, thisprogram);
2462                 rc = EX_FAIL;
2463                 goto mount_exit;
2464         }
2465
2466 do_mtab:
2467         if (!parsed_info->nomtab && !mtab_unusable()) {
2468                 if (parsed_info->flags & MS_REMOUNT) {
2469                         rc = del_mtab(mountpoint);
2470                         if (rc)
2471                                 goto mount_exit;
2472                 }
2473
2474                 rc = add_mtab(orig_dev, mountpoint, parsed_info->flags, cifs_fstype);
2475         }
2476
2477 mount_exit:
2478         if (parsed_info) {
2479                 memset(parsed_info->password, 0, sizeof(parsed_info->password));
2480                 memset(parsed_info->password2, 0, sizeof(parsed_info->password2));
2481                 munmap(parsed_info, sizeof(*parsed_info));
2482         }
2483
2484 mount_child_exit:
2485         /* Objects to be freed both in main process and child */
2486         free(reinit_parsed_info);
2487         free(options);
2488         free(orgoptions);
2489         free(mountpoint);
2490         return rc;
2491 }