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