- if the user already exists then ignore the -add command
[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   fp = fopen(pfile, "r+");
379   if (!fp && errno == ENOENT) {
380           fp = fopen(pfile, "w");
381           if (fp) {
382                   fprintf(fp, "# Samba SMB password file\n");
383                   fclose(fp);
384                   fp = fopen(pfile, "r+");
385           }
386   }
387   if (!fp) {
388           err = errno;
389           fprintf(stderr, "%s: Failed to open password file %s.\n",
390                   argv[0], pfile);
391           errno = err;
392           perror(argv[0]);
393           exit(err);
394   }
395   
396   /* Set read buffer to 16k for effiecient reads */
397   setvbuf(fp, readbuf, _IOFBF, sizeof(readbuf));
398   
399   /* make sure it is only rw by the owner */
400   chmod(pfile, 0600);
401   
402   /* Lock the smbpasswd file for write. */
403   if ((lockfd = pw_file_lock(pfile, F_WRLCK, 5)) < 0) {
404     err = errno;
405     fprintf(stderr, "%s: Failed to lock password file %s.\n",
406             argv[0], pfile);
407     fclose(fp);
408     errno = err;
409     perror(argv[0]);
410     exit(err);
411   }
412   /* Get the smb passwd entry for this user */
413   smb_pwent = _my_get_smbpwnam(fp, pwd->pw_name, &valid_old_pwd, 
414                                &got_valid_nt_entry, &seekpos);
415   if (smb_pwent == NULL) {
416     if(add_user == False) {
417       fprintf(stderr, "%s: Failed to find entry for user %s in file %s.\n",
418               argv[0], pwd->pw_name, pfile);
419       fclose(fp);
420       pw_file_unlock(lockfd);
421       exit(1);
422     }
423
424     /* Create a new smb passwd entry and set it to the given password. */
425     {
426       int fd;
427       int new_entry_length;
428       char *new_entry;
429       long offpos;
430
431       /* The add user write needs to be atomic - so get the fd from 
432          the fp and do a raw write() call.
433        */
434       fd = fileno(fp);
435
436       if((offpos = lseek(fd, 0, SEEK_END)) == -1) {
437         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
438 Error was %s\n", argv[0], pwd->pw_name, pfile, strerror(errno));
439         fclose(fp);
440         pw_file_unlock(lockfd);
441         exit(1);
442       }
443
444       new_entry_length = strlen(pwd->pw_name) + 1 + 15 + 1 + 
445                          32 + 1 + 32 + 1 + strlen(pwd->pw_gecos) + 
446                          1 + strlen(pwd->pw_dir) + 1 + 
447                          strlen(pwd->pw_shell) + 1;
448       if((new_entry = (char *)malloc( new_entry_length )) == 0) {
449         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
450 Error was %s\n", argv[0], pwd->pw_name, pfile, strerror(errno));
451         fclose(fp);
452         pw_file_unlock(lockfd);
453         exit(1);
454       }
455
456       sprintf(new_entry, "%s:%u:", pwd->pw_name, pwd->pw_uid);
457       p = &new_entry[strlen(new_entry)];
458       for( i = 0; i < 16; i++)
459         sprintf(&p[i*2], "%02X", new_p16[i]);
460       p += 32;
461       *p++ = ':';
462       for( i = 0; i < 16; i++)
463         sprintf(&p[i*2], "%02X", new_nt_p16[i]);
464       p += 32;
465       *p++ = ':';
466       sprintf(p, "%s:%s:%s\n", pwd->pw_gecos, 
467               pwd->pw_dir, pwd->pw_shell);
468       if(write(fd, new_entry, strlen(new_entry)) != strlen(new_entry)) {
469         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
470 Error was %s\n", argv[0], pwd->pw_name, pfile, strerror(errno));
471         /* Remove the entry we just wrote. */
472         if(ftruncate(fd, offpos) == -1) {
473           fprintf(stderr, "%s: ERROR failed to ftruncate file %s. \
474 Error was %s. Password file may be corrupt ! Please examine by hand !\n", 
475                    argv[0], pwd->pw_name, strerror(errno));
476         }
477         fclose(fp);
478         pw_file_unlock(lockfd);
479         exit(1);
480       }
481       
482       fclose(fp);  
483       pw_file_unlock(lockfd);  
484       exit(0);
485     }
486   } else {
487           /* the entry already existed */
488           add_user = False;
489   }
490
491   /* If we are root or the password is 'NO PASSWORD' then
492      we don't need to check the old password. */
493   if (real_uid != 0) {
494     if (valid_old_pwd == False) {
495       fprintf(stderr, "%s: User %s has no old SMB password.\n", argv[0], pwd->pw_name);
496     }
497     /* Check the old Lanman password - NULL means 'NO PASSWORD' */
498     if (smb_pwent->smb_passwd != NULL) {
499       if (memcmp(old_p16, smb_pwent->smb_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     /* Check the NT password if it exists */
507     if (smb_pwent->smb_nt_passwd != NULL) {
508       if (memcmp(old_nt_p16, smb_pwent->smb_nt_passwd, 16)) {
509         fprintf(stderr, "%s: Couldn't change password.\n", argv[0]);
510         fclose(fp);
511         pw_file_unlock(lockfd);
512         exit(1);
513       }
514     }
515   }
516   /*
517    * If we get here either we were root or the old password checked out
518    * ok.
519    */
520   /* Create the 32 byte representation of the new p16 */
521   for (i = 0; i < 16; i++) {
522     sprintf(&ascii_p16[i * 2], "%02X", (uchar) new_p16[i]);
523   }
524   if(got_valid_nt_entry) {
525     /* Add on the NT md4 hash */
526     ascii_p16[32] = ':';
527     for (i = 0; i < 16; i++) {
528       sprintf(&ascii_p16[(i * 2)+33], "%02X", (uchar) new_nt_p16[i]);
529     }
530   }
531   /*
532    * Do an atomic write into the file at the position defined by
533    * seekpos.
534    */
535   pwfd = fileno(fp);
536   ret = lseek(pwfd, seekpos - 1, SEEK_SET);
537   if (ret != seekpos - 1) {
538     err = errno;
539     fprintf(stderr, "%s: seek fail on file %s.\n",
540             argv[0], pfile);
541     fclose(fp);
542     errno = err;
543     perror(argv[0]);
544     pw_file_unlock(lockfd);
545     exit(1);
546   }
547   /* Sanity check - ensure the character is a ':' */
548   if (read(pwfd, &c, 1) != 1) {
549     err = errno;
550     fprintf(stderr, "%s: read fail on file %s.\n",
551             argv[0], pfile);
552     fclose(fp);
553     errno = err;
554     perror(argv[0]);
555     pw_file_unlock(lockfd);
556     exit(1);
557   }
558   if (c != ':') {
559     fprintf(stderr, "%s: sanity check on passwd file %s failed.\n",
560             argv[0], pfile);
561     fclose(fp);
562     pw_file_unlock(lockfd);
563     exit(1);
564   }
565   writelen = (got_valid_nt_entry) ? 65 : 32;
566   if (write(pwfd, ascii_p16, writelen) != writelen) {
567     err = errno;
568     fprintf(stderr, "%s: write fail in file %s.\n",
569             argv[0], pfile);
570     fclose(fp);
571     errno = err;
572     perror(argv[0]);
573     pw_file_unlock(lockfd);
574     exit(err);
575   }
576   fclose(fp);
577   pw_file_unlock(lockfd);
578   printf("Password changed\n");
579   return 0;
580 }
581