import HEAD into svn+ssh://svn.samba.org/home/svn/samba/trunk
[metze/old/v3-2-winbind-ndr.git] / source / 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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 #define BIT_BACKEND     0x00000004
27 #define BIT_VERBOSE     0x00000008
28 #define BIT_SPSTYLE     0x00000010
29 #define BIT_RESERV_1    0x00000020
30 #define BIT_RESERV_2    0x00000040
31 #define BIT_RESERV_3    0x00000080
32 #define BIT_FULLNAME    0x00000100
33 #define BIT_HOMEDIR     0x00000200
34 #define BIT_HDIRDRIVE   0x00000400
35 #define BIT_LOGSCRIPT   0x00000800
36 #define BIT_PROFILE     0x00001000
37 #define BIT_MACHINE     0x00002000
38 #define BIT_RESERV_4    0x00004000
39 #define BIT_USER        0x00008000
40 #define BIT_LIST        0x00010000
41 #define BIT_MODIFY      0x00020000
42 #define BIT_CREATE      0x00040000
43 #define BIT_DELETE      0x00080000
44 #define BIT_ACCPOLICY   0x00100000
45 #define BIT_ACCPOLVAL   0x00200000
46 #define BIT_ACCTCTRL    0x00400000
47 #define BIT_RESERV_7    0x00800000
48 #define BIT_IMPORT      0x01000000
49 #define BIT_EXPORT      0x02000000
50 #define BIT_FIX_INIT    0x04000000
51 #define BIT_BADPWRESET  0x08000000
52 #define BIT_TRUSTDOM    0x10000000
53 #define BIT_TRUSTPW     0x20000000
54 #define BIT_TRUSTSID    0x40000000
55 #define BIT_TRUSTFLAGS  0x80000000
56
57 #define MASK_ALWAYS_GOOD        0x0000001F
58 #define MASK_USER_GOOD          0x00401F00
59
60 /*********************************************************
61  Add all currently available users to another db
62  ********************************************************/
63
64 static int export_database (struct pdb_context *in, struct pdb_context *out) {
65         SAM_ACCOUNT *user = NULL;
66
67         if (NT_STATUS_IS_ERR(in->pdb_setsampwent(in, 0))) {
68                 fprintf(stderr, "Can't sampwent!\n");
69                 return 1;
70         }
71
72         if (!NT_STATUS_IS_OK(pdb_init_sam(&user))) {
73                 fprintf(stderr, "Can't initialize new SAM_ACCOUNT!\n");
74                 return 1;
75         }
76
77         while (NT_STATUS_IS_OK(in->pdb_getsampwent(in, user))) {
78                 out->pdb_add_sam_account(out, user);
79                 if (!NT_STATUS_IS_OK(pdb_reset_sam(user))){
80                         fprintf(stderr, "Can't reset SAM_ACCOUNT!\n");
81                         return 1;
82                 }
83         }
84
85         in->pdb_endsampwent(in);
86
87         return 0;
88 }
89
90 /*********************************************************
91  Add all currently available group mappings to another db
92  ********************************************************/
93
94 static int export_groups (struct pdb_context *in, struct pdb_context *out) {
95         GROUP_MAP *maps = NULL;
96         int i, entries = 0;
97
98         if (NT_STATUS_IS_ERR(in->pdb_enum_group_mapping(in, SID_NAME_UNKNOWN,
99                                                         &maps, &entries,
100                                                         False))) {
101                 fprintf(stderr, "Can't get group mappings!\n");
102                 return 1;
103         }
104
105         for (i=0; i<entries; i++) {
106                 out->pdb_add_group_mapping_entry(out, &(maps[i]));
107         }
108
109         SAFE_FREE(maps);
110
111         return 0;
112 }
113
114 /*********************************************************
115  Print info from sam structure
116 **********************************************************/
117
118 static int print_sam_info (SAM_ACCOUNT *sam_pwent, BOOL verbosity, BOOL smbpwdstyle)
119 {
120         uid_t uid;
121         time_t tmp;
122
123         /* TODO: chaeck if entry is a user or a workstation */
124         if (!sam_pwent) return -1;
125         
126         if (verbosity) {
127                 printf ("Unix username:        %s\n", pdb_get_username(sam_pwent));
128                 printf ("NT username:          %s\n", pdb_get_nt_username(sam_pwent));
129                 printf ("Account Flags:        %s\n", pdb_encode_acct_ctrl(pdb_get_acct_ctrl(sam_pwent), NEW_PW_FORMAT_SPACE_PADDED_LEN));
130                 printf ("User SID:             %s\n",
131                         sid_string_static(pdb_get_user_sid(sam_pwent)));
132                 printf ("Primary Group SID:    %s\n",
133                         sid_string_static(pdb_get_group_sid(sam_pwent)));
134                 printf ("Full Name:            %s\n", pdb_get_fullname(sam_pwent));
135                 printf ("Home Directory:       %s\n", pdb_get_homedir(sam_pwent));
136                 printf ("HomeDir Drive:        %s\n", pdb_get_dir_drive(sam_pwent));
137                 printf ("Logon Script:         %s\n", pdb_get_logon_script(sam_pwent));
138                 printf ("Profile Path:         %s\n", pdb_get_profile_path(sam_pwent));
139                 printf ("Domain:               %s\n", pdb_get_domain(sam_pwent));
140                 printf ("Account desc:         %s\n", pdb_get_acct_desc(sam_pwent));
141                 printf ("Workstations:         %s\n", pdb_get_workstations(sam_pwent));
142                 printf ("Munged dial:          %s\n", pdb_get_munged_dial(sam_pwent));
143                 
144                 tmp = pdb_get_logon_time(sam_pwent);
145                 printf ("Logon time:           %s\n", tmp ? http_timestring(tmp) : "0");
146                 
147                 tmp = pdb_get_logoff_time(sam_pwent);
148                 printf ("Logoff time:          %s\n", tmp ? http_timestring(tmp) : "0");
149                 
150                 tmp = pdb_get_kickoff_time(sam_pwent);
151                 printf ("Kickoff time:         %s\n", tmp ? http_timestring(tmp) : "0");
152                 
153                 tmp = pdb_get_pass_last_set_time(sam_pwent);
154                 printf ("Password last set:    %s\n", tmp ? http_timestring(tmp) : "0");
155                 
156                 tmp = pdb_get_pass_can_change_time(sam_pwent);
157                 printf ("Password can change:  %s\n", tmp ? http_timestring(tmp) : "0");
158                 
159                 tmp = pdb_get_pass_must_change_time(sam_pwent);
160                 printf ("Password must change: %s\n", tmp ? http_timestring(tmp) : "0");
161
162                 tmp = pdb_get_bad_password_time(sam_pwent);
163                 printf ("Last bad password   : %s\n", tmp ? http_timestring(tmp) : "0");
164                 printf ("Bad password count  : %d\n", 
165                         pdb_get_bad_password_count(sam_pwent));
166                 
167         } else if (smbpwdstyle) {
168                 char lm_passwd[33];
169                 char nt_passwd[33];
170
171                 uid = nametouid(pdb_get_username(sam_pwent));
172                 pdb_sethexpwd(lm_passwd, pdb_get_lanman_passwd(sam_pwent), pdb_get_acct_ctrl(sam_pwent));
173                 pdb_sethexpwd(nt_passwd, pdb_get_nt_passwd(sam_pwent), pdb_get_acct_ctrl(sam_pwent));
174                         
175                 printf("%s:%lu:%s:%s:%s:LCT-%08X:\n",
176                        pdb_get_username(sam_pwent),
177                        (unsigned long)uid,
178                        lm_passwd,
179                        nt_passwd,
180                        pdb_encode_acct_ctrl(pdb_get_acct_ctrl(sam_pwent),NEW_PW_FORMAT_SPACE_PADDED_LEN),
181                        (uint32)pdb_get_pass_last_set_time(sam_pwent));
182         } else {
183                 uid = nametouid(pdb_get_username(sam_pwent));
184                 printf ("%s:%lu:%s\n", pdb_get_username(sam_pwent), (unsigned long)uid, 
185                         pdb_get_fullname(sam_pwent));
186         }
187
188         return 0;       
189 }
190
191 /*********************************************************
192  Get an Print User Info
193 **********************************************************/
194
195 static int print_user_info (struct pdb_context *in, const char *username, BOOL verbosity, BOOL smbpwdstyle)
196 {
197         SAM_ACCOUNT *sam_pwent=NULL;
198         BOOL ret;
199         BOOL updated_autolock = False, updated_badpw = False;
200
201         if (!NT_STATUS_IS_OK(pdb_init_sam (&sam_pwent))) {
202                 return -1;
203         }
204
205         ret = NT_STATUS_IS_OK(in->pdb_getsampwnam (in, sam_pwent, username));
206
207         if (ret==False) {
208                 fprintf (stderr, "Username not found!\n");
209                 pdb_free_sam(&sam_pwent);
210                 return -1;
211         }
212
213         if (!pdb_update_autolock_flag(sam_pwent, &updated_autolock))
214                 DEBUG(2,("pdb_update_autolock_flag failed.\n"));
215
216         if (!pdb_update_bad_password_count(sam_pwent, &updated_badpw))
217                 DEBUG(2,("pdb_update_bad_password_count failed.\n"));
218
219         if (updated_autolock || updated_badpw) {
220                 become_root();
221                 if(!pdb_update_sam_account(sam_pwent))
222                         DEBUG(1, ("Failed to modify entry.\n"));
223                 unbecome_root();
224         }
225
226         ret=print_sam_info (sam_pwent, verbosity, smbpwdstyle);
227         pdb_free_sam(&sam_pwent);
228         
229         return ret;
230 }
231
232
233 /**
234  * Trust password flag name to flag conversion
235  *
236  * @param flag_name SAM_TRUST_PASSWD structure flag name
237  * @return flag value
238  **/
239
240 static int trustpw_flag(const char* flag_name)
241 {
242         const int flag_num = 5;
243         typedef struct { const char *name; int val; } flag_conv;
244         flag_conv flags[] = {{ "PASS_MACHINE_TRUST_NT", PASS_MACHINE_TRUST_NT  },
245                              { "PASS_SERVER_TRUST_NT",  PASS_SERVER_TRUST_NT   },
246                              { "PASS_DOMAIN_TRUST_NT",  PASS_DOMAIN_TRUST_NT   },
247                              { "PASS_MACHINE_TRUST_ADS",PASS_MACHINE_TRUST_ADS },
248                              { "PASS_DOMAIN_TRUST_ADS", PASS_DOMAIN_TRUST_ADS  }};
249         int i;
250
251         for (i = 0; i < flag_num; i++) {
252                 if (!StrCaseCmp(flags[i].name, flag_name)) {
253                         return flags[i].val;
254                 }
255         }
256                 
257         return 0;
258 }
259
260
261 /**
262  * Trust password flag to flag name conversion
263  *
264  * @param val SAM_TRUST_PASSWD structure flag
265  * @return passed flag name
266  **/
267
268 static char* trustpw_flag_name(const int val)
269 {
270         const int flag_num = 5;
271         typedef struct { const char *name; int val; } flag_conv;
272         flag_conv flags[] = {{ "PASS_MACHINE_TRUST_NT", PASS_MACHINE_TRUST_NT  },
273                              { "PASS_SERVER_TRUST_NT",  PASS_SERVER_TRUST_NT   },
274                              { "PASS_DOMAIN_TRUST_NT",  PASS_DOMAIN_TRUST_NT   },
275                              { "PASS_MACHINE_TRUST_ADS",PASS_MACHINE_TRUST_ADS },
276                              { "PASS_DOMAIN_TRUST_ADS", PASS_DOMAIN_TRUST_ADS  }};
277         int i;
278         
279         for (i = 0; i < flag_num; i++) {
280                 if (flags[i].val == val) {
281                         return strdup(flags[i].name);
282                 }
283         }
284         
285         return strdup("unknown flag");
286 }
287
288
289 /**
290  * Print trust password structure information
291  *
292  * @param mem_ctx memory context (for unicode name conversion)
293  * @param trust SAM_TRUST_PASSWD structure
294  * @param verbose verbose mode on/off
295  * @return 0 on success, otherwise failure
296  **/
297  
298 static int print_trustpw_info(TALLOC_CTX *mem_ctx, SAM_TRUST_PASSWD *trust, BOOL verbose)
299 {
300         char *dom_name;
301         if (!mem_ctx || !trust) return -1;
302
303         /* convert unicode domain name to char* */
304         if (!pull_ucs2_talloc(mem_ctx, &dom_name, trust->private.uni_name)) return -1;
305         dom_name[trust->private.uni_name_len] = 0;
306
307         /* different output depending on level of verbosity */
308         if (verbose) {
309                 printf("Domain name:          %s\n", dom_name);
310                 printf("Domain SID:           %s\n", sid_string_static(&trust->private.domain_sid));
311                 printf("Trust password        %s\n", trust->private.pass);
312                 printf("Trust type:           %s\n", trustpw_flag_name(trust->private.flags));
313                 printf("Last modified         %s\n", trust->private.mod_time ? http_timestring(trust->private.mod_time) : "0");
314         
315         } else {
316                 printf("%s:%s\n", dom_name, sid_string_static(&trust->private.domain_sid));
317         }
318         
319         return 0;
320 }
321
322
323 /**
324  * Print trust password information by given name
325  *
326  * @param in initialised pdb_context
327  * @param name domain name of the trust password
328  * @param verbose verbose mode on/off
329  * @param smbpwdstyle smbpassword-style output (ignored here)
330  * @return 0 on success, otherwise failure
331  **/
332  
333 static int print_trust_info(struct pdb_context *in, const char *name, BOOL verbose, BOOL smbpwdstyle)
334 {
335         SAM_TRUST_PASSWD trust;
336         TALLOC_CTX *mem_ctx = NULL;
337         
338         mem_ctx = talloc_init("pdbedit: trust passwords listing");
339         
340         if (NT_STATUS_IS_OK(in->pdb_gettrustpwnam(in, &trust, name))) {
341                 return print_trustpw_info(mem_ctx, &trust, verbose);
342         }
343         
344         return -1;
345 }
346         
347 /*********************************************************
348  List Users
349 **********************************************************/
350 static int print_users_list (struct pdb_context *in, BOOL verbosity, BOOL smbpwdstyle)
351 {
352         SAM_ACCOUNT *sam_pwent=NULL;
353         BOOL check, ret;
354         
355         check = NT_STATUS_IS_OK(in->pdb_setsampwent(in, False));
356         if (!check) {
357                 return 1;
358         }
359
360         check = True;
361         if (!(NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent)))) return 1;
362
363         while (check && (ret = NT_STATUS_IS_OK(in->pdb_getsampwent (in, sam_pwent)))) {
364                 if (verbosity)
365                         printf ("---------------\n");
366                 print_sam_info (sam_pwent, verbosity, smbpwdstyle);
367                 pdb_free_sam(&sam_pwent);
368                 check = NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent));
369         }
370         if (check) pdb_free_sam(&sam_pwent);
371         
372         in->pdb_endsampwent(in);
373         return 0;
374 }
375
376
377 /**
378  * List trust passwords
379  * 
380  * @param in initialised pdb context
381  * @param verbose turn on/off verbose mode
382  * @param smbpwdstyle ignored here (there was no trust passwords in smbpasswd file)
383  * @return 0 on success, otherwise failure
384  **/
385  
386 static int print_trustpw_list(struct pdb_context *in, BOOL verbose, BOOL smbpwdstyle)
387 {
388         SAM_TRUST_PASSWD trust;
389         TALLOC_CTX *mem_ctx = NULL;
390         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
391         
392         /* start enumeration and initialise memory context */
393         status = in->pdb_settrustpwent(in);
394         if (NT_STATUS_IS_ERR(status)) return -1;
395         mem_ctx = talloc_init("pdbedit: trust passwords listing");
396         
397         /* small separation to make it clear these are not regular accounts */
398         if (!verbose) printf("---\n");
399         
400         do {
401                 /* fetch next trust password */
402                 status = in->pdb_gettrustpwent(in, &trust);
403
404                 if (trust.private.uni_name_len) {
405                         /* print trust password info */
406                         if (verbose) printf ("---------------\n");
407                         print_trustpw_info(mem_ctx, &trust, verbose);
408                 }
409
410         } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES) || NT_STATUS_EQUAL(status, NT_STATUS_OK));
411         
412         talloc_destroy(mem_ctx);
413         return 0;
414 }
415
416
417 /*********************************************************
418  Fix a list of Users for uninitialised passwords
419 **********************************************************/
420 static int fix_users_list (struct pdb_context *in)
421 {
422         SAM_ACCOUNT *sam_pwent=NULL;
423         BOOL check, ret;
424         
425         check = NT_STATUS_IS_OK(in->pdb_setsampwent(in, False));
426         if (!check) {
427                 return 1;
428         }
429
430         check = True;
431         if (!(NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent)))) return 1;
432
433         while (check && (ret = NT_STATUS_IS_OK(in->pdb_getsampwent (in, sam_pwent)))) {
434                 printf("Updating record for user %s\n", pdb_get_username(sam_pwent));
435         
436                 if (!pdb_update_sam_account(sam_pwent)) {
437                         printf("Update of user %s failed!\n", pdb_get_username(sam_pwent));
438                 }
439                 pdb_free_sam(&sam_pwent);
440                 check = NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent));
441                 if (!check) {
442                         fprintf(stderr, "Failed to initialise new SAM_ACCOUNT structure (out of memory?)\n");
443                 }
444                         
445         }
446         if (check) pdb_free_sam(&sam_pwent);
447         
448         in->pdb_endsampwent(in);
449         return 0;
450 }
451
452 /*********************************************************
453  Set User Info
454 **********************************************************/
455
456 static int set_user_info (struct pdb_context *in, const char *username, 
457                           const char *fullname, const char *homedir, 
458                           const char *drive, const char *script, 
459                           const char *profile, const char *account_control,
460                           const char *user_sid, const char *group_sid,
461                           const BOOL badpw)
462 {
463         SAM_ACCOUNT *sam_pwent=NULL;
464         BOOL ret;
465         
466         pdb_init_sam(&sam_pwent);
467         
468         ret = NT_STATUS_IS_OK(in->pdb_getsampwnam (in, sam_pwent, username));
469         if (ret==False) {
470                 fprintf (stderr, "Username not found!\n");
471                 pdb_free_sam(&sam_pwent);
472                 return -1;
473         }
474         
475         if (fullname)
476                 pdb_set_fullname(sam_pwent, fullname, PDB_CHANGED);
477         if (homedir)
478                 pdb_set_homedir(sam_pwent, homedir, PDB_CHANGED);
479         if (drive)
480                 pdb_set_dir_drive(sam_pwent,drive, PDB_CHANGED);
481         if (script)
482                 pdb_set_logon_script(sam_pwent, script, PDB_CHANGED);
483         if (profile)
484                 pdb_set_profile_path (sam_pwent, profile, PDB_CHANGED);
485
486         if (account_control) {
487                 uint16 not_settable = ~(ACB_DISABLED|ACB_HOMDIRREQ|ACB_PWNOTREQ|
488                                         ACB_PWNOEXP|ACB_AUTOLOCK);
489
490                 uint16 newflag = pdb_decode_acct_ctrl(account_control);
491
492                 if (newflag & not_settable) {
493                         fprintf(stderr, "Can only set [NDHLX] flags\n");
494                         pdb_free_sam(&sam_pwent);
495                         return -1;
496                 }
497
498                 pdb_set_acct_ctrl(sam_pwent,
499                                   (pdb_get_acct_ctrl(sam_pwent) & not_settable) | newflag,
500                                   PDB_CHANGED);
501         }
502         if (user_sid) {
503                 DOM_SID u_sid;
504                 if (!string_to_sid(&u_sid, user_sid)) {
505                         /* not a complete sid, may be a RID, try building a SID */
506                         int u_rid;
507                         
508                         if (sscanf(user_sid, "%d", &u_rid) != 1) {
509                                 fprintf(stderr, "Error passed string is not a complete user SID or RID!\n");
510                                 return -1;
511                         }
512                         sid_copy(&u_sid, get_global_sam_sid());
513                         sid_append_rid(&u_sid, u_rid);
514                 }
515                 pdb_set_user_sid (sam_pwent, &u_sid, PDB_CHANGED);
516         }
517         if (group_sid) {
518                 DOM_SID g_sid;
519                 if (!string_to_sid(&g_sid, group_sid)) {
520                         /* not a complete sid, may be a RID, try building a SID */
521                         int g_rid;
522                         
523                         if (sscanf(group_sid, "%d", &g_rid) != 1) {
524                                 fprintf(stderr, "Error passed string is not a complete group SID or RID!\n");
525                                 return -1;
526                         }
527                         sid_copy(&g_sid, get_global_sam_sid());
528                         sid_append_rid(&g_sid, g_rid);
529                 }
530                 pdb_set_group_sid (sam_pwent, &g_sid, PDB_CHANGED);
531         }
532
533         if (badpw) {
534                 pdb_set_bad_password_count(sam_pwent, 0, PDB_CHANGED);
535                 pdb_set_bad_password_time(sam_pwent, 0, PDB_CHANGED);
536         }
537         
538         if (NT_STATUS_IS_OK(in->pdb_update_sam_account (in, sam_pwent)))
539                 print_user_info (in, username, True, False);
540         else {
541                 fprintf (stderr, "Unable to modify entry!\n");
542                 pdb_free_sam(&sam_pwent);
543                 return -1;
544         }
545         pdb_free_sam(&sam_pwent);
546         return 0;
547 }
548
549 /*********************************************************
550  Add New User
551 **********************************************************/
552 static int new_user (struct pdb_context *in, const char *username,
553                         const char *fullname, const char *homedir,
554                         const char *drive, const char *script,
555                         const char *profile, char *user_sid, char *group_sid)
556 {
557         SAM_ACCOUNT *sam_pwent=NULL;
558         NTSTATUS nt_status;
559         char *password1, *password2, *staticpass;
560         
561         get_global_sam_sid();
562
563         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_new(&sam_pwent, username, 0))) {
564                 DEBUG(0, ("could not create account to add new user %s\n", username));
565                 return -1;
566         }
567
568         staticpass = getpass("new password:");
569         password1 = strdup(staticpass);
570         memset(staticpass, 0, strlen(staticpass));
571         staticpass = getpass("retype new password:");
572         password2 = strdup(staticpass);
573         memset(staticpass, 0, strlen(staticpass));
574         if (strcmp (password1, password2)) {
575                 fprintf (stderr, "Passwords does not match!\n");
576                 memset(password1, 0, strlen(password1));
577                 SAFE_FREE(password1);
578                 memset(password2, 0, strlen(password2));
579                 SAFE_FREE(password2);
580                 pdb_free_sam (&sam_pwent);
581                 return -1;
582         }
583
584         pdb_set_plaintext_passwd(sam_pwent, password1);
585         memset(password1, 0, strlen(password1));
586         SAFE_FREE(password1);
587         memset(password2, 0, strlen(password2));
588         SAFE_FREE(password2);
589
590         if (fullname)
591                 pdb_set_fullname(sam_pwent, fullname, PDB_CHANGED);
592         if (homedir)
593                 pdb_set_homedir (sam_pwent, homedir, PDB_CHANGED);
594         if (drive)
595                 pdb_set_dir_drive (sam_pwent, drive, PDB_CHANGED);
596         if (script)
597                 pdb_set_logon_script(sam_pwent, script, PDB_CHANGED);
598         if (profile)
599                 pdb_set_profile_path (sam_pwent, profile, PDB_CHANGED);
600         if (user_sid) {
601                 DOM_SID u_sid;
602                 if (!string_to_sid(&u_sid, user_sid)) {
603                         /* not a complete sid, may be a RID, try building a SID */
604                         int u_rid;
605                         
606                         if (sscanf(user_sid, "%d", &u_rid) != 1) {
607                                 fprintf(stderr, "Error passed string is not a complete user SID or RID!\n");
608                                 return -1;
609                         }
610                         sid_copy(&u_sid, get_global_sam_sid());
611                         sid_append_rid(&u_sid, u_rid);
612                 }
613                 pdb_set_user_sid (sam_pwent, &u_sid, PDB_CHANGED);
614         }
615         if (group_sid) {
616                 DOM_SID g_sid;
617                 if (!string_to_sid(&g_sid, group_sid)) {
618                         /* not a complete sid, may be a RID, try building a SID */
619                         int g_rid;
620                         
621                         if (sscanf(group_sid, "%d", &g_rid) != 1) {
622                                 fprintf(stderr, "Error passed string is not a complete group SID or RID!\n");
623                                 return -1;
624                         }
625                         sid_copy(&g_sid, get_global_sam_sid());
626                         sid_append_rid(&g_sid, g_rid);
627                 }
628                 pdb_set_group_sid (sam_pwent, &g_sid, PDB_CHANGED);
629         }
630         
631         pdb_set_acct_ctrl (sam_pwent, ACB_NORMAL, PDB_CHANGED);
632         
633         if (NT_STATUS_IS_OK(in->pdb_add_sam_account (in, sam_pwent))) { 
634                 print_user_info (in, username, True, False);
635         } else {
636                 fprintf (stderr, "Unable to add user! (does it already exist?)\n");
637                 pdb_free_sam (&sam_pwent);
638                 return -1;
639         }
640         pdb_free_sam (&sam_pwent);
641         return 0;
642 }
643
644 /*********************************************************
645  Add New Machine
646 **********************************************************/
647
648 static int new_machine (struct pdb_context *in, const char *machine_in)
649 {
650         SAM_ACCOUNT *sam_pwent=NULL;
651         fstring machinename;
652         fstring machineaccount;
653         struct passwd  *pwd = NULL;
654         
655         get_global_sam_sid();
656
657         fstrcpy(machinename, machine_in); 
658         machinename[15]= '\0';
659
660         if (machinename[strlen (machinename) -1] == '$')
661                 machinename[strlen (machinename) -1] = '\0';
662         
663         strlower_m(machinename);
664         
665         fstrcpy(machineaccount, machinename);
666         fstrcat(machineaccount, "$");
667
668         if ((pwd = getpwnam_alloc(machineaccount))) {
669                 if (!NT_STATUS_IS_OK(pdb_init_sam_pw( &sam_pwent, pwd))) {
670                         fprintf(stderr, "Could not init sam from pw\n");
671                         passwd_free(&pwd);
672                         return -1;
673                 }
674                 passwd_free(&pwd);
675         } else {
676                 if (!NT_STATUS_IS_OK(pdb_init_sam (&sam_pwent))) {
677                         fprintf(stderr, "Could not init sam from pw\n");
678                         return -1;
679                 }
680         }
681
682         pdb_set_plaintext_passwd (sam_pwent, machinename);
683
684         pdb_set_username (sam_pwent, machineaccount, PDB_CHANGED);
685         
686         pdb_set_acct_ctrl (sam_pwent, ACB_WSTRUST, PDB_CHANGED);
687         
688         pdb_set_group_sid_from_rid(sam_pwent, DOMAIN_GROUP_RID_COMPUTERS, PDB_CHANGED);
689         
690         if (NT_STATUS_IS_OK(in->pdb_add_sam_account (in, sam_pwent))) {
691                 print_user_info (in, machineaccount, True, False);
692         } else {
693                 fprintf (stderr, "Unable to add machine! (does it already exist?)\n");
694                 pdb_free_sam (&sam_pwent);
695                 return -1;
696         }
697         pdb_free_sam (&sam_pwent);
698         return 0;
699 }
700
701
702 /**
703  * Add new trusting domain account
704  *
705  * @param in initialised pdb_context
706  * @param dom_name trusted domain name given in command line
707  *
708  * @return 0 on success, -1 otherwise
709  **/
710  
711 static int new_trustdom(struct pdb_context *in, const char *dom_name)
712 {
713         /* TODO */
714         return -1;
715 }
716
717
718 /**
719  * Add new trust relationship password
720  *
721  * @param in initialised pdb_context
722  * @param dom_name trusting domain name given in command line
723  * @param dom_sid domain sid given in command line
724  * @param flag trust password type flag given in command line
725  *
726  * @return 0 on success, -1 otherwise
727  **/
728
729 static int new_trustpw(struct pdb_context *in, const char *dom_name,
730                        const char *dom_sid, const char* flag)
731 {
732         TALLOC_CTX *mem_ctx = NULL;
733         SAM_TRUST_PASSWD trust;
734         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
735         POLICY_HND connect_hnd;
736         DOM_SID *domain_sid = NULL;
737         smb_ucs2_t *uni_name = NULL;
738         char *givenpass, *domain_name = NULL;
739         struct in_addr srv_ip;
740         fstring srv_name, myname;
741         struct cli_state *cli;
742         time_t lct;
743         
744         if (!dom_name) return -1;
745         
746         mem_ctx = talloc_init("pdbedit: adding new trust password");
747         
748         /* unicode name */
749         trust.private.uni_name_len = strnlen(dom_name, 32);
750         push_ucs2_talloc(mem_ctx, &uni_name, dom_name);
751         strncpy_w(trust.private.uni_name, uni_name, 32);
752         
753         /* flags */
754         trust.private.flags = trustpw_flag(flag);
755
756         /* trusting SID */
757         if (!dom_sid) {
758                 /* if sid is not specified in command line, do our best
759                    to establish it */
760
761                 /* find domain PDC */
762                 if (!get_pdc_ip(dom_name, &srv_ip))
763                         return -1;
764                 if (is_zero_ip(srv_ip))
765                         return -1;
766                 if (!name_status_find(dom_name, 0x1b, 0x20, srv_ip, srv_name))
767                         return -1;
768                         
769                 get_myname(myname);
770                         
771                 /* Connect the domain pdc...  */
772                 nt_status = cli_full_connection(&cli, myname, srv_name, &srv_ip, 139,
773                                                 "IPC$", "IPC", "", "", "", 0, Undefined, NULL);
774                 if (NT_STATUS_IS_ERR(nt_status))
775                         return -1;
776                 if (!cli_nt_session_open(cli, PI_LSARPC))
777                         return -1;
778                 
779                 /* ...and query the domain sid */
780                 nt_status = cli_lsa_open_policy2(cli, mem_ctx, True, SEC_RIGHTS_QUERY_VALUE,
781                                                  &connect_hnd);
782                 if (NT_STATUS_IS_ERR(nt_status)) return -1;
783
784                 nt_status = cli_lsa_query_info_policy(cli, mem_ctx, &connect_hnd,
785                                                       5, &domain_name, &domain_sid);
786                 if (NT_STATUS_IS_ERR(nt_status)) return -1;
787                 
788                 nt_status = cli_lsa_close(cli, mem_ctx, &connect_hnd);
789                 if (NT_STATUS_IS_ERR(nt_status)) return -1;
790                 
791                 cli_nt_session_close(cli);
792                 cli_shutdown(cli);
793                 
794                 /* copying sid to trust password structure */
795                 sid_copy(&trust.private.domain_sid, domain_sid);
796                         
797         } else {
798                 if (!string_to_sid(&trust.private.domain_sid, dom_sid)) {
799                         printf("Error: wrong SID specified !\n");
800                         return -1;
801                 }
802         }
803                 
804         /* password */
805         givenpass = getpass("password:");
806         memset(trust.private.pass, '\0', FSTRING_LEN);
807         strncpy(trust.private.pass, givenpass, FSTRING_LEN);
808         
809         /* last change time */
810         lct = time(NULL);
811         trust.private.mod_time = lct;
812         
813         /* store trust password in passdb */
814         nt_status = in->pdb_add_trust_passwd(in, &trust);
815                         
816         talloc_destroy(mem_ctx);
817         if (NT_STATUS_IS_OK(nt_status))
818                 return 0;
819         
820         return -1;
821 }
822
823
824 /*********************************************************
825  Delete user entry
826 **********************************************************/
827
828 static int delete_user_entry (struct pdb_context *in, const char *username)
829 {
830         SAM_ACCOUNT *samaccount = NULL;
831
832         if (!NT_STATUS_IS_OK(pdb_init_sam (&samaccount))) {
833                 return -1;
834         }
835
836         if (!NT_STATUS_IS_OK(in->pdb_getsampwnam(in, samaccount, username))) {
837                 fprintf (stderr, "user %s does not exist in the passdb\n", username);
838                 return -1;
839         }
840
841         if (!NT_STATUS_IS_OK(in->pdb_delete_sam_account (in, samaccount))) {
842                 fprintf (stderr, "Unable to delete user %s\n", username);
843                 return -1;
844         }
845         return 0;
846 }
847
848 /*********************************************************
849  Delete machine entry
850 **********************************************************/
851
852 static int delete_machine_entry (struct pdb_context *in, const char *machinename)
853 {
854         fstring name;
855         SAM_ACCOUNT *samaccount = NULL;
856         
857         fstrcpy(name, machinename);
858         name[15] = '\0';
859         if (name[strlen(name)-1] != '$')
860                 fstrcat (name, "$");
861
862         if (!NT_STATUS_IS_OK(pdb_init_sam (&samaccount))) {
863                 return -1;
864         }
865
866         if (!NT_STATUS_IS_OK(in->pdb_getsampwnam(in, samaccount, name))) {
867                 fprintf (stderr, "machine %s does not exist in the passdb\n", name);
868                 return -1;
869         }
870
871         if (!NT_STATUS_IS_OK(in->pdb_delete_sam_account (in, samaccount))) {
872                 fprintf (stderr, "Unable to delete machine %s\n", name);
873                 return -1;
874         }
875
876         return 0;
877 }
878
879 /*********************************************************
880  Start here.
881 **********************************************************/
882
883 int main (int argc, char **argv)
884 {
885         static BOOL list_users = False;
886         static BOOL verbose = False;
887         static BOOL spstyle = False;
888         static BOOL machine = False;
889         static BOOL trustdom = False;
890         static BOOL add_user = False;
891         static BOOL delete_user = False;
892         static BOOL modify_user = False;
893         uint32  setparms, checkparms;
894         int opt;
895         static char *full_name = NULL;
896         static const char *user_name = NULL;
897         static char *home_dir = NULL;
898         static char *home_drive = NULL;
899         static char *backend = NULL;
900         static char *backend_in = NULL;
901         static char *backend_out = NULL;
902         static BOOL transfer_groups = False;
903         static BOOL  force_initialised_password = False;
904         static char *logon_script = NULL;
905         static char *profile_path = NULL;
906         static char *account_control = NULL;
907         static char *account_policy = NULL;
908         static char *user_sid = NULL;
909         static char *group_sid = NULL;
910         static long int account_policy_value = 0;
911         BOOL account_policy_value_set = False;
912         static BOOL badpw_reset = False;
913         /* trust password parameters */
914         static char *trustpw = NULL;
915         static char *trustsid = NULL;
916         static char *trustflags = NULL;
917
918         struct pdb_context *bin;
919         struct pdb_context *bout;
920         struct pdb_context *bdef;
921         poptContext pc;
922         struct poptOption long_options[] = {
923                 POPT_AUTOHELP
924                 {"list",        'L', POPT_ARG_NONE, &list_users, 0, "list all users", NULL},
925                 {"verbose",     'v', POPT_ARG_NONE, &verbose, 0, "be verbose", NULL },
926                 {"smbpasswd-style",     'w',POPT_ARG_NONE, &spstyle, 0, "give output in smbpasswd style", NULL},
927                 {"user",        'u', POPT_ARG_STRING, &user_name, 0, "use username", "USER" },
928                 {"fullname",    'f', POPT_ARG_STRING, &full_name, 0, "set full name", NULL},
929                 {"homedir",     'h', POPT_ARG_STRING, &home_dir, 0, "set home directory", NULL},
930                 {"drive",       'D', POPT_ARG_STRING, &home_drive, 0, "set home drive", NULL},
931                 {"script",      'S', POPT_ARG_STRING, &logon_script, 0, "set logon script", NULL},
932                 {"profile",     'p', POPT_ARG_STRING, &profile_path, 0, "set profile path", NULL},
933                 {"user SID",    'U', POPT_ARG_STRING, &user_sid, 0, "set user SID or RID", NULL},
934                 {"group SID",   'G', POPT_ARG_STRING, &group_sid, 0, "set group SID or RID", NULL},
935                 {"create",      'a', POPT_ARG_NONE, &add_user, 0, "create user", NULL},
936                 {"modify",      'r', POPT_ARG_NONE, &modify_user, 0, "modify user", NULL},
937                 {"delete",      'x', POPT_ARG_NONE, &delete_user, 0, "delete user", NULL},
938                 {"machine",     'm', POPT_ARG_NONE, &machine, 0, "account is a machine account", NULL},
939                 {"trustdom",    'I', POPT_ARG_NONE, &trustdom, 0, "account is a domain trust account", NULL},
940                 {"trustpw",     'N', POPT_ARG_STRING, &trustpw, 0, "trust password's domain name", NULL},
941                 {"trustsid",    'T', POPT_ARG_STRING, &trustsid, 0, "trust password's domain sid", NULL},
942                 {"trustflags",  'F', POPT_ARG_STRING, &trustflags, 0, "trust password flags", NULL},
943                 {"backend",     'b', POPT_ARG_STRING, &backend, 0, "use different passdb backend as default backend", NULL},
944                 {"import",      'i', POPT_ARG_STRING, &backend_in, 0, "import user accounts from this backend", NULL},
945                 {"export",      'e', POPT_ARG_STRING, &backend_out, 0, "export user accounts to this backend", NULL},
946                 {"group",       'g', POPT_ARG_NONE, &transfer_groups, 0, "use -i and -e for groups", NULL},
947                 {"account-policy",      'P', POPT_ARG_STRING, &account_policy, 0,"value of an account policy (like maximum password age)",NULL},
948                 {"value",       'C', POPT_ARG_LONG, &account_policy_value, 'C',"set the account policy to this value", NULL},
949                 {"account-control",     'c', POPT_ARG_STRING, &account_control, 0, "Values of account control", NULL},
950                 {"force-initialized-passwords", 0, POPT_ARG_NONE, &force_initialised_password, 0, "Force initialization of corrupt password strings in a passdb backend", NULL},
951                 {"bad-password-count-reset", 'z', POPT_ARG_NONE, &badpw_reset, 0, "reset bad password count", NULL},
952                 POPT_COMMON_SAMBA
953                 POPT_TABLEEND
954         };
955         
956         setup_logging("pdbedit", True);
957         
958         pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
959                             POPT_CONTEXT_KEEP_FIRST);
960         
961         while((opt = poptGetNextOpt(pc)) != -1) {
962                 switch (opt) {
963                 case 'C':
964                         account_policy_value_set = True;
965                         break;
966                 }
967         }
968
969         poptGetArg(pc); /* Drop argv[0], the program name */
970
971         if (user_name == NULL)
972                 user_name = poptGetArg(pc);
973
974         if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
975                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", dyn_CONFIGFILE);
976                 exit(1);
977         }
978
979         if(!initialize_password_db(False))
980                 exit(1);
981
982         if (!init_names())
983                 exit(1);
984
985         setparms =      (backend ? BIT_BACKEND : 0) +
986                         (verbose ? BIT_VERBOSE : 0) +
987                         (spstyle ? BIT_SPSTYLE : 0) +
988                         (full_name ? BIT_FULLNAME : 0) +
989                         (home_dir ? BIT_HOMEDIR : 0) +
990                         (home_drive ? BIT_HDIRDRIVE : 0) +
991                         (logon_script ? BIT_LOGSCRIPT : 0) +
992                         (profile_path ? BIT_PROFILE : 0) +
993                         (machine ? BIT_MACHINE : 0) +
994                         (trustdom ? BIT_TRUSTDOM : 0) +
995                         (trustpw ? BIT_TRUSTPW : 0) +
996                         (trustsid ? BIT_TRUSTSID : 0) +
997                         (trustflags ? BIT_TRUSTFLAGS : 0) +
998                         (user_name ? BIT_USER : 0) +
999                         (list_users ? BIT_LIST : 0) +
1000                         (force_initialised_password ? BIT_FIX_INIT : 0) +
1001                         (modify_user ? BIT_MODIFY : 0) +
1002                         (add_user ? BIT_CREATE : 0) +
1003                         (delete_user ? BIT_DELETE : 0) +
1004                         (account_control ? BIT_ACCTCTRL : 0) +
1005                         (account_policy ? BIT_ACCPOLICY : 0) +
1006                         (account_policy_value_set ? BIT_ACCPOLVAL : 0) +
1007                         (backend_in ? BIT_IMPORT : 0) +
1008                         (backend_out ? BIT_EXPORT : 0) +
1009                         (badpw_reset ? BIT_BADPWRESET : 0);
1010
1011         if (setparms & BIT_BACKEND) {
1012                 if (!NT_STATUS_IS_OK(make_pdb_context_string(&bdef, backend))) {
1013                         fprintf(stderr, "Can't initialize passdb backend.\n");
1014                         return 1;
1015                 }
1016         } else {
1017                 if (!NT_STATUS_IS_OK(make_pdb_context_list(&bdef, lp_passdb_backend()))) {
1018                         fprintf(stderr, "Can't initialize passdb backend.\n");
1019                         return 1;
1020                 }
1021         }
1022         
1023         /* the lowest bit options are always accepted */
1024         checkparms = setparms & ~MASK_ALWAYS_GOOD;
1025
1026         if (checkparms & BIT_FIX_INIT) {
1027                 return fix_users_list(bdef);
1028         }
1029
1030         /* account policy operations */
1031         if ((checkparms & BIT_ACCPOLICY) && !(checkparms & ~(BIT_ACCPOLICY + BIT_ACCPOLVAL))) {
1032                 uint32 value;
1033                 int field = account_policy_name_to_fieldnum(account_policy);
1034                 if (field == 0) {
1035                         fprintf(stderr, "No account policy by that name\n");
1036                         exit(1);
1037                 }
1038                 if (!account_policy_get(field, &value)) {
1039                         fprintf(stderr, "valid account policy, but unable to fetch value!\n");
1040                         exit(1);
1041                 }
1042                 if (account_policy_value_set) {
1043                         printf("account policy value for %s was %u\n", account_policy, value);
1044                         if (!account_policy_set(field, account_policy_value)) {
1045                                 fprintf(stderr, "valid account policy, but unable to set value!\n");
1046                                 exit(1);
1047                         }
1048                         printf("account policy value for %s is now %lu\n", account_policy, account_policy_value);
1049                         exit(0);
1050                 } else {
1051                         printf("account policy value for %s is %u\n", account_policy, value);
1052                         exit(0);
1053                 }
1054         }
1055
1056         /* import and export operations */
1057         if (((checkparms & BIT_IMPORT) || (checkparms & BIT_EXPORT))
1058                         && !(checkparms & ~(BIT_IMPORT +BIT_EXPORT))) {
1059                 if (backend_in) {
1060                         if (!NT_STATUS_IS_OK(make_pdb_context_string(&bin, backend_in))) {
1061                                 fprintf(stderr, "Can't initialize passdb backend.\n");
1062                                 return 1;
1063                         }
1064                 } else {
1065                         bin = bdef;
1066                 }
1067                 if (backend_out) {
1068                         if (!NT_STATUS_IS_OK(make_pdb_context_string(&bout, backend_out))) {
1069                                 fprintf(stderr, "Can't initialize %s.\n", backend_out);
1070                                 return 1;
1071                         }
1072                 } else {
1073                         bout = bdef;
1074                 }
1075                 if (transfer_groups) {
1076                         return export_groups(bin, bout);
1077                 } else {
1078                         return export_database(bin, bout);
1079                 }
1080         }
1081
1082         /* if BIT_USER is defined but nothing else then threat it as -l -u for compatibility */
1083         /* fake up BIT_LIST if only BIT_USER is defined */
1084         if ((checkparms & BIT_USER) && !(checkparms & ~BIT_USER)) {
1085                 checkparms += BIT_LIST;
1086         }
1087         
1088         /* modify flag is optional to maintain backwards compatibility */
1089         /* fake up BIT_MODIFY if BIT_USER  and at least one of MASK_USER_GOOD is defined */
1090         if (!((checkparms & ~MASK_USER_GOOD) & ~BIT_USER) && (checkparms & MASK_USER_GOOD)) {
1091                 checkparms += BIT_MODIFY;
1092         }
1093
1094         /* list users operations */
1095         if (checkparms & BIT_LIST) {
1096                 if (!(checkparms & ~BIT_LIST)) {
1097                         print_users_list (bdef, verbose, spstyle);
1098                         return print_trustpw_list(bdef, verbose, spstyle);
1099                 }
1100                 if (!(checkparms & ~(BIT_USER + BIT_LIST))) {
1101                         return print_user_info (bdef, user_name, verbose, spstyle);
1102
1103                 } else if (!(checkparms & ~(BIT_TRUSTPW + BIT_LIST))) {
1104                         return print_trust_info(bdef, trustpw, verbose, spstyle);
1105                 }
1106         }
1107         
1108         /* mask out users options */
1109         checkparms &= ~MASK_USER_GOOD;
1110
1111         /* if bad password count is reset, we must be modifying */
1112         if (checkparms & BIT_BADPWRESET) {
1113                 checkparms |= BIT_MODIFY;
1114                 checkparms &= ~BIT_BADPWRESET;
1115         }
1116         
1117         /* account operation */
1118         if ((checkparms & BIT_CREATE) || (checkparms & BIT_MODIFY) || (checkparms & BIT_DELETE)) {
1119                 /* check use of -u option */
1120                 if (!(checkparms & (BIT_USER + BIT_TRUSTPW))) {
1121                         fprintf (stderr, "Username not specified! (use -u option)\n");
1122                         return -1;
1123                 }
1124
1125                 /* account creation operations */
1126                 if (!(checkparms & ~(BIT_CREATE + BIT_USER + BIT_MACHINE + BIT_TRUSTDOM))) {
1127                         /* machine trust account */
1128                         if (checkparms & BIT_MACHINE) {
1129                                 return new_machine (bdef, user_name);
1130                         /* interdomain trust account */
1131                         } else if (checkparms & BIT_TRUSTDOM) {
1132                                 return new_trustdom(bdef, user_name);
1133
1134                         /* ordinary user account */
1135                         } else {
1136                                 return new_user (bdef, user_name, full_name, home_dir, 
1137                                                  home_drive, logon_script, 
1138                                                  profile_path, user_sid, group_sid);
1139                         }
1140                 }
1141
1142                 /* account deletion operations */
1143                 if (!(checkparms & ~(BIT_DELETE + BIT_USER + BIT_MACHINE))) {
1144                         if (checkparms & BIT_MACHINE) {
1145                                 return delete_machine_entry (bdef, user_name);
1146                         } else {
1147                                 return delete_user_entry (bdef, user_name);
1148                         }
1149                 }
1150
1151                 /* account modification operations */
1152                 if (!(checkparms & ~(BIT_MODIFY + BIT_USER))) {
1153                         return set_user_info (bdef, user_name, full_name,
1154                                               home_dir,
1155                                               home_drive,
1156                                               logon_script,
1157                                               profile_path, account_control,
1158                                               user_sid, group_sid,
1159                                               badpw_reset);
1160                 }
1161         }
1162
1163         /* trust password operation */
1164         if ((checkparms & BIT_CREATE) || (checkparms & BIT_MODIFY) || (checkparms & BIT_DELETE)) {
1165                 /* trust password creation */
1166                 if (!(checkparms & ~(BIT_CREATE + BIT_TRUSTPW + BIT_TRUSTSID + BIT_TRUSTFLAGS))) {
1167                         return new_trustpw(bdef, trustpw, trustsid, trustflags);
1168                 }               
1169         }
1170         
1171         
1172         if (setparms >= 0x20) {
1173                 fprintf (stderr, "Incompatible or insufficient options on command line!\n");
1174         }
1175         poptPrintHelp(pc, stderr, 0);
1176
1177         return 1;
1178 }
1179