includes.h: Added John's redhat fix for QSORT_CAST.
[kai/samba.git] / source3 / 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  Print command usage on stderr and die.
78 **********************************************************/
79
80 static void usage(char *name, BOOL is_root)
81 {
82         if(is_root)
83                 fprintf(stderr, "Usage is : %s [-D DEBUGLEVEL] [-a] [-d] [-m] [-n] [username] [password]\n\
84 %s: [-R <name resolve order>] [-D DEBUGLEVEL] [-r machine] [username] [password]\n%s: [-h]\n", name, name, name);
85         else
86                 fprintf(stderr, "Usage is : %s [-h] [-D DEBUGLEVEL] [-r machine] [password]\n", name);
87         exit(1);
88 }
89
90 /*********************************************************
91  Start here.
92 **********************************************************/
93
94 int main(int argc, char **argv)
95 {
96   extern char *optarg;
97   extern int optind;
98   extern int DEBUGLEVEL;
99   char *prog_name;
100   int             real_uid;
101   struct passwd  *pwd;
102   fstring         old_passwd;
103   fstring         new_passwd;
104   uchar           new_p16[16];
105   uchar           new_nt_p16[16];
106   char           *p;
107   struct smb_passwd *smb_pwent;
108   FILE           *fp;
109   int             ch;
110   int             err;
111   BOOL is_root = False;
112   pstring  user_name;
113   char *remote_machine = NULL;
114   BOOL           add_user = False;
115   BOOL           got_new_pass = False;
116   BOOL           machine_account = False;
117   BOOL           disable_user = False;
118   BOOL           set_no_password = False;
119   pstring servicesf = CONFIGFILE;
120   void           *vp;
121
122   new_passwd[0] = '\0';
123   user_name[0] = '\0';
124
125   memset(old_passwd, '\0', sizeof(old_passwd));
126   memset(new_passwd, '\0', sizeof(new_passwd));
127
128   prog_name = argv[0];
129
130   TimeInit();
131
132   setup_logging(prog_name,True);
133   
134   charset_initialise();
135
136   if (!lp_load(servicesf,True,False,False)) {
137     fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n", prog_name, servicesf);
138   }
139     
140   codepage_initialise(lp_client_code_page());
141
142   /* Get the real uid */
143   real_uid = getuid();
144   
145   /* Check the effective uid */
146   if ((geteuid() == 0) && (real_uid != 0)) {
147     fprintf(stderr, "%s: Must *NOT* be setuid root.\n", prog_name);
148     exit(1);
149   }
150
151   is_root = (real_uid == 0);
152
153   while ((ch = getopt(argc, argv, "adhmnr:R:D:")) != EOF) {
154     switch(ch) {
155     case 'a':
156       if(is_root)
157         add_user = True;
158       else
159         usage(prog_name, is_root);
160       break;
161     case 'd':
162       if(is_root) {
163         disable_user = True;
164         got_new_pass = True;
165         strcpy(new_passwd, "XXXXXX");
166       } else
167         usage(prog_name, is_root);
168       break;
169     case 'D':
170       DEBUGLEVEL = atoi(optarg);
171       break;
172     case 'n':
173       if(is_root) {
174         set_no_password = True;
175         got_new_pass = True;
176         strcpy(new_passwd, "NO PASSWORD");
177       } else
178         usage(prog_name, is_root);
179     case 'r':
180       remote_machine = optarg;
181       break;
182     case 'R':
183       if(is_root) {
184         lp_set_name_resolve_order(optarg);
185         break;
186       } else
187         usage(prog_name, is_root);
188     case 'm':
189       if(is_root) {
190         machine_account = True;
191       } else
192         usage(prog_name, is_root);
193       break;
194     case 'h':
195     default:
196       usage(prog_name, is_root);
197     }
198   }
199
200   argc -= optind;
201   argv += optind;
202
203   /*
204    * Ensure add_user and remote machine are
205    * not both set.
206    */
207   if(add_user && (remote_machine != NULL))
208     usage(prog_name, True);
209
210   if( is_root ) {
211
212     /*
213      * Deal with root - can add a user, but only locally.
214      */
215
216     switch(argc) {
217       case 0:
218         break;
219       case 1:
220         /* If we are root we can change another's password. */
221         pstrcpy(user_name, argv[0]);
222         break;
223       case 2:
224         pstrcpy(user_name, argv[0]);
225         fstrcpy(new_passwd, argv[1]);
226         got_new_pass = True;
227         break;
228       default:
229         usage(prog_name, True);
230     }
231
232     if(*user_name) {
233
234       if(machine_account) {
235         int username_len = strlen(user_name);
236         if(username_len >= sizeof(pstring) - 1) {
237           fprintf(stderr, "%s: machine account name too long.\n", user_name);
238           exit(1);
239         }
240
241         if(user_name[username_len-1] != '$') {
242           user_name[username_len] = '$';
243           user_name[username_len+1] = '\0';
244         }
245       }
246
247     /*
248      * Setup the pwd struct to point to known
249      * values for a machine account (it doesn't
250      * exist in /etc/passwd).
251      */
252       if((pwd = getpwnam(user_name)) == NULL) {
253         fprintf(stderr, "%s: User \"%s\" was not found in system password file.\n", 
254                     prog_name, user_name);
255         exit(1);
256       }
257     } else {
258       if((pwd = getpwuid(real_uid)) != NULL)
259         pstrcpy( user_name, pwd->pw_name);
260     }
261
262   } else {
263
264     if(add_user) {
265       fprintf(stderr, "%s: Only root can set anothers password.\n", prog_name);
266       usage(prog_name, False);
267     }
268
269     if(argc > 1)
270       usage(prog_name, False);
271
272     if(argc == 1) {
273       fstrcpy(new_passwd, argv[0]);
274       got_new_pass = True;
275     }
276
277     if((pwd = getpwuid(real_uid)) != NULL)
278       pstrcpy( user_name, pwd->pw_name);
279
280     /*
281      * A non-root user is always setting a password
282      * via a remote machine (even if that machine is
283      * localhost).
284      */
285
286     if(remote_machine == NULL)
287       remote_machine = "127.0.0.1";
288   }    
289     
290   if (*user_name == '\0') {
291     fprintf(stderr, "%s: Unable to get a user name for password change.\n", prog_name);
292     exit(1);
293   }
294
295   /*
296    * If we are adding a machine account then pretend
297    * we already have the new password, we will be using
298    * the machinename as the password.
299    */
300
301   if(add_user && machine_account) {
302     got_new_pass = True;
303     strncpy(new_passwd, user_name, sizeof(fstring));
304     new_passwd[sizeof(fstring)-1] = '\0';
305     strlower(new_passwd);
306     if(new_passwd[strlen(new_passwd)-1] == '$')
307       new_passwd[strlen(new_passwd)-1] = '\0';
308   }
309
310   /* 
311    * If we are root we don't ask for the old password (unless it's on a
312    * remote machine.
313    */
314
315   if (remote_machine != NULL) {
316     p = getpass("Old SMB password:");
317     fstrcpy(old_passwd, p);
318   }
319
320   if (!got_new_pass) {
321     new_passwd[0] = '\0';
322
323     p = getpass("New SMB password:");
324
325     strncpy(new_passwd, p, sizeof(fstring));
326     new_passwd[sizeof(fstring)-1] = '\0';
327
328     p = getpass("Retype new SMB password:");
329
330     if (strncmp(p, new_passwd, sizeof(fstring)-1))
331     {
332       fprintf(stderr, "%s: Mismatch - password unchanged.\n", prog_name);
333       exit(1);
334     }
335   }
336   
337   if (new_passwd[0] == '\0') {
338     printf("Password not set\n");
339     exit(0);
340   }
341  
342   /* 
343    * Now do things differently depending on if we're changing the
344    * password on a remote machine. Remember - a normal user is
345    * always using this code, looping back to the local smbd.
346    */
347
348   if(remote_machine != NULL) {
349     struct cli_state cli;
350     struct in_addr ip;
351     fstring myname;
352
353     if(get_myname(myname,NULL) == False) {
354       fprintf(stderr, "%s: unable to get my hostname.\n", prog_name );
355       exit(1);
356     }
357
358     if(!resolve_name( remote_machine, &ip)) {
359       fprintf(stderr, "%s: unable to find an IP address for machine %s.\n",
360               prog_name, remote_machine );
361       exit(1);
362     }
363  
364     memset(&cli, '\0', sizeof(struct cli_state));
365  
366     if (!cli_initialise(&cli) || !cli_connect(&cli, remote_machine, &ip)) {
367       fprintf(stderr, "%s: unable to connect to SMB server on machine %s. Error was : %s.\n",
368               prog_name, remote_machine, get_error_message(&cli) );
369       exit(1);
370     }
371   
372     if (!cli_session_request(&cli, remote_machine, 0x20, myname)) {
373       fprintf(stderr, "%s: machine %s rejected the session setup. Error was : %s.\n",
374               prog_name, remote_machine, get_error_message(&cli) );
375       cli_shutdown(&cli);
376       exit(1);
377     }
378   
379     cli.protocol = PROTOCOL_NT1;
380
381     if (!cli_negprot(&cli)) {
382       fprintf(stderr, "%s: machine %s rejected the negotiate protocol. Error was : %s.\n",        
383               prog_name, remote_machine, get_error_message(&cli) );
384       cli_shutdown(&cli);
385       exit(1);
386     }
387   
388     if (!cli_session_setup(&cli, user_name, old_passwd, strlen(old_passwd),
389                            "", 0, "")) {
390       fprintf(stderr, "%s: machine %s rejected the session setup. Error was : %s.\n",        
391               prog_name, remote_machine, get_error_message(&cli) );
392       cli_shutdown(&cli);
393       exit(1);
394     }               
395
396     if (!cli_send_tconX(&cli, "IPC$", "IPC", "", 1)) {
397       fprintf(stderr, "%s: machine %s rejected the tconX on the IPC$ share. Error was : %s.\n",
398               prog_name, remote_machine, get_error_message(&cli) );
399       cli_shutdown(&cli);
400       exit(1);
401     }
402
403     if(!cli_oem_change_password(&cli, user_name, new_passwd, old_passwd)) {
404       fprintf(stderr, "%s: machine %s rejected the password change: Error was : %s.\n",
405               prog_name, remote_machine, get_error_message(&cli) );
406       cli_shutdown(&cli);
407       exit(1);
408     }
409
410     cli_shutdown(&cli);
411     exit(0);
412   }
413
414   /*
415    * Check for a machine account.
416    */
417
418   if(machine_account && !pwd) {
419     fprintf(stderr, "%s: User %s does not exist in system password file \
420 (usually /etc/passwd). Cannot add machine account without a valid system user.\n",
421            prog_name, user_name);
422     exit(1);
423   }
424
425   /* Calculate the MD4 hash (NT compatible) of the new password. */
426   
427   memset(new_nt_p16, '\0', 16);
428   E_md4hash((uchar *) new_passwd, new_nt_p16);
429   
430   /* Mangle the password into Lanman format */
431   new_passwd[14] = '\0';
432   strupper(new_passwd);
433   
434   /*
435    * Calculate the SMB (lanman) hash functions of the new password.
436    */
437   
438   memset(new_p16, '\0', 16);
439   E_P16((uchar *) new_passwd, new_p16);
440   
441   /*
442    * Open the smbpaswd file.
443    */
444   vp = startsmbpwent(True);
445   if (!vp && errno == ENOENT) {
446           fp = fopen(lp_smb_passwd_file(), "w");
447           if (fp) {
448                   fprintf(fp, "# Samba SMB password file\n");
449                   fclose(fp);
450                   vp = startsmbpwent(True);
451           }
452   }
453   if (!fp) {
454           err = errno;
455           fprintf(stderr, "%s: Failed to open password file %s.\n",
456                   prog_name, lp_smb_passwd_file());
457           errno = err;
458           perror(prog_name);
459           exit(err);
460   }
461   
462   /* Get the smb passwd entry for this user */
463   smb_pwent = getsmbpwnam(user_name);
464   if (smb_pwent == NULL) {
465     if(add_user == False) {
466       fprintf(stderr, "%s: Failed to find entry for user %s.\n",
467               prog_name, pwd->pw_name);
468       endsmbpwent(vp);
469       exit(1);
470     }
471
472     /* Create a new smb passwd entry and set it to the given password. */
473     {
474       struct smb_passwd new_smb_pwent;
475
476       new_smb_pwent.smb_userid = pwd->pw_uid;
477       new_smb_pwent.smb_name = pwd->pw_name; 
478       new_smb_pwent.smb_passwd = NULL;
479       new_smb_pwent.smb_nt_passwd = NULL;
480       new_smb_pwent.acct_ctrl = (machine_account ? ACB_WSTRUST : ACB_NORMAL);
481
482       if(disable_user) {
483         new_smb_pwent.acct_ctrl |= ACB_DISABLED;
484       } else if (set_no_password) {
485         new_smb_pwent.acct_ctrl |= ACB_PWNOTREQ;
486       } else {
487         new_smb_pwent.smb_passwd = new_p16;
488         new_smb_pwent.smb_nt_passwd = new_nt_p16;
489       }
490
491       if(add_smbpwd_entry(&new_smb_pwent) == False) {
492         fprintf(stderr, "%s: Failed to add entry for user %s.\n", 
493                 prog_name, pwd->pw_name);
494         endsmbpwent(vp);
495         exit(1);
496       }
497       
498       endsmbpwent(vp);
499       printf("%s: Added user %s.\n", prog_name, user_name);
500       exit(0);
501     }
502   } else {
503           /* the entry already existed */
504           add_user = False;
505   }
506
507   /*
508    * We are root - just write the new password
509    * and the valid last change time.
510    */
511
512   if(disable_user) {
513     /*
514      * This currently won't work as it means changing
515      * the length of the record. JRA.
516      */
517     smb_pwent->acct_ctrl |= ACB_DISABLED;
518     smb_pwent->smb_passwd = NULL;
519     smb_pwent->smb_nt_passwd = NULL;
520   } else if (set_no_password) {
521     /*
522      * This currently won't work as it means changing
523      * the length of the record. JRA.
524      */
525     smb_pwent->acct_ctrl |= ACB_PWNOTREQ;
526     smb_pwent->smb_passwd = NULL;
527     smb_pwent->smb_nt_passwd = NULL; 
528   } else {
529     smb_pwent->smb_passwd = new_p16;
530     smb_pwent->smb_nt_passwd = new_nt_p16;
531   }
532
533   if(mod_smbpwd_entry(smb_pwent) == False) {
534     fprintf(stderr, "%s: Failed to modify entry for user %s.\n",
535             prog_name, pwd->pw_name);
536     endsmbpwent(vp);
537     exit(1);
538   }
539
540   endsmbpwent(vp);
541   if(disable_user)
542     printf("User %s disabled.\n", user_name);
543   else if (set_no_password)
544     printf("User %s - set to no password.\n", user_name);
545   else
546     printf("Password changed for user %s.\n", user_name);
547   return 0;
548 }