root/source3/passdb/pdb_ldap.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. priv2ld
  2. get_userattr_key2string
  3. get_userattr_list
  4. get_userattr_delete_list
  5. get_objclass_filter
  6. ldapsam_get_seq_num
  7. ldapsam_search_suffix_by_name
  8. ldapsam_search_suffix_by_rid
  9. ldapsam_search_suffix_by_sid
  10. ldapsam_delete_entry
  11. ldapsam_get_entry_timestamp
  12. init_sam_from_ldap
  13. init_ldap_from_sam
  14. ldapsam_endsampwent
  15. append_attr
  16. ldapsam_getsampwnam
  17. ldapsam_get_ldap_user_by_sid
  18. ldapsam_getsampwsid
  19. ldapsam_modify_entry
  20. ldapsam_delete_sam_account
  21. element_is_changed
  22. ldapsam_update_sam_account
  23. ldapsam_rename_sam_account
  24. element_is_set_or_changed
  25. ldapsam_add_sam_account
  26. ldapsam_search_one_group
  27. init_group_from_ldap
  28. ldapsam_getgroup
  29. ldapsam_getgrsid
  30. ldapsam_getgrgid
  31. ldapsam_getgrnam
  32. ldapsam_extract_rid_from_entry
  33. ldapsam_enum_group_members
  34. ldapsam_enum_group_memberships
  35. ldapsam_map_posixgroup
  36. ldapsam_add_group_mapping_entry
  37. ldapsam_update_group_mapping_entry
  38. ldapsam_delete_group_mapping_entry
  39. ldapsam_setsamgrent
  40. ldapsam_endsamgrent
  41. ldapsam_getsamgrent
  42. ldapsam_enum_group_mapping
  43. ldapsam_modify_aliasmem
  44. ldapsam_add_aliasmem
  45. ldapsam_del_aliasmem
  46. ldapsam_enum_aliasmem
  47. ldapsam_alias_memberships
  48. ldapsam_set_account_policy_in_ldap
  49. ldapsam_set_account_policy
  50. ldapsam_get_account_policy_from_ldap
  51. ldapsam_get_account_policy
  52. ldapsam_lookup_rids
  53. get_ldap_filter
  54. talloc_attrs
  55. ldapsam_search_firstpage
  56. ldapsam_search_nextpage
  57. ldapsam_search_next_entry
  58. ldapsam_search_end
  59. ldapuser2displayentry
  60. ldapsam_search_users
  61. ldapgroup2displayentry
  62. ldapsam_search_grouptype
  63. ldapsam_search_groups
  64. ldapsam_search_aliases
  65. ldapsam_rid_algorithm
  66. ldapsam_get_new_rid
  67. ldapsam_new_rid_internal
  68. ldapsam_new_rid
  69. ldapsam_sid_to_id
  70. ldapsam_create_user
  71. ldapsam_delete_user
  72. ldapsam_create_dom_group
  73. ldapsam_delete_dom_group
  74. ldapsam_change_groupmem
  75. ldapsam_add_groupmem
  76. ldapsam_del_groupmem
  77. ldapsam_set_primary_group
  78. trusteddom_dn
  79. get_trusteddom_pw_int
  80. ldapsam_get_trusteddom_pw
  81. ldapsam_set_trusteddom_pw
  82. ldapsam_del_trusteddom_pw
  83. ldapsam_enum_trusteddoms
  84. free_private_data
  85. pdb_init_ldapsam_common
  86. pdb_init_ldapsam_compat
  87. pdb_init_ldapsam
  88. pdb_ldap_init

   1 /* 
   2    Unix SMB/CIFS implementation.
   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    Copyright (C) Simo Sorce                     2006
  10     
  11    This program is free software; you can redistribute it and/or modify
  12    it under the terms of the GNU General Public License as published by
  13    the Free Software Foundation; either version 3 of the License, or
  14    (at your option) any later version.
  15    
  16    This program is distributed in the hope that it will be useful,
  17    but WITHOUT ANY WARRANTY; without even the implied warranty of
  18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19    GNU General Public License for more details.
  20    
  21    You should have received a copy of the GNU General Public License
  22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  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/struct samu
  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 #include "smbldap.h"
  81 
  82 /**********************************************************************
  83  Simple helper function to make stuff better readable
  84  **********************************************************************/
  85 
  86 static LDAP *priv2ld(struct ldapsam_privates *priv)
     /* [<][>][^][v][top][bottom][index][help] */
  87 {
  88         return priv->smbldap_state->ldap_struct;
  89 }
  90 
  91 /**********************************************************************
  92  Get the attribute name given a user schame version.
  93  **********************************************************************/
  94  
  95 static const char* get_userattr_key2string( int schema_ver, int key )
     /* [<][>][^][v][top][bottom][index][help] */
  96 {
  97         switch ( schema_ver ) {
  98                 case SCHEMAVER_SAMBAACCOUNT:
  99                         return get_attr_key2string( attrib_map_v22, key );
 100                         
 101                 case SCHEMAVER_SAMBASAMACCOUNT:
 102                         return get_attr_key2string( attrib_map_v30, key );
 103                         
 104                 default:
 105                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
 106                         break;
 107         }
 108         return NULL;
 109 }
 110 
 111 /**********************************************************************
 112  Return the list of attribute names given a user schema version.
 113 **********************************************************************/
 114 
 115 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
     /* [<][>][^][v][top][bottom][index][help] */
 116 {
 117         switch ( schema_ver ) {
 118                 case SCHEMAVER_SAMBAACCOUNT:
 119                         return get_attr_list( mem_ctx, attrib_map_v22 );
 120                         
 121                 case SCHEMAVER_SAMBASAMACCOUNT:
 122                         return get_attr_list( mem_ctx, attrib_map_v30 );
 123                 default:
 124                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
 125                         break;
 126         }
 127         
 128         return NULL;
 129 }
 130 
 131 /**************************************************************************
 132  Return the list of attribute names to delete given a user schema version.
 133 **************************************************************************/
 134 
 135 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
     /* [<][>][^][v][top][bottom][index][help] */
 136                                               int schema_ver )
 137 {
 138         switch ( schema_ver ) {
 139                 case SCHEMAVER_SAMBAACCOUNT:
 140                         return get_attr_list( mem_ctx,
 141                                               attrib_map_to_delete_v22 );
 142                         
 143                 case SCHEMAVER_SAMBASAMACCOUNT:
 144                         return get_attr_list( mem_ctx,
 145                                               attrib_map_to_delete_v30 );
 146                 default:
 147                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
 148                         break;
 149         }
 150         
 151         return NULL;
 152 }
 153 
 154 
 155 /*******************************************************************
 156  Generate the LDAP search filter for the objectclass based on the 
 157  version of the schema we are using.
 158 ******************************************************************/
 159 
 160 static const char* get_objclass_filter( int schema_ver )
     /* [<][>][^][v][top][bottom][index][help] */
 161 {
 162         fstring objclass_filter;
 163         char *result;
 164         
 165         switch( schema_ver ) {
 166                 case SCHEMAVER_SAMBAACCOUNT:
 167                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
 168                         break;
 169                 case SCHEMAVER_SAMBASAMACCOUNT:
 170                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
 171                         break;
 172                 default:
 173                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
 174                         objclass_filter[0] = '\0';
 175                         break;
 176         }
 177         
 178         result = talloc_strdup(talloc_tos(), objclass_filter);
 179         SMB_ASSERT(result != NULL);
 180         return result;
 181 }
 182 
 183 /*****************************************************************
 184  Scan a sequence number off OpenLDAP's syncrepl contextCSN
 185 ******************************************************************/
 186 
 187 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
     /* [<][>][^][v][top][bottom][index][help] */
 188 {
 189         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
 190         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
 191         LDAPMessage *msg = NULL;
 192         LDAPMessage *entry = NULL;
 193         TALLOC_CTX *mem_ctx;
 194         char **values = NULL;
 195         int rc, num_result, num_values, rid;
 196         char *suffix = NULL;
 197         char *tok;
 198         const char *p;
 199         const char **attrs;
 200 
 201         /* Unfortunatly there is no proper way to detect syncrepl-support in
 202          * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
 203          * but do not show up in the root-DSE yet. Neither we can query the
 204          * subschema-context for the syncProviderSubentry or syncConsumerSubentry
 205          * objectclass. Currently we require lp_ldap_suffix() to show up as
 206          * namingContext.  -  Guenther
 207          */
 208 
 209         if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
 210                 return ntstatus;
 211         }
 212 
 213         if (!seq_num) {
 214                 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
 215                 return ntstatus;
 216         }
 217 
 218         if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix())) {
 219                 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
 220                          "as top-level namingContext\n", lp_ldap_suffix()));
 221                 return ntstatus;
 222         }
 223 
 224         mem_ctx = talloc_init("ldapsam_get_seq_num");
 225 
 226         if (mem_ctx == NULL)
 227                 return NT_STATUS_NO_MEMORY;
 228 
 229         if ((attrs = TALLOC_ARRAY(mem_ctx, const char *, 2)) == NULL) {
 230                 ntstatus = NT_STATUS_NO_MEMORY;
 231                 goto done;
 232         }
 233 
 234         /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
 235         rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
 236         if (rid > 0) {
 237 
 238                 /* consumer syncreplCookie: */
 239                 /* csn=20050126161620Z#0000001#00#00000 */
 240                 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
 241                 attrs[1] = NULL;
 242                 suffix = talloc_asprintf(mem_ctx,
 243                                 "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
 244                 if (!suffix) {
 245                         ntstatus = NT_STATUS_NO_MEMORY;
 246                         goto done;
 247                 }
 248         } else {
 249 
 250                 /* provider contextCSN */
 251                 /* 20050126161620Z#000009#00#000000 */
 252                 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
 253                 attrs[1] = NULL;
 254                 suffix = talloc_asprintf(mem_ctx,
 255                                 "cn=ldapsync,%s", lp_ldap_suffix());
 256 
 257                 if (!suffix) {
 258                         ntstatus = NT_STATUS_NO_MEMORY;
 259                         goto done;
 260                 }
 261         }
 262 
 263         rc = smbldap_search(ldap_state->smbldap_state, suffix,
 264                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
 265 
 266         if (rc != LDAP_SUCCESS) {
 267                 goto done;
 268         }
 269 
 270         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
 271         if (num_result != 1) {
 272                 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
 273                 goto done;
 274         }
 275 
 276         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
 277         if (entry == NULL) {
 278                 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
 279                 goto done;
 280         }
 281 
 282         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
 283         if (values == NULL) {
 284                 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
 285                 goto done;
 286         }
 287 
 288         num_values = ldap_count_values(values);
 289         if (num_values == 0) {
 290                 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
 291                 goto done;
 292         }
 293 
 294         p = values[0];
 295         if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
 296                 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
 297                 goto done;
 298         }
 299 
 300         p = tok;
 301         if (!strncmp(p, "csn=", strlen("csn=")))
 302                 p += strlen("csn=");
 303 
 304         DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
 305 
 306         *seq_num = generalized_to_unix_time(p);
 307 
 308         /* very basic sanity check */
 309         if (*seq_num <= 0) {
 310                 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n", 
 311                         (int)*seq_num));
 312                 goto done;
 313         }
 314 
 315         ntstatus = NT_STATUS_OK;
 316 
 317  done:
 318         if (values != NULL)
 319                 ldap_value_free(values);
 320         if (msg != NULL)
 321                 ldap_msgfree(msg);
 322         if (mem_ctx)
 323                 talloc_destroy(mem_ctx);
 324 
 325         return ntstatus;
 326 }
 327 
 328 /*******************************************************************
 329  Run the search by name.
 330 ******************************************************************/
 331 
 332 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
 333                                           const char *user,
 334                                           LDAPMessage ** result,
 335                                           const char **attr)
 336 {
 337         char *filter = NULL;
 338         char *escape_user = escape_ldap_string_alloc(user);
 339         int ret = -1;
 340 
 341         if (!escape_user) {
 342                 return LDAP_NO_MEMORY;
 343         }
 344 
 345         /*
 346          * in the filter expression, replace %u with the real name
 347          * so in ldap filter, %u MUST exist :-)
 348          */
 349         filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
 350                 get_objclass_filter(ldap_state->schema_ver));
 351         if (!filter) {
 352                 SAFE_FREE(escape_user);
 353                 return LDAP_NO_MEMORY;
 354         }
 355         /*
 356          * have to use this here because $ is filtered out
 357          * in string_sub
 358          */
 359 
 360         filter = talloc_all_string_sub(talloc_tos(),
 361                                 filter, "%u", escape_user);
 362         SAFE_FREE(escape_user);
 363         if (!filter) {
 364                 return LDAP_NO_MEMORY;
 365         }
 366 
 367         ret = smbldap_search_suffix(ldap_state->smbldap_state,
 368                         filter, attr, result);
 369         TALLOC_FREE(filter);
 370         return ret;
 371 }
 372 
 373 /*******************************************************************
 374  Run the search by rid.
 375 ******************************************************************/
 376 
 377 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
 378                                          uint32 rid, LDAPMessage ** result,
 379                                          const char **attr)
 380 {
 381         char *filter = NULL;
 382         int rc;
 383 
 384         filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
 385                 get_objclass_filter(ldap_state->schema_ver));
 386         if (!filter) {
 387                 return LDAP_NO_MEMORY;
 388         }
 389 
 390         rc = smbldap_search_suffix(ldap_state->smbldap_state,
 391                         filter, attr, result);
 392         TALLOC_FREE(filter);
 393         return rc;
 394 }
 395 
 396 /*******************************************************************
 397  Run the search by SID.
 398 ******************************************************************/
 399 
 400 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
 401                                  const DOM_SID *sid, LDAPMessage ** result,
 402                                  const char **attr)
 403 {
 404         char *filter = NULL;
 405         int rc;
 406         fstring sid_string;
 407 
 408         filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
 409                 get_userattr_key2string(ldap_state->schema_ver,
 410                         LDAP_ATTR_USER_SID),
 411                 sid_to_fstring(sid_string, sid),
 412                 get_objclass_filter(ldap_state->schema_ver));
 413         if (!filter) {
 414                 return LDAP_NO_MEMORY;
 415         }
 416 
 417         rc = smbldap_search_suffix(ldap_state->smbldap_state,
 418                         filter, attr, result);
 419 
 420         TALLOC_FREE(filter);
 421         return rc;
 422 }
 423 
 424 /*******************************************************************
 425  Delete complete object or objectclass and attrs from
 426  object found in search_result depending on lp_ldap_delete_dn
 427 ******************************************************************/
 428 
 429 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
     /* [<][>][^][v][top][bottom][index][help] */
 430                                 TALLOC_CTX *mem_ctx,
 431                                 LDAPMessage *entry,
 432                                 const char *objectclass,
 433                                 const char **attrs)
 434 {
 435         LDAPMod **mods = NULL;
 436         char *name;
 437         const char *dn;
 438         BerElement *ptr = NULL;
 439 
 440         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
 441         if (dn == NULL) {
 442                 return LDAP_NO_MEMORY;
 443         }
 444 
 445         if (lp_ldap_delete_dn()) {
 446                 return smbldap_delete(priv->smbldap_state, dn);
 447         }
 448 
 449         /* Ok, delete only the SAM attributes */
 450         
 451         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
 452              name != NULL;
 453              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
 454                 const char **attrib;
 455 
 456                 /* We are only allowed to delete the attributes that
 457                    really exist. */
 458 
 459                 for (attrib = attrs; *attrib != NULL; attrib++) {
 460                         if (strequal(*attrib, name)) {
 461                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
 462                                            "attribute %s\n", name));
 463                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
 464                                                 NULL);
 465                         }
 466                 }
 467                 ldap_memfree(name);
 468         }
 469 
 470         if (ptr != NULL) {
 471                 ber_free(ptr, 0);
 472         }
 473 
 474         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
 475         talloc_autofree_ldapmod(mem_ctx, mods);
 476 
 477         return smbldap_modify(priv->smbldap_state, dn, mods);
 478 }
 479 
 480 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
     /* [<][>][^][v][top][bottom][index][help] */
 481 {
 482         char *temp;
 483         struct tm tm;
 484 
 485         temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
 486                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
 487                         talloc_tos());
 488         if (!temp) {
 489                 return (time_t) 0;
 490         }
 491 
 492         if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
 493                 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
 494                         (char*)temp));
 495                 TALLOC_FREE(temp);
 496                 return (time_t) 0;
 497         }
 498         TALLOC_FREE(temp);
 499         tzset();
 500         return timegm(&tm);
 501 }
 502 
 503 /**********************************************************************
 504  Initialize struct samu from an LDAP query.
 505  (Based on init_sam_from_buffer in pdb_tdb.c)
 506 *********************************************************************/
 507 
 508 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
 509                                 struct samu * sampass,
 510                                 LDAPMessage * entry)
 511 {
 512         time_t  logon_time,
 513                         logoff_time,
 514                         kickoff_time,
 515                         pass_last_set_time,
 516                         pass_can_change_time,
 517                         pass_must_change_time,
 518                         ldap_entry_time,
 519                         bad_password_time;
 520         char *username = NULL,
 521                         *domain = NULL,
 522                         *nt_username = NULL,
 523                         *fullname = NULL,
 524                         *homedir = NULL,
 525                         *dir_drive = NULL,
 526                         *logon_script = NULL,
 527                         *profile_path = NULL,
 528                         *acct_desc = NULL,
 529                         *workstations = NULL,
 530                         *munged_dial = NULL;
 531         uint32          user_rid;
 532         uint8           smblmpwd[LM_HASH_LEN],
 533                         smbntpwd[NT_HASH_LEN];
 534         bool            use_samba_attrs = True;
 535         uint32          acct_ctrl = 0;
 536         uint16          logon_divs;
 537         uint16          bad_password_count = 0,
 538                         logon_count = 0;
 539         uint32 hours_len;
 540         uint8           hours[MAX_HOURS_LEN];
 541         char *temp = NULL;
 542         LOGIN_CACHE     *cache_entry = NULL;
 543         uint32          pwHistLen;
 544         bool expand_explicit = lp_passdb_expand_explicit();
 545         bool ret = false;
 546         TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
 547 
 548         if (!ctx) {
 549                 return false;
 550         }
 551         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
 552                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
 553                 goto fn_exit;
 554         }
 555 
 556         if (priv2ld(ldap_state) == NULL) {
 557                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
 558                           "ldap_struct is NULL!\n"));
 559                 goto fn_exit;
 560         }
 561 
 562         if (!(username = smbldap_talloc_smallest_attribute(priv2ld(ldap_state),
 563                                         entry,
 564                                         "uid",
 565                                         ctx))) {
 566                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
 567                           "this user!\n"));
 568                 goto fn_exit;
 569         }
 570 
 571         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
 572 
 573         nt_username = talloc_strdup(ctx, username);
 574         if (!nt_username) {
 575                 goto fn_exit;
 576         }
 577 
 578         domain = talloc_strdup(ctx, ldap_state->domain_name);
 579         if (!domain) {
 580                 goto fn_exit;
 581         }
 582 
 583         pdb_set_username(sampass, username, PDB_SET);
 584 
 585         pdb_set_domain(sampass, domain, PDB_DEFAULT);
 586         pdb_set_nt_username(sampass, nt_username, PDB_SET);
 587 
 588         /* deal with different attributes between the schema first */
 589 
 590         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
 591                 if ((temp = smbldap_talloc_single_attribute(
 592                                 ldap_state->smbldap_state->ldap_struct,
 593                                 entry,
 594                                 get_userattr_key2string(ldap_state->schema_ver,
 595                                         LDAP_ATTR_USER_SID),
 596                                 ctx))!=NULL) {
 597                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
 598                 }
 599         } else {
 600                 if ((temp = smbldap_talloc_single_attribute(
 601                                 ldap_state->smbldap_state->ldap_struct,
 602                                 entry,
 603                                 get_userattr_key2string(ldap_state->schema_ver,
 604                                         LDAP_ATTR_USER_RID),
 605                                 ctx))!=NULL) {
 606                         user_rid = (uint32)atol(temp);
 607                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
 608                 }
 609         }
 610 
 611         if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
 612                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
 613                         get_userattr_key2string(ldap_state->schema_ver,
 614                                 LDAP_ATTR_USER_SID),
 615                         get_userattr_key2string(ldap_state->schema_ver,
 616                                 LDAP_ATTR_USER_RID),
 617                         username));
 618                 return False;
 619         }
 620 
 621         temp = smbldap_talloc_single_attribute(
 622                         ldap_state->smbldap_state->ldap_struct,
 623                         entry,
 624                         get_userattr_key2string(ldap_state->schema_ver,
 625                                 LDAP_ATTR_PWD_LAST_SET),
 626                         ctx);
 627         if (temp) {
 628                 pass_last_set_time = (time_t) atol(temp);
 629                 pdb_set_pass_last_set_time(sampass,
 630                                 pass_last_set_time, PDB_SET);
 631         }
 632 
 633         temp = smbldap_talloc_single_attribute(
 634                         ldap_state->smbldap_state->ldap_struct,
 635                         entry,
 636                         get_userattr_key2string(ldap_state->schema_ver,
 637                                 LDAP_ATTR_LOGON_TIME),
 638                         ctx);
 639         if (temp) {
 640                 logon_time = (time_t) atol(temp);
 641                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
 642         }
 643 
 644         temp = smbldap_talloc_single_attribute(
 645                         ldap_state->smbldap_state->ldap_struct,
 646                         entry,
 647                         get_userattr_key2string(ldap_state->schema_ver,
 648                                 LDAP_ATTR_LOGOFF_TIME),
 649                         ctx);
 650         if (temp) {
 651                 logoff_time = (time_t) atol(temp);
 652                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
 653         }
 654 
 655         temp = smbldap_talloc_single_attribute(
 656                         ldap_state->smbldap_state->ldap_struct,
 657                         entry,
 658                         get_userattr_key2string(ldap_state->schema_ver,
 659                                 LDAP_ATTR_KICKOFF_TIME),
 660                         ctx);
 661         if (temp) {
 662                 kickoff_time = (time_t) atol(temp);
 663                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
 664         }
 665 
 666         temp = smbldap_talloc_single_attribute(
 667                         ldap_state->smbldap_state->ldap_struct,
 668                         entry,
 669                         get_userattr_key2string(ldap_state->schema_ver,
 670                                 LDAP_ATTR_PWD_CAN_CHANGE),
 671                         ctx);
 672         if (temp) {
 673                 pass_can_change_time = (time_t) atol(temp);
 674                 pdb_set_pass_can_change_time(sampass,
 675                                 pass_can_change_time, PDB_SET);
 676         }
 677 
 678         temp = smbldap_talloc_single_attribute(
 679                         ldap_state->smbldap_state->ldap_struct,
 680                         entry,
 681                         get_userattr_key2string(ldap_state->schema_ver,
 682                                 LDAP_ATTR_PWD_MUST_CHANGE),
 683                         ctx);
 684         if (temp) {
 685                 pass_must_change_time = (time_t) atol(temp);
 686                 pdb_set_pass_must_change_time(sampass,
 687                                 pass_must_change_time, PDB_SET);
 688         }
 689 
 690         /* recommend that 'gecos' and 'displayName' should refer to the same
 691          * attribute OID.  userFullName depreciated, only used by Samba
 692          * primary rules of LDAP: don't make a new attribute when one is already defined
 693          * that fits your needs; using cn then displayName rather than 'userFullName'
 694          */
 695 
 696         fullname = smbldap_talloc_single_attribute(
 697                         ldap_state->smbldap_state->ldap_struct,
 698                         entry,
 699                         get_userattr_key2string(ldap_state->schema_ver,
 700                                 LDAP_ATTR_DISPLAY_NAME),
 701                         ctx);
 702         if (fullname) {
 703                 pdb_set_fullname(sampass, fullname, PDB_SET);
 704         } else {
 705                 fullname = smbldap_talloc_single_attribute(
 706                                 ldap_state->smbldap_state->ldap_struct,
 707                                 entry,
 708                                 get_userattr_key2string(ldap_state->schema_ver,
 709                                         LDAP_ATTR_CN),
 710                                 ctx);
 711                 if (fullname) {
 712                         pdb_set_fullname(sampass, fullname, PDB_SET);
 713                 }
 714         }
 715 
 716         dir_drive = smbldap_talloc_single_attribute(
 717                         ldap_state->smbldap_state->ldap_struct,
 718                         entry,
 719                         get_userattr_key2string(ldap_state->schema_ver,
 720                                 LDAP_ATTR_HOME_DRIVE),
 721                         ctx);
 722         if (dir_drive) {
 723                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
 724         } else {
 725                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
 726         }
 727 
 728         homedir = smbldap_talloc_single_attribute(
 729                         ldap_state->smbldap_state->ldap_struct,
 730                         entry,
 731                         get_userattr_key2string(ldap_state->schema_ver,
 732                                 LDAP_ATTR_HOME_PATH),
 733                         ctx);
 734         if (homedir) {
 735                 if (expand_explicit) {
 736                         homedir = talloc_sub_basic(ctx,
 737                                                 username,
 738                                                 domain,
 739                                                 homedir);
 740                         if (!homedir) {
 741                                 goto fn_exit;
 742                         }
 743                 }
 744                 pdb_set_homedir(sampass, homedir, PDB_SET);
 745         } else {
 746                 pdb_set_homedir(sampass,
 747                         talloc_sub_basic(ctx, username, domain,
 748                                          lp_logon_home()),
 749                         PDB_DEFAULT);
 750         }
 751 
 752         logon_script = smbldap_talloc_single_attribute(
 753                         ldap_state->smbldap_state->ldap_struct,
 754                         entry,
 755                         get_userattr_key2string(ldap_state->schema_ver,
 756                                 LDAP_ATTR_LOGON_SCRIPT),
 757                         ctx);
 758         if (logon_script) {
 759                 if (expand_explicit) {
 760                         logon_script = talloc_sub_basic(ctx,
 761                                                 username,
 762                                                 domain,
 763                                                 logon_script);
 764                         if (!logon_script) {
 765                                 goto fn_exit;
 766                         }
 767                 }
 768                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
 769         } else {
 770                 pdb_set_logon_script(sampass,
 771                         talloc_sub_basic(ctx, username, domain,
 772                                          lp_logon_script()),
 773                         PDB_DEFAULT );
 774         }
 775 
 776         profile_path = smbldap_talloc_single_attribute(
 777                         ldap_state->smbldap_state->ldap_struct,
 778                         entry,
 779                         get_userattr_key2string(ldap_state->schema_ver,
 780                                 LDAP_ATTR_PROFILE_PATH),
 781                         ctx);
 782         if (profile_path) {
 783                 if (expand_explicit) {
 784                         profile_path = talloc_sub_basic(ctx,
 785                                                 username,
 786                                                 domain,
 787                                                 profile_path);
 788                         if (!profile_path) {
 789                                 goto fn_exit;
 790                         }
 791                 }
 792                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
 793         } else {
 794                 pdb_set_profile_path(sampass,
 795                         talloc_sub_basic(ctx, username, domain,
 796                                           lp_logon_path()),
 797                         PDB_DEFAULT );
 798         }
 799 
 800         acct_desc = smbldap_talloc_single_attribute(
 801                         ldap_state->smbldap_state->ldap_struct,
 802                         entry,
 803                         get_userattr_key2string(ldap_state->schema_ver,
 804                                 LDAP_ATTR_DESC),
 805                         ctx);
 806         if (acct_desc) {
 807                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
 808         }
 809 
 810         workstations = smbldap_talloc_single_attribute(
 811                         ldap_state->smbldap_state->ldap_struct,
 812                         entry,
 813                         get_userattr_key2string(ldap_state->schema_ver,
 814                                 LDAP_ATTR_USER_WKS),
 815                         ctx);
 816         if (workstations) {
 817                 pdb_set_workstations(sampass, workstations, PDB_SET);
 818         }
 819 
 820         munged_dial = smbldap_talloc_single_attribute(
 821                         ldap_state->smbldap_state->ldap_struct,
 822                         entry,
 823                         get_userattr_key2string(ldap_state->schema_ver,
 824                                 LDAP_ATTR_MUNGED_DIAL),
 825                         ctx);
 826         if (munged_dial) {
 827                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
 828         }
 829 
 830         /* FIXME: hours stuff should be cleaner */
 831 
 832         logon_divs = 168;
 833         hours_len = 21;
 834         memset(hours, 0xff, hours_len);
 835 
 836         if (ldap_state->is_nds_ldap) {
 837                 char *user_dn;
 838                 size_t pwd_len;
 839                 char clear_text_pw[512];
 840 
 841                 /* Make call to Novell eDirectory ldap extension to get clear text password.
 842                         NOTE: This will only work if we have an SSL connection to eDirectory. */
 843                 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
 844                 if (user_dn != NULL) {
 845                         DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
 846 
 847                         pwd_len = sizeof(clear_text_pw);
 848                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
 849                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
 850                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
 851                                         TALLOC_FREE(user_dn);
 852                                         return False;
 853                                 }
 854                                 ZERO_STRUCT(smblmpwd);
 855                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
 856                                         TALLOC_FREE(user_dn);
 857                                         return False;
 858                                 }
 859                                 ZERO_STRUCT(smbntpwd);
 860                                 use_samba_attrs = False;
 861                         }
 862 
 863                         TALLOC_FREE(user_dn);
 864 
 865                 } else {
 866                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
 867                 }
 868         }
 869 
 870         if (use_samba_attrs) {
 871                 temp = smbldap_talloc_single_attribute(
 872                                 ldap_state->smbldap_state->ldap_struct,
 873                                 entry,
 874                                 get_userattr_key2string(ldap_state->schema_ver,
 875                                         LDAP_ATTR_LMPW),
 876                                 ctx);
 877                 if (temp) {
 878                         pdb_gethexpwd(temp, smblmpwd);
 879                         memset((char *)temp, '\0', strlen(temp)+1);
 880                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
 881                                 goto fn_exit;
 882                         }
 883                         ZERO_STRUCT(smblmpwd);
 884                 }
 885 
 886                 temp = smbldap_talloc_single_attribute(
 887                                 ldap_state->smbldap_state->ldap_struct,
 888                                 entry,
 889                                 get_userattr_key2string(ldap_state->schema_ver,
 890                                         LDAP_ATTR_NTPW),
 891                                 ctx);
 892                 if (temp) {
 893                         pdb_gethexpwd(temp, smbntpwd);
 894                         memset((char *)temp, '\0', strlen(temp)+1);
 895                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
 896                                 goto fn_exit;
 897                         }
 898                         ZERO_STRUCT(smbntpwd);
 899                 }
 900         }
 901 
 902         pwHistLen = 0;
 903 
 904         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
 905         if (pwHistLen > 0){
 906                 uint8 *pwhist = NULL;
 907                 int i;
 908                 char *history_string = TALLOC_ARRAY(ctx, char,
 909                                                 MAX_PW_HISTORY_LEN*64);
 910 
 911                 if (!history_string) {
 912                         goto fn_exit;
 913                 }
 914 
 915                 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
 916 
 917                 if ((pwhist = TALLOC_ARRAY(ctx, uint8,
 918                                         pwHistLen * PW_HISTORY_ENTRY_LEN)) ==
 919                                 NULL){
 920                         DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
 921                         goto fn_exit;
 922                 }
 923                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
 924 
 925                 if (smbldap_get_single_attribute(
 926                                 ldap_state->smbldap_state->ldap_struct,
 927                                 entry,
 928                                 get_userattr_key2string(ldap_state->schema_ver,
 929                                         LDAP_ATTR_PWD_HISTORY),
 930                                 history_string,
 931                                 MAX_PW_HISTORY_LEN*64)) {
 932                         bool hex_failed = false;
 933                         for (i = 0; i < pwHistLen; i++){
 934                                 /* Get the 16 byte salt. */
 935                                 if (!pdb_gethexpwd(&history_string[i*64],
 936                                         &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
 937                                         hex_failed = true;
 938                                         break;
 939                                 }
 940                                 /* Get the 16 byte MD5 hash of salt+passwd. */
 941                                 if (!pdb_gethexpwd(&history_string[(i*64)+32],
 942                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
 943                                                 PW_HISTORY_SALT_LEN])) {
 944                                         hex_failed = True;
 945                                         break;
 946                                 }
 947                         }
 948                         if (hex_failed) {
 949                                 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
 950                                         username));
 951                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
 952                         }
 953                 }
 954                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
 955                         goto fn_exit;
 956                 }
 957         }
 958 
 959         temp = smbldap_talloc_single_attribute(
 960                         ldap_state->smbldap_state->ldap_struct,
 961                         entry,
 962                         get_userattr_key2string(ldap_state->schema_ver,
 963                                 LDAP_ATTR_ACB_INFO),
 964                         ctx);
 965         if (temp) {
 966                 acct_ctrl = pdb_decode_acct_ctrl(temp);
 967 
 968                 if (acct_ctrl == 0) {
 969                         acct_ctrl |= ACB_NORMAL;
 970                 }
 971 
 972                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
 973         } else {
 974                 acct_ctrl |= ACB_NORMAL;
 975         }
 976 
 977         pdb_set_hours_len(sampass, hours_len, PDB_SET);
 978         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
 979 
 980         temp = smbldap_talloc_single_attribute(
 981                         ldap_state->smbldap_state->ldap_struct,
 982                         entry,
 983                         get_userattr_key2string(ldap_state->schema_ver,
 984                                 LDAP_ATTR_BAD_PASSWORD_COUNT),
 985                         ctx);
 986         if (temp) {
 987                 bad_password_count = (uint32) atol(temp);
 988                 pdb_set_bad_password_count(sampass,
 989                                 bad_password_count, PDB_SET);
 990         }
 991 
 992         temp = smbldap_talloc_single_attribute(
 993                         ldap_state->smbldap_state->ldap_struct,
 994                         entry,
 995                         get_userattr_key2string(ldap_state->schema_ver,
 996                                 LDAP_ATTR_BAD_PASSWORD_TIME),
 997                         ctx);
 998         if (temp) {
 999                 bad_password_time = (time_t) atol(temp);
1000                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
1001         }
1002 
1003 
1004         temp = smbldap_talloc_single_attribute(
1005                         ldap_state->smbldap_state->ldap_struct,
1006                         entry,
1007                         get_userattr_key2string(ldap_state->schema_ver,
1008                                 LDAP_ATTR_LOGON_COUNT),
1009                         ctx);
1010         if (temp) {
1011                 logon_count = (uint32) atol(temp);
1012                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
1013         }
1014 
1015         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
1016 
1017         temp = smbldap_talloc_single_attribute(
1018                         ldap_state->smbldap_state->ldap_struct,
1019                         entry,
1020                         get_userattr_key2string(ldap_state->schema_ver,
1021                                 LDAP_ATTR_LOGON_HOURS),
1022                         ctx);
1023         if (temp) {
1024                 pdb_gethexhours(temp, hours);
1025                 memset((char *)temp, '\0', strlen(temp) +1);
1026                 pdb_set_hours(sampass, hours, PDB_SET);
1027                 ZERO_STRUCT(hours);
1028         }
1029 
1030         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
1031                 temp = smbldap_talloc_single_attribute(
1032                                 priv2ld(ldap_state),
1033                                 entry,
1034                                 "uidNumber",
1035                                 ctx);
1036                 if (temp) {
1037                         /* We've got a uid, feed the cache */
1038                         uid_t uid = strtoul(temp, NULL, 10);
1039                         store_uid_sid_cache(pdb_get_user_sid(sampass), uid);
1040                 }
1041         }
1042 
1043         /* check the timestamp of the cache vs ldap entry */
1044         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1045                                                             entry))) {
1046                 ret = true;
1047                 goto fn_exit;
1048         }
1049 
1050         /* see if we have newer updates */
1051         if (!(cache_entry = login_cache_read(sampass))) {
1052                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1053                            (unsigned int)pdb_get_bad_password_count(sampass),
1054                            (unsigned int)pdb_get_bad_password_time(sampass)));
1055                 ret = true;
1056                 goto fn_exit;
1057         }
1058 
1059         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1060                   (unsigned int)ldap_entry_time,
1061                   (unsigned int)cache_entry->entry_timestamp,
1062                   (unsigned int)cache_entry->bad_password_time));
1063 
1064         if (ldap_entry_time > cache_entry->entry_timestamp) {
1065                 /* cache is older than directory , so
1066                    we need to delete the entry but allow the
1067                    fields to be written out */
1068                 login_cache_delentry(sampass);
1069         } else {
1070                 /* read cache in */
1071                 pdb_set_acct_ctrl(sampass,
1072                                   pdb_get_acct_ctrl(sampass) |
1073                                   (cache_entry->acct_ctrl & ACB_AUTOLOCK),
1074                                   PDB_SET);
1075                 pdb_set_bad_password_count(sampass,
1076                                            cache_entry->bad_password_count,
1077                                            PDB_SET);
1078                 pdb_set_bad_password_time(sampass,
1079                                           cache_entry->bad_password_time,
1080                                           PDB_SET);
1081         }
1082 
1083         ret = true;
1084 
1085   fn_exit:
1086 
1087         TALLOC_FREE(ctx);
1088         SAFE_FREE(cache_entry);
1089         return ret;
1090 }
1091 
1092 /**********************************************************************
1093  Initialize the ldap db from a struct samu. Called on update.
1094  (Based on init_buffer_from_sam in pdb_tdb.c)
1095 *********************************************************************/
1096 
1097 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
1098                                 LDAPMessage *existing,
1099                                 LDAPMod *** mods, struct samu * sampass,
1100                                 bool (*need_update)(const struct samu *,
1101                                                     enum pdb_elements))
1102 {
1103         char *temp = NULL;
1104         uint32 rid;
1105 
1106         if (mods == NULL || sampass == NULL) {
1107                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1108                 return False;
1109         }
1110 
1111         *mods = NULL;
1112 
1113         /*
1114          * took out adding "objectclass: sambaAccount"
1115          * do this on a per-mod basis
1116          */
1117         if (need_update(sampass, PDB_USERNAME)) {
1118                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1119                               "uid", pdb_get_username(sampass));
1120                 if (ldap_state->is_nds_ldap) {
1121                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1122                                       "cn", pdb_get_username(sampass));
1123                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1124                                       "sn", pdb_get_username(sampass));
1125                 }
1126         }
1127 
1128         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1129 
1130         /* only update the RID if we actually need to */
1131         if (need_update(sampass, PDB_USERSID)) {
1132                 fstring sid_string;
1133                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
1134 
1135                 switch ( ldap_state->schema_ver ) {
1136                         case SCHEMAVER_SAMBAACCOUNT:
1137                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
1138                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
1139                                                   sid_string_dbg(user_sid),
1140                                                   sid_string_dbg(
1141                                                           &ldap_state->domain_sid)));
1142                                         return False;
1143                                 }
1144                                 if (asprintf(&temp, "%i", rid) < 0) {
1145                                         return false;
1146                                 }
1147                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1148                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
1149                                         temp);
1150                                 SAFE_FREE(temp);
1151                                 break;
1152 
1153                         case SCHEMAVER_SAMBASAMACCOUNT:
1154                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1155                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
1156                                         sid_to_fstring(sid_string, user_sid));
1157                                 break;
1158 
1159                         default:
1160                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1161                                 break;
1162                 }
1163         }
1164 
1165         /* we don't need to store the primary group RID - so leaving it
1166            'free' to hang off the unix primary group makes life easier */
1167 
1168         if (need_update(sampass, PDB_GROUPSID)) {
1169                 fstring sid_string;
1170                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
1171 
1172                 switch ( ldap_state->schema_ver ) {
1173                         case SCHEMAVER_SAMBAACCOUNT:
1174                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1175                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1176                                                   sid_string_dbg(group_sid),
1177                                                   sid_string_dbg(
1178                                                           &ldap_state->domain_sid)));
1179                                         return False;
1180                                 }
1181 
1182                                 if (asprintf(&temp, "%i", rid) < 0) {
1183                                         return false;
1184                                 }
1185                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1186                                         get_userattr_key2string(ldap_state->schema_ver, 
1187                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1188                                 SAFE_FREE(temp);
1189                                 break;
1190 
1191                         case SCHEMAVER_SAMBASAMACCOUNT:
1192                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1193                                         get_userattr_key2string(ldap_state->schema_ver, 
1194                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1195                                 break;
1196 
1197                         default:
1198                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1199                                 break;
1200                 }
1201 
1202         }
1203 
1204         /* displayName, cn, and gecos should all be the same
1205          *  most easily accomplished by giving them the same OID
1206          *  gecos isn't set here b/c it should be handled by the
1207          *  add-user script
1208          *  We change displayName only and fall back to cn if
1209          *  it does not exist.
1210          */
1211 
1212         if (need_update(sampass, PDB_FULLNAME))
1213                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1214                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1215                         pdb_get_fullname(sampass));
1216 
1217         if (need_update(sampass, PDB_ACCTDESC))
1218                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1219                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1220                         pdb_get_acct_desc(sampass));
1221 
1222         if (need_update(sampass, PDB_WORKSTATIONS))
1223                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1224                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1225                         pdb_get_workstations(sampass));
1226 
1227         if (need_update(sampass, PDB_MUNGEDDIAL))
1228                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1229                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1230                         pdb_get_munged_dial(sampass));
1231 
1232         if (need_update(sampass, PDB_SMBHOME))
1233                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1234                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1235                         pdb_get_homedir(sampass));
1236 
1237         if (need_update(sampass, PDB_DRIVE))
1238                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1239                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1240                         pdb_get_dir_drive(sampass));
1241 
1242         if (need_update(sampass, PDB_LOGONSCRIPT))
1243                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1244                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1245                         pdb_get_logon_script(sampass));
1246 
1247         if (need_update(sampass, PDB_PROFILE))
1248                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1249                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1250                         pdb_get_profile_path(sampass));
1251 
1252         if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1253                 return false;
1254         }
1255         if (need_update(sampass, PDB_LOGONTIME))
1256                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1257                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1258         SAFE_FREE(temp);
1259 
1260         if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1261                 return false;
1262         }
1263         if (need_update(sampass, PDB_LOGOFFTIME))
1264                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1265                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1266         SAFE_FREE(temp);
1267 
1268         if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1269                 return false;
1270         }
1271         if (need_update(sampass, PDB_KICKOFFTIME))
1272                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1273                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1274         SAFE_FREE(temp);
1275 
1276         if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1277                 return false;
1278         }
1279         if (need_update(sampass, PDB_CANCHANGETIME))
1280                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1281                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1282         SAFE_FREE(temp);
1283 
1284         if (asprintf(&temp, "%li", (long int)pdb_get_pass_must_change_time(sampass)) < 0) {
1285                 return false;
1286         }
1287         if (need_update(sampass, PDB_MUSTCHANGETIME))
1288                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1289                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1290         SAFE_FREE(temp);
1291 
1292         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1293                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1294 
1295                 if (need_update(sampass, PDB_LMPASSWD)) {
1296                         const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1297                         if (lm_pw) {
1298                                 char pwstr[34];
1299                                 pdb_sethexpwd(pwstr, lm_pw,
1300                                               pdb_get_acct_ctrl(sampass));
1301                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1302                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1303                                                  pwstr);
1304                         } else {
1305                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1306                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1307                                                  NULL);
1308                         }
1309                 }
1310                 if (need_update(sampass, PDB_NTPASSWD)) {
1311                         const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1312                         if (nt_pw) {
1313                                 char pwstr[34];
1314                                 pdb_sethexpwd(pwstr, nt_pw,
1315                                               pdb_get_acct_ctrl(sampass));
1316                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1317                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1318                                                  pwstr);
1319                         } else {
1320                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1321                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1322                                                  NULL);
1323                         }
1324                 }
1325 
1326                 if (need_update(sampass, PDB_PWHISTORY)) {
1327                         char *pwstr = NULL;
1328                         uint32 pwHistLen = 0;
1329                         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1330 
1331                         pwstr = SMB_MALLOC_ARRAY(char, 1024);
1332                         if (!pwstr) {
1333                                 return false;
1334                         }
1335                         if (pwHistLen == 0) {
1336                                 /* Remove any password history from the LDAP store. */
1337                                 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1338                                 pwstr[64] = '\0';
1339                         } else {
1340                                 int i;
1341                                 uint32 currHistLen = 0;
1342                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1343                                 if (pwhist != NULL) {
1344                                         /* We can only store (1024-1/64 password history entries. */
1345                                         pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1346                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1347                                                 /* Store the salt. */
1348                                                 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1349                                                 /* Followed by the md5 hash of salt + md4 hash */
1350                                                 pdb_sethexpwd(&pwstr[(i*64)+32],
1351                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1352                                                 DEBUG(100, ("pwstr=%s\n", pwstr));
1353                                         }
1354                                 }
1355                         }
1356                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1357                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1358                                          pwstr);
1359                         SAFE_FREE(pwstr);
1360                 }
1361 
1362                 if (need_update(sampass, PDB_PASSLASTSET)) {
1363                         if (asprintf(&temp, "%li",
1364                                 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1365                                 return false;
1366                         }
1367                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1368                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1369                                 temp);
1370                         SAFE_FREE(temp);
1371                 }
1372         }
1373 
1374         if (need_update(sampass, PDB_HOURS)) {
1375                 const uint8 *hours = pdb_get_hours(sampass);
1376                 if (hours) {
1377                         char hourstr[44];
1378                         pdb_sethexhours(hourstr, hours);
1379                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1380                                 existing,
1381                                 mods,
1382                                 get_userattr_key2string(ldap_state->schema_ver,
1383                                                 LDAP_ATTR_LOGON_HOURS),
1384                                 hourstr);
1385                 }
1386         }
1387 
1388         if (need_update(sampass, PDB_ACCTCTRL))
1389                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1390                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1391                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1392 
1393         /* password lockout cache:
1394            - If we are now autolocking or clearing, we write to ldap
1395            - If we are clearing, we delete the cache entry
1396            - If the count is > 0, we update the cache
1397 
1398            This even means when autolocking, we cache, just in case the
1399            update doesn't work, and we have to cache the autolock flag */
1400 
1401         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1402             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1403                 uint16 badcount = pdb_get_bad_password_count(sampass);
1404                 time_t badtime = pdb_get_bad_password_time(sampass);
1405                 uint32 pol;
1406                 pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1407 
1408                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1409                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1410 
1411                 if ((badcount >= pol) || (badcount == 0)) {
1412                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1413                                 (unsigned int)badcount, (unsigned int)badtime));
1414                         if (asprintf(&temp, "%li", (long)badcount) < 0) {
1415                                 return false;
1416                         }
1417                         smbldap_make_mod(
1418                                 ldap_state->smbldap_state->ldap_struct,
1419                                 existing, mods,
1420                                 get_userattr_key2string(
1421                                         ldap_state->schema_ver,
1422                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1423                                 temp);
1424                         SAFE_FREE(temp);
1425 
1426                         if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1427                                 return false;
1428                         }
1429                         smbldap_make_mod(
1430                                 ldap_state->smbldap_state->ldap_struct,
1431                                 existing, mods,
1432                                 get_userattr_key2string(
1433                                         ldap_state->schema_ver,
1434                                         LDAP_ATTR_BAD_PASSWORD_TIME),
1435                                 temp);
1436                         SAFE_FREE(temp);
1437                 }
1438                 if (badcount == 0) {
1439                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1440                         login_cache_delentry(sampass);
1441                 } else {
1442                         LOGIN_CACHE cache_entry;
1443 
1444                         cache_entry.entry_timestamp = time(NULL);
1445                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1446                         cache_entry.bad_password_count = badcount;
1447                         cache_entry.bad_password_time = badtime;
1448 
1449                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1450                         login_cache_write(sampass, cache_entry);
1451                 }
1452         }
1453 
1454         return True;
1455 }
1456 
1457 /**********************************************************************
1458  End enumeration of the LDAP password list.
1459 *********************************************************************/
1460 
1461 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
     /* [<][>][^][v][top][bottom][index][help] */
1462 {
1463         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1464         if (ldap_state->result) {
1465                 ldap_msgfree(ldap_state->result);
1466                 ldap_state->result = NULL;
1467         }
1468 }
1469 
1470 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
     /* [<][>][^][v][top][bottom][index][help] */
1471                         const char *new_attr)
1472 {
1473         int i;
1474 
1475         if (new_attr == NULL) {
1476                 return;
1477         }
1478 
1479         for (i=0; (*attr_list)[i] != NULL; i++) {
1480                 ;
1481         }
1482 
1483         (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1484                                             const char *,  i+2);
1485         SMB_ASSERT((*attr_list) != NULL);
1486         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1487         (*attr_list)[i+1] = NULL;
1488 }
1489 
1490 /**********************************************************************
1491 Get struct samu entry from LDAP by username.
1492 *********************************************************************/
1493 
1494 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
     /* [<][>][^][v][top][bottom][index][help] */
1495 {
1496         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1497         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1498         LDAPMessage *result = NULL;
1499         LDAPMessage *entry = NULL;
1500         int count;
1501         const char ** attr_list;
1502         int rc;
1503         
1504         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1505         append_attr(user, &attr_list,
1506                     get_userattr_key2string(ldap_state->schema_ver,
1507                                             LDAP_ATTR_MOD_TIMESTAMP));
1508         append_attr(user, &attr_list, "uidNumber");
1509         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1510                                            attr_list);
1511         TALLOC_FREE( attr_list );
1512 
1513         if ( rc != LDAP_SUCCESS ) 
1514                 return NT_STATUS_NO_SUCH_USER;
1515         
1516         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1517         
1518         if (count < 1) {
1519                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1520                 ldap_msgfree(result);
1521                 return NT_STATUS_NO_SUCH_USER;
1522         } else if (count > 1) {
1523                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1524                 ldap_msgfree(result);
1525                 return NT_STATUS_NO_SUCH_USER;
1526         }
1527 
1528         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1529         if (entry) {
1530                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1531                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1532                         ldap_msgfree(result);
1533                         return NT_STATUS_NO_SUCH_USER;
1534                 }
1535                 pdb_set_backend_private_data(user, result, NULL,
1536                                              my_methods, PDB_CHANGED);
1537                 talloc_autofree_ldapmsg(user, result);
1538                 ret = NT_STATUS_OK;
1539         } else {
1540                 ldap_msgfree(result);
1541         }
1542         return ret;
1543 }
1544 
1545 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
     /* [<][>][^][v][top][bottom][index][help] */
1546                                    const DOM_SID *sid, LDAPMessage **result) 
1547 {
1548         int rc = -1;
1549         const char ** attr_list;
1550         uint32 rid;
1551 
1552         switch ( ldap_state->schema_ver ) {
1553                 case SCHEMAVER_SAMBASAMACCOUNT: {
1554                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1555                         if (tmp_ctx == NULL) {
1556                                 return LDAP_NO_MEMORY;
1557                         }
1558 
1559                         attr_list = get_userattr_list(tmp_ctx,
1560                                                       ldap_state->schema_ver);
1561                         append_attr(tmp_ctx, &attr_list,
1562                                     get_userattr_key2string(
1563                                             ldap_state->schema_ver,
1564                                             LDAP_ATTR_MOD_TIMESTAMP));
1565                         append_attr(tmp_ctx, &attr_list, "uidNumber");
1566                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1567                                                           result, attr_list);
1568                         TALLOC_FREE(tmp_ctx);
1569 
1570                         if ( rc != LDAP_SUCCESS ) 
1571                                 return rc;
1572                         break;
1573                 }
1574                         
1575                 case SCHEMAVER_SAMBAACCOUNT:
1576                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1577                                 return rc;
1578                         }
1579                 
1580                         attr_list = get_userattr_list(NULL,
1581                                                       ldap_state->schema_ver);
1582                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1583                         TALLOC_FREE( attr_list );
1584 
1585                         if ( rc != LDAP_SUCCESS ) 
1586                                 return rc;
1587                         break;
1588         }
1589         return rc;
1590 }
1591 
1592 /**********************************************************************
1593  Get struct samu entry from LDAP by SID.
1594 *********************************************************************/
1595 
1596 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
     /* [<][>][^][v][top][bottom][index][help] */
1597 {
1598         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1599         LDAPMessage *result = NULL;
1600         LDAPMessage *entry = NULL;
1601         int count;
1602         int rc;
1603 
1604         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1605                                           sid, &result); 
1606         if (rc != LDAP_SUCCESS)
1607                 return NT_STATUS_NO_SUCH_USER;
1608 
1609         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1610         
1611         if (count < 1) {
1612                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1613                           "count=%d\n", sid_string_dbg(sid), count));
1614                 ldap_msgfree(result);
1615                 return NT_STATUS_NO_SUCH_USER;
1616         }  else if (count > 1) {
1617                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1618                           "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1619                           count));
1620                 ldap_msgfree(result);
1621                 return NT_STATUS_NO_SUCH_USER;
1622         }
1623 
1624         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1625         if (!entry) {
1626                 ldap_msgfree(result);
1627                 return NT_STATUS_NO_SUCH_USER;
1628         }
1629 
1630         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1631                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1632                 ldap_msgfree(result);
1633                 return NT_STATUS_NO_SUCH_USER;
1634         }
1635 
1636         pdb_set_backend_private_data(user, result, NULL,
1637                                      my_methods, PDB_CHANGED);
1638         talloc_autofree_ldapmsg(user, result);
1639         return NT_STATUS_OK;
1640 }       
1641 
1642 /********************************************************************
1643  Do the actual modification - also change a plaintext passord if 
1644  it it set.
1645 **********************************************************************/
1646 
1647 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
     /* [<][>][^][v][top][bottom][index][help] */
1648                                      struct samu *newpwd, char *dn,
1649                                      LDAPMod **mods, int ldap_op, 
1650                                      bool (*need_update)(const struct samu *, enum pdb_elements))
1651 {
1652         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1653         int rc;
1654         
1655         if (!newpwd || !dn) {
1656                 return NT_STATUS_INVALID_PARAMETER;
1657         }
1658         
1659         if (!mods) {
1660                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1661                 /* may be password change below however */
1662         } else {
1663                 switch(ldap_op) {
1664                         case LDAP_MOD_ADD:
1665                                 if (ldap_state->is_nds_ldap) {
1666                                         smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1667                                                         "objectclass", 
1668                                                         "inetOrgPerson");
1669                                 } else {
1670                                         smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1671                                                         "objectclass", 
1672                                                         LDAP_OBJ_ACCOUNT);
1673                                 }
1674                                 rc = smbldap_add(ldap_state->smbldap_state, 
1675                                                  dn, mods);
1676                                 break;
1677                         case LDAP_MOD_REPLACE: 
1678                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1679                                                     dn ,mods);
1680                                 break;
1681                         default:        
1682                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1683                                          ldap_op));
1684                                 return NT_STATUS_INVALID_PARAMETER;
1685                 }
1686                 
1687                 if (rc!=LDAP_SUCCESS) {
1688                         return NT_STATUS_UNSUCCESSFUL;
1689                 }  
1690         }
1691         
1692         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1693                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1694                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1695                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1696                 BerElement *ber;
1697                 struct berval *bv;
1698                 char *retoid = NULL;
1699                 struct berval *retdata = NULL;
1700                 char *utf8_password;
1701                 char *utf8_dn;
1702                 size_t converted_size;
1703                 int ret;
1704 
1705                 if (!ldap_state->is_nds_ldap) {
1706 
1707                         if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
1708                                                    LDAP_EXOP_MODIFY_PASSWD)) {
1709                                 DEBUG(2, ("ldap password change requested, but LDAP "
1710                                           "server does not support it -- ignoring\n"));
1711                                 return NT_STATUS_OK;
1712                         }
1713                 }
1714 
1715                 if (!push_utf8_allocate(&utf8_password,
1716                                         pdb_get_plaintext_passwd(newpwd),
1717                                         &converted_size))
1718                 {
1719                         return NT_STATUS_NO_MEMORY;
1720                 }
1721 
1722                 if (!push_utf8_allocate(&utf8_dn, dn, &converted_size)) {
1723                         SAFE_FREE(utf8_password);
1724                         return NT_STATUS_NO_MEMORY;
1725                 }
1726 
1727                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1728                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1729                         SAFE_FREE(utf8_password);
1730                         SAFE_FREE(utf8_dn);
1731                         return NT_STATUS_UNSUCCESSFUL;
1732                 }
1733 
1734                 if ((ber_printf (ber, "{") < 0) ||
1735                     (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1736                                  utf8_dn) < 0)) {
1737                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1738                                  "value <0\n"));
1739                         ber_free(ber,1);
1740                         SAFE_FREE(utf8_dn);
1741                         SAFE_FREE(utf8_password);
1742                         return NT_STATUS_UNSUCCESSFUL;
1743                 }
1744 
1745                 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1746                         ret = ber_printf(ber, "ts}",
1747                                          LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1748                                          utf8_password);
1749                 } else {
1750                         ret = ber_printf(ber, "}");
1751                 }
1752 
1753                 if (ret < 0) {
1754                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1755                                  "value <0\n"));
1756                         ber_free(ber,1);
1757                         SAFE_FREE(utf8_dn);
1758                         SAFE_FREE(utf8_password);
1759                         return NT_STATUS_UNSUCCESSFUL;
1760                 }
1761 
1762                 if ((rc = ber_flatten (ber, &bv))<0) {
1763                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1764                         ber_free(ber,1);
1765                         SAFE_FREE(utf8_dn);
1766                         SAFE_FREE(utf8_password);
1767                         return NT_STATUS_UNSUCCESSFUL;
1768                 }
1769                 
1770                 SAFE_FREE(utf8_dn);
1771                 SAFE_FREE(utf8_password);
1772                 ber_free(ber, 1);
1773 
1774                 if (!ldap_state->is_nds_ldap) {
1775                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1776                                                         LDAP_EXOP_MODIFY_PASSWD,
1777                                                         bv, NULL, NULL, &retoid, 
1778                                                         &retdata);
1779                 } else {
1780                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1781                                                         pdb_get_plaintext_passwd(newpwd));
1782                 }
1783                 if (rc != LDAP_SUCCESS) {
1784                         char *ld_error = NULL;
1785 
1786                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1787                                 DEBUG(3, ("Could not set userPassword "
1788                                           "attribute due to an objectClass "
1789                                           "violation -- ignoring\n"));
1790                                 ber_bvfree(bv);
1791                                 return NT_STATUS_OK;
1792                         }
1793 
1794                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1795                                         &ld_error);
1796                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1797                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1798                         SAFE_FREE(ld_error);
1799                         ber_bvfree(bv);
1800 #if defined(LDAP_CONSTRAINT_VIOLATION)
1801                         if (rc == LDAP_CONSTRAINT_VIOLATION)
1802                                 return NT_STATUS_PASSWORD_RESTRICTION;
1803 #endif
1804                         return NT_STATUS_UNSUCCESSFUL;
1805                 } else {
1806                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1807 #ifdef DEBUG_PASSWORD
1808                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1809 #endif    
1810                         if (retdata)
1811                                 ber_bvfree(retdata);
1812                         if (retoid)
1813                                 ldap_memfree(retoid);
1814                 }
1815                 ber_bvfree(bv);
1816         }
1817         return NT_STATUS_OK;
1818 }
1819 
1820 /**********************************************************************
1821  Delete entry from LDAP for username.
1822 *********************************************************************/
1823 
1824 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
1825                                            struct samu * sam_acct)
1826 {
1827         struct ldapsam_privates *priv =
1828                 (struct ldapsam_privates *)my_methods->private_data;
1829         const char *sname;
1830         int rc;
1831         LDAPMessage *msg, *entry;
1832         NTSTATUS result = NT_STATUS_NO_MEMORY;
1833         const char **attr_list;
1834         TALLOC_CTX *mem_ctx;
1835 
1836         if (!sam_acct) {
1837                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1838                 return NT_STATUS_INVALID_PARAMETER;
1839         }
1840 
1841         sname = pdb_get_username(sam_acct);
1842 
1843         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1844                   "LDAP.\n", sname));
1845 
1846         mem_ctx = talloc_new(NULL);
1847         if (mem_ctx == NULL) {
1848                 DEBUG(0, ("talloc_new failed\n"));
1849                 goto done;
1850         }
1851 
1852         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1853         if (attr_list == NULL) {
1854                 goto done;
1855         }
1856 
1857         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1858 
1859         if ((rc != LDAP_SUCCESS) ||
1860             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1861             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1862                 DEBUG(5, ("Could not find user %s\n", sname));
1863                 result = NT_STATUS_NO_SUCH_USER;
1864                 goto done;
1865         }
1866         
1867         rc = ldapsam_delete_entry(
1868                 priv, mem_ctx, entry,
1869                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1870                 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1871                 attr_list);
1872 
1873         result = (rc == LDAP_SUCCESS) ?
1874                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1875 
1876  done:
1877         TALLOC_FREE(mem_ctx);
1878         return result;
1879 }
1880 
1881 /**********************************************************************
1882  Helper function to determine for update_sam_account whether
1883  we need LDAP modification.
1884 *********************************************************************/
1885 
1886 static bool element_is_changed(const struct samu *sampass,
     /* [<][>][^][v][top][bottom][index][help] */
1887                                enum pdb_elements element)
1888 {
1889         return IS_SAM_CHANGED(sampass, element);
1890 }
1891 
1892 /**********************************************************************
1893  Update struct samu.
1894 *********************************************************************/
1895 
1896 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
     /* [<][>][^][v][top][bottom][index][help] */
1897 {
1898         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1899         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1900         int rc = 0;
1901         char *dn;
1902         LDAPMessage *result = NULL;
1903         LDAPMessage *entry = NULL;
1904         LDAPMod **mods = NULL;
1905         const char **attr_list;
1906 
1907         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1908         if (!result) {
1909                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1910                 if (pdb_get_username(newpwd) == NULL) {
1911                         return NT_STATUS_INVALID_PARAMETER;
1912                 }
1913                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1914                 TALLOC_FREE( attr_list );
1915                 if (rc != LDAP_SUCCESS) {
1916                         return NT_STATUS_UNSUCCESSFUL;
1917                 }
1918                 pdb_set_backend_private_data(newpwd, result, NULL,
1919                                              my_methods, PDB_CHANGED);
1920                 talloc_autofree_ldapmsg(newpwd, result);
1921         }
1922 
1923         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1924                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1925                 return NT_STATUS_UNSUCCESSFUL;
1926         }
1927 
1928         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1929         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1930         if (!dn) {
1931                 return NT_STATUS_UNSUCCESSFUL;
1932         }
1933 
1934         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1935 
1936         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1937                                 element_is_changed)) {
1938                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1939                 TALLOC_FREE(dn);
1940                 if (mods != NULL)
1941                         ldap_mods_free(mods,True);
1942                 return NT_STATUS_UNSUCCESSFUL;
1943         }
1944 
1945         if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1946             && (mods == NULL)) {
1947                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1948                          pdb_get_username(newpwd)));
1949                 TALLOC_FREE(dn);
1950                 return NT_STATUS_OK;
1951         }
1952         
1953         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1954 
1955         if (mods != NULL) {
1956                 ldap_mods_free(mods,True);
1957         }
1958 
1959         TALLOC_FREE(dn);
1960 
1961         /*
1962          * We need to set the backend private data to NULL here. For example
1963          * setuserinfo level 25 does a pdb_update_sam_account twice on the
1964          * same one, and with the explicit delete / add logic for attribute
1965          * values the second time we would use the wrong "old" value which
1966          * does not exist in LDAP anymore. Thus the LDAP server would refuse
1967          * the update.
1968          * The existing LDAPMessage is still being auto-freed by the
1969          * destructor.
1970          */
1971         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1972                                      PDB_CHANGED);
1973 
1974         if (!NT_STATUS_IS_OK(ret)) {
1975                 return ret;
1976         }
1977 
1978         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1979                   pdb_get_username(newpwd)));
1980         return NT_STATUS_OK;
1981 }
1982 
1983 /***************************************************************************
1984  Renames a struct samu
1985  - The "rename user script" has full responsibility for changing everything
1986 ***************************************************************************/
1987 
1988 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
1989                                            struct samu *old_acct,
1990                                            const char *newname)
1991 {
1992         const char *oldname;
1993         int rc;
1994         char *rename_script = NULL;
1995         fstring oldname_lower, newname_lower;
1996 
1997         if (!old_acct) {
1998                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1999                 return NT_STATUS_INVALID_PARAMETER;
2000         }
2001         if (!newname) {
2002                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
2003                 return NT_STATUS_INVALID_PARAMETER;
2004         }
2005 
2006         oldname = pdb_get_username(old_acct);
2007 
2008         /* rename the posix user */
2009         rename_script = SMB_STRDUP(lp_renameuser_script());
2010         if (rename_script == NULL) {
2011                 return NT_STATUS_NO_MEMORY;
2012         }
2013 
2014         if (!(*rename_script)) {
2015                 SAFE_FREE(rename_script);
2016                 return NT_STATUS_ACCESS_DENIED;
2017         }
2018 
2019         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2020                    oldname, newname));
2021 
2022         /* We have to allow the account name to end with a '$'.
2023            Also, follow the semantics in _samr_create_user() and lower case the
2024            posix name but preserve the case in passdb */
2025 
2026         fstrcpy( oldname_lower, oldname );
2027         strlower_m( oldname_lower );
2028         fstrcpy( newname_lower, newname );
2029         strlower_m( newname_lower );
2030         rename_script = realloc_string_sub2(rename_script,
2031                                         "%unew",
2032                                         newname_lower,
2033                                         true,
2034                                         true);
2035         if (!rename_script) {
2036                 return NT_STATUS_NO_MEMORY;
2037         }
2038         rename_script = realloc_string_sub2(rename_script,
2039                                         "%uold",
2040                                         oldname_lower,
2041                                         true,
2042                                         true);
2043         rc = smbrun(rename_script, NULL);
2044 
2045         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2046                           rename_script, rc));
2047 
2048         SAFE_FREE(rename_script);
2049 
2050         if (rc == 0) {
2051                 smb_nscd_flush_user_cache();
2052         }
2053 
2054         if (rc)
2055                 return NT_STATUS_UNSUCCESSFUL;
2056 
2057         return NT_STATUS_OK;
2058 }
2059 
2060 /**********************************************************************
2061  Helper function to determine for update_sam_account whether
2062  we need LDAP modification.
2063  *********************************************************************/
2064 
2065 static bool element_is_set_or_changed(const struct samu *sampass,
     /* [<][>][^][v][top][bottom][index][help] */
2066                                       enum pdb_elements element)
2067 {
2068         return (IS_SAM_SET(sampass, element) ||
2069                 IS_SAM_CHANGED(sampass, element));
2070 }
2071 
2072 /**********************************************************************
2073  Add struct samu to LDAP.
2074 *********************************************************************/
2075 
2076 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
     /* [<][>][^][v][top][bottom][index][help] */
2077 {
2078         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2079         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2080         int rc;
2081         LDAPMessage     *result = NULL;
2082         LDAPMessage     *entry  = NULL;
2083         LDAPMod         **mods = NULL;
2084         int             ldap_op = LDAP_MOD_REPLACE;
2085         uint32          num_result;
2086         const char      **attr_list;
2087         char *escape_user = NULL;
2088         const char      *username = pdb_get_username(newpwd);
2089         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
2090         char *filter = NULL;
2091         char *dn = NULL;
2092         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2093         TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2094 
2095         if (!ctx) {
2096                 return NT_STATUS_NO_MEMORY;
2097         }
2098 
2099         if (!username || !*username) {
2100                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2101                 status = NT_STATUS_INVALID_PARAMETER;
2102                 goto fn_exit;
2103         }
2104 
2105         /* free this list after the second search or in case we exit on failure */
2106         attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2107 
2108         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2109 
2110         if (rc != LDAP_SUCCESS) {
2111                 goto fn_exit;
2112         }
2113 
2114         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2115                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
2116                          username));
2117                 goto fn_exit;
2118         }
2119         ldap_msgfree(result);
2120         result = NULL;
2121 
2122         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
2123                 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2124                                                   sid, &result);
2125                 if (rc == LDAP_SUCCESS) {
2126                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2127                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2128                                          "already in the base, with samba "
2129                                          "attributes\n", sid_string_dbg(sid)));
2130                                 goto fn_exit;
2131                         }
2132                         ldap_msgfree(result);
2133                         result = NULL;
2134                 }
2135         }
2136 
2137         /* does the entry already exist but without a samba attributes?
2138            we need to return the samba attributes here */
2139 
2140         escape_user = escape_ldap_string_alloc( username );
2141         filter = talloc_strdup(attr_list, "(uid=%u)");
2142         if (!filter) {
2143                 status = NT_STATUS_NO_MEMORY;
2144                 goto fn_exit;
2145         }
2146         filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2147         if (!filter) {
2148                 status = NT_STATUS_NO_MEMORY;
2149                 goto fn_exit;
2150         }
2151         SAFE_FREE(escape_user);
2152 
2153         rc = smbldap_search_suffix(ldap_state->smbldap_state,
2154                                    filter, attr_list, &result);
2155         if ( rc != LDAP_SUCCESS ) {
2156                 goto fn_exit;
2157         }
2158 
2159         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2160 
2161         if (num_result > 1) {
2162                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2163                 goto fn_exit;
2164         }
2165 
2166         /* Check if we need to update an existing entry */
2167         if (num_result == 1) {
2168                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2169                 ldap_op = LDAP_MOD_REPLACE;
2170                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2171                 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2172                 if (!dn) {
2173                         status = NT_STATUS_NO_MEMORY;
2174                         goto fn_exit;
2175                 }
2176 
2177         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2178 
2179                 /* There might be a SID for this account already - say an idmap entry */
2180 
2181                 filter = talloc_asprintf(ctx,
2182                                 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2183                                  get_userattr_key2string(ldap_state->schema_ver,
2184                                          LDAP_ATTR_USER_SID),
2185                                  sid_string_talloc(ctx, sid),
2186                                  LDAP_OBJ_IDMAP_ENTRY,
2187                                  LDAP_OBJ_SID_ENTRY);
2188                 if (!filter) {
2189                         status = NT_STATUS_NO_MEMORY;
2190                         goto fn_exit;
2191                 }
2192 
2193                 /* free old result before doing a new search */
2194                 if (result != NULL) {
2195                         ldap_msgfree(result);
2196                         result = NULL;
2197                 }
2198                 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2199                                            filter, attr_list, &result);
2200 
2201                 if ( rc != LDAP_SUCCESS ) {
2202                         goto fn_exit;
2203                 }
2204 
2205                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2206 
2207                 if (num_result > 1) {
2208                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2209                         goto fn_exit;
2210                 }
2211 
2212                 /* Check if we need to update an existing entry */
2213                 if (num_result == 1) {
2214 
2215                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2216                         ldap_op = LDAP_MOD_REPLACE;
2217                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2218                         dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2219                         if (!dn) {
2220                                 status = NT_STATUS_NO_MEMORY;
2221                                 goto fn_exit;
2222                         }
2223                 }
2224         }
2225 
2226         if (num_result == 0) {
2227                 char *escape_username;
2228                 /* Check if we need to add an entry */
2229                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2230                 ldap_op = LDAP_MOD_ADD;
2231 
2232                 escape_username = escape_rdn_val_string_alloc(username);
2233                 if (!escape_username) {
2234                         status = NT_STATUS_NO_MEMORY;
2235                         goto fn_exit;
2236                 }
2237 
2238                 if (username[strlen(username)-1] == '$') {
2239                         dn = talloc_asprintf(ctx,
2240                                         "uid=%s,%s",
2241                                         escape_username,
2242                                         lp_ldap_machine_suffix());
2243                 } else {
2244                         dn = talloc_asprintf(ctx,
2245                                         "uid=%s,%s",
2246                                         escape_username,
2247                                         lp_ldap_user_suffix());
2248                 }
2249 
2250                 SAFE_FREE(escape_username);
2251                 if (!dn) {
2252                         status = NT_STATUS_NO_MEMORY;
2253                         goto fn_exit;
2254                 }
2255         }
2256 
2257         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2258                                 element_is_set_or_changed)) {
2259                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2260                 if (mods != NULL) {
2261                         ldap_mods_free(mods, true);
2262                 }
2263                 goto fn_exit;
2264         }
2265 
2266         if (mods == NULL) {
2267                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2268                 goto fn_exit;
2269         }
2270         switch ( ldap_state->schema_ver ) {
2271                 case SCHEMAVER_SAMBAACCOUNT:
2272                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2273                         break;
2274                 case SCHEMAVER_SAMBASAMACCOUNT:
2275                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2276                         break;
2277                 default:
2278                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2279                         break;
2280         }
2281 
2282         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2283         if (!NT_STATUS_IS_OK(ret)) {
2284                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2285                          pdb_get_username(newpwd),dn));
2286                 ldap_mods_free(mods, true);
2287                 goto fn_exit;
2288         }
2289 
2290         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2291         ldap_mods_free(mods, true);
2292 
2293         status = NT_STATUS_OK;
2294 
2295   fn_exit:
2296 
2297         TALLOC_FREE(ctx);
2298         SAFE_FREE(escape_user);
2299         if (result) {
2300                 ldap_msgfree(result);
2301         }
2302         return status;
2303 }
2304 
2305 /**********************************************************************
2306  *********************************************************************/
2307 
2308 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
2309                                      const char *filter,
2310                                      LDAPMessage ** result)
2311 {
2312         int scope = LDAP_SCOPE_SUBTREE;
2313         int rc;
2314         const char **attr_list;
2315 
2316         attr_list = get_attr_list(NULL, groupmap_attr_list);
2317         rc = smbldap_search(ldap_state->smbldap_state,
2318                             lp_ldap_suffix (), scope,
2319                             filter, attr_list, 0, result);
2320         TALLOC_FREE(attr_list);
2321 
2322         return rc;
2323 }
2324 
2325 /**********************************************************************
2326  *********************************************************************/
2327 
2328 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
2329                                  GROUP_MAP *map, LDAPMessage *entry)
2330 {
2331         char *temp = NULL;
2332         TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2333 
2334         if (ldap_state == NULL || map == NULL || entry == NULL ||
2335                         ldap_state->smbldap_state->ldap_struct == NULL) {
2336                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2337                 TALLOC_FREE(ctx);
2338                 return false;
2339         }
2340 
2341         temp = smbldap_talloc_single_attribute(
2342                         ldap_state->smbldap_state->ldap_struct,
2343                         entry,
2344                         get_attr_key2string(groupmap_attr_list,
2345                                 LDAP_ATTR_GIDNUMBER),
2346                         ctx);
2347         if (!temp) {
2348                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2349                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2350                 TALLOC_FREE(ctx);
2351                 return false;
2352         }
2353         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2354 
2355         map->gid = (gid_t)atol(temp);
2356 
2357         TALLOC_FREE(temp);
2358         temp = smbldap_talloc_single_attribute(
2359                         ldap_state->smbldap_state->ldap_struct,
2360                         entry,
2361                         get_attr_key2string(groupmap_attr_list,
2362                                 LDAP_ATTR_GROUP_SID),
2363                         ctx);
2364         if (!temp) {
2365                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2366                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2367                 TALLOC_FREE(ctx);
2368                 return false;
2369         }
2370 
2371         if (!string_to_sid(&map->sid, temp)) {
2372                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2373                 TALLOC_FREE(ctx);
2374                 return false;
2375         }
2376 
2377         TALLOC_FREE(temp);
2378         temp = smbldap_talloc_single_attribute(
2379                         ldap_state->smbldap_state->ldap_struct,
2380                         entry,
2381                         get_attr_key2string(groupmap_attr_list,
2382                                 LDAP_ATTR_GROUP_TYPE),
2383                         ctx);
2384         if (!temp) {
2385                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2386                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2387                 TALLOC_FREE(ctx);
2388                 return false;
2389         }
2390         map->sid_name_use = (enum lsa_SidType)atol(temp);
2391 
2392         if ((map->sid_name_use < SID_NAME_USER) ||
2393                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2394                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2395                 TALLOC_FREE(ctx);
2396                 return false;
2397         }
2398 
2399         TALLOC_FREE(temp);
2400         temp = smbldap_talloc_single_attribute(
2401                         ldap_state->smbldap_state->ldap_struct,
2402                         entry,
2403                         get_attr_key2string(groupmap_attr_list,
2404                                 LDAP_ATTR_DISPLAY_NAME),
2405                         ctx);
2406         if (!temp) {
2407                 temp = smbldap_talloc_single_attribute(
2408                                 ldap_state->smbldap_state->ldap_struct,
2409                                 entry,
2410                                 get_attr_key2string(groupmap_attr_list,
2411                                         LDAP_ATTR_CN),
2412                                 ctx);
2413                 if (!temp) {
2414                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2415 for gidNumber(%lu)\n",(unsigned long)map->gid));
2416                         TALLOC_FREE(ctx);
2417                         return false;
2418                 }
2419         }
2420         fstrcpy(map->nt_name, temp);
2421 
2422         TALLOC_FREE(temp);
2423         temp = smbldap_talloc_single_attribute(
2424                         ldap_state->smbldap_state->ldap_struct,
2425                         entry,
2426                         get_attr_key2string(groupmap_attr_list,
2427                                 LDAP_ATTR_DESC),
2428                         ctx);
2429         if (!temp) {
2430                 temp = talloc_strdup(ctx, "");
2431                 if (!temp) {
2432                         TALLOC_FREE(ctx);
2433                         return false;
2434                 }
2435         }
2436         fstrcpy(map->comment, temp);
2437 
2438         if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2439                 store_gid_sid_cache(&map->sid, map->gid);
2440         }
2441 
2442         TALLOC_FREE(ctx);
2443         return true;
2444 }
2445 
2446 /**********************************************************************
2447  *********************************************************************/
2448 
2449 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
2450                                  const char *filter,
2451                                  GROUP_MAP *map)
2452 {
2453         struct ldapsam_privates *ldap_state =
2454                 (struct ldapsam_privates *)methods->private_data;
2455         LDAPMessage *result = NULL;
2456         LDAPMessage *entry = NULL;
2457         int count;
2458 
2459         if (ldapsam_search_one_group(ldap_state, filter, &result)
2460             != LDAP_SUCCESS) {
2461                 return NT_STATUS_NO_SUCH_GROUP;
2462         }
2463 
2464         count = ldap_count_entries(priv2ld(ldap_state), result);
2465 
2466         if (count < 1) {
2467                 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2468                           "%s\n", filter));
2469                 ldap_msgfree(result);
2470                 return NT_STATUS_NO_SUCH_GROUP;
2471         }
2472 
2473         if (count > 1) {
2474                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2475                           "count=%d\n", filter, count));
2476                 ldap_msgfree(result);
2477                 return NT_STATUS_NO_SUCH_GROUP;
2478         }
2479 
2480         entry = ldap_first_entry(priv2ld(ldap_state), result);
2481 
2482         if (!entry) {
2483                 ldap_msgfree(result);
2484                 return NT_STATUS_UNSUCCESSFUL;
2485         }
2486 
2487         if (!init_group_from_ldap(ldap_state, map, entry)) {
2488                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2489                           "group filter %s\n", filter));
2490                 ldap_msgfree(result);
2491                 return NT_STATUS_NO_SUCH_GROUP;
2492         }
2493 
2494         ldap_msgfree(result);
2495         return NT_STATUS_OK;
2496 }
2497 
2498 /**********************************************************************
2499  *********************************************************************/
2500 
2501 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
     /* [<][>][^][v][top][bottom][index][help] */
2502                                  DOM_SID sid)
2503 {
2504         char *filter = NULL;
2505         NTSTATUS status;
2506         fstring tmp;
2507 
2508         if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2509                 LDAP_OBJ_GROUPMAP,
2510                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2511                 sid_to_fstring(tmp, &sid)) < 0) {
2512                 return NT_STATUS_NO_MEMORY;
2513         }
2514 
2515         status = ldapsam_getgroup(methods, filter, map);
2516         SAFE_FREE(filter);
2517         return status;
2518 }
2519 
2520 /**********************************************************************
2521  *********************************************************************/
2522 
2523 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
     /* [<][>][^][v][top][bottom][index][help] */
2524                                  gid_t gid)
2525 {
2526         char *filter = NULL;
2527         NTSTATUS status;
2528 
2529         if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2530                 LDAP_OBJ_GROUPMAP,
2531                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2532                 (unsigned long)gid) < 0) {
2533                 return NT_STATUS_NO_MEMORY;
2534         }
2535 
2536         status = ldapsam_getgroup(methods, filter, map);
2537         SAFE_FREE(filter);
2538         return status;
2539 }
2540 
2541 /**********************************************************************
2542  *********************************************************************/
2543 
2544 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
     /* [<][>][^][v][top][bottom][index][help] */
2545                                  const char *name)
2546 {
2547         char *filter = NULL;
2548         char *escape_name = escape_ldap_string_alloc(name);
2549         NTSTATUS status;
2550 
2551         if (!escape_name) {
2552                 return NT_STATUS_NO_MEMORY;
2553         }
2554 
2555         if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2556                 LDAP_OBJ_GROUPMAP,
2557                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2558                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2559                 escape_name) < 0) {
2560                 SAFE_FREE(escape_name);
2561                 return NT_STATUS_NO_MEMORY;
2562         }
2563 
2564         SAFE_FREE(escape_name);
2565         status = ldapsam_getgroup(methods, filter, map);
2566         SAFE_FREE(filter);
2567         return status;
2568 }
2569 
2570 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
     /* [<][>][^][v][top][bottom][index][help] */
2571                                            LDAPMessage *entry,
2572                                            const DOM_SID *domain_sid,
2573                                            uint32 *rid)
2574 {
2575         fstring str;
2576         DOM_SID sid;
2577 
2578         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2579                                           str, sizeof(str)-1)) {
2580                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2581                 return False;
2582         }
2583 
2584         if (!string_to_sid(&sid, str)) {
2585                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2586                 return False;
2587         }
2588 
2589         if (sid_compare_domain(&sid, domain_sid) != 0) {
2590                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2591                            str, sid_string_dbg(domain_sid)));
2592                 return False;
2593         }
2594 
2595         if (!sid_peek_rid(&sid, rid)) {
2596                 DEBUG(10, ("Could not peek into RID\n"));
2597                 return False;
2598         }
2599 
2600         return True;
2601 }
2602 
2603 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
2604                                            TALLOC_CTX *mem_ctx,
2605                                            const DOM_SID *group,
2606                                            uint32 **pp_member_rids,
2607                                            size_t *p_num_members)
2608 {
2609         struct ldapsam_privates *ldap_state =
2610                 (struct ldapsam_privates *)methods->private_data;
2611         struct smbldap_state *conn = ldap_state->smbldap_state;
2612         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2613         const char *sid_attrs[] = { "sambaSID", NULL };
2614         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2615         LDAPMessage *result = NULL;
2616         LDAPMessage *entry;
2617         char *filter;
2618         char **values = NULL;
2619         char **memberuid;
2620         char *gidstr;
2621         int rc, count;
2622 
2623         *pp_member_rids = NULL;
2624         *p_num_members = 0;
2625 
2626         filter = talloc_asprintf(mem_ctx,
2627                                  "(&(objectClass=%s)"
2628                                  "(objectClass=%s)"
2629                                  "(sambaSID=%s))",
2630                                  LDAP_OBJ_POSIXGROUP,
2631                                  LDAP_OBJ_GROUPMAP,
2632                                  sid_string_talloc(mem_ctx, group));
2633         if (filter == NULL) {
2634                 ret = NT_STATUS_NO_MEMORY;
2635                 goto done;
2636         }
2637 
2638         rc = smbldap_search(conn, lp_ldap_suffix(),
2639                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2640                             &result);
2641 
2642         if (rc != LDAP_SUCCESS)
2643                 goto done;
2644 
2645         talloc_autofree_ldapmsg(mem_ctx, result);
2646 
2647         count = ldap_count_entries(conn->ldap_struct, result);
2648 
2649         if (count > 1) {
2650                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2651                           sid_string_dbg(group)));
2652                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2653                 goto done;
2654         }
2655 
2656         if (count == 0) {
2657                 ret = NT_STATUS_NO_SUCH_GROUP;
2658                 goto done;
2659         }
2660 
2661         entry = ldap_first_entry(conn->ldap_struct, result);
2662         if (entry == NULL)
2663                 goto done;
2664 
2665         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2666         if (!gidstr) {
2667                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2668                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2669                 goto done;
2670         }
2671 
2672         values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2673 
2674         if (values) {
2675 
2676                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2677                 if (filter == NULL) {
2678                         ret = NT_STATUS_NO_MEMORY;
2679                         goto done;
2680                 }
2681 
2682                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2683                         char *escape_memberuid;
2684 
2685                         escape_memberuid = escape_ldap_string_alloc(*memberuid);
2686                         if (escape_memberuid == NULL) {
2687                                 ret = NT_STATUS_NO_MEMORY;
2688                                 goto done;
2689                         }
2690                         
2691                         filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2692                         if (filter == NULL) {
2693                                 SAFE_FREE(escape_memberuid);
2694                                 ret = NT_STATUS_NO_MEMORY;
2695                                 goto done;
2696                         }
2697 
2698                         SAFE_FREE(escape_memberuid);
2699                 }
2700 
2701                 filter = talloc_asprintf_append_buffer(filter, "))");
2702                 if (filter == NULL) {
2703                         ret = NT_STATUS_NO_MEMORY;
2704                         goto done;
2705                 }
2706 
2707                 rc = smbldap_search(conn, lp_ldap_suffix(),
2708                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2709                                     &result);
2710 
2711                 if (rc != LDAP_SUCCESS)
2712                         goto done;
2713 
2714                 count = ldap_count_entries(conn->ldap_struct, result);
2715                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2716 
2717                 talloc_autofree_ldapmsg(mem_ctx, result);
2718 
2719                 for (entry = ldap_first_entry(conn->ldap_struct, result);
2720                      entry != NULL;
2721                      entry = ldap_next_entry(conn->ldap_struct, entry))
2722                 {
2723                         char *sidstr;
2724                         DOM_SID sid;
2725                         uint32 rid;
2726 
2727                         sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2728                                                                  entry, "sambaSID",
2729                                                                  mem_ctx);
2730                         if (!sidstr) {
2731                                 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2732                                           "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2733                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2734                                 goto done;
2735                         }
2736 
2737                         if (!string_to_sid(&sid, sidstr))
2738                                 goto done;
2739 
2740                         if (!sid_check_is_in_our_domain(&sid)) {
2741                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2742                                           "in our domain\n"));
2743                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2744                                 goto done;
2745                         }
2746 
2747                         sid_peek_rid(&sid, &rid);
2748 
2749                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2750                                                 p_num_members)) {
2751                                 ret = NT_STATUS_NO_MEMORY;
2752                                 goto done;
2753                         }
2754                 }
2755         }
2756 
2757         filter = talloc_asprintf(mem_ctx,
2758                                  "(&(objectClass=%s)"
2759                                  "(gidNumber=%s))",
2760                                  LDAP_OBJ_SAMBASAMACCOUNT,
2761                                  gidstr);
2762 
2763         rc = smbldap_search(conn, lp_ldap_suffix(),
2764                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2765                             &result);
2766 
2767         if (rc != LDAP_SUCCESS)
2768                 goto done;
2769 
2770         talloc_autofree_ldapmsg(mem_ctx, result);
2771 
2772         for (entry = ldap_first_entry(conn->ldap_struct, result);
2773              entry != NULL;
2774              entry = ldap_next_entry(conn->ldap_struct, entry))
2775         {
2776                 uint32 rid;
2777 
2778                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2779                                                     entry,
2780                                                     get_global_sam_sid(),
2781                                                     &rid)) {
2782                         DEBUG(0, ("Severe DB error, %s can't miss the samba SID"                                                                "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2783                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2784                         goto done;
2785                 }
2786 
2787                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2788                                         p_num_members)) {
2789                         ret = NT_STATUS_NO_MEMORY;
2790                         goto done;
2791                 }
2792         }
2793 
2794         ret = NT_STATUS_OK;
2795         
2796  done:
2797 
2798         if (values)
2799                 ldap_value_free(values);
2800 
2801         return ret;
2802 }
2803 
2804 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
2805                                                TALLOC_CTX *mem_ctx,
2806                                                struct samu *user,
2807                                                DOM_SID **pp_sids,
2808                                                gid_t **pp_gids,
2809                                                size_t *p_num_groups)
2810 {
2811         struct ldapsam_privates *ldap_state =
2812                 (struct ldapsam_privates *)methods->private_data;
2813         struct smbldap_state *conn = ldap_state->smbldap_state;
2814         char *filter;
2815         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2816         char *escape_name;
2817         int rc, count;
2818         LDAPMessage *result = NULL;
2819         LDAPMessage *entry;
2820         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2821         size_t num_sids, num_gids;
2822         char *gidstr;
2823         gid_t primary_gid = -1;
2824 
2825         *pp_sids = NULL;
2826         num_sids = 0;
2827 
2828         if (pdb_get_username(user) == NULL) {
2829                 return NT_STATUS_INVALID_PARAMETER;
2830         }
2831 
2832         escape_name = escape_ldap_string_alloc(pdb_get_username(user));
2833         if (escape_name == NULL)
2834                 return NT_STATUS_NO_MEMORY;
2835 
2836         /* retrieve the users primary gid */
2837         filter = talloc_asprintf(mem_ctx,
2838                                  "(&(objectClass=%s)(uid=%s))",
2839                                  LDAP_OBJ_SAMBASAMACCOUNT,
2840                                  escape_name);
2841         if (filter == NULL) {
2842                 ret = NT_STATUS_NO_MEMORY;
2843                 goto done;
2844         }
2845 
2846         rc = smbldap_search(conn, lp_ldap_suffix(),
2847                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2848 
2849         if (rc != LDAP_SUCCESS)
2850                 goto done;
2851 
2852         talloc_autofree_ldapmsg(mem_ctx, result);
2853 
2854         count = ldap_count_entries(priv2ld(ldap_state), result);
2855 
2856         switch (count) {
2857         case 0: 
2858                 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2859                 ret = NT_STATUS_NO_SUCH_USER;
2860                 goto done;
2861         case 1:
2862                 entry = ldap_first_entry(priv2ld(ldap_state), result);
2863 
2864                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2865                 if (!gidstr) {
2866                         DEBUG (1, ("Unable to find the member's gid!\n"));
2867                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2868                         goto done;
2869                 }
2870                 primary_gid = strtoul(gidstr, NULL, 10);
2871                 break;
2872         default:
2873                 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2874                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2875                 goto done;
2876         }
2877 
2878         filter = talloc_asprintf(mem_ctx,
2879                                  "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2880                                  LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2881         if (filter == NULL) {
2882                 ret = NT_STATUS_NO_MEMORY;
2883                 goto done;
2884         }
2885 
2886         rc = smbldap_search(conn, lp_ldap_suffix(),
2887                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2888 
2889         if (rc != LDAP_SUCCESS)
2890                 goto done;
2891 
2892         talloc_autofree_ldapmsg(mem_ctx, result);
2893 
2894         num_gids = 0;
2895         *pp_gids = NULL;
2896 
2897         num_sids = 0;
2898         *pp_sids = NULL;
2899 
2900         /* We need to add the primary group as the first gid/sid */
2901 
2902         if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2903                 ret = NT_STATUS_NO_MEMORY;
2904                 goto done;
2905         }
2906 
2907         /* This sid will be replaced later */
2908 
2909         ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2910                                       &num_sids);
2911         if (!NT_STATUS_IS_OK(ret)) {
2912                 goto done;
2913         }
2914 
2915         for (entry = ldap_first_entry(conn->ldap_struct, result);
2916              entry != NULL;
2917              entry = ldap_next_entry(conn->ldap_struct, entry))
2918         {
2919                 fstring str;
2920                 DOM_SID sid;
2921                 gid_t gid;
2922                 char *end;
2923 
2924                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2925                                                   entry, "sambaSID",
2926                                                   str, sizeof(str)-1))
2927                         continue;
2928 
2929                 if (!string_to_sid(&sid, str))
2930                         goto done;
2931 
2932                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2933                                                   entry, "gidNumber",
2934                                                   str, sizeof(str)-1))
2935                         continue;
2936 
2937                 gid = strtoul(str, &end, 10);
2938 
2939                 if (PTR_DIFF(end, str) != strlen(str))
2940                         goto done;
2941 
2942                 if (gid == primary_gid) {
2943                         sid_copy(&(*pp_sids)[0], &sid);
2944                 } else {
2945                         if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2946                                                 &num_gids)) {
2947                                 ret = NT_STATUS_NO_MEMORY;
2948                                 goto done;
2949                         }
2950                         ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2951                                                       &num_sids);
2952                         if (!NT_STATUS_IS_OK(ret)) {
2953                                 goto done;
2954                         }
2955                 }
2956         }
2957 
2958         if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2959                 DEBUG(3, ("primary group of [%s] not found\n",
2960                           pdb_get_username(user)));
2961                 goto done;
2962         }
2963 
2964         *p_num_groups = num_sids;
2965 
2966         ret = NT_STATUS_OK;
2967 
2968  done:
2969 
2970         SAFE_FREE(escape_name);
2971         return ret;
2972 }
2973 
2974 /**********************************************************************
2975  * Augment a posixGroup object with a sambaGroupMapping domgroup
2976  *********************************************************************/
2977 
2978 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
     /* [<][>][^][v][top][bottom][index][help] */
2979                                        struct ldapsam_privates *ldap_state,
2980                                        GROUP_MAP *map)
2981 {
2982         const char *filter, *dn;
2983         LDAPMessage *msg, *entry;
2984         LDAPMod **mods;
2985         int rc;
2986 
2987         filter = talloc_asprintf(mem_ctx,
2988                                  "(&(objectClass=%s)(gidNumber=%u))",
2989                                  LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2990         if (filter == NULL) {
2991                 return NT_STATUS_NO_MEMORY;
2992         }
2993 
2994         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2995                                    get_attr_list(mem_ctx, groupmap_attr_list),
2996                                    &msg);
2997         talloc_autofree_ldapmsg(mem_ctx, msg);
2998 
2999         if ((rc != LDAP_SUCCESS) ||
3000             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3001             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3002                 return NT_STATUS_NO_SUCH_GROUP;
3003         }
3004 
3005         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3006         if (dn == NULL) {
3007                 return NT_STATUS_NO_MEMORY;
3008         }
3009 
3010         mods = NULL;
3011         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3012                         LDAP_OBJ_GROUPMAP);
3013         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3014                          sid_string_talloc(mem_ctx, &map->sid));
3015         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3016                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3017         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3018                          map->nt_name);
3019         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3020                          map->comment);
3021         talloc_autofree_ldapmod(mem_ctx, mods);
3022 
3023         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3024         if (rc != LDAP_SUCCESS) {
3025                 return NT_STATUS_ACCESS_DENIED;
3026         }
3027 
3028         return NT_STATUS_OK;
3029 }
3030 
3031 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3032                                                 GROUP_MAP *map)
3033 {
3034         struct ldapsam_privates *ldap_state =
3035                 (struct ldapsam_privates *)methods->private_data;
3036         LDAPMessage *msg = NULL;
3037         LDAPMod **mods = NULL;
3038         const char *attrs[] = { NULL };
3039         char *filter;
3040 
3041         char *dn;
3042         TALLOC_CTX *mem_ctx;
3043         NTSTATUS result;
3044 
3045         DOM_SID sid;
3046 
3047         int rc;
3048 
3049         mem_ctx = talloc_new(NULL);
3050         if (mem_ctx == NULL) {
3051                 DEBUG(0, ("talloc_new failed\n"));
3052                 return NT_STATUS_NO_MEMORY;
3053         }
3054 
3055         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3056                                  sid_string_talloc(mem_ctx, &map->sid));
3057         if (filter == NULL) {
3058                 result = NT_STATUS_NO_MEMORY;
3059                 goto done;
3060         }
3061 
3062         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3063                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3064         talloc_autofree_ldapmsg(mem_ctx, msg);
3065 
3066         if ((rc == LDAP_SUCCESS) &&
3067             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3068 
3069                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3070                           "group mapping entry\n", sid_string_dbg(&map->sid)));
3071                 result = NT_STATUS_GROUP_EXISTS;
3072                 goto done;
3073         }
3074 
3075         switch (map->sid_name_use) {
3076 
3077         case SID_NAME_DOM_GRP:
3078                 /* To map a domain group we need to have a posix group
3079                    to attach to. */
3080                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3081                 goto done;
3082                 break;
3083 
3084         case SID_NAME_ALIAS:
3085                 if (!sid_check_is_in_our_domain(&map->sid) 
3086                         && !sid_check_is_in_builtin(&map->sid) ) 
3087                 {
3088                         DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3089                                   sid_string_dbg(&map->sid)));
3090                         result = NT_STATUS_INVALID_PARAMETER;
3091                         goto done;
3092                 }
3093                 break;
3094 
3095         default:
3096                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3097                           sid_type_lookup(map->sid_name_use)));
3098                 result = NT_STATUS_INVALID_PARAMETER;
3099                 goto done;
3100         }
3101 
3102         /* Domain groups have been mapped in a separate routine, we have to
3103          * create an alias now */
3104 
3105         if (map->gid == -1) {
3106                 DEBUG(10, ("Refusing to map gid==-1\n"));
3107                 result = NT_STATUS_INVALID_PARAMETER;
3108                 goto done;
3109         }
3110 
3111         if (pdb_gid_to_sid(map->gid, &sid)) {
3112                 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3113                           "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3114                 result = NT_STATUS_GROUP_EXISTS;
3115                 goto done;
3116         }
3117 
3118         /* Ok, enough checks done. It's still racy to go ahead now, but that's
3119          * the best we can get out of LDAP. */
3120 
3121         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3122                              sid_string_talloc(mem_ctx, &map->sid),
3123                              lp_ldap_group_suffix());
3124         if (dn == NULL) {
3125                 result = NT_STATUS_NO_MEMORY;
3126                 goto done;
3127         }
3128 
3129         mods = NULL;
3130 
3131         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3132                          LDAP_OBJ_SID_ENTRY);
3133         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3134                          LDAP_OBJ_GROUPMAP);
3135         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3136                          sid_string_talloc(mem_ctx, &map->sid));
3137         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3138                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3139         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3140                          map->nt_name);
3141         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3142                          map->comment);
3143         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3144                          talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3145         talloc_autofree_ldapmod(mem_ctx, mods);
3146 
3147         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3148 
3149         result = (rc == LDAP_SUCCESS) ?
3150                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3151 
3152  done:
3153         TALLOC_FREE(mem_ctx);
3154         return result;
3155 }
3156 
3157 /**********************************************************************
3158  * Update a group mapping entry. We're quite strict about what can be changed:
3159  * Only the description and displayname may be changed. It simply does not
3160  * make any sense to change the SID, gid or the type in a mapping.
3161  *********************************************************************/
3162 
3163 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3164                                                    GROUP_MAP *map)
3165 {
3166         struct ldapsam_privates *ldap_state =
3167                 (struct ldapsam_privates *)methods->private_data;
3168         int rc;
3169         const char *filter, *dn;
3170         LDAPMessage *msg = NULL;
3171         LDAPMessage *entry = NULL;
3172         LDAPMod **mods = NULL;
3173         TALLOC_CTX *mem_ctx;
3174         NTSTATUS result;
3175 
3176         mem_ctx = talloc_new(NULL);
3177         if (mem_ctx == NULL) {
3178                 DEBUG(0, ("talloc_new failed\n"));
3179                 return NT_STATUS_NO_MEMORY;
3180         }
3181 
3182         /* Make 100% sure that sid, gid and type are not changed by looking up
3183          * exactly the values we're given in LDAP. */
3184 
3185         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3186                                  "(sambaSid=%s)(gidNumber=%u)"
3187                                  "(sambaGroupType=%d))",
3188                                  LDAP_OBJ_GROUPMAP,
3189                                  sid_string_talloc(mem_ctx, &map->sid),
3190                                  (unsigned int)map->gid, map->sid_name_use);
3191         if (filter == NULL) {
3192                 result = NT_STATUS_NO_MEMORY;
3193                 goto done;
3194         }
3195 
3196         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3197                                    get_attr_list(mem_ctx, groupmap_attr_list),
3198                                    &msg);
3199         talloc_autofree_ldapmsg(mem_ctx, msg);
3200 
3201         if ((rc != LDAP_SUCCESS) ||
3202             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3203             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3204                 result = NT_STATUS_NO_SUCH_GROUP;
3205                 goto done;
3206         }
3207 
3208         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3209 
3210         if (dn == NULL) {
3211                 result = NT_STATUS_NO_MEMORY;
3212                 goto done;
3213         }
3214 
3215         mods = NULL;
3216         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3217                          map->nt_name);
3218         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3219                          map->comment);
3220         talloc_autofree_ldapmod(mem_ctx, mods);
3221 
3222         if (mods == NULL) {
3223                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3224                           "nothing to do\n"));
3225                 result = NT_STATUS_OK;
3226                 goto done;
3227         }
3228 
3229         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3230 
3231         if (rc != LDAP_SUCCESS) {
3232                 result = NT_STATUS_ACCESS_DENIED;
3233                 goto done;
3234         }
3235 
3236         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3237                   "group %lu in LDAP\n", (unsigned long)map->gid));
3238 
3239         result = NT_STATUS_OK;
3240 
3241  done:
3242         TALLOC_FREE(mem_ctx);
3243         return result;
3244 }
3245 
3246 /**********************************************************************
3247  *********************************************************************/
3248 
3249 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3250                                                    DOM_SID sid)
3251 {
3252         struct ldapsam_privates *priv =
3253                 (struct ldapsam_privates *)methods->private_data;
3254         LDAPMessage *msg, *entry;
3255         int rc;
3256         NTSTATUS result;
3257         TALLOC_CTX *mem_ctx;
3258         char *filter;
3259 
3260         mem_ctx = talloc_new(NULL);
3261         if (mem_ctx == NULL) {
3262                 DEBUG(0, ("talloc_new failed\n"));
3263                 return NT_STATUS_NO_MEMORY;
3264         }
3265 
3266         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3267                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3268                                  sid_string_talloc(mem_ctx, &sid));
3269         if (filter == NULL) {
3270                 result = NT_STATUS_NO_MEMORY;
3271                 goto done;
3272         }
3273         rc = smbldap_search_suffix(priv->smbldap_state, filter,
3274                                    get_attr_list(mem_ctx, groupmap_attr_list),
3275                                    &msg);
3276         talloc_autofree_ldapmsg(mem_ctx, msg);
3277 
3278         if ((rc != LDAP_SUCCESS) ||
3279             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3280             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3281                 result = NT_STATUS_NO_SUCH_GROUP;
3282                 goto done;
3283         }
3284 
3285         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3286                                   get_attr_list(mem_ctx,
3287                                                 groupmap_attr_list_to_delete));
3288  
3289         if ((rc == LDAP_NAMING_VIOLATION) ||
3290             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3291             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3292                 const char *attrs[] = { "sambaGroupType", "description",
3293                                         "displayName", "sambaSIDList",
3294                                         NULL };
3295 
3296                 /* Second try. Don't delete the sambaSID attribute, this is
3297                    for "old" entries that are tacked on a winbind
3298                    sambaIdmapEntry. */
3299 
3300                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3301                                           LDAP_OBJ_GROUPMAP, attrs);
3302         }
3303 
3304         if ((rc == LDAP_NAMING_VIOLATION) ||
3305             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3306             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3307                 const char *attrs[] = { "sambaGroupType", "description",
3308                                         "displayName", "sambaSIDList",
3309                                         "gidNumber", NULL };
3310 
3311                 /* Third try. This is a post-3.0.21 alias (containing only
3312                  * sambaSidEntry and sambaGroupMapping classes), we also have
3313                  * to delete the gidNumber attribute, only the sambaSidEntry
3314                  * remains */
3315 
3316                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3317                                           LDAP_OBJ_GROUPMAP, attrs);
3318         }
3319 
3320         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3321 
3322  done:
3323         TALLOC_FREE(mem_ctx);
3324         return result;
3325  }
3326 
3327 /**********************************************************************
3328  *********************************************************************/
3329 
3330 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
3331                                     bool update)
3332 {
3333         struct ldapsam_privates *ldap_state =
3334                 (struct ldapsam_privates *)my_methods->private_data;
3335         char *filter = NULL;
3336         int rc;
3337         const char **attr_list;
3338 
3339         filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3340         if (!filter) {
3341                 return NT_STATUS_NO_MEMORY;
3342         }
3343         attr_list = get_attr_list( NULL, groupmap_attr_list );
3344         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3345                             LDAP_SCOPE_SUBTREE, filter,
3346                             attr_list, 0, &ldap_state->result);
3347         TALLOC_FREE(attr_list);
3348 
3349         if (rc != LDAP_SUCCESS) {
3350                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3351                           ldap_err2string(rc)));
3352                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3353                           lp_ldap_suffix(), filter));
3354                 ldap_msgfree(ldap_state->result);
3355                 ldap_state->result = NULL;
3356                 TALLOC_FREE(filter);
3357                 return NT_STATUS_UNSUCCESSFUL;
3358         }
3359 
3360         TALLOC_FREE(filter);
3361 
3362         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3363                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3364                                      ldap_state->result)));
3365 
3366         ldap_state->entry =
3367                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3368                                  ldap_state->result);
3369         ldap_state->index = 0;
3370 
3371         return NT_STATUS_OK;
3372 }
3373 
3374 /**********************************************************************
3375  *********************************************************************/
3376 
3377 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
     /* [<][>][^][v][top][bottom][index][help] */
3378 {
3379         ldapsam_endsampwent(my_methods);
3380 }
3381 
3382 /**********************************************************************
3383  *********************************************************************/
3384 
3385 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
3386                                     GROUP_MAP *map)
3387 {
3388         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3389         struct ldapsam_privates *ldap_state =
3390                 (struct ldapsam_privates *)my_methods->private_data;
3391         bool bret = False;
3392 
3393         while (!bret) {
3394                 if (!ldap_state->entry)
3395                         return ret;
3396                 
3397                 ldap_state->index++;
3398                 bret = init_group_from_ldap(ldap_state, map,
3399                                             ldap_state->entry);
3400                 
3401                 ldap_state->entry =
3402                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3403                                         ldap_state->entry);     
3404         }
3405 
3406         return NT_STATUS_OK;
3407 }
3408 
3409 /**********************************************************************
3410  *********************************************************************/
3411 
3412 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3413                                            const DOM_SID *domsid, enum lsa_SidType sid_name_use,
3414                                            GROUP_MAP **pp_rmap,
3415                                            size_t *p_num_entries,
3416                                            bool unix_only)
3417 {
3418         GROUP_MAP map;
3419         size_t entries = 0;
3420 
3421         *p_num_entries = 0;
3422         *pp_rmap = NULL;
3423 
3424         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3425                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3426                           "passdb\n"));
3427                 return NT_STATUS_ACCESS_DENIED;
3428         }
3429 
3430         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3431                 if (sid_name_use != SID_NAME_UNKNOWN &&
3432                     sid_name_use != map.sid_name_use) {
3433                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3434                                   "not of the requested type\n", map.nt_name));
3435                         continue;
3436                 }
3437                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3438                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3439                                   "non mapped\n", map.nt_name));
3440                         continue;
3441                 }
3442 
3443                 (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3444                 if (!(*pp_rmap)) {
3445                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3446                                  "enlarge group map!\n"));
3447                         return NT_STATUS_UNSUCCESSFUL;
3448                 }
3449 
3450                 (*pp_rmap)[entries] = map;
3451 
3452                 entries += 1;
3453 
3454         }
3455         ldapsam_endsamgrent(methods);
3456 
3457         *p_num_entries = entries;
3458 
3459         return NT_STATUS_OK;
3460 }
3461 
3462 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3463                                         const DOM_SID *alias,
3464                                         const DOM_SID *member,
3465                                         int modop)
3466 {
3467         struct ldapsam_privates *ldap_state =
3468                 (struct ldapsam_privates *)methods->private_data;
3469         char *dn = NULL;
3470         LDAPMessage *result = NULL;
3471         LDAPMessage *entry = NULL;
3472         int count;
3473         LDAPMod **mods = NULL;
3474         int rc;
3475         enum lsa_SidType type = SID_NAME_USE_NONE;
3476         fstring tmp;
3477 
3478         char *filter = NULL;
3479 
3480         if (sid_check_is_in_builtin(alias)) {
3481                 type = SID_NAME_ALIAS;
3482         }
3483 
3484         if (sid_check_is_in_our_domain(alias)) {
3485                 type = SID_NAME_ALIAS;
3486         }
3487 
3488         if (type == SID_NAME_USE_NONE) {
3489                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3490                           sid_string_dbg(alias)));
3491                 return NT_STATUS_NO_SUCH_ALIAS;
3492         }
3493 
3494         if (asprintf(&filter,
3495                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3496                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3497                      type) < 0) {
3498                 return NT_STATUS_NO_MEMORY;
3499         }
3500 
3501         if (ldapsam_search_one_group(ldap_state, filter,
3502                                      &result) != LDAP_SUCCESS) {
3503                 SAFE_FREE(filter);
3504                 return NT_STATUS_NO_SUCH_ALIAS;
3505         }
3506 
3507         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3508                                    result);
3509 
3510         if (count < 1) {
3511                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3512                 ldap_msgfree(result);
3513                 SAFE_FREE(filter);
3514                 return NT_STATUS_NO_SUCH_ALIAS;
3515         }
3516 
3517         if (count > 1) {
3518                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3519                           "filter %s: count=%d\n", filter, count));
3520                 ldap_msgfree(result);
3521                 SAFE_FREE(filter);
3522                 return NT_STATUS_NO_SUCH_ALIAS;
3523         }
3524 
3525         SAFE_FREE(filter);
3526 
3527         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3528                                  result);
3529 
3530         if (!entry) {
3531                 ldap_msgfree(result);
3532                 return NT_STATUS_UNSUCCESSFUL;
3533         }
3534 
3535         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3536         if (!dn) {
3537                 ldap_msgfree(result);
3538                 return NT_STATUS_UNSUCCESSFUL;
3539         }
3540 
3541         smbldap_set_mod(&mods, modop,
3542                         get_attr_key2string(groupmap_attr_list,
3543                                             LDAP_ATTR_SID_LIST),
3544                         sid_to_fstring(tmp, member));
3545 
3546         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3547 
3548         ldap_mods_free(mods, True);
3549         ldap_msgfree(result);
3550         TALLOC_FREE(dn);
3551 
3552         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3553                 return NT_STATUS_MEMBER_IN_ALIAS;
3554         }
3555 
3556         if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3557                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3558         }
3559 
3560         if (rc != LDAP_SUCCESS) {
3561                 return NT_STATUS_UNSUCCESSFUL;
3562         }
3563 
3564         return NT_STATUS_OK;
3565 }
3566 
3567 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3568                                      const DOM_SID *alias,
3569                                      const DOM_SID *member)
3570 {
3571         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3572 }
3573 
3574 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3575                                      const DOM_SID *alias,
3576                                      const DOM_SID *member)
3577 {
3578         return ldapsam_modify_aliasmem(methods, alias, member,
3579                                        LDAP_MOD_DELETE);
3580 }
3581 
3582 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3583                                       const DOM_SID *alias,
3584                                       DOM_SID **pp_members,
3585                                       size_t *p_num_members)
3586 {
3587         struct ldapsam_privates *ldap_state =
3588                 (struct ldapsam_privates *)methods->private_data;
3589         LDAPMessage *result = NULL;
3590         LDAPMessage *entry = NULL;
3591         int count;
3592         char **values = NULL;
3593         int i;
3594         char *filter = NULL;
3595         size_t num_members = 0;
3596         enum lsa_SidType type = SID_NAME_USE_NONE;
3597         fstring tmp;
3598 
3599         *pp_members = NULL;
3600         *p_num_members = 0;
3601 
3602         if (sid_check_is_in_builtin(alias)) {
3603                 type = SID_NAME_ALIAS;
3604         }
3605 
3606         if (sid_check_is_in_our_domain(alias)) {
3607                 type = SID_NAME_ALIAS;
3608         }
3609 
3610         if (type == SID_NAME_USE_NONE) {
3611                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3612                           sid_string_dbg(alias)));
3613                 return NT_STATUS_NO_SUCH_ALIAS;
3614         }
3615 
3616         if (asprintf(&filter,
3617                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3618                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3619                      type) < 0) {
3620                 return NT_STATUS_NO_MEMORY;
3621         }
3622 
3623         if (ldapsam_search_one_group(ldap_state, filter,
3624                                      &result) != LDAP_SUCCESS) {
3625                 SAFE_FREE(filter);
3626                 return NT_STATUS_NO_SUCH_ALIAS;
3627         }
3628 
3629         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3630                                    result);
3631 
3632         if (count < 1) {
3633                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3634                 ldap_msgfree(result);
3635                 SAFE_FREE(filter);
3636                 return NT_STATUS_NO_SUCH_ALIAS;
3637         }
3638 
3639         if (count > 1) {
3640                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3641                           "filter %s: count=%d\n", filter, count));
3642                 ldap_msgfree(result);
3643                 SAFE_FREE(filter);
3644                 return NT_STATUS_NO_SUCH_ALIAS;
3645         }
3646 
3647         SAFE_FREE(filter);
3648 
3649         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3650                                  result);
3651 
3652         if (!entry) {
3653                 ldap_msgfree(result);
3654                 return NT_STATUS_UNSUCCESSFUL;
3655         }
3656 
3657         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3658                                  entry,
3659                                  get_attr_key2string(groupmap_attr_list,
3660                                                      LDAP_ATTR_SID_LIST));
3661 
3662         if (values == NULL) {
3663                 ldap_msgfree(result);
3664                 return NT_STATUS_OK;
3665         }
3666 
3667         count = ldap_count_values(values);
3668 
3669         for (i=0; i<count; i++) {
3670                 DOM_SID member;
3671                 NTSTATUS status;
3672 
3673                 if (!string_to_sid(&member, values[i]))
3674                         continue;
3675 
3676                 status = add_sid_to_array(NULL, &member, pp_members,
3677                                           &num_members);
3678                 if (!NT_STATUS_IS_OK(status)) {
3679                         ldap_value_free(values);
3680                         ldap_msgfree(result);
3681                         return status;
3682                 }
3683         }
3684 
3685         *p_num_members = num_members;
3686         ldap_value_free(values);
3687         ldap_msgfree(result);
3688 
3689         return NT_STATUS_OK;
3690 }
3691 
3692 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3693                                           TALLOC_CTX *mem_ctx,
3694                                           const DOM_SID *domain_sid,
3695                                           const DOM_SID *members,
3696                                           size_t num_members,
3697                                           uint32 **pp_alias_rids,
3698                                           size_t *p_num_alias_rids)
3699 {
3700         struct ldapsam_privates *ldap_state =
3701                 (struct ldapsam_privates *)methods->private_data;
3702         LDAP *ldap_struct;
3703 
3704         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3705 
3706         LDAPMessage *result = NULL;
3707         LDAPMessage *entry = NULL;
3708         int i;
3709         int rc;
3710         char *filter;
3711         enum lsa_SidType type = SID_NAME_USE_NONE;
3712 
3713         if (sid_check_is_builtin(domain_sid)) {
3714                 type = SID_NAME_ALIAS;
3715         }
3716 
3717         if (sid_check_is_domain(domain_sid)) {
3718                 type = SID_NAME_ALIAS;
3719         }
3720 
3721         if (type == SID_NAME_USE_NONE) {
3722                 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3723                           sid_string_dbg(domain_sid)));
3724                 return NT_STATUS_UNSUCCESSFUL;
3725         }
3726 
3727         filter = talloc_asprintf(mem_ctx,
3728                                  "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3729                                  LDAP_OBJ_GROUPMAP, type);
3730 
3731         for (i=0; i<num_members; i++)
3732                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3733                                          filter,
3734                                          sid_string_talloc(mem_ctx,
3735                                                            &members[i]));
3736 
3737         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3738 
3739         if (filter == NULL) {
3740                 return NT_STATUS_NO_MEMORY;
3741         }
3742 
3743         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3744                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3745 
3746         if (rc != LDAP_SUCCESS)
3747                 return NT_STATUS_UNSUCCESSFUL;
3748 
3749         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3750 
3751         for (entry = ldap_first_entry(ldap_struct, result);
3752              entry != NULL;
3753              entry = ldap_next_entry(ldap_struct, entry))
3754         {
3755                 fstring sid_str;
3756                 DOM_SID sid;
3757                 uint32 rid;
3758 
3759                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3760                                                   LDAP_ATTRIBUTE_SID,
3761                                                   sid_str,
3762                                                   sizeof(sid_str)-1))
3763                         continue;
3764 
3765                 if (!string_to_sid(&sid, sid_str))
3766                         continue;
3767 
3768                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3769                         continue;
3770 
3771                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3772                                         p_num_alias_rids)) {
3773                         ldap_msgfree(result);
3774                         return NT_STATUS_NO_MEMORY;
3775                 }
3776         }
3777 
3778         ldap_msgfree(result);
3779         return NT_STATUS_OK;
3780 }
3781 
3782 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3783                                                    int policy_index,
3784                                                    uint32 value)
3785 {
3786         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3787         int rc;
3788         LDAPMod **mods = NULL;
3789         fstring value_string;
3790         const char *policy_attr = NULL;
3791 
3792         struct ldapsam_privates *ldap_state =
3793                 (struct ldapsam_privates *)methods->private_data;
3794 
3795         DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3796 
3797         if (!ldap_state->domain_dn) {
3798                 return NT_STATUS_INVALID_PARAMETER;
3799         }
3800 
3801         policy_attr = get_account_policy_attr(policy_index);
3802         if (policy_attr == NULL) {
3803                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3804                          "policy\n"));
3805                 return ntstatus;
3806         }
3807 
3808         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3809 
3810         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3811 
3812         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3813                             mods);
3814 
3815         ldap_mods_free(mods, True);
3816 
3817         if (rc != LDAP_SUCCESS) {
3818                 return ntstatus;
3819         }
3820 
3821         if (!cache_account_policy_set(policy_index, value)) {
3822                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3823                          "update local tdb cache\n"));
3824                 return ntstatus;
3825         }
3826 
3827         return NT_STATUS_OK;
3828 }
3829 
3830 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3831                                            int policy_index, uint32 value)
3832 {
3833         return ldapsam_set_account_policy_in_ldap(methods, policy_index,
3834                                                   value);
3835 }
3836 
3837 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3838                                                      int policy_index,
3839                                                      uint32 *value)
3840 {
3841         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3842         LDAPMessage *result = NULL;
3843         LDAPMessage *entry = NULL;
3844         int count;
3845         int rc;
3846         char **vals = NULL;
3847         const char *policy_attr = NULL;
3848 
3849         struct ldapsam_privates *ldap_state =
3850                 (struct ldapsam_privates *)methods->private_data;
3851 
3852         const char *attrs[2];
3853 
3854         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3855 
3856         if (!ldap_state->domain_dn) {
3857                 return NT_STATUS_INVALID_PARAMETER;
3858         }
3859 
3860         policy_attr = get_account_policy_attr(policy_index);
3861         if (!policy_attr) {
3862                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3863                          "policy index: %d\n", policy_index));
3864                 return ntstatus;
3865         }
3866 
3867         attrs[0] = policy_attr;
3868         attrs[1] = NULL;
3869 
3870         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3871                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0,
3872                             &result);
3873 
3874         if (rc != LDAP_SUCCESS) {
3875                 return ntstatus;
3876         }
3877 
3878         count = ldap_count_entries(priv2ld(ldap_state), result);
3879         if (count < 1) {
3880                 goto out;
3881         }
3882 
3883         entry = ldap_first_entry(priv2ld(ldap_state), result);
3884         if (entry == NULL) {
3885                 goto out;
3886         }
3887 
3888         vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3889         if (vals == NULL) {
3890                 goto out;
3891         }
3892 
3893         *value = (uint32)atol(vals[0]);
3894         
3895         ntstatus = NT_STATUS_OK;
3896 
3897 out:
3898         if (vals)
3899                 ldap_value_free(vals);
3900         ldap_msgfree(result);
3901 
3902         return ntstatus;
3903 }
3904 
3905 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
3906 
3907    - if user hasn't decided to use account policies inside LDAP just reuse the
3908      old tdb values
3909    
3910    - if there is a valid cache entry, return that
3911    - if there is an LDAP entry, update cache and return 
3912    - otherwise set to default, update cache and return
3913 
3914    Guenther
3915 */
3916 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3917                                            int policy_index, uint32 *value)
3918 {
3919         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3920 
3921         if (cache_account_policy_get(policy_index, value)) {
3922                 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3923                           "cache\n"));
3924                 return NT_STATUS_OK;
3925         }
3926 
3927         ntstatus = ldapsam_get_account_policy_from_ldap(methods, policy_index,
3928                                                         value);
3929         if (NT_STATUS_IS_OK(ntstatus)) {
3930                 goto update_cache;
3931         }
3932 
3933         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3934                   "ldap\n"));
3935 
3936 #if 0
3937         /* should we automagically migrate old tdb value here ? */
3938         if (account_policy_get(policy_index, value))
3939                 goto update_ldap;
3940 
3941         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3942                   "default\n", policy_index));
3943 #endif
3944 
3945         if (!account_policy_get_default(policy_index, value)) {
3946                 return ntstatus;
3947         }
3948         
3949 /* update_ldap: */
3950  
3951         ntstatus = ldapsam_set_account_policy(methods, policy_index, *value);
3952         if (!NT_STATUS_IS_OK(ntstatus)) {
3953                 return ntstatus;
3954         }
3955                 
3956  update_cache:
3957  
3958         if (!cache_account_policy_set(policy_index, *value)) {
3959                 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3960                          "tdb as a cache\n"));
3961                 return NT_STATUS_UNSUCCESSFUL;
3962         }
3963 
3964         return NT_STATUS_OK;
3965 }
3966 
3967 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
3968                                     const DOM_SID *domain_sid,
3969                                     int num_rids,
3970                                     uint32 *rids,
3971                                     const char **names,
3972                                     enum lsa_SidType *attrs)
3973 {
3974         struct ldapsam_privates *ldap_state =
3975                 (struct ldapsam_privates *)methods->private_data;
3976         LDAPMessage *msg = NULL;
3977         LDAPMessage *entry;
3978         char *allsids = NULL;
3979         int i, rc, num_mapped;
3980         NTSTATUS result = NT_STATUS_NO_MEMORY;
3981         TALLOC_CTX *mem_ctx;
3982         LDAP *ld;
3983         bool is_builtin;
3984 
3985         mem_ctx = talloc_new(NULL);
3986         if (mem_ctx == NULL) {
3987                 DEBUG(0, ("talloc_new failed\n"));
3988                 goto done;
3989         }
3990 
3991         if (!sid_check_is_builtin(domain_sid) &&
3992             !sid_check_is_domain(domain_sid)) {
3993                 result = NT_STATUS_INVALID_PARAMETER;
3994                 goto done;
3995         }
3996 
3997         for (i=0; i<num_rids; i++)
3998                 attrs[i] = SID_NAME_UNKNOWN;
3999 
4000         allsids = talloc_strdup(mem_ctx, "");
4001         if (allsids == NULL) {
4002                 goto done;
4003         }
4004 
4005         for (i=0; i<num_rids; i++) {
4006                 DOM_SID sid;
4007                 sid_compose(&sid, domain_sid, rids[i]);
4008                 allsids = talloc_asprintf_append_buffer(
4009                         allsids, "(sambaSid=%s)",
4010                         sid_string_talloc(mem_ctx, &sid));
4011                 if (allsids == NULL) {
4012                         goto done;
4013                 }
4014         }
4015 
4016         /* First look for users */
4017 
4018         {
4019                 char *filter;
4020                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4021 
4022                 filter = talloc_asprintf(
4023                         mem_ctx, ("(&(objectClass=%s)(|%s))"),
4024                         LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4025 
4026                 if (filter == NULL) {
4027                         goto done;
4028                 }
4029 
4030                 rc = smbldap_search(ldap_state->smbldap_state,
4031                                     lp_ldap_user_suffix(),
4032                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4033                                     &msg);
4034                 talloc_autofree_ldapmsg(mem_ctx, msg);
4035         }
4036 
4037         if (rc != LDAP_SUCCESS)
4038                 goto done;
4039 
4040         ld = ldap_state->smbldap_state->ldap_struct;
4041         num_mapped = 0;
4042 
4043         for (entry = ldap_first_entry(ld, msg);
4044              entry != NULL;
4045              entry = ldap_next_entry(ld, entry)) {
4046                 uint32 rid;
4047                 int rid_index;
4048                 const char *name;
4049 
4050                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4051                                                     &rid)) {
4052                         DEBUG(2, ("Could not find sid from ldap entry\n"));
4053                         continue;
4054                 }
4055 
4056                 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4057                                                        names);
4058                 if (name == NULL) {
4059                         DEBUG(2, ("Could not retrieve uid attribute\n"));
4060                         continue;
4061                 }
4062 
4063                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4064                         if (rid == rids[rid_index])
4065                                 break;
4066                 }
4067 
4068                 if (rid_index == num_rids) {
4069                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4070                         continue;
4071                 }
4072 
4073                 attrs[rid_index] = SID_NAME_USER;
4074                 names[rid_index] = name;
4075                 num_mapped += 1;
4076         }
4077 
4078         if (num_mapped == num_rids) {
4079                 /* No need to look for groups anymore -- we're done */
4080                 result = NT_STATUS_OK;
4081                 goto done;
4082         }
4083 
4084         /* Same game for groups */
4085 
4086         {
4087                 char *filter;
4088                 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4089                                              "sambaGroupType", NULL };
4090 
4091                 filter = talloc_asprintf(
4092                         mem_ctx, "(&(objectClass=%s)(|%s))",
4093                         LDAP_OBJ_GROUPMAP, allsids);
4094                 if (filter == NULL) {
4095                         goto done;
4096                 }
4097 
4098                 rc = smbldap_search(ldap_state->smbldap_state,
4099                                     lp_ldap_suffix(),
4100                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4101                                     &msg);
4102                 talloc_autofree_ldapmsg(mem_ctx, msg);
4103         }
4104 
4105         if (rc != LDAP_SUCCESS)
4106                 goto done;
4107 
4108         /* ldap_struct might have changed due to a reconnect */
4109 
4110         ld = ldap_state->smbldap_state->ldap_struct;
4111 
4112         /* For consistency checks, we already checked we're only domain or builtin */
4113 
4114         is_builtin = sid_check_is_builtin(domain_sid);
4115 
4116         for (entry = ldap_first_entry(ld, msg);
4117              entry != NULL;
4118              entry = ldap_next_entry(ld, entry))
4119         {
4120                 uint32 rid;
4121                 int rid_index;
4122                 const char *attr;
4123                 enum lsa_SidType type;
4124                 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4125 
4126                 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4127                                                        mem_ctx);
4128                 if (attr == NULL) {
4129                         DEBUG(2, ("Could not extract type from ldap entry %s\n",
4130                                   dn));
4131                         continue;
4132                 }
4133 
4134                 type = (enum lsa_SidType)atol(attr);
4135 
4136                 /* Consistency checks */
4137                 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4138                     (!is_builtin && ((type != SID_NAME_ALIAS) &&
4139                                      (type != SID_NAME_DOM_GRP)))) {
4140                         DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4141                 }
4142 
4143                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4144                                                     &rid)) {
4145                         DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4146                         continue;
4147                 }
4148 
4149                 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4150 
4151                 if (attr == NULL) {
4152                         DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4153                                    dn));
4154                         attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4155                 }
4156 
4157                 if (attr == NULL) {
4158                         DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4159                                   dn));
4160                         continue;
4161                 }
4162 
4163                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4164                         if (rid == rids[rid_index])
4165                                 break;
4166                 }
4167 
4168                 if (rid_index == num_rids) {
4169                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4170                         continue;
4171                 }
4172 
4173                 attrs[rid_index] = type;
4174                 names[rid_index] = attr;
4175                 num_mapped += 1;
4176         }
4177 
4178         result = NT_STATUS_NONE_MAPPED;
4179 
4180         if (num_mapped > 0)
4181                 result = (num_mapped == num_rids) ?
4182                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4183  done:
4184         TALLOC_FREE(mem_ctx);
4185         return result;
4186 }
4187 
4188 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
     /* [<][>][^][v][top][bottom][index][help] */
4189 {
4190         char *filter = NULL;
4191         char *escaped = NULL;
4192         char *result = NULL;
4193 
4194         if (asprintf(&filter, "(&%s(objectclass=%s))",
4195                           "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4196                 goto done;
4197         }
4198 
4199         escaped = escape_ldap_string_alloc(username);
4200         if (escaped == NULL) goto done;
4201 
4202         result = talloc_string_sub(mem_ctx, filter, "%u", username);
4203 
4204  done:
4205         SAFE_FREE(filter);
4206         SAFE_FREE(escaped);
4207 
4208         return result;
4209 }
4210 
4211 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
     /* [<][>][^][v][top][bottom][index][help] */
4212 {
4213         int i, num = 0;
4214         va_list ap;
4215         const char **result;
4216 
4217         va_start(ap, mem_ctx);
4218         while (va_arg(ap, const char *) != NULL)
4219                 num += 1;
4220         va_end(ap);
4221 
4222         if ((result = TALLOC_ARRAY(mem_ctx, const char *, num+1)) == NULL) {
4223                 return NULL;
4224         }
4225 
4226         va_start(ap, mem_ctx);
4227         for (i=0; i<num; i++) {
4228                 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4229                 if (result[i] == NULL) {
4230                         talloc_free(result);
4231                         va_end(ap);
4232                         return NULL;
4233                 }
4234         }
4235         va_end(ap);
4236 
4237         result[num] = NULL;
4238         return result;
4239 }
4240 
4241 struct ldap_search_state {
4242         struct smbldap_state *connection;
4243 
4244         uint32 acct_flags;
4245         uint16 group_type;
4246 
4247         const char *base;
4248         int scope;
4249         const char *filter;
4250         const char **attrs;
4251         int attrsonly;
4252         void *pagedresults_cookie;
4253 
4254         LDAPMessage *entries, *current_entry;
4255         bool (*ldap2displayentry)(struct ldap_search_state *state,
4256                                   TALLOC_CTX *mem_ctx,
4257                                   LDAP *ld, LDAPMessage *entry,
4258                                   struct samr_displayentry *result);
4259 };
4260 
4261 static bool ldapsam_search_firstpage(struct pdb_search *search)
     /* [<][>][^][v][top][bottom][index][help] */
4262 {
4263         struct ldap_search_state *state =
4264                 (struct ldap_search_state *)search->private_data;
4265         LDAP *ld;
4266         int rc = LDAP_OPERATIONS_ERROR;
4267 
4268         state->entries = NULL;
4269 
4270         if (state->connection->paged_results) {
4271                 rc = smbldap_search_paged(state->connection, state->base,
4272                                           state->scope, state->filter,
4273                                           state->attrs, state->attrsonly,
4274                                           lp_ldap_page_size(), &state->entries,
4275                                           &state->pagedresults_cookie);
4276         }
4277 
4278         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4279 
4280                 if (state->entries != NULL) {
4281                         /* Left over from unsuccessful paged attempt */
4282                         ldap_msgfree(state->entries);
4283                         state->entries = NULL;
4284                 }
4285 
4286                 rc = smbldap_search(state->connection, state->base,
4287                                     state->scope, state->filter, state->attrs,
4288                                     state->attrsonly, &state->entries);
4289 
4290                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4291                         return False;
4292 
4293                 /* Ok, the server was lying. It told us it could do paged
4294                  * searches when it could not. */
4295                 state->connection->paged_results = False;
4296         }
4297 
4298         ld = state->connection->ldap_struct;
4299         if ( ld == NULL) {
4300                 DEBUG(5, ("Don't have an LDAP connection right after a "
4301                           "search\n"));
4302                 return False;
4303         }
4304         state->current_entry = ldap_first_entry(ld, state->entries);
4305 
4306         if (state->current_entry == NULL) {
4307                 ldap_msgfree(state->entries);
4308                 state->entries = NULL;
4309         }
4310 
4311         return True;
4312 }
4313 
4314 static bool ldapsam_search_nextpage(struct pdb_search *search)
     /* [<][>][^][v][top][bottom][index][help] */
4315 {
4316         struct ldap_search_state *state =
4317                 (struct ldap_search_state *)search->private_data;
4318         int rc;
4319 
4320         if (!state->connection->paged_results) {
4321                 /* There is no next page when there are no paged results */
4322                 return False;
4323         }
4324 
4325         rc = smbldap_search_paged(state->connection, state->base,
4326                                   state->scope, state->filter, state->attrs,
4327                                   state->attrsonly, lp_ldap_page_size(),
4328                                   &state->entries,
4329                                   &state->pagedresults_cookie);
4330 
4331         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4332                 return False;
4333 
4334         state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4335 
4336         if (state->current_entry == NULL) {
4337                 ldap_msgfree(state->entries);
4338                 state->entries = NULL;
4339         }
4340 
4341         return True;
4342 }
4343 
4344 static bool ldapsam_search_next_entry(struct pdb_search *search,
     /* [<][>][^][v][top][bottom][index][help] */
4345                                       struct samr_displayentry *entry)
4346 {
4347         struct ldap_search_state *state =
4348                 (struct ldap_search_state *)search->private_data;
4349         bool result;
4350 
4351  retry:
4352         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4353                 return False;
4354 
4355         if ((state->entries == NULL) &&
4356             !ldapsam_search_nextpage(search))
4357                     return False;
4358 
4359         result = state->ldap2displayentry(state, search,
4360                                           state->connection->ldap_struct,
4361                                           state->current_entry, entry);
4362 
4363         if (!result) {
4364                 char *dn;
4365                 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4366                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4367                 if (dn != NULL) ldap_memfree(dn);
4368         }
4369 
4370         state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4371 
4372         if (state->current_entry == NULL) {
4373                 ldap_msgfree(state->entries);
4374                 state->entries = NULL;
4375         }
4376 
4377         if (!result) goto retry;
4378 
4379         return True;
4380 }
4381 
4382 static void ldapsam_search_end(struct pdb_search *search)
     /* [<][>][^][v][top][bottom][index][help] */
4383 {
4384         struct ldap_search_state *state =
4385                 (struct ldap_search_state *)search->private_data;
4386         int rc;
4387 
4388         if (state->pagedresults_cookie == NULL)
4389                 return;
4390 
4391         if (state->entries != NULL)
4392                 ldap_msgfree(state->entries);
4393 
4394         state->entries = NULL;
4395         state->current_entry = NULL;
4396 
4397         if (!state->connection->paged_results)
4398                 return;
4399 
4400         /* Tell the LDAP server we're not interested in the rest anymore. */
4401 
4402         rc = smbldap_search_paged(state->connection, state->base, state->scope,
4403                                   state->filter, state->attrs,
4404                                   state->attrsonly, 0, &state->entries,
4405                                   &state->pagedresults_cookie);
4406 
4407         if (rc != LDAP_SUCCESS)
4408                 DEBUG(5, ("Could not end search properly\n"));
4409 
4410         return;
4411 }
4412 
4413 static bool ldapuser2displayentry(struct ldap_search_state *state,
     /* [<][>][^][v][top][bottom][index][help] */
4414                                   TALLOC_CTX *mem_ctx,
4415                                   LDAP *ld, LDAPMessage *entry,
4416                                   struct samr_displayentry *result)
4417 {
4418         char **vals;
4419         size_t converted_size;
4420         DOM_SID sid;
4421         uint32 acct_flags;
4422 
4423         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4424         if ((vals == NULL) || (vals[0] == NULL)) {
4425                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4426                 return False;
4427         }
4428         acct_flags = pdb_decode_acct_ctrl(vals[0]);
4429         ldap_value_free(vals);
4430 
4431         if ((state->acct_flags != 0) &&
4432             ((state->acct_flags & acct_flags) == 0))
4433                 return False;           
4434 
4435         result->acct_flags = acct_flags;
4436         result->account_name = "";
4437         result->fullname = "";
4438         result->description = "";
4439 
4440         vals = ldap_get_values(ld, entry, "uid");
4441         if ((vals == NULL) || (vals[0] == NULL)) {
4442                 DEBUG(5, ("\"uid\" not found\n"));
4443                 return False;
4444         }
4445         if (!pull_utf8_talloc(mem_ctx,
4446                               CONST_DISCARD(char **, &result->account_name),
4447                               vals[0], &converted_size))
4448         {
4449                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4450                          strerror(errno)));
4451         }
4452 
4453         ldap_value_free(vals);
4454 
4455         vals = ldap_get_values(ld, entry, "displayName");
4456         if ((vals == NULL) || (vals[0] == NULL))
4457                 DEBUG(8, ("\"displayName\" not found\n"));
4458         else if (!pull_utf8_talloc(mem_ctx,
4459                                    CONST_DISCARD(char **, &result->fullname),
4460                                    vals[0], &converted_size))
4461         {
4462                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4463                          strerror(errno)));
4464         }
4465 
4466         ldap_value_free(vals);
4467 
4468         vals = ldap_get_values(ld, entry, "description");
4469         if ((vals == NULL) || (vals[0] == NULL))
4470                 DEBUG(8, ("\"description\" not found\n"));
4471         else if (!pull_utf8_talloc(mem_ctx,
4472                                    CONST_DISCARD(char **, &result->description),
4473                                    vals[0], &converted_size))
4474         {
4475                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4476                          strerror(errno)));
4477         }
4478 
4479         ldap_value_free(vals);
4480 
4481         if ((result->account_name == NULL) ||
4482             (result->fullname == NULL) ||
4483             (result->description == NULL)) {
4484                 DEBUG(0, ("talloc failed\n"));
4485                 return False;
4486         }
4487         
4488         vals = ldap_get_values(ld, entry, "sambaSid");
4489         if ((vals == NULL) || (vals[0] == NULL)) {
4490                 DEBUG(0, ("\"objectSid\" not found\n"));
4491                 return False;
4492         }
4493 
4494         if (!string_to_sid(&sid, vals[0])) {
4495                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4496                 ldap_value_free(vals);
4497                 return False;
4498         }
4499         ldap_value_free(vals);
4500 
4501         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4502                 DEBUG(0, ("sid %s does not belong to our domain\n",
4503                           sid_string_dbg(&sid)));
4504                 return False;
4505         }
4506 
4507         return True;
4508 }
4509 
4510 
4511 static bool ldapsam_search_users(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
4512                                  struct pdb_search *search,
4513                                  uint32 acct_flags)
4514 {
4515         struct ldapsam_privates *ldap_state =
4516                 (struct ldapsam_privates *)methods->private_data;
4517         struct ldap_search_state *state;
4518 
4519         state = talloc(search, struct ldap_search_state);
4520         if (state == NULL) {
4521                 DEBUG(0, ("talloc failed\n"));
4522                 return False;
4523         }
4524 
4525         state->connection = ldap_state->smbldap_state;
4526 
4527         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4528                 state->base = lp_ldap_user_suffix();
4529         else if ((acct_flags != 0) &&
4530                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4531                 state->base = lp_ldap_machine_suffix();
4532         else
4533                 state->base = lp_ldap_suffix();
4534 
4535         state->acct_flags = acct_flags;
4536         state->base = talloc_strdup(search, state->base);
4537         state->scope = LDAP_SCOPE_SUBTREE;
4538         state->filter = get_ldap_filter(search, "*");
4539         state->attrs = talloc_attrs(search, "uid", "sambaSid",
4540                                     "displayName", "description",
4541                                     "sambaAcctFlags", NULL);
4542         state->attrsonly = 0;
4543         state->pagedresults_cookie = NULL;
4544         state->entries = NULL;
4545         state->ldap2displayentry = ldapuser2displayentry;
4546 
4547         if ((state->filter == NULL) || (state->attrs == NULL)) {
4548                 DEBUG(0, ("talloc failed\n"));
4549                 return False;
4550         }
4551 
4552         search->private_data = state;
4553         search->next_entry = ldapsam_search_next_entry;
4554         search->search_end = ldapsam_search_end;
4555 
4556         return ldapsam_search_firstpage(search);
4557 }
4558 
4559 static bool ldapgroup2displayentry(struct ldap_search_state *state,
     /* [<][>][^][v][top][bottom][index][help] */
4560                                    TALLOC_CTX *mem_ctx,
4561                                    LDAP *ld, LDAPMessage *entry,
4562                                    struct samr_displayentry *result)
4563 {
4564         char **vals;
4565         size_t converted_size;
4566         DOM_SID sid;
4567         uint16 group_type;
4568 
4569         result->account_name = "";
4570         result->fullname = "";
4571         result->description = "";
4572 
4573 
4574         vals = ldap_get_values(ld, entry, "sambaGroupType");
4575         if ((vals == NULL) || (vals[0] == NULL)) {
4576                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4577                 if (vals != NULL) {
4578                         ldap_value_free(vals);
4579                 }
4580                 return False;
4581         }
4582 
4583         group_type = atoi(vals[0]);
4584 
4585         if ((state->group_type != 0) &&
4586             ((state->group_type != group_type))) {
4587                 ldap_value_free(vals);
4588                 return False;
4589         }
4590 
4591         ldap_value_free(vals);
4592 
4593         /* display name is the NT group name */
4594 
4595         vals = ldap_get_values(ld, entry, "displayName");
4596         if ((vals == NULL) || (vals[0] == NULL)) {
4597                 DEBUG(8, ("\"displayName\" not found\n"));
4598 
4599                 /* fallback to the 'cn' attribute */
4600                 vals = ldap_get_values(ld, entry, "cn");
4601                 if ((vals == NULL) || (vals[0] == NULL)) {
4602                         DEBUG(5, ("\"cn\" not found\n"));
4603                         return False;
4604                 }
4605                 if (!pull_utf8_talloc(mem_ctx,
4606                                       CONST_DISCARD(char **,
4607                                                     &result->account_name),
4608                                       vals[0], &converted_size))
4609                 {
4610                         DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4611                                   "failed: %s", strerror(errno)));
4612                 }
4613         }
4614         else if (!pull_utf8_talloc(mem_ctx,
4615                                    CONST_DISCARD(char **,
4616                                                  &result->account_name),
4617                                    vals[0], &converted_size))
4618         {
4619                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4620                           strerror(errno)));
4621         }
4622 
4623         ldap_value_free(vals);
4624 
4625         vals = ldap_get_values(ld, entry, "description");
4626         if ((vals == NULL) || (vals[0] == NULL))
4627                 DEBUG(8, ("\"description\" not found\n"));
4628         else if (!pull_utf8_talloc(mem_ctx,
4629                                    CONST_DISCARD(char **, &result->description),
4630                                    vals[0], &converted_size))
4631         {
4632                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4633                           strerror(errno)));
4634         }
4635         ldap_value_free(vals);
4636 
4637         if ((result->account_name == NULL) ||
4638             (result->fullname == NULL) ||
4639             (result->description == NULL)) {
4640                 DEBUG(0, ("talloc failed\n"));
4641                 return False;
4642         }
4643         
4644         vals = ldap_get_values(ld, entry, "sambaSid");
4645         if ((vals == NULL) || (vals[0] == NULL)) {
4646                 DEBUG(0, ("\"objectSid\" not found\n"));
4647                 if (vals != NULL) {
4648                         ldap_value_free(vals);
4649                 }
4650                 return False;
4651         }
4652 
4653         if (!string_to_sid(&sid, vals[0])) {
4654                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4655                 return False;
4656         }
4657 
4658         ldap_value_free(vals);
4659 
4660         switch (group_type) {
4661                 case SID_NAME_DOM_GRP:
4662                 case SID_NAME_ALIAS:
4663 
4664                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid) 
4665                                 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid)) 
4666                         {
4667                                 DEBUG(0, ("%s is not in our domain\n",
4668                                           sid_string_dbg(&sid)));
4669                                 return False;
4670                         }
4671                         break;
4672         
4673                 default:
4674                         DEBUG(0,("unkown group type: %d\n", group_type));
4675                         return False;
4676         }
4677 
4678         result->acct_flags = 0;
4679 
4680         return True;
4681 }
4682 
4683 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
4684                                      struct pdb_search *search,
4685                                      const DOM_SID *sid,
4686                                      enum lsa_SidType type)
4687 {
4688         struct ldapsam_privates *ldap_state =
4689                 (struct ldapsam_privates *)methods->private_data;
4690         struct ldap_search_state *state;
4691         fstring tmp;
4692 
4693         state = talloc(search, struct ldap_search_state);
4694         if (state == NULL) {
4695                 DEBUG(0, ("talloc failed\n"));
4696                 return False;
4697         }
4698 
4699         state->connection = ldap_state->smbldap_state;
4700 
4701         state->base = talloc_strdup(search, lp_ldap_suffix());
4702         state->connection = ldap_state->smbldap_state;
4703         state->scope = LDAP_SCOPE_SUBTREE;
4704         state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4705                                         "(sambaGroupType=%d)(sambaSID=%s*))",
4706                                          LDAP_OBJ_GROUPMAP,
4707                                          type, sid_to_fstring(tmp, sid));
4708         state->attrs = talloc_attrs(search, "cn", "sambaSid",
4709                                     "displayName", "description",
4710                                     "sambaGroupType", NULL);
4711         state->attrsonly = 0;
4712         state->pagedresults_cookie = NULL;
4713         state->entries = NULL;
4714         state->group_type = type;
4715         state->ldap2displayentry = ldapgroup2displayentry;
4716 
4717         if ((state->filter == NULL) || (state->attrs == NULL)) {
4718                 DEBUG(0, ("talloc failed\n"));
4719                 return False;
4720         }
4721 
4722         search->private_data = state;
4723         search->next_entry = ldapsam_search_next_entry;
4724         search->search_end = ldapsam_search_end;
4725 
4726         return ldapsam_search_firstpage(search);
4727 }
4728 
4729 static bool ldapsam_search_groups(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
4730                                   struct pdb_search *search)
4731 {
4732         return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4733 }
4734 
4735 static bool ldapsam_search_aliases(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
4736                                    struct pdb_search *search,
4737                                    const DOM_SID *sid)
4738 {
4739         return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4740 }
4741 
4742 static bool ldapsam_rid_algorithm(struct pdb_methods *methods)
     /* [<][>][^][v][top][bottom][index][help] */
4743 {
4744         return False;
4745 }
4746 
4747 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
     /* [<][>][^][v][top][bottom][index][help] */
4748                                     uint32 *rid)
4749 {
4750         struct smbldap_state *smbldap_state = priv->smbldap_state;
4751 
4752         LDAPMessage *result = NULL;
4753         LDAPMessage *entry = NULL;
4754         LDAPMod **mods = NULL;
4755         NTSTATUS status;
4756         char *value;
4757         int rc;
4758         uint32 nextRid = 0;
4759         const char *dn;
4760 
4761         TALLOC_CTX *mem_ctx;
4762 
4763         mem_ctx = talloc_new(NULL);
4764         if (mem_ctx == NULL) {
4765                 DEBUG(0, ("talloc_new failed\n"));
4766                 return NT_STATUS_NO_MEMORY;
4767         }
4768 
4769         status = smbldap_search_domain_info(smbldap_state, &result,
4770                                             get_global_sam_name(), False);
4771         if (!NT_STATUS_IS_OK(status)) {
4772                 DEBUG(3, ("Could not get domain info: %s\n",
4773                           nt_errstr(status)));
4774                 goto done;
4775         }
4776 
4777         talloc_autofree_ldapmsg(mem_ctx, result);
4778 
4779         entry = ldap_first_entry(priv2ld(priv), result);
4780         if (entry == NULL) {
4781                 DEBUG(0, ("Could not get domain info entry\n"));
4782                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4783                 goto done;
4784         }
4785 
4786         /* Find the largest of the three attributes "sambaNextRid",
4787            "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4788            concept of differentiating between user and group rids, and will
4789            use only "sambaNextRid" in the future. But for compatibility
4790            reasons I look if others have chosen different strategies -- VL */
4791 
4792         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4793                                                 "sambaNextRid", mem_ctx);
4794         if (value != NULL) {
4795                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4796                 nextRid = MAX(nextRid, tmp);
4797         }
4798 
4799         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4800                                                 "sambaNextUserRid", mem_ctx);
4801         if (value != NULL) {
4802                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4803                 nextRid = MAX(nextRid, tmp);
4804         }
4805 
4806         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4807                                                 "sambaNextGroupRid", mem_ctx);
4808         if (value != NULL) {
4809                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4810                 nextRid = MAX(nextRid, tmp);
4811         }
4812 
4813         if (nextRid == 0) {
4814                 nextRid = BASE_RID-1;
4815         }
4816 
4817         nextRid += 1;
4818 
4819         smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4820                          talloc_asprintf(mem_ctx, "%d", nextRid));
4821         talloc_autofree_ldapmod(mem_ctx, mods);
4822 
4823         if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4824                 status = NT_STATUS_NO_MEMORY;
4825                 goto done;
4826         }
4827 
4828         rc = smbldap_modify(smbldap_state, dn, mods);
4829 
4830         /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4831          * please retry" */
4832 
4833         status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4834 
4835  done:
4836         if (NT_STATUS_IS_OK(status)) {
4837                 *rid = nextRid;
4838         }
4839 
4840         TALLOC_FREE(mem_ctx);
4841         return status;
4842 }
4843 
4844 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32 *rid)
     /* [<][>][^][v][top][bottom][index][help] */
4845 {
4846         int i;
4847 
4848         for (i=0; i<10; i++) {
4849                 NTSTATUS result = ldapsam_get_new_rid(
4850                         (struct ldapsam_privates *)methods->private_data, rid);
4851                 if (NT_STATUS_IS_OK(result)) {
4852                         return result;
4853                 }
4854 
4855                 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4856                         return result;
4857                 }
4858 
4859                 /* The ldap update failed (maybe a race condition), retry */
4860         }
4861 
4862         /* Tried 10 times, fail. */
4863         return NT_STATUS_ACCESS_DENIED;
4864 }
4865 
4866 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
     /* [<][>][^][v][top][bottom][index][help] */
4867 {
4868         NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4869         return NT_STATUS_IS_OK(result) ? True : False;
4870 }
4871 
4872 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
4873                               const DOM_SID *sid,
4874                               union unid_t *id, enum lsa_SidType *type)
4875 {
4876         struct ldapsam_privates *priv =
4877                 (struct ldapsam_privates *)methods->private_data;
4878         char *filter;
4879         const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4880                                 NULL };
4881         LDAPMessage *result = NULL;
4882         LDAPMessage *entry = NULL;
4883         bool ret = False;
4884         char *value;
4885         int rc;
4886 
4887         TALLOC_CTX *mem_ctx;
4888 
4889         mem_ctx = talloc_new(NULL);
4890         if (mem_ctx == NULL) {
4891                 DEBUG(0, ("talloc_new failed\n"));
4892                 return False;
4893         }
4894 
4895         filter = talloc_asprintf(mem_ctx,
4896                                  "(&(sambaSid=%s)"
4897                                  "(|(objectClass=%s)(objectClass=%s)))",
4898                                  sid_string_talloc(mem_ctx, sid),
4899                                  LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4900         if (filter == NULL) {
4901                 DEBUG(5, ("talloc_asprintf failed\n"));
4902                 goto done;
4903         }
4904 
4905         rc = smbldap_search_suffix(priv->smbldap_state, filter,
4906                                    attrs, &result);
4907         if (rc != LDAP_SUCCESS) {
4908                 goto done;
4909         }
4910         talloc_autofree_ldapmsg(mem_ctx, result);
4911 
4912         if (ldap_count_entries(priv2ld(priv), result) != 1) {
4913                 DEBUG(10, ("Got %d entries, expected one\n",
4914                            ldap_count_entries(priv2ld(priv), result)));
4915                 goto done;
4916         }
4917 
4918         entry = ldap_first_entry(priv2ld(priv), result);
4919 
4920         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4921                                                 "sambaGroupType", mem_ctx);
4922 
4923         if (value != NULL) {
4924                 const char *gid_str;
4925                 /* It's a group */
4926 
4927                 gid_str = smbldap_talloc_single_attribute(
4928                         priv2ld(priv), entry, "gidNumber", mem_ctx);
4929                 if (gid_str == NULL) {
4930                         DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4931                                   smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4932                                                     entry)));
4933                         goto done;
4934                 }
4935 
4936                 id->gid = strtoul(gid_str, NULL, 10);
4937                 *type = (enum lsa_SidType)strtoul(value, NULL, 10);
4938                 ret = True;
4939                 goto done;
4940         }
4941 
4942         /* It must be a user */
4943 
4944         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4945                                                 "uidNumber", mem_ctx);
4946         if (value == NULL) {
4947                 DEBUG(1, ("Could not find uidNumber in %s\n",
4948                           smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4949                 goto done;
4950         }
4951 
4952         id->uid = strtoul(value, NULL, 10);
4953         *type = SID_NAME_USER;
4954 
4955         ret = True;
4956  done:
4957         TALLOC_FREE(mem_ctx);
4958         return ret;
4959 }
4960 
4961 /*
4962  * The following functions is called only if
4963  * ldapsam:trusted and ldapsam:editposix are
4964  * set to true
4965  */
4966 
4967 /*
4968  * ldapsam_create_user creates a new
4969  * posixAccount and sambaSamAccount object
4970  * in the ldap users subtree
4971  *
4972  * The uid is allocated by winbindd.
4973  */
4974 
4975 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
4976                                     TALLOC_CTX *tmp_ctx, const char *name,
4977                                     uint32 acb_info, uint32 *rid)
4978 {
4979         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
4980         LDAPMessage *entry = NULL;
4981         LDAPMessage *result = NULL;
4982         uint32 num_result;
4983         bool is_machine = False;
4984         bool add_posix = False;
4985         LDAPMod **mods = NULL;
4986         struct samu *user;
4987         char *filter;
4988         char *username;
4989         char *homedir;
4990         char *gidstr;
4991         char *uidstr;
4992         char *shell;
4993         const char *dn = NULL;
4994         DOM_SID group_sid;
4995         DOM_SID user_sid;
4996         gid_t gid = -1;
4997         uid_t uid = -1;
4998         NTSTATUS ret;
4999         int rc;
5000         
5001         if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5002               acb_info & ACB_WSTRUST ||
5003               acb_info & ACB_SVRTRUST ||
5004               acb_info & ACB_DOMTRUST) {
5005                 is_machine = True;
5006         }
5007 
5008         username = escape_ldap_string_alloc(name);
5009         filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5010                                  username, LDAP_OBJ_POSIXACCOUNT);
5011         SAFE_FREE(username);
5012 
5013         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5014         if (rc != LDAP_SUCCESS) {
5015                 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5016                 return NT_STATUS_ACCESS_DENIED;
5017         }
5018         talloc_autofree_ldapmsg(tmp_ctx, result);
5019 
5020         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5021 
5022         if (num_result > 1) {
5023                 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5024                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5025         }
5026         
5027         if (num_result == 1) {
5028                 char *tmp;
5029                 /* check if it is just a posix account.
5030                  * or if there is a sid attached to this entry
5031                  */
5032 
5033                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5034                 if (!entry) {
5035                         return NT_STATUS_UNSUCCESSFUL;
5036                 }
5037 
5038                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5039                 if (tmp) {
5040                         DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5041                         return NT_STATUS_USER_EXISTS;
5042                 }
5043 
5044                 /* it is just a posix account, retrieve the dn for later use */
5045                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5046                 if (!dn) {
5047                         DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5048                         return NT_STATUS_NO_MEMORY;
5049                 }
5050         }
5051 
5052         if (num_result == 0) {
5053                 add_posix = True;
5054         }
5055         
5056         /* Create the basic samu structure and generate the mods for the ldap commit */
5057         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5058                 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5059                 return ret;
5060         }
5061 
5062         sid_compose(&user_sid, get_global_sam_sid(), *rid);
5063 
5064         user = samu_new(tmp_ctx);
5065         if (!user) {
5066                 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5067                 return NT_STATUS_NO_MEMORY;
5068         }
5069 
5070         if (!pdb_set_username(user, name, PDB_SET)) {
5071                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5072                 return NT_STATUS_UNSUCCESSFUL;
5073         }
5074         if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5075                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5076                 return NT_STATUS_UNSUCCESSFUL;
5077         }
5078         if (is_machine) {
5079                 if (acb_info & ACB_NORMAL) {
5080                         if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5081                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5082                                 return NT_STATUS_UNSUCCESSFUL;
5083                         }
5084                 } else {
5085                         if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5086                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5087                                 return NT_STATUS_UNSUCCESSFUL;
5088                         }
5089                 }
5090         } else {
5091                 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5092                         DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5093                         return NT_STATUS_UNSUCCESSFUL;
5094                 }
5095         }
5096 
5097         if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5098                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5099                 return NT_STATUS_UNSUCCESSFUL;
5100         }
5101 
5102         if (!init_ldap_from_sam(ldap_state, NULL, &mods, user, element_is_set_or_changed)) {
5103                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5104                 return NT_STATUS_UNSUCCESSFUL;
5105         }
5106 
5107         if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5108                 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5109         }
5110         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5111 
5112         if (add_posix) {
5113                 char *escape_name;
5114 
5115                 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5116 
5117                 /* retrieve the Domain Users group gid */
5118                 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_GROUP_RID_USERS) ||
5119                     !sid_to_gid(&group_sid, &gid)) {
5120                         DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5121                         return NT_STATUS_INVALID_PRIMARY_GROUP;
5122                 }
5123 
5124                 /* lets allocate a new userid for this user */
5125                 if (!winbind_allocate_uid(&uid)) {
5126                         DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5127                         return NT_STATUS_UNSUCCESSFUL;
5128                 }
5129 
5130 
5131                 if (is_machine) {
5132                         /* TODO: choose a more appropriate default for machines */
5133                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5134                         shell = talloc_strdup(tmp_ctx, "/bin/false");
5135                 } else {
5136                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5137                         shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5138                 }
5139                 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5140                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5141 
5142                 escape_name = escape_rdn_val_string_alloc(name);
5143                 if (!escape_name) {
5144                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5145                         return NT_STATUS_NO_MEMORY;
5146                 }
5147 
5148                 if (is_machine) {
5149                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix ());
5150                 } else {
5151                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix ());
5152                 }
5153 
5154                 SAFE_FREE(escape_name);
5155 
5156                 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5157                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5158                         return NT_STATUS_NO_MEMORY;
5159                 }
5160 
5161                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5162                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5163                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5164                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5165                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5166                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5167                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5168         }
5169 
5170         talloc_autofree_ldapmod(tmp_ctx, mods);
5171 
5172         if (add_posix) {        
5173                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5174         } else {
5175                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5176         }       
5177 
5178         if (rc != LDAP_SUCCESS) {
5179                 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5180                 return NT_STATUS_UNSUCCESSFUL;
5181         }
5182 
5183         DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5184 
5185         flush_pwnam_cache();
5186 
5187         return NT_STATUS_OK;
5188 }
5189 
5190 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5191                                      TALLOC_CTX *tmp_ctx,
5192                                      uint32 group_rid,
5193                                      uint32 member_rid);
5194 
5195 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
5196                                                TALLOC_CTX *mem_ctx,
5197                                                struct samu *user,
5198                                                DOM_SID **pp_sids,
5199                                                gid_t **pp_gids,
5200                                                size_t *p_num_groups);
5201 
5202 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
     /* [<][>][^][v][top][bottom][index][help] */
5203 {
5204         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5205         LDAPMessage *result = NULL;
5206         LDAPMessage *entry = NULL;
5207         int num_result;
5208         const char *dn;
5209         char *filter;
5210         int rc;
5211 
5212         DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5213         
5214         filter = talloc_asprintf(tmp_ctx,
5215                                  "(&(uid=%s)"
5216                                  "(objectClass=%s)"
5217                                  "(objectClass=%s))",
5218                                  pdb_get_username(sam_acct),
5219                                  LDAP_OBJ_POSIXACCOUNT,
5220                                  LDAP_OBJ_SAMBASAMACCOUNT);
5221         if (filter == NULL) {
5222                 return NT_STATUS_NO_MEMORY;
5223         }
5224 
5225         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5226         if (rc != LDAP_SUCCESS) {
5227                 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5228                 return NT_STATUS_UNSUCCESSFUL;
5229         }
5230         talloc_autofree_ldapmsg(tmp_ctx, result);
5231 
5232         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5233 
5234         if (num_result == 0) {
5235                 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5236                 return NT_STATUS_NO_SUCH_USER;
5237         }
5238 
5239         if (num_result > 1) {
5240                 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5241                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5242         }
5243 
5244         entry = ldap_first_entry(priv2ld(ldap_state), result);
5245         if (!entry) {
5246                 return NT_STATUS_UNSUCCESSFUL;
5247         }
5248 
5249         /* it is just a posix account, retrieve the dn for later use */
5250         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5251         if (!dn) {
5252                 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5253                 return NT_STATUS_NO_MEMORY;
5254         }
5255 
5256         /* try to remove memberships first */
5257         {
5258                 NTSTATUS status;
5259                 struct dom_sid *sids = NULL;
5260                 gid_t *gids = NULL;
5261                 size_t num_groups = 0;
5262                 int i;
5263                 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5264 
5265                 status = ldapsam_enum_group_memberships(my_methods,
5266                                                         tmp_ctx,
5267                                                         sam_acct,
5268                                                         &sids,
5269                                                         &gids,
5270                                                         &num_groups);
5271                 if (!NT_STATUS_IS_OK(status)) {
5272                         goto delete_dn;
5273                 }
5274 
5275                 for (i=0; i < num_groups; i++) {
5276 
5277                         uint32_t group_rid;
5278 
5279                         sid_peek_rid(&sids[i], &group_rid);
5280 
5281                         ldapsam_del_groupmem(my_methods,
5282                                              tmp_ctx,
5283                                              group_rid,
5284                                              user_rid);
5285                 }
5286         }
5287 
5288  delete_dn:
5289 
5290         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5291         if (rc != LDAP_SUCCESS) {
5292                 return NT_STATUS_UNSUCCESSFUL;
5293         }
5294 
5295         flush_pwnam_cache();
5296 
5297         return NT_STATUS_OK;
5298 }
5299 
5300 /*
5301  * ldapsam_create_group creates a new
5302  * posixGroup and sambaGroupMapping object
5303  * in the ldap groups subtree
5304  *
5305  * The gid is allocated by winbindd.
5306  */
5307 
5308 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
5309                                          TALLOC_CTX *tmp_ctx,
5310                                          const char *name,
5311                                          uint32 *rid)
5312 {
5313         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5314         NTSTATUS ret;
5315         LDAPMessage *entry = NULL;
5316         LDAPMessage *result = NULL;
5317         uint32 num_result;
5318         bool is_new_entry = False;
5319         LDAPMod **mods = NULL;
5320         char *filter;
5321         char *groupsidstr;
5322         char *groupname;
5323         char *grouptype;
5324         char *gidstr;
5325         const char *dn = NULL;
5326         DOM_SID group_sid;
5327         gid_t gid = -1;
5328         int rc;
5329         
5330         groupname = escape_ldap_string_alloc(name);
5331         filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5332                                  groupname, LDAP_OBJ_POSIXGROUP);
5333         SAFE_FREE(groupname);
5334 
5335         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5336         if (rc != LDAP_SUCCESS) {
5337                 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5338                 return NT_STATUS_UNSUCCESSFUL;
5339         }
5340         talloc_autofree_ldapmsg(tmp_ctx, result);
5341 
5342         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5343 
5344         if (num_result > 1) {
5345                 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5346                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5347         }
5348         
5349         if (num_result == 1) {
5350                 char *tmp;
5351                 /* check if it is just a posix group.
5352                  * or if there is a sid attached to this entry
5353                  */
5354 
5355                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5356                 if (!entry) {
5357                         return NT_STATUS_UNSUCCESSFUL;
5358                 }
5359 
5360                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5361                 if (tmp) {
5362                         DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5363                         return NT_STATUS_GROUP_EXISTS;
5364                 }
5365 
5366                 /* it is just a posix group, retrieve the gid and the dn for later use */
5367                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5368                 if (!tmp) {
5369                         DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5370                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5371                 }
5372                 
5373                 gid = strtoul(tmp, NULL, 10);
5374 
5375                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5376                 if (!dn) {
5377                         DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5378                         return NT_STATUS_NO_MEMORY;
5379                 }
5380         }
5381 
5382         if (num_result == 0) {
5383                 char *escape_name;
5384 
5385                 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5386 
5387                 is_new_entry = True;
5388         
5389                 /* lets allocate a new groupid for this group */
5390                 if (!winbind_allocate_gid(&gid)) {
5391                         DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5392                         return NT_STATUS_UNSUCCESSFUL;
5393                 }
5394 
5395                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5396 
5397                 escape_name = escape_rdn_val_string_alloc(name);
5398                 if (!escape_name) {
5399                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5400                         return NT_STATUS_NO_MEMORY;
5401                 }
5402 
5403                 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix());
5404 
5405                 SAFE_FREE(escape_name);
5406 
5407                 if (!gidstr || !dn) {
5408                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5409                         return NT_STATUS_NO_MEMORY;
5410                 }
5411 
5412                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5413                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5414                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5415         }
5416 
5417         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5418                 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5419                 return ret;
5420         }
5421 
5422         sid_compose(&group_sid, get_global_sam_sid(), *rid);
5423 
5424         groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5425                                                                &group_sid));
5426         grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5427 
5428         if (!groupsidstr || !grouptype) {
5429                 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5430                 return NT_STATUS_NO_MEMORY;
5431         }
5432 
5433         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5434         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5435         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5436         smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5437         talloc_autofree_ldapmod(tmp_ctx, mods);
5438 
5439         if (is_new_entry) {     
5440                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5441 #if 0
5442                 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5443                         /* This call may fail with rfc2307bis schema */
5444                         /* Retry adding a structural class */
5445                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5446                         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5447                 }
5448 #endif
5449         } else {
5450                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5451         }       
5452 
5453         if (rc != LDAP_SUCCESS) {
5454                 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5455                 return NT_STATUS_UNSUCCESSFUL;
5456         }
5457 
5458         DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5459 
5460         return NT_STATUS_OK;
5461 }
5462 
5463 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32 rid)
     /* [<][>][^][v][top][bottom][index][help] */
5464 {
5465         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5466         LDAPMessage *result = NULL;
5467         LDAPMessage *entry = NULL;
5468         int num_result;
5469         const char *dn;
5470         char *gidstr;
5471         char *filter;
5472         DOM_SID group_sid;
5473         int rc;
5474 
5475         /* get the group sid */
5476         sid_compose(&group_sid, get_global_sam_sid(), rid);
5477 
5478         filter = talloc_asprintf(tmp_ctx,
5479                                  "(&(sambaSID=%s)"
5480                                  "(objectClass=%s)"
5481                                  "(objectClass=%s))",
5482                                  sid_string_talloc(tmp_ctx, &group_sid),
5483                                  LDAP_OBJ_POSIXGROUP,
5484                                  LDAP_OBJ_GROUPMAP);
5485         if (filter == NULL) {
5486                 return NT_STATUS_NO_MEMORY;
5487         }
5488 
5489         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5490         if (rc != LDAP_SUCCESS) {
5491                 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5492                 return NT_STATUS_UNSUCCESSFUL;
5493         }
5494         talloc_autofree_ldapmsg(tmp_ctx, result);
5495 
5496         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5497 
5498         if (num_result == 0) {
5499                 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5500                 return NT_STATUS_NO_SUCH_GROUP;
5501         }
5502 
5503         if (num_result > 1) {
5504                 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5505                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5506         }
5507 
5508         entry = ldap_first_entry(priv2ld(ldap_state), result);
5509         if (!entry) {
5510                 return NT_STATUS_UNSUCCESSFUL;
5511         }
5512 
5513         /* here it is, retrieve the dn for later use */
5514         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5515         if (!dn) {
5516                 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5517                 return NT_STATUS_NO_MEMORY;
5518         }
5519 
5520         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5521         if (!gidstr) {
5522                 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5523                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5524         }
5525 
5526         /* check no user have this group marked as primary group */
5527         filter = talloc_asprintf(tmp_ctx,
5528                                  "(&(gidNumber=%s)"
5529                                  "(objectClass=%s)"
5530                                  "(objectClass=%s))",
5531                                  gidstr,
5532                                  LDAP_OBJ_POSIXACCOUNT,
5533                                  LDAP_OBJ_SAMBASAMACCOUNT);
5534 
5535         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5536         if (rc != LDAP_SUCCESS) {
5537                 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5538                 return NT_STATUS_UNSUCCESSFUL;
5539         }
5540         talloc_autofree_ldapmsg(tmp_ctx, result);
5541 
5542         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5543 
5544         if (num_result != 0) {
5545                 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5546                 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5547         }
5548 
5549         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5550         if (rc != LDAP_SUCCESS) {
5551                 return NT_STATUS_UNSUCCESSFUL;
5552         }
5553 
5554         return NT_STATUS_OK;
5555 }
5556 
5557 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
5558                                         TALLOC_CTX *tmp_ctx,
5559                                         uint32 group_rid,
5560                                         uint32 member_rid,
5561                                         int modop)
5562 {
5563         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5564         LDAPMessage *entry = NULL;
5565         LDAPMessage *result = NULL;
5566         uint32 num_result;
5567         LDAPMod **mods = NULL;
5568         char *filter;
5569         char *uidstr;
5570         const char *dn = NULL;
5571         DOM_SID group_sid;
5572         DOM_SID member_sid;
5573         int rc;
5574 
5575         switch (modop) {
5576         case LDAP_MOD_ADD:
5577                 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5578                 break;
5579         case LDAP_MOD_DELETE:
5580                 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5581                 break;
5582         default:
5583                 return NT_STATUS_UNSUCCESSFUL;
5584         }
5585         
5586         /* get member sid  */
5587         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5588 
5589         /* get the group sid */
5590         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5591 
5592         filter = talloc_asprintf(tmp_ctx,
5593                                  "(&(sambaSID=%s)"
5594                                  "(objectClass=%s)"
5595                                  "(objectClass=%s))",
5596                                  sid_string_talloc(tmp_ctx, &member_sid),
5597                                  LDAP_OBJ_POSIXACCOUNT,
5598                                  LDAP_OBJ_SAMBASAMACCOUNT);
5599         if (filter == NULL) {
5600                 return NT_STATUS_NO_MEMORY;
5601         }
5602 
5603         /* get the member uid */
5604         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5605         if (rc != LDAP_SUCCESS) {
5606                 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5607                 return NT_STATUS_UNSUCCESSFUL;
5608         }
5609         talloc_autofree_ldapmsg(tmp_ctx, result);
5610 
5611         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5612 
5613         if (num_result == 0) {
5614                 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5615                 return NT_STATUS_NO_SUCH_MEMBER;
5616         }
5617 
5618         if (num_result > 1) {
5619                 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5620                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5621         }
5622 
5623         entry = ldap_first_entry(priv2ld(ldap_state), result);
5624         if (!entry) {
5625                 return NT_STATUS_UNSUCCESSFUL;
5626         }
5627 
5628         if (modop == LDAP_MOD_DELETE) {
5629                 /* check if we are trying to remove the member from his primary group */
5630                 char *gidstr;
5631                 gid_t user_gid, group_gid;
5632                 
5633                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5634                 if (!gidstr) {
5635                         DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5636                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5637                 }
5638 
5639                 user_gid = strtoul(gidstr, NULL, 10);
5640         
5641                 if (!sid_to_gid(&group_sid, &group_gid)) {
5642                         DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5643                         return NT_STATUS_UNSUCCESSFUL;
5644                 }
5645 
5646                 if (user_gid == group_gid) {
5647                         DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5648                         return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5649                 }
5650         }
5651 
5652         /* here it is, retrieve the uid for later use */
5653         uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5654         if (!uidstr) {
5655                 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5656                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5657         }
5658 
5659         filter = talloc_asprintf(tmp_ctx,
5660                                  "(&(sambaSID=%s)"
5661                                  "(objectClass=%s)"
5662                                  "(objectClass=%s))",
5663                                  sid_string_talloc(tmp_ctx, &group_sid),
5664                                  LDAP_OBJ_POSIXGROUP,
5665                                  LDAP_OBJ_GROUPMAP);
5666 
5667         /* get the group */
5668         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5669         if (rc != LDAP_SUCCESS) {
5670                 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5671                 return NT_STATUS_UNSUCCESSFUL;
5672         }
5673         talloc_autofree_ldapmsg(tmp_ctx, result);
5674 
5675         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5676 
5677         if (num_result == 0) {
5678                 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5679                 return NT_STATUS_NO_SUCH_GROUP;
5680         }
5681 
5682         if (num_result > 1) {
5683                 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5684                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5685         }
5686 
5687         entry = ldap_first_entry(priv2ld(ldap_state), result);
5688         if (!entry) {
5689                 return NT_STATUS_UNSUCCESSFUL;
5690         }
5691 
5692         /* here it is, retrieve the dn for later use */
5693         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5694         if (!dn) {
5695                 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5696                 return NT_STATUS_NO_MEMORY;
5697         }
5698 
5699         smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5700 
5701         talloc_autofree_ldapmod(tmp_ctx, mods);
5702 
5703         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5704         if (rc != LDAP_SUCCESS) {
5705                 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5706                         DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5707                         return NT_STATUS_MEMBER_IN_GROUP;
5708                 }
5709                 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5710                         DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5711                         return NT_STATUS_MEMBER_NOT_IN_GROUP;
5712                 }
5713                 return NT_STATUS_UNSUCCESSFUL;
5714         }
5715         
5716         return NT_STATUS_OK;
5717 }
5718 
5719 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
5720                                      TALLOC_CTX *tmp_ctx,
5721                                      uint32 group_rid,
5722                                      uint32 member_rid)
5723 {
5724         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5725 }
5726 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
5727                                      TALLOC_CTX *tmp_ctx,
5728                                      uint32 group_rid,
5729                                      uint32 member_rid)
5730 {
5731         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5732 }
5733 
5734 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
     /* [<][>][^][v][top][bottom][index][help] */
5735                                           TALLOC_CTX *mem_ctx,
5736                                           struct samu *sampass)
5737 {
5738         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5739         LDAPMessage *entry = NULL;
5740         LDAPMessage *result = NULL;
5741         uint32 num_result;
5742         LDAPMod **mods = NULL;
5743         char *filter;
5744         char *escape_username;
5745         char *gidstr;
5746         const char *dn = NULL;
5747         gid_t gid;
5748         int rc;
5749 
5750         DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5751 
5752         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5753                 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5754                 return NT_STATUS_UNSUCCESSFUL;
5755         }
5756         gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5757         if (!gidstr) {
5758                 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5759                 return NT_STATUS_NO_MEMORY;
5760         }
5761 
5762         escape_username = escape_ldap_string_alloc(pdb_get_username(sampass));
5763         if (escape_username== NULL) {
5764                 return NT_STATUS_NO_MEMORY;
5765         }
5766 
5767         filter = talloc_asprintf(mem_ctx,
5768                                  "(&(uid=%s)"
5769                                  "(objectClass=%s)"
5770                                  "(objectClass=%s))",
5771                                  escape_username,
5772                                  LDAP_OBJ_POSIXACCOUNT,
5773                                  LDAP_OBJ_SAMBASAMACCOUNT);
5774 
5775         SAFE_FREE(escape_username);
5776 
5777         if (filter == NULL) {
5778                 return NT_STATUS_NO_MEMORY;
5779         }
5780 
5781         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5782         if (rc != LDAP_SUCCESS) {
5783                 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5784                 return NT_STATUS_UNSUCCESSFUL;
5785         }
5786         talloc_autofree_ldapmsg(mem_ctx, result);
5787 
5788         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5789 
5790         if (num_result == 0) {
5791                 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5792                 return NT_STATUS_NO_SUCH_USER;
5793         }
5794 
5795         if (num_result > 1) {
5796                 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5797                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5798         }
5799 
5800         entry = ldap_first_entry(priv2ld(ldap_state), result);
5801         if (!entry) {
5802                 return NT_STATUS_UNSUCCESSFUL;
5803         }
5804 
5805         /* retrieve the dn for later use */
5806         dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
5807         if (!dn) {
5808                 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
5809                 return NT_STATUS_NO_MEMORY;
5810         }
5811 
5812         /* remove the old one, and add the new one, this way we do not risk races */
5813         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
5814 
5815         if (mods == NULL) {
5816                 return NT_STATUS_OK;
5817         }
5818 
5819         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5820 
5821         if (rc != LDAP_SUCCESS) {
5822                 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
5823                          pdb_get_username(sampass), gidstr));
5824                 return NT_STATUS_UNSUCCESSFUL;
5825         }
5826 
5827         flush_pwnam_cache();
5828 
5829         return NT_STATUS_OK;
5830 }
5831 
5832 
5833 /**********************************************************************
5834  trusted domains functions
5835  *********************************************************************/
5836 
5837 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
5838                            const char *domain)
5839 {
5840         return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
5841                                ldap_state->domain_dn);
5842 }
5843 
5844 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
     /* [<][>][^][v][top][bottom][index][help] */
5845                                   TALLOC_CTX *mem_ctx,
5846                                   const char *domain, LDAPMessage **entry)
5847 {
5848         int rc;
5849         char *filter;
5850         int scope = LDAP_SCOPE_SUBTREE;
5851         const char **attrs = NULL; /* NULL: get all attrs */
5852         int attrsonly = 0; /* 0: return values too */
5853         LDAPMessage *result = NULL;
5854         char *trusted_dn;
5855         uint32 num_result;
5856 
5857         filter = talloc_asprintf(talloc_tos(),
5858                                  "(&(objectClass=%s)(sambaDomainName=%s))",
5859                                  LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
5860 
5861         trusted_dn = trusteddom_dn(ldap_state, domain);
5862         if (trusted_dn == NULL) {
5863                 return False;
5864         }
5865         rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
5866                             filter, attrs, attrsonly, &result);
5867 
5868         if (result != NULL) {
5869                 talloc_autofree_ldapmsg(mem_ctx, result);
5870         }
5871 
5872         if (rc == LDAP_NO_SUCH_OBJECT) {
5873                 *entry = NULL;
5874                 return True;
5875         }
5876 
5877         if (rc != LDAP_SUCCESS) {
5878                 return False;
5879         }
5880 
5881         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5882 
5883         if (num_result > 1) {
5884                 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
5885                           "%s object for domain '%s'?!\n",
5886                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
5887                 return False;
5888         }
5889 
5890         if (num_result == 0) {
5891                 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
5892                           "%s object for domain %s.\n",
5893                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
5894                 *entry = NULL;
5895         } else {
5896                 *entry = ldap_first_entry(priv2ld(ldap_state), result);
5897         }
5898 
5899         return True;
5900 }
5901 
5902 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
5903                                       const char *domain,
5904                                       char** pwd,
5905                                       DOM_SID *sid,
5906                                       time_t *pass_last_set_time)
5907 {
5908         struct ldapsam_privates *ldap_state =
5909                 (struct ldapsam_privates *)methods->private_data;
5910         LDAPMessage *entry = NULL;
5911 
5912         DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
5913 
5914         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
5915             (entry == NULL))
5916         {
5917                 return False;
5918         }
5919 
5920         /* password */
5921         if (pwd != NULL) {
5922                 char *pwd_str;
5923                 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5924                                 entry, "sambaClearTextPassword", talloc_tos());
5925                 if (pwd_str == NULL) {
5926                         return False;
5927                 }
5928                 /* trusteddom_pw routines do not use talloc yet... */
5929                 *pwd = SMB_STRDUP(pwd_str);
5930                 if (*pwd == NULL) {
5931                         return False;
5932                 }
5933         }
5934 
5935         /* last change time */
5936         if (pass_last_set_time != NULL) {
5937                 char *time_str;
5938                 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5939                                 entry, "sambaPwdLastSet", talloc_tos());
5940                 if (time_str == NULL) {
5941                         return False;
5942                 }
5943                 *pass_last_set_time = (time_t)atol(time_str);
5944         }
5945 
5946         /* domain sid */
5947         if (sid != NULL) {
5948                 char *sid_str;
5949                 DOM_SID *dom_sid;
5950                 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5951                                                           entry, "sambaSID",
5952                                                           talloc_tos());
5953                 if (sid_str == NULL) {
5954                         return False;
5955                 }
5956                 dom_sid = string_sid_talloc(talloc_tos(), sid_str);
5957                 if (dom_sid == NULL) {
5958                         return False;
5959                 }
5960                 sid_copy(sid, dom_sid);
5961         }
5962 
5963         return True;
5964 }
5965 
5966 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
5967                                       const char* domain,
5968                                       const char* pwd,
5969                                       const DOM_SID *sid)
5970 {
5971         struct ldapsam_privates *ldap_state =
5972                 (struct ldapsam_privates *)methods->private_data;
5973         LDAPMessage *entry = NULL;
5974         LDAPMod **mods = NULL;
5975         char *prev_pwd = NULL;
5976         char *trusted_dn = NULL;
5977         int rc;
5978 
5979         DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
5980 
5981         /*
5982          * get the current entry (if there is one) in order to put the
5983          * current password into the previous password attribute
5984          */
5985         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
5986                 return False;
5987         }
5988 
5989         mods = NULL;
5990         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
5991                          LDAP_OBJ_TRUSTDOM_PASSWORD);
5992         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
5993                          domain);
5994         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
5995                          sid_string_tos(sid));
5996         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
5997                          talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
5998         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
5999                          "sambaClearTextPassword", pwd);
6000 
6001         talloc_autofree_ldapmod(talloc_tos(), mods);
6002 
6003         if (entry != NULL) {
6004                 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6005                                 entry, "sambaClearTextPassword", talloc_tos());
6006                 if (prev_pwd != NULL) {
6007                         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6008                                          "sambaPreviousClearTextPassword",
6009                                          prev_pwd);
6010                 }
6011         }
6012 
6013         trusted_dn = trusteddom_dn(ldap_state, domain);
6014         if (trusted_dn == NULL) {
6015                 return False;
6016         }
6017         if (entry == NULL) {
6018                 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6019         } else {
6020                 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6021         }
6022 
6023         if (rc != LDAP_SUCCESS) {
6024                 DEBUG(1, ("error writing trusted domain password!\n"));
6025                 return False;
6026         }
6027 
6028         return True;
6029 }
6030 
6031 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
6032                                       const char *domain)
6033 {
6034         int rc;
6035         struct ldapsam_privates *ldap_state =
6036                 (struct ldapsam_privates *)methods->private_data;
6037         LDAPMessage *entry = NULL;
6038         const char *trusted_dn;
6039 
6040         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6041                 return False;
6042         }
6043 
6044         if (entry == NULL) {
6045                 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6046                           "%s\n", domain));
6047                 return True;
6048         }
6049 
6050         trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6051                                        entry);
6052         if (trusted_dn == NULL) {
6053                 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6054                 return False;
6055         }
6056 
6057         rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6058         if (rc != LDAP_SUCCESS) {
6059                 return False;
6060         }
6061 
6062         return True;
6063 }
6064 
6065 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
     /* [<][>][^][v][top][bottom][index][help] */
6066                                          TALLOC_CTX *mem_ctx,
6067                                          uint32 *num_domains,
6068                                          struct trustdom_info ***domains)
6069 {
6070         int rc;
6071         struct ldapsam_privates *ldap_state =
6072                 (struct ldapsam_privates *)methods->private_data;
6073         char *filter;
6074         int scope = LDAP_SCOPE_SUBTREE;
6075         const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6076         int attrsonly = 0; /* 0: return values too */
6077         LDAPMessage *result = NULL;
6078         LDAPMessage *entry = NULL;
6079 
6080         filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6081                                  LDAP_OBJ_TRUSTDOM_PASSWORD);
6082 
6083         rc = smbldap_search(ldap_state->smbldap_state,
6084                             ldap_state->domain_dn,
6085                             scope,
6086                             filter,
6087                             attrs,
6088                             attrsonly,
6089                             &result);
6090 
6091         if (result != NULL) {
6092                 talloc_autofree_ldapmsg(mem_ctx, result);
6093         }
6094 
6095         if (rc != LDAP_SUCCESS) {
6096                 return NT_STATUS_UNSUCCESSFUL;
6097         }
6098 
6099         *num_domains = 0;
6100         if (!(*domains = TALLOC_ARRAY(mem_ctx, struct trustdom_info *, 1))) {
6101                 DEBUG(1, ("talloc failed\n"));
6102                 return NT_STATUS_NO_MEMORY;
6103         }
6104 
6105         for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6106              entry != NULL;
6107              entry = ldap_next_entry(priv2ld(ldap_state), entry))
6108         {
6109                 char *dom_name, *dom_sid_str;
6110                 struct trustdom_info *dom_info;
6111 
6112                 dom_info = TALLOC_P(*domains, struct trustdom_info);
6113                 if (dom_info == NULL) {
6114                         DEBUG(1, ("talloc failed\n"));
6115                         return NT_STATUS_NO_MEMORY;
6116                 }
6117 
6118                 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6119                                                            entry,
6120                                                            "sambaDomainName",
6121                                                            talloc_tos());
6122                 if (dom_name == NULL) {
6123                         DEBUG(1, ("talloc failed\n"));
6124                         return NT_STATUS_NO_MEMORY;
6125                 }
6126                 dom_info->name = dom_name;
6127 
6128                 dom_sid_str = smbldap_talloc_single_attribute(
6129                                         priv2ld(ldap_state), entry, "sambaSID",
6130                                         talloc_tos());
6131                 if (dom_sid_str == NULL) {
6132                         DEBUG(1, ("talloc failed\n"));
6133                         return NT_STATUS_NO_MEMORY;
6134                 }
6135                 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6136                         DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6137                                   dom_sid_str));
6138                         return NT_STATUS_UNSUCCESSFUL;
6139                 }
6140 
6141                 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6142                              domains, num_domains);
6143 
6144                 if (*domains == NULL) {
6145                         DEBUG(1, ("talloc failed\n"));
6146                         return NT_STATUS_NO_MEMORY;
6147                 }
6148         }
6149 
6150         DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6151         return NT_STATUS_OK;
6152 }
6153 
6154 
6155 /**********************************************************************
6156  Housekeeping
6157  *********************************************************************/
6158 
6159 static void free_private_data(void **vp) 
     /* [<][>][^][v][top][bottom][index][help] */
6160 {
6161         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6162 
6163         smbldap_free_struct(&(*ldap_state)->smbldap_state);
6164 
6165         if ((*ldap_state)->result != NULL) {
6166                 ldap_msgfree((*ldap_state)->result);
6167                 (*ldap_state)->result = NULL;
6168         }
6169         if ((*ldap_state)->domain_dn != NULL) {
6170                 SAFE_FREE((*ldap_state)->domain_dn);
6171         }
6172 
6173         *ldap_state = NULL;
6174 
6175         /* No need to free any further, as it is talloc()ed */
6176 }
6177 
6178 /*********************************************************************
6179  Intitalise the parts of the pdb_methods structure that are common to 
6180  all pdb_ldap modes
6181 *********************************************************************/
6182 
6183 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
     /* [<][>][^][v][top][bottom][index][help] */
6184 {
6185         NTSTATUS nt_status;
6186         struct ldapsam_privates *ldap_state;
6187 
6188         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6189                 return nt_status;
6190         }
6191 
6192         (*pdb_method)->name = "ldapsam";
6193 
6194         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6195         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6196         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6197         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6198         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6199         (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6200 
6201         (*pdb_method)->getgrsid = ldapsam_getgrsid;
6202         (*pdb_method)->getgrgid = ldapsam_getgrgid;
6203         (*pdb_method)->getgrnam = ldapsam_getgrnam;
6204         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6205         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6206         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6207         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6208 
6209         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6210         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6211 
6212         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6213 
6214         (*pdb_method)->rid_algorithm = ldapsam_rid_algorithm;
6215         (*pdb_method)->new_rid = ldapsam_new_rid;
6216 
6217         (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6218         (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6219         (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6220         (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6221 
6222         /* TODO: Setup private data and free */
6223 
6224         if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
6225                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6226                 return NT_STATUS_NO_MEMORY;
6227         }
6228 
6229         nt_status = smbldap_init(*pdb_method, pdb_get_event_context(),
6230                                  location, &ldap_state->smbldap_state);
6231 
6232         if ( !NT_STATUS_IS_OK(nt_status) ) {
6233                 return nt_status;
6234         }
6235 
6236         if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6237                 return NT_STATUS_NO_MEMORY;
6238         }
6239 
6240         (*pdb_method)->private_data = ldap_state;
6241 
6242         (*pdb_method)->free_private_data = free_private_data;
6243 
6244         return NT_STATUS_OK;
6245 }
6246 
6247 /**********************************************************************
6248  Initialise the 'compat' mode for pdb_ldap
6249  *********************************************************************/
6250 
6251 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
     /* [<][>][^][v][top][bottom][index][help] */
6252 {
6253         NTSTATUS nt_status;
6254         struct ldapsam_privates *ldap_state;
6255         char *uri = talloc_strdup( NULL, location );
6256 
6257         trim_char( uri, '\"', '\"' );
6258         nt_status = pdb_init_ldapsam_common( pdb_method, uri );
6259         if ( uri )
6260                 TALLOC_FREE( uri );
6261 
6262         if ( !NT_STATUS_IS_OK(nt_status) ) {
6263                 return nt_status;
6264         }
6265 
6266         (*pdb_method)->name = "ldapsam_compat";
6267 
6268         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6269         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
6270 
6271         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6272 
6273         return NT_STATUS_OK;
6274 }
6275 
6276 /**********************************************************************
6277  Initialise the normal mode for pdb_ldap
6278  *********************************************************************/
6279 
6280 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
     /* [<][>][^][v][top][bottom][index][help] */
6281 {
6282         NTSTATUS nt_status;
6283         struct ldapsam_privates *ldap_state = NULL;
6284         uint32 alg_rid_base;
6285         char *alg_rid_base_string = NULL;
6286         LDAPMessage *result = NULL;
6287         LDAPMessage *entry = NULL;
6288         DOM_SID ldap_domain_sid;
6289         DOM_SID secrets_domain_sid;
6290         char *domain_sid_string = NULL;
6291         char *dn = NULL;
6292         char *uri = talloc_strdup( NULL, location );
6293 
6294         trim_char( uri, '\"', '\"' );
6295         nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6296         if (uri) {
6297                 TALLOC_FREE(uri);
6298         }
6299 
6300         if (!NT_STATUS_IS_OK(nt_status)) {
6301                 return nt_status;
6302         }
6303 
6304         (*pdb_method)->name = "ldapsam";
6305 
6306         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6307         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6308         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6309         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6310         (*pdb_method)->search_users = ldapsam_search_users;
6311         (*pdb_method)->search_groups = ldapsam_search_groups;
6312         (*pdb_method)->search_aliases = ldapsam_search_aliases;
6313 
6314         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6315                 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6316                 (*pdb_method)->enum_group_memberships =
6317                         ldapsam_enum_group_memberships;
6318                 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6319                 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6320 
6321                 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6322                         (*pdb_method)->create_user = ldapsam_create_user;
6323                         (*pdb_method)->delete_user = ldapsam_delete_user;
6324                         (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6325                         (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6326                         (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6327                         (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6328                         (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6329                 }
6330         }
6331 
6332         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6333         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6334 
6335         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6336 
6337         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6338                                                &result,
6339                                                ldap_state->domain_name, True);
6340 
6341         if ( !NT_STATUS_IS_OK(nt_status) ) {
6342                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
6343                           "info, nor add one to the domain\n"));
6344                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
6345                              "will be unable to allocate new users/groups, "
6346                              "and will risk BDCs having inconsistant SIDs\n"));
6347                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6348                 return NT_STATUS_OK;
6349         }
6350 
6351         /* Given that the above might fail, everything below this must be
6352          * optional */
6353 
6354         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6355                                  result);
6356         if (!entry) {
6357                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6358                           "entry\n"));
6359                 ldap_msgfree(result);
6360                 return NT_STATUS_UNSUCCESSFUL;
6361         }
6362 
6363         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6364         if (!dn) {
6365                 ldap_msgfree(result);
6366                 return NT_STATUS_UNSUCCESSFUL;
6367         }
6368 
6369         ldap_state->domain_dn = smb_xstrdup(dn);
6370         TALLOC_FREE(dn);
6371 
6372         domain_sid_string = smbldap_talloc_single_attribute(
6373                     ldap_state->smbldap_state->ldap_struct,
6374                     entry,
6375                     get_userattr_key2string(ldap_state->schema_ver,
6376                                             LDAP_ATTR_USER_SID),
6377                     talloc_tos());
6378 
6379         if (domain_sid_string) {
6380                 bool found_sid;
6381                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6382                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6383                                   "read as a valid SID\n", domain_sid_string));
6384                         ldap_msgfree(result);
6385                         TALLOC_FREE(domain_sid_string);
6386                         return NT_STATUS_INVALID_PARAMETER;
6387                 }
6388                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
6389                                                      &secrets_domain_sid);
6390                 if (!found_sid || !sid_equal(&secrets_domain_sid,
6391                                              &ldap_domain_sid)) {
6392                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6393                                   "%s based on pdb_ldap results %s -> %s\n",
6394                                   ldap_state->domain_name,
6395                                   sid_string_dbg(&secrets_domain_sid),
6396                                   sid_string_dbg(&ldap_domain_sid)));
6397 
6398                         /* reset secrets.tdb sid */
6399                         secrets_store_domain_sid(ldap_state->domain_name,
6400                                                  &ldap_domain_sid);
6401                         DEBUG(1, ("New global sam SID: %s\n",
6402                                   sid_string_dbg(get_global_sam_sid())));
6403                 }
6404                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6405                 TALLOC_FREE(domain_sid_string);
6406         }
6407 
6408         alg_rid_base_string = smbldap_talloc_single_attribute(
6409                     ldap_state->smbldap_state->ldap_struct,
6410                     entry,
6411                     get_attr_key2string( dominfo_attr_list,
6412                                          LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6413                     talloc_tos());
6414         if (alg_rid_base_string) {
6415                 alg_rid_base = (uint32)atol(alg_rid_base_string);
6416                 if (alg_rid_base != algorithmic_rid_base()) {
6417                         DEBUG(0, ("The value of 'algorithmic RID base' has "
6418                                   "changed since the LDAP\n"
6419                                   "database was initialised.  Aborting. \n"));
6420                         ldap_msgfree(result);
6421                         TALLOC_FREE(alg_rid_base_string);
6422                         return NT_STATUS_UNSUCCESSFUL;
6423                 }
6424                 TALLOC_FREE(alg_rid_base_string);
6425         }
6426         ldap_msgfree(result);
6427 
6428         return NT_STATUS_OK;
6429 }
6430 
6431 NTSTATUS pdb_ldap_init(void)
     /* [<][>][^][v][top][bottom][index][help] */
6432 {
6433         NTSTATUS nt_status;
6434         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
6435                 return nt_status;
6436 
6437         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
6438                 return nt_status;
6439 
6440         /* Let pdb_nds register backends */
6441         pdb_nds_init();
6442 
6443         return NT_STATUS_OK;
6444 }

/* [<][>][^][v][top][bottom][index][help] */