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