Added check for getpwnam returning NULL.
[samba.git] / source / utils / smbpasswd.c
1 /*
2  * Unix SMB/Netbios implementation. Version 1.9. smbpasswd module. Copyright
3  * (C) Jeremy Allison 1995-1998
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 /* 
23  * Password changing error codes.
24  */
25
26 struct
27 {
28   int err;
29   char *message;
30 } pw_change_errmap[] =
31 {
32   {5,    "User has insufficient privilege" },
33   {86,   "The specified password is invalid" },
34   {2226, "Operation only permitted on a Primary Domain Controller"  },
35   {2242, "The password of this user has expired." },
36   {2243, "The password of this user cannot change." },
37   {2244, "This password cannot be used now (password history conflict)." },
38   {2245, "The password is shorter than required." },
39   {2246, "The password of this user is too recent to change."},
40   {0, NULL}
41 };
42
43 /******************************************************
44  Return an error message for a remote password change.
45 *******************************************************/
46
47 char *get_error_message(struct cli_state *cli)
48 {
49   static fstring error_message;
50   int errclass;
51   int errnum;
52   int i;
53
54   /*
55    * Errors are of two kinds - smb errors,
56    * dealt with by cli_errstr, and rap
57    * errors, whose error code is in cli.error.
58    */
59
60   cli_error(cli, &errclass, &errnum);
61   if(errclass != 0)
62     return cli_errstr(cli);
63
64   sprintf(error_message, "code %d", cli->error);
65
66   for(i = 0; pw_change_errmap[i].message != NULL; i++) {
67     if (pw_change_errmap[i].err == cli->error) {
68       fstrcpy( error_message, pw_change_errmap[i].message);
69       break;
70     }
71   }
72
73   return error_message;
74 }
75
76 /******************************************************
77  Convert a hex password.
78 *******************************************************/
79
80 static int gethexpwd(char *p, char *pwd)
81 {
82         int i;
83         unsigned char   lonybble, hinybble;
84         char           *hexchars = "0123456789ABCDEF";
85         char           *p1, *p2;
86         for (i = 0; i < 32; i += 2) {
87                 hinybble = toupper(p[i]);
88                 lonybble = toupper(p[i + 1]);
89
90                 p1 = strchr(hexchars, hinybble);
91                 p2 = strchr(hexchars, lonybble);
92                 if (!p1 || !p2)
93                         return (False);
94
95                 hinybble = PTR_DIFF(p1, hexchars);
96                 lonybble = PTR_DIFF(p2, hexchars);
97
98                 pwd[i / 2] = (hinybble << 4) | lonybble;
99         }
100         return (True);
101 }
102
103 /******************************************************
104  Find a password entry by name.
105 *******************************************************/
106
107 static struct smb_passwd *
108 _my_get_smbpwnam(FILE * fp, char *name, BOOL * valid_old_pwd, 
109                 BOOL *got_valid_nt_entry, long *pwd_seekpos)
110 {
111         /* Static buffers we will return. */
112         static struct smb_passwd pw_buf;
113         static pstring  user_name;
114         static unsigned char smbpwd[16];
115         static unsigned char smbntpwd[16];
116
117         char            linebuf[256];
118         unsigned char   c;
119         unsigned char  *p;
120         long            uidval;
121         long            linebuf_len;
122
123         pw_buf.acct_ctrl = ACB_NORMAL;
124
125         /*
126          * Scan the file, a line at a time and check if the name matches.
127          */
128         while (!feof(fp)) {
129                 linebuf[0] = '\0';
130                 *pwd_seekpos = ftell(fp);
131
132                 fgets(linebuf, 256, fp);
133                 if (ferror(fp))
134                         return NULL;
135
136                 /*
137                  * Check if the string is terminated with a newline - if not
138                  * then we must keep reading and discard until we get one.
139                  */
140                 linebuf_len = strlen(linebuf);
141                 if (linebuf[linebuf_len - 1] != '\n') {
142                         c = '\0';
143                         while (!ferror(fp) && !feof(fp)) {
144                                 c = fgetc(fp);
145                                 if (c == '\n')
146                                         break;
147                         }
148                 } else
149                         linebuf[linebuf_len - 1] = '\0';
150
151                 if ((linebuf[0] == 0) && feof(fp))
152                         break;
153                 /*
154                  * The line we have should be of the form :-
155                  * 
156                  * username:uid:[32hex bytes]:....other flags presently
157                  * ignored....
158                  * 
159                  * or,
160                  * 
161                  * username:uid:[32hex bytes]:[32hex bytes]:....ignored....
162                  * 
163                  * if Windows NT compatible passwords are also present.
164                  */
165
166                 if (linebuf[0] == '#' || linebuf[0] == '\0')
167                         continue;
168                 p = (unsigned char *) strchr(linebuf, ':');
169                 if (p == NULL)
170                         continue;
171                 /*
172                  * As 256 is shorter than a pstring we don't need to check
173                  * length here - if this ever changes....
174                  */
175                 strncpy(user_name, linebuf, PTR_DIFF(p, linebuf));
176                 user_name[PTR_DIFF(p, linebuf)] = '\0';
177                 if (!strequal(user_name, name))
178                         continue;
179
180                 /* User name matches - get uid and password */
181                 p++;            /* Go past ':' */
182                 if (!isdigit(*p))
183                         return (False);
184
185                 uidval = atoi((char *) p);
186                 while (*p && isdigit(*p))
187                         p++;
188
189                 if (*p != ':')
190                         return (False);
191
192                 /*
193                  * Now get the password value - this should be 32 hex digits
194                  * which are the ascii representations of a 16 byte string.
195                  * Get two at a time and put them into the password.
196                  */
197                 p++;
198                 *pwd_seekpos += PTR_DIFF(p, linebuf);   /* Save exact position
199                                                          * of passwd in file -
200                                                          * this is used by
201                                                          * smbpasswd.c */
202                 if (*p == '*' || *p == 'X') {
203                         /* Password deliberately invalid - end here. */
204                         *valid_old_pwd = False;
205                         *got_valid_nt_entry = False;
206                         pw_buf.smb_nt_passwd = NULL;    /* No NT password (yet)*/
207
208                         pw_buf.acct_ctrl |= ACB_DISABLED;
209
210                         /* Now check if the NT compatible password is
211                            available. */
212                         p += 33; /* Move to the first character of the line after 
213                                                 the lanman password. */
214                         if ((linebuf_len >= (PTR_DIFF(p, linebuf) + 33)) && (p[32] == ':')) {
215                                 /* NT Entry was valid - even if 'X' or '*', can be overwritten */
216                                 *got_valid_nt_entry = True;
217                                 if (*p != '*' && *p != 'X') {
218                                   if (gethexpwd((char *)p,(char *)smbntpwd))
219                                     pw_buf.smb_nt_passwd = smbntpwd;
220                                 }
221                         }
222                         pw_buf.smb_name = user_name;
223                         pw_buf.smb_userid = uidval;
224                         pw_buf.smb_passwd = NULL;       /* No password */
225                         return (&pw_buf);
226                 }
227                 if (linebuf_len < (PTR_DIFF(p, linebuf) + 33))
228                         return (False);
229
230                 if (p[32] != ':')
231                         return (False);
232
233                 if (!strncasecmp((char *)p, "NO PASSWORD", 11)) {
234                   pw_buf.smb_passwd = NULL;     /* No password */
235                   pw_buf.acct_ctrl |= ACB_PWNOTREQ;
236                 } else {
237                   if(!gethexpwd((char *)p,(char *)smbpwd))
238                     return False;
239                   pw_buf.smb_passwd = smbpwd;
240                 }
241
242                 pw_buf.smb_name = user_name;
243                 pw_buf.smb_userid = uidval;
244                 pw_buf.smb_nt_passwd = NULL;
245                 *got_valid_nt_entry = False;
246                 *valid_old_pwd = True;
247
248                 /* Now check if the NT compatible password is
249                    available. */
250                 p += 33; /* Move to the first character of the line after 
251                                         the lanman password. */
252                 if ((linebuf_len >= (PTR_DIFF(p, linebuf) + 33)) && (p[32] == ':')) {
253                         /* NT Entry was valid - even if 'X' or '*', can be overwritten */
254                         *got_valid_nt_entry = True;
255                         if (*p != '*' && *p != 'X') {
256                           if (gethexpwd((char *)p,(char *)smbntpwd))
257                             pw_buf.smb_nt_passwd = smbntpwd;
258                         }
259
260                         p += 33; /* Move to the first character of the line after
261                                     the NT password. */
262                 }
263
264                 /*
265                  * Check if the account type bits have been encoded after the
266                  * NT password (in the form [NDHTUWSLXI]).
267                  */
268             
269                 if (*p == '[') {
270                   BOOL finished = False;
271             
272                   pw_buf.acct_ctrl = 0;
273             
274                   for(p++;*p && !finished; p++) {
275                     switch (*p) {
276 #if 0
277                       /* 
278                        * Hmmm. Don't allow these to be set/read independently
279                        * of the actual password fields. We don't want a mismatch.
280                        * JRA.
281                        */
282                       case 'N':
283                         /* 'N'o password. */
284                         pw_buf.acct_ctrl |= ACB_PWNOTREQ;
285                         break;
286                       case 'D':
287                         /* 'D'isabled. */
288                         pw_buf.acct_ctrl |= ACB_DISABLED;
289                         break;
290 #endif
291                       case 'H':
292                         /* 'H'omedir required. */
293                         pw_buf.acct_ctrl |= ACB_HOMDIRREQ;
294                         break;
295                       case 'T':
296                         /* 'T'emp account. */
297                         pw_buf.acct_ctrl |= ACB_TEMPDUP;
298                         break;
299                       case 'U':
300                         /* 'U'ser account (normal). */
301                         pw_buf.acct_ctrl |= ACB_NORMAL;
302                         break;
303                       case 'M':
304                         /* 'M'NS logon user account. What is this ? */
305                         pw_buf.acct_ctrl |= ACB_MNS;
306                         break;
307                       case 'W':
308                         /* 'W'orkstation account. */
309                         pw_buf.acct_ctrl |= ACB_WSTRUST;
310                         break;
311                       case 'S':
312                         /* 'S'erver account. */
313                         pw_buf.acct_ctrl |= ACB_SVRTRUST;
314                         break;
315                       case 'L':
316                         /* 'L'ocked account. */
317                         pw_buf.acct_ctrl |= ACB_AUTOLOCK;
318                         break;
319                       case 'X':
320                         /* No 'X'piry. */
321                         pw_buf.acct_ctrl |= ACB_PWNOEXP;
322                         break;
323                       case 'I':
324                         /* 'I'nterdomain trust account. */
325                         pw_buf.acct_ctrl |= ACB_DOMTRUST;
326                         break;
327             
328                       case ':':
329                       case '\n':
330                       case '\0': 
331                       case ']':
332                       default:
333                         finished = True;
334                     }
335                   }
336             
337                   /* Must have some account type set. */
338                   if(pw_buf.acct_ctrl == 0)
339                     pw_buf.acct_ctrl = ACB_NORMAL;
340             
341                 } else {
342                   /* 'Old' style file. Fake up based on user name. */
343                   /*
344                    * Currently machine accounts are kept in the same
345                    * password file as 'normal accounts'. If this changes
346                    * we will have to fix this code. JRA.
347                    */
348                   if(pw_buf.smb_name[strlen(pw_buf.smb_name) - 1] == '$') {
349                     pw_buf.acct_ctrl &= ~ACB_NORMAL;
350                     pw_buf.acct_ctrl |= ACB_WSTRUST;
351                   }
352                 }
353                 return &pw_buf;
354         }
355         return NULL;
356 }
357
358 /**********************************************************
359  Encode the account control bits into a string.
360 **********************************************************/
361
362 char *encode_acct_ctrl(uint16 acct_ctrl)
363 {
364   static fstring acct_str;
365   char *p = acct_str;
366
367   *p++ = '[';
368
369   if(acct_ctrl & ACB_HOMDIRREQ)
370     *p++ = 'H';
371   if(acct_ctrl & ACB_TEMPDUP)
372     *p++ = 'T';
373   if(acct_ctrl & ACB_NORMAL)
374     *p++ = 'U';
375   if(acct_ctrl & ACB_MNS)
376     *p++ = 'M';
377   if(acct_ctrl & ACB_WSTRUST)
378     *p++ = 'W';
379   if(acct_ctrl & ACB_SVRTRUST)
380     *p++ = 'S';
381   if(acct_ctrl & ACB_AUTOLOCK)
382     *p++ = 'L';
383   if(acct_ctrl & ACB_PWNOEXP)
384     *p++ = 'X';
385   if(acct_ctrl & ACB_DOMTRUST)
386     *p++ = 'I';
387
388   *p++ = ']';
389   *p = '\0';
390   return acct_str;
391 }
392
393 /**********************************************************
394  Allocate an unused uid in the smbpasswd file to a new
395  machine account.
396 ***********************************************************/
397
398 int get_new_machine_uid(void)
399 {
400   int next_uid_start;
401   FILE *fp;
402   struct smb_passwd *smbpw;
403
404   if(sizeof(uid_t) == 2)
405     next_uid_start = 65533;
406
407   if(sizeof(uid_t) == 4)
408     next_uid_start = 0x7fffffff;
409
410   fp = startsmbpwent(False);
411   while((smbpw = getsmbpwent(fp)) != NULL) {
412     if((smbpw->acct_ctrl & (ACB_SVRTRUST|ACB_WSTRUST)))
413       next_uid_start = MIN(next_uid_start, (smbpw->smb_userid-1));
414   }
415   endsmbpwent(fp);
416   return next_uid_start;
417 }
418
419 /*********************************************************
420  Print command usage on stderr and die.
421 **********************************************************/
422
423 static void usage(char *name, BOOL is_root)
424 {
425         if(is_root)
426                 fprintf(stderr, "Usage is : %s [-D DEBUGLEVEL] [-a] [-d] [-m] [-n] [username] [password]\n\
427 %s: [-R <name resolve order>] [-D DEBUGLEVEL] [-r machine] [username] [password]\n%s: [-h]\n", name, name, name);
428         else
429                 fprintf(stderr, "Usage is : %s [-h] [-D DEBUGLEVEL] [-r machine] [password]\n", name);
430         exit(1);
431 }
432
433 /*********************************************************
434  Start here.
435 **********************************************************/
436
437 int main(int argc, char **argv)
438 {
439   extern char *optarg;
440   extern int optind;
441   extern int DEBUGLEVEL;
442   char *prog_name;
443   int             real_uid;
444   struct passwd  *pwd;
445   struct passwd   machine_account_pwd;
446   fstring         old_passwd;
447   fstring         new_passwd;
448   uchar           new_p16[16];
449   uchar           new_nt_p16[16];
450   char           *p;
451   struct smb_passwd *smb_pwent;
452   FILE           *fp;
453   BOOL            valid_old_pwd = False;
454   BOOL           got_valid_nt_entry = False;
455   long            seekpos;
456   int             pwfd;
457   char            ascii_p16[66];
458   char            c;
459   int             ch;
460   int             ret, i, err, writelen;
461   int             lockfd = -1;
462   char           *pfile = SMB_PASSWD_FILE;
463   char            readbuf[16 * 1024];
464   BOOL is_root = False;
465   pstring  user_name;
466   pstring  machine_dir_name;
467   char *remote_machine = NULL;
468   BOOL           add_user = False;
469   BOOL           got_new_pass = False;
470   BOOL           machine_account = False;
471   BOOL           disable_user = False;
472   BOOL           set_no_password = False;
473   pstring servicesf = CONFIGFILE;
474
475   new_passwd[0] = '\0';
476   user_name[0] = '\0';
477
478   memset(old_passwd, '\0', sizeof(old_passwd));
479   memset(new_passwd, '\0', sizeof(new_passwd));
480
481   prog_name = argv[0];
482
483   TimeInit();
484
485   setup_logging(prog_name,True);
486   
487   charset_initialise();
488
489   if (!lp_load(servicesf,True,False,False)) {
490     fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n", prog_name, servicesf);
491   }
492     
493   codepage_initialise(lp_client_code_page());
494
495   /* Get the real uid */
496   real_uid = getuid();
497   
498   /* Check the effective uid */
499   if ((geteuid() == 0) && (real_uid != 0)) {
500     fprintf(stderr, "%s: Must *NOT* be setuid root.\n", prog_name);
501     exit(1);
502   }
503
504   is_root = (real_uid == 0);
505
506   while ((ch = getopt(argc, argv, "adhmnr:R:D:")) != EOF) {
507     switch(ch) {
508     case 'a':
509       if(is_root)
510         add_user = True;
511       else
512         usage(prog_name, is_root);
513       break;
514     case 'd':
515       if(is_root) {
516         disable_user = True;
517         got_new_pass = True;
518         strcpy(new_passwd, "XXXXXX");
519       } else
520         usage(prog_name, is_root);
521       break;
522     case 'D':
523       DEBUGLEVEL = atoi(optarg);
524       break;
525     case 'n':
526       if(is_root) {
527         set_no_password = True;
528         got_new_pass = True;
529         strcpy(new_passwd, "NO PASSWORD");
530       } else
531         usage(prog_name, is_root);
532     case 'r':
533       remote_machine = optarg;
534       break;
535     case 'R':
536       if(is_root) {
537         lp_set_name_resolve_order(optarg);
538         break;
539       } else
540         usage(prog_name, is_root);
541     case 'm':
542       if(is_root) {
543         machine_account = True;
544       } else
545         usage(prog_name, is_root);
546       break;
547     case 'h':
548     default:
549       usage(prog_name, is_root);
550     }
551   }
552
553   argc -= optind;
554   argv += optind;
555
556   /*
557    * Ensure add_user and remote machine are
558    * not both set.
559    */
560   if(add_user && (remote_machine != NULL))
561     usage(prog_name, True);
562
563   if( is_root ) {
564
565     /*
566      * Deal with root - can add a user, but only locally.
567      */
568
569     switch(argc) {
570       case 0:
571         break;
572       case 1:
573         /* If we are root we can change another's password. */
574         pstrcpy(user_name, argv[0]);
575         break;
576       case 2:
577         pstrcpy(user_name, argv[0]);
578         fstrcpy(new_passwd, argv[1]);
579         got_new_pass = True;
580         break;
581       default:
582         usage(prog_name, True);
583     }
584
585     if(*user_name) {
586       if((pwd = getpwnam(user_name)) == NULL) {
587         fprintf(stderr, "%s: User \"%s\" was not found in system password file.\n", 
588                     prog_name, user_name);
589         exit(1);
590       }
591     } else {
592       if((pwd = getpwuid(real_uid)) != NULL)
593         pstrcpy( user_name, pwd->pw_name);
594     }
595
596   } else {
597
598     if(add_user) {
599       fprintf(stderr, "%s: Only root can set anothers password.\n", prog_name);
600       usage(prog_name, False);
601     }
602
603     if(argc > 1)
604       usage(prog_name, False);
605
606     if(argc == 1) {
607       fstrcpy(new_passwd, argv[0]);
608       got_new_pass = True;
609     }
610
611     if((pwd = getpwuid(real_uid)) != NULL)
612       pstrcpy( user_name, pwd->pw_name);
613
614     /*
615      * A non-root user is always setting a password
616      * via a remote machine (even if that machine is
617      * localhost).
618      */
619
620     if(remote_machine == NULL)
621       remote_machine = "127.0.0.1";
622   }    
623     
624   if (*user_name == '\0') {
625     fprintf(stderr, "%s: Unable to get a user name for password change.\n", prog_name);
626     exit(1);
627   }
628
629   /*
630    * If we are adding a machine account then pretend
631    * we already have the new password, we will be using
632    * the machinename as the password.
633    */
634
635   if(add_user && machine_account) {
636     got_new_pass = True;
637     strncpy(new_passwd, user_name, sizeof(fstring));
638     new_passwd[sizeof(fstring)-1] = '\0';
639     strlower(new_passwd);
640   }
641
642   /* 
643    * If we are root we don't ask for the old password (unless it's on a
644    * remote machine.
645    */
646
647   if (remote_machine != NULL) {
648     p = getpass("Old SMB password:");
649     fstrcpy(old_passwd, p);
650   }
651
652   if (!got_new_pass) {
653     new_passwd[0] = '\0';
654
655     p = getpass("New SMB password:");
656
657     strncpy(new_passwd, p, sizeof(fstring));
658     new_passwd[sizeof(fstring)-1] = '\0';
659
660     p = getpass("Retype new SMB password:");
661
662     if (strncmp(p, new_passwd, sizeof(fstring)-1))
663     {
664       fprintf(stderr, "%s: Mismatch - password unchanged.\n", prog_name);
665       exit(1);
666     }
667   }
668   
669   if (new_passwd[0] == '\0') {
670     printf("Password not set\n");
671     exit(0);
672   }
673  
674   /* 
675    * Now do things differently depending on if we're changing the
676    * password on a remote machine. Remember - a normal user is
677    * always using this code, looping back to the local smbd.
678    */
679
680   if(remote_machine != NULL) {
681     struct cli_state cli;
682     struct in_addr ip;
683     fstring myname;
684
685     if(get_myname(myname,NULL) == False) {
686       fprintf(stderr, "%s: unable to get my hostname.\n", prog_name );
687       exit(1);
688     }
689
690     if(!resolve_name( remote_machine, &ip)) {
691       fprintf(stderr, "%s: unable to find an IP address for machine %s.\n",
692               prog_name, remote_machine );
693       exit(1);
694     }
695  
696     cli.error = 0;
697  
698     if (!cli_initialise(&cli) || !cli_connect(&cli, remote_machine, &ip)) {
699       fprintf(stderr, "%s: unable to connect to SMB server on machine %s. Error was : %s.\n",
700               prog_name, remote_machine, get_error_message(&cli) );
701       exit(1);
702     }
703   
704     if (!cli_session_request(&cli, remote_machine, 0x20, myname)) {
705       fprintf(stderr, "%s: machine %s rejected the session setup. Error was : %s.\n",
706               prog_name, remote_machine, get_error_message(&cli) );
707       cli_shutdown(&cli);
708       exit(1);
709     }
710   
711     cli.protocol = PROTOCOL_NT1;
712
713     if (!cli_negprot(&cli)) {
714       fprintf(stderr, "%s: machine %s rejected the negotiate protocol. Error was : %s.\n",        
715               prog_name, remote_machine, get_error_message(&cli) );
716       cli_shutdown(&cli);
717       exit(1);
718     }
719   
720     if (!cli_session_setup(&cli, user_name, old_passwd, strlen(old_passwd),
721                            "", 0, "")) {
722       fprintf(stderr, "%s: machine %s rejected the session setup. Error was : %s.\n",        
723               prog_name, remote_machine, get_error_message(&cli) );
724       cli_shutdown(&cli);
725       exit(1);
726     }               
727
728     if (!cli_send_tconX(&cli, "IPC$", "IPC", "", 1)) {
729       fprintf(stderr, "%s: machine %s rejected the tconX on the IPC$ share. Error was : %s.\n",
730               prog_name, remote_machine, get_error_message(&cli) );
731       cli_shutdown(&cli);
732       exit(1);
733     }
734
735     if(!cli_oem_change_password(&cli, user_name, new_passwd, old_passwd)) {
736       fprintf(stderr, "%s: machine %s rejected the password change: Error was : %s.\n",
737               prog_name, remote_machine, get_error_message(&cli) );
738       cli_shutdown(&cli);
739       exit(1);
740     }
741
742     cli_shutdown(&cli);
743     exit(0);
744   }
745
746   /*
747    * Check for a machine account flag - make sure the username ends in
748    * a '$' etc....
749    */
750
751   if(machine_account) {
752     int username_len = strlen(user_name);
753     if(username_len >= sizeof(pstring) - 1) {
754       fprintf(stderr, "%s: machine account name too long.\n", user_name);
755       exit(1);
756     }
757
758     if(user_name[username_len] != '$') {
759       user_name[username_len] = '$';
760       user_name[username_len+1] = '\0';
761     }
762
763     /*
764      * Setup the pwd struct to point to known
765      * values for a machine account (it doesn't
766      * exist in /etc/passwd).
767      */
768
769     pwd = &machine_account_pwd;
770     pwd->pw_name = user_name;
771     sprintf(machine_dir_name, "Workstation machine account for %s", user_name);
772     pwd->pw_gecos = "";
773     pwd->pw_dir = machine_dir_name;
774     pwd->pw_shell = "";
775     pwd->pw_uid = get_new_machine_uid();
776       
777   }
778
779   /* Calculate the MD4 hash (NT compatible) of the new password. */
780   
781   memset(new_nt_p16, '\0', 16);
782   E_md4hash((uchar *) new_passwd, new_nt_p16);
783   
784   /* Mangle the password into Lanman format */
785   new_passwd[14] = '\0';
786   strupper(new_passwd);
787   
788   /*
789    * Calculate the SMB (lanman) hash functions of the new password.
790    */
791   
792   memset(new_p16, '\0', 16);
793   E_P16((uchar *) new_passwd, new_p16);
794   
795   /*
796    * Open the smbpaswd file XXXX - we need to parse smb.conf to get the
797    * filename
798    */
799   fp = fopen(pfile, "r+");
800   if (!fp && errno == ENOENT) {
801           fp = fopen(pfile, "w");
802           if (fp) {
803                   fprintf(fp, "# Samba SMB password file\n");
804                   fclose(fp);
805                   fp = fopen(pfile, "r+");
806           }
807   }
808   if (!fp) {
809           err = errno;
810           fprintf(stderr, "%s: Failed to open password file %s.\n",
811                   prog_name, pfile);
812           errno = err;
813           perror(prog_name);
814           exit(err);
815   }
816   
817   /* Set read buffer to 16k for effiecient reads */
818   setvbuf(fp, readbuf, _IOFBF, sizeof(readbuf));
819   
820   /* make sure it is only rw by the owner */
821   chmod(pfile, 0600);
822
823   /* Lock the smbpasswd file for write. */
824   if ((lockfd = pw_file_lock(fileno(fp), F_WRLCK, 5)) < 0) {
825     err = errno;
826     fprintf(stderr, "%s: Failed to lock password file %s.\n",
827             prog_name, pfile);
828     fclose(fp);
829     errno = err;
830     perror(prog_name);
831     exit(err);
832   }
833
834   /* Get the smb passwd entry for this user */
835   smb_pwent = _my_get_smbpwnam(fp, user_name, &valid_old_pwd, 
836                                &got_valid_nt_entry, &seekpos);
837   if (smb_pwent == NULL) {
838     if(add_user == False) {
839       fprintf(stderr, "%s: Failed to find entry for user %s in file %s.\n",
840               prog_name, pwd->pw_name, pfile);
841       fclose(fp);
842       pw_file_unlock(lockfd);
843       exit(1);
844     }
845
846     /* Create a new smb passwd entry and set it to the given password. */
847     {
848       int fd;
849       int new_entry_length;
850       char *new_entry;
851       long offpos;
852       uint16 acct_ctrl = (machine_account ? ACB_WSTRUST : ACB_NORMAL);
853
854       /* The add user write needs to be atomic - so get the fd from 
855          the fp and do a raw write() call.
856        */
857       fd = fileno(fp);
858
859       if((offpos = lseek(fd, 0, SEEK_END)) == -1) {
860         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
861 Error was %s\n", prog_name, user_name, pfile, strerror(errno));
862         fclose(fp);
863         pw_file_unlock(lockfd);
864         exit(1);
865       }
866
867       new_entry_length = strlen(user_name) + 1 + 15 + 1 + 
868                          32 + 1 + 32 + 1 + sizeof(fstring) + 
869                          1 + strlen(pwd->pw_dir) + 1 + 
870                          strlen(pwd->pw_shell) + 1;
871       if((new_entry = (char *)malloc( new_entry_length )) == 0) {
872         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
873 Error was %s\n", prog_name, pwd->pw_name, pfile, strerror(errno));
874         pw_file_unlock(lockfd);
875         fclose(fp);
876         exit(1);
877       }
878
879       sprintf(new_entry, "%s:%u:", pwd->pw_name, (unsigned)pwd->pw_uid);
880       p = &new_entry[strlen(new_entry)];
881       if(disable_user) {
882         memcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 32);
883         p += 32;
884         *p++ = ':';
885         memcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 32);
886       } else if (set_no_password) {
887         memcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 32);
888         p += 32;
889         *p++ = ':';
890         memcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 32);
891       } else {
892         for( i = 0; i < 16; i++)
893           sprintf(&p[i*2], "%02X", new_p16[i]);
894         p += 32;
895         *p++ = ':';
896         for( i = 0; i < 16; i++)
897           sprintf(&p[i*2], "%02X", new_nt_p16[i]);
898       }
899       p += 32;
900       *p++ = ':';
901       sprintf(p, "%s:%s:%s\n", encode_acct_ctrl(acct_ctrl),
902               pwd->pw_dir, pwd->pw_shell);
903       if(write(fd, new_entry, strlen(new_entry)) != strlen(new_entry)) {
904         fprintf(stderr, "%s: Failed to add entry for user %s to file %s. \
905 Error was %s\n", prog_name, pwd->pw_name, pfile, strerror(errno));
906         /* Remove the entry we just wrote. */
907         if(ftruncate(fd, offpos) == -1) {
908           fprintf(stderr, "%s: ERROR failed to ftruncate file %s. \
909 Error was %s. Password file may be corrupt ! Please examine by hand !\n", 
910                    prog_name, pwd->pw_name, strerror(errno));
911         }
912         pw_file_unlock(lockfd);
913         fclose(fp);
914         exit(1);
915       }
916       
917       pw_file_unlock(lockfd);  
918       fclose(fp);  
919       exit(0);
920     }
921   } else {
922           /* the entry already existed */
923           add_user = False;
924   }
925
926   /*
927    * We are root - just write the new password.
928    */
929
930   /* Create the 32 byte representation of the new p16 */
931   if(disable_user) {
932     memcpy(ascii_p16, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 32);
933   } else if (set_no_password) {
934     memcpy(ascii_p16, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 32);
935   } else {
936     for (i = 0; i < 16; i++) {
937       sprintf(&ascii_p16[i * 2], "%02X", (uchar) new_p16[i]);
938     }
939   }
940   if(got_valid_nt_entry) {
941     /* Add on the NT md4 hash */
942     ascii_p16[32] = ':';
943     if(disable_user) {
944       memcpy(&ascii_p16[33], "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 32);
945     } else if (set_no_password) {
946       memcpy(&ascii_p16[33], "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 32);
947     } else {
948       for (i = 0; i < 16; i++) {
949         sprintf(&ascii_p16[(i * 2)+33], "%02X", (uchar) new_nt_p16[i]);
950       }
951     }
952   }
953   /*
954    * Do an atomic write into the file at the position defined by
955    * seekpos.
956    */
957   pwfd = fileno(fp);
958   ret = lseek(pwfd, seekpos - 1, SEEK_SET);
959   if (ret != seekpos - 1) {
960     err = errno;
961     fprintf(stderr, "%s: seek fail on file %s.\n",
962             prog_name, pfile);
963     errno = err;
964     perror(prog_name);
965     pw_file_unlock(lockfd);
966     fclose(fp);
967     exit(1);
968   }
969   /* Sanity check - ensure the character is a ':' */
970   if (read(pwfd, &c, 1) != 1) {
971     err = errno;
972     fprintf(stderr, "%s: read fail on file %s.\n",
973             prog_name, pfile);
974     errno = err;
975     perror(prog_name);
976     pw_file_unlock(lockfd);
977     fclose(fp);
978     exit(1);
979   }
980   if (c != ':') {
981     fprintf(stderr, "%s: sanity check on passwd file %s failed.\n",
982             prog_name, pfile);
983     pw_file_unlock(lockfd);
984     fclose(fp);
985     exit(1);
986   }
987   writelen = (got_valid_nt_entry) ? 65 : 32;
988   if (write(pwfd, ascii_p16, writelen) != writelen) {
989     err = errno;
990     fprintf(stderr, "%s: write fail in file %s.\n",
991             prog_name, pfile);
992     errno = err;
993     perror(prog_name);
994     pw_file_unlock(lockfd);
995     fclose(fp);
996     exit(err);
997   }
998   pw_file_unlock(lockfd);
999   fclose(fp);
1000   if(disable_user)
1001     printf("User %s disabled.\n", user_name);
1002   else if (set_no_password)
1003     printf("User %s - set to no password.\n", user_name);
1004   else
1005     printf("Password changed for user %s.\n", user_name);
1006   return 0;
1007 }