r22969: fix some more places where we could end up with more than one event
[jelmer/samba4-debian.git] / source / 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 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 /*
25  *  Name: ldb
26  *
27  *  Component: ldb password_hash module
28  *
29  *  Description: correctly update hash values based on changes to sambaPassword and friends
30  *
31  *  Author: Andrew Bartlett
32  *  Author: Stefan Metzmacher
33  */
34
35 #include "includes.h"
36 #include "libcli/ldap/ldap.h"
37 #include "ldb/include/ldb_errors.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 "hdb.h"
49 #include "dsdb/samdb/ldb_modules/password_modules.h"
50 #include "librpc/ndr/libndr.h"
51 #include "librpc/gen_ndr/ndr_drsblobs.h"
52 #include "lib/crypto/crypto.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 sambaPassword 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         NTSTATUS status;
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         pkb3->unknown3  = talloc_zero_array(io->ac, uint64_t, pkb3->num_keys);
340         if (!pkb3->unknown3) {
341                 ldb_oom(io->ac->module->ldb);
342                 return LDB_ERR_OPERATIONS_ERROR;
343         }
344
345 if (lp_parm_bool(-1, "password_hash", "create_aes_key", false)) {
346 /*
347  * TODO:
348  *
349  * w2k and w2k3 doesn't support AES, so we'll not include
350  * the AES key here yet.
351  *
352  * Also we don't have an example supplementalCredentials blob
353  * from Windows Longhorn Server with AES support
354  *
355  */
356         /*
357          * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
358          * the salt and the cleartext password
359          */
360         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
361                                            ENCTYPE_AES256_CTS_HMAC_SHA1_96,
362                                            io->n.cleartext,
363                                            salt,
364                                            &key);
365         pkb3->keys[k].keytype   = ENCTYPE_AES256_CTS_HMAC_SHA1_96;
366         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
367         if (!pkb3->keys[k].value) {
368                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
369                 ldb_oom(io->ac->module->ldb);
370                 return LDB_ERR_OPERATIONS_ERROR;
371         }
372         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
373                                                    key.keyvalue.data,
374                                                    key.keyvalue.length);
375         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
376         if (!pkb3->keys[k].value->data) {
377                 ldb_oom(io->ac->module->ldb);
378                 return LDB_ERR_OPERATIONS_ERROR;
379         }
380         k++;
381 }
382
383         /*
384          * create ENCTYPE_DES_CBC_MD5 key out of
385          * the salt and the cleartext password
386          */
387         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
388                                            ENCTYPE_DES_CBC_MD5,
389                                            io->n.cleartext,
390                                            salt,
391                                            &key);
392         pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_MD5;
393         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
394         if (!pkb3->keys[k].value) {
395                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
396                 ldb_oom(io->ac->module->ldb);
397                 return LDB_ERR_OPERATIONS_ERROR;
398         }
399         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
400                                                    key.keyvalue.data,
401                                                    key.keyvalue.length);
402         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
403         if (!pkb3->keys[k].value->data) {
404                 ldb_oom(io->ac->module->ldb);
405                 return LDB_ERR_OPERATIONS_ERROR;
406         }
407         k++;
408
409         /*
410          * create ENCTYPE_DES_CBC_CRC key out of
411          * the salt and the cleartext password
412          */
413         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
414                                            ENCTYPE_DES_CBC_CRC,
415                                            io->n.cleartext,
416                                            salt,
417                                            &key);
418         pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_CRC;
419         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
420         if (!pkb3->keys[k].value) {
421                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
422                 ldb_oom(io->ac->module->ldb);
423                 return LDB_ERR_OPERATIONS_ERROR;
424         }
425         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
426                                                    key.keyvalue.data,
427                                                    key.keyvalue.length);
428         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
429         if (!pkb3->keys[k].value->data) {
430                 ldb_oom(io->ac->module->ldb);
431                 return LDB_ERR_OPERATIONS_ERROR;
432         }
433         k++;
434
435         /* fix up key number */
436         pkb3->num_keys = k;
437
438         /* initialize the old keys to zero */
439         pkb3->num_old_keys      = 0;
440         pkb3->old_keys          = NULL;
441         pkb3->unknown3_old      = NULL;
442
443         /* if there're no old keys, then we're done */
444         if (!old_scb) {
445                 return LDB_SUCCESS;
446         }
447
448         for (i=0; i < old_scb->sub.num_packages; i++) {
449                 if (old_scb->sub.packages[i].unknown1 != 0x00000001) {
450                         continue;
451                 }
452
453                 if (strcmp("Primary:Kerberos", old_scb->sub.packages[i].name) != 0) {
454                         continue;
455                 }
456
457                 if (!old_scb->sub.packages[i].data || !old_scb->sub.packages[i].data[0]) {
458                         continue;
459                 }
460
461                 old_scp = &old_scb->sub.packages[i];
462                 break;
463         }
464         /* Primary:Kerberos element of supplementalCredentials */
465         if (old_scp) {
466                 DATA_BLOB blob;
467
468                 blob = strhex_to_data_blob(old_scp->data);
469                 if (!blob.data) {
470                         ldb_oom(io->ac->module->ldb);
471                         return LDB_ERR_OPERATIONS_ERROR;
472                 }
473                 talloc_steal(io->ac, blob.data);
474
475                 /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
476                 status = ndr_pull_struct_blob(&blob, io->ac, &_old_pkb,
477                                               (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
478                 if (!NT_STATUS_IS_OK(status)) {
479                         ldb_asprintf_errstring(io->ac->module->ldb,
480                                                "setup_primary_kerberos: "
481                                                "failed to pull old package_PrimaryKerberosBlob: %s",
482                                                nt_errstr(status));
483                         return LDB_ERR_OPERATIONS_ERROR;
484                 }
485
486                 if (_old_pkb.version != 3) {
487                         ldb_asprintf_errstring(io->ac->module->ldb,
488                                                "setup_primary_kerberos: "
489                                                "package_PrimaryKerberosBlob version[%u] expected[3]",
490                                                _old_pkb.version);
491                         return LDB_ERR_OPERATIONS_ERROR;
492                 }
493
494                 old_pkb3 = &_old_pkb.ctr.ctr3;
495         }
496
497         /* if we didn't found the old keys we're done */
498         if (!old_pkb3) {
499                 return LDB_SUCCESS;
500         }
501
502         /* fill in the old keys */
503         pkb3->num_old_keys      = old_pkb3->num_keys;
504         pkb3->old_keys          = old_pkb3->keys;
505         pkb3->unknown3_old      = old_pkb3->unknown3;
506
507         return LDB_SUCCESS;
508 }
509
510 static int setup_primary_wdigest(struct setup_password_fields_io *io,
511                                  const struct supplementalCredentialsBlob *old_scb,
512                                  struct package_PrimaryWDigestBlob *pdb)
513 {
514         DATA_BLOB sAMAccountName;
515         DATA_BLOB sAMAccountName_l;
516         DATA_BLOB sAMAccountName_u;
517         const char *user_principal_name = io->u.user_principal_name;
518         DATA_BLOB userPrincipalName;
519         DATA_BLOB userPrincipalName_l;
520         DATA_BLOB userPrincipalName_u;
521         DATA_BLOB netbios_domain;
522         DATA_BLOB netbios_domain_l;
523         DATA_BLOB netbios_domain_u;
524         DATA_BLOB dns_domain;
525         DATA_BLOB dns_domain_l;
526         DATA_BLOB dns_domain_u;
527         DATA_BLOB cleartext;
528         DATA_BLOB digest;
529         DATA_BLOB delim;
530         DATA_BLOB backslash;
531         uint8_t i;
532         struct {
533                 DATA_BLOB *user;
534                 DATA_BLOB *realm;
535                 DATA_BLOB *nt4dom;
536         } wdigest[] = {
537         /*
538          * See
539          * http://technet2.microsoft.com/WindowsServer/en/library/717b450c-f4a0-4cc9-86f4-cc0633aae5f91033.mspx?mfr=true
540          * for what precalculated hashes are supposed to be stored...
541          *
542          * I can't reproduce all values which should contain "Digest" as realm,
543          * am I doing something wrong or is w2k3 just broken...?
544          *
545          * W2K3 fills in following for a user:
546          *
547          * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
548          * sAMAccountName: NewUser2Sam
549          * userPrincipalName: NewUser2Princ@sub1.w2k3.vmnet1.vm.base
550          *
551          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
552          * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
553          * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
554          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
555          * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
556          * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
557          * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
558          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
559          * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
560          * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
561          * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
562          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
563          * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
564          * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
565          * 221c55284451ae9b3aacaa2a3c86f10f => NewUser2Princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
566          * 74e1be668853d4324d38c07e2acfb8ea => (w2k3 has a bug here!) newuser2princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
567          * e1e244ab7f098e3ae1761be7f9229bbb => NEWUSER2PRINC@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
568          * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
569          * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
570          * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
571          * 31dc704d3640335b2123d4ee28aa1f11 => ??? changes with NewUser2Sam => NewUser1Sam
572          * 36349f5cecd07320fb3bb0e119230c43 => ??? changes with NewUser2Sam => NewUser1Sam
573          * 12adf019d037fb535c01fd0608e78d9d => ??? changes with NewUser2Sam => NewUser1Sam
574          * 6feecf8e724906f3ee1105819c5105a1 => ??? changes with NewUser2Princ => NewUser1Princ
575          * 6c6911f3de6333422640221b9c51ff1f => ??? changes with NewUser2Princ => NewUser1Princ
576          * 4b279877e742895f9348ac67a8de2f69 => ??? changes with NewUser2Princ => NewUser1Princ
577          * db0c6bff069513e3ebb9870d29b57490 => ??? changes with NewUser2Sam => NewUser1Sam
578          * 45072621e56b1c113a4e04a8ff68cd0e => ??? changes with NewUser2Sam => NewUser1Sam
579          * 11d1220abc44a9c10cf91ef4a9c1de02 => ??? changes with NewUser2Sam => NewUser1Sam
580          *
581          * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
582          * sAMAccountName: NewUser2Sam
583          *
584          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
585          * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
586          * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
587          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
588          * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
589          * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
590          * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
591          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
592          * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
593          * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
594          * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
595          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
596          * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
597          * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
598          * 8a140d30b6f0a5912735dc1e3bc993b4 => NewUser2Sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
599          * 86d95b2faae6cae4ec261e7fbaccf093 => (here w2k3 is correct) newuser2sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
600          * dfeff1493110220efcdfc6362e5f5450 => NEWUSER2SAM@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
601          * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
602          * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
603          * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
604          * 31dc704d3640335b2123d4ee28aa1f11 => ???M1   changes with NewUser2Sam => NewUser1Sam
605          * 36349f5cecd07320fb3bb0e119230c43 => ???M1.L changes with newuser2sam => newuser1sam
606          * 12adf019d037fb535c01fd0608e78d9d => ???M1.U changes with NEWUSER2SAM => NEWUSER1SAM
607          * 569b4533f2d9e580211dd040e5e360a8 => ???M2   changes with NewUser2Princ => NewUser1Princ
608          * 52528bddf310a587c5d7e6a9ae2cbb20 => ???M2.L changes with newuser2princ => newuser1princ
609          * 4f629a4f0361289ca4255ab0f658fcd5 => ???M3 changes with NewUser2Princ => NewUser1Princ (doesn't depend on case of userPrincipal )
610          * db0c6bff069513e3ebb9870d29b57490 => ???M4 changes with NewUser2Sam => NewUser1Sam
611          * 45072621e56b1c113a4e04a8ff68cd0e => ???M5 changes with NewUser2Sam => NewUser1Sam (doesn't depend on case of sAMAccountName)
612          * 11d1220abc44a9c10cf91ef4a9c1de02 => ???M4.U changes with NEWUSER2SAM => NEWUSER1SAM
613          */
614
615         /*
616          * sAMAccountName, netbios_domain
617          */
618                 {
619                 .user   = &sAMAccountName,
620                 .realm  = &netbios_domain,
621                 },
622                 {
623                 .user   = &sAMAccountName_l,
624                 .realm  = &netbios_domain_l,
625                 },
626                 {
627                 .user   = &sAMAccountName_u,
628                 .realm  = &netbios_domain_u,
629                 },
630                 {
631                 .user   = &sAMAccountName,
632                 .realm  = &netbios_domain_u,
633                 },
634                 {
635                 .user   = &sAMAccountName,
636                 .realm  = &netbios_domain_l,
637                 },
638                 {
639                 .user   = &sAMAccountName_u,
640                 .realm  = &netbios_domain_l,
641                 },
642                 {
643                 .user   = &sAMAccountName_l,
644                 .realm  = &netbios_domain_u,
645                 },
646         /* 
647          * sAMAccountName, dns_domain
648          */
649                 {
650                 .user   = &sAMAccountName,
651                 .realm  = &dns_domain,
652                 },
653                 {
654                 .user   = &sAMAccountName_l,
655                 .realm  = &dns_domain_l,
656                 },
657                 {
658                 .user   = &sAMAccountName_u,
659                 .realm  = &dns_domain_u,
660                 },
661                 {
662                 .user   = &sAMAccountName,
663                 .realm  = &dns_domain_u,
664                 },
665                 {
666                 .user   = &sAMAccountName,
667                 .realm  = &dns_domain_l,
668                 },
669                 {
670                 .user   = &sAMAccountName_u,
671                 .realm  = &dns_domain_l,
672                 },
673                 {
674                 .user   = &sAMAccountName_l,
675                 .realm  = &dns_domain_u,
676                 },
677         /* 
678          * userPrincipalName, no realm
679          */
680                 {
681                 .user   = &userPrincipalName,
682                 },
683                 {
684                 /* 
685                  * NOTE: w2k3 messes this up, if the user has a real userPrincipalName,
686                  *       the fallback to the sAMAccountName based userPrincipalName is correct
687                  */
688                 .user   = &userPrincipalName_l,
689                 },
690                 {
691                 .user   = &userPrincipalName_u,
692                 },
693         /* 
694          * nt4dom\sAMAccountName, no realm
695          */
696                 {
697                 .user   = &sAMAccountName,
698                 .nt4dom = &netbios_domain
699                 },
700                 {
701                 .user   = &sAMAccountName_l,
702                 .nt4dom = &netbios_domain_l
703                 },
704                 {
705                 .user   = &sAMAccountName_u,
706                 .nt4dom = &netbios_domain_u
707                 },
708
709         /*
710          * the following ones are guessed depending on the technet2 article
711          * but not reproducable on a w2k3 server
712          */
713         /* sAMAccountName with "Digest" realm */
714                 {
715                 .user   = &sAMAccountName,
716                 .realm  = &digest
717                 },
718                 {
719                 .user   = &sAMAccountName_l,
720                 .realm  = &digest
721                 },
722                 {
723                 .user   = &sAMAccountName_u,
724                 .realm  = &digest
725                 },
726         /* userPrincipalName with "Digest" realm */
727                 {
728                 .user   = &userPrincipalName,
729                 .realm  = &digest
730                 },
731                 {
732                 .user   = &userPrincipalName_l,
733                 .realm  = &digest
734                 },
735                 {
736                 .user   = &userPrincipalName_u,
737                 .realm  = &digest
738                 },
739         /* nt4dom\\sAMAccountName with "Digest" realm */
740                 {
741                 .user   = &sAMAccountName,
742                 .nt4dom = &netbios_domain,
743                 .realm  = &digest
744                 },
745                 {
746                 .user   = &sAMAccountName_l,
747                 .nt4dom = &netbios_domain_l,
748                 .realm  = &digest
749                 },
750                 {
751                 .user   = &sAMAccountName_u,
752                 .nt4dom = &netbios_domain_u,
753                 .realm  = &digest
754                 },
755         };
756
757         /* prepare DATA_BLOB's used in the combinations array */
758         sAMAccountName          = data_blob_string_const(io->u.sAMAccountName);
759         sAMAccountName_l        = data_blob_string_const(strlower_talloc(io->ac, io->u.sAMAccountName));
760         if (!sAMAccountName_l.data) {
761                 ldb_oom(io->ac->module->ldb);
762                 return LDB_ERR_OPERATIONS_ERROR;
763         }
764         sAMAccountName_u        = data_blob_string_const(strupper_talloc(io->ac, io->u.sAMAccountName));
765         if (!sAMAccountName_u.data) {
766                 ldb_oom(io->ac->module->ldb);
767                 return LDB_ERR_OPERATIONS_ERROR;
768         }
769
770         /* if the user doesn't have a userPrincipalName, create one (with lower case realm) */
771         if (!user_principal_name) {
772                 user_principal_name = talloc_asprintf(io->ac, "%s@%s",
773                                                       io->u.sAMAccountName,
774                                                       io->domain->dns_domain);
775                 if (!user_principal_name) {
776                         ldb_oom(io->ac->module->ldb);
777                         return LDB_ERR_OPERATIONS_ERROR;
778                 }       
779         }
780         userPrincipalName       = data_blob_string_const(user_principal_name);
781         userPrincipalName_l     = data_blob_string_const(strlower_talloc(io->ac, user_principal_name));
782         if (!userPrincipalName_l.data) {
783                 ldb_oom(io->ac->module->ldb);
784                 return LDB_ERR_OPERATIONS_ERROR;
785         }
786         userPrincipalName_u     = data_blob_string_const(strupper_talloc(io->ac, user_principal_name));
787         if (!userPrincipalName_u.data) {
788                 ldb_oom(io->ac->module->ldb);
789                 return LDB_ERR_OPERATIONS_ERROR;
790         }
791
792         netbios_domain          = data_blob_string_const(io->domain->netbios_domain);
793         netbios_domain_l        = data_blob_string_const(strlower_talloc(io->ac, io->domain->netbios_domain));
794         if (!netbios_domain_l.data) {
795                 ldb_oom(io->ac->module->ldb);
796                 return LDB_ERR_OPERATIONS_ERROR;
797         }
798         netbios_domain_u        = data_blob_string_const(strupper_talloc(io->ac, io->domain->netbios_domain));
799         if (!netbios_domain_u.data) {
800                 ldb_oom(io->ac->module->ldb);
801                 return LDB_ERR_OPERATIONS_ERROR;
802         }
803
804         dns_domain              = data_blob_string_const(io->domain->dns_domain);
805         dns_domain_l            = data_blob_string_const(io->domain->dns_domain);
806         dns_domain_u            = data_blob_string_const(io->domain->realm);
807
808         cleartext               = data_blob_string_const(io->n.cleartext);
809
810         digest                  = data_blob_string_const("Digest");
811
812         delim                   = data_blob_string_const(":");
813         backslash               = data_blob_string_const("\\");
814
815         pdb->num_hashes = ARRAY_SIZE(wdigest);
816         pdb->hashes     = talloc_array(io->ac, struct package_PrimaryWDigestHash, pdb->num_hashes);
817         if (!pdb->hashes) {
818                 ldb_oom(io->ac->module->ldb);
819                 return LDB_ERR_OPERATIONS_ERROR;
820         }
821
822         for (i=0; i < ARRAY_SIZE(wdigest); i++) {
823                 struct MD5Context md5;
824                 MD5Init(&md5);
825                 if (wdigest[i].nt4dom) {
826                         MD5Update(&md5, wdigest[i].nt4dom->data, wdigest[i].nt4dom->length);
827                         MD5Update(&md5, backslash.data, backslash.length);
828                 }
829                 MD5Update(&md5, wdigest[i].user->data, wdigest[i].user->length);
830                 MD5Update(&md5, delim.data, delim.length);
831                 if (wdigest[i].realm) {
832                         MD5Update(&md5, wdigest[i].realm->data, wdigest[i].realm->length);
833                 }
834                 MD5Update(&md5, delim.data, delim.length);
835                 MD5Update(&md5, cleartext.data, cleartext.length);
836                 MD5Final(pdb->hashes[i].hash, &md5);
837         }
838
839         return LDB_SUCCESS;
840 }
841
842 static int setup_supplemental_field(struct setup_password_fields_io *io)
843 {
844         struct supplementalCredentialsBlob scb;
845         struct supplementalCredentialsBlob _old_scb;
846         struct supplementalCredentialsBlob *old_scb = NULL;
847         /* Packages + (Kerberos, WDigest and maybe CLEARTEXT) */
848         uint32_t num_packages = 1 + 2;
849         struct supplementalCredentialsPackage packages[1+3];
850         struct supplementalCredentialsPackage *pp = &packages[0];
851         struct supplementalCredentialsPackage *pk = &packages[1];
852         struct supplementalCredentialsPackage *pd = &packages[2];
853         struct supplementalCredentialsPackage *pc = NULL;
854         struct package_PackagesBlob pb;
855         DATA_BLOB pb_blob;
856         char *pb_hexstr;
857         struct package_PrimaryKerberosBlob pkb;
858         DATA_BLOB pkb_blob;
859         char *pkb_hexstr;
860         struct package_PrimaryWDigestBlob pdb;
861         DATA_BLOB pdb_blob;
862         char *pdb_hexstr;
863         struct package_PrimaryCLEARTEXTBlob pcb;
864         DATA_BLOB pcb_blob;
865         char *pcb_hexstr;
866         int ret;
867         NTSTATUS status;
868         uint8_t zero16[16];
869
870         ZERO_STRUCT(zero16);
871
872         if (!io->n.cleartext) {
873                 /* 
874                  * when we don't have a cleartext password
875                  * we can't setup a supplementalCredential value
876                  */
877                 return LDB_SUCCESS;
878         }
879
880         /* if there's an old supplementaCredentials blob then parse it */
881         if (io->o.supplemental) {
882                 status = ndr_pull_struct_blob_all(io->o.supplemental, io->ac, &_old_scb,
883                                                   (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
884                 if (!NT_STATUS_IS_OK(status)) {
885                         ldb_asprintf_errstring(io->ac->module->ldb,
886                                                "setup_supplemental_field: "
887                                                "failed to pull old supplementalCredentialsBlob: %s",
888                                                nt_errstr(status));
889                         return LDB_ERR_OPERATIONS_ERROR;
890                 }
891
892                 old_scb = &_old_scb;
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         status = ndr_push_struct_blob(&pkb_blob, io->ac, &pkb,
915                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
916         if (!NT_STATUS_IS_OK(status)) {
917                 ldb_asprintf_errstring(io->ac->module->ldb,
918                                        "setup_supplemental_field: "
919                                        "failed to push package_PrimaryKerberosBlob: %s",
920                                        nt_errstr(status));
921                 return LDB_ERR_OPERATIONS_ERROR;
922         }
923         /*
924          * TODO:
925          *
926          * This is ugly, but we want to generate the same blob as
927          * w2k and w2k3...we should handle this in the idl
928          */
929         status = data_blob_append(io->ac, &pkb_blob, zero16, sizeof(zero16));
930         if (!NT_STATUS_IS_OK(status)) {
931                 ldb_oom(io->ac->module->ldb);
932                 return LDB_ERR_OPERATIONS_ERROR;
933         }
934         pkb_hexstr = data_blob_hex_string(io->ac, &pkb_blob);
935         if (!pkb_hexstr) {
936                 ldb_oom(io->ac->module->ldb);
937                 return LDB_ERR_OPERATIONS_ERROR;
938         }
939         pk->name        = "Primary:Kerberos";
940         pk->unknown1    = 1;
941         pk->data        = pkb_hexstr;
942
943         /*
944          * setup 'Primary:WDigest' element
945          */
946         pb.names[1] = "WDigest";
947
948         ret = setup_primary_wdigest(io, old_scb, &pdb);
949         if (ret != LDB_SUCCESS) {
950                 return ret;
951         }
952
953         status = ndr_push_struct_blob(&pdb_blob, io->ac, &pdb,
954                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
955         if (!NT_STATUS_IS_OK(status)) {
956                 ldb_asprintf_errstring(io->ac->module->ldb,
957                                        "setup_supplemental_field: "
958                                        "failed to push package_PrimaryWDigestBlob: %s",
959                                        nt_errstr(status));
960                 return LDB_ERR_OPERATIONS_ERROR;
961         }
962         pdb_hexstr = data_blob_hex_string(io->ac, &pdb_blob);
963         if (!pdb_hexstr) {
964                 ldb_oom(io->ac->module->ldb);
965                 return LDB_ERR_OPERATIONS_ERROR;
966         }
967         pd->name        = "Primary:WDigest";
968         pd->unknown1    = 1;
969         pd->data        = pdb_hexstr;
970
971         /*
972          * setup 'Primary:CLEARTEXT' element
973          */
974         if (pc) {
975                 pb.names[2]     = "CLEARTEXT";
976
977                 pcb.cleartext   = io->n.cleartext;
978
979                 status = ndr_push_struct_blob(&pcb_blob, io->ac, &pcb,
980                                               (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
981                 if (!NT_STATUS_IS_OK(status)) {
982                         ldb_asprintf_errstring(io->ac->module->ldb,
983                                                "setup_supplemental_field: "
984                                                "failed to push package_PrimaryCLEARTEXTBlob: %s",
985                                                nt_errstr(status));
986                         return LDB_ERR_OPERATIONS_ERROR;
987                 }
988                 pcb_hexstr = data_blob_hex_string(io->ac, &pcb_blob);
989                 if (!pcb_hexstr) {
990                         ldb_oom(io->ac->module->ldb);
991                         return LDB_ERR_OPERATIONS_ERROR;
992                 }
993                 pc->name        = "Primary:CLEARTEXT";
994                 pc->unknown1    = 1;
995                 pc->data        = pcb_hexstr;
996         }
997
998         /*
999          * setup 'Packages' element
1000          */
1001         status = ndr_push_struct_blob(&pb_blob, io->ac, &pb,
1002                                       (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
1003         if (!NT_STATUS_IS_OK(status)) {
1004                 ldb_asprintf_errstring(io->ac->module->ldb,
1005                                        "setup_supplemental_field: "
1006                                        "failed to push package_PackagesBlob: %s",
1007                                        nt_errstr(status));
1008                 return LDB_ERR_OPERATIONS_ERROR;
1009         }
1010         pb_hexstr = data_blob_hex_string(io->ac, &pb_blob);
1011         if (!pb_hexstr) {
1012                 ldb_oom(io->ac->module->ldb);
1013                 return LDB_ERR_OPERATIONS_ERROR;
1014         }
1015         pp->name        = "Packages";
1016         pp->unknown1    = 2;
1017         pp->data        = pb_hexstr;
1018
1019         /*
1020          * setup 'supplementalCredentials' value
1021          */
1022         scb.sub.num_packages    = num_packages;
1023         scb.sub.packages        = packages;
1024
1025         status = ndr_push_struct_blob(&io->g.supplemental, io->ac, &scb,
1026                                       (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
1027         if (!NT_STATUS_IS_OK(status)) {
1028                 ldb_asprintf_errstring(io->ac->module->ldb,
1029                                        "setup_supplemental_field: "
1030                                        "failed to push supplementalCredentialsBlob: %s",
1031                                        nt_errstr(status));
1032                 return LDB_ERR_OPERATIONS_ERROR;
1033         }
1034
1035         return LDB_SUCCESS;
1036 }
1037
1038 static int setup_last_set_field(struct setup_password_fields_io *io)
1039 {
1040         /* set it as now */
1041         unix_to_nt_time(&io->g.last_set, time(NULL));
1042
1043         return LDB_SUCCESS;
1044 }
1045
1046 static int setup_kvno_field(struct setup_password_fields_io *io)
1047 {
1048         /* increment by one */
1049         io->g.kvno = io->o.kvno + 1;
1050
1051         return LDB_SUCCESS;
1052 }
1053
1054 static int setup_password_fields(struct setup_password_fields_io *io)
1055 {
1056         bool ok;
1057         int ret;
1058
1059         /*
1060          * refuse the change if someone want to change the cleartext
1061          * and supply his own hashes at the same time...
1062          */
1063         if (io->n.cleartext && (io->n.nt_hash || io->n.lm_hash)) {
1064                 ldb_asprintf_errstring(io->ac->module->ldb,
1065                                        "setup_password_fields: "
1066                                        "it's only allowed to set the cleartext password or the password hashes");
1067                 return LDB_ERR_UNWILLING_TO_PERFORM;
1068         }
1069
1070         if (io->n.cleartext && !io->n.nt_hash) {
1071                 struct samr_Password *hash;
1072
1073                 hash = talloc(io->ac, struct samr_Password);
1074                 if (!hash) {
1075                         ldb_oom(io->ac->module->ldb);
1076                         return LDB_ERR_OPERATIONS_ERROR;
1077                 }
1078
1079                 /* compute the new nt hash */
1080                 ok = E_md4hash(io->n.cleartext, hash->hash);
1081                 if (ok) {
1082                         io->n.nt_hash = hash;
1083                 } else {
1084                         ldb_asprintf_errstring(io->ac->module->ldb,
1085                                                "setup_password_fields: "
1086                                                "failed to generate nthash from cleartext password");
1087                         return LDB_ERR_OPERATIONS_ERROR;
1088                 }
1089         }
1090
1091         if (io->n.cleartext && !io->n.lm_hash) {
1092                 struct samr_Password *hash;
1093
1094                 hash = talloc(io->ac, struct samr_Password);
1095                 if (!hash) {
1096                         ldb_oom(io->ac->module->ldb);
1097                         return LDB_ERR_OPERATIONS_ERROR;
1098                 }
1099
1100                 /* compute the new lm hash */
1101                 ok = E_deshash(io->n.cleartext, hash->hash);
1102                 if (ok) {
1103                         io->n.lm_hash = hash;
1104                 } else {
1105                         talloc_free(hash->hash);
1106                 }
1107         }
1108
1109         ret = setup_nt_fields(io);
1110         if (ret != 0) {
1111                 return ret;
1112         }
1113
1114         ret = setup_lm_fields(io);
1115         if (ret != 0) {
1116                 return ret;
1117         }
1118
1119         ret = setup_supplemental_field(io);
1120         if (ret != 0) {
1121                 return ret;
1122         }
1123
1124         ret = setup_last_set_field(io);
1125         if (ret != 0) {
1126                 return ret;
1127         }
1128
1129         ret = setup_kvno_field(io);
1130         if (ret != 0) {
1131                 return ret;
1132         }
1133
1134         return LDB_SUCCESS;
1135 }
1136
1137 static struct ldb_handle *ph_init_handle(struct ldb_request *req, struct ldb_module *module, enum ph_type type)
1138 {
1139         struct ph_context *ac;
1140         struct ldb_handle *h;
1141
1142         h = talloc_zero(req, struct ldb_handle);
1143         if (h == NULL) {
1144                 ldb_set_errstring(module->ldb, "Out of Memory");
1145                 return NULL;
1146         }
1147
1148         h->module = module;
1149
1150         ac = talloc_zero(h, struct ph_context);
1151         if (ac == NULL) {
1152                 ldb_set_errstring(module->ldb, "Out of Memory");
1153                 talloc_free(h);
1154                 return NULL;
1155         }
1156
1157         h->private_data = (void *)ac;
1158
1159         h->state = LDB_ASYNC_INIT;
1160         h->status = LDB_SUCCESS;
1161
1162         ac->type = type;
1163         ac->module = module;
1164         ac->orig_req = req;
1165
1166         return h;
1167 }
1168
1169 static int get_domain_data_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
1170 {
1171         struct ph_context *ac;
1172
1173         if (!context || !ares) {
1174                 ldb_set_errstring(ldb, "NULL Context or Result in callback");
1175                 return LDB_ERR_OPERATIONS_ERROR;
1176         }
1177
1178         ac = talloc_get_type(context, struct ph_context);
1179
1180         /* we are interested only in the single reply (base search) we receive here */
1181         if (ares->type == LDB_REPLY_ENTRY) {
1182                 if (ac->dom_res != NULL) {
1183                         ldb_set_errstring(ldb, "Too many results");
1184                         talloc_free(ares);
1185                         return LDB_ERR_OPERATIONS_ERROR;
1186                 }
1187                 ac->dom_res = talloc_steal(ac, ares);
1188         } else {
1189                 talloc_free(ares);
1190         }
1191
1192         return LDB_SUCCESS;
1193 }
1194
1195 static int build_domain_data_request(struct ph_context *ac)
1196 {
1197         /* attrs[] is returned from this function in
1198            ac->dom_req->op.search.attrs, so it must be static, as
1199            otherwise the compiler can put it on the stack */
1200         static const char * const attrs[] = { "pwdProperties", "pwdHistoryLength", NULL };
1201         char *filter;
1202
1203         ac->dom_req = talloc_zero(ac, struct ldb_request);
1204         if (ac->dom_req == NULL) {
1205                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1206                 return LDB_ERR_OPERATIONS_ERROR;
1207         }
1208         ac->dom_req->operation = LDB_SEARCH;
1209         ac->dom_req->op.search.base = ldb_get_default_basedn(ac->module->ldb);
1210         ac->dom_req->op.search.scope = LDB_SCOPE_SUBTREE;
1211
1212         filter = talloc_asprintf(ac->dom_req, "(&(objectSid=%s)(|(objectClass=domain)(objectClass=builtinDomain)))", 
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 sambaPassword, 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, "sambaPassword");
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 sambaPassword 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 sambaPassword is single valued here */
1351         /* TODO: remove this when sambaPassword will be single valued in schema */
1352         if (sambaAttr && sambaAttr->num_values > 1) {
1353                 ldb_set_errstring(module->ldb, "mupltiple values for sambaPassword 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, "sambaPassword 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                                   &smb_krb5_context) != 0) {
1436                 return LDB_ERR_OPERATIONS_ERROR;
1437         }
1438
1439         ZERO_STRUCT(io);
1440         io.ac                           = ac;
1441         io.domain                       = domain;
1442         io.smb_krb5_context             = smb_krb5_context;
1443
1444         io.u.user_account_control       = samdb_result_uint(msg, "userAccountControl", 0);
1445         io.u.sAMAccountName             = samdb_result_string(msg, "samAccountName", NULL);
1446         io.u.user_principal_name        = samdb_result_string(msg, "userPrincipalName", NULL);
1447         io.u.is_computer                = ldb_msg_check_string_attribute(msg, "objectClass", "computer");
1448
1449         io.n.cleartext                  = samdb_result_string(msg, "sambaPassword", NULL);
1450         io.n.nt_hash                    = samdb_result_hash(io.ac, msg, "unicodePwd");
1451         io.n.lm_hash                    = samdb_result_hash(io.ac, msg, "dBCSPwd");
1452
1453         /* remove attributes */
1454         if (io.n.cleartext) ldb_msg_remove_attr(msg, "sambaPassword");
1455         if (io.n.nt_hash) ldb_msg_remove_attr(msg, "unicodePwd");
1456         if (io.n.lm_hash) ldb_msg_remove_attr(msg, "dBCSPwd");
1457         ldb_msg_remove_attr(msg, "pwdLastSet");
1458         io.o.kvno = samdb_result_uint(msg, "msDs-KeyVersionNumber", 1) - 1;
1459         ldb_msg_remove_attr(msg, "msDs-KeyVersionNumber");
1460
1461         ret = setup_password_fields(&io);
1462         if (ret != LDB_SUCCESS) {
1463                 return ret;
1464         }
1465
1466         if (io.g.nt_hash) {
1467                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1468                                          "unicodePwd", io.g.nt_hash);
1469                 if (ret != LDB_SUCCESS) {
1470                         return ret;
1471                 }
1472         }
1473         if (io.g.lm_hash) {
1474                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1475                                          "dBCSPwd", io.g.lm_hash);
1476                 if (ret != LDB_SUCCESS) {
1477                         return ret;
1478                 }
1479         }
1480         if (io.g.nt_history_len > 0) {
1481                 ret = samdb_msg_add_hashes(ac, msg,
1482                                            "ntPwdHistory",
1483                                            io.g.nt_history,
1484                                            io.g.nt_history_len);
1485                 if (ret != LDB_SUCCESS) {
1486                         return ret;
1487                 }
1488         }
1489         if (io.g.lm_history_len > 0) {
1490                 ret = samdb_msg_add_hashes(ac, msg,
1491                                            "lmPwdHistory",
1492                                            io.g.lm_history,
1493                                            io.g.lm_history_len);
1494                 if (ret != LDB_SUCCESS) {
1495                         return ret;
1496                 }
1497         }
1498         if (io.g.supplemental.length > 0) {
1499                 ret = ldb_msg_add_value(msg, "supplementalCredentials",
1500                                         &io.g.supplemental, NULL);
1501                 if (ret != LDB_SUCCESS) {
1502                         return ret;
1503                 }
1504         }
1505         ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
1506                                    "pwdLastSet",
1507                                    io.g.last_set);
1508         if (ret != LDB_SUCCESS) {
1509                 return ret;
1510         }
1511         ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
1512                                  "msDs-KeyVersionNumber",
1513                                  io.g.kvno);
1514         if (ret != LDB_SUCCESS) {
1515                 return ret;
1516         }
1517
1518         h->state = LDB_ASYNC_INIT;
1519         h->status = LDB_SUCCESS;
1520
1521         ac->step = PH_ADD_DO_ADD;
1522
1523         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->down_req);
1524
1525         /* perform the operation */
1526         return ldb_next_request(ac->module, ac->down_req);
1527 }
1528
1529 static int password_hash_mod_search_self(struct ldb_handle *h);
1530
1531 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
1532 {
1533         struct ldb_handle *h;
1534         struct ph_context *ac;
1535         struct ldb_message_element *sambaAttr;
1536         struct ldb_message_element *ntAttr;
1537         struct ldb_message_element *lmAttr;
1538         struct ldb_message *msg;
1539
1540         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");
1541
1542         if (ldb_dn_is_special(req->op.mod.message->dn)) { /* do not manipulate our control entries */
1543                 return ldb_next_request(module, req);
1544         }
1545         
1546         /* If the caller is manipulating the local passwords directly, let them pass */
1547         if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
1548                                 req->op.mod.message->dn) == 0) {
1549                 return ldb_next_request(module, req);
1550         }
1551
1552         /* nobody must touch password Histories */
1553         if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
1554                 return LDB_ERR_UNWILLING_TO_PERFORM;
1555         }
1556         if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
1557                 return LDB_ERR_UNWILLING_TO_PERFORM;
1558         }
1559         if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
1560                 return LDB_ERR_UNWILLING_TO_PERFORM;
1561         }
1562
1563         sambaAttr = ldb_msg_find_element(req->op.mod.message, "sambaPassword");
1564         ntAttr = ldb_msg_find_element(req->op.mod.message, "unicodePwd");
1565         lmAttr = ldb_msg_find_element(req->op.mod.message, "dBCSPwd");
1566
1567         /* If no part of this touches the sambaPassword OR unicodePwd and/or dBCSPwd, then we don't
1568          * need to make any changes.  For password changes/set there should
1569          * be a 'delete' or a 'modify' on this attribute. */
1570         if ((!sambaAttr) && (!ntAttr) && (!lmAttr)) {
1571                 return ldb_next_request(module, req);
1572         }
1573
1574         /* check passwords are single valued here */
1575         /* TODO: remove this when passwords will be single valued in schema */
1576         if (sambaAttr && (sambaAttr->num_values > 1)) {
1577                 return LDB_ERR_CONSTRAINT_VIOLATION;
1578         }
1579         if (ntAttr && (ntAttr->num_values > 1)) {
1580                 return LDB_ERR_CONSTRAINT_VIOLATION;
1581         }
1582         if (lmAttr && (lmAttr->num_values > 1)) {
1583                 return LDB_ERR_CONSTRAINT_VIOLATION;
1584         }
1585
1586         h = ph_init_handle(req, module, PH_MOD);
1587         if (!h) {
1588                 return LDB_ERR_OPERATIONS_ERROR;
1589         }
1590         ac = talloc_get_type(h->private_data, struct ph_context);
1591
1592         /* return or own handle to deal with this call */
1593         req->handle = h;
1594
1595         /* prepare the first operation */
1596         ac->down_req = talloc_zero(ac, struct ldb_request);
1597         if (ac->down_req == NULL) {
1598                 ldb_set_errstring(module->ldb, "Out of memory!");
1599                 return LDB_ERR_OPERATIONS_ERROR;
1600         }
1601
1602         *(ac->down_req) = *req; /* copy the request */
1603
1604         /* use a new message structure so that we can modify it */
1605         ac->down_req->op.mod.message = msg = ldb_msg_copy_shallow(ac->down_req, req->op.mod.message);
1606
1607         /* - remove any imodification to the password from the first commit
1608          *   we will make the real modification later */
1609         if (sambaAttr) ldb_msg_remove_attr(msg, "sambaPassword");
1610         if (ntAttr) ldb_msg_remove_attr(msg, "unicodePwd");
1611         if (lmAttr) ldb_msg_remove_attr(msg, "dBCSPwd");
1612
1613         /* if there was nothing else to be modify skip to next step */
1614         if (msg->num_elements == 0) {
1615                 talloc_free(ac->down_req);
1616                 ac->down_req = NULL;
1617                 return password_hash_mod_search_self(h);
1618         }
1619         
1620         ac->down_req->context = NULL;
1621         ac->down_req->callback = NULL;
1622
1623         ac->step = PH_MOD_DO_REQ;
1624
1625         ldb_set_timeout_from_prev_req(module->ldb, req, ac->down_req);
1626
1627         return ldb_next_request(module, ac->down_req);
1628 }
1629
1630 static int get_self_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
1631 {
1632         struct ph_context *ac;
1633
1634         if (!context || !ares) {
1635                 ldb_set_errstring(ldb, "NULL Context or Result in callback");
1636                 return LDB_ERR_OPERATIONS_ERROR;
1637         }
1638
1639         ac = talloc_get_type(context, struct ph_context);
1640
1641         /* we are interested only in the single reply (base search) we receive here */
1642         if (ares->type == LDB_REPLY_ENTRY) {
1643                 if (ac->search_res != NULL) {
1644                         ldb_set_errstring(ldb, "Too many results");
1645                         talloc_free(ares);
1646                         return LDB_ERR_OPERATIONS_ERROR;
1647                 }
1648
1649                 /* if it is not an entry of type person this is an error */
1650                 /* TODO: remove this when sambaPassword will be in schema */
1651                 if (!ldb_msg_check_string_attribute(ares->message, "objectClass", "person")) {
1652                         ldb_set_errstring(ldb, "Object class violation");
1653                         talloc_free(ares);
1654                         return LDB_ERR_OBJECT_CLASS_VIOLATION;
1655                 }
1656
1657                 ac->search_res = talloc_steal(ac, ares);
1658         } else {
1659                 talloc_free(ares);
1660         }
1661
1662         return LDB_SUCCESS;
1663 }
1664
1665 static int password_hash_mod_search_self(struct ldb_handle *h) {
1666
1667         struct ph_context *ac;
1668         static const char * const attrs[] = { "userAccountControl", "lmPwdHistory", 
1669                                               "ntPwdHistory", 
1670                                               "objectSid", "msDS-KeyVersionNumber", 
1671                                               "objectClass", "userPrincipalName",
1672                                               "sAMAccountName", 
1673                                               "dBCSPwd", "unicodePwd",
1674                                               "supplementalCredentials",
1675                                               NULL };
1676
1677         ac = talloc_get_type(h->private_data, struct ph_context);
1678
1679         /* prepare the search operation */
1680         ac->search_req = talloc_zero(ac, struct ldb_request);
1681         if (ac->search_req == NULL) {
1682                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1683                 return LDB_ERR_OPERATIONS_ERROR;
1684         }
1685
1686         ac->search_req->operation = LDB_SEARCH;
1687         ac->search_req->op.search.base = ac->orig_req->op.mod.message->dn;
1688         ac->search_req->op.search.scope = LDB_SCOPE_BASE;
1689         ac->search_req->op.search.tree = ldb_parse_tree(ac->search_req, NULL);
1690         if (ac->search_req->op.search.tree == NULL) {
1691                 ldb_set_errstring(ac->module->ldb, "Invalid search filter");
1692                 return LDB_ERR_OPERATIONS_ERROR;
1693         }
1694         ac->search_req->op.search.attrs = attrs;
1695         ac->search_req->controls = NULL;
1696         ac->search_req->context = ac;
1697         ac->search_req->callback = get_self_callback;
1698         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
1699
1700         ac->step = PH_MOD_SEARCH_SELF;
1701
1702         return ldb_next_request(ac->module, ac->search_req);
1703 }
1704
1705 static int password_hash_mod_search_dom(struct ldb_handle *h) {
1706
1707         struct ph_context *ac;
1708         int ret;
1709
1710         ac = talloc_get_type(h->private_data, struct ph_context);
1711
1712         /* get object domain sid */
1713         ac->domain_sid = samdb_result_sid_prefix(ac, ac->search_res->message, "objectSid");
1714         if (ac->domain_sid == NULL) {
1715                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
1716                 return LDB_ERR_OPERATIONS_ERROR;
1717         }
1718
1719         /* get user domain data */
1720         ret = build_domain_data_request(ac);
1721         if (ret != LDB_SUCCESS) {
1722                 return ret;
1723         }
1724
1725         ac->step = PH_MOD_SEARCH_DOM;
1726
1727         return ldb_next_request(ac->module, ac->dom_req);
1728 }
1729
1730 static int password_hash_mod_do_mod(struct ldb_handle *h) {
1731
1732         struct ph_context *ac;
1733         struct domain_data *domain;
1734         struct smb_krb5_context *smb_krb5_context;
1735         struct ldb_message *msg;
1736         struct ldb_message *orig_msg;
1737         struct ldb_message *searched_msg;
1738         struct setup_password_fields_io io;
1739         int ret;
1740
1741         ac = talloc_get_type(h->private_data, struct ph_context);
1742
1743         domain = get_domain_data(ac->module, ac, ac->dom_res);
1744         if (domain == NULL) {
1745                 return LDB_ERR_OPERATIONS_ERROR;
1746         }
1747
1748         ac->mod_req = talloc(ac, struct ldb_request);
1749         if (ac->mod_req == NULL) {
1750                 return LDB_ERR_OPERATIONS_ERROR;
1751         }
1752
1753         *(ac->mod_req) = *(ac->orig_req);
1754         
1755         /* use a new message structure so that we can modify it */
1756         ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
1757         if (msg == NULL) {
1758                 return LDB_ERR_OPERATIONS_ERROR;
1759         }
1760
1761         /* modify dn */
1762         msg->dn = ac->orig_req->op.mod.message->dn;
1763
1764         /* Some operations below require kerberos contexts */
1765         if (smb_krb5_init_context(ac->mod_req, 
1766                                   ldb_get_opaque(h->module->ldb, "EventContext"), 
1767                                   &smb_krb5_context) != 0) {
1768                 return LDB_ERR_OPERATIONS_ERROR;
1769         }
1770
1771         orig_msg        = discard_const(ac->orig_req->op.mod.message);
1772         searched_msg    = ac->search_res->message;
1773
1774         ZERO_STRUCT(io);
1775         io.ac                           = ac;
1776         io.domain                       = domain;
1777         io.smb_krb5_context             = smb_krb5_context;
1778
1779         io.u.user_account_control       = samdb_result_uint(searched_msg, "userAccountControl", 0);
1780         io.u.sAMAccountName             = samdb_result_string(searched_msg, "samAccountName", NULL);
1781         io.u.user_principal_name        = samdb_result_string(searched_msg, "userPrincipalName", NULL);
1782         io.u.is_computer                = ldb_msg_check_string_attribute(searched_msg, "objectClass", "computer");
1783
1784         io.n.cleartext                  = samdb_result_string(orig_msg, "sambaPassword", NULL);
1785         io.n.nt_hash                    = samdb_result_hash(io.ac, orig_msg, "unicodePwd");
1786         io.n.lm_hash                    = samdb_result_hash(io.ac, orig_msg, "dBCSPwd");
1787
1788         io.o.kvno                       = samdb_result_uint(searched_msg, "msDs-KeyVersionNumber", 0);
1789         io.o.nt_history_len             = samdb_result_hashes(io.ac, searched_msg, "ntPwdHistory", &io.o.nt_history);
1790         io.o.lm_history_len             = samdb_result_hashes(io.ac, searched_msg, "lmPwdHistory", &io.o.lm_history);
1791         io.o.supplemental               = ldb_msg_find_ldb_val(searched_msg, "supplementalCredentials");
1792
1793         ret = setup_password_fields(&io);
1794         if (ret != LDB_SUCCESS) {
1795                 return ret;
1796         }
1797
1798         /* make sure we replace all the old attributes */
1799         ret = ldb_msg_add_empty(msg, "unicodePwd", LDB_FLAG_MOD_REPLACE, NULL);
1800         ret = ldb_msg_add_empty(msg, "dBCSPwd", LDB_FLAG_MOD_REPLACE, NULL);
1801         ret = ldb_msg_add_empty(msg, "ntPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1802         ret = ldb_msg_add_empty(msg, "lmPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1803         ret = ldb_msg_add_empty(msg, "supplementalCredentials", LDB_FLAG_MOD_REPLACE, NULL);
1804         ret = ldb_msg_add_empty(msg, "pwdLastSet", LDB_FLAG_MOD_REPLACE, NULL);
1805         ret = ldb_msg_add_empty(msg, "msDs-KeyVersionNumber", LDB_FLAG_MOD_REPLACE, NULL);
1806
1807         if (io.g.nt_hash) {
1808                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1809                                          "unicodePwd", io.g.nt_hash);
1810                 if (ret != LDB_SUCCESS) {
1811                         return ret;
1812                 }
1813         }
1814         if (io.g.lm_hash) {
1815                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1816                                          "dBCSPwd", io.g.lm_hash);
1817                 if (ret != LDB_SUCCESS) {
1818                         return ret;
1819                 }
1820         }
1821         if (io.g.nt_history_len > 0) {
1822                 ret = samdb_msg_add_hashes(ac, msg,
1823                                            "ntPwdHistory",
1824                                            io.g.nt_history,
1825                                            io.g.nt_history_len);
1826                 if (ret != LDB_SUCCESS) {
1827                         return ret;
1828                 }
1829         }
1830         if (io.g.lm_history_len > 0) {
1831                 ret = samdb_msg_add_hashes(ac, msg,
1832                                            "lmPwdHistory",
1833                                            io.g.lm_history,
1834                                            io.g.lm_history_len);
1835                 if (ret != LDB_SUCCESS) {
1836                         return ret;
1837                 }
1838         }
1839         if (io.g.supplemental.length > 0) {
1840                 ret = ldb_msg_add_value(msg, "supplementalCredentials",
1841                                         &io.g.supplemental, NULL);
1842                 if (ret != LDB_SUCCESS) {
1843                         return ret;
1844                 }
1845         }
1846         ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
1847                                    "pwdLastSet",
1848                                    io.g.last_set);
1849         if (ret != LDB_SUCCESS) {
1850                 return ret;
1851         }
1852         ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
1853                                  "msDs-KeyVersionNumber",
1854                                  io.g.kvno);
1855         if (ret != LDB_SUCCESS) {
1856                 return ret;
1857         }
1858
1859         h->state = LDB_ASYNC_INIT;
1860         h->status = LDB_SUCCESS;
1861
1862         ac->step = PH_MOD_DO_MOD;
1863
1864         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
1865
1866         /* perform the search */
1867         return ldb_next_request(ac->module, ac->mod_req);
1868 }
1869
1870 static int ph_wait(struct ldb_handle *handle) {
1871         struct ph_context *ac;
1872         int ret;
1873     
1874         if (!handle || !handle->private_data) {
1875                 return LDB_ERR_OPERATIONS_ERROR;
1876         }
1877
1878         if (handle->state == LDB_ASYNC_DONE) {
1879                 return handle->status;
1880         }
1881
1882         handle->state = LDB_ASYNC_PENDING;
1883         handle->status = LDB_SUCCESS;
1884
1885         ac = talloc_get_type(handle->private_data, struct ph_context);
1886
1887         switch (ac->step) {
1888         case PH_ADD_SEARCH_DOM:
1889                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1890
1891                 if (ret != LDB_SUCCESS) {
1892                         handle->status = ret;
1893                         goto done;
1894                 }
1895                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1896                         handle->status = ac->dom_req->handle->status;
1897                         goto done;
1898                 }
1899
1900                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1901                         return LDB_SUCCESS;
1902                 }
1903
1904                 /* domain search done, go on */
1905                 return password_hash_add_do_add(handle);
1906
1907         case PH_ADD_DO_ADD:
1908                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1909
1910                 if (ret != LDB_SUCCESS) {
1911                         handle->status = ret;
1912                         goto done;
1913                 }
1914                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1915                         handle->status = ac->down_req->handle->status;
1916                         goto done;
1917                 }
1918
1919                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1920                         return LDB_SUCCESS;
1921                 }
1922
1923                 break;
1924                 
1925         case PH_MOD_DO_REQ:
1926                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1927
1928                 if (ret != LDB_SUCCESS) {
1929                         handle->status = ret;
1930                         goto done;
1931                 }
1932                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1933                         handle->status = ac->down_req->handle->status;
1934                         goto done;
1935                 }
1936
1937                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1938                         return LDB_SUCCESS;
1939                 }
1940
1941                 /* non-password mods done, go on */
1942                 return password_hash_mod_search_self(handle);
1943                 
1944         case PH_MOD_SEARCH_SELF:
1945                 ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
1946
1947                 if (ret != LDB_SUCCESS) {
1948                         handle->status = ret;
1949                         goto done;
1950                 }
1951                 if (ac->search_req->handle->status != LDB_SUCCESS) {
1952                         handle->status = ac->search_req->handle->status;
1953                         goto done;
1954                 }
1955
1956                 if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
1957                         return LDB_SUCCESS;
1958                 }
1959
1960                 if (ac->search_res == NULL) {
1961                         return LDB_ERR_NO_SUCH_OBJECT;
1962                 }
1963
1964                 /* self search done, go on */
1965                 return password_hash_mod_search_dom(handle);
1966                 
1967         case PH_MOD_SEARCH_DOM:
1968                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1969
1970                 if (ret != LDB_SUCCESS) {
1971                         handle->status = ret;
1972                         goto done;
1973                 }
1974                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1975                         handle->status = ac->dom_req->handle->status;
1976                         goto done;
1977                 }
1978
1979                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1980                         return LDB_SUCCESS;
1981                 }
1982
1983                 /* domain search done, go on */
1984                 return password_hash_mod_do_mod(handle);
1985
1986         case PH_MOD_DO_MOD:
1987                 ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
1988
1989                 if (ret != LDB_SUCCESS) {
1990                         handle->status = ret;
1991                         goto done;
1992                 }
1993                 if (ac->mod_req->handle->status != LDB_SUCCESS) {
1994                         handle->status = ac->mod_req->handle->status;
1995                         goto done;
1996                 }
1997
1998                 if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
1999                         return LDB_SUCCESS;
2000                 }
2001
2002                 break;
2003                 
2004         default:
2005                 ret = LDB_ERR_OPERATIONS_ERROR;
2006                 goto done;
2007         }
2008
2009         ret = LDB_SUCCESS;
2010
2011 done:
2012         handle->state = LDB_ASYNC_DONE;
2013         return ret;
2014 }
2015
2016 static int ph_wait_all(struct ldb_handle *handle) {
2017
2018         int ret;
2019
2020         while (handle->state != LDB_ASYNC_DONE) {
2021                 ret = ph_wait(handle);
2022                 if (ret != LDB_SUCCESS) {
2023                         return ret;
2024                 }
2025         }
2026
2027         return handle->status;
2028 }
2029
2030 static int password_hash_wait(struct ldb_handle *handle, enum ldb_wait_type type)
2031 {
2032         if (type == LDB_WAIT_ALL) {
2033                 return ph_wait_all(handle);
2034         } else {
2035                 return ph_wait(handle);
2036         }
2037 }
2038
2039 static const struct ldb_module_ops password_hash_ops = {
2040         .name          = "password_hash",
2041         .add           = password_hash_add,
2042         .modify        = password_hash_modify,
2043         .wait          = password_hash_wait
2044 };
2045
2046
2047 int password_hash_module_init(void)
2048 {
2049         return ldb_register_module(&password_hash_ops);
2050 }