Convert pdbedit to use pdb_search_users
[kai/samba.git] / source3 / utils / pdbedit.c
1 /* 
2    Unix SMB/CIFS implementation.
3    passdb editing frontend
4    
5    Copyright (C) Simo Sorce      2000
6    Copyright (C) Andrew Bartlett 2001   
7    Copyright (C) Jelmer Vernooij 2002
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24
25 #define BIT_BACKEND     0x00000004
26 #define BIT_VERBOSE     0x00000008
27 #define BIT_SPSTYLE     0x00000010
28 #define BIT_CAN_CHANGE  0x00000020
29 #define BIT_MUST_CHANGE 0x00000040
30 #define BIT_USERSIDS    0x00000080
31 #define BIT_FULLNAME    0x00000100
32 #define BIT_HOMEDIR     0x00000200
33 #define BIT_HDIRDRIVE   0x00000400
34 #define BIT_LOGSCRIPT   0x00000800
35 #define BIT_PROFILE     0x00001000
36 #define BIT_MACHINE     0x00002000
37 #define BIT_USERDOMAIN  0x00004000
38 #define BIT_USER        0x00008000
39 #define BIT_LIST        0x00010000
40 #define BIT_MODIFY      0x00020000
41 #define BIT_CREATE      0x00040000
42 #define BIT_DELETE      0x00080000
43 #define BIT_ACCPOLICY   0x00100000
44 #define BIT_ACCPOLVAL   0x00200000
45 #define BIT_ACCTCTRL    0x00400000
46 #define BIT_RESERV_7    0x00800000
47 #define BIT_IMPORT      0x01000000
48 #define BIT_EXPORT      0x02000000
49 #define BIT_FIX_INIT    0x04000000
50 #define BIT_BADPWRESET  0x08000000
51 #define BIT_LOGONHOURS  0x10000000
52
53 #define MASK_ALWAYS_GOOD        0x0000001F
54 #define MASK_USER_GOOD          0x00405FE0
55
56 /*********************************************************
57  Add all currently available users to another db
58  ********************************************************/
59
60 static int export_database (struct pdb_methods *in, 
61                             struct pdb_methods *out, 
62                             const char *username) 
63 {
64         NTSTATUS status;
65         struct pdb_search *u_search;
66         struct samr_displayentry userentry;
67
68         DEBUG(3, ("export_database: username=\"%s\"\n", username ? username : "(NULL)"));
69
70         u_search = pdb_search_init(PDB_USER_SEARCH);
71         if (u_search == NULL) {
72                 DEBUG(0, ("pdb_search_init failed\n"));
73                 return 1;
74         }
75
76         if (!in->search_users(in, u_search, 0)) {
77                 DEBUG(0, ("Could not start searching users\n"));
78                 pdb_search_destroy(u_search);
79                 return 1;
80         }
81
82         while (u_search->next_entry(u_search, &userentry)) {
83                 struct samu *user;
84                 struct samu *account;
85                 DOM_SID user_sid;
86
87                 DEBUG(4, ("Processing account %s\n", userentry.account_name));
88
89                 if ((username != NULL)
90                     && (strcmp(username, userentry.account_name) != 0)) {
91                         /*
92                          * ignore unwanted users
93                          */
94                         continue;
95                 }
96
97                 user = samu_new(talloc_tos());
98                 if (user == NULL) {
99                         DEBUG(0, ("talloc failed\n"));
100                         break;
101                 }
102
103                 sid_compose(&user_sid, get_global_sam_sid(), userentry.rid);
104
105                 status = in->getsampwsid(in, user, &user_sid);
106
107                 if (!NT_STATUS_IS_OK(status)) {
108                         DEBUG(2, ("getsampwsid failed: %s\n",
109                                   nt_errstr(status)));
110                         TALLOC_FREE(user);
111                         continue;
112                 }
113
114                 account = samu_new(NULL);
115                 if (account == NULL) {
116                         fprintf(stderr, "export_database: Memory allocation "
117                                 "failure!\n");
118                         TALLOC_FREE( user );
119                         pdb_search_destroy(u_search);
120                         return 1;
121                 }
122
123                 printf("Importing account for %s...", user->username);
124                 status = out->getsampwnam(out, account, user->username);
125
126                 if (NT_STATUS_IS_OK(status)) {
127                         status = out->update_sam_account( out, user );
128                 } else {
129                         status = out->add_sam_account(out, user);
130                 }
131
132                 if ( NT_STATUS_IS_OK(status) ) {
133                         printf( "ok\n");
134                 } else {
135                         printf( "failed\n");
136                 }
137
138                 TALLOC_FREE( account );
139                 TALLOC_FREE( user );
140         }
141
142         pdb_search_destroy(u_search);
143
144         return 0;
145 }
146
147 /*********************************************************
148  Add all currently available group mappings to another db
149  ********************************************************/
150
151 static int export_groups (struct pdb_methods *in, struct pdb_methods *out) 
152 {
153         GROUP_MAP *maps = NULL;
154         size_t i, entries = 0;
155         NTSTATUS status;
156
157         status = in->enum_group_mapping(in, get_global_sam_sid(), 
158                         SID_NAME_DOM_GRP, &maps, &entries, False);
159
160         if ( NT_STATUS_IS_ERR(status) ) {
161                 fprintf(stderr, "Unable to enumerate group map entries.\n");
162                 return 1;
163         }
164
165         for (i=0; i<entries; i++) {
166                 out->add_group_mapping_entry(out, &(maps[i]));
167         }
168
169         SAFE_FREE( maps );
170
171         return 0;
172 }
173
174 /*********************************************************
175  Reset account policies to their default values and remove marker
176  ********************************************************/
177
178 static int reinit_account_policies (void) 
179 {
180         int i;
181
182         for (i=1; decode_account_policy_name(i) != NULL; i++) {
183                 uint32 policy_value;
184                 if (!account_policy_get_default(i, &policy_value)) {
185                         fprintf(stderr, "Can't get default account policy\n");
186                         return -1;
187                 }
188                 if (!account_policy_set(i, policy_value)) {
189                         fprintf(stderr, "Can't set account policy in tdb\n");
190                         return -1;
191                 }
192         }
193
194         return 0;
195 }
196
197
198 /*********************************************************
199  Add all currently available account policy from tdb to one backend
200  ********************************************************/
201
202 static int export_account_policies (struct pdb_methods *in, struct pdb_methods *out) 
203 {
204         int i;
205
206         for ( i=1; decode_account_policy_name(i) != NULL; i++ ) {
207                 uint32 policy_value;
208                 NTSTATUS status;
209
210                 status = in->get_account_policy(in, i, &policy_value);
211
212                 if ( NT_STATUS_IS_ERR(status) ) {
213                         fprintf(stderr, "Unable to get account policy from %s\n", in->name);
214                         return -1;
215                 }
216
217                 status = out->set_account_policy(out, i, policy_value);
218
219                 if ( NT_STATUS_IS_ERR(status) ) {
220                         fprintf(stderr, "Unable to migrate account policy to %s\n", out->name);
221                         return -1;
222                 }
223         }
224
225         return 0;
226 }
227
228
229 /*********************************************************
230  Print info from sam structure
231 **********************************************************/
232
233 static int print_sam_info (struct samu *sam_pwent, bool verbosity, bool smbpwdstyle)
234 {
235         uid_t uid;
236         time_t tmp;
237
238         /* TODO: chaeck if entry is a user or a workstation */
239         if (!sam_pwent) return -1;
240
241         if (verbosity) {
242                 char temp[44];
243                 const uint8 *hours;
244
245                 printf ("Unix username:        %s\n", pdb_get_username(sam_pwent));
246                 printf ("NT username:          %s\n", pdb_get_nt_username(sam_pwent));
247                 printf ("Account Flags:        %s\n", pdb_encode_acct_ctrl(pdb_get_acct_ctrl(sam_pwent), NEW_PW_FORMAT_SPACE_PADDED_LEN));
248                 printf ("User SID:             %s\n",
249                         sid_string_tos(pdb_get_user_sid(sam_pwent)));
250                 printf ("Primary Group SID:    %s\n",
251                         sid_string_tos(pdb_get_group_sid(sam_pwent)));
252                 printf ("Full Name:            %s\n", pdb_get_fullname(sam_pwent));
253                 printf ("Home Directory:       %s\n", pdb_get_homedir(sam_pwent));
254                 printf ("HomeDir Drive:        %s\n", pdb_get_dir_drive(sam_pwent));
255                 printf ("Logon Script:         %s\n", pdb_get_logon_script(sam_pwent));
256                 printf ("Profile Path:         %s\n", pdb_get_profile_path(sam_pwent));
257                 printf ("Domain:               %s\n", pdb_get_domain(sam_pwent));
258                 printf ("Account desc:         %s\n", pdb_get_acct_desc(sam_pwent));
259                 printf ("Workstations:         %s\n", pdb_get_workstations(sam_pwent));
260                 printf ("Munged dial:          %s\n", pdb_get_munged_dial(sam_pwent));
261
262                 tmp = pdb_get_logon_time(sam_pwent);
263                 printf ("Logon time:           %s\n", tmp ? http_timestring(tmp) : "0");
264
265                 tmp = pdb_get_logoff_time(sam_pwent);
266                 printf ("Logoff time:          %s\n", tmp ? http_timestring(tmp) : "0");
267
268                 tmp = pdb_get_kickoff_time(sam_pwent);
269                 printf ("Kickoff time:         %s\n", tmp ? http_timestring(tmp) : "0");
270
271                 tmp = pdb_get_pass_last_set_time(sam_pwent);
272                 printf ("Password last set:    %s\n", tmp ? http_timestring(tmp) : "0");
273
274                 tmp = pdb_get_pass_can_change_time(sam_pwent);
275                 printf ("Password can change:  %s\n", tmp ? http_timestring(tmp) : "0");
276
277                 tmp = pdb_get_pass_must_change_time(sam_pwent);
278                 printf ("Password must change: %s\n", tmp ? http_timestring(tmp) : "0");
279
280                 tmp = pdb_get_bad_password_time(sam_pwent);
281                 printf ("Last bad password   : %s\n", tmp ? http_timestring(tmp) : "0");
282                 printf ("Bad password count  : %d\n",
283                         pdb_get_bad_password_count(sam_pwent));
284
285                 hours = pdb_get_hours(sam_pwent);
286                 pdb_sethexhours(temp, hours);
287                 printf ("Logon hours         : %s\n", temp);
288
289         } else if (smbpwdstyle) {
290                 char lm_passwd[33];
291                 char nt_passwd[33];
292
293                 uid = nametouid(pdb_get_username(sam_pwent));
294                 pdb_sethexpwd(lm_passwd, pdb_get_lanman_passwd(sam_pwent), pdb_get_acct_ctrl(sam_pwent));
295                 pdb_sethexpwd(nt_passwd, pdb_get_nt_passwd(sam_pwent), pdb_get_acct_ctrl(sam_pwent));
296
297                 printf("%s:%lu:%s:%s:%s:LCT-%08X:\n",
298                        pdb_get_username(sam_pwent),
299                        (unsigned long)uid,
300                        lm_passwd,
301                        nt_passwd,
302                        pdb_encode_acct_ctrl(pdb_get_acct_ctrl(sam_pwent),NEW_PW_FORMAT_SPACE_PADDED_LEN),
303                        (uint32)convert_time_t_to_uint32(pdb_get_pass_last_set_time(sam_pwent)));
304         } else {
305                 uid = nametouid(pdb_get_username(sam_pwent));
306                 printf ("%s:%lu:%s\n", pdb_get_username(sam_pwent), (unsigned long)uid, 
307                         pdb_get_fullname(sam_pwent));
308         }
309
310         return 0;
311 }
312
313 /*********************************************************
314  Get an Print User Info
315 **********************************************************/
316
317 static int print_user_info (struct pdb_methods *in, const char *username, bool verbosity, bool smbpwdstyle)
318 {
319         struct samu *sam_pwent=NULL;
320         bool ret;
321
322         if ( (sam_pwent = samu_new( NULL )) == NULL ) {
323                 return -1;
324         }
325
326         ret = NT_STATUS_IS_OK(in->getsampwnam (in, sam_pwent, username));
327
328         if (ret==False) {
329                 fprintf (stderr, "Username not found!\n");
330                 TALLOC_FREE(sam_pwent);
331                 return -1;
332         }
333
334         ret=print_sam_info (sam_pwent, verbosity, smbpwdstyle);
335         TALLOC_FREE(sam_pwent);
336         
337         return ret;
338 }
339         
340 /*********************************************************
341  List Users
342 **********************************************************/
343 static int print_users_list (struct pdb_methods *in, bool verbosity, bool smbpwdstyle)
344 {
345         struct pdb_search *u_search;
346         struct samr_displayentry userentry;
347
348         u_search = pdb_search_init(PDB_USER_SEARCH);
349         if (u_search == NULL) {
350                 DEBUG(0, ("pdb_search_init failed\n"));
351                 return 1;
352         }
353
354         if (!in->search_users(in, u_search, 0)) {
355                 DEBUG(0, ("Could not start searching users\n"));
356                 pdb_search_destroy(u_search);
357                 return 1;
358         }
359
360         while (u_search->next_entry(u_search, &userentry)) {
361                 struct samu *sam_pwent;
362                 DOM_SID user_sid;
363                 NTSTATUS status;
364
365                 sam_pwent = samu_new(talloc_tos());
366                 if (sam_pwent == NULL) {
367                         DEBUG(0, ("talloc failed\n"));
368                         break;
369                 }
370
371                 sid_compose(&user_sid, get_global_sam_sid(), userentry.rid);
372
373                 status = in->getsampwsid(in, sam_pwent, &user_sid);
374
375                 if (!NT_STATUS_IS_OK(status)) {
376                         DEBUG(2, ("getsampwsid failed: %s\n",
377                                   nt_errstr(status)));
378                         TALLOC_FREE(sam_pwent);
379                         continue;
380                 }
381
382                 if (verbosity)
383                         printf ("---------------\n");
384                 print_sam_info (sam_pwent, verbosity, smbpwdstyle);
385                 TALLOC_FREE(sam_pwent);
386         }
387         pdb_search_destroy(u_search);
388
389         return 0;
390 }
391
392 /*********************************************************
393  Fix a list of Users for uninitialised passwords
394 **********************************************************/
395 static int fix_users_list (struct pdb_methods *in)
396 {
397         struct pdb_search *u_search;
398         struct samr_displayentry userentry;
399
400         u_search = pdb_search_init(PDB_USER_SEARCH);
401         if (u_search == NULL) {
402                 DEBUG(0, ("pdb_search_init failed\n"));
403                 return 1;
404         }
405
406         if (!in->search_users(in, u_search, 0)) {
407                 DEBUG(0, ("Could not start searching users\n"));
408                 pdb_search_destroy(u_search);
409                 return 1;
410         }
411
412         while (u_search->next_entry(u_search, &userentry)) {
413                 struct samu *sam_pwent;
414                 DOM_SID user_sid;
415                 NTSTATUS status;
416
417                 sam_pwent = samu_new(talloc_tos());
418                 if (sam_pwent == NULL) {
419                         DEBUG(0, ("talloc failed\n"));
420                         break;
421                 }
422
423                 sid_compose(&user_sid, get_global_sam_sid(), userentry.rid);
424
425                 status = in->getsampwsid(in, sam_pwent, &user_sid);
426
427                 if (!NT_STATUS_IS_OK(status)) {
428                         DEBUG(2, ("getsampwsid failed: %s\n",
429                                   nt_errstr(status)));
430                         TALLOC_FREE(sam_pwent);
431                         continue;
432                 }
433
434                 if (!NT_STATUS_IS_OK(pdb_update_sam_account(sam_pwent))) {
435                         printf("Update of user %s failed!\n",
436                                pdb_get_username(sam_pwent));
437                 }
438                 TALLOC_FREE(sam_pwent);
439         }
440         pdb_search_destroy(u_search);
441         return 0;
442 }
443
444 /*********************************************************
445  Set User Info
446 **********************************************************/
447
448 static int set_user_info (struct pdb_methods *in, const char *username, 
449                           const char *fullname, const char *homedir, 
450                           const char *acct_desc, 
451                           const char *drive, const char *script, 
452                           const char *profile, const char *account_control,
453                           const char *user_sid, const char *user_domain,
454                           const bool badpw, const bool hours)
455 {
456         bool updated_autolock = False, updated_badpw = False;
457         struct samu *sam_pwent=NULL;
458         bool ret;
459         
460         if ( (sam_pwent = samu_new( NULL )) == NULL ) {
461                 return 1;
462         }
463         
464         ret = NT_STATUS_IS_OK(in->getsampwnam (in, sam_pwent, username));
465         if (ret==False) {
466                 fprintf (stderr, "Username not found!\n");
467                 TALLOC_FREE(sam_pwent);
468                 return -1;
469         }
470
471         if (hours) {
472                 uint8 hours_array[MAX_HOURS_LEN];
473                 uint32 hours_len;
474                 
475                 hours_len = pdb_get_hours_len(sam_pwent);
476                 memset(hours_array, 0xff, hours_len);
477                 
478                 pdb_set_hours(sam_pwent, hours_array, PDB_CHANGED);
479         }
480
481         if (!pdb_update_autolock_flag(sam_pwent, &updated_autolock)) {
482                 DEBUG(2,("pdb_update_autolock_flag failed.\n"));
483         }
484
485         if (!pdb_update_bad_password_count(sam_pwent, &updated_badpw)) {
486                 DEBUG(2,("pdb_update_bad_password_count failed.\n"));
487         }
488
489         if (fullname)
490                 pdb_set_fullname(sam_pwent, fullname, PDB_CHANGED);
491         if (acct_desc)
492                 pdb_set_acct_desc(sam_pwent, acct_desc, PDB_CHANGED);
493         if (homedir)
494                 pdb_set_homedir(sam_pwent, homedir, PDB_CHANGED);
495         if (drive)
496                 pdb_set_dir_drive(sam_pwent,drive, PDB_CHANGED);
497         if (script)
498                 pdb_set_logon_script(sam_pwent, script, PDB_CHANGED);
499         if (profile)
500                 pdb_set_profile_path (sam_pwent, profile, PDB_CHANGED);
501         if (user_domain)
502                 pdb_set_domain(sam_pwent, user_domain, PDB_CHANGED);
503
504         if (account_control) {
505                 uint32 not_settable = ~(ACB_DISABLED|ACB_HOMDIRREQ|ACB_PWNOTREQ|
506                                         ACB_PWNOEXP|ACB_AUTOLOCK);
507
508                 uint32 newflag = pdb_decode_acct_ctrl(account_control);
509
510                 if (newflag & not_settable) {
511                         fprintf(stderr, "Can only set [NDHLX] flags\n");
512                         TALLOC_FREE(sam_pwent);
513                         return -1;
514                 }
515
516                 pdb_set_acct_ctrl(sam_pwent,
517                                   (pdb_get_acct_ctrl(sam_pwent) & not_settable) | newflag,
518                                   PDB_CHANGED);
519         }
520         if (user_sid) {
521                 DOM_SID u_sid;
522                 if (!string_to_sid(&u_sid, user_sid)) {
523                         /* not a complete sid, may be a RID, try building a SID */
524                         int u_rid;
525                         
526                         if (sscanf(user_sid, "%d", &u_rid) != 1) {
527                                 fprintf(stderr, "Error passed string is not a complete user SID or RID!\n");
528                                 return -1;
529                         }
530                         sid_copy(&u_sid, get_global_sam_sid());
531                         sid_append_rid(&u_sid, u_rid);
532                 }
533                 pdb_set_user_sid (sam_pwent, &u_sid, PDB_CHANGED);
534         }
535
536         if (badpw) {
537                 pdb_set_bad_password_count(sam_pwent, 0, PDB_CHANGED);
538                 pdb_set_bad_password_time(sam_pwent, 0, PDB_CHANGED);
539         }
540
541         if (NT_STATUS_IS_OK(in->update_sam_account (in, sam_pwent)))
542                 print_user_info (in, username, True, False);
543         else {
544                 fprintf (stderr, "Unable to modify entry!\n");
545                 TALLOC_FREE(sam_pwent);
546                 return -1;
547         }
548         TALLOC_FREE(sam_pwent);
549         return 0;
550 }
551
552 /*********************************************************
553  Add New User
554 **********************************************************/
555 static int new_user (struct pdb_methods *in, const char *username,
556                         const char *fullname, const char *homedir,
557                         const char *drive, const char *script,
558                         const char *profile, char *user_sid, bool stdin_get)
559 {
560         struct samu *sam_pwent;
561         char *password1, *password2;
562         int rc_pwd_cmp;
563         struct passwd *pwd;
564
565         get_global_sam_sid();
566
567         if ( !(pwd = getpwnam_alloc( NULL, username )) ) {
568                 DEBUG(0,("Cannot locate Unix account for %s\n", username));
569                 return -1;
570         }
571
572         if ( (sam_pwent = samu_new( NULL )) == NULL ) {
573                 DEBUG(0, ("Memory allocation failure!\n"));
574                 return -1;
575         }
576
577         if (!NT_STATUS_IS_OK(samu_alloc_rid_unix(sam_pwent, pwd ))) {
578                 TALLOC_FREE( sam_pwent );
579                 TALLOC_FREE( pwd );
580                 DEBUG(0, ("could not create account to add new user %s\n", username));
581                 return -1;
582         }
583
584         password1 = get_pass( "new password:", stdin_get);
585         password2 = get_pass( "retype new password:", stdin_get);
586         if ((rc_pwd_cmp = strcmp (password1, password2))) {
587                 fprintf (stderr, "Passwords do not match!\n");
588                 TALLOC_FREE(sam_pwent);
589         } else {
590                 pdb_set_plaintext_passwd(sam_pwent, password1);
591         }
592
593         memset(password1, 0, strlen(password1));
594         SAFE_FREE(password1);
595         memset(password2, 0, strlen(password2));
596         SAFE_FREE(password2);
597
598         /* pwds do _not_ match? */
599         if (rc_pwd_cmp)
600                 return -1;
601
602         if (fullname)
603                 pdb_set_fullname(sam_pwent, fullname, PDB_CHANGED);
604         if (homedir)
605                 pdb_set_homedir (sam_pwent, homedir, PDB_CHANGED);
606         if (drive)
607                 pdb_set_dir_drive (sam_pwent, drive, PDB_CHANGED);
608         if (script)
609                 pdb_set_logon_script(sam_pwent, script, PDB_CHANGED);
610         if (profile)
611                 pdb_set_profile_path (sam_pwent, profile, PDB_CHANGED);
612         if (user_sid) {
613                 DOM_SID u_sid;
614                 if (!string_to_sid(&u_sid, user_sid)) {
615                         /* not a complete sid, may be a RID, try building a SID */
616                         int u_rid;
617                         
618                         if (sscanf(user_sid, "%d", &u_rid) != 1) {
619                                 fprintf(stderr, "Error passed string is not a complete user SID or RID!\n");
620                                 TALLOC_FREE(sam_pwent);
621                                 return -1;
622                         }
623                         sid_copy(&u_sid, get_global_sam_sid());
624                         sid_append_rid(&u_sid, u_rid);
625                 }
626                 pdb_set_user_sid (sam_pwent, &u_sid, PDB_CHANGED);
627         }
628         
629         pdb_set_acct_ctrl (sam_pwent, ACB_NORMAL, PDB_CHANGED);
630         
631         if (NT_STATUS_IS_OK(in->add_sam_account (in, sam_pwent))) { 
632                 print_user_info (in, username, True, False);
633         } else {
634                 fprintf (stderr, "Unable to add user! (does it already exist?)\n");
635                 TALLOC_FREE(sam_pwent);
636                 return -1;
637         }
638         TALLOC_FREE(sam_pwent);
639         return 0;
640 }
641
642 /*********************************************************
643  Add New Machine
644 **********************************************************/
645
646 static int new_machine (struct pdb_methods *in, const char *machine_in)
647 {
648         struct samu *sam_pwent=NULL;
649         fstring machinename;
650         fstring machineaccount;
651         struct passwd  *pwd = NULL;
652         
653         get_global_sam_sid();
654
655         if (strlen(machine_in) == 0) {
656                 fprintf(stderr, "No machine name given\n");
657                 return -1;
658         }
659
660         fstrcpy(machinename, machine_in); 
661         machinename[15]= '\0';
662
663         if (machinename[strlen (machinename) -1] == '$')
664                 machinename[strlen (machinename) -1] = '\0';
665         
666         strlower_m(machinename);
667         
668         fstrcpy(machineaccount, machinename);
669         fstrcat(machineaccount, "$");
670
671         if ( !(pwd = getpwnam_alloc( NULL, machineaccount )) ) {
672                 DEBUG(0,("Cannot locate Unix account for %s\n", machineaccount));
673                 return -1;
674         }
675
676         if ( (sam_pwent = samu_new( NULL )) == NULL ) {
677                 fprintf(stderr, "Memory allocation error!\n");
678                 TALLOC_FREE(pwd);
679                 return -1;
680         }
681
682         if ( !NT_STATUS_IS_OK(samu_alloc_rid_unix(sam_pwent, pwd )) ) {
683                 fprintf(stderr, "Could not init sam from pw\n");
684                 TALLOC_FREE(pwd);
685                 return -1;
686         }
687
688         TALLOC_FREE(pwd);
689
690         pdb_set_plaintext_passwd (sam_pwent, machinename);
691         pdb_set_username (sam_pwent, machineaccount, PDB_CHANGED);      
692         pdb_set_acct_ctrl (sam_pwent, ACB_WSTRUST, PDB_CHANGED);
693         
694         if (NT_STATUS_IS_OK(in->add_sam_account (in, sam_pwent))) {
695                 print_user_info (in, machineaccount, True, False);
696         } else {
697                 fprintf (stderr, "Unable to add machine! (does it already exist?)\n");
698                 TALLOC_FREE(sam_pwent);
699                 return -1;
700         }
701         TALLOC_FREE(sam_pwent);
702         return 0;
703 }
704
705 /*********************************************************
706  Delete user entry
707 **********************************************************/
708
709 static int delete_user_entry (struct pdb_methods *in, const char *username)
710 {
711         struct samu *samaccount = NULL;
712
713         if ( (samaccount = samu_new( NULL )) == NULL ) {
714                 return -1;
715         }
716
717         if (!NT_STATUS_IS_OK(in->getsampwnam(in, samaccount, username))) {
718                 fprintf (stderr, "user %s does not exist in the passdb\n", username);
719                 return -1;
720         }
721
722         if (!NT_STATUS_IS_OK(in->delete_sam_account (in, samaccount))) {
723                 fprintf (stderr, "Unable to delete user %s\n", username);
724                 return -1;
725         }
726         return 0;
727 }
728
729 /*********************************************************
730  Delete machine entry
731 **********************************************************/
732
733 static int delete_machine_entry (struct pdb_methods *in, const char *machinename)
734 {
735         fstring name;
736         struct samu *samaccount = NULL;
737
738         if (strlen(machinename) == 0) {
739                 fprintf(stderr, "No machine name given\n");
740                 return -1;
741         }
742         
743         fstrcpy(name, machinename);
744         name[15] = '\0';
745         if (name[strlen(name)-1] != '$')
746                 fstrcat (name, "$");
747
748         if ( (samaccount = samu_new( NULL )) == NULL ) {
749                 return -1;
750         }
751
752         if (!NT_STATUS_IS_OK(in->getsampwnam(in, samaccount, name))) {
753                 fprintf (stderr, "machine %s does not exist in the passdb\n", name);
754                 return -1;
755         }
756
757         if (!NT_STATUS_IS_OK(in->delete_sam_account (in, samaccount))) {
758                 fprintf (stderr, "Unable to delete machine %s\n", name);
759                 return -1;
760         }
761
762         return 0;
763 }
764
765 /*********************************************************
766  Start here.
767 **********************************************************/
768
769 int main (int argc, char **argv)
770 {
771         static int list_users = False;
772         static int verbose = False;
773         static int spstyle = False;
774         static int machine = False;
775         static int add_user = False;
776         static int delete_user = False;
777         static int modify_user = False;
778         uint32  setparms, checkparms;
779         int opt;
780         static char *full_name = NULL;
781         static char *acct_desc = NULL;
782         static const char *user_name = NULL;
783         static char *home_dir = NULL;
784         static char *home_drive = NULL;
785         static char *backend = NULL;
786         static char *backend_in = NULL;
787         static char *backend_out = NULL;
788         static int transfer_groups = False;
789         static int transfer_account_policies = False;
790         static int reset_account_policies = False;
791         static int  force_initialised_password = False;
792         static char *logon_script = NULL;
793         static char *profile_path = NULL;
794         static char *user_domain = NULL;
795         static char *account_control = NULL;
796         static char *account_policy = NULL;
797         static char *user_sid = NULL;
798         static long int account_policy_value = 0;
799         bool account_policy_value_set = False;
800         static int badpw_reset = False;
801         static int hours_reset = False;
802         static char *pwd_time_format = NULL;
803         static int pw_from_stdin = False;
804         struct pdb_methods *bin, *bout, *bdef;
805         char *configfile = NULL;
806         TALLOC_CTX *frame = talloc_stackframe();
807         poptContext pc;
808         struct poptOption long_options[] = {
809                 POPT_AUTOHELP
810                 {"list",        'L', POPT_ARG_NONE, &list_users, 0, "list all users", NULL},
811                 {"verbose",     'v', POPT_ARG_NONE, &verbose, 0, "be verbose", NULL },
812                 {"smbpasswd-style",     'w',POPT_ARG_NONE, &spstyle, 0, "give output in smbpasswd style", NULL},
813                 {"user",        'u', POPT_ARG_STRING, &user_name, 0, "use username", "USER" },
814                 {"account-desc",        'N', POPT_ARG_STRING, &acct_desc, 0, "set account description", NULL},
815                 {"fullname",    'f', POPT_ARG_STRING, &full_name, 0, "set full name", NULL},
816                 {"homedir",     'h', POPT_ARG_STRING, &home_dir, 0, "set home directory", NULL},
817                 {"drive",       'D', POPT_ARG_STRING, &home_drive, 0, "set home drive", NULL},
818                 {"script",      'S', POPT_ARG_STRING, &logon_script, 0, "set logon script", NULL},
819                 {"profile",     'p', POPT_ARG_STRING, &profile_path, 0, "set profile path", NULL},
820                 {"domain",      'I', POPT_ARG_STRING, &user_domain, 0, "set a users' domain", NULL},
821                 {"user SID",    'U', POPT_ARG_STRING, &user_sid, 0, "set user SID or RID", NULL},
822                 {"create",      'a', POPT_ARG_NONE, &add_user, 0, "create user", NULL},
823                 {"modify",      'r', POPT_ARG_NONE, &modify_user, 0, "modify user", NULL},
824                 {"machine",     'm', POPT_ARG_NONE, &machine, 0, "account is a machine account", NULL},
825                 {"delete",      'x', POPT_ARG_NONE, &delete_user, 0, "delete user", NULL},
826                 {"backend",     'b', POPT_ARG_STRING, &backend, 0, "use different passdb backend as default backend", NULL},
827                 {"import",      'i', POPT_ARG_STRING, &backend_in, 0, "import user accounts from this backend", NULL},
828                 {"export",      'e', POPT_ARG_STRING, &backend_out, 0, "export user accounts to this backend", NULL},
829                 {"group",       'g', POPT_ARG_NONE, &transfer_groups, 0, "use -i and -e for groups", NULL},
830                 {"policies",    'y', POPT_ARG_NONE, &transfer_account_policies, 0, "use -i and -e to move account policies between backends", NULL},
831                 {"policies-reset",      0, POPT_ARG_NONE, &reset_account_policies, 0, "restore default policies", NULL},
832                 {"account-policy",      'P', POPT_ARG_STRING, &account_policy, 0,"value of an account policy (like maximum password age)",NULL},
833                 {"value",       'C', POPT_ARG_LONG, &account_policy_value, 'C',"set the account policy to this value", NULL},
834                 {"account-control",     'c', POPT_ARG_STRING, &account_control, 0, "Values of account control", NULL},
835                 {"force-initialized-passwords", 0, POPT_ARG_NONE, &force_initialised_password, 0, "Force initialization of corrupt password strings in a passdb backend", NULL},
836                 {"bad-password-count-reset", 'z', POPT_ARG_NONE, &badpw_reset, 0, "reset bad password count", NULL},
837                 {"logon-hours-reset", 'Z', POPT_ARG_NONE, &hours_reset, 0, "reset logon hours", NULL},
838                 {"time-format", 0, POPT_ARG_STRING, &pwd_time_format, 0, "The time format for time parameters", NULL },
839                 {"password-from-stdin", 't', POPT_ARG_NONE, &pw_from_stdin, 0, "get password from standard in", NULL},
840                 POPT_COMMON_SAMBA
841                 POPT_TABLEEND
842         };
843         
844         /* we shouldn't have silly checks like this */
845         if (getuid() != 0) {
846                 d_fprintf(stderr, "You must be root to use pdbedit\n");
847                 TALLOC_FREE(frame);
848                 return -1;
849         }
850         
851         bin = bout = bdef = NULL;
852
853         load_case_tables();
854
855         setup_logging("pdbedit", True);
856         
857         pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
858                             POPT_CONTEXT_KEEP_FIRST);
859         
860         while((opt = poptGetNextOpt(pc)) != -1) {
861                 switch (opt) {
862                 case 'C':
863                         account_policy_value_set = True;
864                         break;
865                 case 's':
866                         configfile = optarg;
867                         break;
868                 }
869         }
870
871         poptGetArg(pc); /* Drop argv[0], the program name */
872
873         if (user_name == NULL)
874                 user_name = poptGetArg(pc);
875
876         if (!lp_load(get_dyn_CONFIGFILE(),True,False,False,True)) {
877                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", get_dyn_CONFIGFILE());
878                 exit(1);
879         }
880
881         if(!initialize_password_db(False, NULL))
882                 exit(1);
883
884         if (!init_names())
885                 exit(1);
886
887         setparms =      (backend ? BIT_BACKEND : 0) +
888                         (verbose ? BIT_VERBOSE : 0) +
889                         (spstyle ? BIT_SPSTYLE : 0) +
890                         (full_name ? BIT_FULLNAME : 0) +
891                         (home_dir ? BIT_HOMEDIR : 0) +
892                         (home_drive ? BIT_HDIRDRIVE : 0) +
893                         (logon_script ? BIT_LOGSCRIPT : 0) +
894                         (profile_path ? BIT_PROFILE : 0) +
895                         (user_domain ? BIT_USERDOMAIN : 0) +
896                         (machine ? BIT_MACHINE : 0) +
897                         (user_name ? BIT_USER : 0) +
898                         (list_users ? BIT_LIST : 0) +
899                         (force_initialised_password ? BIT_FIX_INIT : 0) +
900                         (user_sid ? BIT_USERSIDS : 0) +
901                         (modify_user ? BIT_MODIFY : 0) +
902                         (add_user ? BIT_CREATE : 0) +
903                         (delete_user ? BIT_DELETE : 0) +
904                         (account_control ? BIT_ACCTCTRL : 0) +
905                         (account_policy ? BIT_ACCPOLICY : 0) +
906                         (account_policy_value_set ? BIT_ACCPOLVAL : 0) +
907                         (backend_in ? BIT_IMPORT : 0) +
908                         (backend_out ? BIT_EXPORT : 0) +
909                         (badpw_reset ? BIT_BADPWRESET : 0) +
910                         (hours_reset ? BIT_LOGONHOURS : 0);
911
912         if (setparms & BIT_BACKEND) {
913                 if (!NT_STATUS_IS_OK(make_pdb_method_name( &bdef, backend ))) {
914                         fprintf(stderr, "Can't initialize passdb backend.\n");
915                         return 1;
916                 }
917         } else {
918                 if (!NT_STATUS_IS_OK(make_pdb_method_name(&bdef, lp_passdb_backend()))) {
919                         fprintf(stderr, "Can't initialize passdb backend.\n");
920                         return 1;
921                 }
922         }
923         
924         /* the lowest bit options are always accepted */
925         checkparms = setparms & ~MASK_ALWAYS_GOOD;
926
927         if (checkparms & BIT_FIX_INIT) {
928                 return fix_users_list(bdef);
929         }
930
931         /* account policy operations */
932         if ((checkparms & BIT_ACCPOLICY) && !(checkparms & ~(BIT_ACCPOLICY + BIT_ACCPOLVAL))) {
933                 uint32 value;
934                 int field = account_policy_name_to_fieldnum(account_policy);
935                 if (field == 0) {
936                         const char **names;
937                         int count;
938                         int i;
939                         account_policy_names_list(&names, &count);
940                         fprintf(stderr, "No account policy by that name!\n");
941                         if (count !=0) {
942                                 fprintf(stderr, "Account policy names are:\n");
943                                 for (i = 0; i < count ; i++) {
944                                         d_fprintf(stderr, "%s\n", names[i]);
945                                 }
946                         }
947                         SAFE_FREE(names);
948                         exit(1);
949                 }
950                 if (!pdb_get_account_policy(field, &value)) {
951                         fprintf(stderr, "valid account policy, but unable to fetch value!\n");
952                         if (!account_policy_value_set)
953                                 exit(1);
954                 }
955                 printf("account policy \"%s\" description: %s\n", account_policy, account_policy_get_desc(field));
956                 if (account_policy_value_set) {
957                         printf("account policy \"%s\" value was: %u\n", account_policy, value);
958                         if (!pdb_set_account_policy(field, account_policy_value)) {
959                                 fprintf(stderr, "valid account policy, but unable to set value!\n");
960                                 exit(1);
961                         }
962                         printf("account policy \"%s\" value is now: %lu\n", account_policy, account_policy_value);
963                         exit(0);
964                 } else {
965                         printf("account policy \"%s\" value is: %u\n", account_policy, value);
966                         exit(0);
967                 }
968         }
969
970         if (reset_account_policies) {
971                 if (!reinit_account_policies()) {
972                         exit(1);
973                 }
974
975                 exit(0);
976         }
977
978         /* import and export operations */
979
980         if ( ((checkparms & BIT_IMPORT) 
981                 || (checkparms & BIT_EXPORT))
982                 && !(checkparms & ~(BIT_IMPORT +BIT_EXPORT +BIT_USER)) ) 
983         {
984                 NTSTATUS status;
985
986                 bin = bout = bdef;
987
988                 if (backend_in) {
989                         status = make_pdb_method_name(&bin, backend_in);
990
991                         if ( !NT_STATUS_IS_OK(status) ) {
992                                 fprintf(stderr, "Unable to initialize %s.\n", backend_in);
993                                 return 1;
994                         }
995                 }
996
997                 if (backend_out) {
998                         status = make_pdb_method_name(&bout, backend_out);
999
1000                         if ( !NT_STATUS_IS_OK(status) ) {
1001                                 fprintf(stderr, "Unable to initialize %s.\n", backend_out);
1002                                 return 1;
1003                         }
1004                 }
1005
1006                 if (transfer_account_policies) {
1007
1008                         if (!(checkparms & BIT_USER))
1009                                 return export_account_policies(bin, bout);
1010
1011                 } else  if (transfer_groups) {
1012
1013                         if (!(checkparms & BIT_USER))
1014                                 return export_groups(bin, bout);
1015
1016                 } else {
1017                                 return export_database(bin, bout, 
1018                                         (checkparms & BIT_USER) ? user_name : NULL );
1019                 }
1020         }
1021
1022         /* if BIT_USER is defined but nothing else then threat it as -l -u for compatibility */
1023         /* fake up BIT_LIST if only BIT_USER is defined */
1024         if ((checkparms & BIT_USER) && !(checkparms & ~BIT_USER)) {
1025                 checkparms += BIT_LIST;
1026         }
1027         
1028         /* modify flag is optional to maintain backwards compatibility */
1029         /* fake up BIT_MODIFY if BIT_USER  and at least one of MASK_USER_GOOD is defined */
1030         if (!((checkparms & ~MASK_USER_GOOD) & ~BIT_USER) && (checkparms & MASK_USER_GOOD)) {
1031                 checkparms += BIT_MODIFY;
1032         }
1033
1034         /* list users operations */
1035         if (checkparms & BIT_LIST) {
1036                 if (!(checkparms & ~BIT_LIST)) {
1037                         return print_users_list (bdef, verbose, spstyle);
1038                 }
1039                 if (!(checkparms & ~(BIT_USER + BIT_LIST))) {
1040                         return print_user_info (bdef, user_name, verbose, spstyle);
1041                 }
1042         }
1043         
1044         /* mask out users options */
1045         checkparms &= ~MASK_USER_GOOD;
1046
1047         /* if bad password count is reset, we must be modifying */
1048         if (checkparms & BIT_BADPWRESET) {
1049                 checkparms |= BIT_MODIFY;
1050                 checkparms &= ~BIT_BADPWRESET;
1051         }
1052
1053         /* if logon hours is reset, must modify */
1054         if (checkparms & BIT_LOGONHOURS) {
1055                 checkparms |= BIT_MODIFY;
1056                 checkparms &= ~BIT_LOGONHOURS;
1057         }
1058         
1059         /* account operation */
1060         if ((checkparms & BIT_CREATE) || (checkparms & BIT_MODIFY) || (checkparms & BIT_DELETE)) {
1061                 /* check use of -u option */
1062                 if (!(checkparms & BIT_USER)) {
1063                         fprintf (stderr, "Username not specified! (use -u option)\n");
1064                         return -1;
1065                 }
1066
1067                 /* account creation operations */
1068                 if (!(checkparms & ~(BIT_CREATE + BIT_USER + BIT_MACHINE))) {
1069                         if (checkparms & BIT_MACHINE) {
1070                                 return new_machine (bdef, user_name);
1071                         } else {
1072                                 return new_user (bdef, user_name, full_name, home_dir, 
1073                                         home_drive, logon_script, profile_path, user_sid, pw_from_stdin);
1074                         }
1075                 }
1076
1077                 /* account deletion operations */
1078                 if (!(checkparms & ~(BIT_DELETE + BIT_USER + BIT_MACHINE))) {
1079                         if (checkparms & BIT_MACHINE) {
1080                                 return delete_machine_entry (bdef, user_name);
1081                         } else {
1082                                 return delete_user_entry (bdef, user_name);
1083                         }
1084                 }
1085
1086                 /* account modification operations */
1087                 if (!(checkparms & ~(BIT_MODIFY + BIT_USER))) {
1088                         return set_user_info (bdef, user_name, full_name, home_dir,
1089                                 acct_desc, home_drive, logon_script, profile_path, account_control,
1090                                 user_sid, user_domain, badpw_reset, hours_reset);
1091                 }
1092         }
1093
1094         if (setparms >= 0x20) {
1095                 fprintf (stderr, "Incompatible or insufficient options on command line!\n");
1096         }
1097         poptPrintHelp(pc, stderr, 0);
1098
1099         TALLOC_FREE(frame);
1100         return 1;
1101 }