- change a lot of occurances of errno to use strerror(errno). We can't
[kai/samba.git] / source / utils / smbpasswd.c
1 /*
2  * Unix SMB/Netbios implementation. Version 1.9. smbpasswd module. Copyright
3  * (C) Jeremy Allison 1995-1997.
4  * 
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 2 of the License, or (at your option)
8  * any later version.
9  * 
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  * 
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 675
17  * Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include "includes.h"
21
22 /* Static buffers we will return. */
23 static struct smb_passwd pw_buf;
24 static pstring  user_name;
25 static unsigned char smbpwd[16];
26 static unsigned char smbntpwd[16];
27
28 static int gethexpwd(char *p, char *pwd)
29 {
30         int i;
31         unsigned char   lonybble, hinybble;
32         char           *hexchars = "0123456789ABCDEF";
33         char           *p1, *p2;
34         for (i = 0; i < 32; i += 2) {
35                 hinybble = toupper(p[i]);
36                 lonybble = toupper(p[i + 1]);
37
38                 p1 = strchr(hexchars, hinybble);
39                 p2 = strchr(hexchars, lonybble);
40                 if (!p1 || !p2)
41                         return (False);
42
43                 hinybble = PTR_DIFF(p1, hexchars);
44                 lonybble = PTR_DIFF(p2, hexchars);
45
46                 pwd[i / 2] = (hinybble << 4) | lonybble;
47         }
48         return (True);
49 }
50
51 struct smb_passwd *
52 _my_get_smbpwnam(FILE * fp, char *name, BOOL * valid_old_pwd, 
53                 BOOL *got_valid_nt_entry, long *pwd_seekpos)
54 {
55         char            linebuf[256];
56         unsigned char   c;
57         unsigned char  *p;
58         long            uidval;
59         long            linebuf_len;
60
61         /*
62          * Scan the file, a line at a time and check if the name matches.
63          */
64         while (!feof(fp)) {
65                 linebuf[0] = '\0';
66                 *pwd_seekpos = ftell(fp);
67
68                 fgets(linebuf, 256, fp);
69                 if (ferror(fp))
70                         return NULL;
71
72                 /*
73                  * Check if the string is terminated with a newline - if not
74                  * then we must keep reading and discard until we get one.
75                  */
76                 linebuf_len = strlen(linebuf);
77                 if (linebuf[linebuf_len - 1] != '\n') {
78                         c = '\0';
79                         while (!ferror(fp) && !feof(fp)) {
80                                 c = fgetc(fp);
81                                 if (c == '\n')
82                                         break;
83                         }
84                 } else
85                         linebuf[linebuf_len - 1] = '\0';
86
87                 if ((linebuf[0] == 0) && feof(fp))
88                         break;
89                 /*
90                  * The line we have should be of the form :-
91                  * 
92                  * username:uid:[32hex bytes]:....other flags presently
93                  * ignored....
94                  * 
95                  * or,
96                  * 
97                  * username:uid:[32hex bytes]:[32hex bytes]:....ignored....
98                  * 
99                  * if Windows NT compatible passwords are also present.
100                  */
101
102                 if (linebuf[0] == '#' || linebuf[0] == '\0')
103                         continue;
104                 p = (unsigned char *) strchr(linebuf, ':');
105                 if (p == NULL)
106                         continue;
107                 /*
108                  * As 256 is shorter than a pstring we don't need to check
109                  * length here - if this ever changes....
110                  */
111                 strncpy(user_name, linebuf, PTR_DIFF(p, linebuf));
112                 user_name[PTR_DIFF(p, linebuf)] = '\0';
113                 if (!strequal(user_name, name))
114                         continue;
115
116                 /* User name matches - get uid and password */
117                 p++;            /* Go past ':' */
118                 if (!isdigit(*p))
119                         return (False);
120
121                 uidval = atoi((char *) p);
122                 while (*p && isdigit(*p))
123                         p++;
124
125                 if (*p != ':')
126                         return (False);
127
128                 /*
129                  * Now get the password value - this should be 32 hex digits
130                  * which are the ascii representations of a 16 byte string.
131                  * Get two at a time and put them into the password.
132                  */
133                 p++;
134                 *pwd_seekpos += PTR_DIFF(p, linebuf);   /* Save exact position
135                                                          * of passwd in file -
136                                                          * this is used by
137                                                          * smbpasswd.c */
138                 if (*p == '*' || *p == 'X') {
139                         /* Password deliberately invalid - end here. */
140                         *valid_old_pwd = False;
141                         *got_valid_nt_entry = False;
142                         pw_buf.smb_nt_passwd = NULL;    /* No NT password (yet)*/
143
144                         /* Now check if the NT compatible password is
145                            available. */
146                         p += 33; /* Move to the first character of the line after 
147                                                 the lanman password. */
148                         if ((linebuf_len >= (PTR_DIFF(p, linebuf) + 33)) && (p[32] == ':')) {
149                                 /* NT Entry was valid - even if 'X' or '*', can be overwritten */
150                                 *got_valid_nt_entry = True;
151                                 if (*p != '*' && *p != 'X') {
152                                   if (gethexpwd((char *)p,(char *)smbntpwd))
153                                     pw_buf.smb_nt_passwd = smbntpwd;
154                                 }
155                         }
156                         pw_buf.smb_name = user_name;
157                         pw_buf.smb_userid = uidval;
158                         pw_buf.smb_passwd = NULL;       /* No password */
159                         return (&pw_buf);
160                 }
161                 if (linebuf_len < (PTR_DIFF(p, linebuf) + 33))
162                         return (False);
163
164                 if (p[32] != ':')
165                         return (False);
166
167                 if (!strncasecmp((char *)p, "NO PASSWORD", 11)) {
168                   pw_buf.smb_passwd = NULL;     /* No password */
169                 } else {
170                   if(!gethexpwd((char *)p,(char *)smbpwd))
171                     return False;
172                   pw_buf.smb_passwd = smbpwd;
173                 }
174
175                 pw_buf.smb_name = user_name;
176                 pw_buf.smb_userid = uidval;
177                 pw_buf.smb_nt_passwd = NULL;
178                 *got_valid_nt_entry = False;
179                 *valid_old_pwd = True;
180
181                 /* Now check if the NT compatible password is
182                    available. */
183                 p += 33; /* Move to the first character of the line after 
184                                         the lanman password. */
185                 if ((linebuf_len >= (PTR_DIFF(p, linebuf) + 33)) && (p[32] == ':')) {
186                         /* NT Entry was valid - even if 'X' or '*', can be overwritten */
187                         *got_valid_nt_entry = True;
188                         if (*p != '*' && *p != 'X') {
189                           if (gethexpwd((char *)p,(char *)smbntpwd))
190                             pw_buf.smb_nt_passwd = smbntpwd;
191                         }
192                 }
193                 return &pw_buf;
194         }
195         return NULL;
196 }
197
198 /*
199  * Print command usage on stderr and die.
200  */
201 static void usage(char *name)
202 {
203         fprintf(stderr, "Usage is : %s [-add] [username] [password]\n", name);
204         exit(1);
205 }
206
207  int main(int argc, char **argv)
208 {
209   int             real_uid;
210   struct passwd  *pwd;
211   fstring         old_passwd;
212   uchar           old_p16[16];
213   uchar           old_nt_p16[16];
214   fstring         new_passwd;
215   uchar           new_p16[16];
216   uchar           new_nt_p16[16];
217   char           *p;
218   struct smb_passwd *smb_pwent;
219   FILE           *fp;
220   BOOL            valid_old_pwd = False;
221   BOOL                  got_valid_nt_entry = False;
222   BOOL            add_user = False;
223   int             add_pass = 0;
224   long            seekpos;
225   int             pwfd;
226   char            ascii_p16[66];
227   char            c;
228   int             ret, i, err, writelen;
229   int             lockfd = -1;
230   char           *pfile = SMB_PASSWD_FILE;
231   char            readbuf[16 * 1024];
232   
233   TimeInit();
234
235   setup_logging(argv[0],True);
236   
237   charset_initialise();
238   
239 #ifndef DEBUG_PASSWORD
240   /* Check the effective uid */
241   if (geteuid() != 0) {
242     fprintf(stderr, "%s: Must be setuid root.\n", argv[0]);
243     exit(1);
244   }
245 #endif
246   
247   /* Get the real uid */
248   real_uid = getuid();
249   
250   /* Deal with usage problems */
251   if (real_uid == 0)
252   {
253     /* As root we can change anothers password and add a user. */
254     if (argc > 4 )
255       usage(argv[0]);
256   }
257   else if (argc == 2 || argc > 3)
258   {
259     fprintf(stderr, "%s: Only root can set anothers password.\n", argv[0]);
260     usage(argv[0]);
261   }
262   
263   if (real_uid == 0 && (argc > 1))
264   {
265     /* We are root - check if we should add the user */
266     if ((argv[1][0] == '-') && (argv[1][1] == 'a'))
267       add_user = True;
268
269     if(add_user && (argc <= 2 || argc > 4))
270       usage(argv[0]);
271
272     /* root can specify password on command-line */
273     if (argc == (add_user ? 4 : 3))
274     {
275       /* -a argument (add_user): new password is 3rd argument. */
276       /* no -a argument (add_user): new password is 2nd argument */
277
278       add_pass = add_user ? 3 : 2;
279     }
280
281     /* If we are root we can change another's password. */
282     strncpy(user_name, add_user ? argv[2] : argv[1], sizeof(user_name) - 1);
283     user_name[sizeof(user_name) - 1] = '\0';
284
285     pwd = getpwnam(user_name);
286   }
287   else
288   {
289     /* non-root can specify old pass / new pass on command-line */
290     if (argc == 3)
291     {
292        /* non-root specifies new password as 2nd argument */
293        add_pass = 2;
294     }
295
296     pwd = getpwuid(real_uid);
297   }
298   
299   if (pwd == 0) {
300     fprintf(stderr, "%s: Unable to get UNIX password entry for user.\n", argv[0]);
301     exit(1);
302   }
303
304   /* If we are root we don't ask for the old password. */
305   old_passwd[0] = '\0';
306   if (real_uid != 0)
307   {
308     if (add_pass)
309     {
310       /* old password, as non-root, is 1st argument */
311       strncpy(old_passwd, argv[1], sizeof(fstring));
312     }
313     else
314     {
315       p = getpass("Old SMB password:");
316       strncpy(old_passwd, p, sizeof(fstring));
317     }
318     old_passwd[sizeof(fstring)-1] = '\0';
319   }
320
321   if (add_pass)
322   {
323     /* new password is specified on the command line */
324     strncpy(new_passwd, argv[add_user ? 3 : 2], sizeof(new_passwd) - 1);
325     new_passwd[sizeof(new_passwd) - 1] = '\0';
326   }
327   else
328   {
329     new_passwd[0] = '\0';
330
331     p = getpass("New SMB password:");
332
333     strncpy(new_passwd, p, sizeof(fstring));
334     new_passwd[sizeof(fstring)-1] = '\0';
335
336     p = getpass("Retype new SMB password:");
337
338     if (strncmp(p, new_passwd, sizeof(fstring)-1))
339     {
340       fprintf(stderr, "%s: Mismatch - password unchanged.\n", argv[0]);
341       exit(1);
342     }
343   }
344   
345   if (new_passwd[0] == '\0')
346   {
347     printf("Password not set\n");
348     exit(0);
349   }
350   
351   /* Calculate the MD4 hash (NT compatible) of the old and new passwords */
352   memset(old_nt_p16, '\0', 16);
353   E_md4hash((uchar *)old_passwd, old_nt_p16);
354   
355   memset(new_nt_p16, '\0', 16);
356   E_md4hash((uchar *) new_passwd, new_nt_p16);
357   
358   /* Mangle the passwords into Lanman format */
359   old_passwd[14] = '\0';
360   strupper(old_passwd);
361   new_passwd[14] = '\0';
362   strupper(new_passwd);
363   
364   /*
365    * Calculate the SMB (lanman) hash functions of both old and new passwords.
366    */
367   
368   memset(old_p16, '\0', 16);
369   E_P16((uchar *) old_passwd, old_p16);
370   
371   memset(new_p16, '\0', 16);
372   E_P16((uchar *) new_passwd, new_p16);
373   
374   /*
375    * Open the smbpaswd file XXXX - we need to parse smb.conf to get the
376    * filename
377    */
378   if ((fp = fopen(pfile, "a+")) == NULL) {
379     err = errno;
380     fprintf(stderr, "%s: Failed to open password file %s.\n",
381             argv[0], pfile);
382     errno = err;
383     perror(argv[0]);
384     exit(err);
385   }
386   
387   /* position at the start of the file */
388   fseek(fp, 0, SEEK_SET);
389
390   /* Set read buffer to 16k for effiecient reads */
391   setvbuf(fp, readbuf, _IOFBF, sizeof(readbuf));
392   
393   /* make sure it is only rw by the owner */
394   chmod(pfile, 0600);
395   
396   /* Lock the smbpasswd file for write. */
397   if ((lockfd = pw_file_lock(pfile, F_WRLCK, 5)) < 0) {
398     err = errno;
399     fprintf(stderr, "%s: Failed to lock password file %s.\n",
400             argv[0], pfile);
401     fclose(fp);
402     errno = err;
403     perror(argv[0]);
404     exit(err);
405   }
406   /* Get the smb passwd entry for this user */
407   smb_pwent = _my_get_smbpwnam(fp, pwd->pw_name, &valid_old_pwd, 
408                                &got_valid_nt_entry, &seekpos);
409   if (smb_pwent == NULL) {
410     if(add_user == False) {
411       fprintf(stderr, "%s: Failed to find entry for user %s in file %s.\n",
412               argv[0], pwd->pw_name, pfile);
413       fclose(fp);
414       pw_file_unlock(lockfd);
415       exit(1);
416     }
417
418     /* Create a new smb passwd entry and set it to the given password. */
419     {
420       int fd;
421       int new_entry_length;
422       char *new_entry;
423       long offpos;
424
425       /* The add user write needs to be atomic - so get the fd from 
426          the fp and do a raw write() call.
427        */
428       fd = fileno(fp);
429
430       if((offpos = lseek(fd, 0, SEEK_END)) == -1) {
431         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
432 Error was %s\n", argv[0], pwd->pw_name, pfile, strerror(errno));
433         fclose(fp);
434         pw_file_unlock(lockfd);
435         exit(1);
436       }
437
438       new_entry_length = strlen(pwd->pw_name) + 1 + 15 + 1 + 
439                          32 + 1 + 32 + 1 + strlen(pwd->pw_gecos) + 
440                          1 + strlen(pwd->pw_dir) + 1 + 
441                          strlen(pwd->pw_shell) + 1;
442       if((new_entry = (char *)malloc( new_entry_length )) == 0) {
443         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
444 Error was %s\n", argv[0], pwd->pw_name, pfile, strerror(errno));
445         fclose(fp);
446         pw_file_unlock(lockfd);
447         exit(1);
448       }
449
450       sprintf(new_entry, "%s:%u:", pwd->pw_name, pwd->pw_uid);
451       p = &new_entry[strlen(new_entry)];
452       for( i = 0; i < 16; i++)
453         sprintf(&p[i*2], "%02X", new_p16[i]);
454       p += 32;
455       *p++ = ':';
456       for( i = 0; i < 16; i++)
457         sprintf(&p[i*2], "%02X", new_nt_p16[i]);
458       p += 32;
459       *p++ = ':';
460       sprintf(p, "%s:%s:%s\n", pwd->pw_gecos, 
461               pwd->pw_dir, pwd->pw_shell);
462       if(write(fd, new_entry, strlen(new_entry)) != strlen(new_entry)) {
463         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
464 Error was %s\n", argv[0], pwd->pw_name, pfile, strerror(errno));
465         /* Remove the entry we just wrote. */
466         if(ftruncate(fd, offpos) == -1) {
467           fprintf(stderr, "%s: ERROR failed to ftruncate file %s. \
468 Error was %s. Password file may be corrupt ! Please examine by hand !\n", 
469                    argv[0], pwd->pw_name, strerror(errno));
470         }
471         fclose(fp);
472         pw_file_unlock(lockfd);
473         exit(1);
474       }
475       
476       fclose(fp);  
477       pw_file_unlock(lockfd);  
478       exit(0);
479     }
480   }
481
482   /* If we are root or the password is 'NO PASSWORD' then
483      we don't need to check the old password. */
484   if (real_uid != 0) {
485     if (valid_old_pwd == False) {
486       fprintf(stderr, "%s: User %s has no old SMB password.\n", argv[0], pwd->pw_name);
487     }
488     /* Check the old Lanman password - NULL means 'NO PASSWORD' */
489     if (smb_pwent->smb_passwd != NULL) {
490       if (memcmp(old_p16, smb_pwent->smb_passwd, 16)) {
491         fprintf(stderr, "%s: Couldn't change password.\n", argv[0]);
492         fclose(fp);
493         pw_file_unlock(lockfd);
494         exit(1);
495       }
496     }
497     /* Check the NT password if it exists */
498     if (smb_pwent->smb_nt_passwd != NULL) {
499       if (memcmp(old_nt_p16, smb_pwent->smb_nt_passwd, 16)) {
500         fprintf(stderr, "%s: Couldn't change password.\n", argv[0]);
501         fclose(fp);
502         pw_file_unlock(lockfd);
503         exit(1);
504       }
505     }
506   }
507   /*
508    * If we get here either we were root or the old password checked out
509    * ok.
510    */
511   /* Create the 32 byte representation of the new p16 */
512   for (i = 0; i < 16; i++) {
513     sprintf(&ascii_p16[i * 2], "%02X", (uchar) new_p16[i]);
514   }
515   if(got_valid_nt_entry) {
516     /* Add on the NT md4 hash */
517     ascii_p16[32] = ':';
518     for (i = 0; i < 16; i++) {
519       sprintf(&ascii_p16[(i * 2)+33], "%02X", (uchar) new_nt_p16[i]);
520     }
521   }
522   /*
523    * Do an atomic write into the file at the position defined by
524    * seekpos.
525    */
526   pwfd = fileno(fp);
527   ret = lseek(pwfd, seekpos - 1, SEEK_SET);
528   if (ret != seekpos - 1) {
529     err = errno;
530     fprintf(stderr, "%s: seek fail on file %s.\n",
531             argv[0], pfile);
532     fclose(fp);
533     errno = err;
534     perror(argv[0]);
535     pw_file_unlock(lockfd);
536     exit(1);
537   }
538   /* Sanity check - ensure the character is a ':' */
539   if (read(pwfd, &c, 1) != 1) {
540     err = errno;
541     fprintf(stderr, "%s: read fail on file %s.\n",
542             argv[0], pfile);
543     fclose(fp);
544     errno = err;
545     perror(argv[0]);
546     pw_file_unlock(lockfd);
547     exit(1);
548   }
549   if (c != ':') {
550     fprintf(stderr, "%s: sanity check on passwd file %s failed.\n",
551             argv[0], pfile);
552     fclose(fp);
553     pw_file_unlock(lockfd);
554     exit(1);
555   }
556   writelen = (got_valid_nt_entry) ? 65 : 32;
557   if (write(pwfd, ascii_p16, writelen) != writelen) {
558     err = errno;
559     fprintf(stderr, "%s: write fail in file %s.\n",
560             argv[0], pfile);
561     fclose(fp);
562     errno = err;
563     perror(argv[0]);
564     pw_file_unlock(lockfd);
565     exit(err);
566   }
567   fclose(fp);
568   pw_file_unlock(lockfd);
569   printf("Password changed\n");
570   return 0;
571 }
572