r53: Remove modifyTimestamp from list of our attributes. We just check it for
[vlendec/samba-autobuild/.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS mplementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau        1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23    
24 */
25
26 /* TODO:
27 *  persistent connections: if using NSS LDAP, many connections are made
28 *      however, using only one within Samba would be nice
29 *  
30 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
31 *
32 *  Other LDAP based login attributes: accountExpires, etc.
33 *  (should be the domain of Samba proper, but the sam_password/SAM_ACCOUNT
34 *  structures don't have fields for some of these attributes)
35 *
36 *  SSL is done, but can't get the certificate based authentication to work
37 *  against on my test platform (Linux 2.4, OpenLDAP 2.x)
38 */
39
40 /* NOTE: this will NOT work against an Active Directory server
41 *  due to the fact that the two password fields cannot be retrieved
42 *  from a server; recommend using security = domain in this situation
43 *  and/or winbind
44 */
45
46 #include "includes.h"
47
48 #undef DBGC_CLASS
49 #define DBGC_CLASS DBGC_PASSDB
50
51 #include <lber.h>
52 #include <ldap.h>
53
54 /*
55  * Work around versions of the LDAP client libs that don't have the OIDs
56  * defined, or have them defined under the old name.  
57  * This functionality is really a factor of the server, not the client 
58  *
59  */
60
61 #if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
62 #define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
63 #elif !defined(LDAP_EXOP_MODIFY_PASSWD)
64 #define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
65 #endif
66
67 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
68 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
69 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
70 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID        ((ber_tag_t) 0x80U)
71 #endif
72
73 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
74 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
75 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
76 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW       ((ber_tag_t) 0x82U)
77 #endif
78
79
80 #ifndef SAM_ACCOUNT
81 #define SAM_ACCOUNT struct sam_passwd
82 #endif
83
84 #define MODIFY_TIMESTAMP_STRING "modifyTimestamp"
85
86 #include "smbldap.h"
87
88 struct ldapsam_privates {
89         struct smbldap_state *smbldap_state;
90
91         /* Former statics */
92         LDAPMessage *result;
93         LDAPMessage *entry;
94         int index;
95         
96         const char *domain_name;
97         DOM_SID domain_sid;
98         
99         /* configuration items */
100         int schema_ver;
101 };
102
103 /**********************************************************************
104  Free a LDAPMessage (one is stored on the SAM_ACCOUNT).
105  **********************************************************************/
106  
107 static void private_data_free_fn(void **result) 
108 {
109         ldap_msgfree(*result);
110         *result = NULL;
111 }
112
113 /**********************************************************************
114  Get the attribute name given a user schame version.
115  **********************************************************************/
116  
117 static const char* get_userattr_key2string( int schema_ver, int key )
118 {
119         switch ( schema_ver ) {
120                 case SCHEMAVER_SAMBAACCOUNT:
121                         return get_attr_key2string( attrib_map_v22, key );
122                         
123                 case SCHEMAVER_SAMBASAMACCOUNT:
124                         return get_attr_key2string( attrib_map_v30, key );
125                         
126                 default:
127                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
128                         break;
129         }
130         return NULL;
131 }
132
133 /**********************************************************************
134  Return the list of attribute names given a user schema version.
135 **********************************************************************/
136
137 static char** get_userattr_list( int schema_ver )
138 {
139         switch ( schema_ver ) {
140                 case SCHEMAVER_SAMBAACCOUNT:
141                         return get_attr_list( attrib_map_v22 );
142                         
143                 case SCHEMAVER_SAMBASAMACCOUNT:
144                         return get_attr_list( attrib_map_v30 );
145                 default:
146                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
147                         break;
148         }
149         
150         return NULL;
151 }
152
153 /*******************************************************************
154  Generate the LDAP search filter for the objectclass based on the 
155  version of the schema we are using.
156 ******************************************************************/
157
158 static const char* get_objclass_filter( int schema_ver )
159 {
160         static fstring objclass_filter;
161         
162         switch( schema_ver ) {
163                 case SCHEMAVER_SAMBAACCOUNT:
164                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
165                         break;
166                 case SCHEMAVER_SAMBASAMACCOUNT:
167                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
168                         break;
169                 default:
170                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
171                         break;
172         }
173         
174         return objclass_filter; 
175 }
176
177 /*******************************************************************
178  Run the search by name.
179 ******************************************************************/
180
181 static int ldapsam_search_suffix_by_name (struct ldapsam_privates *ldap_state, 
182                                           const char *user,
183                                           LDAPMessage ** result, char **attr)
184 {
185         pstring filter;
186         char *escape_user = escape_ldap_string_alloc(user);
187
188         if (!escape_user) {
189                 return LDAP_NO_MEMORY;
190         }
191
192         /*
193          * in the filter expression, replace %u with the real name
194          * so in ldap filter, %u MUST exist :-)
195          */
196         pstr_sprintf(filter, "(&%s%s)", lp_ldap_filter(), 
197                 get_objclass_filter(ldap_state->schema_ver));
198
199         /* 
200          * have to use this here because $ is filtered out
201            * in pstring_sub
202          */
203         
204
205         all_string_sub(filter, "%u", escape_user, sizeof(pstring));
206         SAFE_FREE(escape_user);
207
208         return smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
209 }
210
211 /*******************************************************************
212  Run the search by rid.
213 ******************************************************************/
214
215 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state, 
216                                          uint32 rid, LDAPMessage ** result, 
217                                          char **attr)
218 {
219         pstring filter;
220         int rc;
221
222         pstr_sprintf(filter, "(&(rid=%i)%s)", rid, 
223                 get_objclass_filter(ldap_state->schema_ver));
224         
225         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
226         
227         return rc;
228 }
229
230 /*******************************************************************
231  Run the search by SID.
232 ******************************************************************/
233
234 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state, 
235                                          const DOM_SID *sid, LDAPMessage ** result, 
236                                          char **attr)
237 {
238         pstring filter;
239         int rc;
240         fstring sid_string;
241
242         pstr_sprintf(filter, "(&(%s=%s)%s)", 
243                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
244                 sid_to_string(sid_string, sid), 
245                 get_objclass_filter(ldap_state->schema_ver));
246                 
247         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
248         
249         return rc;
250 }
251
252 /*******************************************************************
253  Delete complete object or objectclass and attrs from
254  object found in search_result depending on lp_ldap_delete_dn
255 ******************************************************************/
256
257 static NTSTATUS ldapsam_delete_entry(struct ldapsam_privates *ldap_state,
258                                      LDAPMessage *result,
259                                      const char *objectclass,
260                                      char **attrs)
261 {
262         int rc;
263         LDAPMessage *entry = NULL;
264         LDAPMod **mods = NULL;
265         char *name, *dn;
266         BerElement *ptr = NULL;
267
268         rc = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
269
270         if (rc != 1) {
271                 DEBUG(0, ("ldapsam_delete_entry: Entry must exist exactly once!\n"));
272                 return NT_STATUS_UNSUCCESSFUL;
273         }
274
275         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
276         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
277         if (!dn) {
278                 return NT_STATUS_UNSUCCESSFUL;
279         }
280
281         if (lp_ldap_delete_dn()) {
282                 NTSTATUS ret = NT_STATUS_OK;
283                 rc = smbldap_delete(ldap_state->smbldap_state, dn);
284
285                 if (rc != LDAP_SUCCESS) {
286                         DEBUG(0, ("ldapsam_delete_entry: Could not delete object %s\n", dn));
287                         ret = NT_STATUS_UNSUCCESSFUL;
288                 }
289                 SAFE_FREE(dn);
290                 return ret;
291         }
292
293         /* Ok, delete only the SAM attributes */
294         
295         for (name = ldap_first_attribute(ldap_state->smbldap_state->ldap_struct, entry, &ptr);
296              name != NULL;
297              name = ldap_next_attribute(ldap_state->smbldap_state->ldap_struct, entry, ptr)) {
298                 char **attrib;
299
300                 /* We are only allowed to delete the attributes that
301                    really exist. */
302
303                 for (attrib = attrs; *attrib != NULL; attrib++) {
304                         if (StrCaseCmp(*attrib, name) == 0) {
305                                 DEBUG(10, ("ldapsam_delete_entry: deleting attribute %s\n", name));
306                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name, NULL);
307                         }
308                 }
309
310                 ldap_memfree(name);
311         }
312         
313         if (ptr != NULL) {
314                 ber_free(ptr, 0);
315         }
316         
317         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
318
319         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
320         ldap_mods_free(mods, True);
321
322         if (rc != LDAP_SUCCESS) {
323                 char *ld_error = NULL;
324                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
325                                 &ld_error);
326                 
327                 DEBUG(0, ("ldapsam_delete_entry: Could not delete attributes for %s, error: %s (%s)\n",
328                           dn, ldap_err2string(rc), ld_error?ld_error:"unknown"));
329                 SAFE_FREE(ld_error);
330                 SAFE_FREE(dn);
331                 return NT_STATUS_UNSUCCESSFUL;
332         }
333
334         SAFE_FREE(dn);
335         return NT_STATUS_OK;
336 }
337                   
338 /* New Interface is being implemented here */
339
340 #if 0   /* JERRY - not uesed anymore */
341
342 /**********************************************************************
343 Initialize SAM_ACCOUNT from an LDAP query (unix attributes only)
344 *********************************************************************/
345 static BOOL get_unix_attributes (struct ldapsam_privates *ldap_state, 
346                                 SAM_ACCOUNT * sampass,
347                                 LDAPMessage * entry,
348                                 gid_t *gid)
349 {
350         pstring  homedir;
351         pstring  temp;
352         char **ldap_values;
353         char **values;
354
355         if ((ldap_values = ldap_get_values (ldap_state->smbldap_state->ldap_struct, entry, "objectClass")) == NULL) {
356                 DEBUG (1, ("get_unix_attributes: no objectClass! \n"));
357                 return False;
358         }
359
360         for (values=ldap_values;*values;values++) {
361                 if (strequal(*values, LDAP_OBJ_POSIXACCOUNT )) {
362                         break;
363                 }
364         }
365         
366         if (!*values) { /*end of array, no posixAccount */
367                 DEBUG(10, ("user does not have %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
368                 ldap_value_free(ldap_values);
369                 return False;
370         }
371         ldap_value_free(ldap_values);
372
373         if ( !smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
374                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_UNIX_HOME), homedir) ) 
375         {
376                 return False;
377         }
378         
379         if ( !smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
380                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_GIDNUMBER), temp) )
381         {
382                 return False;
383         }
384         
385         *gid = (gid_t)atol(temp);
386
387         pdb_set_unix_homedir(sampass, homedir, PDB_SET);
388         
389         DEBUG(10, ("user has %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
390         
391         return True;
392 }
393
394 #endif
395
396 static time_t ldapsam_get_entry_timestamp(
397         struct ldapsam_privates *ldap_state,
398         LDAPMessage * entry)
399 {
400         pstring temp;   
401         struct tm tm;
402
403         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct,
404                                         entry, MODIFY_TIMESTAMP_STRING, temp)) 
405                 return (time_t) 0;
406
407         strptime(temp, "%Y%m%d%H%M%SZ", &tm);
408         tzset();
409         return timegm(&tm);
410 }
411
412 /**********************************************************************
413  Initialize SAM_ACCOUNT from an LDAP query.
414  (Based on init_sam_from_buffer in pdb_tdb.c)
415 *********************************************************************/
416
417 static BOOL init_sam_from_ldap (struct ldapsam_privates *ldap_state, 
418                                 SAM_ACCOUNT * sampass,
419                                 LDAPMessage * entry)
420 {
421         time_t  logon_time,
422                         logoff_time,
423                         kickoff_time,
424                         pass_last_set_time, 
425                         pass_can_change_time, 
426                         pass_must_change_time,
427                         ldap_entry_time,
428                         bad_password_time;
429         pstring         username, 
430                         domain,
431                         nt_username,
432                         fullname,
433                         homedir,
434                         dir_drive,
435                         logon_script,
436                         profile_path,
437                         acct_desc,
438                         workstations;
439         char            munged_dial[2048];
440         uint32          user_rid; 
441         uint8           smblmpwd[LM_HASH_LEN],
442                         smbntpwd[NT_HASH_LEN];
443         uint16          acct_ctrl = 0, 
444                         logon_divs;
445         uint16          bad_password_count = 0, 
446                         logon_count = 0;
447         uint32 hours_len;
448         uint8           hours[MAX_HOURS_LEN];
449         pstring temp;
450         LOGIN_CACHE     *cache_entry = NULL;
451
452         /*
453          * do a little initialization
454          */
455         username[0]     = '\0';
456         domain[0]       = '\0';
457         nt_username[0]  = '\0';
458         fullname[0]     = '\0';
459         homedir[0]      = '\0';
460         dir_drive[0]    = '\0';
461         logon_script[0] = '\0';
462         profile_path[0] = '\0';
463         acct_desc[0]    = '\0';
464         munged_dial[0]  = '\0';
465         workstations[0] = '\0';
466          
467
468         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
469                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
470                 return False;
471         }
472
473         if (ldap_state->smbldap_state->ldap_struct == NULL) {
474                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->ldap_struct is NULL!\n"));
475                 return False;
476         }
477         
478         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, "uid", username)) {
479                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for this user!\n"));
480                 return False;
481         }
482
483         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
484
485         pstrcpy(nt_username, username);
486
487         pstrcpy(domain, ldap_state->domain_name);
488         
489         pdb_set_username(sampass, username, PDB_SET);
490
491         pdb_set_domain(sampass, domain, PDB_DEFAULT);
492         pdb_set_nt_username(sampass, nt_username, PDB_SET);
493
494         /* deal with different attributes between the schema first */
495         
496         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
497                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
498                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), temp)) {
499                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
500                 }
501                 
502                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
503                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_SID), temp)) {
504                         pdb_set_group_sid_from_string(sampass, temp, PDB_SET);                  
505                 } else {
506                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
507                 }
508         } else {
509                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
510                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), temp)) {
511                         user_rid = (uint32)atol(temp);
512                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
513                 }
514                 
515                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
516                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_RID), temp)) {
517                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
518                 } else {
519                         uint32 group_rid;
520                         
521                         group_rid = (uint32)atol(temp);
522                         
523                         /* for some reason, we often have 0 as a primary group RID.
524                            Make sure that we treat this just as a 'default' value */
525                            
526                         if ( group_rid > 0 )
527                                 pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
528                         else
529                                 pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
530                 }
531         }
532
533         if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
534                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
535                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
536                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
537                         username));
538                 return False;
539         }
540
541         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
542                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), temp)) {
543                 /* leave as default */
544         } else {
545                 pass_last_set_time = (time_t) atol(temp);
546                 pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
547         }
548
549         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
550                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp)) {
551                 /* leave as default */
552         } else {
553                 logon_time = (time_t) atol(temp);
554                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
555         }
556
557         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
558                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp)) {
559                 /* leave as default */
560         } else {
561                 logoff_time = (time_t) atol(temp);
562                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
563         }
564
565         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
566                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp)) {
567                 /* leave as default */
568         } else {
569                 kickoff_time = (time_t) atol(temp);
570                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
571         }
572
573         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
574                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp)) {
575                 /* leave as default */
576         } else {
577                 pass_can_change_time = (time_t) atol(temp);
578                 pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
579         }
580
581         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
582                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp)) {    
583                 /* leave as default */
584         } else {
585                 pass_must_change_time = (time_t) atol(temp);
586                 pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
587         }
588
589         /* recommend that 'gecos' and 'displayName' should refer to the same
590          * attribute OID.  userFullName depreciated, only used by Samba
591          * primary rules of LDAP: don't make a new attribute when one is already defined
592          * that fits your needs; using cn then displayName rather than 'userFullName'
593          */
594
595         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
596                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), fullname)) {
597                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
598                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_CN), fullname)) {
599                         /* leave as default */
600                 } else {
601                         pdb_set_fullname(sampass, fullname, PDB_SET);
602                 }
603         } else {
604                 pdb_set_fullname(sampass, fullname, PDB_SET);
605         }
606
607         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
608                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), dir_drive)) 
609         {
610                 pdb_set_dir_drive( sampass, 
611                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_drive()),
612                         PDB_DEFAULT );
613         } else {
614                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
615         }
616
617         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
618                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), homedir)) 
619         {
620                 pdb_set_homedir( sampass, 
621                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_home()),
622                         PDB_DEFAULT );
623         } else {
624                 pdb_set_homedir(sampass, homedir, PDB_SET);
625         }
626
627         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
628                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), logon_script)) 
629         {
630                 pdb_set_logon_script( sampass, 
631                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_script()), 
632                         PDB_DEFAULT );
633         } else {
634                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
635         }
636
637         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
638                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), profile_path)) 
639         {
640                 pdb_set_profile_path( sampass, 
641                         talloc_sub_basic( sampass->mem_ctx, username, lp_logon_path()),
642                         PDB_DEFAULT );
643         } else {
644                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
645         }
646
647         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
648                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), acct_desc)) 
649         {
650                 /* leave as default */
651         } else {
652                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
653         }
654
655         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
656                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), workstations)) {
657                 /* leave as default */;
658         } else {
659                 pdb_set_workstations(sampass, workstations, PDB_SET);
660         }
661
662         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
663                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), munged_dial, sizeof(munged_dial))) {
664                 /* leave as default */;
665         } else {
666                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
667         }
668         
669         /* FIXME: hours stuff should be cleaner */
670         
671         logon_divs = 168;
672         hours_len = 21;
673         memset(hours, 0xff, hours_len);
674
675         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
676                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), temp)) {
677                 /* leave as default */
678         } else {
679                 pdb_gethexpwd(temp, smblmpwd);
680                 memset((char *)temp, '\0', strlen(temp)+1);
681                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
682                         return False;
683                 ZERO_STRUCT(smblmpwd);
684         }
685
686         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
687                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), temp)) {
688                 /* leave as default */
689         } else {
690                 pdb_gethexpwd(temp, smbntpwd);
691                 memset((char *)temp, '\0', strlen(temp)+1);
692                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
693                         return False;
694                 ZERO_STRUCT(smbntpwd);
695         }
696
697         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
698                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) {
699                 acct_ctrl |= ACB_NORMAL;
700         } else {
701                 acct_ctrl = pdb_decode_acct_ctrl(temp);
702
703                 if (acct_ctrl == 0)
704                         acct_ctrl |= ACB_NORMAL;
705
706                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
707         }
708
709         pdb_set_hours_len(sampass, hours_len, PDB_SET);
710         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
711
712 /*      pdb_set_munged_dial(sampass, munged_dial, PDB_SET); */
713         
714         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
715                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_COUNT), temp)) {
716                         /* leave as default */
717         } else {
718                 bad_password_count = (uint32) atol(temp);
719                 pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
720         }
721
722         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
723                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_TIME), temp)) {
724                 /* leave as default */
725         } else {
726                 bad_password_time = (time_t) atol(temp);
727                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
728         }
729
730
731         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
732                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_COUNT), temp)) {
733                         /* leave as default */
734         } else {
735                 logon_count = (uint32) atol(temp);
736                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
737         }
738
739         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
740
741         pdb_set_hours(sampass, hours, PDB_SET);
742
743         /* check the timestamp of the cache vs ldap entry */
744         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state, 
745                                                             entry)))
746                 return True;
747
748         /* see if we have newer updates */
749         if (!(cache_entry = login_cache_read(sampass))) {
750                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
751                            (unsigned int)pdb_get_bad_password_count(sampass),
752                            (unsigned int)pdb_get_bad_password_time(sampass)));
753                 return True;
754         }
755
756         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n", 
757                   (unsigned int)ldap_entry_time, (unsigned int)cache_entry->entry_timestamp, 
758                   (unsigned int)cache_entry->bad_password_time));
759
760         if (ldap_entry_time > cache_entry->entry_timestamp) {
761                 /* cache is older than directory , so
762                    we need to delete the entry but allow the 
763                    fields to be written out */
764                 login_cache_delentry(sampass);
765         } else {
766                 /* read cache in */
767                 pdb_set_acct_ctrl(sampass, 
768                                   pdb_get_acct_ctrl(sampass) | 
769                                   (cache_entry->acct_ctrl & ACB_AUTOLOCK),
770                                   PDB_SET);
771                 pdb_set_bad_password_count(sampass, 
772                                            cache_entry->bad_password_count, 
773                                            PDB_SET);
774                 pdb_set_bad_password_time(sampass, 
775                                           cache_entry->bad_password_time, 
776                                           PDB_SET);
777         }
778
779         SAFE_FREE(cache_entry);
780         return True;
781 }
782
783 /**********************************************************************
784  Initialize SAM_ACCOUNT from an LDAP query.
785  (Based on init_buffer_from_sam in pdb_tdb.c)
786 *********************************************************************/
787
788 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
789                                 LDAPMessage *existing,
790                                 LDAPMod *** mods, SAM_ACCOUNT * sampass,
791                                 BOOL (*need_update)(const SAM_ACCOUNT *,
792                                                     enum pdb_elements))
793 {
794         pstring temp;
795         uint32 rid;
796
797         if (mods == NULL || sampass == NULL) {
798                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
799                 return False;
800         }
801
802         *mods = NULL;
803
804         /* 
805          * took out adding "objectclass: sambaAccount"
806          * do this on a per-mod basis
807          */
808         if (need_update(sampass, PDB_USERNAME))
809                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
810                               "uid", pdb_get_username(sampass));
811
812         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
813
814         /* only update the RID if we actually need to */
815         if (need_update(sampass, PDB_USERSID)) {
816                 fstring sid_string;
817                 fstring dom_sid_string;
818                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
819                 
820                 switch ( ldap_state->schema_ver ) {
821                         case SCHEMAVER_SAMBAACCOUNT:
822                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
823                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
824                                                 sid_to_string(sid_string, user_sid), 
825                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
826                                         return False;
827                                 }
828                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
829                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
830                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
831                                         temp);
832                                 break;
833                                 
834                         case SCHEMAVER_SAMBASAMACCOUNT:
835                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
836                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
837                                         sid_to_string(sid_string, user_sid));                                 
838                                 break;
839                                 
840                         default:
841                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
842                                 break;
843                 }               
844         }
845
846         /* we don't need to store the primary group RID - so leaving it
847            'free' to hang off the unix primary group makes life easier */
848
849         if (need_update(sampass, PDB_GROUPSID)) {
850                 fstring sid_string;
851                 fstring dom_sid_string;
852                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
853                 
854                 switch ( ldap_state->schema_ver ) {
855                         case SCHEMAVER_SAMBAACCOUNT:
856                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
857                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
858                                                 sid_to_string(sid_string, group_sid),
859                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
860                                         return False;
861                                 }
862
863                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
864                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
865                                         get_userattr_key2string(ldap_state->schema_ver, 
866                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
867                                 break;
868                                 
869                         case SCHEMAVER_SAMBASAMACCOUNT:
870                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
871                                         get_userattr_key2string(ldap_state->schema_ver, 
872                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
873                                 break;
874                                 
875                         default:
876                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
877                                 break;
878                 }
879                 
880         }
881         
882         /* displayName, cn, and gecos should all be the same
883          *  most easily accomplished by giving them the same OID
884          *  gecos isn't set here b/c it should be handled by the 
885          *  add-user script
886          *  We change displayName only and fall back to cn if
887          *  it does not exist.
888          */
889
890         if (need_update(sampass, PDB_FULLNAME))
891                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
892                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
893                         pdb_get_fullname(sampass));
894
895         if (need_update(sampass, PDB_ACCTDESC))
896                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
897                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
898                         pdb_get_acct_desc(sampass));
899
900         if (need_update(sampass, PDB_WORKSTATIONS))
901                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
902                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
903                         pdb_get_workstations(sampass));
904         
905         if (need_update(sampass, PDB_MUNGEDDIAL))
906                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
907                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
908                         pdb_get_munged_dial(sampass));
909         
910         if (need_update(sampass, PDB_SMBHOME))
911                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
912                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
913                         pdb_get_homedir(sampass));
914                         
915         if (need_update(sampass, PDB_DRIVE))
916                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
917                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
918                         pdb_get_dir_drive(sampass));
919
920         if (need_update(sampass, PDB_LOGONSCRIPT))
921                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
922                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
923                         pdb_get_logon_script(sampass));
924
925         if (need_update(sampass, PDB_PROFILE))
926                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
927                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
928                         pdb_get_profile_path(sampass));
929
930         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
931         if (need_update(sampass, PDB_LOGONTIME))
932                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
933                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
934
935         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
936         if (need_update(sampass, PDB_LOGOFFTIME))
937                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
938                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
939
940         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
941         if (need_update(sampass, PDB_KICKOFFTIME))
942                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
943                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
944
945         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
946         if (need_update(sampass, PDB_CANCHANGETIME))
947                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
948                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
949
950         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
951         if (need_update(sampass, PDB_MUSTCHANGETIME))
952                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
953                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
954
955
956         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
957                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
958
959                 if (need_update(sampass, PDB_LMPASSWD)) {
960                         const uchar *lm_pw =  pdb_get_lanman_passwd(sampass);
961                         if (lm_pw) {
962                                 pdb_sethexpwd(temp, lm_pw,
963                                               pdb_get_acct_ctrl(sampass));
964                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
965                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
966                                                  temp);
967                         } else {
968                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
969                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
970                                                  NULL);
971                         }
972                 }
973                 if (need_update(sampass, PDB_NTPASSWD)) {
974                         const uchar *nt_pw =  pdb_get_nt_passwd(sampass);
975                         if (nt_pw) {
976                                 pdb_sethexpwd(temp, nt_pw,
977                                               pdb_get_acct_ctrl(sampass));
978                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
979                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
980                                                  temp);
981                         } else {
982                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
983                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
984                                                  NULL);
985                         }
986                 }
987
988                 if (need_update(sampass, PDB_PASSLASTSET)) {
989                         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
990                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
991                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
992                                 temp);
993                 }
994         }
995
996         /* FIXME: Hours stuff goes in LDAP  */
997
998         if (need_update(sampass, PDB_ACCTCTRL))
999                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1000                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1001                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1002
1003         /* password lockout cache: 
1004            - If we are now autolocking or clearing, we write to ldap
1005            - If we are clearing, we delete the cache entry
1006            - If the count is > 0, we update the cache
1007
1008            This even means when autolocking, we cache, just in case the
1009            update doesn't work, and we have to cache the autolock flag */
1010
1011         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1012             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1013                 uint16 badcount = pdb_get_bad_password_count(sampass);
1014                 time_t badtime = pdb_get_bad_password_time(sampass);
1015                 uint32 pol;
1016                 account_policy_get(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1017
1018                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1019                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1020
1021                 if ((badcount >= pol) || (badcount == 0)) {
1022                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1023                                 (unsigned int)badcount, (unsigned int)badtime));
1024                         slprintf (temp, sizeof (temp) - 1, "%li", (long)badcount);
1025                         smbldap_make_mod(
1026                                 ldap_state->smbldap_state->ldap_struct,
1027                                 existing, mods, 
1028                                 get_userattr_key2string(
1029                                         ldap_state->schema_ver, 
1030                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1031                                 temp);
1032
1033                         slprintf (temp, sizeof (temp) - 1, "%li", badtime);
1034                         smbldap_make_mod(
1035                                 ldap_state->smbldap_state->ldap_struct, 
1036                                 existing, mods,
1037                                 get_userattr_key2string(
1038                                         ldap_state->schema_ver, 
1039                                         LDAP_ATTR_BAD_PASSWORD_TIME), 
1040                                 temp);
1041                 }
1042                 if (badcount == 0) {
1043                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1044                         login_cache_delentry(sampass);
1045                 } else {
1046                         LOGIN_CACHE cache_entry ={time(NULL),
1047                                                   pdb_get_acct_ctrl(sampass),
1048                                                   badcount, badtime};
1049                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1050                         login_cache_write(sampass, cache_entry);
1051                 }
1052         }
1053
1054         return True;
1055 }
1056
1057 /**********************************************************************
1058  Connect to LDAP server for password enumeration.
1059 *********************************************************************/
1060
1061 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update)
1062 {
1063         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1064         int rc;
1065         pstring filter;
1066         char **attr_list;
1067
1068         pstr_sprintf( filter, "(&%s%s)", lp_ldap_filter(), 
1069                 get_objclass_filter(ldap_state->schema_ver));
1070         all_string_sub(filter, "%u", "*", sizeof(pstring));
1071
1072         attr_list = get_userattr_list(ldap_state->schema_ver);
1073         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, 
1074                                    attr_list, &ldap_state->result);
1075         free_attr_list( attr_list );
1076
1077         if (rc != LDAP_SUCCESS) {
1078                 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1079                 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", lp_ldap_suffix(), filter));
1080                 ldap_msgfree(ldap_state->result);
1081                 ldap_state->result = NULL;
1082                 return NT_STATUS_UNSUCCESSFUL;
1083         }
1084
1085         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
1086                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
1087                 ldap_state->result)));
1088
1089         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1090                                  ldap_state->result);
1091         ldap_state->index = 0;
1092
1093         return NT_STATUS_OK;
1094 }
1095
1096 /**********************************************************************
1097  End enumeration of the LDAP password list.
1098 *********************************************************************/
1099
1100 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1101 {
1102         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1103         if (ldap_state->result) {
1104                 ldap_msgfree(ldap_state->result);
1105                 ldap_state->result = NULL;
1106         }
1107 }
1108
1109 /**********************************************************************
1110 Get the next entry in the LDAP password database.
1111 *********************************************************************/
1112
1113 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods, SAM_ACCOUNT *user)
1114 {
1115         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1116         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1117         BOOL bret = False;
1118
1119         while (!bret) {
1120                 if (!ldap_state->entry)
1121                         return ret;
1122                 
1123                 ldap_state->index++;
1124                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1125                 
1126                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
1127                                             ldap_state->entry); 
1128         }
1129
1130         return NT_STATUS_OK;
1131 }
1132
1133 /**********************************************************************
1134 Get SAM_ACCOUNT entry from LDAP by username.
1135 *********************************************************************/
1136
1137 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, SAM_ACCOUNT *user, const char *sname)
1138 {
1139         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1140         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1141         LDAPMessage *result = NULL;
1142         LDAPMessage *entry = NULL;
1143         int count;
1144         char ** attr_list;
1145         int rc;
1146         
1147         attr_list = get_userattr_list( ldap_state->schema_ver );
1148         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1149         free_attr_list( attr_list );
1150
1151         if ( rc != LDAP_SUCCESS ) 
1152                 return NT_STATUS_NO_SUCH_USER;
1153         
1154         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1155         
1156         if (count < 1) {
1157                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1158                 ldap_msgfree(result);
1159                 return NT_STATUS_NO_SUCH_USER;
1160         } else if (count > 1) {
1161                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1162                 ldap_msgfree(result);
1163                 return NT_STATUS_NO_SUCH_USER;
1164         }
1165
1166         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1167         if (entry) {
1168                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1169                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1170                         ldap_msgfree(result);
1171                         return NT_STATUS_NO_SUCH_USER;
1172                 }
1173                 pdb_set_backend_private_data(user, result, 
1174                                              private_data_free_fn, 
1175                                              my_methods, PDB_CHANGED);
1176                 ret = NT_STATUS_OK;
1177         } else {
1178                 ldap_msgfree(result);
1179         }
1180         return ret;
1181 }
1182
1183 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1184                                    const DOM_SID *sid, LDAPMessage **result) 
1185 {
1186         int rc = -1;
1187         char ** attr_list;
1188         uint32 rid;
1189
1190         switch ( ldap_state->schema_ver ) {
1191                 case SCHEMAVER_SAMBASAMACCOUNT:
1192                         attr_list = get_userattr_list(ldap_state->schema_ver);
1193                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid, result, attr_list);
1194                         free_attr_list( attr_list );
1195
1196                         if ( rc != LDAP_SUCCESS ) 
1197                                 return rc;
1198                         break;
1199                         
1200                 case SCHEMAVER_SAMBAACCOUNT:
1201                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1202                                 return rc;
1203                         }
1204                 
1205                         attr_list = get_userattr_list(ldap_state->schema_ver);
1206                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1207                         free_attr_list( attr_list );
1208
1209                         if ( rc != LDAP_SUCCESS ) 
1210                                 return rc;
1211                         break;
1212         }
1213         return rc;
1214 }
1215
1216 /**********************************************************************
1217  Get SAM_ACCOUNT entry from LDAP by SID.
1218 *********************************************************************/
1219
1220 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, SAM_ACCOUNT * user, const DOM_SID *sid)
1221 {
1222         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1223         LDAPMessage *result = NULL;
1224         LDAPMessage *entry = NULL;
1225         int count;
1226         int rc;
1227         fstring sid_string;
1228
1229         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1230                                           sid, &result); 
1231         if (rc != LDAP_SUCCESS)
1232                 return NT_STATUS_NO_SUCH_USER;
1233
1234         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1235         
1236         if (count < 1) {
1237                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1238                        count));
1239                 ldap_msgfree(result);
1240                 return NT_STATUS_NO_SUCH_USER;
1241         }  else if (count > 1) {
1242                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1243                        count));
1244                 ldap_msgfree(result);
1245                 return NT_STATUS_NO_SUCH_USER;
1246         }
1247
1248         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1249         if (!entry) {
1250                 ldap_msgfree(result);
1251                 return NT_STATUS_NO_SUCH_USER;
1252         }
1253
1254         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1255                 DEBUG(1,("ldapsam_getsampwrid: init_sam_from_ldap failed!\n"));
1256                 ldap_msgfree(result);
1257                 return NT_STATUS_NO_SUCH_USER;
1258         }
1259
1260         pdb_set_backend_private_data(user, result, 
1261                                      private_data_free_fn, 
1262                                      my_methods, PDB_CHANGED);
1263         return NT_STATUS_OK;
1264 }       
1265
1266 /********************************************************************
1267  Do the actual modification - also change a plaintext passord if 
1268  it it set.
1269 **********************************************************************/
1270
1271 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1272                                      SAM_ACCOUNT *newpwd, char *dn,
1273                                      LDAPMod **mods, int ldap_op, 
1274                                      BOOL (*need_update)(const SAM_ACCOUNT *, enum pdb_elements))
1275 {
1276         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1277         int rc;
1278         
1279         if (!my_methods || !newpwd || !dn) {
1280                 return NT_STATUS_INVALID_PARAMETER;
1281         }
1282         
1283         if (!mods) {
1284                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1285                 /* may be password change below however */
1286         } else {
1287                 switch(ldap_op) {
1288                         case LDAP_MOD_ADD: 
1289                                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1290                                                 "objectclass", 
1291                                                 LDAP_OBJ_ACCOUNT);
1292                                 rc = smbldap_add(ldap_state->smbldap_state, 
1293                                                  dn, mods);
1294                                 break;
1295                         case LDAP_MOD_REPLACE: 
1296                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1297                                                     dn ,mods);
1298                                 break;
1299                         default:        
1300                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1301                                          ldap_op));
1302                                 return NT_STATUS_INVALID_PARAMETER;
1303                 }
1304                 
1305                 if (rc!=LDAP_SUCCESS) {
1306                         char *ld_error = NULL;
1307                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1308                                         &ld_error);
1309                         DEBUG(1, ("ldapsam_modify_entry: Failed to %s user dn= %s with: %s\n\t%s\n",
1310                                ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1311                                dn, ldap_err2string(rc),
1312                                ld_error?ld_error:"unknown"));
1313                         SAFE_FREE(ld_error);
1314                         return NT_STATUS_UNSUCCESSFUL;
1315                 }  
1316         }
1317         
1318         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1319                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1320                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1321                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1322                 BerElement *ber;
1323                 struct berval *bv;
1324                 char *retoid;
1325                 struct berval *retdata;
1326                 char *utf8_password;
1327                 char *utf8_dn;
1328
1329                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1330                         return NT_STATUS_NO_MEMORY;
1331                 }
1332
1333                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1334                         return NT_STATUS_NO_MEMORY;
1335                 }
1336
1337                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1338                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1339                         SAFE_FREE(utf8_password);
1340                         return NT_STATUS_UNSUCCESSFUL;
1341                 }
1342
1343                 ber_printf (ber, "{");
1344                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1345                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1346                 ber_printf (ber, "N}");
1347
1348                 if ((rc = ber_flatten (ber, &bv))<0) {
1349                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1350                         ber_free(ber,1);
1351                         SAFE_FREE(utf8_dn);
1352                         SAFE_FREE(utf8_password);
1353                         return NT_STATUS_UNSUCCESSFUL;
1354                 }
1355                 
1356                 SAFE_FREE(utf8_dn);
1357                 SAFE_FREE(utf8_password);
1358                 ber_free(ber, 1);
1359
1360                 if ((rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1361                                                      LDAP_EXOP_MODIFY_PASSWD,
1362                                                      bv, NULL, NULL, &retoid, 
1363                                                      &retdata)) != LDAP_SUCCESS) {
1364                         char *ld_error = NULL;
1365                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1366                                         &ld_error);
1367                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1368                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1369                         SAFE_FREE(ld_error);
1370                         ber_bvfree(bv);
1371                         return NT_STATUS_UNSUCCESSFUL;
1372                 } else {
1373                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1374 #ifdef DEBUG_PASSWORD
1375                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1376 #endif    
1377                         ber_bvfree(retdata);
1378                         ber_memfree(retoid);
1379                 }
1380                 ber_bvfree(bv);
1381         }
1382         return NT_STATUS_OK;
1383 }
1384
1385 /**********************************************************************
1386  Delete entry from LDAP for username.
1387 *********************************************************************/
1388
1389 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * sam_acct)
1390 {
1391         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1392         const char *sname;
1393         int rc;
1394         LDAPMessage *result = NULL;
1395         NTSTATUS ret;
1396         char **attr_list;
1397         fstring objclass;
1398
1399         if (!sam_acct) {
1400                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1401                 return NT_STATUS_INVALID_PARAMETER;
1402         }
1403
1404         sname = pdb_get_username(sam_acct);
1405
1406         DEBUG (3, ("ldapsam_delete_sam_account: Deleting user %s from LDAP.\n", sname));
1407
1408         attr_list= get_userattr_list( ldap_state->schema_ver );
1409         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1410
1411         if (rc != LDAP_SUCCESS)  {
1412                 free_attr_list( attr_list );
1413                 return NT_STATUS_NO_SUCH_USER;
1414         }
1415         
1416         switch ( ldap_state->schema_ver ) {
1417                 case SCHEMAVER_SAMBASAMACCOUNT:
1418                         fstrcpy( objclass, LDAP_OBJ_SAMBASAMACCOUNT );
1419                         break;
1420                         
1421                 case SCHEMAVER_SAMBAACCOUNT:
1422                         fstrcpy( objclass, LDAP_OBJ_SAMBAACCOUNT );
1423                         break;
1424                 default:
1425                         fstrcpy( objclass, "UNKNOWN" );
1426                         DEBUG(0,("ldapsam_delete_sam_account: Unknown schema version specified!\n"));
1427                                 break;
1428         }
1429
1430         ret = ldapsam_delete_entry(ldap_state, result, objclass, attr_list );
1431         ldap_msgfree(result);
1432         free_attr_list( attr_list );
1433
1434         return ret;
1435 }
1436
1437 /**********************************************************************
1438  Helper function to determine for update_sam_account whether
1439  we need LDAP modification.
1440 *********************************************************************/
1441
1442 static BOOL element_is_changed(const SAM_ACCOUNT *sampass,
1443                                enum pdb_elements element)
1444 {
1445         return IS_SAM_CHANGED(sampass, element);
1446 }
1447
1448 /**********************************************************************
1449  Update SAM_ACCOUNT.
1450 *********************************************************************/
1451
1452 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1453 {
1454         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1455         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1456         int rc = 0;
1457         char *dn;
1458         LDAPMessage *result = NULL;
1459         LDAPMessage *entry = NULL;
1460         LDAPMod **mods = NULL;
1461         char **attr_list;
1462
1463         result = pdb_get_backend_private_data(newpwd, my_methods);
1464         if (!result) {
1465                 attr_list = get_userattr_list(ldap_state->schema_ver);
1466                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1467                 free_attr_list( attr_list );
1468                 if (rc != LDAP_SUCCESS) {
1469                         return NT_STATUS_UNSUCCESSFUL;
1470                 }
1471                 pdb_set_backend_private_data(newpwd, result, private_data_free_fn, my_methods, PDB_CHANGED);
1472         }
1473
1474         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1475                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1476                 return NT_STATUS_UNSUCCESSFUL;
1477         }
1478
1479         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1480         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1481         if (!dn) {
1482                 return NT_STATUS_UNSUCCESSFUL;
1483         }
1484
1485         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1486
1487         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1488                                 element_is_changed)) {
1489                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1490                 SAFE_FREE(dn);
1491                 if (mods != NULL)
1492                         ldap_mods_free(mods,True);
1493                 return NT_STATUS_UNSUCCESSFUL;
1494         }
1495         
1496         if (mods == NULL) {
1497                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1498                          pdb_get_username(newpwd)));
1499                 SAFE_FREE(dn);
1500                 return NT_STATUS_OK;
1501         }
1502         
1503         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1504         ldap_mods_free(mods,True);
1505         SAFE_FREE(dn);
1506
1507         if (!NT_STATUS_IS_OK(ret)) {
1508                 char *ld_error = NULL;
1509                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1510                                 &ld_error);
1511                 DEBUG(0,("ldapsam_update_sam_account: failed to modify user with uid = %s, error: %s (%s)\n",
1512                          pdb_get_username(newpwd), ld_error?ld_error:"(unknwon)", ldap_err2string(rc)));
1513                 SAFE_FREE(ld_error);
1514                 return ret;
1515         }
1516
1517         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1518                   pdb_get_username(newpwd)));
1519         return NT_STATUS_OK;
1520 }
1521
1522 /**********************************************************************
1523  Helper function to determine for update_sam_account whether
1524  we need LDAP modification.
1525  *********************************************************************/
1526
1527 static BOOL element_is_set_or_changed(const SAM_ACCOUNT *sampass,
1528                                       enum pdb_elements element)
1529 {
1530         return (IS_SAM_SET(sampass, element) ||
1531                 IS_SAM_CHANGED(sampass, element));
1532 }
1533
1534 /**********************************************************************
1535  Add SAM_ACCOUNT to LDAP.
1536 *********************************************************************/
1537
1538 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1539 {
1540         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1541         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1542         int rc;
1543         LDAPMessage     *result = NULL;
1544         LDAPMessage     *entry  = NULL;
1545         pstring         dn;
1546         LDAPMod         **mods = NULL;
1547         int             ldap_op = LDAP_MOD_REPLACE;
1548         uint32          num_result;
1549         char            **attr_list;
1550         char            *escape_user;
1551         const char      *username = pdb_get_username(newpwd);
1552         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1553         pstring         filter;
1554         fstring         sid_string;
1555
1556         if (!username || !*username) {
1557                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1558                 return NT_STATUS_INVALID_PARAMETER;
1559         }
1560
1561         /* free this list after the second search or in case we exit on failure */
1562         attr_list = get_userattr_list(ldap_state->schema_ver);
1563
1564         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1565
1566         if (rc != LDAP_SUCCESS) {
1567                 free_attr_list( attr_list );
1568                 return NT_STATUS_UNSUCCESSFUL;
1569         }
1570
1571         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1572                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
1573                          username));
1574                 ldap_msgfree(result);
1575                 free_attr_list( attr_list );
1576                 return NT_STATUS_UNSUCCESSFUL;
1577         }
1578         ldap_msgfree(result);
1579         result = NULL;
1580
1581         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1582                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1583                                                   sid, &result); 
1584                 if (rc == LDAP_SUCCESS) {
1585                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1586                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
1587                                          sid_to_string(sid_string, sid)));
1588                                 free_attr_list( attr_list );
1589                                 ldap_msgfree(result);
1590                                 return NT_STATUS_UNSUCCESSFUL;
1591                         }
1592                         ldap_msgfree(result);
1593                 }
1594         }
1595
1596         /* does the entry already exist but without a samba attributes?
1597            we need to return the samba attributes here */
1598            
1599         escape_user = escape_ldap_string_alloc( username );
1600         pstrcpy( filter, lp_ldap_filter() );
1601         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1602         SAFE_FREE( escape_user );
1603
1604         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1605                                    filter, attr_list, &result);
1606         if ( rc != LDAP_SUCCESS ) {
1607                 free_attr_list( attr_list );
1608                 return NT_STATUS_UNSUCCESSFUL;
1609         }
1610
1611         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1612         
1613         if (num_result > 1) {
1614                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1615                 free_attr_list( attr_list );
1616                 ldap_msgfree(result);
1617                 return NT_STATUS_UNSUCCESSFUL;
1618         }
1619         
1620         /* Check if we need to update an existing entry */
1621         if (num_result == 1) {
1622                 char *tmp;
1623                 
1624                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1625                 ldap_op = LDAP_MOD_REPLACE;
1626                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1627                 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1628                 if (!tmp) {
1629                         free_attr_list( attr_list );
1630                         ldap_msgfree(result);
1631                         return NT_STATUS_UNSUCCESSFUL;
1632                 }
1633                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1634                 SAFE_FREE(tmp);
1635
1636         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
1637
1638                 /* There might be a SID for this account already - say an idmap entry */
1639
1640                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
1641                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1642                          sid_to_string(sid_string, sid),
1643                          LDAP_OBJ_IDMAP_ENTRY,
1644                          LDAP_OBJ_SID_ENTRY);
1645                 
1646                 /* free old result before doing a new search */
1647                 if (result != NULL) {
1648                         ldap_msgfree(result);
1649                         result = NULL;
1650                 }
1651                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1652                                            filter, attr_list, &result);
1653                         
1654                 if ( rc != LDAP_SUCCESS ) {
1655                         free_attr_list( attr_list );
1656                         return NT_STATUS_UNSUCCESSFUL;
1657                 }
1658                 
1659                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1660                 
1661                 if (num_result > 1) {
1662                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1663                         free_attr_list( attr_list );
1664                         ldap_msgfree(result);
1665                         return NT_STATUS_UNSUCCESSFUL;
1666                 }
1667                 
1668                 /* Check if we need to update an existing entry */
1669                 if (num_result == 1) {
1670                         char *tmp;
1671                         
1672                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1673                         ldap_op = LDAP_MOD_REPLACE;
1674                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1675                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1676                         if (!tmp) {
1677                                 free_attr_list( attr_list );
1678                                 ldap_msgfree(result);
1679                                 return NT_STATUS_UNSUCCESSFUL;
1680                         }
1681                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1682                         SAFE_FREE(tmp);
1683                 }
1684         }
1685         
1686         free_attr_list( attr_list );
1687
1688         if (num_result == 0) {
1689                 /* Check if we need to add an entry */
1690                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
1691                 ldap_op = LDAP_MOD_ADD;
1692                 if (username[strlen(username)-1] == '$') {
1693                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
1694                 } else {
1695                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
1696                 }
1697         }
1698
1699         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1700                                 element_is_set_or_changed)) {
1701                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
1702                 ldap_msgfree(result);
1703                 if (mods != NULL)
1704                         ldap_mods_free(mods,True);
1705                 return NT_STATUS_UNSUCCESSFUL;          
1706         }
1707         
1708         ldap_msgfree(result);
1709
1710         if (mods == NULL) {
1711                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
1712                 return NT_STATUS_UNSUCCESSFUL;
1713         }
1714         switch ( ldap_state->schema_ver ) {
1715                 case SCHEMAVER_SAMBAACCOUNT:
1716                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
1717                         break;
1718                 case SCHEMAVER_SAMBASAMACCOUNT:
1719                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
1720                         break;
1721                 default:
1722                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
1723                         break;
1724         }
1725
1726         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
1727         if (!NT_STATUS_IS_OK(ret)) {
1728                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
1729                          pdb_get_username(newpwd),dn));
1730                 ldap_mods_free(mods, True);
1731                 return ret;
1732         }
1733
1734         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
1735         ldap_mods_free(mods, True);
1736         
1737         return NT_STATUS_OK;
1738 }
1739
1740 /**********************************************************************
1741  *********************************************************************/
1742
1743 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
1744                                      const char *filter,
1745                                      LDAPMessage ** result)
1746 {
1747         int scope = LDAP_SCOPE_SUBTREE;
1748         int rc;
1749         char **attr_list;
1750
1751         attr_list = get_attr_list(groupmap_attr_list);
1752         rc = smbldap_search(ldap_state->smbldap_state, 
1753                             lp_ldap_group_suffix (), scope,
1754                             filter, attr_list, 0, result);
1755         free_attr_list( attr_list );
1756
1757         if (rc != LDAP_SUCCESS) {
1758                 char *ld_error = NULL;
1759                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1760                                 &ld_error);
1761                 DEBUG(0, ("ldapsam_search_one_group: "
1762                           "Problem during the LDAP search: LDAP error: %s (%s)\n",
1763                           ld_error?ld_error:"(unknown)", ldap_err2string(rc)));
1764                 DEBUGADD(3, ("ldapsam_search_one_group: Query was: %s, %s\n",
1765                           lp_ldap_group_suffix(), filter));
1766                 SAFE_FREE(ld_error);
1767         }
1768
1769         return rc;
1770 }
1771
1772 /**********************************************************************
1773  *********************************************************************/
1774
1775 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
1776                                  GROUP_MAP *map, LDAPMessage *entry)
1777 {
1778         pstring temp;
1779
1780         if (ldap_state == NULL || map == NULL || entry == NULL ||
1781                         ldap_state->smbldap_state->ldap_struct == NULL) {
1782                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
1783                 return False;
1784         }
1785
1786         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
1787                         get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
1788                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
1789                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
1790                 return False;
1791         }
1792         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
1793
1794         map->gid = (gid_t)atol(temp);
1795
1796         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
1797                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
1798                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
1799                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
1800                 return False;
1801         }
1802         
1803         if (!string_to_sid(&map->sid, temp)) {
1804                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
1805                 return False;
1806         }
1807
1808         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
1809                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
1810                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
1811                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
1812                 return False;
1813         }
1814         map->sid_name_use = (enum SID_NAME_USE)atol(temp);
1815
1816         if ((map->sid_name_use < SID_NAME_USER) ||
1817                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
1818                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
1819                 return False;
1820         }
1821
1822         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
1823                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
1824                 temp[0] = '\0';
1825                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
1826                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
1827                 {
1828                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
1829 for gidNumber(%lu)\n",(unsigned long)map->gid));
1830                         return False;
1831                 }
1832         }
1833         fstrcpy(map->nt_name, temp);
1834
1835         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
1836                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
1837                 temp[0] = '\0';
1838         }
1839         fstrcpy(map->comment, temp);
1840
1841         return True;
1842 }
1843
1844 /**********************************************************************
1845  *********************************************************************/
1846
1847 static BOOL init_ldap_from_group(LDAP *ldap_struct,
1848                                  LDAPMessage *existing,
1849                                  LDAPMod ***mods,
1850                                  const GROUP_MAP *map)
1851 {
1852         pstring tmp;
1853
1854         if (mods == NULL || map == NULL) {
1855                 DEBUG(0, ("init_ldap_from_group: NULL parameters found!\n"));
1856                 return False;
1857         }
1858
1859         *mods = NULL;
1860
1861         sid_to_string(tmp, &map->sid);
1862
1863         smbldap_make_mod(ldap_struct, existing, mods, 
1864                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID), tmp);
1865         pstr_sprintf(tmp, "%i", map->sid_name_use);
1866         smbldap_make_mod(ldap_struct, existing, mods, 
1867                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), tmp);
1868
1869         smbldap_make_mod(ldap_struct, existing, mods, 
1870                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), map->nt_name);
1871         smbldap_make_mod(ldap_struct, existing, mods, 
1872                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), map->comment);
1873
1874         return True;
1875 }
1876
1877 /**********************************************************************
1878  *********************************************************************/
1879
1880 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
1881                                  const char *filter,
1882                                  GROUP_MAP *map)
1883 {
1884         struct ldapsam_privates *ldap_state =
1885                 (struct ldapsam_privates *)methods->private_data;
1886         LDAPMessage *result = NULL;
1887         LDAPMessage *entry = NULL;
1888         int count;
1889
1890         if (ldapsam_search_one_group(ldap_state, filter, &result)
1891             != LDAP_SUCCESS) {
1892                 return NT_STATUS_NO_SUCH_GROUP;
1893         }
1894
1895         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1896
1897         if (count < 1) {
1898                 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
1899                 ldap_msgfree(result);
1900                 return NT_STATUS_NO_SUCH_GROUP;
1901         }
1902
1903         if (count > 1) {
1904                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: count=%d\n",
1905                           filter, count));
1906                 ldap_msgfree(result);
1907                 return NT_STATUS_NO_SUCH_GROUP;
1908         }
1909
1910         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1911
1912         if (!entry) {
1913                 ldap_msgfree(result);
1914                 return NT_STATUS_UNSUCCESSFUL;
1915         }
1916
1917         if (!init_group_from_ldap(ldap_state, map, entry)) {
1918                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for group filter %s\n",
1919                           filter));
1920                 ldap_msgfree(result);
1921                 return NT_STATUS_NO_SUCH_GROUP;
1922         }
1923
1924         ldap_msgfree(result);
1925         return NT_STATUS_OK;
1926 }
1927
1928 /**********************************************************************
1929  *********************************************************************/
1930
1931 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1932                                  DOM_SID sid)
1933 {
1934         pstring filter;
1935
1936         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
1937                 LDAP_OBJ_GROUPMAP, 
1938                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
1939                 sid_string_static(&sid));
1940
1941         return ldapsam_getgroup(methods, filter, map);
1942 }
1943
1944 /**********************************************************************
1945  *********************************************************************/
1946
1947 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1948                                  gid_t gid)
1949 {
1950         pstring filter;
1951
1952         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
1953                 LDAP_OBJ_GROUPMAP,
1954                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
1955                 (unsigned long)gid);
1956
1957         return ldapsam_getgroup(methods, filter, map);
1958 }
1959
1960 /**********************************************************************
1961  *********************************************************************/
1962
1963 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1964                                  const char *name)
1965 {
1966         pstring filter;
1967         char *escape_name = escape_ldap_string_alloc(name);
1968
1969         if (!escape_name) {
1970                 return NT_STATUS_NO_MEMORY;
1971         }
1972
1973         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
1974                 LDAP_OBJ_GROUPMAP,
1975                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
1976                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
1977
1978         SAFE_FREE(escape_name);
1979
1980         return ldapsam_getgroup(methods, filter, map);
1981 }
1982
1983 /**********************************************************************
1984  *********************************************************************/
1985
1986 static int ldapsam_search_one_group_by_gid(struct ldapsam_privates *ldap_state,
1987                                            gid_t gid,
1988                                            LDAPMessage **result)
1989 {
1990         pstring filter;
1991
1992         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))", 
1993                 LDAP_OBJ_POSIXGROUP,
1994                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
1995                 (unsigned long)gid);
1996
1997         return ldapsam_search_one_group(ldap_state, filter, result);
1998 }
1999
2000 /**********************************************************************
2001  *********************************************************************/
2002
2003 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2004                                                 GROUP_MAP *map)
2005 {
2006         struct ldapsam_privates *ldap_state =
2007                 (struct ldapsam_privates *)methods->private_data;
2008         LDAPMessage *result = NULL;
2009         LDAPMod **mods = NULL;
2010         int count;
2011
2012         char *tmp;
2013         pstring dn;
2014         LDAPMessage *entry;
2015
2016         GROUP_MAP dummy;
2017
2018         int rc;
2019
2020         if (NT_STATUS_IS_OK(ldapsam_getgrgid(methods, &dummy,
2021                                              map->gid))) {
2022                 DEBUG(0, ("ldapsam_add_group_mapping_entry: Group %ld already exists in LDAP\n", (unsigned long)map->gid));
2023                 return NT_STATUS_UNSUCCESSFUL;
2024         }
2025
2026         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2027         if (rc != LDAP_SUCCESS) {
2028                 ldap_msgfree(result);
2029                 return NT_STATUS_UNSUCCESSFUL;
2030         }
2031
2032         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2033
2034         if ( count == 0 ) {
2035                 ldap_msgfree(result);
2036                 return NT_STATUS_UNSUCCESSFUL;
2037         }
2038
2039         if (count > 1) {
2040                 DEBUG(2, ("ldapsam_add_group_mapping_entry: Group %lu must exist exactly once in LDAP\n",
2041                           (unsigned long)map->gid));
2042                 ldap_msgfree(result);
2043                 return NT_STATUS_UNSUCCESSFUL;
2044         }
2045
2046         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2047         tmp = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2048         if (!tmp) {
2049                 ldap_msgfree(result);
2050                 return NT_STATUS_UNSUCCESSFUL;
2051         }
2052         pstrcpy(dn, tmp);
2053         SAFE_FREE(tmp);
2054
2055         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2056                                   result, &mods, map)) {
2057                 DEBUG(0, ("ldapsam_add_group_mapping_entry: init_ldap_from_group failed!\n"));
2058                 ldap_mods_free(mods, True);
2059                 ldap_msgfree(result);
2060                 return NT_STATUS_UNSUCCESSFUL;
2061         }
2062
2063         ldap_msgfree(result);
2064
2065         if (mods == NULL) {
2066                 DEBUG(0, ("ldapsam_add_group_mapping_entry: mods is empty\n"));
2067                 return NT_STATUS_UNSUCCESSFUL;
2068         }
2069
2070         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP );
2071
2072         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2073         ldap_mods_free(mods, True);
2074
2075         if (rc != LDAP_SUCCESS) {
2076                 char *ld_error = NULL;
2077                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2078                                 &ld_error);
2079                 DEBUG(0, ("ldapsam_add_group_mapping_entry: failed to add group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2080                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2081                 SAFE_FREE(ld_error);
2082                 return NT_STATUS_UNSUCCESSFUL;
2083         }
2084
2085         DEBUG(2, ("ldapsam_add_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2086         return NT_STATUS_OK;
2087 }
2088
2089 /**********************************************************************
2090  *********************************************************************/
2091
2092 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2093                                                    GROUP_MAP *map)
2094 {
2095         struct ldapsam_privates *ldap_state =
2096                 (struct ldapsam_privates *)methods->private_data;
2097         int rc;
2098         char *dn = NULL;
2099         LDAPMessage *result = NULL;
2100         LDAPMessage *entry = NULL;
2101         LDAPMod **mods = NULL;
2102
2103         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2104
2105         if (rc != LDAP_SUCCESS) {
2106                 return NT_STATUS_UNSUCCESSFUL;
2107         }
2108
2109         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
2110                 DEBUG(0, ("ldapsam_update_group_mapping_entry: No group to modify!\n"));
2111                 ldap_msgfree(result);
2112                 return NT_STATUS_UNSUCCESSFUL;
2113         }
2114
2115         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2116
2117         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2118                                   result, &mods, map)) {
2119                 DEBUG(0, ("ldapsam_update_group_mapping_entry: init_ldap_from_group failed\n"));
2120                 ldap_msgfree(result);
2121                 if (mods != NULL)
2122                         ldap_mods_free(mods,True);
2123                 return NT_STATUS_UNSUCCESSFUL;
2124         }
2125
2126         if (mods == NULL) {
2127                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: nothing to do\n"));
2128                 ldap_msgfree(result);
2129                 return NT_STATUS_OK;
2130         }
2131
2132         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2133         if (!dn) {
2134                 ldap_msgfree(result);
2135                 return NT_STATUS_UNSUCCESSFUL;
2136         }
2137         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2138         SAFE_FREE(dn);
2139
2140         ldap_mods_free(mods, True);
2141         ldap_msgfree(result);
2142
2143         if (rc != LDAP_SUCCESS) {
2144                 char *ld_error = NULL;
2145                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2146                                 &ld_error);
2147                 DEBUG(0, ("ldapsam_update_group_mapping_entry: failed to modify group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2148                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2149                 SAFE_FREE(ld_error);
2150                 return NT_STATUS_UNSUCCESSFUL;
2151         }
2152
2153         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2154         return NT_STATUS_OK;
2155 }
2156
2157 /**********************************************************************
2158  *********************************************************************/
2159
2160 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2161                                                    DOM_SID sid)
2162 {
2163         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)methods->private_data;
2164         pstring sidstring, filter;
2165         LDAPMessage *result = NULL;
2166         int rc;
2167         NTSTATUS ret;
2168         char **attr_list;
2169
2170         sid_to_string(sidstring, &sid);
2171         
2172         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))", 
2173                 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID, sidstring);
2174
2175         rc = ldapsam_search_one_group(ldap_state, filter, &result);
2176
2177         if (rc != LDAP_SUCCESS) {
2178                 return NT_STATUS_NO_SUCH_GROUP;
2179         }
2180
2181         attr_list = get_attr_list( groupmap_attr_list_to_delete );
2182         ret = ldapsam_delete_entry(ldap_state, result, LDAP_OBJ_GROUPMAP, attr_list);
2183         free_attr_list ( attr_list );
2184
2185         ldap_msgfree(result);
2186
2187         return ret;
2188 }
2189
2190 /**********************************************************************
2191  *********************************************************************/
2192
2193 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods, BOOL update)
2194 {
2195         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2196         fstring filter;
2197         int rc;
2198         char **attr_list;
2199
2200         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
2201         attr_list = get_attr_list( groupmap_attr_list );
2202         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2203                             LDAP_SCOPE_SUBTREE, filter,
2204                             attr_list, 0, &ldap_state->result);
2205         free_attr_list( attr_list );
2206
2207         if (rc != LDAP_SUCCESS) {
2208                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n", ldap_err2string(rc)));
2209                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n", lp_ldap_group_suffix(), filter));
2210                 ldap_msgfree(ldap_state->result);
2211                 ldap_state->result = NULL;
2212                 return NT_STATUS_UNSUCCESSFUL;
2213         }
2214
2215         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
2216                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2217                                      ldap_state->result)));
2218
2219         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, ldap_state->result);
2220         ldap_state->index = 0;
2221
2222         return NT_STATUS_OK;
2223 }
2224
2225 /**********************************************************************
2226  *********************************************************************/
2227
2228 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
2229 {
2230         ldapsam_endsampwent(my_methods);
2231 }
2232
2233 /**********************************************************************
2234  *********************************************************************/
2235
2236 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
2237                                     GROUP_MAP *map)
2238 {
2239         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2240         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2241         BOOL bret = False;
2242
2243         while (!bret) {
2244                 if (!ldap_state->entry)
2245                         return ret;
2246                 
2247                 ldap_state->index++;
2248                 bret = init_group_from_ldap(ldap_state, map, ldap_state->entry);
2249                 
2250                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
2251                                             ldap_state->entry); 
2252         }
2253
2254         return NT_STATUS_OK;
2255 }
2256
2257 /**********************************************************************
2258  *********************************************************************/
2259
2260 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
2261                                            enum SID_NAME_USE sid_name_use,
2262                                            GROUP_MAP **rmap, int *num_entries,
2263                                            BOOL unix_only)
2264 {
2265         GROUP_MAP map;
2266         GROUP_MAP *mapt;
2267         int entries = 0;
2268
2269         *num_entries = 0;
2270         *rmap = NULL;
2271
2272         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
2273                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open passdb\n"));
2274                 return NT_STATUS_ACCESS_DENIED;
2275         }
2276
2277         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
2278                 if (sid_name_use != SID_NAME_UNKNOWN &&
2279                     sid_name_use != map.sid_name_use) {
2280                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
2281                         continue;
2282                 }
2283                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
2284                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is non mapped\n", map.nt_name));
2285                         continue;
2286                 }
2287
2288                 mapt=(GROUP_MAP *)Realloc((*rmap), (entries+1)*sizeof(GROUP_MAP));
2289                 if (!mapt) {
2290                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to enlarge group map!\n"));
2291                         SAFE_FREE(*rmap);
2292                         return NT_STATUS_UNSUCCESSFUL;
2293                 }
2294                 else
2295                         (*rmap) = mapt;
2296
2297                 mapt[entries] = map;
2298
2299                 entries += 1;
2300
2301         }
2302         ldapsam_endsamgrent(methods);
2303
2304         *num_entries = entries;
2305
2306         return NT_STATUS_OK;
2307 }
2308
2309 /**********************************************************************
2310  Housekeeping
2311  *********************************************************************/
2312
2313 static void free_private_data(void **vp) 
2314 {
2315         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
2316
2317         smbldap_free_struct(&(*ldap_state)->smbldap_state);
2318
2319         if ((*ldap_state)->result != NULL) {
2320                 ldap_msgfree((*ldap_state)->result);
2321                 (*ldap_state)->result = NULL;
2322         }
2323
2324         *ldap_state = NULL;
2325
2326         /* No need to free any further, as it is talloc()ed */
2327 }
2328
2329 /**********************************************************************
2330  Intitalise the parts of the pdb_context that are common to all pdb_ldap modes
2331  *********************************************************************/
2332
2333 static NTSTATUS pdb_init_ldapsam_common(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, 
2334                                         const char *location)
2335 {
2336         NTSTATUS nt_status;
2337         struct ldapsam_privates *ldap_state;
2338
2339         if (!NT_STATUS_IS_OK(nt_status = make_pdb_methods(pdb_context->mem_ctx, pdb_method))) {
2340                 return nt_status;
2341         }
2342
2343         (*pdb_method)->name = "ldapsam";
2344
2345         (*pdb_method)->setsampwent = ldapsam_setsampwent;
2346         (*pdb_method)->endsampwent = ldapsam_endsampwent;
2347         (*pdb_method)->getsampwent = ldapsam_getsampwent;
2348         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
2349         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
2350         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
2351         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
2352         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
2353
2354         (*pdb_method)->getgrsid = ldapsam_getgrsid;
2355         (*pdb_method)->getgrgid = ldapsam_getgrgid;
2356         (*pdb_method)->getgrnam = ldapsam_getgrnam;
2357         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
2358         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
2359         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
2360         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
2361
2362         /* TODO: Setup private data and free */
2363
2364         ldap_state = talloc_zero(pdb_context->mem_ctx, sizeof(*ldap_state));
2365         if (!ldap_state) {
2366                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
2367                 return NT_STATUS_NO_MEMORY;
2368         }
2369
2370         if (!NT_STATUS_IS_OK(nt_status = 
2371                              smbldap_init(pdb_context->mem_ctx, location, 
2372                                           &ldap_state->smbldap_state)));
2373
2374         ldap_state->domain_name = talloc_strdup(pdb_context->mem_ctx, get_global_sam_name());
2375         if (!ldap_state->domain_name) {
2376                 return NT_STATUS_NO_MEMORY;
2377         }
2378
2379         (*pdb_method)->private_data = ldap_state;
2380
2381         (*pdb_method)->free_private_data = free_private_data;
2382
2383         return NT_STATUS_OK;
2384 }
2385
2386 /**********************************************************************
2387  Initialise the 'compat' mode for pdb_ldap
2388  *********************************************************************/
2389
2390 static NTSTATUS pdb_init_ldapsam_compat(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
2391 {
2392         NTSTATUS nt_status;
2393         struct ldapsam_privates *ldap_state;
2394
2395 #ifdef WITH_LDAP_SAMCONFIG
2396         if (!location) {
2397                 int ldap_port = lp_ldap_port();
2398                         
2399                 /* remap default port if not using SSL (ie clear or TLS) */
2400                 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
2401                         ldap_port = 389;
2402                 }
2403
2404                 location = talloc_asprintf(pdb_context->mem_ctx, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
2405                 if (!location) {
2406                         return NT_STATUS_NO_MEMORY;
2407                 }
2408         }
2409 #endif
2410
2411         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
2412                 return nt_status;
2413         }
2414
2415         (*pdb_method)->name = "ldapsam_compat";
2416
2417         ldap_state = (*pdb_method)->private_data;
2418         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
2419
2420         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
2421
2422         return NT_STATUS_OK;
2423 }
2424
2425 /**********************************************************************
2426  Initialise the normal mode for pdb_ldap
2427  *********************************************************************/
2428
2429 static NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
2430 {
2431         NTSTATUS nt_status;
2432         struct ldapsam_privates *ldap_state;
2433         uint32 alg_rid_base;
2434         pstring alg_rid_base_string;
2435         LDAPMessage *result = NULL;
2436         LDAPMessage *entry = NULL;
2437         DOM_SID ldap_domain_sid;
2438         DOM_SID secrets_domain_sid;
2439         pstring domain_sid_string;
2440
2441         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
2442                 return nt_status;
2443         }
2444
2445         (*pdb_method)->name = "ldapsam";
2446
2447         ldap_state = (*pdb_method)->private_data;
2448         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
2449
2450         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
2451         
2452         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state, &result, 
2453                                                ldap_state->domain_name, True);
2454         
2455         if ( !NT_STATUS_IS_OK(nt_status) ) {
2456                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain info, nor add one to the domain\n"));
2457                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, will be unable to allocate new users/groups, \
2458 and will risk BDCs having inconsistant SIDs\n"));
2459                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
2460                 return NT_STATUS_OK;
2461         }
2462
2463         /* Given that the above might fail, everything below this must be optional */
2464         
2465         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2466         if (!entry) {
2467                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info entry\n"));
2468                 ldap_msgfree(result);
2469                 return NT_STATUS_UNSUCCESSFUL;
2470         }
2471
2472         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2473                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
2474                                  domain_sid_string)) {
2475                 BOOL found_sid;
2476                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
2477                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be read as a valid SID\n", domain_sid_string));
2478                         return NT_STATUS_INVALID_PARAMETER;
2479                 }
2480                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name, &secrets_domain_sid);
2481                 if (!found_sid || !sid_equal(&secrets_domain_sid, &ldap_domain_sid)) {
2482                         fstring new_sid_str, old_sid_str;
2483                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain %s based on pdb_ldap results %s -> %s\n",
2484                                   ldap_state->domain_name, 
2485                                   sid_to_string(old_sid_str, &secrets_domain_sid),
2486                                   sid_to_string(new_sid_str, &ldap_domain_sid)));
2487                         
2488                         /* reset secrets.tdb sid */
2489                         secrets_store_domain_sid(ldap_state->domain_name, &ldap_domain_sid);
2490                         DEBUG(1, ("New global sam SID: %s\n", sid_to_string(new_sid_str, get_global_sam_sid())));
2491                 }
2492                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
2493         }
2494
2495         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2496                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ALGORITHMIC_RID_BASE), 
2497                                  alg_rid_base_string)) {
2498                 alg_rid_base = (uint32)atol(alg_rid_base_string);
2499                 if (alg_rid_base != algorithmic_rid_base()) {
2500                         DEBUG(0, ("The value of 'algorithmic RID base' has changed since the LDAP\n"
2501                                   "database was initialised.  Aborting. \n"));
2502                         ldap_msgfree(result);
2503                         return NT_STATUS_UNSUCCESSFUL;
2504                 }
2505         }
2506         ldap_msgfree(result);
2507
2508         return NT_STATUS_OK;
2509 }
2510
2511 NTSTATUS pdb_ldap_init(void)
2512 {
2513         NTSTATUS nt_status;
2514         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
2515                 return nt_status;
2516
2517         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
2518                 return nt_status;
2519
2520         return NT_STATUS_OK;
2521 }