r26229: Set loadparm context as opaque pointer in ldb, remove more uses of global_loa...
[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 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 sambaPassword and friends
29  *
30  *  Author: Andrew Bartlett
31  *  Author: Stefan Metzmacher
32  */
33
34 #include "includes.h"
35 #include "libcli/ldap/ldap.h"
36 #include "ldb/include/ldb_errors.h"
37 #include "ldb/include/ldb_private.h"
38 #include "librpc/gen_ndr/misc.h"
39 #include "librpc/gen_ndr/samr.h"
40 #include "libcli/auth/libcli_auth.h"
41 #include "libcli/security/security.h"
42 #include "system/kerberos.h"
43 #include "auth/kerberos/kerberos.h"
44 #include "system/time.h"
45 #include "dsdb/samdb/samdb.h"
46 #include "dsdb/common/flags.h"
47 #include "dsdb/samdb/ldb_modules/password_modules.h"
48 #include "librpc/ndr/libndr.h"
49 #include "librpc/gen_ndr/ndr_drsblobs.h"
50 #include "lib/crypto/crypto.h"
51 #include "param/param.h"
52
53 /* If we have decided there is reason to work on this request, then
54  * setup all the password hash types correctly.
55  *
56  * If the administrator doesn't want the sambaPassword stored (set in the
57  * domain and per-account policies) then we must strip that out before
58  * we do the first operation.
59  *
60  * Once this is done (which could update anything at all), we
61  * calculate the password hashes.
62  *
63  * This function must not only update the unicodePwd, dBCSPwd and
64  * supplementalCredentials fields, it must also atomicly increment the
65  * msDS-KeyVersionNumber.  We should be in a transaction, so all this
66  * should be quite safe...
67  *
68  * Finally, if the administrator has requested that a password history
69  * be maintained, then this should also be written out.
70  *
71  */
72
73 struct ph_context {
74
75         enum ph_type {PH_ADD, PH_MOD} type;
76         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;
77
78         struct ldb_module *module;
79         struct ldb_request *orig_req;
80
81         struct ldb_request *dom_req;
82         struct ldb_reply *dom_res;
83
84         struct ldb_request *down_req;
85
86         struct ldb_request *search_req;
87         struct ldb_reply *search_res;
88
89         struct ldb_request *mod_req;
90
91         struct dom_sid *domain_sid;
92 };
93
94 struct domain_data {
95         bool store_cleartext;
96         uint_t pwdProperties;
97         uint_t pwdHistoryLength;
98         char *netbios_domain;
99         char *dns_domain;
100         char *realm;
101 };
102
103 struct setup_password_fields_io {
104         struct ph_context *ac;
105         struct domain_data *domain;
106         struct smb_krb5_context *smb_krb5_context;
107
108         /* infos about the user account */
109         struct {
110                 uint32_t user_account_control;
111                 const char *sAMAccountName;
112                 const char *user_principal_name;
113                 bool is_computer;
114         } u;
115
116         /* new credentials */
117         struct {
118                 const char *cleartext;
119                 struct samr_Password *nt_hash;
120                 struct samr_Password *lm_hash;
121         } n;
122
123         /* old credentials */
124         struct {
125                 uint32_t nt_history_len;
126                 struct samr_Password *nt_history;
127                 uint32_t lm_history_len;
128                 struct samr_Password *lm_history;
129                 const struct ldb_val *supplemental;
130                 struct supplementalCredentialsBlob scb;
131                 uint32_t kvno;
132         } o;
133
134         /* generated credentials */
135         struct {
136                 struct samr_Password *nt_hash;
137                 struct samr_Password *lm_hash;
138                 uint32_t nt_history_len;
139                 struct samr_Password *nt_history;
140                 uint32_t lm_history_len;
141                 struct samr_Password *lm_history;
142                 struct ldb_val supplemental;
143                 NTTIME last_set;
144                 uint32_t kvno;
145         } g;
146 };
147
148 static int setup_nt_fields(struct setup_password_fields_io *io)
149 {
150         uint32_t i;
151
152         io->g.nt_hash = io->n.nt_hash;
153
154         if (io->domain->pwdHistoryLength == 0) {
155                 return LDB_SUCCESS;
156         }
157
158         /* We might not have an old NT password */
159         io->g.nt_history = talloc_array(io->ac,
160                                         struct samr_Password,
161                                         io->domain->pwdHistoryLength);
162         if (!io->g.nt_history) {
163                 ldb_oom(io->ac->module->ldb);
164                 return LDB_ERR_OPERATIONS_ERROR;
165         }
166
167         for (i = 0; i < MIN(io->domain->pwdHistoryLength-1, io->o.nt_history_len); i++) {
168                 io->g.nt_history[i+1] = io->o.nt_history[i];
169         }
170         io->g.nt_history_len = i + 1;
171
172         if (io->g.nt_hash) {
173                 io->g.nt_history[0] = *io->g.nt_hash;
174         } else {
175                 /* 
176                  * TODO: is this correct?
177                  * the simular behavior is correct for the lm history case
178                  */
179                 E_md4hash("", io->g.nt_history[0].hash);
180         }
181
182         return LDB_SUCCESS;
183 }
184
185 static int setup_lm_fields(struct setup_password_fields_io *io)
186 {
187         uint32_t i;
188
189         io->g.lm_hash = io->n.lm_hash;
190
191         if (io->domain->pwdHistoryLength == 0) {
192                 return LDB_SUCCESS;
193         }
194
195         /* We might not have an old NT password */
196         io->g.lm_history = talloc_array(io->ac,
197                                         struct samr_Password,
198                                         io->domain->pwdHistoryLength);
199         if (!io->g.lm_history) {
200                 ldb_oom(io->ac->module->ldb);
201                 return LDB_ERR_OPERATIONS_ERROR;
202         }
203
204         for (i = 0; i < MIN(io->domain->pwdHistoryLength-1, io->o.lm_history_len); i++) {
205                 io->g.lm_history[i+1] = io->o.lm_history[i];
206         }
207         io->g.lm_history_len = i + 1;
208
209         if (io->g.lm_hash) {
210                 io->g.lm_history[0] = *io->g.lm_hash;
211         } else {
212                 E_deshash("", io->g.lm_history[0].hash);
213         }
214
215         return LDB_SUCCESS;
216 }
217
218 static int setup_primary_kerberos(struct setup_password_fields_io *io,
219                                   const struct supplementalCredentialsBlob *old_scb,
220                                   struct package_PrimaryKerberosBlob *pkb)
221 {
222         krb5_error_code krb5_ret;
223         Principal *salt_principal;
224         krb5_salt salt;
225         krb5_keyblock key;
226         uint32_t k=0;
227         struct package_PrimaryKerberosCtr3 *pkb3 = &pkb->ctr.ctr3;
228         struct supplementalCredentialsPackage *old_scp = NULL;
229         struct package_PrimaryKerberosBlob _old_pkb;
230         struct package_PrimaryKerberosCtr3 *old_pkb3 = NULL;
231         uint32_t i;
232         enum ndr_err_code ndr_err;
233
234         /* Many, many thanks to lukeh@padl.com for this
235          * algorithm, described in his Nov 10 2004 mail to
236          * samba-technical@samba.org */
237
238         /*
239          * Determine a salting principal
240          */
241         if (io->u.is_computer) {
242                 char *name;
243                 char *saltbody;
244
245                 name = talloc_strdup(io->ac, io->u.sAMAccountName);
246                 if (!name) {
247                         ldb_oom(io->ac->module->ldb);
248                         return LDB_ERR_OPERATIONS_ERROR;
249                 }
250
251                 if (name[strlen(name)-1] == '$') {
252                         name[strlen(name)-1] = '\0';
253                 }
254
255                 saltbody = talloc_asprintf(io->ac, "%s.%s", name, io->domain->dns_domain);
256                 if (!saltbody) {
257                         ldb_oom(io->ac->module->ldb);
258                         return LDB_ERR_OPERATIONS_ERROR;
259                 }
260                 
261                 krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
262                                                &salt_principal,
263                                                io->domain->realm, "host",
264                                                saltbody, NULL);
265         } else if (io->u.user_principal_name) {
266                 char *user_principal_name;
267                 char *p;
268
269                 user_principal_name = talloc_strdup(io->ac, io->u.user_principal_name);
270                 if (!user_principal_name) {
271                         ldb_oom(io->ac->module->ldb);
272                         return LDB_ERR_OPERATIONS_ERROR;
273                 }
274
275                 p = strchr(user_principal_name, '@');
276                 if (p) {
277                         p[0] = '\0';
278                 }
279
280                 krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
281                                                &salt_principal,
282                                                io->domain->realm, user_principal_name,
283                                                NULL);
284         } else {
285                 krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
286                                                &salt_principal,
287                                                io->domain->realm, io->u.sAMAccountName,
288                                                NULL);
289         }
290         if (krb5_ret) {
291                 ldb_asprintf_errstring(io->ac->module->ldb,
292                                        "setup_primary_kerberos: "
293                                        "generation of a salting principal failed: %s",
294                                        smb_get_krb5_error_message(io->smb_krb5_context->krb5_context, krb5_ret, io->ac));
295                 return LDB_ERR_OPERATIONS_ERROR;
296         }
297
298         /*
299          * create salt from salt_principal
300          */
301         krb5_ret = krb5_get_pw_salt(io->smb_krb5_context->krb5_context,
302                                     salt_principal, &salt);
303         krb5_free_principal(io->smb_krb5_context->krb5_context, salt_principal);
304         if (krb5_ret) {
305                 ldb_asprintf_errstring(io->ac->module->ldb,
306                                        "setup_primary_kerberos: "
307                                        "generation of krb5_salt failed: %s",
308                                        smb_get_krb5_error_message(io->smb_krb5_context->krb5_context, krb5_ret, io->ac));
309                 return LDB_ERR_OPERATIONS_ERROR;
310         }
311         /* create a talloc copy */
312         pkb3->salt.string = talloc_strndup(io->ac,
313                                           salt.saltvalue.data,
314                                           salt.saltvalue.length);
315         krb5_free_salt(io->smb_krb5_context->krb5_context, salt);
316         if (!pkb3->salt.string) {
317                 ldb_oom(io->ac->module->ldb);
318                 return LDB_ERR_OPERATIONS_ERROR;
319         }
320         salt.saltvalue.data     = discard_const(pkb3->salt.string);
321         salt.saltvalue.length   = strlen(pkb3->salt.string);
322
323         /*
324          * prepare generation of keys
325          *
326          * ENCTYPE_AES256_CTS_HMAC_SHA1_96 (disabled by default)
327          * ENCTYPE_DES_CBC_MD5
328          * ENCTYPE_DES_CBC_CRC
329          *
330          * NOTE: update num_keys when you add another enctype!
331          */
332         pkb3->num_keys  = 3;
333         pkb3->keys      = talloc_array(io->ac, struct package_PrimaryKerberosKey, pkb3->num_keys);
334         if (!pkb3->keys) {
335                 ldb_oom(io->ac->module->ldb);
336                 return LDB_ERR_OPERATIONS_ERROR;
337         }
338         pkb3->unknown3  = talloc_zero_array(io->ac, uint64_t, pkb3->num_keys);
339         if (!pkb3->unknown3) {
340                 ldb_oom(io->ac->module->ldb);
341                 return LDB_ERR_OPERATIONS_ERROR;
342         }
343
344         if (lp_parm_bool(ldb_get_opaque(io->ac->module->ldb, "loadparm"), NULL, "password_hash", "create_aes_key", false)) {
345         /*
346          * TODO:
347          *
348          * w2k and w2k3 doesn't support AES, so we'll not include
349          * the AES key here yet.
350          *
351          * Also we don't have an example supplementalCredentials blob
352          * from Windows Longhorn Server with AES support
353          *
354          */
355         /*
356          * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
357          * the salt and the cleartext password
358          */
359         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
360                                            ENCTYPE_AES256_CTS_HMAC_SHA1_96,
361                                            io->n.cleartext,
362                                            salt,
363                                            &key);
364         pkb3->keys[k].keytype   = ENCTYPE_AES256_CTS_HMAC_SHA1_96;
365         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
366         if (!pkb3->keys[k].value) {
367                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
368                 ldb_oom(io->ac->module->ldb);
369                 return LDB_ERR_OPERATIONS_ERROR;
370         }
371         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
372                                                    key.keyvalue.data,
373                                                    key.keyvalue.length);
374         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
375         if (!pkb3->keys[k].value->data) {
376                 ldb_oom(io->ac->module->ldb);
377                 return LDB_ERR_OPERATIONS_ERROR;
378         }
379         k++;
380 }
381
382         /*
383          * create ENCTYPE_DES_CBC_MD5 key out of
384          * the salt and the cleartext password
385          */
386         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
387                                            ENCTYPE_DES_CBC_MD5,
388                                            io->n.cleartext,
389                                            salt,
390                                            &key);
391         pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_MD5;
392         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
393         if (!pkb3->keys[k].value) {
394                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
395                 ldb_oom(io->ac->module->ldb);
396                 return LDB_ERR_OPERATIONS_ERROR;
397         }
398         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
399                                                    key.keyvalue.data,
400                                                    key.keyvalue.length);
401         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
402         if (!pkb3->keys[k].value->data) {
403                 ldb_oom(io->ac->module->ldb);
404                 return LDB_ERR_OPERATIONS_ERROR;
405         }
406         k++;
407
408         /*
409          * create ENCTYPE_DES_CBC_CRC key out of
410          * the salt and the cleartext password
411          */
412         krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
413                                            ENCTYPE_DES_CBC_CRC,
414                                            io->n.cleartext,
415                                            salt,
416                                            &key);
417         pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_CRC;
418         pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
419         if (!pkb3->keys[k].value) {
420                 krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
421                 ldb_oom(io->ac->module->ldb);
422                 return LDB_ERR_OPERATIONS_ERROR;
423         }
424         *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
425                                                    key.keyvalue.data,
426                                                    key.keyvalue.length);
427         krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
428         if (!pkb3->keys[k].value->data) {
429                 ldb_oom(io->ac->module->ldb);
430                 return LDB_ERR_OPERATIONS_ERROR;
431         }
432         k++;
433
434         /* fix up key number */
435         pkb3->num_keys = k;
436
437         /* initialize the old keys to zero */
438         pkb3->num_old_keys      = 0;
439         pkb3->old_keys          = NULL;
440         pkb3->unknown3_old      = NULL;
441
442         /* if there're no old keys, then we're done */
443         if (!old_scb) {
444                 return LDB_SUCCESS;
445         }
446
447         for (i=0; i < old_scb->sub.num_packages; i++) {
448                 if (old_scb->sub.packages[i].unknown1 != 0x00000001) {
449                         continue;
450                 }
451
452                 if (strcmp("Primary:Kerberos", old_scb->sub.packages[i].name) != 0) {
453                         continue;
454                 }
455
456                 if (!old_scb->sub.packages[i].data || !old_scb->sub.packages[i].data[0]) {
457                         continue;
458                 }
459
460                 old_scp = &old_scb->sub.packages[i];
461                 break;
462         }
463         /* Primary:Kerberos element of supplementalCredentials */
464         if (old_scp) {
465                 DATA_BLOB blob;
466
467                 blob = strhex_to_data_blob(old_scp->data);
468                 if (!blob.data) {
469                         ldb_oom(io->ac->module->ldb);
470                         return LDB_ERR_OPERATIONS_ERROR;
471                 }
472                 talloc_steal(io->ac, blob.data);
473
474                 /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
475                 ndr_err = ndr_pull_struct_blob(&blob, io->ac, &_old_pkb,
476                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
477                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
478                         NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
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         enum ndr_err_code ndr_err;
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                 ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac, &_old_scb,
883                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
884                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
885                         NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
886                         ldb_asprintf_errstring(io->ac->module->ldb,
887                                                "setup_supplemental_field: "
888                                                "failed to pull old supplementalCredentialsBlob: %s",
889                                                nt_errstr(status));
890                         return LDB_ERR_OPERATIONS_ERROR;
891                 }
892
893                 old_scb = &_old_scb;
894         }
895
896         if (io->domain->store_cleartext &&
897             (io->u.user_account_control & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
898                 pc = &packages[3];
899                 num_packages++;
900         }
901
902         /* Kerberos, WDigest, CLEARTEXT and termination(counted by the Packages element) */
903         pb.names = talloc_zero_array(io->ac, const char *, num_packages);
904
905         /*
906          * setup 'Primary:Kerberos' element
907          */
908         pb.names[0] = "Kerberos";
909
910         ret = setup_primary_kerberos(io, old_scb, &pkb);
911         if (ret != LDB_SUCCESS) {
912                 return ret;
913         }
914
915         ndr_err = ndr_push_struct_blob(&pkb_blob, io->ac, &pkb,
916                                        (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
917         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
918                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
919                 ldb_asprintf_errstring(io->ac->module->ldb,
920                                        "setup_supplemental_field: "
921                                        "failed to push package_PrimaryKerberosBlob: %s",
922                                        nt_errstr(status));
923                 return LDB_ERR_OPERATIONS_ERROR;
924         }
925         /*
926          * TODO:
927          *
928          * This is ugly, but we want to generate the same blob as
929          * w2k and w2k3...we should handle this in the idl
930          */
931         if (!data_blob_append(io->ac, &pkb_blob, zero16, sizeof(zero16))) {
932                 ldb_oom(io->ac->module->ldb);
933                 return LDB_ERR_OPERATIONS_ERROR;
934         }
935         pkb_hexstr = data_blob_hex_string(io->ac, &pkb_blob);
936         if (!pkb_hexstr) {
937                 ldb_oom(io->ac->module->ldb);
938                 return LDB_ERR_OPERATIONS_ERROR;
939         }
940         pk->name        = "Primary:Kerberos";
941         pk->unknown1    = 1;
942         pk->data        = pkb_hexstr;
943
944         /*
945          * setup 'Primary:WDigest' element
946          */
947         pb.names[1] = "WDigest";
948
949         ret = setup_primary_wdigest(io, old_scb, &pdb);
950         if (ret != LDB_SUCCESS) {
951                 return ret;
952         }
953
954         ndr_err = ndr_push_struct_blob(&pdb_blob, io->ac, &pdb,
955                                        (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
956         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
957                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
958                 ldb_asprintf_errstring(io->ac->module->ldb,
959                                        "setup_supplemental_field: "
960                                        "failed to push package_PrimaryWDigestBlob: %s",
961                                        nt_errstr(status));
962                 return LDB_ERR_OPERATIONS_ERROR;
963         }
964         pdb_hexstr = data_blob_hex_string(io->ac, &pdb_blob);
965         if (!pdb_hexstr) {
966                 ldb_oom(io->ac->module->ldb);
967                 return LDB_ERR_OPERATIONS_ERROR;
968         }
969         pd->name        = "Primary:WDigest";
970         pd->unknown1    = 1;
971         pd->data        = pdb_hexstr;
972
973         /*
974          * setup 'Primary:CLEARTEXT' element
975          */
976         if (pc) {
977                 pb.names[2]     = "CLEARTEXT";
978
979                 pcb.cleartext   = io->n.cleartext;
980
981                 ndr_err = ndr_push_struct_blob(&pcb_blob, io->ac, &pcb,
982                                                (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
983                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
984                         NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
985                         ldb_asprintf_errstring(io->ac->module->ldb,
986                                                "setup_supplemental_field: "
987                                                "failed to push package_PrimaryCLEARTEXTBlob: %s",
988                                                nt_errstr(status));
989                         return LDB_ERR_OPERATIONS_ERROR;
990                 }
991                 pcb_hexstr = data_blob_hex_string(io->ac, &pcb_blob);
992                 if (!pcb_hexstr) {
993                         ldb_oom(io->ac->module->ldb);
994                         return LDB_ERR_OPERATIONS_ERROR;
995                 }
996                 pc->name        = "Primary:CLEARTEXT";
997                 pc->unknown1    = 1;
998                 pc->data        = pcb_hexstr;
999         }
1000
1001         /*
1002          * setup 'Packages' element
1003          */
1004         ndr_err = ndr_push_struct_blob(&pb_blob, io->ac, &pb,
1005                                        (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
1006         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1007                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
1008                 ldb_asprintf_errstring(io->ac->module->ldb,
1009                                        "setup_supplemental_field: "
1010                                        "failed to push package_PackagesBlob: %s",
1011                                        nt_errstr(status));
1012                 return LDB_ERR_OPERATIONS_ERROR;
1013         }
1014         pb_hexstr = data_blob_hex_string(io->ac, &pb_blob);
1015         if (!pb_hexstr) {
1016                 ldb_oom(io->ac->module->ldb);
1017                 return LDB_ERR_OPERATIONS_ERROR;
1018         }
1019         pp->name        = "Packages";
1020         pp->unknown1    = 2;
1021         pp->data        = pb_hexstr;
1022
1023         /*
1024          * setup 'supplementalCredentials' value
1025          */
1026         scb.sub.num_packages    = num_packages;
1027         scb.sub.packages        = packages;
1028
1029         ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac, &scb,
1030                                        (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
1031         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1032                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
1033                 ldb_asprintf_errstring(io->ac->module->ldb,
1034                                        "setup_supplemental_field: "
1035                                        "failed to push supplementalCredentialsBlob: %s",
1036                                        nt_errstr(status));
1037                 return LDB_ERR_OPERATIONS_ERROR;
1038         }
1039
1040         return LDB_SUCCESS;
1041 }
1042
1043 static int setup_last_set_field(struct setup_password_fields_io *io)
1044 {
1045         /* set it as now */
1046         unix_to_nt_time(&io->g.last_set, time(NULL));
1047
1048         return LDB_SUCCESS;
1049 }
1050
1051 static int setup_kvno_field(struct setup_password_fields_io *io)
1052 {
1053         /* increment by one */
1054         io->g.kvno = io->o.kvno + 1;
1055
1056         return LDB_SUCCESS;
1057 }
1058
1059 static int setup_password_fields(struct setup_password_fields_io *io)
1060 {
1061         bool ok;
1062         int ret;
1063
1064         /*
1065          * refuse the change if someone want to change the cleartext
1066          * and supply his own hashes at the same time...
1067          */
1068         if (io->n.cleartext && (io->n.nt_hash || io->n.lm_hash)) {
1069                 ldb_asprintf_errstring(io->ac->module->ldb,
1070                                        "setup_password_fields: "
1071                                        "it's only allowed to set the cleartext password or the password hashes");
1072                 return LDB_ERR_UNWILLING_TO_PERFORM;
1073         }
1074
1075         if (io->n.cleartext && !io->n.nt_hash) {
1076                 struct samr_Password *hash;
1077
1078                 hash = talloc(io->ac, struct samr_Password);
1079                 if (!hash) {
1080                         ldb_oom(io->ac->module->ldb);
1081                         return LDB_ERR_OPERATIONS_ERROR;
1082                 }
1083
1084                 /* compute the new nt hash */
1085                 ok = E_md4hash(io->n.cleartext, hash->hash);
1086                 if (ok) {
1087                         io->n.nt_hash = hash;
1088                 } else {
1089                         ldb_asprintf_errstring(io->ac->module->ldb,
1090                                                "setup_password_fields: "
1091                                                "failed to generate nthash from cleartext password");
1092                         return LDB_ERR_OPERATIONS_ERROR;
1093                 }
1094         }
1095
1096         if (io->n.cleartext && !io->n.lm_hash) {
1097                 struct samr_Password *hash;
1098
1099                 hash = talloc(io->ac, struct samr_Password);
1100                 if (!hash) {
1101                         ldb_oom(io->ac->module->ldb);
1102                         return LDB_ERR_OPERATIONS_ERROR;
1103                 }
1104
1105                 /* compute the new lm hash */
1106                 ok = E_deshash(io->n.cleartext, hash->hash);
1107                 if (ok) {
1108                         io->n.lm_hash = hash;
1109                 } else {
1110                         talloc_free(hash->hash);
1111                 }
1112         }
1113
1114         ret = setup_nt_fields(io);
1115         if (ret != 0) {
1116                 return ret;
1117         }
1118
1119         ret = setup_lm_fields(io);
1120         if (ret != 0) {
1121                 return ret;
1122         }
1123
1124         ret = setup_supplemental_field(io);
1125         if (ret != 0) {
1126                 return ret;
1127         }
1128
1129         ret = setup_last_set_field(io);
1130         if (ret != 0) {
1131                 return ret;
1132         }
1133
1134         ret = setup_kvno_field(io);
1135         if (ret != 0) {
1136                 return ret;
1137         }
1138
1139         return LDB_SUCCESS;
1140 }
1141
1142 static struct ldb_handle *ph_init_handle(struct ldb_request *req, struct ldb_module *module, enum ph_type type)
1143 {
1144         struct ph_context *ac;
1145         struct ldb_handle *h;
1146
1147         h = talloc_zero(req, struct ldb_handle);
1148         if (h == NULL) {
1149                 ldb_set_errstring(module->ldb, "Out of Memory");
1150                 return NULL;
1151         }
1152
1153         h->module = module;
1154
1155         ac = talloc_zero(h, struct ph_context);
1156         if (ac == NULL) {
1157                 ldb_set_errstring(module->ldb, "Out of Memory");
1158                 talloc_free(h);
1159                 return NULL;
1160         }
1161
1162         h->private_data = (void *)ac;
1163
1164         h->state = LDB_ASYNC_INIT;
1165         h->status = LDB_SUCCESS;
1166
1167         ac->type = type;
1168         ac->module = module;
1169         ac->orig_req = req;
1170
1171         return h;
1172 }
1173
1174 static int get_domain_data_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
1175 {
1176         struct ph_context *ac;
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         ac = talloc_get_type(context, struct ph_context);
1635
1636         /* we are interested only in the single reply (base search) we receive here */
1637         if (ares->type == LDB_REPLY_ENTRY) {
1638                 if (ac->search_res != NULL) {
1639                         ldb_set_errstring(ldb, "Too many results");
1640                         talloc_free(ares);
1641                         return LDB_ERR_OPERATIONS_ERROR;
1642                 }
1643
1644                 /* if it is not an entry of type person this is an error */
1645                 /* TODO: remove this when sambaPassword will be in schema */
1646                 if (!ldb_msg_check_string_attribute(ares->message, "objectClass", "person")) {
1647                         ldb_set_errstring(ldb, "Object class violation");
1648                         talloc_free(ares);
1649                         return LDB_ERR_OBJECT_CLASS_VIOLATION;
1650                 }
1651
1652                 ac->search_res = talloc_steal(ac, ares);
1653         } else {
1654                 talloc_free(ares);
1655         }
1656
1657         return LDB_SUCCESS;
1658 }
1659
1660 static int password_hash_mod_search_self(struct ldb_handle *h) {
1661
1662         struct ph_context *ac;
1663         static const char * const attrs[] = { "userAccountControl", "lmPwdHistory", 
1664                                               "ntPwdHistory", 
1665                                               "objectSid", "msDS-KeyVersionNumber", 
1666                                               "objectClass", "userPrincipalName",
1667                                               "sAMAccountName", 
1668                                               "dBCSPwd", "unicodePwd",
1669                                               "supplementalCredentials",
1670                                               NULL };
1671
1672         ac = talloc_get_type(h->private_data, struct ph_context);
1673
1674         /* prepare the search operation */
1675         ac->search_req = talloc_zero(ac, struct ldb_request);
1676         if (ac->search_req == NULL) {
1677                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1678                 return LDB_ERR_OPERATIONS_ERROR;
1679         }
1680
1681         ac->search_req->operation = LDB_SEARCH;
1682         ac->search_req->op.search.base = ac->orig_req->op.mod.message->dn;
1683         ac->search_req->op.search.scope = LDB_SCOPE_BASE;
1684         ac->search_req->op.search.tree = ldb_parse_tree(ac->search_req, NULL);
1685         if (ac->search_req->op.search.tree == NULL) {
1686                 ldb_set_errstring(ac->module->ldb, "Invalid search filter");
1687                 return LDB_ERR_OPERATIONS_ERROR;
1688         }
1689         ac->search_req->op.search.attrs = attrs;
1690         ac->search_req->controls = NULL;
1691         ac->search_req->context = ac;
1692         ac->search_req->callback = get_self_callback;
1693         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
1694
1695         ac->step = PH_MOD_SEARCH_SELF;
1696
1697         return ldb_next_request(ac->module, ac->search_req);
1698 }
1699
1700 static int password_hash_mod_search_dom(struct ldb_handle *h) {
1701
1702         struct ph_context *ac;
1703         int ret;
1704
1705         ac = talloc_get_type(h->private_data, struct ph_context);
1706
1707         /* get object domain sid */
1708         ac->domain_sid = samdb_result_sid_prefix(ac, ac->search_res->message, "objectSid");
1709         if (ac->domain_sid == NULL) {
1710                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
1711                 return LDB_ERR_OPERATIONS_ERROR;
1712         }
1713
1714         /* get user domain data */
1715         ret = build_domain_data_request(ac);
1716         if (ret != LDB_SUCCESS) {
1717                 return ret;
1718         }
1719
1720         ac->step = PH_MOD_SEARCH_DOM;
1721
1722         return ldb_next_request(ac->module, ac->dom_req);
1723 }
1724
1725 static int password_hash_mod_do_mod(struct ldb_handle *h) {
1726
1727         struct ph_context *ac;
1728         struct domain_data *domain;
1729         struct smb_krb5_context *smb_krb5_context;
1730         struct ldb_message *msg;
1731         struct ldb_message *orig_msg;
1732         struct ldb_message *searched_msg;
1733         struct setup_password_fields_io io;
1734         int ret;
1735
1736         ac = talloc_get_type(h->private_data, struct ph_context);
1737
1738         domain = get_domain_data(ac->module, ac, ac->dom_res);
1739         if (domain == NULL) {
1740                 return LDB_ERR_OPERATIONS_ERROR;
1741         }
1742
1743         ac->mod_req = talloc(ac, struct ldb_request);
1744         if (ac->mod_req == NULL) {
1745                 return LDB_ERR_OPERATIONS_ERROR;
1746         }
1747
1748         *(ac->mod_req) = *(ac->orig_req);
1749         
1750         /* use a new message structure so that we can modify it */
1751         ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
1752         if (msg == NULL) {
1753                 return LDB_ERR_OPERATIONS_ERROR;
1754         }
1755
1756         /* modify dn */
1757         msg->dn = ac->orig_req->op.mod.message->dn;
1758
1759         /* Some operations below require kerberos contexts */
1760         if (smb_krb5_init_context(ac->mod_req, 
1761                                   ldb_get_opaque(h->module->ldb, "EventContext"), 
1762                                   &smb_krb5_context) != 0) {
1763                 return LDB_ERR_OPERATIONS_ERROR;
1764         }
1765
1766         orig_msg        = discard_const(ac->orig_req->op.mod.message);
1767         searched_msg    = ac->search_res->message;
1768
1769         ZERO_STRUCT(io);
1770         io.ac                           = ac;
1771         io.domain                       = domain;
1772         io.smb_krb5_context             = smb_krb5_context;
1773
1774         io.u.user_account_control       = samdb_result_uint(searched_msg, "userAccountControl", 0);
1775         io.u.sAMAccountName             = samdb_result_string(searched_msg, "samAccountName", NULL);
1776         io.u.user_principal_name        = samdb_result_string(searched_msg, "userPrincipalName", NULL);
1777         io.u.is_computer                = ldb_msg_check_string_attribute(searched_msg, "objectClass", "computer");
1778
1779         io.n.cleartext                  = samdb_result_string(orig_msg, "sambaPassword", NULL);
1780         io.n.nt_hash                    = samdb_result_hash(io.ac, orig_msg, "unicodePwd");
1781         io.n.lm_hash                    = samdb_result_hash(io.ac, orig_msg, "dBCSPwd");
1782
1783         io.o.kvno                       = samdb_result_uint(searched_msg, "msDs-KeyVersionNumber", 0);
1784         io.o.nt_history_len             = samdb_result_hashes(io.ac, searched_msg, "ntPwdHistory", &io.o.nt_history);
1785         io.o.lm_history_len             = samdb_result_hashes(io.ac, searched_msg, "lmPwdHistory", &io.o.lm_history);
1786         io.o.supplemental               = ldb_msg_find_ldb_val(searched_msg, "supplementalCredentials");
1787
1788         ret = setup_password_fields(&io);
1789         if (ret != LDB_SUCCESS) {
1790                 return ret;
1791         }
1792
1793         /* make sure we replace all the old attributes */
1794         ret = ldb_msg_add_empty(msg, "unicodePwd", LDB_FLAG_MOD_REPLACE, NULL);
1795         ret = ldb_msg_add_empty(msg, "dBCSPwd", LDB_FLAG_MOD_REPLACE, NULL);
1796         ret = ldb_msg_add_empty(msg, "ntPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1797         ret = ldb_msg_add_empty(msg, "lmPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1798         ret = ldb_msg_add_empty(msg, "supplementalCredentials", LDB_FLAG_MOD_REPLACE, NULL);
1799         ret = ldb_msg_add_empty(msg, "pwdLastSet", LDB_FLAG_MOD_REPLACE, NULL);
1800         ret = ldb_msg_add_empty(msg, "msDs-KeyVersionNumber", LDB_FLAG_MOD_REPLACE, NULL);
1801
1802         if (io.g.nt_hash) {
1803                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1804                                          "unicodePwd", io.g.nt_hash);
1805                 if (ret != LDB_SUCCESS) {
1806                         return ret;
1807                 }
1808         }
1809         if (io.g.lm_hash) {
1810                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1811                                          "dBCSPwd", io.g.lm_hash);
1812                 if (ret != LDB_SUCCESS) {
1813                         return ret;
1814                 }
1815         }
1816         if (io.g.nt_history_len > 0) {
1817                 ret = samdb_msg_add_hashes(ac, msg,
1818                                            "ntPwdHistory",
1819                                            io.g.nt_history,
1820                                            io.g.nt_history_len);
1821                 if (ret != LDB_SUCCESS) {
1822                         return ret;
1823                 }
1824         }
1825         if (io.g.lm_history_len > 0) {
1826                 ret = samdb_msg_add_hashes(ac, msg,
1827                                            "lmPwdHistory",
1828                                            io.g.lm_history,
1829                                            io.g.lm_history_len);
1830                 if (ret != LDB_SUCCESS) {
1831                         return ret;
1832                 }
1833         }
1834         if (io.g.supplemental.length > 0) {
1835                 ret = ldb_msg_add_value(msg, "supplementalCredentials",
1836                                         &io.g.supplemental, NULL);
1837                 if (ret != LDB_SUCCESS) {
1838                         return ret;
1839                 }
1840         }
1841         ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
1842                                    "pwdLastSet",
1843                                    io.g.last_set);
1844         if (ret != LDB_SUCCESS) {
1845                 return ret;
1846         }
1847         ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
1848                                  "msDs-KeyVersionNumber",
1849                                  io.g.kvno);
1850         if (ret != LDB_SUCCESS) {
1851                 return ret;
1852         }
1853
1854         h->state = LDB_ASYNC_INIT;
1855         h->status = LDB_SUCCESS;
1856
1857         ac->step = PH_MOD_DO_MOD;
1858
1859         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
1860
1861         /* perform the search */
1862         return ldb_next_request(ac->module, ac->mod_req);
1863 }
1864
1865 static int ph_wait(struct ldb_handle *handle) {
1866         struct ph_context *ac;
1867         int ret;
1868     
1869         if (!handle || !handle->private_data) {
1870                 return LDB_ERR_OPERATIONS_ERROR;
1871         }
1872
1873         if (handle->state == LDB_ASYNC_DONE) {
1874                 return handle->status;
1875         }
1876
1877         handle->state = LDB_ASYNC_PENDING;
1878         handle->status = LDB_SUCCESS;
1879
1880         ac = talloc_get_type(handle->private_data, struct ph_context);
1881
1882         switch (ac->step) {
1883         case PH_ADD_SEARCH_DOM:
1884                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1885
1886                 if (ret != LDB_SUCCESS) {
1887                         handle->status = ret;
1888                         goto done;
1889                 }
1890                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1891                         handle->status = ac->dom_req->handle->status;
1892                         goto done;
1893                 }
1894
1895                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1896                         return LDB_SUCCESS;
1897                 }
1898
1899                 /* domain search done, go on */
1900                 return password_hash_add_do_add(handle);
1901
1902         case PH_ADD_DO_ADD:
1903                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1904
1905                 if (ret != LDB_SUCCESS) {
1906                         handle->status = ret;
1907                         goto done;
1908                 }
1909                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1910                         handle->status = ac->down_req->handle->status;
1911                         goto done;
1912                 }
1913
1914                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1915                         return LDB_SUCCESS;
1916                 }
1917
1918                 break;
1919                 
1920         case PH_MOD_DO_REQ:
1921                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1922
1923                 if (ret != LDB_SUCCESS) {
1924                         handle->status = ret;
1925                         goto done;
1926                 }
1927                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1928                         handle->status = ac->down_req->handle->status;
1929                         goto done;
1930                 }
1931
1932                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1933                         return LDB_SUCCESS;
1934                 }
1935
1936                 /* non-password mods done, go on */
1937                 return password_hash_mod_search_self(handle);
1938                 
1939         case PH_MOD_SEARCH_SELF:
1940                 ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
1941
1942                 if (ret != LDB_SUCCESS) {
1943                         handle->status = ret;
1944                         goto done;
1945                 }
1946                 if (ac->search_req->handle->status != LDB_SUCCESS) {
1947                         handle->status = ac->search_req->handle->status;
1948                         goto done;
1949                 }
1950
1951                 if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
1952                         return LDB_SUCCESS;
1953                 }
1954
1955                 if (ac->search_res == NULL) {
1956                         return LDB_ERR_NO_SUCH_OBJECT;
1957                 }
1958
1959                 /* self search done, go on */
1960                 return password_hash_mod_search_dom(handle);
1961                 
1962         case PH_MOD_SEARCH_DOM:
1963                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1964
1965                 if (ret != LDB_SUCCESS) {
1966                         handle->status = ret;
1967                         goto done;
1968                 }
1969                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1970                         handle->status = ac->dom_req->handle->status;
1971                         goto done;
1972                 }
1973
1974                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1975                         return LDB_SUCCESS;
1976                 }
1977
1978                 /* domain search done, go on */
1979                 return password_hash_mod_do_mod(handle);
1980
1981         case PH_MOD_DO_MOD:
1982                 ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
1983
1984                 if (ret != LDB_SUCCESS) {
1985                         handle->status = ret;
1986                         goto done;
1987                 }
1988                 if (ac->mod_req->handle->status != LDB_SUCCESS) {
1989                         handle->status = ac->mod_req->handle->status;
1990                         goto done;
1991                 }
1992
1993                 if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
1994                         return LDB_SUCCESS;
1995                 }
1996
1997                 break;
1998                 
1999         default:
2000                 ret = LDB_ERR_OPERATIONS_ERROR;
2001                 goto done;
2002         }
2003
2004         ret = LDB_SUCCESS;
2005
2006 done:
2007         handle->state = LDB_ASYNC_DONE;
2008         return ret;
2009 }
2010
2011 static int ph_wait_all(struct ldb_handle *handle) {
2012
2013         int ret;
2014
2015         while (handle->state != LDB_ASYNC_DONE) {
2016                 ret = ph_wait(handle);
2017                 if (ret != LDB_SUCCESS) {
2018                         return ret;
2019                 }
2020         }
2021
2022         return handle->status;
2023 }
2024
2025 static int password_hash_wait(struct ldb_handle *handle, enum ldb_wait_type type)
2026 {
2027         if (type == LDB_WAIT_ALL) {
2028                 return ph_wait_all(handle);
2029         } else {
2030                 return ph_wait(handle);
2031         }
2032 }
2033
2034 static const struct ldb_module_ops password_hash_ops = {
2035         .name          = "password_hash",
2036         .add           = password_hash_add,
2037         .modify        = password_hash_modify,
2038         .wait          = password_hash_wait
2039 };
2040
2041
2042 int password_hash_module_init(void)
2043 {
2044         return ldb_register_module(&password_hash_ops);
2045 }