merge from the autoconf2 branch to the main branch
[jra/samba/.git] / source3 / smbd / chgpasswd.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Samba utility functions
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 /* fork a child process to exec passwd and write to its
23 * tty to change a users password. This is running as the
24 * user who is attempting to change the password.
25 */
26
27 /* 
28  * This code was copied/borrowed and stolen from various sources.
29  * The primary source was the poppasswd.c from the authors of POPMail. This software
30  * was included as a client to change passwords using the 'passwd' program
31  * on the remote machine.
32  *
33  * This routine is called by set_user_password() in password.c only if ALLOW_PASSWORD_CHANGE
34  * is defined in the compiler directives located in the Makefile.
35  *
36  * This code has been hacked by Bob Nance (nance@niehs.nih.gov) and Evan Patterson
37  * (patters2@niehs.nih.gov) at the National Institute of Environmental Health Sciences
38  * and rights to modify, distribute or incorporate this change to the CAP suite or
39  * using it for any other reason are granted, so long as this disclaimer is left intact.
40  */
41
42 /*
43    This code was hacked considerably for inclusion in Samba, primarily
44    by Andrew.Tridgell@anu.edu.au. The biggest change was the addition
45    of the "password chat" option, which allows the easy runtime
46    specification of the expected sequence of events to change a
47    password.
48    */
49
50 #include "includes.h"
51
52 extern int DEBUGLEVEL;
53
54 #if ALLOW_CHANGE_PASSWORD
55 #define MINPASSWDLENGTH 5
56 #define BUFSIZE 512
57
58 static int findpty(char **slave)
59 {
60   int master;
61 #ifndef HAVE_GRANTPT
62   static fstring line;
63   void *dirp;
64   char *dpname;
65 #endif /* !HAVE_GRANTPT */
66   
67 #if defined(HAVE_GRANTPT)
68   if ((master = open("/dev/ptmx", O_RDWR)) >= 1) {
69     grantpt(master);
70     unlockpt(master);
71     *slave = ptsname(master);
72     if(*slave == NULL) {
73       DEBUG(0,("findpty: Unable to create master/slave pty pair.\n"));
74       return -1;
75     } else {
76       DEBUG(10, ("findpty: Allocated slave pty %s\n", *slave));
77       return (master);
78     }
79   }
80 #else /* HAVE_GRANTPT */
81   fstrcpy( line, "/dev/ptyXX" );
82
83   dirp = OpenDir(-1, "/dev", False);
84   if (!dirp) return(-1);
85   while ((dpname = ReadDirName(dirp)) != NULL) {
86     if (strncmp(dpname, "pty", 3) == 0 && strlen(dpname) == 5) {
87       DEBUG(3,("pty: try to open %s, line was %s\n", dpname, line ) );
88       line[8] = dpname[3];
89       line[9] = dpname[4];
90       if ((master = open(line, O_RDWR)) >= 0) {
91         DEBUG(3,("pty: opened %s\n", line ) );
92         line[5] = 't';
93         *slave = line;
94         CloseDir(dirp);
95         return (master);
96       }
97     }
98   }
99   CloseDir(dirp);
100 #endif /* HAVE_GRANTPT */
101   return (-1);
102 }
103
104 static int dochild(int master,char *slavedev, char *name, char *passwordprogram, BOOL as_root)
105 {
106   int slave;
107   struct termios stermios;
108   struct passwd *pass = Get_Pwnam(name,True);
109   int gid;
110   int uid;
111
112   if(pass == NULL) {
113     DEBUG(0,("dochild: user name %s doesn't exist in the UNIX password database.\n",
114               name));
115     return False;
116   }
117
118   gid = pass->pw_gid;
119   uid = pass->pw_uid;
120 #ifdef HAVE_SETRESUID
121   setresuid(0,0,0);
122 #else 
123   setuid(0);
124 #endif
125
126   /* Start new session - gets rid of controlling terminal. */
127   if (setsid() < 0) {
128     DEBUG(3,("Weirdness, couldn't let go of controlling terminal\n"));
129     return(False);
130   }
131
132   /* Open slave pty and acquire as new controlling terminal. */
133   if ((slave = open(slavedev, O_RDWR)) < 0) {
134     DEBUG(3,("More weirdness, could not open %s\n", 
135              slavedev));
136     return(False);
137   }
138 #ifdef I_PUSH
139   ioctl(slave, I_PUSH, "ptem");
140   ioctl(slave, I_PUSH, "ldterm");
141 #elif defined(TIOCSCTTY)
142   if (ioctl(slave,TIOCSCTTY,0) <0) {
143      DEBUG(3,("Error in ioctl call for slave pty\n"));
144      /* return(False); */
145   }
146 #endif 
147
148   /* Close master. */
149   close(master);
150
151   /* Make slave stdin/out/err of child. */
152
153   if (dup2(slave, STDIN_FILENO) != STDIN_FILENO) {
154     DEBUG(3,("Could not re-direct stdin\n"));
155     return(False);
156   }
157   if (dup2(slave, STDOUT_FILENO) != STDOUT_FILENO) {
158     DEBUG(3,("Could not re-direct stdout\n"));
159     return(False);
160   }
161   if (dup2(slave, STDERR_FILENO) != STDERR_FILENO) {
162     DEBUG(3,("Could not re-direct stderr\n"));
163     return(False);
164   }
165   if (slave > 2) close(slave);
166
167   /* Set proper terminal attributes - no echo, canonical input processing,
168      no map NL to CR/NL on output. */
169
170   if (tcgetattr(0, &stermios) < 0) {
171     DEBUG(3,("could not read default terminal attributes on pty\n"));
172     return(False);
173   }
174   stermios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
175   stermios.c_lflag |= ICANON;
176   stermios.c_oflag &= ~(ONLCR);
177   if (tcsetattr(0, TCSANOW, &stermios) < 0) {
178     DEBUG(3,("could not set attributes of pty\n"));
179     return(False);
180   }
181
182   /* make us completely into the right uid */
183   if(!as_root) {
184 #ifdef HAVE_SETRESUID
185           setresgid(0,0,0);
186           setresuid(0,0,0);
187           setresgid(gid,gid,gid);
188           setresuid(uid,uid,uid);      
189 #else      
190           setuid(0);
191           seteuid(0);
192           setgid(gid);
193           setegid(gid);
194           setuid(uid);
195           seteuid(uid);
196 #endif
197   }
198
199   DEBUG(10, ("Invoking '%s' as password change program.\n", passwordprogram));
200
201   /* execl() password-change application */
202   if (execl("/bin/sh","sh","-c",passwordprogram,NULL) < 0) {
203     DEBUG(3,("Bad status returned from %s\n",passwordprogram));
204     return(False);
205   }
206   return(True);
207 }
208
209 static int expect(int master,char *expected,char *buf)
210 {
211   int n, m;
212  
213   n = 0;
214   buf[0] = 0;
215   while (1) {
216     if (n >= BUFSIZE-1) {
217       return False;
218     }
219
220     /* allow 4 seconds for some output to appear */
221     m = read_with_timeout(master, buf+n, 1, BUFSIZE-1-n, 4000);
222     if (m < 0) 
223       return False;
224
225     n += m;
226     buf[n] = 0;
227
228     {
229       pstring s1,s2;
230       pstrcpy(s1,buf);
231       pstrcpy(s2,expected);
232       if (do_match(s1, s2, False))
233         return(True);
234     }
235   }
236 }
237
238 static void pwd_sub(char *buf)
239 {
240   string_sub(buf,"\\n","\n");
241   string_sub(buf,"\\r","\r");
242   string_sub(buf,"\\s"," ");
243   string_sub(buf,"\\t","\t");
244 }
245
246 static void writestring(int fd,char *s)
247 {
248   int l;
249   
250   l = strlen (s);
251   write (fd, s, l);
252 }
253
254
255 static int talktochild(int master, char *chatsequence)
256 {
257   char buf[BUFSIZE];
258   int count=0;
259   char *ptr=chatsequence;
260   fstring chatbuf;
261
262   *buf = 0;
263   sleep(1);
264
265   while (next_token(&ptr,chatbuf,NULL)) {
266     BOOL ok=True;
267     count++;
268     pwd_sub(chatbuf);
269     if (!strequal(chatbuf,"."))
270       ok = expect(master,chatbuf,buf);
271
272     if(lp_passwd_chat_debug())
273       DEBUG(100,("talktochild: chatbuf=[%s] responsebuf=[%s]\n",chatbuf,buf));
274
275     if (!ok) {
276       DEBUG(3,("response %d incorrect\n",count));
277       return(False);
278     }
279
280     if (!next_token(&ptr,chatbuf,NULL)) break;
281     pwd_sub(chatbuf);
282     if (!strequal(chatbuf,"."))
283       writestring(master,chatbuf);
284
285     if(lp_passwd_chat_debug())
286       DEBUG(100,("talktochild: sendbuf=[%s]\n",chatbuf));
287   }
288
289   if (count<1) return(False);
290
291   return (True);
292 }
293
294
295 BOOL chat_with_program(char *passwordprogram,char *name,char *chatsequence, BOOL as_root)
296 {
297   char *slavedev;
298   int master;
299   pid_t pid, wpid;
300   int wstat;
301   BOOL chstat = False;    
302
303   /* allocate a pseudo-terminal device */
304   if ((master = findpty (&slavedev)) < 0) {
305     DEBUG(3,("Cannot Allocate pty for password change: %s",name));
306     return(False);
307   }
308
309   if ((pid = fork()) < 0) {
310     DEBUG(3,("Cannot fork() child for password change: %s",name));
311     return(False);
312   }
313
314   /* we now have a pty */
315   if (pid > 0){                 /* This is the parent process */
316     if ((chstat = talktochild(master, chatsequence)) == False) {
317       DEBUG(3,("Child failed to change password: %s\n",name));
318       kill(pid, SIGKILL); /* be sure to end this process */
319     }
320     if ((wpid = sys_waitpid(pid, &wstat, 0)) < 0) {
321       DEBUG(3,("The process is no longer waiting!\n\n"));
322       return(False);
323     }
324     if (pid != wpid) {
325       DEBUG(3,("We were waiting for the wrong process ID\n"));  
326       return(False);
327     }
328     if (WIFEXITED(wstat) == 0) {
329       DEBUG(3,("The process exited while we were waiting\n"));
330       return(False);
331     }
332     if (WEXITSTATUS(wstat) != 0) {
333       DEBUG(3,("The status of the process exiting was %d\n", wstat));
334       return(False);
335     }
336     
337   } else {
338     /* CHILD */
339
340     /* make sure it doesn't freeze */
341     alarm(20);
342
343     if(as_root)
344       become_root(False);
345     DEBUG(3,("Dochild for user %s (uid=%d,gid=%d)\n",name,getuid(),getgid()));
346     chstat = dochild(master, slavedev, name, passwordprogram, as_root);
347
348     if(as_root)
349       unbecome_root(False);
350   }
351
352   if(chstat)
353     DEBUG(3,("Password change %ssuccessful for user %s\n", (chstat?"":"un"), name));
354   return (chstat);
355 }
356
357
358 BOOL chgpasswd(char *name,char *oldpass,char *newpass, BOOL as_root)
359 {
360   pstring passwordprogram;
361   pstring chatsequence;
362   int i;
363   int len;
364
365   strlower(name); 
366   DEBUG(3,("Password change for user: %s\n",name));
367
368 #if DEBUG_PASSWORD
369   DEBUG(100,("Passwords: old=%s new=%s\n",oldpass,newpass)); 
370 #endif
371
372   /* Take the passed information and test it for minimum criteria */
373   /* Minimum password length */
374   if (strlen(newpass) < MINPASSWDLENGTH) /* too short, must be at least MINPASSWDLENGTH */ 
375     {
376       DEBUG(2,("Password Change: %s, New password is shorter than MINPASSWDLENGTH\n",name));
377       return (False);           /* inform the user */
378     }
379   
380   /* Password is same as old password */
381   if (strcmp(oldpass,newpass) == 0) /* don't allow same password */
382     {
383       DEBUG(2,("Password Change: %s, New password is same as old\n",name)); /* log the attempt */
384       return (False);           /* inform the user */
385     }
386
387   pstrcpy(passwordprogram,lp_passwd_program());
388   pstrcpy(chatsequence,lp_passwd_chat());
389
390   if (!*chatsequence) {
391     DEBUG(2,("Null chat sequence - no password changing\n"));
392     return(False);
393   }
394
395   if (!*passwordprogram) {
396     DEBUG(2,("Null password program - no password changing\n"));
397     return(False);
398   }
399
400   /* 
401    * Check the old and new passwords don't contain any control
402    * characters.
403    */
404
405   len = strlen(oldpass); 
406   for(i = 0; i < len; i++) {
407     if(iscntrl(oldpass[i])) {
408       DEBUG(0,("chat_with_program: oldpass contains control characters (disallowed).\n"));
409       return False;
410     }
411   }
412
413   len = strlen(newpass);
414   for(i = 0; i < len; i++) {
415     if(iscntrl(newpass[i])) {
416       DEBUG(0,("chat_with_program: newpass contains control characters (disallowed).\n"));
417       return False;
418     }
419   }
420
421   string_sub(passwordprogram,"%u",name);
422   string_sub(passwordprogram,"%o",oldpass);
423   string_sub(passwordprogram,"%n",newpass);
424
425   string_sub(chatsequence,"%u",name);
426   string_sub(chatsequence,"%o",oldpass);
427   string_sub(chatsequence,"%n",newpass);
428   return(chat_with_program(passwordprogram,name,chatsequence, as_root));
429 }
430
431 #else /* ALLOW_CHANGE_PASSWORD */
432 BOOL chgpasswd(char *name,char *oldpass,char *newpass, BOOL as_root)
433 {
434   DEBUG(0,("Password changing not compiled in (user=%s)\n",name));
435   return(False);
436 }
437 #endif /* ALLOW_CHANGE_PASSWORD */
438
439 /***********************************************************
440  Code to check the lanman hashed password.
441 ************************************************************/
442
443 BOOL check_lanman_password(char *user, unsigned char *pass1, 
444                            unsigned char *pass2, struct smb_passwd **psmbpw)
445 {
446   unsigned char unenc_new_pw[16];
447   unsigned char unenc_old_pw[16];
448   unsigned char null_pw[16];
449   struct smb_passwd *smbpw;
450
451   *psmbpw = NULL;
452
453   become_root(0);
454   smbpw = getsmbpwnam(user);
455   unbecome_root(0);
456
457   if(smbpw == NULL)
458   {
459     DEBUG(0,("check_lanman_password: getsmbpwnam returned NULL\n"));
460     return False;
461   }
462
463   if(smbpw->acct_ctrl & ACB_DISABLED)
464   {
465     DEBUG(0,("check_lanman_password: account %s disabled.\n", user));
466     return False;
467   }
468
469   if((smbpw->smb_passwd == NULL) && (smbpw->acct_ctrl & ACB_PWNOTREQ))
470   {
471     unsigned char no_pw[14];
472     memset(no_pw, '\0', 14);
473     E_P16((uchar *)no_pw, (uchar *)null_pw);
474     smbpw->smb_passwd = null_pw;
475   } else if (smbpw->smb_passwd == NULL) {
476     DEBUG(0,("check_lanman_password: no lanman password !\n"));
477     return False;
478   }
479
480   /* Get the new lanman hash. */
481   D_P16(smbpw->smb_passwd, pass2, unenc_new_pw);
482
483   /* Use this to get the old lanman hash. */
484   D_P16(unenc_new_pw, pass1, unenc_old_pw);
485
486   /* Check that the two old passwords match. */
487   if(memcmp(smbpw->smb_passwd, unenc_old_pw, 16))
488   {
489     DEBUG(0,("check_lanman_password: old password doesn't match.\n"));
490     return False;
491   }
492
493   *psmbpw = smbpw;
494   return True;
495 }
496
497 /***********************************************************
498  Code to change the lanman hashed password.
499  It nulls out the NT hashed password as it will
500  no longer be valid.
501 ************************************************************/
502
503 BOOL change_lanman_password(struct smb_passwd *smbpw, unsigned char *pass1, unsigned char *pass2)
504 {
505   unsigned char unenc_new_pw[16];
506   unsigned char null_pw[16];
507   BOOL ret;
508
509   if(smbpw == NULL)
510   { 
511     DEBUG(0,("change_lanman_password: no smb password entry.\n"));
512     return False;
513   }
514
515   if(smbpw->acct_ctrl & ACB_DISABLED)
516   {
517     DEBUG(0,("change_lanman_password: account %s disabled.\n", smbpw->smb_name));
518     return False;
519   }
520
521   if((smbpw->smb_passwd == NULL) && (smbpw->acct_ctrl & ACB_PWNOTREQ))
522   {
523     unsigned char no_pw[14];
524     memset(no_pw, '\0', 14);
525     E_P16((uchar *)no_pw, (uchar *)null_pw);
526     smbpw->smb_passwd = null_pw;
527   } else if (smbpw->smb_passwd == NULL) {
528     DEBUG(0,("change_lanman_password: no lanman password !\n"));
529     return False;
530   }
531
532   /* Get the new lanman hash. */
533   D_P16(smbpw->smb_passwd, pass2, unenc_new_pw);
534
535   smbpw->smb_passwd = unenc_new_pw;
536   smbpw->smb_nt_passwd = NULL; /* We lose the NT hash. Sorry. */
537
538   /* Now write it into the file. */
539   become_root(0);
540   ret = mod_smbpwd_entry(smbpw,False);
541   unbecome_root(0);
542     
543   return ret;
544 }
545
546 /***********************************************************
547  Code to check the OEM hashed password.
548 ************************************************************/
549
550 BOOL check_oem_password(char *user, unsigned char *data,
551                         struct smb_passwd **psmbpw, char *new_passwd,
552                         int new_passwd_size)
553 {
554   struct smb_passwd *smbpw = NULL;
555   int new_pw_len;
556   fstring upper_case_new_passwd;
557   unsigned char new_p16[16];
558   unsigned char unenc_old_pw[16];
559   unsigned char null_pw[16];
560
561   become_root(0);
562   *psmbpw = smbpw = getsmbpwnam(user);
563   unbecome_root(0);
564
565   if(smbpw == NULL)
566   {
567     DEBUG(0,("check_oem_password: getsmbpwnam returned NULL\n"));
568     return False;
569   }
570
571   if(smbpw->acct_ctrl & ACB_DISABLED)
572   {
573     DEBUG(0,("check_lanman_password: account %s disabled.\n", user));
574     return False;
575   }
576
577   if((smbpw->smb_passwd == NULL) && (smbpw->acct_ctrl & ACB_PWNOTREQ))
578   {
579     unsigned char no_pw[14];
580     memset(no_pw, '\0', 14);
581     E_P16((uchar *)no_pw, (uchar *)null_pw);
582     smbpw->smb_passwd = null_pw;
583   } else if (smbpw->smb_passwd == NULL) {
584     DEBUG(0,("check_oem_password: no lanman password !\n"));
585     return False;
586   }
587
588   /* 
589    * Call the hash function to get the new password.
590    */
591   SamOEMhash( (unsigned char *)data, (unsigned char *)smbpw->smb_passwd, True);
592
593   /* 
594    * The length of the new password is in the last 4 bytes of
595    * the data buffer.
596    */
597   new_pw_len = IVAL(data,512);
598   if(new_pw_len < 0 || new_pw_len > new_passwd_size - 1) {
599     DEBUG(0,("check_oem_password: incorrect password length (%d).\n", new_pw_len));
600     return False;
601   }
602
603   memcpy(new_passwd, &data[512-new_pw_len], new_pw_len);
604   new_passwd[new_pw_len] = '\0';
605
606   /*
607    * To ensure we got the correct new password, hash it and
608    * use it as a key to test the passed old password.
609    */
610
611   memset(upper_case_new_passwd, '\0', sizeof(upper_case_new_passwd));
612   fstrcpy(upper_case_new_passwd, new_passwd);
613   strupper(upper_case_new_passwd);
614
615   E_P16((uchar *)upper_case_new_passwd, new_p16);
616
617   /*
618    * Now use new_p16 as the key to see if the old
619    * password matches.
620    */
621   D_P16(new_p16, &data[516], unenc_old_pw);
622
623   if(memcmp(smbpw->smb_passwd, unenc_old_pw, 16)) {
624     DEBUG(0,("check_oem_password: old password doesn't match.\n"));
625     return False;
626   }
627
628   memset(upper_case_new_passwd, '\0', strlen(upper_case_new_passwd));
629
630   return True;
631 }
632
633 /***********************************************************
634  Code to change the oem password. Changes both the lanman
635  and NT hashes.
636  override = False, normal
637  override = True, override XXXXXXXXXX'd password
638 ************************************************************/
639
640 BOOL change_oem_password(struct smb_passwd *smbpw, char *new_passwd, BOOL override)
641 {
642   int ret;
643   fstring upper_case_new_passwd;
644   unsigned char new_nt_p16[16];
645   unsigned char new_p16[16];
646
647   memset(upper_case_new_passwd, '\0', sizeof(upper_case_new_passwd));
648   fstrcpy(upper_case_new_passwd, new_passwd);
649   strupper(upper_case_new_passwd);
650
651   E_P16((uchar *)upper_case_new_passwd, new_p16);
652
653   smbpw->smb_passwd = new_p16;
654   
655   E_md4hash((uchar *) new_passwd, new_nt_p16);
656   smbpw->smb_nt_passwd = new_nt_p16;
657   
658   /* Now write it into the file. */
659   become_root(0);
660   ret = mod_smbpwd_entry(smbpw,override);
661   unbecome_root(0);
662
663   memset(upper_case_new_passwd, '\0', strlen(upper_case_new_passwd));
664   memset(new_passwd, '\0', strlen(new_passwd));
665
666   return ret;
667 }