password_hash: simplify the logic if we have cleartext we always generate the hashes
[kai/samba.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
1 /* 
2    ldb database module
3
4    Copyright (C) Simo Sorce  2004-2006
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2006
6    Copyright (C) Andrew Tridgell 2004
7    Copyright (C) Stefan Metzmacher 2007
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 /*
24  *  Name: ldb
25  *
26  *  Component: ldb password_hash module
27  *
28  *  Description: correctly update hash values based on changes to userPassword and friends
29  *
30  *  Author: Andrew Bartlett
31  *  Author: Stefan Metzmacher
32  */
33
34 #include "includes.h"
35 #include "libcli/ldap/ldap_ndr.h"
36 #include "ldb/include/ldb_errors.h"
37 #include "ldb/include/ldb.h"
38 #include "ldb/include/ldb_private.h"
39 #include "librpc/gen_ndr/misc.h"
40 #include "librpc/gen_ndr/samr.h"
41 #include "libcli/auth/libcli_auth.h"
42 #include "libcli/security/security.h"
43 #include "system/kerberos.h"
44 #include "auth/kerberos/kerberos.h"
45 #include "system/time.h"
46 #include "dsdb/samdb/samdb.h"
47 #include "dsdb/common/flags.h"
48 #include "dsdb/samdb/ldb_modules/password_modules.h"
49 #include "librpc/ndr/libndr.h"
50 #include "librpc/gen_ndr/ndr_drsblobs.h"
51 #include "lib/crypto/crypto.h"
52 #include "param/param.h"
53
54 /* If we have decided there is reason to work on this request, then
55  * setup all the password hash types correctly.
56  *
57  * If the administrator doesn't want the userPassword stored (set in the
58  * domain and per-account policies) then we must strip that out before
59  * we do the first operation.
60  *
61  * Once this is done (which could update anything at all), we
62  * calculate the password hashes.
63  *
64  * This function must not only update the unicodePwd, dBCSPwd and
65  * supplementalCredentials fields, it must also atomicly increment the
66  * msDS-KeyVersionNumber.  We should be in a transaction, so all this
67  * should be quite safe...
68  *
69  * Finally, if the administrator has requested that a password history
70  * be maintained, then this should also be written out.
71  *
72  */
73
74 struct ph_context {
75
76         enum ph_type {PH_ADD, PH_MOD} type;
77         enum ph_step {PH_ADD_SEARCH_DOM, PH_ADD_DO_ADD, PH_MOD_DO_REQ, PH_MOD_SEARCH_SELF, PH_MOD_SEARCH_DOM, PH_MOD_DO_MOD} step;
78
79         struct ldb_module *module;
80         struct ldb_request *orig_req;
81
82         struct ldb_request *dom_req;
83         struct ldb_reply *dom_res;
84
85         struct ldb_request *down_req;
86
87         struct ldb_request *search_req;
88         struct ldb_reply *search_res;
89
90         struct ldb_request *mod_req;
91
92         struct dom_sid *domain_sid;
93 };
94
95 struct domain_data {
96         bool store_cleartext;
97         uint_t pwdProperties;
98         uint_t pwdHistoryLength;
99         char *netbios_domain;
100         char *dns_domain;
101         char *realm;
102 };
103
104 struct setup_password_fields_io {
105         struct ph_context *ac;
106         struct domain_data *domain;
107         struct smb_krb5_context *smb_krb5_context;
108
109         /* infos about the user account */
110         struct {
111                 uint32_t user_account_control;
112                 const char *sAMAccountName;
113                 const char *user_principal_name;
114                 bool is_computer;
115         } u;
116
117         /* new credentials */
118         struct {
119                 const char *cleartext;
120                 struct samr_Password *nt_hash;
121                 struct samr_Password *lm_hash;
122         } n;
123
124         /* old credentials */
125         struct {
126                 uint32_t nt_history_len;
127                 struct samr_Password *nt_history;
128                 uint32_t lm_history_len;
129                 struct samr_Password *lm_history;
130                 const struct ldb_val *supplemental;
131                 struct supplementalCredentialsBlob scb;
132                 uint32_t kvno;
133         } o;
134
135         /* generated credentials */
136         struct {
137                 struct samr_Password *nt_hash;
138                 struct samr_Password *lm_hash;
139                 uint32_t nt_history_len;
140                 struct samr_Password *nt_history;
141                 uint32_t lm_history_len;
142                 struct samr_Password *lm_history;
143                 struct ldb_val supplemental;
144                 NTTIME last_set;
145                 uint32_t kvno;
146         } g;
147 };
148
149 static int setup_nt_fields(struct setup_password_fields_io *io)
150 {
151         uint32_t i;
152
153         io->g.nt_hash = io->n.nt_hash;
154
155         if (io->domain->pwdHistoryLength == 0) {
156                 return LDB_SUCCESS;
157         }
158
159         /* We might not have an old NT password */
160         io->g.nt_history = talloc_array(io->ac,
161                                         struct samr_Password,
162                                         io->domain->pwdHistoryLength);
163         if (!io->g.nt_history) {
164                 ldb_oom(io->ac->module->ldb);
165                 return LDB_ERR_OPERATIONS_ERROR;
166         }
167
168         for (i = 0; i < MIN(io->domain->pwdHistoryLength-1, io->o.nt_history_len); i++) {
169                 io->g.nt_history[i+1] = io->o.nt_history[i];
170         }
171         io->g.nt_history_len = i + 1;
172
173         if (io->g.nt_hash) {
174                 io->g.nt_history[0] = *io->g.nt_hash;
175         } else {
176                 /* 
177                  * TODO: is this correct?
178                  * the simular behavior is correct for the lm history case
179                  */
180                 E_md4hash("", io->g.nt_history[0].hash);
181         }
182
183         return LDB_SUCCESS;
184 }
185
186 static int setup_lm_fields(struct setup_password_fields_io *io)
187 {
188         uint32_t i;
189
190         io->g.lm_hash = io->n.lm_hash;
191
192         if (io->domain->pwdHistoryLength == 0) {
193                 return LDB_SUCCESS;
194         }
195
196         /* We might not have an old NT password */
197         io->g.lm_history = talloc_array(io->ac,
198                                         struct samr_Password,
199                                         io->domain->pwdHistoryLength);
200         if (!io->g.lm_history) {
201                 ldb_oom(io->ac->module->ldb);
202                 return LDB_ERR_OPERATIONS_ERROR;
203         }
204
205         for (i = 0; i < MIN(io->domain->pwdHistoryLength-1, io->o.lm_history_len); i++) {
206                 io->g.lm_history[i+1] = io->o.lm_history[i];
207         }
208         io->g.lm_history_len = i + 1;
209
210         if (io->g.lm_hash) {
211                 io->g.lm_history[0] = *io->g.lm_hash;
212         } else {
213                 E_deshash("", io->g.lm_history[0].hash);
214         }
215
216         return LDB_SUCCESS;
217 }
218
219 static int setup_primary_kerberos(struct setup_password_fields_io *io,
220                                   const struct supplementalCredentialsBlob *old_scb,
221                                   struct package_PrimaryKerberosBlob *pkb)
222 {
223         krb5_error_code krb5_ret;
224         Principal *salt_principal;
225         krb5_salt salt;
226         krb5_keyblock key;
227         uint32_t k=0;
228         struct package_PrimaryKerberosCtr3 *pkb3 = &pkb->ctr.ctr3;
229         struct supplementalCredentialsPackage *old_scp = NULL;
230         struct package_PrimaryKerberosBlob _old_pkb;
231         struct package_PrimaryKerberosCtr3 *old_pkb3 = NULL;
232         uint32_t i;
233         enum ndr_err_code ndr_err;
234
235         /* Many, many thanks to lukeh@padl.com for this
236          * algorithm, described in his Nov 10 2004 mail to
237          * samba-technical@samba.org */
238
239         /*
240          * Determine a salting principal
241          */
242         if (io->u.is_computer) {
243                 char *name;
244                 char *saltbody;
245
246                 name = talloc_strdup(io->ac, io->u.sAMAccountName);
247                 if (!name) {
248                         ldb_oom(io->ac->module->ldb);
249                         return LDB_ERR_OPERATIONS_ERROR;
250                 }
251
252                 if (name[strlen(name)-1] == '$') {
253                         name[strlen(name)-1] = '\0';
254                 }
255
256                 saltbody = talloc_asprintf(io->ac, "%s.%s", name, io->domain->dns_domain);
257                 if (!saltbody) {
258                         ldb_oom(io->ac->module->ldb);
259                         return LDB_ERR_OPERATIONS_ERROR;
260                 }
261                 
262                 krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
263                                                &salt_principal,
264                                                io->domain->realm, "host",
265                                                saltbody, NULL);
266         } else if (io->u.user_principal_name) {
267                 char *user_principal_name;
268                 char *p;
269
270                 user_principal_name = talloc_strdup(io->ac, io->u.user_principal_name);
271                 if (!user_principal_name) {
272                         ldb_oom(io->ac->module->ldb);
273                         return LDB_ERR_OPERATIONS_ERROR;
274                 }
275
276                 p = strchr(user_principal_name, '@');
277                 if (p) {
278                         p[0] = '\0';
279                 }
280
281                 krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
282                                                &salt_principal,
283                                                io->domain->realm, user_principal_name,
284                                                NULL);
285         } else {
286                 krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
287                                                &salt_principal,
288                                                io->domain->realm, io->u.sAMAccountName,
289                                                NULL);
290         }
291         if (krb5_ret) {
292                 ldb_asprintf_errstring(io->ac->module->ldb,
293                                        "setup_primary_kerberos: "
294                                        "generation of a salting principal failed: %s",
295                                        smb_get_krb5_error_message(io->smb_krb5_context->krb5_context, krb5_ret, io->ac));
296                 return LDB_ERR_OPERATIONS_ERROR;
297         }
298
299         /*
300          * create salt from salt_principal
301          */
302         krb5_ret = krb5_get_pw_salt(io->smb_krb5_context->krb5_context,
303                                     salt_principal, &salt);
304         krb5_free_principal(io->smb_krb5_context->krb5_context, salt_principal);
305         if (krb5_ret) {
306                 ldb_asprintf_errstring(io->ac->module->ldb,
307                                        "setup_primary_kerberos: "
308                                        "generation of krb5_salt failed: %s",
309                                        smb_get_krb5_error_message(io->smb_krb5_context->krb5_context, krb5_ret, io->ac));
310                 return LDB_ERR_OPERATIONS_ERROR;
311         }
312         /* create a talloc copy */
313         pkb3->salt.string = talloc_strndup(io->ac,
314                                           salt.saltvalue.data,
315                                           salt.saltvalue.length);
316         krb5_free_salt(io->smb_krb5_context->krb5_context, salt);
317         if (!pkb3->salt.string) {
318                 ldb_oom(io->ac->module->ldb);
319                 return LDB_ERR_OPERATIONS_ERROR;
320         }
321         salt.saltvalue.data     = discard_const(pkb3->salt.string);
322         salt.saltvalue.length   = strlen(pkb3->salt.string);
323
324         /*
325          * prepare generation of keys
326          *
327          * ENCTYPE_AES256_CTS_HMAC_SHA1_96 (disabled by default)
328          * ENCTYPE_DES_CBC_MD5
329          * ENCTYPE_DES_CBC_CRC
330          *
331          * NOTE: update num_keys when you add another enctype!
332          */
333         pkb3->num_keys  = 3;
334         pkb3->keys      = talloc_array(io->ac, struct package_PrimaryKerberosKey, pkb3->num_keys);
335         if (!pkb3->keys) {
336                 ldb_oom(io->ac->module->ldb);
337                 return LDB_ERR_OPERATIONS_ERROR;
338         }
339
340         if (lp_parm_bool(ldb_get_opaque(io->ac->module->ldb, "loadparm"), NULL, "password_hash", "create_aes_key", false)) {
341         /*
342          * TODO:
343          *
344          * w2k and w2k3 doesn't support AES, so we'll not include
345          * the AES key here yet.
346          *
347          * Also we don't have an example supplementalCredentials blob
348          * from Windows Longhorn Server with AES support
349          *
350          */
351         /*
352          * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
353          * the salt and the cleartext password
354          */
355         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
356                                            ENCTYPE_AES256_CTS_HMAC_SHA1_96,
357                                            io->n.cleartext,
358                                            salt,
359                                            &key);
360         pkb3->keys[k].keytype   = ENCTYPE_AES256_CTS_HMAC_SHA1_96;
361         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
362         if (!pkb3->keys[k].value) {
363                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
364                 ldb_oom(io->ac->module->ldb);
365                 return LDB_ERR_OPERATIONS_ERROR;
366         }
367         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
368                                                    key.keyvalue.data,
369                                                    key.keyvalue.length);
370         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
371         if (!pkb3->keys[k].value->data) {
372                 ldb_oom(io->ac->module->ldb);
373                 return LDB_ERR_OPERATIONS_ERROR;
374         }
375         k++;
376 }
377
378         /*
379          * create ENCTYPE_DES_CBC_MD5 key out of
380          * the salt and the cleartext password
381          */
382         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
383                                            ENCTYPE_DES_CBC_MD5,
384                                            io->n.cleartext,
385                                            salt,
386                                            &key);
387         pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_MD5;
388         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
389         if (!pkb3->keys[k].value) {
390                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
391                 ldb_oom(io->ac->module->ldb);
392                 return LDB_ERR_OPERATIONS_ERROR;
393         }
394         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
395                                                    key.keyvalue.data,
396                                                    key.keyvalue.length);
397         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
398         if (!pkb3->keys[k].value->data) {
399                 ldb_oom(io->ac->module->ldb);
400                 return LDB_ERR_OPERATIONS_ERROR;
401         }
402         k++;
403
404         /*
405          * create ENCTYPE_DES_CBC_CRC key out of
406          * the salt and the cleartext password
407          */
408         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
409                                            ENCTYPE_DES_CBC_CRC,
410                                            io->n.cleartext,
411                                            salt,
412                                            &key);
413         pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_CRC;
414         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
415         if (!pkb3->keys[k].value) {
416                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
417                 ldb_oom(io->ac->module->ldb);
418                 return LDB_ERR_OPERATIONS_ERROR;
419         }
420         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
421                                                    key.keyvalue.data,
422                                                    key.keyvalue.length);
423         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
424         if (!pkb3->keys[k].value->data) {
425                 ldb_oom(io->ac->module->ldb);
426                 return LDB_ERR_OPERATIONS_ERROR;
427         }
428         k++;
429
430         /* fix up key number */
431         pkb3->num_keys = k;
432
433         /* initialize the old keys to zero */
434         pkb3->num_old_keys      = 0;
435         pkb3->old_keys          = NULL;
436
437         /* if there're no old keys, then we're done */
438         if (!old_scb) {
439                 return LDB_SUCCESS;
440         }
441
442         for (i=0; i < old_scb->sub.num_packages; i++) {
443                 if (strcmp("Primary:Kerberos", old_scb->sub.packages[i].name) != 0) {
444                         continue;
445                 }
446
447                 if (!old_scb->sub.packages[i].data || !old_scb->sub.packages[i].data[0]) {
448                         continue;
449                 }
450
451                 old_scp = &old_scb->sub.packages[i];
452                 break;
453         }
454         /* Primary:Kerberos element of supplementalCredentials */
455         if (old_scp) {
456                 DATA_BLOB blob;
457
458                 blob = strhex_to_data_blob(old_scp->data);
459                 if (!blob.data) {
460                         ldb_oom(io->ac->module->ldb);
461                         return LDB_ERR_OPERATIONS_ERROR;
462                 }
463                 talloc_steal(io->ac, blob.data);
464
465                 /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
466                 ndr_err = ndr_pull_struct_blob(&blob, io->ac, lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")), &_old_pkb,
467                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
468                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
469                         NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
470                         ldb_asprintf_errstring(io->ac->module->ldb,
471                                                "setup_primary_kerberos: "
472                                                "failed to pull old package_PrimaryKerberosBlob: %s",
473                                                nt_errstr(status));
474                         return LDB_ERR_OPERATIONS_ERROR;
475                 }
476
477                 if (_old_pkb.version != 3) {
478                         ldb_asprintf_errstring(io->ac->module->ldb,
479                                                "setup_primary_kerberos: "
480                                                "package_PrimaryKerberosBlob version[%u] expected[3]",
481                                                _old_pkb.version);
482                         return LDB_ERR_OPERATIONS_ERROR;
483                 }
484
485                 old_pkb3 = &_old_pkb.ctr.ctr3;
486         }
487
488         /* if we didn't found the old keys we're done */
489         if (!old_pkb3) {
490                 return LDB_SUCCESS;
491         }
492
493         /* fill in the old keys */
494         pkb3->num_old_keys      = old_pkb3->num_keys;
495         pkb3->old_keys          = old_pkb3->keys;
496
497         return LDB_SUCCESS;
498 }
499
500 static int setup_primary_wdigest(struct setup_password_fields_io *io,
501                                  const struct supplementalCredentialsBlob *old_scb,
502                                  struct package_PrimaryWDigestBlob *pdb)
503 {
504         DATA_BLOB sAMAccountName;
505         DATA_BLOB sAMAccountName_l;
506         DATA_BLOB sAMAccountName_u;
507         const char *user_principal_name = io->u.user_principal_name;
508         DATA_BLOB userPrincipalName;
509         DATA_BLOB userPrincipalName_l;
510         DATA_BLOB userPrincipalName_u;
511         DATA_BLOB netbios_domain;
512         DATA_BLOB netbios_domain_l;
513         DATA_BLOB netbios_domain_u;
514         DATA_BLOB dns_domain;
515         DATA_BLOB dns_domain_l;
516         DATA_BLOB dns_domain_u;
517         DATA_BLOB cleartext;
518         DATA_BLOB digest;
519         DATA_BLOB delim;
520         DATA_BLOB backslash;
521         uint8_t i;
522         struct {
523                 DATA_BLOB *user;
524                 DATA_BLOB *realm;
525                 DATA_BLOB *nt4dom;
526         } wdigest[] = {
527         /*
528          * See
529          * http://technet2.microsoft.com/WindowsServer/en/library/717b450c-f4a0-4cc9-86f4-cc0633aae5f91033.mspx?mfr=true
530          * for what precalculated hashes are supposed to be stored...
531          *
532          * I can't reproduce all values which should contain "Digest" as realm,
533          * am I doing something wrong or is w2k3 just broken...?
534          *
535          * W2K3 fills in following for a user:
536          *
537          * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
538          * sAMAccountName: NewUser2Sam
539          * userPrincipalName: NewUser2Princ@sub1.w2k3.vmnet1.vm.base
540          *
541          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
542          * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
543          * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
544          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
545          * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
546          * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
547          * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
548          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
549          * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
550          * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
551          * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
552          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
553          * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
554          * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
555          * 221c55284451ae9b3aacaa2a3c86f10f => NewUser2Princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
556          * 74e1be668853d4324d38c07e2acfb8ea => (w2k3 has a bug here!) newuser2princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
557          * e1e244ab7f098e3ae1761be7f9229bbb => NEWUSER2PRINC@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
558          * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
559          * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
560          * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
561          * 31dc704d3640335b2123d4ee28aa1f11 => ??? changes with NewUser2Sam => NewUser1Sam
562          * 36349f5cecd07320fb3bb0e119230c43 => ??? changes with NewUser2Sam => NewUser1Sam
563          * 12adf019d037fb535c01fd0608e78d9d => ??? changes with NewUser2Sam => NewUser1Sam
564          * 6feecf8e724906f3ee1105819c5105a1 => ??? changes with NewUser2Princ => NewUser1Princ
565          * 6c6911f3de6333422640221b9c51ff1f => ??? changes with NewUser2Princ => NewUser1Princ
566          * 4b279877e742895f9348ac67a8de2f69 => ??? changes with NewUser2Princ => NewUser1Princ
567          * db0c6bff069513e3ebb9870d29b57490 => ??? changes with NewUser2Sam => NewUser1Sam
568          * 45072621e56b1c113a4e04a8ff68cd0e => ??? changes with NewUser2Sam => NewUser1Sam
569          * 11d1220abc44a9c10cf91ef4a9c1de02 => ??? changes with NewUser2Sam => NewUser1Sam
570          *
571          * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
572          * sAMAccountName: NewUser2Sam
573          *
574          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
575          * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
576          * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
577          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
578          * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
579          * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
580          * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
581          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
582          * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
583          * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
584          * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
585          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
586          * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
587          * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
588          * 8a140d30b6f0a5912735dc1e3bc993b4 => NewUser2Sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
589          * 86d95b2faae6cae4ec261e7fbaccf093 => (here w2k3 is correct) newuser2sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
590          * dfeff1493110220efcdfc6362e5f5450 => NEWUSER2SAM@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
591          * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
592          * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
593          * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
594          * 31dc704d3640335b2123d4ee28aa1f11 => ???M1   changes with NewUser2Sam => NewUser1Sam
595          * 36349f5cecd07320fb3bb0e119230c43 => ???M1.L changes with newuser2sam => newuser1sam
596          * 12adf019d037fb535c01fd0608e78d9d => ???M1.U changes with NEWUSER2SAM => NEWUSER1SAM
597          * 569b4533f2d9e580211dd040e5e360a8 => ???M2   changes with NewUser2Princ => NewUser1Princ
598          * 52528bddf310a587c5d7e6a9ae2cbb20 => ???M2.L changes with newuser2princ => newuser1princ
599          * 4f629a4f0361289ca4255ab0f658fcd5 => ???M3 changes with NewUser2Princ => NewUser1Princ (doesn't depend on case of userPrincipal )
600          * db0c6bff069513e3ebb9870d29b57490 => ???M4 changes with NewUser2Sam => NewUser1Sam
601          * 45072621e56b1c113a4e04a8ff68cd0e => ???M5 changes with NewUser2Sam => NewUser1Sam (doesn't depend on case of sAMAccountName)
602          * 11d1220abc44a9c10cf91ef4a9c1de02 => ???M4.U changes with NEWUSER2SAM => NEWUSER1SAM
603          */
604
605         /*
606          * sAMAccountName, netbios_domain
607          */
608                 {
609                 .user   = &sAMAccountName,
610                 .realm  = &netbios_domain,
611                 },
612                 {
613                 .user   = &sAMAccountName_l,
614                 .realm  = &netbios_domain_l,
615                 },
616                 {
617                 .user   = &sAMAccountName_u,
618                 .realm  = &netbios_domain_u,
619                 },
620                 {
621                 .user   = &sAMAccountName,
622                 .realm  = &netbios_domain_u,
623                 },
624                 {
625                 .user   = &sAMAccountName,
626                 .realm  = &netbios_domain_l,
627                 },
628                 {
629                 .user   = &sAMAccountName_u,
630                 .realm  = &netbios_domain_l,
631                 },
632                 {
633                 .user   = &sAMAccountName_l,
634                 .realm  = &netbios_domain_u,
635                 },
636         /* 
637          * sAMAccountName, dns_domain
638          */
639                 {
640                 .user   = &sAMAccountName,
641                 .realm  = &dns_domain,
642                 },
643                 {
644                 .user   = &sAMAccountName_l,
645                 .realm  = &dns_domain_l,
646                 },
647                 {
648                 .user   = &sAMAccountName_u,
649                 .realm  = &dns_domain_u,
650                 },
651                 {
652                 .user   = &sAMAccountName,
653                 .realm  = &dns_domain_u,
654                 },
655                 {
656                 .user   = &sAMAccountName,
657                 .realm  = &dns_domain_l,
658                 },
659                 {
660                 .user   = &sAMAccountName_u,
661                 .realm  = &dns_domain_l,
662                 },
663                 {
664                 .user   = &sAMAccountName_l,
665                 .realm  = &dns_domain_u,
666                 },
667         /* 
668          * userPrincipalName, no realm
669          */
670                 {
671                 .user   = &userPrincipalName,
672                 },
673                 {
674                 /* 
675                  * NOTE: w2k3 messes this up, if the user has a real userPrincipalName,
676                  *       the fallback to the sAMAccountName based userPrincipalName is correct
677                  */
678                 .user   = &userPrincipalName_l,
679                 },
680                 {
681                 .user   = &userPrincipalName_u,
682                 },
683         /* 
684          * nt4dom\sAMAccountName, no realm
685          */
686                 {
687                 .user   = &sAMAccountName,
688                 .nt4dom = &netbios_domain
689                 },
690                 {
691                 .user   = &sAMAccountName_l,
692                 .nt4dom = &netbios_domain_l
693                 },
694                 {
695                 .user   = &sAMAccountName_u,
696                 .nt4dom = &netbios_domain_u
697                 },
698
699         /*
700          * the following ones are guessed depending on the technet2 article
701          * but not reproducable on a w2k3 server
702          */
703         /* sAMAccountName with "Digest" realm */
704                 {
705                 .user   = &sAMAccountName,
706                 .realm  = &digest
707                 },
708                 {
709                 .user   = &sAMAccountName_l,
710                 .realm  = &digest
711                 },
712                 {
713                 .user   = &sAMAccountName_u,
714                 .realm  = &digest
715                 },
716         /* userPrincipalName with "Digest" realm */
717                 {
718                 .user   = &userPrincipalName,
719                 .realm  = &digest
720                 },
721                 {
722                 .user   = &userPrincipalName_l,
723                 .realm  = &digest
724                 },
725                 {
726                 .user   = &userPrincipalName_u,
727                 .realm  = &digest
728                 },
729         /* nt4dom\\sAMAccountName with "Digest" realm */
730                 {
731                 .user   = &sAMAccountName,
732                 .nt4dom = &netbios_domain,
733                 .realm  = &digest
734                 },
735                 {
736                 .user   = &sAMAccountName_l,
737                 .nt4dom = &netbios_domain_l,
738                 .realm  = &digest
739                 },
740                 {
741                 .user   = &sAMAccountName_u,
742                 .nt4dom = &netbios_domain_u,
743                 .realm  = &digest
744                 },
745         };
746
747         /* prepare DATA_BLOB's used in the combinations array */
748         sAMAccountName          = data_blob_string_const(io->u.sAMAccountName);
749         sAMAccountName_l        = data_blob_string_const(strlower_talloc(io->ac, io->u.sAMAccountName));
750         if (!sAMAccountName_l.data) {
751                 ldb_oom(io->ac->module->ldb);
752                 return LDB_ERR_OPERATIONS_ERROR;
753         }
754         sAMAccountName_u        = data_blob_string_const(strupper_talloc(io->ac, io->u.sAMAccountName));
755         if (!sAMAccountName_u.data) {
756                 ldb_oom(io->ac->module->ldb);
757                 return LDB_ERR_OPERATIONS_ERROR;
758         }
759
760         /* if the user doesn't have a userPrincipalName, create one (with lower case realm) */
761         if (!user_principal_name) {
762                 user_principal_name = talloc_asprintf(io->ac, "%s@%s",
763                                                       io->u.sAMAccountName,
764                                                       io->domain->dns_domain);
765                 if (!user_principal_name) {
766                         ldb_oom(io->ac->module->ldb);
767                         return LDB_ERR_OPERATIONS_ERROR;
768                 }       
769         }
770         userPrincipalName       = data_blob_string_const(user_principal_name);
771         userPrincipalName_l     = data_blob_string_const(strlower_talloc(io->ac, user_principal_name));
772         if (!userPrincipalName_l.data) {
773                 ldb_oom(io->ac->module->ldb);
774                 return LDB_ERR_OPERATIONS_ERROR;
775         }
776         userPrincipalName_u     = data_blob_string_const(strupper_talloc(io->ac, user_principal_name));
777         if (!userPrincipalName_u.data) {
778                 ldb_oom(io->ac->module->ldb);
779                 return LDB_ERR_OPERATIONS_ERROR;
780         }
781
782         netbios_domain          = data_blob_string_const(io->domain->netbios_domain);
783         netbios_domain_l        = data_blob_string_const(strlower_talloc(io->ac, io->domain->netbios_domain));
784         if (!netbios_domain_l.data) {
785                 ldb_oom(io->ac->module->ldb);
786                 return LDB_ERR_OPERATIONS_ERROR;
787         }
788         netbios_domain_u        = data_blob_string_const(strupper_talloc(io->ac, io->domain->netbios_domain));
789         if (!netbios_domain_u.data) {
790                 ldb_oom(io->ac->module->ldb);
791                 return LDB_ERR_OPERATIONS_ERROR;
792         }
793
794         dns_domain              = data_blob_string_const(io->domain->dns_domain);
795         dns_domain_l            = data_blob_string_const(io->domain->dns_domain);
796         dns_domain_u            = data_blob_string_const(io->domain->realm);
797
798         cleartext               = data_blob_string_const(io->n.cleartext);
799
800         digest                  = data_blob_string_const("Digest");
801
802         delim                   = data_blob_string_const(":");
803         backslash               = data_blob_string_const("\\");
804
805         pdb->num_hashes = ARRAY_SIZE(wdigest);
806         pdb->hashes     = talloc_array(io->ac, struct package_PrimaryWDigestHash, pdb->num_hashes);
807         if (!pdb->hashes) {
808                 ldb_oom(io->ac->module->ldb);
809                 return LDB_ERR_OPERATIONS_ERROR;
810         }
811
812         for (i=0; i < ARRAY_SIZE(wdigest); i++) {
813                 struct MD5Context md5;
814                 MD5Init(&md5);
815                 if (wdigest[i].nt4dom) {
816                         MD5Update(&md5, wdigest[i].nt4dom->data, wdigest[i].nt4dom->length);
817                         MD5Update(&md5, backslash.data, backslash.length);
818                 }
819                 MD5Update(&md5, wdigest[i].user->data, wdigest[i].user->length);
820                 MD5Update(&md5, delim.data, delim.length);
821                 if (wdigest[i].realm) {
822                         MD5Update(&md5, wdigest[i].realm->data, wdigest[i].realm->length);
823                 }
824                 MD5Update(&md5, delim.data, delim.length);
825                 MD5Update(&md5, cleartext.data, cleartext.length);
826                 MD5Final(pdb->hashes[i].hash, &md5);
827         }
828
829         return LDB_SUCCESS;
830 }
831
832 static int setup_supplemental_field(struct setup_password_fields_io *io)
833 {
834         struct supplementalCredentialsBlob scb;
835         struct supplementalCredentialsBlob _old_scb;
836         struct supplementalCredentialsBlob *old_scb = NULL;
837         /* Packages + (Kerberos, WDigest and maybe CLEARTEXT) */
838         uint32_t num_packages = 1 + 2;
839         struct supplementalCredentialsPackage packages[1+3];
840         struct supplementalCredentialsPackage *pp = &packages[0];
841         struct supplementalCredentialsPackage *pk = &packages[1];
842         struct supplementalCredentialsPackage *pd = &packages[2];
843         struct supplementalCredentialsPackage *pc = NULL;
844         struct package_PackagesBlob pb;
845         DATA_BLOB pb_blob;
846         char *pb_hexstr;
847         struct package_PrimaryKerberosBlob pkb;
848         DATA_BLOB pkb_blob;
849         char *pkb_hexstr;
850         struct package_PrimaryWDigestBlob pdb;
851         DATA_BLOB pdb_blob;
852         char *pdb_hexstr;
853         struct package_PrimaryCLEARTEXTBlob pcb;
854         DATA_BLOB pcb_blob;
855         char *pcb_hexstr;
856         int ret;
857         enum ndr_err_code ndr_err;
858         uint8_t zero16[16];
859
860         ZERO_STRUCT(zero16);
861
862         if (!io->n.cleartext) {
863                 /* 
864                  * when we don't have a cleartext password
865                  * we can't setup a supplementalCredential value
866                  */
867                 return LDB_SUCCESS;
868         }
869
870         /* if there's an old supplementaCredentials blob then parse it */
871         if (io->o.supplemental) {
872                 ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac,
873                                                    lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
874                                                    &_old_scb,
875                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
876                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
877                         NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
878                         ldb_asprintf_errstring(io->ac->module->ldb,
879                                                "setup_supplemental_field: "
880                                                "failed to pull old supplementalCredentialsBlob: %s",
881                                                nt_errstr(status));
882                         return LDB_ERR_OPERATIONS_ERROR;
883                 }
884
885                 if (_old_scb.sub.signature == SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
886                         old_scb = &_old_scb;
887                 } else {
888                         ldb_debug(io->ac->module->ldb, LDB_DEBUG_ERROR,
889                                                "setup_supplemental_field: "
890                                                "supplementalCredentialsBlob signature[0x%04X] expected[0x%04X]",
891                                                _old_scb.sub.signature, SUPPLEMENTAL_CREDENTIALS_SIGNATURE);
892                 }
893         }
894
895         if (io->domain->store_cleartext &&
896             (io->u.user_account_control & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
897                 pc = &packages[3];
898                 num_packages++;
899         }
900
901         /* Kerberos, WDigest, CLEARTEXT and termination(counted by the Packages element) */
902         pb.names = talloc_zero_array(io->ac, const char *, num_packages);
903
904         /*
905          * setup 'Primary:Kerberos' element
906          */
907         pb.names[0] = "Kerberos";
908
909         ret = setup_primary_kerberos(io, old_scb, &pkb);
910         if (ret != LDB_SUCCESS) {
911                 return ret;
912         }
913
914         ndr_err = ndr_push_struct_blob(&pkb_blob, io->ac, 
915                                        lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
916                                        &pkb,
917                                        (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
918         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
919                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
920                 ldb_asprintf_errstring(io->ac->module->ldb,
921                                        "setup_supplemental_field: "
922                                        "failed to push package_PrimaryKerberosBlob: %s",
923                                        nt_errstr(status));
924                 return LDB_ERR_OPERATIONS_ERROR;
925         }
926         pkb_hexstr = data_blob_hex_string(io->ac, &pkb_blob);
927         if (!pkb_hexstr) {
928                 ldb_oom(io->ac->module->ldb);
929                 return LDB_ERR_OPERATIONS_ERROR;
930         }
931         pk->name        = "Primary:Kerberos";
932         pk->reserved    = 1;
933         pk->data        = pkb_hexstr;
934
935         /*
936          * setup 'Primary:WDigest' element
937          */
938         pb.names[1] = "WDigest";
939
940         ret = setup_primary_wdigest(io, old_scb, &pdb);
941         if (ret != LDB_SUCCESS) {
942                 return ret;
943         }
944
945         ndr_err = ndr_push_struct_blob(&pdb_blob, io->ac, 
946                                        lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
947                                        &pdb,
948                                        (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
949         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
950                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
951                 ldb_asprintf_errstring(io->ac->module->ldb,
952                                        "setup_supplemental_field: "
953                                        "failed to push package_PrimaryWDigestBlob: %s",
954                                        nt_errstr(status));
955                 return LDB_ERR_OPERATIONS_ERROR;
956         }
957         pdb_hexstr = data_blob_hex_string(io->ac, &pdb_blob);
958         if (!pdb_hexstr) {
959                 ldb_oom(io->ac->module->ldb);
960                 return LDB_ERR_OPERATIONS_ERROR;
961         }
962         pd->name        = "Primary:WDigest";
963         pd->reserved    = 1;
964         pd->data        = pdb_hexstr;
965
966         /*
967          * setup 'Primary:CLEARTEXT' element
968          */
969         if (pc) {
970                 pb.names[2]     = "CLEARTEXT";
971
972                 pcb.cleartext   = io->n.cleartext;
973
974                 ndr_err = ndr_push_struct_blob(&pcb_blob, io->ac, 
975                                                lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
976                                                &pcb,
977                                                (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
978                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
979                         NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
980                         ldb_asprintf_errstring(io->ac->module->ldb,
981                                                "setup_supplemental_field: "
982                                                "failed to push package_PrimaryCLEARTEXTBlob: %s",
983                                                nt_errstr(status));
984                         return LDB_ERR_OPERATIONS_ERROR;
985                 }
986                 pcb_hexstr = data_blob_hex_string(io->ac, &pcb_blob);
987                 if (!pcb_hexstr) {
988                         ldb_oom(io->ac->module->ldb);
989                         return LDB_ERR_OPERATIONS_ERROR;
990                 }
991                 pc->name        = "Primary:CLEARTEXT";
992                 pc->reserved    = 1;
993                 pc->data        = pcb_hexstr;
994         }
995
996         /*
997          * setup 'Packages' element
998          */
999         ndr_err = ndr_push_struct_blob(&pb_blob, io->ac, 
1000                                        lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")), 
1001                                        &pb,
1002                                        (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
1003         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1004                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
1005                 ldb_asprintf_errstring(io->ac->module->ldb,
1006                                        "setup_supplemental_field: "
1007                                        "failed to push package_PackagesBlob: %s",
1008                                        nt_errstr(status));
1009                 return LDB_ERR_OPERATIONS_ERROR;
1010         }
1011         pb_hexstr = data_blob_hex_string(io->ac, &pb_blob);
1012         if (!pb_hexstr) {
1013                 ldb_oom(io->ac->module->ldb);
1014                 return LDB_ERR_OPERATIONS_ERROR;
1015         }
1016         pp->name        = "Packages";
1017         pp->reserved    = 2;
1018         pp->data        = pb_hexstr;
1019
1020         /*
1021          * setup 'supplementalCredentials' value
1022          */
1023         scb.sub.num_packages    = num_packages;
1024         scb.sub.packages        = packages;
1025
1026         ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac, 
1027                                        lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
1028                                        &scb,
1029                                        (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
1030         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1031                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
1032                 ldb_asprintf_errstring(io->ac->module->ldb,
1033                                        "setup_supplemental_field: "
1034                                        "failed to push supplementalCredentialsBlob: %s",
1035                                        nt_errstr(status));
1036                 return LDB_ERR_OPERATIONS_ERROR;
1037         }
1038
1039         return LDB_SUCCESS;
1040 }
1041
1042 static int setup_last_set_field(struct setup_password_fields_io *io)
1043 {
1044         /* set it as now */
1045         unix_to_nt_time(&io->g.last_set, time(NULL));
1046
1047         return LDB_SUCCESS;
1048 }
1049
1050 static int setup_kvno_field(struct setup_password_fields_io *io)
1051 {
1052         /* increment by one */
1053         io->g.kvno = io->o.kvno + 1;
1054
1055         return LDB_SUCCESS;
1056 }
1057
1058 static int setup_password_fields(struct setup_password_fields_io *io)
1059 {
1060         bool ok;
1061         int ret;
1062
1063         /*
1064          * refuse the change if someone want to change the cleartext
1065          * and supply his own hashes at the same time...
1066          */
1067         if (io->n.cleartext && (io->n.nt_hash || io->n.lm_hash)) {
1068                 ldb_asprintf_errstring(io->ac->module->ldb,
1069                                        "setup_password_fields: "
1070                                        "it's only allowed to set the cleartext password or the password hashes");
1071                 return LDB_ERR_UNWILLING_TO_PERFORM;
1072         }
1073
1074         if (io->n.cleartext) {
1075                 struct samr_Password *hash;
1076
1077                 hash = talloc(io->ac, struct samr_Password);
1078                 if (!hash) {
1079                         ldb_oom(io->ac->module->ldb);
1080                         return LDB_ERR_OPERATIONS_ERROR;
1081                 }
1082
1083                 /* compute the new nt hash */
1084                 ok = E_md4hash(io->n.cleartext, hash->hash);
1085                 if (ok) {
1086                         io->n.nt_hash = hash;
1087                 } else {
1088                         ldb_asprintf_errstring(io->ac->module->ldb,
1089                                                "setup_password_fields: "
1090                                                "failed to generate nthash from cleartext password");
1091                         return LDB_ERR_OPERATIONS_ERROR;
1092                 }
1093         }
1094
1095         if (io->n.cleartext) {
1096                 struct samr_Password *hash;
1097
1098                 hash = talloc(io->ac, struct samr_Password);
1099                 if (!hash) {
1100                         ldb_oom(io->ac->module->ldb);
1101                         return LDB_ERR_OPERATIONS_ERROR;
1102                 }
1103
1104                 /* compute the new lm hash */
1105                 ok = E_deshash(io->n.cleartext, hash->hash);
1106                 if (ok) {
1107                         io->n.lm_hash = hash;
1108                 } else {
1109                         talloc_free(hash->hash);
1110                 }
1111         }
1112
1113         ret = setup_nt_fields(io);
1114         if (ret != 0) {
1115                 return ret;
1116         }
1117
1118         ret = setup_lm_fields(io);
1119         if (ret != 0) {
1120                 return ret;
1121         }
1122
1123         ret = setup_supplemental_field(io);
1124         if (ret != 0) {
1125                 return ret;
1126         }
1127
1128         ret = setup_last_set_field(io);
1129         if (ret != 0) {
1130                 return ret;
1131         }
1132
1133         ret = setup_kvno_field(io);
1134         if (ret != 0) {
1135                 return ret;
1136         }
1137
1138         return LDB_SUCCESS;
1139 }
1140
1141 static struct ldb_handle *ph_init_handle(struct ldb_request *req, struct ldb_module *module, enum ph_type type)
1142 {
1143         struct ph_context *ac;
1144         struct ldb_handle *h;
1145
1146         h = talloc_zero(req, struct ldb_handle);
1147         if (h == NULL) {
1148                 ldb_set_errstring(module->ldb, "Out of Memory");
1149                 return NULL;
1150         }
1151
1152         h->module = module;
1153
1154         ac = talloc_zero(h, struct ph_context);
1155         if (ac == NULL) {
1156                 ldb_set_errstring(module->ldb, "Out of Memory");
1157                 talloc_free(h);
1158                 return NULL;
1159         }
1160
1161         h->private_data = (void *)ac;
1162
1163         h->state = LDB_ASYNC_INIT;
1164         h->status = LDB_SUCCESS;
1165
1166         ac->type = type;
1167         ac->module = module;
1168         ac->orig_req = req;
1169
1170         return h;
1171 }
1172
1173 static int get_domain_data_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
1174 {
1175         struct ph_context *ac;
1176
1177         ac = talloc_get_type(context, struct ph_context);
1178
1179         /* we are interested only in the single reply (base search) we receive here */
1180         if (ares->type == LDB_REPLY_ENTRY) {
1181                 if (ac->dom_res != NULL) {
1182                         ldb_set_errstring(ldb, "Too many results");
1183                         talloc_free(ares);
1184                         return LDB_ERR_OPERATIONS_ERROR;
1185                 }
1186                 ac->dom_res = talloc_steal(ac, ares);
1187         } else {
1188                 talloc_free(ares);
1189         }
1190
1191         return LDB_SUCCESS;
1192 }
1193
1194 static int build_domain_data_request(struct ph_context *ac)
1195 {
1196         /* attrs[] is returned from this function in
1197            ac->dom_req->op.search.attrs, so it must be static, as
1198            otherwise the compiler can put it on the stack */
1199         static const char * const attrs[] = { "pwdProperties", "pwdHistoryLength", NULL };
1200         char *filter;
1201
1202         ac->dom_req = talloc_zero(ac, struct ldb_request);
1203         if (ac->dom_req == NULL) {
1204                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1205                 return LDB_ERR_OPERATIONS_ERROR;
1206         }
1207         ac->dom_req->operation = LDB_SEARCH;
1208         ac->dom_req->op.search.base = ldb_get_default_basedn(ac->module->ldb);
1209         ac->dom_req->op.search.scope = LDB_SCOPE_SUBTREE;
1210
1211         filter = talloc_asprintf(ac->dom_req,
1212                                  "(&(objectSid=%s)(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain)))", 
1213                                  ldap_encode_ndr_dom_sid(ac->dom_req, ac->domain_sid));
1214         if (filter == NULL) {
1215                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1216                 talloc_free(ac->dom_req);
1217                 return LDB_ERR_OPERATIONS_ERROR;
1218         }
1219
1220         ac->dom_req->op.search.tree = ldb_parse_tree(ac->dom_req, filter);
1221         if (ac->dom_req->op.search.tree == NULL) {
1222                 ldb_set_errstring(ac->module->ldb, "Invalid search filter");
1223                 talloc_free(ac->dom_req);
1224                 return LDB_ERR_OPERATIONS_ERROR;
1225         }
1226         ac->dom_req->op.search.attrs = attrs;
1227         ac->dom_req->controls = NULL;
1228         ac->dom_req->context = ac;
1229         ac->dom_req->callback = get_domain_data_callback;
1230         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->dom_req);
1231
1232         return LDB_SUCCESS;
1233 }
1234
1235 static struct domain_data *get_domain_data(struct ldb_module *module, void *ctx, struct ldb_reply *res)
1236 {
1237         struct domain_data *data;
1238         const char *tmp;
1239         struct ph_context *ac;
1240         char *p;
1241
1242         ac = talloc_get_type(ctx, struct ph_context);
1243
1244         data = talloc_zero(ac, struct domain_data);
1245         if (data == NULL) {
1246                 return NULL;
1247         }
1248
1249         if (res == NULL) {
1250                 ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Could not find this user's domain: %s!\n", dom_sid_string(data, ac->domain_sid));
1251                 talloc_free(data);
1252                 return NULL;
1253         }
1254
1255         data->pwdProperties= samdb_result_uint(res->message, "pwdProperties", 0);
1256         data->store_cleartext = data->pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;
1257         data->pwdHistoryLength = samdb_result_uint(res->message, "pwdHistoryLength", 0);
1258
1259         /* For a domain DN, this puts things in dotted notation */
1260         /* For builtin domains, this will give details for the host,
1261          * but that doesn't really matter, as it's just used for salt
1262          * and kerberos principals, which don't exist here */
1263
1264         tmp = ldb_dn_canonical_string(ctx, res->message->dn);
1265         if (!tmp) {
1266                 return NULL;
1267         }
1268         
1269         /* But it puts a trailing (or just before 'builtin') / on things, so kill that */
1270         p = strchr(tmp, '/');
1271         if (p) {
1272                 p[0] = '\0';
1273         }
1274
1275         if (tmp != NULL) {
1276                 data->dns_domain = strlower_talloc(data, tmp);
1277                 if (data->dns_domain == NULL) {
1278                         ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
1279                         return NULL;
1280                 }
1281                 data->realm = strupper_talloc(data, tmp);
1282                 if (data->realm == NULL) {
1283                         ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
1284                         return NULL;
1285                 }
1286                 p = strchr(tmp, '.');
1287                 if (p) {
1288                         p[0] = '\0';
1289                 }
1290                 data->netbios_domain = strupper_talloc(data, tmp);
1291                 if (data->netbios_domain == NULL) {
1292                         ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
1293                         return NULL;
1294                 }
1295         }
1296
1297         return data;
1298 }
1299
1300 static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
1301 {
1302         struct ldb_handle *h;
1303         struct ph_context *ac;
1304         struct ldb_message_element *sambaAttr;
1305         struct ldb_message_element *ntAttr;
1306         struct ldb_message_element *lmAttr;
1307         int ret;
1308
1309         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
1310
1311         if (ldb_dn_is_special(req->op.add.message->dn)) { /* do not manipulate our control entries */
1312                 return ldb_next_request(module, req);
1313         }
1314
1315         /* If the caller is manipulating the local passwords directly, let them pass */
1316         if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
1317                                 req->op.add.message->dn) == 0) {
1318                 return ldb_next_request(module, req);
1319         }
1320
1321         /* nobody must touch this fields */
1322         if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
1323                 return LDB_ERR_UNWILLING_TO_PERFORM;
1324         }
1325         if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
1326                 return LDB_ERR_UNWILLING_TO_PERFORM;
1327         }
1328         if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
1329                 return LDB_ERR_UNWILLING_TO_PERFORM;
1330         }
1331
1332         /* If no part of this ADD touches the userPassword, or the NT
1333          * or LM hashes, then we don't need to make any changes.  */
1334
1335         sambaAttr = ldb_msg_find_element(req->op.mod.message, "userPassword");
1336         ntAttr = ldb_msg_find_element(req->op.mod.message, "unicodePwd");
1337         lmAttr = ldb_msg_find_element(req->op.mod.message, "dBCSPwd");
1338
1339         if ((!sambaAttr) && (!ntAttr) && (!lmAttr)) {
1340                 return ldb_next_request(module, req);
1341         }
1342
1343         /* if it is not an entry of type person its an error */
1344         /* TODO: remove this when userPassword will be in schema */
1345         if (!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "person")) {
1346                 ldb_set_errstring(module->ldb, "Cannot set a password on entry that does not have objectClass 'person'");
1347                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1348         }
1349
1350         /* check userPassword is single valued here */
1351         /* TODO: remove this when userPassword will be single valued in schema */
1352         if (sambaAttr && sambaAttr->num_values > 1) {
1353                 ldb_set_errstring(module->ldb, "mupltiple values for userPassword not allowed!\n");
1354                 return LDB_ERR_CONSTRAINT_VIOLATION;
1355         }
1356
1357         if (ntAttr && (ntAttr->num_values > 1)) {
1358                 ldb_set_errstring(module->ldb, "mupltiple values for unicodePwd not allowed!\n");
1359                 return LDB_ERR_CONSTRAINT_VIOLATION;
1360         }
1361         if (lmAttr && (lmAttr->num_values > 1)) {
1362                 ldb_set_errstring(module->ldb, "mupltiple values for dBCSPwd not allowed!\n");
1363                 return LDB_ERR_CONSTRAINT_VIOLATION;
1364         }
1365
1366         if (sambaAttr && sambaAttr->num_values == 0) {
1367                 ldb_set_errstring(module->ldb, "userPassword must have a value!\n");
1368                 return LDB_ERR_CONSTRAINT_VIOLATION;
1369         }
1370
1371         if (ntAttr && (ntAttr->num_values == 0)) {
1372                 ldb_set_errstring(module->ldb, "unicodePwd must have a value!\n");
1373                 return LDB_ERR_CONSTRAINT_VIOLATION;
1374         }
1375         if (lmAttr && (lmAttr->num_values == 0)) {
1376                 ldb_set_errstring(module->ldb, "dBCSPwd must have a value!\n");
1377                 return LDB_ERR_CONSTRAINT_VIOLATION;
1378         }
1379
1380         h = ph_init_handle(req, module, PH_ADD);
1381         if (!h) {
1382                 return LDB_ERR_OPERATIONS_ERROR;
1383         }
1384         ac = talloc_get_type(h->private_data, struct ph_context);
1385
1386         /* get user domain data */
1387         ac->domain_sid = samdb_result_sid_prefix(ac, req->op.add.message, "objectSid");
1388         if (ac->domain_sid == NULL) {
1389                 ldb_debug(module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
1390                 return LDB_ERR_OPERATIONS_ERROR;
1391         }
1392
1393         ret = build_domain_data_request(ac);
1394         if (ret != LDB_SUCCESS) {
1395                 return ret;
1396         }
1397
1398         ac->step = PH_ADD_SEARCH_DOM;
1399
1400         req->handle = h;
1401
1402         return ldb_next_request(module, ac->dom_req);
1403 }
1404
1405 static int password_hash_add_do_add(struct ldb_handle *h) {
1406
1407         struct ph_context *ac;
1408         struct domain_data *domain;
1409         struct smb_krb5_context *smb_krb5_context;
1410         struct ldb_message *msg;
1411         struct setup_password_fields_io io;
1412         int ret;
1413
1414         ac = talloc_get_type(h->private_data, struct ph_context);
1415
1416         domain = get_domain_data(ac->module, ac, ac->dom_res);
1417         if (domain == NULL) {
1418                 return LDB_ERR_OPERATIONS_ERROR;
1419         }
1420
1421         ac->down_req = talloc(ac, struct ldb_request);
1422         if (ac->down_req == NULL) {
1423                 return LDB_ERR_OPERATIONS_ERROR;
1424         }
1425
1426         *(ac->down_req) = *(ac->orig_req);
1427         ac->down_req->op.add.message = msg = ldb_msg_copy_shallow(ac->down_req, ac->orig_req->op.add.message);
1428         if (ac->down_req->op.add.message == NULL) {
1429                 return LDB_ERR_OPERATIONS_ERROR;
1430         }
1431
1432         /* Some operations below require kerberos contexts */
1433         if (smb_krb5_init_context(ac->down_req, 
1434                                   ldb_get_opaque(h->module->ldb, "EventContext"), 
1435                                   (struct loadparm_context *)ldb_get_opaque(h->module->ldb, "loadparm"), 
1436                                   &smb_krb5_context) != 0) {
1437                 return LDB_ERR_OPERATIONS_ERROR;
1438         }
1439
1440         ZERO_STRUCT(io);
1441         io.ac                           = ac;
1442         io.domain                       = domain;
1443         io.smb_krb5_context             = smb_krb5_context;
1444
1445         io.u.user_account_control       = samdb_result_uint(msg, "userAccountControl", 0);
1446         io.u.sAMAccountName             = samdb_result_string(msg, "samAccountName", NULL);
1447         io.u.user_principal_name        = samdb_result_string(msg, "userPrincipalName", NULL);
1448         io.u.is_computer                = ldb_msg_check_string_attribute(msg, "objectClass", "computer");
1449
1450         io.n.cleartext                  = samdb_result_string(msg, "userPassword", NULL);
1451         io.n.nt_hash                    = samdb_result_hash(io.ac, msg, "unicodePwd");
1452         io.n.lm_hash                    = samdb_result_hash(io.ac, msg, "dBCSPwd");
1453
1454         /* remove attributes */
1455         if (io.n.cleartext) ldb_msg_remove_attr(msg, "userPassword");
1456         if (io.n.nt_hash) ldb_msg_remove_attr(msg, "unicodePwd");
1457         if (io.n.lm_hash) ldb_msg_remove_attr(msg, "dBCSPwd");
1458         ldb_msg_remove_attr(msg, "pwdLastSet");
1459         io.o.kvno = samdb_result_uint(msg, "msDs-KeyVersionNumber", 1) - 1;
1460         ldb_msg_remove_attr(msg, "msDs-KeyVersionNumber");
1461
1462         ret = setup_password_fields(&io);
1463         if (ret != LDB_SUCCESS) {
1464                 return ret;
1465         }
1466
1467         if (io.g.nt_hash) {
1468                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1469                                          "unicodePwd", io.g.nt_hash);
1470                 if (ret != LDB_SUCCESS) {
1471                         return ret;
1472                 }
1473         }
1474         if (io.g.lm_hash) {
1475                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1476                                          "dBCSPwd", io.g.lm_hash);
1477                 if (ret != LDB_SUCCESS) {
1478                         return ret;
1479                 }
1480         }
1481         if (io.g.nt_history_len > 0) {
1482                 ret = samdb_msg_add_hashes(ac, msg,
1483                                            "ntPwdHistory",
1484                                            io.g.nt_history,
1485                                            io.g.nt_history_len);
1486                 if (ret != LDB_SUCCESS) {
1487                         return ret;
1488                 }
1489         }
1490         if (io.g.lm_history_len > 0) {
1491                 ret = samdb_msg_add_hashes(ac, msg,
1492                                            "lmPwdHistory",
1493                                            io.g.lm_history,
1494                                            io.g.lm_history_len);
1495                 if (ret != LDB_SUCCESS) {
1496                         return ret;
1497                 }
1498         }
1499         if (io.g.supplemental.length > 0) {
1500                 ret = ldb_msg_add_value(msg, "supplementalCredentials",
1501                                         &io.g.supplemental, NULL);
1502                 if (ret != LDB_SUCCESS) {
1503                         return ret;
1504                 }
1505         }
1506         ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
1507                                    "pwdLastSet",
1508                                    io.g.last_set);
1509         if (ret != LDB_SUCCESS) {
1510                 return ret;
1511         }
1512         ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
1513                                  "msDs-KeyVersionNumber",
1514                                  io.g.kvno);
1515         if (ret != LDB_SUCCESS) {
1516                 return ret;
1517         }
1518
1519         h->state = LDB_ASYNC_INIT;
1520         h->status = LDB_SUCCESS;
1521
1522         ac->step = PH_ADD_DO_ADD;
1523
1524         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->down_req);
1525
1526         /* perform the operation */
1527         return ldb_next_request(ac->module, ac->down_req);
1528 }
1529
1530 static int password_hash_mod_search_self(struct ldb_handle *h);
1531
1532 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
1533 {
1534         struct ldb_handle *h;
1535         struct ph_context *ac;
1536         struct ldb_message_element *sambaAttr;
1537         struct ldb_message_element *ntAttr;
1538         struct ldb_message_element *lmAttr;
1539         struct ldb_message *msg;
1540
1541         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");
1542
1543         if (ldb_dn_is_special(req->op.mod.message->dn)) { /* do not manipulate our control entries */
1544                 return ldb_next_request(module, req);
1545         }
1546         
1547         /* If the caller is manipulating the local passwords directly, let them pass */
1548         if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
1549                                 req->op.mod.message->dn) == 0) {
1550                 return ldb_next_request(module, req);
1551         }
1552
1553         /* nobody must touch password Histories */
1554         if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
1555                 return LDB_ERR_UNWILLING_TO_PERFORM;
1556         }
1557         if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
1558                 return LDB_ERR_UNWILLING_TO_PERFORM;
1559         }
1560         if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
1561                 return LDB_ERR_UNWILLING_TO_PERFORM;
1562         }
1563
1564         sambaAttr = ldb_msg_find_element(req->op.mod.message, "userPassword");
1565         ntAttr = ldb_msg_find_element(req->op.mod.message, "unicodePwd");
1566         lmAttr = ldb_msg_find_element(req->op.mod.message, "dBCSPwd");
1567
1568         /* If no part of this touches the userPassword OR unicodePwd and/or dBCSPwd, then we don't
1569          * need to make any changes.  For password changes/set there should
1570          * be a 'delete' or a 'modify' on this attribute. */
1571         if ((!sambaAttr) && (!ntAttr) && (!lmAttr)) {
1572                 return ldb_next_request(module, req);
1573         }
1574
1575         /* check passwords are single valued here */
1576         /* TODO: remove this when passwords will be single valued in schema */
1577         if (sambaAttr && (sambaAttr->num_values > 1)) {
1578                 return LDB_ERR_CONSTRAINT_VIOLATION;
1579         }
1580         if (ntAttr && (ntAttr->num_values > 1)) {
1581                 return LDB_ERR_CONSTRAINT_VIOLATION;
1582         }
1583         if (lmAttr && (lmAttr->num_values > 1)) {
1584                 return LDB_ERR_CONSTRAINT_VIOLATION;
1585         }
1586
1587         h = ph_init_handle(req, module, PH_MOD);
1588         if (!h) {
1589                 return LDB_ERR_OPERATIONS_ERROR;
1590         }
1591         ac = talloc_get_type(h->private_data, struct ph_context);
1592
1593         /* return or own handle to deal with this call */
1594         req->handle = h;
1595
1596         /* prepare the first operation */
1597         ac->down_req = talloc_zero(ac, struct ldb_request);
1598         if (ac->down_req == NULL) {
1599                 ldb_set_errstring(module->ldb, "Out of memory!");
1600                 return LDB_ERR_OPERATIONS_ERROR;
1601         }
1602
1603         *(ac->down_req) = *req; /* copy the request */
1604
1605         /* use a new message structure so that we can modify it */
1606         ac->down_req->op.mod.message = msg = ldb_msg_copy_shallow(ac->down_req, req->op.mod.message);
1607
1608         /* - remove any imodification to the password from the first commit
1609          *   we will make the real modification later */
1610         if (sambaAttr) ldb_msg_remove_attr(msg, "userPassword");
1611         if (ntAttr) ldb_msg_remove_attr(msg, "unicodePwd");
1612         if (lmAttr) ldb_msg_remove_attr(msg, "dBCSPwd");
1613
1614         /* if there was nothing else to be modify skip to next step */
1615         if (msg->num_elements == 0) {
1616                 talloc_free(ac->down_req);
1617                 ac->down_req = NULL;
1618                 return password_hash_mod_search_self(h);
1619         }
1620         
1621         ac->down_req->context = NULL;
1622         ac->down_req->callback = NULL;
1623
1624         ac->step = PH_MOD_DO_REQ;
1625
1626         ldb_set_timeout_from_prev_req(module->ldb, req, ac->down_req);
1627
1628         return ldb_next_request(module, ac->down_req);
1629 }
1630
1631 static int get_self_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
1632 {
1633         struct ph_context *ac;
1634
1635         ac = talloc_get_type(context, struct ph_context);
1636
1637         /* we are interested only in the single reply (base search) we receive here */
1638         if (ares->type == LDB_REPLY_ENTRY) {
1639                 if (ac->search_res != NULL) {
1640                         ldb_set_errstring(ldb, "Too many results");
1641                         talloc_free(ares);
1642                         return LDB_ERR_OPERATIONS_ERROR;
1643                 }
1644
1645                 /* if it is not an entry of type person this is an error */
1646                 /* TODO: remove this when userPassword will be in schema */
1647                 if (!ldb_msg_check_string_attribute(ares->message, "objectClass", "person")) {
1648                         ldb_set_errstring(ldb, "Object class violation");
1649                         talloc_free(ares);
1650                         return LDB_ERR_OBJECT_CLASS_VIOLATION;
1651                 }
1652
1653                 ac->search_res = talloc_steal(ac, ares);
1654         } else {
1655                 talloc_free(ares);
1656         }
1657
1658         return LDB_SUCCESS;
1659 }
1660
1661 static int password_hash_mod_search_self(struct ldb_handle *h) {
1662
1663         struct ph_context *ac;
1664         static const char * const attrs[] = { "userAccountControl", "lmPwdHistory", 
1665                                               "ntPwdHistory", 
1666                                               "objectSid", "msDS-KeyVersionNumber", 
1667                                               "objectClass", "userPrincipalName",
1668                                               "sAMAccountName", 
1669                                               "dBCSPwd", "unicodePwd",
1670                                               "supplementalCredentials",
1671                                               NULL };
1672
1673         ac = talloc_get_type(h->private_data, struct ph_context);
1674
1675         /* prepare the search operation */
1676         ac->search_req = talloc_zero(ac, struct ldb_request);
1677         if (ac->search_req == NULL) {
1678                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1679                 return LDB_ERR_OPERATIONS_ERROR;
1680         }
1681
1682         ac->search_req->operation = LDB_SEARCH;
1683         ac->search_req->op.search.base = ac->orig_req->op.mod.message->dn;
1684         ac->search_req->op.search.scope = LDB_SCOPE_BASE;
1685         ac->search_req->op.search.tree = ldb_parse_tree(ac->search_req, NULL);
1686         if (ac->search_req->op.search.tree == NULL) {
1687                 ldb_set_errstring(ac->module->ldb, "Invalid search filter");
1688                 return LDB_ERR_OPERATIONS_ERROR;
1689         }
1690         ac->search_req->op.search.attrs = attrs;
1691         ac->search_req->controls = NULL;
1692         ac->search_req->context = ac;
1693         ac->search_req->callback = get_self_callback;
1694         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
1695
1696         ac->step = PH_MOD_SEARCH_SELF;
1697
1698         return ldb_next_request(ac->module, ac->search_req);
1699 }
1700
1701 static int password_hash_mod_search_dom(struct ldb_handle *h) {
1702
1703         struct ph_context *ac;
1704         int ret;
1705
1706         ac = talloc_get_type(h->private_data, struct ph_context);
1707
1708         /* get object domain sid */
1709         ac->domain_sid = samdb_result_sid_prefix(ac, ac->search_res->message, "objectSid");
1710         if (ac->domain_sid == NULL) {
1711                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
1712                 return LDB_ERR_OPERATIONS_ERROR;
1713         }
1714
1715         /* get user domain data */
1716         ret = build_domain_data_request(ac);
1717         if (ret != LDB_SUCCESS) {
1718                 return ret;
1719         }
1720
1721         ac->step = PH_MOD_SEARCH_DOM;
1722
1723         return ldb_next_request(ac->module, ac->dom_req);
1724 }
1725
1726 static int password_hash_mod_do_mod(struct ldb_handle *h) {
1727
1728         struct ph_context *ac;
1729         struct domain_data *domain;
1730         struct smb_krb5_context *smb_krb5_context;
1731         struct ldb_message *msg;
1732         struct ldb_message *orig_msg;
1733         struct ldb_message *searched_msg;
1734         struct setup_password_fields_io io;
1735         int ret;
1736
1737         ac = talloc_get_type(h->private_data, struct ph_context);
1738
1739         domain = get_domain_data(ac->module, ac, ac->dom_res);
1740         if (domain == NULL) {
1741                 return LDB_ERR_OPERATIONS_ERROR;
1742         }
1743
1744         ac->mod_req = talloc(ac, struct ldb_request);
1745         if (ac->mod_req == NULL) {
1746                 return LDB_ERR_OPERATIONS_ERROR;
1747         }
1748
1749         *(ac->mod_req) = *(ac->orig_req);
1750         
1751         /* use a new message structure so that we can modify it */
1752         ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
1753         if (msg == NULL) {
1754                 return LDB_ERR_OPERATIONS_ERROR;
1755         }
1756
1757         /* modify dn */
1758         msg->dn = ac->orig_req->op.mod.message->dn;
1759
1760         /* Some operations below require kerberos contexts */
1761         if (smb_krb5_init_context(ac->mod_req, 
1762                                   ldb_get_opaque(h->module->ldb, "EventContext"), 
1763                                   (struct loadparm_context *)ldb_get_opaque(h->module->ldb, "loadparm"), 
1764                                   &smb_krb5_context) != 0) {
1765                 return LDB_ERR_OPERATIONS_ERROR;
1766         }
1767
1768         orig_msg        = discard_const(ac->orig_req->op.mod.message);
1769         searched_msg    = ac->search_res->message;
1770
1771         ZERO_STRUCT(io);
1772         io.ac                           = ac;
1773         io.domain                       = domain;
1774         io.smb_krb5_context             = smb_krb5_context;
1775
1776         io.u.user_account_control       = samdb_result_uint(searched_msg, "userAccountControl", 0);
1777         io.u.sAMAccountName             = samdb_result_string(searched_msg, "samAccountName", NULL);
1778         io.u.user_principal_name        = samdb_result_string(searched_msg, "userPrincipalName", NULL);
1779         io.u.is_computer                = ldb_msg_check_string_attribute(searched_msg, "objectClass", "computer");
1780
1781         io.n.cleartext                  = samdb_result_string(orig_msg, "userPassword", NULL);
1782         io.n.nt_hash                    = samdb_result_hash(io.ac, orig_msg, "unicodePwd");
1783         io.n.lm_hash                    = samdb_result_hash(io.ac, orig_msg, "dBCSPwd");
1784
1785         io.o.kvno                       = samdb_result_uint(searched_msg, "msDs-KeyVersionNumber", 0);
1786         io.o.nt_history_len             = samdb_result_hashes(io.ac, searched_msg, "ntPwdHistory", &io.o.nt_history);
1787         io.o.lm_history_len             = samdb_result_hashes(io.ac, searched_msg, "lmPwdHistory", &io.o.lm_history);
1788         io.o.supplemental               = ldb_msg_find_ldb_val(searched_msg, "supplementalCredentials");
1789
1790         ret = setup_password_fields(&io);
1791         if (ret != LDB_SUCCESS) {
1792                 return ret;
1793         }
1794
1795         /* make sure we replace all the old attributes */
1796         ret = ldb_msg_add_empty(msg, "unicodePwd", LDB_FLAG_MOD_REPLACE, NULL);
1797         ret = ldb_msg_add_empty(msg, "dBCSPwd", LDB_FLAG_MOD_REPLACE, NULL);
1798         ret = ldb_msg_add_empty(msg, "ntPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1799         ret = ldb_msg_add_empty(msg, "lmPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1800         ret = ldb_msg_add_empty(msg, "supplementalCredentials", LDB_FLAG_MOD_REPLACE, NULL);
1801         ret = ldb_msg_add_empty(msg, "pwdLastSet", LDB_FLAG_MOD_REPLACE, NULL);
1802         ret = ldb_msg_add_empty(msg, "msDs-KeyVersionNumber", LDB_FLAG_MOD_REPLACE, NULL);
1803
1804         if (io.g.nt_hash) {
1805                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1806                                          "unicodePwd", io.g.nt_hash);
1807                 if (ret != LDB_SUCCESS) {
1808                         return ret;
1809                 }
1810         }
1811         if (io.g.lm_hash) {
1812                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1813                                          "dBCSPwd", io.g.lm_hash);
1814                 if (ret != LDB_SUCCESS) {
1815                         return ret;
1816                 }
1817         }
1818         if (io.g.nt_history_len > 0) {
1819                 ret = samdb_msg_add_hashes(ac, msg,
1820                                            "ntPwdHistory",
1821                                            io.g.nt_history,
1822                                            io.g.nt_history_len);
1823                 if (ret != LDB_SUCCESS) {
1824                         return ret;
1825                 }
1826         }
1827         if (io.g.lm_history_len > 0) {
1828                 ret = samdb_msg_add_hashes(ac, msg,
1829                                            "lmPwdHistory",
1830                                            io.g.lm_history,
1831                                            io.g.lm_history_len);
1832                 if (ret != LDB_SUCCESS) {
1833                         return ret;
1834                 }
1835         }
1836         if (io.g.supplemental.length > 0) {
1837                 ret = ldb_msg_add_value(msg, "supplementalCredentials",
1838                                         &io.g.supplemental, NULL);
1839                 if (ret != LDB_SUCCESS) {
1840                         return ret;
1841                 }
1842         }
1843         ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
1844                                    "pwdLastSet",
1845                                    io.g.last_set);
1846         if (ret != LDB_SUCCESS) {
1847                 return ret;
1848         }
1849         ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
1850                                  "msDs-KeyVersionNumber",
1851                                  io.g.kvno);
1852         if (ret != LDB_SUCCESS) {
1853                 return ret;
1854         }
1855
1856         h->state = LDB_ASYNC_INIT;
1857         h->status = LDB_SUCCESS;
1858
1859         ac->step = PH_MOD_DO_MOD;
1860
1861         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
1862
1863         /* perform the search */
1864         return ldb_next_request(ac->module, ac->mod_req);
1865 }
1866
1867 static int ph_wait(struct ldb_handle *handle) {
1868         struct ph_context *ac;
1869         int ret;
1870     
1871         if (!handle || !handle->private_data) {
1872                 return LDB_ERR_OPERATIONS_ERROR;
1873         }
1874
1875         if (handle->state == LDB_ASYNC_DONE) {
1876                 return handle->status;
1877         }
1878
1879         handle->state = LDB_ASYNC_PENDING;
1880         handle->status = LDB_SUCCESS;
1881
1882         ac = talloc_get_type(handle->private_data, struct ph_context);
1883
1884         switch (ac->step) {
1885         case PH_ADD_SEARCH_DOM:
1886                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1887
1888                 if (ret != LDB_SUCCESS) {
1889                         handle->status = ret;
1890                         goto done;
1891                 }
1892                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1893                         handle->status = ac->dom_req->handle->status;
1894                         goto done;
1895                 }
1896
1897                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1898                         return LDB_SUCCESS;
1899                 }
1900
1901                 /* domain search done, go on */
1902                 return password_hash_add_do_add(handle);
1903
1904         case PH_ADD_DO_ADD:
1905                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1906
1907                 if (ret != LDB_SUCCESS) {
1908                         handle->status = ret;
1909                         goto done;
1910                 }
1911                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1912                         handle->status = ac->down_req->handle->status;
1913                         goto done;
1914                 }
1915
1916                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1917                         return LDB_SUCCESS;
1918                 }
1919
1920                 break;
1921                 
1922         case PH_MOD_DO_REQ:
1923                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1924
1925                 if (ret != LDB_SUCCESS) {
1926                         handle->status = ret;
1927                         goto done;
1928                 }
1929                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1930                         handle->status = ac->down_req->handle->status;
1931                         goto done;
1932                 }
1933
1934                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1935                         return LDB_SUCCESS;
1936                 }
1937
1938                 /* non-password mods done, go on */
1939                 return password_hash_mod_search_self(handle);
1940                 
1941         case PH_MOD_SEARCH_SELF:
1942                 ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
1943
1944                 if (ret != LDB_SUCCESS) {
1945                         handle->status = ret;
1946                         goto done;
1947                 }
1948                 if (ac->search_req->handle->status != LDB_SUCCESS) {
1949                         handle->status = ac->search_req->handle->status;
1950                         goto done;
1951                 }
1952
1953                 if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
1954                         return LDB_SUCCESS;
1955                 }
1956
1957                 if (ac->search_res == NULL) {
1958                         return LDB_ERR_NO_SUCH_OBJECT;
1959                 }
1960
1961                 /* self search done, go on */
1962                 return password_hash_mod_search_dom(handle);
1963                 
1964         case PH_MOD_SEARCH_DOM:
1965                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1966
1967                 if (ret != LDB_SUCCESS) {
1968                         handle->status = ret;
1969                         goto done;
1970                 }
1971                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1972                         handle->status = ac->dom_req->handle->status;
1973                         goto done;
1974                 }
1975
1976                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1977                         return LDB_SUCCESS;
1978                 }
1979
1980                 /* domain search done, go on */
1981                 return password_hash_mod_do_mod(handle);
1982
1983         case PH_MOD_DO_MOD:
1984                 ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
1985
1986                 if (ret != LDB_SUCCESS) {
1987                         handle->status = ret;
1988                         goto done;
1989                 }
1990                 if (ac->mod_req->handle->status != LDB_SUCCESS) {
1991                         handle->status = ac->mod_req->handle->status;
1992                         goto done;
1993                 }
1994
1995                 if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
1996                         return LDB_SUCCESS;
1997                 }
1998
1999                 break;
2000                 
2001         default:
2002                 ret = LDB_ERR_OPERATIONS_ERROR;
2003                 goto done;
2004         }
2005
2006         ret = LDB_SUCCESS;
2007
2008 done:
2009         handle->state = LDB_ASYNC_DONE;
2010         return ret;
2011 }
2012
2013 static int ph_wait_all(struct ldb_handle *handle) {
2014
2015         int ret;
2016
2017         while (handle->state != LDB_ASYNC_DONE) {
2018                 ret = ph_wait(handle);
2019                 if (ret != LDB_SUCCESS) {
2020                         return ret;
2021                 }
2022         }
2023
2024         return handle->status;
2025 }
2026
2027 static int password_hash_wait(struct ldb_handle *handle, enum ldb_wait_type type)
2028 {
2029         if (type == LDB_WAIT_ALL) {
2030                 return ph_wait_all(handle);
2031         } else {
2032                 return ph_wait(handle);
2033         }
2034 }
2035
2036 _PUBLIC_ const struct ldb_module_ops ldb_password_hash_module_ops = {
2037         .name          = "password_hash",
2038         .add           = password_hash_add,
2039         .modify        = password_hash_modify,
2040         .wait          = password_hash_wait
2041 };