r12743: Remove the ugly way we had to make a second stage init and introduce
[kai/samba.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
1 /* 
2    ldb database module
3
4    Copyright (C) Simo Sorce  2004
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
6    Copyright (C) Andrew Tridgell 2004
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 /*
24  *  Name: ldb
25  *
26  *  Component: ldb password_hash module
27  *
28  *  Description: correctly update hash values based on changes to sambaPassword and friends
29  *
30  *  Author: Andrew Bartlett
31  */
32
33 #include "includes.h"
34 #include "libcli/ldap/ldap.h"
35 #include "ldb/include/ldb_errors.h"
36 #include "ldb/include/ldb_private.h"
37 #include "librpc/gen_ndr/ndr_misc.h"
38 #include "librpc/gen_ndr/ndr_samr.h"
39 #include "system/kerberos.h"
40 #include "auth/kerberos/kerberos.h"
41 #include "system/time.h"
42 #include "dsdb/samdb/samdb.h"
43 #include "ads.h"
44 #include "hdb.h"
45
46 /* If we have decided there is reason to work on this request, then
47  * setup all the password hash types correctly.
48  *
49  * If the administrator doesn't want the sambaPassword stored (set in the
50  * domain and per-account policies) then we must strip that out before
51  * we do the first operation.
52  *
53  * Once this is done (which could update anything at all), we
54  * calculate the password hashes.
55  *
56  * This function must not only update the ntPwdHash, lmPwdHash and
57  * krb5Key fields, it must also atomicly increment the
58  * msDS-KeyVersionNumber.  We should be in a transaction, so all this
59  * should be quite safe...
60  *
61  * Finally, if the administrator has requested that a password history
62  * be maintained, then this should also be written out.
63  *
64  */
65
66
67 static int password_hash_handle(struct ldb_module *module, struct ldb_request *req, 
68                              const struct ldb_message *msg)
69 {
70         int ret, old_ret = -1;
71         uint_t pwdProperties, pwdHistoryLength;
72         uint_t userAccountControl;
73         const char *dnsDomain, *realm;
74         const char *sambaPassword;
75         struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory;
76         struct samr_Password *lmPwdHash, *ntPwdHash;
77         struct samr_Password *lmOldHash = NULL, *ntOldHash = NULL;
78         struct samr_Password *new_sambaLMPwdHistory, *new_sambaNTPwdHistory;
79         struct samr_Password local_lmNewHash, local_ntNewHash;
80         int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
81         uint_t kvno;
82         struct dom_sid *domain_sid;
83         time_t now = time(NULL);
84         NTTIME now_nt;
85         int i;
86         krb5_error_code krb5_ret;
87
88         struct smb_krb5_context *smb_krb5_context;
89
90         struct ldb_message_element *attribute;
91         struct ldb_dn *dn = msg->dn;
92         struct ldb_message *msg2;
93
94         struct ldb_request *search_request = NULL;
95         struct ldb_request *modify_request;
96         struct ldb_request *modified_orig_request;
97         struct ldb_result *res, *dom_res, *old_res;
98
99         struct ldb_message_element *objectclasses;
100         struct ldb_val computer_val;
101         struct ldb_val person_val;
102         BOOL is_computer;
103
104         struct ldb_message *modify_msg;
105
106         const char *domain_expression;
107         const char *old_user_attrs[] = { "lmPwdHash", "ntPwdHash", NULL };
108         const char *user_attrs[] = { "userAccountControl", "sambaLMPwdHistory", 
109                                      "sambaNTPwdHistory", 
110                                      "ntPwdHash", 
111                                      "objectSid", "msDS-KeyVersionNumber", 
112                                      "objectClass", "userPrincipalName",
113                                      "samAccountName", 
114                                      NULL };
115         const char * const domain_attrs[] = { "pwdProperties", "pwdHistoryLength", 
116                                               "dnsDomain", NULL };
117
118         TALLOC_CTX *mem_ctx;
119
120         /* Do the original action */
121         
122         /* If no part of this touches the sambaPassword, then we don't
123          * need to make any changes.  For password changes/set there should
124          * be a 'delete' or a 'modify' on this attribute. */
125         if ((attribute = ldb_msg_find_element(msg, "sambaPassword")) == NULL ) {
126                 return ldb_next_request(module, req);
127         }
128
129         mem_ctx = talloc_new(module);
130         if (!mem_ctx) {
131                 return LDB_ERR_OPERATIONS_ERROR;
132         }
133
134         if (req->operation == LDB_REQ_MODIFY) {
135                 search_request = talloc(mem_ctx, struct ldb_request);
136                 if (!search_request) {
137                         talloc_free(mem_ctx);
138                         return LDB_ERR_OPERATIONS_ERROR;
139                 }
140
141                 /* Look up the old ntPwdHash and lmPwdHash values, so
142                  * we can later place these into the password
143                  * history */
144
145                 search_request->operation = LDB_REQ_SEARCH;
146                 search_request->op.search.base = dn;
147                 search_request->op.search.scope = LDB_SCOPE_BASE;
148                 search_request->op.search.tree = ldb_parse_tree(module->ldb, NULL);
149                 search_request->op.search.attrs = old_user_attrs;
150                 search_request->controls = NULL;
151                 
152                 old_ret = ldb_next_request(module, search_request);
153         }
154
155         /* we can't change things untill we copy it */
156         msg2 = ldb_msg_copy_shallow(mem_ctx, msg);
157
158         /* look again, this time at the copied attribute */
159         if (!msg2 || (attribute = ldb_msg_find_element(msg2, "sambaPassword")) == NULL ) {
160                 /* Gah?  where did it go?  Oh well... */
161                 return LDB_ERR_OPERATIONS_ERROR;
162         }
163
164         /* Wipe out the sambaPassword attribute set, we will handle it in
165          * the second modify.  We might not want it written to disk */
166         
167         if (req->operation == LDB_REQ_ADD) {
168                 if (attribute->num_values != 1) {
169                         ldb_set_errstring(module, 
170                                           talloc_asprintf(mem_ctx, "sambaPassword_handle: "
171                                                           "attempted set of multiple sambaPassword attributes on %s rejected",
172                                                           ldb_dn_linearize(mem_ctx, dn)));
173                         return LDB_ERR_CONSTRAINT_VIOLAION;
174                 }
175         
176                 sambaPassword = (const char *)attribute->values[0].data;
177                 ldb_msg_remove_attr(msg2, "sambaPassword");
178         } else if (((attribute->flags & LDB_FLAG_MOD_MASK) == LDB_FLAG_MOD_ADD)
179                    || ((attribute->flags & LDB_FLAG_MOD_MASK) == LDB_FLAG_MOD_REPLACE)) {
180                 if (attribute->num_values != 1) {
181                         return LDB_ERR_CONSTRAINT_VIOLAION;
182                 }
183                 
184                 sambaPassword = (const char *)attribute->values[0].data;
185                 ldb_msg_remove_attr(msg2, "sambaPassword");
186         } else {
187                 sambaPassword = NULL;
188         }
189
190         modified_orig_request = talloc(mem_ctx, struct ldb_request);
191         if (!modified_orig_request) {
192                 talloc_free(mem_ctx);
193                 return LDB_ERR_OPERATIONS_ERROR;
194         }
195
196         *modified_orig_request = *req;
197         switch (modified_orig_request->operation) {
198         case LDB_REQ_ADD:
199                 modified_orig_request->op.add.message = msg2;
200                 break;
201         case LDB_REQ_MODIFY:
202                 modified_orig_request->op.mod.message = msg2;
203                 break;
204         }
205
206         /* Send the (modified) request of the original caller down to the database */
207         ret = ldb_next_request(module, modified_orig_request);
208         if (ret) {
209                 return ret;
210         }
211
212         /* While we do the search first (for the old password hashes),
213          * we don't want to override any error that the modify may
214          * have returned.  Now check the error */
215         if (req->operation == LDB_REQ_MODIFY) {
216                 if (old_ret) {
217                         talloc_free(mem_ctx);
218                         return old_ret;
219                 }
220
221                 /* Find out the old passwords details of the user */
222                 old_res = search_request->op.search.res;
223                 
224                 if (old_res->count != 1) {
225                         ldb_set_errstring(module, 
226                                           talloc_asprintf(mem_ctx, "password_hash_handle: "
227                                                           "(pre) search for %s found %d != 1 objects, for entry we just modified",
228                                                           ldb_dn_linearize(mem_ctx, dn),
229                                                           old_res->count));
230                         /* What happend?  The above add/modify worked... */
231                         talloc_free(mem_ctx);
232                         return LDB_ERR_NO_SUCH_OBJECT;
233                 }
234
235                 lmOldHash = samdb_result_hash(mem_ctx, old_res->msgs[0],   "lmPwdHash");
236                 ntOldHash = samdb_result_hash(mem_ctx, old_res->msgs[0],   "ntPwdHash");
237         }
238
239         /* Start finding out details we need for the second modify.
240          * We do this after the first add/modify because other modules
241          * will have filled in the templates, and we may have had
242          * things like the username (affecting the salt) changed along
243          * with the password. */
244
245         /* Now find out what is on the entry after the above add/modify */
246         search_request = talloc(mem_ctx, struct ldb_request);
247         if (!search_request) {
248                 talloc_free(mem_ctx);
249                 return LDB_ERR_OPERATIONS_ERROR;
250         }
251
252         search_request->operation       = LDB_REQ_SEARCH;
253         search_request->op.search.base  = dn;
254         search_request->op.search.scope = LDB_SCOPE_BASE;
255         search_request->op.search.tree  = ldb_parse_tree(module->ldb, NULL);
256         search_request->op.search.attrs = user_attrs;
257         search_request->controls = NULL;
258         
259         ret = ldb_next_request(module, search_request);
260         if (ret) {
261                 talloc_free(mem_ctx);
262                 return ret;
263         }
264
265         /* Find out the full details of the user */
266         res = search_request->op.search.res;
267         if (res->count != 1) {
268                 ldb_set_errstring(module, 
269                                   talloc_asprintf(mem_ctx, "password_hash_handle: "
270                                                   "search for %s found %d != 1 objects, for entry we just added/modified",
271                                                   ldb_dn_linearize(mem_ctx, dn),
272                                                   res->count));
273                 /* What happend?  The above add/modify worked... */
274                 talloc_free(mem_ctx);
275                 return LDB_ERR_NO_SUCH_OBJECT;
276         }
277
278         userAccountControl = samdb_result_uint(res->msgs[0],   "userAccountControl", 0);
279         sambaLMPwdHistory_len   = samdb_result_hashes(mem_ctx, res->msgs[0], 
280                                                  "sambaLMPwdHistory", &sambaLMPwdHistory);
281         sambaNTPwdHistory_len   = samdb_result_hashes(mem_ctx, res->msgs[0], 
282                                                  "sambaNTPwdHistory", &sambaNTPwdHistory);
283         ntPwdHash          = samdb_result_hash(mem_ctx, res->msgs[0],   "ntPwdHash");
284         kvno               = samdb_result_uint(res->msgs[0],   "msDS-KeyVersionNumber", 0);
285
286         domain_sid         = samdb_result_sid_prefix(mem_ctx, res->msgs[0], "objectSid");
287
288         
289         objectclasses = ldb_msg_find_element(res->msgs[0], "objectClass");
290         person_val = data_blob_string_const("person");
291         
292         if (!objectclasses || !ldb_msg_find_val(objectclasses, &person_val)) {
293                 /* Not a 'person', so the rest of this doesn't make
294                  * sense.  How we got a sambaPassword this far I don't
295                  * know... */
296                 ldb_set_errstring(module, 
297                                   talloc_asprintf(mem_ctx, "password_hash_handle: "
298                                                   "attempted set of sambaPassword on non-'person' object %s rejected",
299                                                   ldb_dn_linearize(mem_ctx, dn)));
300                 talloc_free(mem_ctx);
301                 return LDB_ERR_CONSTRAINT_VIOLAION;
302         }
303
304         computer_val = data_blob_string_const("computer");
305         
306         if (ldb_msg_find_val(objectclasses, &computer_val)) {
307                 is_computer = True;
308         } else {
309                 is_computer = False;
310         }
311         
312         domain_expression  = talloc_asprintf(mem_ctx, "(&(objectSid=%s)(objectClass=domain))", 
313                                              ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
314
315         /* Find the user's domain, then find out the domain password
316          * properties */
317         ret = ldb_search(module->ldb, NULL, LDB_SCOPE_SUBTREE, domain_expression, 
318                          domain_attrs, &dom_res);
319         if (ret) {
320                 talloc_free(mem_ctx);
321                 return ret;
322         }
323
324         if (dom_res->count != 1) {
325                 /* What happend?  The user we are modifying must be odd... */
326                 ldb_set_errstring(module, 
327                                   talloc_asprintf(mem_ctx, "password_hash_handle: "
328                                                   "search for domain %s found %d != 1 objects",
329                                                   dom_sid_string(mem_ctx, domain_sid),
330                                                   dom_res->count));
331                 talloc_free(mem_ctx);
332                 return LDB_ERR_NO_SUCH_OBJECT;
333         }
334
335         pwdProperties    = samdb_result_uint(dom_res->msgs[0],   "pwdProperties", 0);
336         pwdHistoryLength = samdb_result_uint(dom_res->msgs[0],   "pwdHistoryLength", 0);
337         dnsDomain        = ldb_msg_find_string(dom_res->msgs[0], "dnsDomain", NULL);
338         realm            = strupper_talloc(mem_ctx, dnsDomain);
339
340         /* Some operations below require kerberos contexts */
341         if (smb_krb5_init_context(mem_ctx, &smb_krb5_context) != 0) {
342                 talloc_free(mem_ctx);
343                 return LDB_ERR_OPERATIONS_ERROR;
344         }
345
346         /* Prepare the modifications to set all the hash/key types */
347         modify_msg = ldb_msg_new(req);
348         modify_msg->dn = talloc_reference(modify_msg, dn);
349
350 #define CHECK_RET(x) \
351         do {                                    \
352                 int check_ret = x;              \
353                 if (check_ret != LDB_SUCCESS) { \
354                         talloc_free(mem_ctx);   \
355                         return check_ret;       \
356                 }                               \
357         } while(0)
358
359         /* Setup krb5Key (we want to either delete an existing value,
360          * or replace with a new one).  Both the unicode and NT hash
361          * only branches append keys to this multivalued entry. */
362         CHECK_RET(ldb_msg_add_empty(modify_msg, "krb5Key", LDB_FLAG_MOD_REPLACE));
363         /* Yay, we can compute new password hashes from the unicode
364          * password */
365         if (sambaPassword) {
366                 Principal *salt_principal;
367                 const char *user_principal_name = ldb_msg_find_string(res->msgs[0], "userPrincipalName", NULL);
368                 
369                 Key *keys;
370                 size_t num_keys;
371
372                 /* compute the new nt and lm hashes */
373                 if (E_deshash(sambaPassword, local_lmNewHash.hash)) {
374                         lmPwdHash = &local_lmNewHash;
375                 } else {
376                         lmPwdHash = NULL;
377                 }
378                 E_md4hash(sambaPassword, local_ntNewHash.hash);
379                 ntPwdHash = &local_ntNewHash;
380                 CHECK_RET(ldb_msg_add_empty(modify_msg, "ntPwdHash", 
381                                             LDB_FLAG_MOD_REPLACE));
382                 CHECK_RET(samdb_msg_add_hash(module->ldb, req, 
383                                              modify_msg, "ntPwdHash", 
384                                              ntPwdHash));
385                 CHECK_RET(ldb_msg_add_empty(modify_msg, "lmPwdHash", 
386                                             LDB_FLAG_MOD_REPLACE));
387                 if (lmPwdHash) {
388                         CHECK_RET(samdb_msg_add_hash(module->ldb, req, 
389                                                      modify_msg, "lmPwdHash", 
390                                                      lmPwdHash));
391                 }
392
393                 /* Many, many thanks to lukeh@padl.com for this
394                  * algorithm, described in his Nov 10 2004 mail to
395                  * samba-technical@samba.org */
396
397                 if (is_computer) {
398                         /* Determine a salting principal */
399                         char *samAccountName = talloc_strdup(mem_ctx, ldb_msg_find_string(res->msgs[0], "samAccountName", NULL));
400                         char *saltbody;
401                         if (!samAccountName) {
402                                 ldb_set_errstring(module, 
403                                                   talloc_asprintf(mem_ctx, "password_hash_handle: "
404                                                                   "generation of new kerberos keys failed: %s is a computer without a samAccountName",
405                                                                   ldb_dn_linearize(mem_ctx, dn)));
406                                 talloc_free(mem_ctx);
407                                 return LDB_ERR_OPERATIONS_ERROR;
408                         }
409                         if (samAccountName[strlen(samAccountName)-1] == '$') {
410                                 samAccountName[strlen(samAccountName)-1] = '\0';
411                         }
412                         saltbody = talloc_asprintf(mem_ctx, "%s.%s", samAccountName, dnsDomain);
413                         
414                         krb5_ret = krb5_make_principal(smb_krb5_context->krb5_context, &salt_principal, realm, "host", saltbody, NULL);
415                 } else if (user_principal_name) {
416                         char *p;
417                         user_principal_name = talloc_strdup(mem_ctx, user_principal_name);
418                         if (!user_principal_name) {
419                                 talloc_free(mem_ctx);
420                                 return LDB_ERR_OPERATIONS_ERROR;
421                         } else {
422                                 p = strchr(user_principal_name, '@');
423                                 if (p) {
424                                         p[0] = '\0';
425                                 }
426                                 krb5_ret = krb5_make_principal(smb_krb5_context->krb5_context, &salt_principal, realm, user_principal_name, NULL);
427                         } 
428                 } else {
429                         const char *samAccountName = ldb_msg_find_string(res->msgs[0], "samAccountName", NULL);
430                         if (!samAccountName) {
431                                 ldb_set_errstring(module, 
432                                                   talloc_asprintf(mem_ctx, "password_hash_handle: "
433                                                                   "generation of new kerberos keys failed: %s has no samAccountName",
434                                                                   ldb_dn_linearize(mem_ctx, dn)));
435                                 talloc_free(mem_ctx);
436                                 return LDB_ERR_OPERATIONS_ERROR;
437                         }
438                         krb5_ret = krb5_make_principal(smb_krb5_context->krb5_context, &salt_principal, realm, samAccountName, NULL);
439                 }
440
441
442                 if (krb5_ret) {
443                         ldb_set_errstring(module, 
444                                           talloc_asprintf(mem_ctx, "password_hash_handle: "
445                                                           "generation of a saltking principal failed: %s",
446                                                           smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
447                                                                                      krb5_ret, mem_ctx)));
448                         talloc_free(mem_ctx);
449                         return LDB_ERR_OPERATIONS_ERROR;
450                 }
451
452                 /* TODO: We may wish to control the encryption types chosen in future */
453                 krb5_ret = hdb_generate_key_set_password(smb_krb5_context->krb5_context,
454                                                     salt_principal, sambaPassword, &keys, &num_keys);
455                 krb5_free_principal(smb_krb5_context->krb5_context, salt_principal);
456
457                 if (krb5_ret) {
458                         ldb_set_errstring(module, 
459                                           talloc_asprintf(mem_ctx, "password_hash_handle: "
460                                                           "generation of new kerberos keys failed: %s",
461                                                           smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
462                                                                                      krb5_ret, mem_ctx)));
463                         talloc_free(mem_ctx);
464                         return LDB_ERR_OPERATIONS_ERROR;
465                 }
466
467                 /* Walking 
468                  */
469                 for (i=0; i < num_keys; i++) {
470                         unsigned char *buf;
471                         size_t buf_size;
472                         size_t len;
473                         struct ldb_val val;
474                         
475                         if (keys[i].key.keytype == ENCTYPE_ARCFOUR_HMAC) {
476                                 /* We might end up doing this below:
477                                  * This ensures we get the unicode
478                                  * conversion right.  This should also
479                                  * be fixed in the Heimdal libs */
480                                 continue;
481                         }
482                         ASN1_MALLOC_ENCODE(Key, buf, buf_size, &keys[i], &len, krb5_ret);
483                         
484                         val.data = talloc_memdup(req, buf, len);
485                         val.length = len;
486                         free(buf);
487                         if (!val.data || krb5_ret) {
488                                 hdb_free_keys (smb_krb5_context->krb5_context, num_keys, keys);
489                                 talloc_free(mem_ctx);
490                                 return LDB_ERR_OPERATIONS_ERROR;
491                         }
492                         ret = ldb_msg_add_value(modify_msg, "krb5Key", &val);
493                         if (ret != LDB_SUCCESS) {
494                                 hdb_free_keys (smb_krb5_context->krb5_context, num_keys, keys);
495                                 talloc_free(mem_ctx);
496                                 return ret;
497                         }
498                 }
499                 
500                 hdb_free_keys (smb_krb5_context->krb5_context, num_keys, keys);
501         }
502
503         /* Possibly kill off the cleartext or store it */
504         CHECK_RET(ldb_msg_add_empty(modify_msg, "sambaPassword", LDB_FLAG_MOD_REPLACE));
505
506         if (sambaPassword && (pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT) &&
507             (userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
508                 CHECK_RET(ldb_msg_add_string(modify_msg, "sambaPassword", sambaPassword));
509         }
510         
511         /* Even if we didn't get a sambaPassword, we can still setup
512          * krb5Key from the NT hash. 
513          *
514          * This is an append, so it works with the 'continue' in the
515          * unicode loop above, to use Samba's NT hash function, which
516          * is more correct than Heimdal's
517          */
518         if (ntPwdHash) {
519                 unsigned char *buf;
520                 size_t buf_size;
521                 size_t len;
522                 struct ldb_val val;
523                 Key key;
524                 
525                 key.mkvno = 0;
526                 key.salt = NULL; /* No salt for this enc type */
527
528                 krb5_ret = krb5_keyblock_init(smb_krb5_context->krb5_context,
529                                          ENCTYPE_ARCFOUR_HMAC,
530                                          ntPwdHash->hash, sizeof(ntPwdHash->hash), 
531                                          &key.key);
532                 if (krb5_ret) {
533                         return LDB_ERR_OPERATIONS_ERROR;
534                 }
535                 ASN1_MALLOC_ENCODE(Key, buf, buf_size, &key, &len, krb5_ret);
536                 krb5_free_keyblock_contents(smb_krb5_context->krb5_context,
537                                             &key.key);
538                 
539                 val.data = talloc_memdup(req, buf, len);
540                 val.length = len;
541                 free(buf);
542                 if (!val.data || ret) {
543                         return LDB_ERR_OPERATIONS_ERROR;
544                 }
545                 CHECK_RET(ldb_msg_add_value(modify_msg, "krb5Key", &val));
546         }
547
548         /* If the original caller did anything with pwdLastSet then skip this.  It could be an incoming samsync */
549         if ((attribute = ldb_msg_find_element(msg, "pwdLastSet")) == NULL ) {
550                 /* Update the password last set time */
551                 unix_to_nt_time(&now_nt, now);
552                 CHECK_RET(ldb_msg_add_empty(modify_msg, "pwdLastSet", LDB_FLAG_MOD_REPLACE));
553                 CHECK_RET(samdb_msg_add_uint64(module->ldb, mem_ctx, modify_msg, "pwdLastSet", now_nt));
554         }
555
556         /* If the original caller did anything with "msDS-KeyVersionNumber" then skip this.  It could be an incoming samsync */
557         if ((attribute = ldb_msg_find_element(msg, "msDS-KeyVersionNumber")) == NULL ) {
558                 if (kvno == 0) {
559                         CHECK_RET(ldb_msg_add_empty(modify_msg, "msDS-KeyVersionNumber",
560                                                     LDB_FLAG_MOD_REPLACE));
561                         CHECK_RET(samdb_msg_add_uint(module->ldb, mem_ctx, modify_msg, "msDS-KeyVersionNumber", kvno + 1));
562                 } else {
563                         /* While we should be in a transaction, go one extra
564                          * step in the dance for an 'atomic' increment.  This
565                          * may be of value against remote LDAP servers.  (Note
566                          * however that Mulitmaster replication stil offers no
567                          * such guarantee) */
568                         
569                         struct ldb_val old_kvno, new_kvno;
570                         old_kvno.data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", kvno);
571                         if (!old_kvno.data) {
572                                 return -1;
573                         }
574                         old_kvno.length = strlen((char *)old_kvno.data);
575                         
576                         new_kvno.data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", kvno + 1);
577                         if (!new_kvno.data) {
578                                 return -1;
579                         }
580                         new_kvno.length = strlen((char *)new_kvno.data);
581                         
582                         CHECK_RET(ldb_msg_add_empty(modify_msg, "msDS-KeyVersionNumber",
583                                                     LDB_FLAG_MOD_DELETE));
584                         CHECK_RET(ldb_msg_add_empty(modify_msg, "msDS-KeyVersionNumber",
585                                                     LDB_FLAG_MOD_ADD));
586                         modify_msg->elements[modify_msg->num_elements - 2].num_values = 1;
587                         modify_msg->elements[modify_msg->num_elements - 2].values = &old_kvno;
588                         modify_msg->elements[modify_msg->num_elements - 1].num_values = 1;
589                         modify_msg->elements[modify_msg->num_elements - 1].values = &new_kvno;
590                 }
591         }
592
593         CHECK_RET(ldb_msg_add_empty(modify_msg, "sambaLMPwdHistory",
594                                     LDB_FLAG_MOD_REPLACE));
595         CHECK_RET(ldb_msg_add_empty(modify_msg, "sambaNTPwdHistory",
596                                     LDB_FLAG_MOD_REPLACE));
597
598         /* If we have something to put into the history, or an old
599          * history element to expire, update the history */
600         if (pwdHistoryLength > 0 && 
601             ((sambaNTPwdHistory_len > 0) || (sambaLMPwdHistory_len > 0) 
602              || lmOldHash || ntOldHash)) {
603                 /* store the password history */
604                 new_sambaLMPwdHistory = talloc_array(mem_ctx, struct samr_Password, 
605                                                 pwdHistoryLength);
606                 if (!new_sambaLMPwdHistory) {
607                         return LDB_ERR_OPERATIONS_ERROR;
608                 }
609                 new_sambaNTPwdHistory = talloc_array(mem_ctx, struct samr_Password, 
610                                                 pwdHistoryLength);
611                 if (!new_sambaNTPwdHistory) {
612                         return LDB_ERR_OPERATIONS_ERROR;
613                 }
614                 for (i=0;i<MIN(pwdHistoryLength-1, sambaLMPwdHistory_len);i++) {
615                         new_sambaLMPwdHistory[i+1] = sambaLMPwdHistory[i];
616                 }
617                 for (i=0;i<MIN(pwdHistoryLength-1, sambaNTPwdHistory_len);i++) {
618                         new_sambaNTPwdHistory[i+1] = sambaNTPwdHistory[i];
619                 }
620                 
621                 /* Don't store 'long' passwords in the LM history, 
622                    but make sure to 'expire' one password off the other end */
623                 if (lmOldHash) {
624                         new_sambaLMPwdHistory[0] = *lmOldHash;
625                 } else {
626                         ZERO_STRUCT(new_sambaLMPwdHistory[0]);
627                 }
628                 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len + 1, pwdHistoryLength);
629                 
630                 /* Likewise, we might not have a new NT password (lm
631                  * only password change function) */
632                 if (ntOldHash) {
633                         new_sambaNTPwdHistory[0] = *ntOldHash;
634                 } else {
635                         ZERO_STRUCT(new_sambaNTPwdHistory[0]);
636                 }
637                 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len + 1, pwdHistoryLength);
638                 
639                 CHECK_RET(samdb_msg_add_hashes(module->ldb, mem_ctx, modify_msg, 
640                                                "sambaLMPwdHistory", 
641                                                new_sambaLMPwdHistory, 
642                                                sambaLMPwdHistory_len));
643                 
644                 CHECK_RET(samdb_msg_add_hashes(module->ldb, mem_ctx, modify_msg, 
645                                                "sambaNTPwdHistory", 
646                                                new_sambaNTPwdHistory, 
647                                                sambaNTPwdHistory_len));
648         }
649
650         /* Too much code above, we should check we got it close to reasonable */
651         CHECK_RET(ldb_msg_sanity_check(modify_msg));
652
653         modify_request = talloc(mem_ctx, struct ldb_request);
654         if (!modify_request) {
655                 talloc_free(mem_ctx);
656                 return LDB_ERR_OPERATIONS_ERROR;
657         }
658
659         modify_request->operation = LDB_REQ_MODIFY;
660         modify_request->op.mod.message = modify_msg;
661         modify_request->controls = NULL;
662
663         ret = ldb_next_request(module, modify_request);
664         
665         talloc_free(mem_ctx);
666         return ret;
667 }
668
669 /* add_record: do things with the sambaPassword attribute */
670 static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
671 {
672         const struct ldb_message *msg = req->op.add.message;
673
674         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_add_record\n");
675
676         if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
677                 return ldb_next_request(module, req);
678         }
679         
680         return password_hash_handle(module, req, msg);
681 }
682
683 /* modify_record: do things with the sambaPassword attribute */
684 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
685 {
686         const struct ldb_message *msg = req->op.mod.message;
687
688         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_modify_record\n");
689
690         if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
691                 return ldb_next_request(module, req);
692         }
693         
694         return password_hash_handle(module, req, msg);
695 }
696
697 static int password_hash_request(struct ldb_module *module, struct ldb_request *req)
698 {
699         switch (req->operation) {
700
701         case LDB_REQ_ADD:
702                 return password_hash_add(module, req);
703
704         case LDB_REQ_MODIFY:
705                 return password_hash_modify(module, req);
706
707         default:
708                 return ldb_next_request(module, req);
709
710         }
711 }
712
713 static const struct ldb_module_ops password_hash_ops = {
714         .name          = "password_hash",
715         .request       = password_hash_request
716 };
717
718
719 /* the init function */
720 struct ldb_module *password_hash_module_init(struct ldb_context *ldb, const char *options[])
721 {
722         struct ldb_module *ctx;
723
724         ctx = talloc(ldb, struct ldb_module);
725         if (!ctx)
726                 return NULL;
727
728         ctx->private_data = NULL;
729         ctx->ldb = ldb;
730         ctx->prev = ctx->next = NULL;
731         ctx->ops = &password_hash_ops;
732
733         return ctx;
734 }