1) Two new functions to trust passwords interface in passdb:
[samba.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 static int trustpw_flag(const char* flag_name)
234 {
235         const int flag_num = 5;
236         typedef struct { const char *name; int val; } flag_conv;
237         flag_conv flags[] = {{ "PASS_MACHINE_TRUST_NT", PASS_MACHINE_TRUST_NT  },
238                              { "PASS_SERVER_TRUST_NT",  PASS_SERVER_TRUST_NT   },
239                              { "PASS_DOMAIN_TRUST_NT",  PASS_DOMAIN_TRUST_NT   },
240                              { "PASS_MACHINE_TRUST_ADS",PASS_MACHINE_TRUST_ADS },
241                              { "PASS_DOMAIN_TRUST_ADS", PASS_DOMAIN_TRUST_ADS  }};
242         int i;
243
244         for (i = 0; i < flag_num; i++) {
245                 if (!StrCaseCmp(flags[i].name, flag_name)) {
246                         return flags[i].val;
247                 }
248         }
249                 
250         return 0;
251 }
252
253
254 static char* trustpw_flag_name(const int val)
255 {
256         const int flag_num = 5;
257         typedef struct { const char *name; int val; } flag_conv;
258         flag_conv flags[] = {{ "PASS_MACHINE_TRUST_NT", PASS_MACHINE_TRUST_NT  },
259                              { "PASS_SERVER_TRUST_NT",  PASS_SERVER_TRUST_NT   },
260                              { "PASS_DOMAIN_TRUST_NT",  PASS_DOMAIN_TRUST_NT   },
261                              { "PASS_MACHINE_TRUST_ADS",PASS_MACHINE_TRUST_ADS },
262                              { "PASS_DOMAIN_TRUST_ADS", PASS_DOMAIN_TRUST_ADS  }};
263         int i;
264         
265         for (i = 0; i < flag_num; i++) {
266                 if (flags[i].val == val) {
267                         return strdup(flags[i].name);
268                 }
269         }
270         
271         return strdup("unknown flag");
272 }
273
274
275 static int print_trustpw_info(TALLOC_CTX *mem_ctx, SAM_TRUST_PASSWD *trust, BOOL verbose)
276 {
277         char *dom_name;
278         if (!mem_ctx || !trust) return -1;
279
280         /* convert unicode domain name to char* */
281         if (!pull_ucs2_talloc(mem_ctx, &dom_name, trust->private.uni_name)) return -1;
282         dom_name[trust->private.uni_name_len] = 0;
283
284         /* different output depending on level of verbosity */
285         if (verbose) {
286                 printf("Domain name:          %s\n", dom_name);
287                 printf("Domain SID:           %s\n", sid_string_static(&trust->private.domain_sid));
288                 printf("Trust password        %s\n", trust->private.pass);
289                 printf("Trust type:           %s\n", trustpw_flag_name(trust->private.flags));
290                 printf("Last modified         %s\n", trust->private.mod_time ? http_timestring(trust->private.mod_time) : "0");
291         
292         } else {
293                 printf("%s:%s\n", dom_name, sid_string_static(&trust->private.domain_sid));
294         }
295         
296         return 0;
297 }
298
299
300 static int print_trust_info(struct pdb_context *in, const char *name, BOOL verbose, BOOL smbpwdstyle)
301 {
302         SAM_TRUST_PASSWD trust;
303         TALLOC_CTX *mem_ctx = NULL;
304         
305         mem_ctx = talloc_init("pdbedit: trust passwords listing");
306         
307         if (NT_STATUS_IS_OK(in->pdb_gettrustpwnam(in, &trust, name))) {
308                 return print_trustpw_info(mem_ctx, &trust, verbose);
309         }
310         
311         return -1;
312 }
313         
314 /*********************************************************
315  List Users
316 **********************************************************/
317 static int print_users_list (struct pdb_context *in, BOOL verbosity, BOOL smbpwdstyle)
318 {
319         SAM_ACCOUNT *sam_pwent=NULL;
320         BOOL check, ret;
321         
322         check = NT_STATUS_IS_OK(in->pdb_setsampwent(in, False));
323         if (!check) {
324                 return 1;
325         }
326
327         check = True;
328         if (!(NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent)))) return 1;
329
330         while (check && (ret = NT_STATUS_IS_OK(in->pdb_getsampwent (in, sam_pwent)))) {
331                 if (verbosity)
332                         printf ("---------------\n");
333                 print_sam_info (sam_pwent, verbosity, smbpwdstyle);
334                 pdb_free_sam(&sam_pwent);
335                 check = NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent));
336         }
337         if (check) pdb_free_sam(&sam_pwent);
338         
339         in->pdb_endsampwent(in);
340         return 0;
341 }
342
343 /**
344  * List trust passwords
345  * 
346  * @param in initialised pdb context
347  * @param verbose turn on/off verbose mode
348  * @param smbpwdstyle ignored here (there was no trust passwords in smbpasswd file)
349  * @return 0 on success, otherwise failure
350  **/
351  
352 static int print_trustpw_list(struct pdb_context *in, BOOL verbose, BOOL smbpwdstyle)
353 {
354         SAM_TRUST_PASSWD trust;
355         TALLOC_CTX *mem_ctx = NULL;
356         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
357         
358         /* start enumeration and initialise memory context */
359         status = in->pdb_settrustpwent(in);
360         if (NT_STATUS_IS_ERR(status)) return -1;
361         mem_ctx = talloc_init("pdbedit: trust passwords listing");
362         
363         /* small separation to make it clear these are not regular accounts */
364         if (!verbose) printf("---\n");
365         
366         do {
367                 /* fetch next trust password */
368                 status = in->pdb_gettrustpwent(in, &trust);
369
370                 if (trust.private.uni_name_len) {
371                         /* print trust password info */
372                         if (verbose) printf ("---------------\n");
373                         print_trustpw_info(mem_ctx, &trust, verbose);
374                 }
375
376         } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES) || NT_STATUS_EQUAL(status, NT_STATUS_OK));
377         
378         talloc_destroy(mem_ctx);
379         return 0;
380 }
381
382
383 /*********************************************************
384  Fix a list of Users for uninitialised passwords
385 **********************************************************/
386 static int fix_users_list (struct pdb_context *in)
387 {
388         SAM_ACCOUNT *sam_pwent=NULL;
389         BOOL check, ret;
390         
391         check = NT_STATUS_IS_OK(in->pdb_setsampwent(in, False));
392         if (!check) {
393                 return 1;
394         }
395
396         check = True;
397         if (!(NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent)))) return 1;
398
399         while (check && (ret = NT_STATUS_IS_OK(in->pdb_getsampwent (in, sam_pwent)))) {
400                 printf("Updating record for user %s\n", pdb_get_username(sam_pwent));
401         
402                 if (!pdb_update_sam_account(sam_pwent)) {
403                         printf("Update of user %s failed!\n", pdb_get_username(sam_pwent));
404                 }
405                 pdb_free_sam(&sam_pwent);
406                 check = NT_STATUS_IS_OK(pdb_init_sam(&sam_pwent));
407                 if (!check) {
408                         fprintf(stderr, "Failed to initialise new SAM_ACCOUNT structure (out of memory?)\n");
409                 }
410                         
411         }
412         if (check) pdb_free_sam(&sam_pwent);
413         
414         in->pdb_endsampwent(in);
415         return 0;
416 }
417
418 /*********************************************************
419  Set User Info
420 **********************************************************/
421
422 static int set_user_info (struct pdb_context *in, const char *username, 
423                           const char *fullname, const char *homedir, 
424                           const char *drive, const char *script, 
425                           const char *profile, const char *account_control,
426                           const char *user_sid, const char *group_sid,
427                           const BOOL badpw)
428 {
429         SAM_ACCOUNT *sam_pwent=NULL;
430         BOOL ret;
431         
432         pdb_init_sam(&sam_pwent);
433         
434         ret = NT_STATUS_IS_OK(in->pdb_getsampwnam (in, sam_pwent, username));
435         if (ret==False) {
436                 fprintf (stderr, "Username not found!\n");
437                 pdb_free_sam(&sam_pwent);
438                 return -1;
439         }
440         
441         if (fullname)
442                 pdb_set_fullname(sam_pwent, fullname, PDB_CHANGED);
443         if (homedir)
444                 pdb_set_homedir(sam_pwent, homedir, PDB_CHANGED);
445         if (drive)
446                 pdb_set_dir_drive(sam_pwent,drive, PDB_CHANGED);
447         if (script)
448                 pdb_set_logon_script(sam_pwent, script, PDB_CHANGED);
449         if (profile)
450                 pdb_set_profile_path (sam_pwent, profile, PDB_CHANGED);
451
452         if (account_control) {
453                 uint16 not_settable = ~(ACB_DISABLED|ACB_HOMDIRREQ|ACB_PWNOTREQ|
454                                         ACB_PWNOEXP|ACB_AUTOLOCK);
455
456                 uint16 newflag = pdb_decode_acct_ctrl(account_control);
457
458                 if (newflag & not_settable) {
459                         fprintf(stderr, "Can only set [NDHLX] flags\n");
460                         pdb_free_sam(&sam_pwent);
461                         return -1;
462                 }
463
464                 pdb_set_acct_ctrl(sam_pwent,
465                                   (pdb_get_acct_ctrl(sam_pwent) & not_settable) | newflag,
466                                   PDB_CHANGED);
467         }
468         if (user_sid) {
469                 DOM_SID u_sid;
470                 if (!string_to_sid(&u_sid, user_sid)) {
471                         /* not a complete sid, may be a RID, try building a SID */
472                         int u_rid;
473                         
474                         if (sscanf(user_sid, "%d", &u_rid) != 1) {
475                                 fprintf(stderr, "Error passed string is not a complete user SID or RID!\n");
476                                 return -1;
477                         }
478                         sid_copy(&u_sid, get_global_sam_sid());
479                         sid_append_rid(&u_sid, u_rid);
480                 }
481                 pdb_set_user_sid (sam_pwent, &u_sid, PDB_CHANGED);
482         }
483         if (group_sid) {
484                 DOM_SID g_sid;
485                 if (!string_to_sid(&g_sid, group_sid)) {
486                         /* not a complete sid, may be a RID, try building a SID */
487                         int g_rid;
488                         
489                         if (sscanf(group_sid, "%d", &g_rid) != 1) {
490                                 fprintf(stderr, "Error passed string is not a complete group SID or RID!\n");
491                                 return -1;
492                         }
493                         sid_copy(&g_sid, get_global_sam_sid());
494                         sid_append_rid(&g_sid, g_rid);
495                 }
496                 pdb_set_group_sid (sam_pwent, &g_sid, PDB_CHANGED);
497         }
498
499         if (badpw) {
500                 pdb_set_bad_password_count(sam_pwent, 0, PDB_CHANGED);
501                 pdb_set_bad_password_time(sam_pwent, 0, PDB_CHANGED);
502         }
503         
504         if (NT_STATUS_IS_OK(in->pdb_update_sam_account (in, sam_pwent)))
505                 print_user_info (in, username, True, False);
506         else {
507                 fprintf (stderr, "Unable to modify entry!\n");
508                 pdb_free_sam(&sam_pwent);
509                 return -1;
510         }
511         pdb_free_sam(&sam_pwent);
512         return 0;
513 }
514
515 /*********************************************************
516  Add New User
517 **********************************************************/
518 static int new_user (struct pdb_context *in, const char *username,
519                         const char *fullname, const char *homedir,
520                         const char *drive, const char *script,
521                         const char *profile, char *user_sid, char *group_sid)
522 {
523         SAM_ACCOUNT *sam_pwent=NULL;
524         NTSTATUS nt_status;
525         char *password1, *password2, *staticpass;
526         
527         get_global_sam_sid();
528
529         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_new(&sam_pwent, username, 0))) {
530                 DEBUG(0, ("could not create account to add new user %s\n", username));
531                 return -1;
532         }
533
534         staticpass = getpass("new password:");
535         password1 = strdup(staticpass);
536         memset(staticpass, 0, strlen(staticpass));
537         staticpass = getpass("retype new password:");
538         password2 = strdup(staticpass);
539         memset(staticpass, 0, strlen(staticpass));
540         if (strcmp (password1, password2)) {
541                 fprintf (stderr, "Passwords does not match!\n");
542                 memset(password1, 0, strlen(password1));
543                 SAFE_FREE(password1);
544                 memset(password2, 0, strlen(password2));
545                 SAFE_FREE(password2);
546                 pdb_free_sam (&sam_pwent);
547                 return -1;
548         }
549
550         pdb_set_plaintext_passwd(sam_pwent, password1);
551         memset(password1, 0, strlen(password1));
552         SAFE_FREE(password1);
553         memset(password2, 0, strlen(password2));
554         SAFE_FREE(password2);
555
556         if (fullname)
557                 pdb_set_fullname(sam_pwent, fullname, PDB_CHANGED);
558         if (homedir)
559                 pdb_set_homedir (sam_pwent, homedir, PDB_CHANGED);
560         if (drive)
561                 pdb_set_dir_drive (sam_pwent, drive, PDB_CHANGED);
562         if (script)
563                 pdb_set_logon_script(sam_pwent, script, PDB_CHANGED);
564         if (profile)
565                 pdb_set_profile_path (sam_pwent, profile, PDB_CHANGED);
566         if (user_sid) {
567                 DOM_SID u_sid;
568                 if (!string_to_sid(&u_sid, user_sid)) {
569                         /* not a complete sid, may be a RID, try building a SID */
570                         int u_rid;
571                         
572                         if (sscanf(user_sid, "%d", &u_rid) != 1) {
573                                 fprintf(stderr, "Error passed string is not a complete user SID or RID!\n");
574                                 return -1;
575                         }
576                         sid_copy(&u_sid, get_global_sam_sid());
577                         sid_append_rid(&u_sid, u_rid);
578                 }
579                 pdb_set_user_sid (sam_pwent, &u_sid, PDB_CHANGED);
580         }
581         if (group_sid) {
582                 DOM_SID g_sid;
583                 if (!string_to_sid(&g_sid, group_sid)) {
584                         /* not a complete sid, may be a RID, try building a SID */
585                         int g_rid;
586                         
587                         if (sscanf(group_sid, "%d", &g_rid) != 1) {
588                                 fprintf(stderr, "Error passed string is not a complete group SID or RID!\n");
589                                 return -1;
590                         }
591                         sid_copy(&g_sid, get_global_sam_sid());
592                         sid_append_rid(&g_sid, g_rid);
593                 }
594                 pdb_set_group_sid (sam_pwent, &g_sid, PDB_CHANGED);
595         }
596         
597         pdb_set_acct_ctrl (sam_pwent, ACB_NORMAL, PDB_CHANGED);
598         
599         if (NT_STATUS_IS_OK(in->pdb_add_sam_account (in, sam_pwent))) { 
600                 print_user_info (in, username, True, False);
601         } else {
602                 fprintf (stderr, "Unable to add user! (does it already exist?)\n");
603                 pdb_free_sam (&sam_pwent);
604                 return -1;
605         }
606         pdb_free_sam (&sam_pwent);
607         return 0;
608 }
609
610 /*********************************************************
611  Add New Machine
612 **********************************************************/
613
614 static int new_machine (struct pdb_context *in, const char *machine_in)
615 {
616         SAM_ACCOUNT *sam_pwent=NULL;
617         fstring machinename;
618         fstring machineaccount;
619         struct passwd  *pwd = NULL;
620         
621         get_global_sam_sid();
622
623         fstrcpy(machinename, machine_in); 
624         machinename[15]= '\0';
625
626         if (machinename[strlen (machinename) -1] == '$')
627                 machinename[strlen (machinename) -1] = '\0';
628         
629         strlower_m(machinename);
630         
631         fstrcpy(machineaccount, machinename);
632         fstrcat(machineaccount, "$");
633
634         if ((pwd = getpwnam_alloc(machineaccount))) {
635                 if (!NT_STATUS_IS_OK(pdb_init_sam_pw( &sam_pwent, pwd))) {
636                         fprintf(stderr, "Could not init sam from pw\n");
637                         passwd_free(&pwd);
638                         return -1;
639                 }
640                 passwd_free(&pwd);
641         } else {
642                 if (!NT_STATUS_IS_OK(pdb_init_sam (&sam_pwent))) {
643                         fprintf(stderr, "Could not init sam from pw\n");
644                         return -1;
645                 }
646         }
647
648         pdb_set_plaintext_passwd (sam_pwent, machinename);
649
650         pdb_set_username (sam_pwent, machineaccount, PDB_CHANGED);
651         
652         pdb_set_acct_ctrl (sam_pwent, ACB_WSTRUST, PDB_CHANGED);
653         
654         pdb_set_group_sid_from_rid(sam_pwent, DOMAIN_GROUP_RID_COMPUTERS, PDB_CHANGED);
655         
656         if (NT_STATUS_IS_OK(in->pdb_add_sam_account (in, sam_pwent))) {
657                 print_user_info (in, machineaccount, True, False);
658         } else {
659                 fprintf (stderr, "Unable to add machine! (does it already exist?)\n");
660                 pdb_free_sam (&sam_pwent);
661                 return -1;
662         }
663         pdb_free_sam (&sam_pwent);
664         return 0;
665 }
666
667
668 /**
669  * Add new trusting domain account
670  *
671  * @param in initialised pdb_context
672  * @param dom_name trusted domain name given in command line
673  *
674  * @return 0 on success, -1 otherwise
675  **/
676  
677 static int new_trustdom(struct pdb_context *in, const char *dom_name)
678 {
679         /* TODO */
680         return -1;
681 }
682
683
684 /**
685  * Add new trust relationship password
686  *
687  * @param in initialised pdb_context
688  * @param dom_name trusting domain name given in command line
689  * @param dom_sid domain sid given in command line
690  * @param flag trust password type flag given in command line
691  *
692  * @return 0 on success, -1 otherwise
693  **/
694
695 static int new_trustpw(struct pdb_context *in, const char *dom_name,
696                        const char *dom_sid, const char* flag)
697 {
698         TALLOC_CTX *mem_ctx = NULL;
699         SAM_TRUST_PASSWD trust;
700         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
701         POLICY_HND connect_hnd;
702         DOM_SID *domain_sid = NULL;
703         smb_ucs2_t *uni_name = NULL;
704         char *givenpass, *domain_name = NULL;
705         struct in_addr srv_ip;
706         fstring srv_name, myname;
707         struct cli_state *cli;
708         time_t lct;
709         
710         if (!dom_name) return -1;
711         
712         mem_ctx = talloc_init("pdbedit: adding new trust password");
713         
714         /* unicode name */
715         trust.private.uni_name_len = strnlen(dom_name, 32);
716         push_ucs2_talloc(mem_ctx, &uni_name, dom_name);
717         strncpy_w(trust.private.uni_name, uni_name, 32);
718         
719         /* flags */
720         trust.private.flags = trustpw_flag(flag);
721
722         /* trusting SID */
723         if (!dom_sid) {
724                 /* if sid is not specified in command line, do our best
725                    to establish it */
726
727                 /* find domain PDC */
728                 if (!get_pdc_ip(dom_name, &srv_ip))
729                         return -1;
730                 if (is_zero_ip(srv_ip))
731                         return -1;
732                 if (!name_status_find(dom_name, 0x1b, 0x20, srv_ip, srv_name))
733                         return -1;
734                         
735                 get_myname(myname);
736                         
737                 /* Connect the domain pdc...  */
738                 nt_status = cli_full_connection(&cli, myname, srv_name, &srv_ip, 139,
739                                                 "IPC$", "IPC", "", "", "", 0, Undefined, NULL);
740                 if (NT_STATUS_IS_ERR(nt_status))
741                         return -1;
742                 if (!cli_nt_session_open(cli, PI_LSARPC))
743                         return -1;
744                 
745                 /* ...and query the domain sid */
746                 nt_status = cli_lsa_open_policy2(cli, mem_ctx, True, SEC_RIGHTS_QUERY_VALUE,
747                                                  &connect_hnd);
748                 if (NT_STATUS_IS_ERR(nt_status)) return -1;
749
750                 nt_status = cli_lsa_query_info_policy(cli, mem_ctx, &connect_hnd,
751                                                       5, &domain_name, &domain_sid);
752                 if (NT_STATUS_IS_ERR(nt_status)) return -1;
753                 
754                 nt_status = cli_lsa_close(cli, mem_ctx, &connect_hnd);
755                 if (NT_STATUS_IS_ERR(nt_status)) return -1;
756                 
757                 cli_nt_session_close(cli);
758                 cli_shutdown(cli);
759                 
760                 /* copying sid to trust password structure */
761                 sid_copy(&trust.private.domain_sid, domain_sid);
762                         
763         } else {
764                 if (!string_to_sid(&trust.private.domain_sid, dom_sid)) {
765                         printf("Error: wrong SID specified !\n");
766                         return -1;
767                 }
768         }
769                 
770         /* password */
771         givenpass = getpass("password:");
772         memset(trust.private.pass, '\0', FSTRING_LEN);
773         strncpy(trust.private.pass, givenpass, FSTRING_LEN);
774         
775         /* last change time */
776         lct = time(NULL);
777         trust.private.mod_time = lct;
778         
779         /* store trust password in passdb */
780         nt_status = in->pdb_add_trust_passwd(in, &trust);
781                         
782         talloc_destroy(mem_ctx);
783         if (NT_STATUS_IS_OK(nt_status))
784                 return 0;
785         
786         return -1;
787 }
788
789
790 /*********************************************************
791  Delete user entry
792 **********************************************************/
793
794 static int delete_user_entry (struct pdb_context *in, const char *username)
795 {
796         SAM_ACCOUNT *samaccount = NULL;
797
798         if (!NT_STATUS_IS_OK(pdb_init_sam (&samaccount))) {
799                 return -1;
800         }
801
802         if (!NT_STATUS_IS_OK(in->pdb_getsampwnam(in, samaccount, username))) {
803                 fprintf (stderr, "user %s does not exist in the passdb\n", username);
804                 return -1;
805         }
806
807         if (!NT_STATUS_IS_OK(in->pdb_delete_sam_account (in, samaccount))) {
808                 fprintf (stderr, "Unable to delete user %s\n", username);
809                 return -1;
810         }
811         return 0;
812 }
813
814 /*********************************************************
815  Delete machine entry
816 **********************************************************/
817
818 static int delete_machine_entry (struct pdb_context *in, const char *machinename)
819 {
820         fstring name;
821         SAM_ACCOUNT *samaccount = NULL;
822         
823         fstrcpy(name, machinename);
824         name[15] = '\0';
825         if (name[strlen(name)-1] != '$')
826                 fstrcat (name, "$");
827
828         if (!NT_STATUS_IS_OK(pdb_init_sam (&samaccount))) {
829                 return -1;
830         }
831
832         if (!NT_STATUS_IS_OK(in->pdb_getsampwnam(in, samaccount, name))) {
833                 fprintf (stderr, "machine %s does not exist in the passdb\n", name);
834                 return -1;
835         }
836
837         if (!NT_STATUS_IS_OK(in->pdb_delete_sam_account (in, samaccount))) {
838                 fprintf (stderr, "Unable to delete machine %s\n", name);
839                 return -1;
840         }
841
842         return 0;
843 }
844
845 /*********************************************************
846  Start here.
847 **********************************************************/
848
849 int main (int argc, char **argv)
850 {
851         static BOOL list_users = False;
852         static BOOL verbose = False;
853         static BOOL spstyle = False;
854         static BOOL machine = False;
855         static BOOL trustdom = False;
856         static BOOL add_user = False;
857         static BOOL delete_user = False;
858         static BOOL modify_user = False;
859         uint32  setparms, checkparms;
860         int opt;
861         static char *full_name = NULL;
862         static const char *user_name = NULL;
863         static char *home_dir = NULL;
864         static char *home_drive = NULL;
865         static char *backend = NULL;
866         static char *backend_in = NULL;
867         static char *backend_out = NULL;
868         static BOOL transfer_groups = False;
869         static BOOL  force_initialised_password = False;
870         static char *logon_script = NULL;
871         static char *profile_path = NULL;
872         static char *account_control = NULL;
873         static char *account_policy = NULL;
874         static char *user_sid = NULL;
875         static char *group_sid = NULL;
876         static long int account_policy_value = 0;
877         BOOL account_policy_value_set = False;
878         static BOOL badpw_reset = False;
879         /* trust password parameters */
880         static char *trustpw = NULL;
881         static char *trustsid = NULL;
882         static char *trustflags = NULL;
883
884         struct pdb_context *bin;
885         struct pdb_context *bout;
886         struct pdb_context *bdef;
887         poptContext pc;
888         struct poptOption long_options[] = {
889                 POPT_AUTOHELP
890                 {"list",        'L', POPT_ARG_NONE, &list_users, 0, "list all users", NULL},
891                 {"verbose",     'v', POPT_ARG_NONE, &verbose, 0, "be verbose", NULL },
892                 {"smbpasswd-style",     'w',POPT_ARG_NONE, &spstyle, 0, "give output in smbpasswd style", NULL},
893                 {"user",        'u', POPT_ARG_STRING, &user_name, 0, "use username", "USER" },
894                 {"fullname",    'f', POPT_ARG_STRING, &full_name, 0, "set full name", NULL},
895                 {"homedir",     'h', POPT_ARG_STRING, &home_dir, 0, "set home directory", NULL},
896                 {"drive",       'D', POPT_ARG_STRING, &home_drive, 0, "set home drive", NULL},
897                 {"script",      'S', POPT_ARG_STRING, &logon_script, 0, "set logon script", NULL},
898                 {"profile",     'p', POPT_ARG_STRING, &profile_path, 0, "set profile path", NULL},
899                 {"user SID",    'U', POPT_ARG_STRING, &user_sid, 0, "set user SID or RID", NULL},
900                 {"group SID",   'G', POPT_ARG_STRING, &group_sid, 0, "set group SID or RID", NULL},
901                 {"create",      'a', POPT_ARG_NONE, &add_user, 0, "create user", NULL},
902                 {"modify",      'r', POPT_ARG_NONE, &modify_user, 0, "modify user", NULL},
903                 {"delete",      'x', POPT_ARG_NONE, &delete_user, 0, "delete user", NULL},
904                 {"machine",     'm', POPT_ARG_NONE, &machine, 0, "account is a machine account", NULL},
905                 {"trustdom",    'I', POPT_ARG_NONE, &trustdom, 0, "account is a domain trust account", NULL},
906                 {"trustpw",     'N', POPT_ARG_STRING, &trustpw, 0, "trust password's domain name", NULL},
907                 {"trustsid",    'T', POPT_ARG_STRING, &trustsid, 0, "trust password's domain sid", NULL},
908                 {"trustflags",  'F', POPT_ARG_STRING, &trustflags, 0, "trust password flags", NULL},
909                 {"backend",     'b', POPT_ARG_STRING, &backend, 0, "use different passdb backend as default backend", NULL},
910                 {"import",      'i', POPT_ARG_STRING, &backend_in, 0, "import user accounts from this backend", NULL},
911                 {"export",      'e', POPT_ARG_STRING, &backend_out, 0, "export user accounts to this backend", NULL},
912                 {"group",       'g', POPT_ARG_NONE, &transfer_groups, 0, "use -i and -e for groups", NULL},
913                 {"account-policy",      'P', POPT_ARG_STRING, &account_policy, 0,"value of an account policy (like maximum password age)",NULL},
914                 {"value",       'C', POPT_ARG_LONG, &account_policy_value, 'C',"set the account policy to this value", NULL},
915                 {"account-control",     'c', POPT_ARG_STRING, &account_control, 0, "Values of account control", NULL},
916                 {"force-initialized-passwords", 0, POPT_ARG_NONE, &force_initialised_password, 0, "Force initialization of corrupt password strings in a passdb backend", NULL},
917                 {"bad-password-count-reset", 'z', POPT_ARG_NONE, &badpw_reset, 0, "reset bad password count", NULL},
918                 POPT_COMMON_SAMBA
919                 POPT_TABLEEND
920         };
921         
922         setup_logging("pdbedit", True);
923         
924         pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
925                             POPT_CONTEXT_KEEP_FIRST);
926         
927         while((opt = poptGetNextOpt(pc)) != -1) {
928                 switch (opt) {
929                 case 'C':
930                         account_policy_value_set = True;
931                         break;
932                 }
933         }
934
935         poptGetArg(pc); /* Drop argv[0], the program name */
936
937         if (user_name == NULL)
938                 user_name = poptGetArg(pc);
939
940         if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
941                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", dyn_CONFIGFILE);
942                 exit(1);
943         }
944
945         if(!initialize_password_db(False))
946                 exit(1);
947
948         if (!init_names())
949                 exit(1);
950
951         setparms =      (backend ? BIT_BACKEND : 0) +
952                         (verbose ? BIT_VERBOSE : 0) +
953                         (spstyle ? BIT_SPSTYLE : 0) +
954                         (full_name ? BIT_FULLNAME : 0) +
955                         (home_dir ? BIT_HOMEDIR : 0) +
956                         (home_drive ? BIT_HDIRDRIVE : 0) +
957                         (logon_script ? BIT_LOGSCRIPT : 0) +
958                         (profile_path ? BIT_PROFILE : 0) +
959                         (machine ? BIT_MACHINE : 0) +
960                         (trustdom ? BIT_TRUSTDOM : 0) +
961                         (trustpw ? BIT_TRUSTPW : 0) +
962                         (trustsid ? BIT_TRUSTSID : 0) +
963                         (trustflags ? BIT_TRUSTFLAGS : 0) +
964                         (user_name ? BIT_USER : 0) +
965                         (list_users ? BIT_LIST : 0) +
966                         (force_initialised_password ? BIT_FIX_INIT : 0) +
967                         (modify_user ? BIT_MODIFY : 0) +
968                         (add_user ? BIT_CREATE : 0) +
969                         (delete_user ? BIT_DELETE : 0) +
970                         (account_control ? BIT_ACCTCTRL : 0) +
971                         (account_policy ? BIT_ACCPOLICY : 0) +
972                         (account_policy_value_set ? BIT_ACCPOLVAL : 0) +
973                         (backend_in ? BIT_IMPORT : 0) +
974                         (backend_out ? BIT_EXPORT : 0) +
975                         (badpw_reset ? BIT_BADPWRESET : 0);
976
977         if (setparms & BIT_BACKEND) {
978                 if (!NT_STATUS_IS_OK(make_pdb_context_string(&bdef, backend))) {
979                         fprintf(stderr, "Can't initialize passdb backend.\n");
980                         return 1;
981                 }
982         } else {
983                 if (!NT_STATUS_IS_OK(make_pdb_context_list(&bdef, lp_passdb_backend()))) {
984                         fprintf(stderr, "Can't initialize passdb backend.\n");
985                         return 1;
986                 }
987         }
988         
989         /* the lowest bit options are always accepted */
990         checkparms = setparms & ~MASK_ALWAYS_GOOD;
991
992         if (checkparms & BIT_FIX_INIT) {
993                 return fix_users_list(bdef);
994         }
995
996         /* account policy operations */
997         if ((checkparms & BIT_ACCPOLICY) && !(checkparms & ~(BIT_ACCPOLICY + BIT_ACCPOLVAL))) {
998                 uint32 value;
999                 int field = account_policy_name_to_fieldnum(account_policy);
1000                 if (field == 0) {
1001                         fprintf(stderr, "No account policy by that name\n");
1002                         exit(1);
1003                 }
1004                 if (!account_policy_get(field, &value)) {
1005                         fprintf(stderr, "valid account policy, but unable to fetch value!\n");
1006                         exit(1);
1007                 }
1008                 if (account_policy_value_set) {
1009                         printf("account policy value for %s was %u\n", account_policy, value);
1010                         if (!account_policy_set(field, account_policy_value)) {
1011                                 fprintf(stderr, "valid account policy, but unable to set value!\n");
1012                                 exit(1);
1013                         }
1014                         printf("account policy value for %s is now %lu\n", account_policy, account_policy_value);
1015                         exit(0);
1016                 } else {
1017                         printf("account policy value for %s is %u\n", account_policy, value);
1018                         exit(0);
1019                 }
1020         }
1021
1022         /* import and export operations */
1023         if (((checkparms & BIT_IMPORT) || (checkparms & BIT_EXPORT))
1024                         && !(checkparms & ~(BIT_IMPORT +BIT_EXPORT))) {
1025                 if (backend_in) {
1026                         if (!NT_STATUS_IS_OK(make_pdb_context_string(&bin, backend_in))) {
1027                                 fprintf(stderr, "Can't initialize passdb backend.\n");
1028                                 return 1;
1029                         }
1030                 } else {
1031                         bin = bdef;
1032                 }
1033                 if (backend_out) {
1034                         if (!NT_STATUS_IS_OK(make_pdb_context_string(&bout, backend_out))) {
1035                                 fprintf(stderr, "Can't initialize %s.\n", backend_out);
1036                                 return 1;
1037                         }
1038                 } else {
1039                         bout = bdef;
1040                 }
1041                 if (transfer_groups) {
1042                         return export_groups(bin, bout);
1043                 } else {
1044                         return export_database(bin, bout);
1045                 }
1046         }
1047
1048         /* if BIT_USER is defined but nothing else then threat it as -l -u for compatibility */
1049         /* fake up BIT_LIST if only BIT_USER is defined */
1050         if ((checkparms & BIT_USER) && !(checkparms & ~BIT_USER)) {
1051                 checkparms += BIT_LIST;
1052         }
1053         
1054         /* modify flag is optional to maintain backwards compatibility */
1055         /* fake up BIT_MODIFY if BIT_USER  and at least one of MASK_USER_GOOD is defined */
1056         if (!((checkparms & ~MASK_USER_GOOD) & ~BIT_USER) && (checkparms & MASK_USER_GOOD)) {
1057                 checkparms += BIT_MODIFY;
1058         }
1059
1060         /* list users operations */
1061         if (checkparms & BIT_LIST) {
1062                 if (!(checkparms & ~BIT_LIST)) {
1063                         print_users_list (bdef, verbose, spstyle);
1064                         return print_trustpw_list(bdef, verbose, spstyle);
1065                 }
1066                 if (!(checkparms & ~(BIT_USER + BIT_LIST))) {
1067                         return print_user_info (bdef, user_name, verbose, spstyle);
1068
1069                 } else if (!(checkparms & ~(BIT_TRUSTPW + BIT_LIST))) {
1070                         return print_trust_info(bdef, trustpw, verbose, spstyle);
1071                 }
1072         }
1073         
1074         /* mask out users options */
1075         checkparms &= ~MASK_USER_GOOD;
1076
1077         /* if bad password count is reset, we must be modifying */
1078         if (checkparms & BIT_BADPWRESET) {
1079                 checkparms |= BIT_MODIFY;
1080                 checkparms &= ~BIT_BADPWRESET;
1081         }
1082         
1083         /* account operation */
1084         if ((checkparms & BIT_CREATE) || (checkparms & BIT_MODIFY) || (checkparms & BIT_DELETE)) {
1085                 /* check use of -u option */
1086                 if (!(checkparms & (BIT_USER + BIT_TRUSTPW))) {
1087                         fprintf (stderr, "Username not specified! (use -u option)\n");
1088                         return -1;
1089                 }
1090
1091                 /* account creation operations */
1092                 if (!(checkparms & ~(BIT_CREATE + BIT_USER + BIT_MACHINE + BIT_TRUSTDOM))) {
1093                         /* machine trust account */
1094                         if (checkparms & BIT_MACHINE) {
1095                                 return new_machine (bdef, user_name);
1096                         /* interdomain trust account */
1097                         } else if (checkparms & BIT_TRUSTDOM) {
1098                                 return new_trustdom(bdef, user_name);
1099
1100                         /* ordinary user account */
1101                         } else {
1102                                 return new_user (bdef, user_name, full_name, home_dir, 
1103                                                  home_drive, logon_script, 
1104                                                  profile_path, user_sid, group_sid);
1105                         }
1106                 }
1107
1108                 /* account deletion operations */
1109                 if (!(checkparms & ~(BIT_DELETE + BIT_USER + BIT_MACHINE))) {
1110                         if (checkparms & BIT_MACHINE) {
1111                                 return delete_machine_entry (bdef, user_name);
1112                         } else {
1113                                 return delete_user_entry (bdef, user_name);
1114                         }
1115                 }
1116
1117                 /* account modification operations */
1118                 if (!(checkparms & ~(BIT_MODIFY + BIT_USER))) {
1119                         return set_user_info (bdef, user_name, full_name,
1120                                               home_dir,
1121                                               home_drive,
1122                                               logon_script,
1123                                               profile_path, account_control,
1124                                               user_sid, group_sid,
1125                                               badpw_reset);
1126                 }
1127         }
1128
1129         /* trust password operation */
1130         if ((checkparms & BIT_CREATE) || (checkparms & BIT_MODIFY) || (checkparms & BIT_DELETE)) {
1131                 /* trust password creation */
1132                 if (!(checkparms & ~(BIT_CREATE + BIT_TRUSTPW + BIT_TRUSTSID + BIT_TRUSTFLAGS))) {
1133                         return new_trustpw(bdef, trustpw, trustsid, trustflags);
1134                 }               
1135         }
1136         
1137         
1138         if (setparms >= 0x20) {
1139                 fprintf (stderr, "Incompatible or insufficient options on command line!\n");
1140         }
1141         poptPrintHelp(pc, stderr, 0);
1142
1143         return 1;
1144 }
1145