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