r25430: Add the loadparm context to all parametric options.
[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         NTSTATUS status;
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(global_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                 status = ndr_pull_struct_blob(&blob, io->ac, &_old_pkb,
476                                               (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
477                 if (!NT_STATUS_IS_OK(status)) {
478                         ldb_asprintf_errstring(io->ac->module->ldb,
479                                                "setup_primary_kerberos: "
480                                                "failed to pull old package_PrimaryKerberosBlob: %s",
481                                                nt_errstr(status));
482                         return LDB_ERR_OPERATIONS_ERROR;
483                 }
484
485                 if (_old_pkb.version != 3) {
486                         ldb_asprintf_errstring(io->ac->module->ldb,
487                                                "setup_primary_kerberos: "
488                                                "package_PrimaryKerberosBlob version[%u] expected[3]",
489                                                _old_pkb.version);
490                         return LDB_ERR_OPERATIONS_ERROR;
491                 }
492
493                 old_pkb3 = &_old_pkb.ctr.ctr3;
494         }
495
496         /* if we didn't found the old keys we're done */
497         if (!old_pkb3) {
498                 return LDB_SUCCESS;
499         }
500
501         /* fill in the old keys */
502         pkb3->num_old_keys      = old_pkb3->num_keys;
503         pkb3->old_keys          = old_pkb3->keys;
504         pkb3->unknown3_old      = old_pkb3->unknown3;
505
506         return LDB_SUCCESS;
507 }
508
509 static int setup_primary_wdigest(struct setup_password_fields_io *io,
510                                  const struct supplementalCredentialsBlob *old_scb,
511                                  struct package_PrimaryWDigestBlob *pdb)
512 {
513         DATA_BLOB sAMAccountName;
514         DATA_BLOB sAMAccountName_l;
515         DATA_BLOB sAMAccountName_u;
516         const char *user_principal_name = io->u.user_principal_name;
517         DATA_BLOB userPrincipalName;
518         DATA_BLOB userPrincipalName_l;
519         DATA_BLOB userPrincipalName_u;
520         DATA_BLOB netbios_domain;
521         DATA_BLOB netbios_domain_l;
522         DATA_BLOB netbios_domain_u;
523         DATA_BLOB dns_domain;
524         DATA_BLOB dns_domain_l;
525         DATA_BLOB dns_domain_u;
526         DATA_BLOB cleartext;
527         DATA_BLOB digest;
528         DATA_BLOB delim;
529         DATA_BLOB backslash;
530         uint8_t i;
531         struct {
532                 DATA_BLOB *user;
533                 DATA_BLOB *realm;
534                 DATA_BLOB *nt4dom;
535         } wdigest[] = {
536         /*
537          * See
538          * http://technet2.microsoft.com/WindowsServer/en/library/717b450c-f4a0-4cc9-86f4-cc0633aae5f91033.mspx?mfr=true
539          * for what precalculated hashes are supposed to be stored...
540          *
541          * I can't reproduce all values which should contain "Digest" as realm,
542          * am I doing something wrong or is w2k3 just broken...?
543          *
544          * W2K3 fills in following for a user:
545          *
546          * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
547          * sAMAccountName: NewUser2Sam
548          * userPrincipalName: NewUser2Princ@sub1.w2k3.vmnet1.vm.base
549          *
550          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
551          * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
552          * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
553          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
554          * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
555          * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
556          * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
557          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
558          * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
559          * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
560          * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
561          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
562          * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
563          * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
564          * 221c55284451ae9b3aacaa2a3c86f10f => NewUser2Princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
565          * 74e1be668853d4324d38c07e2acfb8ea => (w2k3 has a bug here!) newuser2princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
566          * e1e244ab7f098e3ae1761be7f9229bbb => NEWUSER2PRINC@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
567          * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
568          * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
569          * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
570          * 31dc704d3640335b2123d4ee28aa1f11 => ??? changes with NewUser2Sam => NewUser1Sam
571          * 36349f5cecd07320fb3bb0e119230c43 => ??? changes with NewUser2Sam => NewUser1Sam
572          * 12adf019d037fb535c01fd0608e78d9d => ??? changes with NewUser2Sam => NewUser1Sam
573          * 6feecf8e724906f3ee1105819c5105a1 => ??? changes with NewUser2Princ => NewUser1Princ
574          * 6c6911f3de6333422640221b9c51ff1f => ??? changes with NewUser2Princ => NewUser1Princ
575          * 4b279877e742895f9348ac67a8de2f69 => ??? changes with NewUser2Princ => NewUser1Princ
576          * db0c6bff069513e3ebb9870d29b57490 => ??? changes with NewUser2Sam => NewUser1Sam
577          * 45072621e56b1c113a4e04a8ff68cd0e => ??? changes with NewUser2Sam => NewUser1Sam
578          * 11d1220abc44a9c10cf91ef4a9c1de02 => ??? changes with NewUser2Sam => NewUser1Sam
579          *
580          * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
581          * sAMAccountName: NewUser2Sam
582          *
583          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
584          * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
585          * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
586          * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
587          * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
588          * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
589          * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
590          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
591          * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
592          * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
593          * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
594          * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
595          * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
596          * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
597          * 8a140d30b6f0a5912735dc1e3bc993b4 => NewUser2Sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
598          * 86d95b2faae6cae4ec261e7fbaccf093 => (here w2k3 is correct) newuser2sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
599          * dfeff1493110220efcdfc6362e5f5450 => NEWUSER2SAM@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
600          * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
601          * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
602          * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
603          * 31dc704d3640335b2123d4ee28aa1f11 => ???M1   changes with NewUser2Sam => NewUser1Sam
604          * 36349f5cecd07320fb3bb0e119230c43 => ???M1.L changes with newuser2sam => newuser1sam
605          * 12adf019d037fb535c01fd0608e78d9d => ???M1.U changes with NEWUSER2SAM => NEWUSER1SAM
606          * 569b4533f2d9e580211dd040e5e360a8 => ???M2   changes with NewUser2Princ => NewUser1Princ
607          * 52528bddf310a587c5d7e6a9ae2cbb20 => ???M2.L changes with newuser2princ => newuser1princ
608          * 4f629a4f0361289ca4255ab0f658fcd5 => ???M3 changes with NewUser2Princ => NewUser1Princ (doesn't depend on case of userPrincipal )
609          * db0c6bff069513e3ebb9870d29b57490 => ???M4 changes with NewUser2Sam => NewUser1Sam
610          * 45072621e56b1c113a4e04a8ff68cd0e => ???M5 changes with NewUser2Sam => NewUser1Sam (doesn't depend on case of sAMAccountName)
611          * 11d1220abc44a9c10cf91ef4a9c1de02 => ???M4.U changes with NEWUSER2SAM => NEWUSER1SAM
612          */
613
614         /*
615          * sAMAccountName, netbios_domain
616          */
617                 {
618                 .user   = &sAMAccountName,
619                 .realm  = &netbios_domain,
620                 },
621                 {
622                 .user   = &sAMAccountName_l,
623                 .realm  = &netbios_domain_l,
624                 },
625                 {
626                 .user   = &sAMAccountName_u,
627                 .realm  = &netbios_domain_u,
628                 },
629                 {
630                 .user   = &sAMAccountName,
631                 .realm  = &netbios_domain_u,
632                 },
633                 {
634                 .user   = &sAMAccountName,
635                 .realm  = &netbios_domain_l,
636                 },
637                 {
638                 .user   = &sAMAccountName_u,
639                 .realm  = &netbios_domain_l,
640                 },
641                 {
642                 .user   = &sAMAccountName_l,
643                 .realm  = &netbios_domain_u,
644                 },
645         /* 
646          * sAMAccountName, dns_domain
647          */
648                 {
649                 .user   = &sAMAccountName,
650                 .realm  = &dns_domain,
651                 },
652                 {
653                 .user   = &sAMAccountName_l,
654                 .realm  = &dns_domain_l,
655                 },
656                 {
657                 .user   = &sAMAccountName_u,
658                 .realm  = &dns_domain_u,
659                 },
660                 {
661                 .user   = &sAMAccountName,
662                 .realm  = &dns_domain_u,
663                 },
664                 {
665                 .user   = &sAMAccountName,
666                 .realm  = &dns_domain_l,
667                 },
668                 {
669                 .user   = &sAMAccountName_u,
670                 .realm  = &dns_domain_l,
671                 },
672                 {
673                 .user   = &sAMAccountName_l,
674                 .realm  = &dns_domain_u,
675                 },
676         /* 
677          * userPrincipalName, no realm
678          */
679                 {
680                 .user   = &userPrincipalName,
681                 },
682                 {
683                 /* 
684                  * NOTE: w2k3 messes this up, if the user has a real userPrincipalName,
685                  *       the fallback to the sAMAccountName based userPrincipalName is correct
686                  */
687                 .user   = &userPrincipalName_l,
688                 },
689                 {
690                 .user   = &userPrincipalName_u,
691                 },
692         /* 
693          * nt4dom\sAMAccountName, no realm
694          */
695                 {
696                 .user   = &sAMAccountName,
697                 .nt4dom = &netbios_domain
698                 },
699                 {
700                 .user   = &sAMAccountName_l,
701                 .nt4dom = &netbios_domain_l
702                 },
703                 {
704                 .user   = &sAMAccountName_u,
705                 .nt4dom = &netbios_domain_u
706                 },
707
708         /*
709          * the following ones are guessed depending on the technet2 article
710          * but not reproducable on a w2k3 server
711          */
712         /* sAMAccountName with "Digest" realm */
713                 {
714                 .user   = &sAMAccountName,
715                 .realm  = &digest
716                 },
717                 {
718                 .user   = &sAMAccountName_l,
719                 .realm  = &digest
720                 },
721                 {
722                 .user   = &sAMAccountName_u,
723                 .realm  = &digest
724                 },
725         /* userPrincipalName with "Digest" realm */
726                 {
727                 .user   = &userPrincipalName,
728                 .realm  = &digest
729                 },
730                 {
731                 .user   = &userPrincipalName_l,
732                 .realm  = &digest
733                 },
734                 {
735                 .user   = &userPrincipalName_u,
736                 .realm  = &digest
737                 },
738         /* nt4dom\\sAMAccountName with "Digest" realm */
739                 {
740                 .user   = &sAMAccountName,
741                 .nt4dom = &netbios_domain,
742                 .realm  = &digest
743                 },
744                 {
745                 .user   = &sAMAccountName_l,
746                 .nt4dom = &netbios_domain_l,
747                 .realm  = &digest
748                 },
749                 {
750                 .user   = &sAMAccountName_u,
751                 .nt4dom = &netbios_domain_u,
752                 .realm  = &digest
753                 },
754         };
755
756         /* prepare DATA_BLOB's used in the combinations array */
757         sAMAccountName          = data_blob_string_const(io->u.sAMAccountName);
758         sAMAccountName_l        = data_blob_string_const(strlower_talloc(io->ac, io->u.sAMAccountName));
759         if (!sAMAccountName_l.data) {
760                 ldb_oom(io->ac->module->ldb);
761                 return LDB_ERR_OPERATIONS_ERROR;
762         }
763         sAMAccountName_u        = data_blob_string_const(strupper_talloc(io->ac, io->u.sAMAccountName));
764         if (!sAMAccountName_u.data) {
765                 ldb_oom(io->ac->module->ldb);
766                 return LDB_ERR_OPERATIONS_ERROR;
767         }
768
769         /* if the user doesn't have a userPrincipalName, create one (with lower case realm) */
770         if (!user_principal_name) {
771                 user_principal_name = talloc_asprintf(io->ac, "%s@%s",
772                                                       io->u.sAMAccountName,
773                                                       io->domain->dns_domain);
774                 if (!user_principal_name) {
775                         ldb_oom(io->ac->module->ldb);
776                         return LDB_ERR_OPERATIONS_ERROR;
777                 }       
778         }
779         userPrincipalName       = data_blob_string_const(user_principal_name);
780         userPrincipalName_l     = data_blob_string_const(strlower_talloc(io->ac, user_principal_name));
781         if (!userPrincipalName_l.data) {
782                 ldb_oom(io->ac->module->ldb);
783                 return LDB_ERR_OPERATIONS_ERROR;
784         }
785         userPrincipalName_u     = data_blob_string_const(strupper_talloc(io->ac, user_principal_name));
786         if (!userPrincipalName_u.data) {
787                 ldb_oom(io->ac->module->ldb);
788                 return LDB_ERR_OPERATIONS_ERROR;
789         }
790
791         netbios_domain          = data_blob_string_const(io->domain->netbios_domain);
792         netbios_domain_l        = data_blob_string_const(strlower_talloc(io->ac, io->domain->netbios_domain));
793         if (!netbios_domain_l.data) {
794                 ldb_oom(io->ac->module->ldb);
795                 return LDB_ERR_OPERATIONS_ERROR;
796         }
797         netbios_domain_u        = data_blob_string_const(strupper_talloc(io->ac, io->domain->netbios_domain));
798         if (!netbios_domain_u.data) {
799                 ldb_oom(io->ac->module->ldb);
800                 return LDB_ERR_OPERATIONS_ERROR;
801         }
802
803         dns_domain              = data_blob_string_const(io->domain->dns_domain);
804         dns_domain_l            = data_blob_string_const(io->domain->dns_domain);
805         dns_domain_u            = data_blob_string_const(io->domain->realm);
806
807         cleartext               = data_blob_string_const(io->n.cleartext);
808
809         digest                  = data_blob_string_const("Digest");
810
811         delim                   = data_blob_string_const(":");
812         backslash               = data_blob_string_const("\\");
813
814         pdb->num_hashes = ARRAY_SIZE(wdigest);
815         pdb->hashes     = talloc_array(io->ac, struct package_PrimaryWDigestHash, pdb->num_hashes);
816         if (!pdb->hashes) {
817                 ldb_oom(io->ac->module->ldb);
818                 return LDB_ERR_OPERATIONS_ERROR;
819         }
820
821         for (i=0; i < ARRAY_SIZE(wdigest); i++) {
822                 struct MD5Context md5;
823                 MD5Init(&md5);
824                 if (wdigest[i].nt4dom) {
825                         MD5Update(&md5, wdigest[i].nt4dom->data, wdigest[i].nt4dom->length);
826                         MD5Update(&md5, backslash.data, backslash.length);
827                 }
828                 MD5Update(&md5, wdigest[i].user->data, wdigest[i].user->length);
829                 MD5Update(&md5, delim.data, delim.length);
830                 if (wdigest[i].realm) {
831                         MD5Update(&md5, wdigest[i].realm->data, wdigest[i].realm->length);
832                 }
833                 MD5Update(&md5, delim.data, delim.length);
834                 MD5Update(&md5, cleartext.data, cleartext.length);
835                 MD5Final(pdb->hashes[i].hash, &md5);
836         }
837
838         return LDB_SUCCESS;
839 }
840
841 static int setup_supplemental_field(struct setup_password_fields_io *io)
842 {
843         struct supplementalCredentialsBlob scb;
844         struct supplementalCredentialsBlob _old_scb;
845         struct supplementalCredentialsBlob *old_scb = NULL;
846         /* Packages + (Kerberos, WDigest and maybe CLEARTEXT) */
847         uint32_t num_packages = 1 + 2;
848         struct supplementalCredentialsPackage packages[1+3];
849         struct supplementalCredentialsPackage *pp = &packages[0];
850         struct supplementalCredentialsPackage *pk = &packages[1];
851         struct supplementalCredentialsPackage *pd = &packages[2];
852         struct supplementalCredentialsPackage *pc = NULL;
853         struct package_PackagesBlob pb;
854         DATA_BLOB pb_blob;
855         char *pb_hexstr;
856         struct package_PrimaryKerberosBlob pkb;
857         DATA_BLOB pkb_blob;
858         char *pkb_hexstr;
859         struct package_PrimaryWDigestBlob pdb;
860         DATA_BLOB pdb_blob;
861         char *pdb_hexstr;
862         struct package_PrimaryCLEARTEXTBlob pcb;
863         DATA_BLOB pcb_blob;
864         char *pcb_hexstr;
865         int ret;
866         NTSTATUS status;
867         uint8_t zero16[16];
868
869         ZERO_STRUCT(zero16);
870
871         if (!io->n.cleartext) {
872                 /* 
873                  * when we don't have a cleartext password
874                  * we can't setup a supplementalCredential value
875                  */
876                 return LDB_SUCCESS;
877         }
878
879         /* if there's an old supplementaCredentials blob then parse it */
880         if (io->o.supplemental) {
881                 status = ndr_pull_struct_blob_all(io->o.supplemental, io->ac, &_old_scb,
882                                                   (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
883                 if (!NT_STATUS_IS_OK(status)) {
884                         ldb_asprintf_errstring(io->ac->module->ldb,
885                                                "setup_supplemental_field: "
886                                                "failed to pull old supplementalCredentialsBlob: %s",
887                                                nt_errstr(status));
888                         return LDB_ERR_OPERATIONS_ERROR;
889                 }
890
891                 old_scb = &_old_scb;
892         }
893
894         if (io->domain->store_cleartext &&
895             (io->u.user_account_control & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
896                 pc = &packages[3];
897                 num_packages++;
898         }
899
900         /* Kerberos, WDigest, CLEARTEXT and termination(counted by the Packages element) */
901         pb.names = talloc_zero_array(io->ac, const char *, num_packages);
902
903         /*
904          * setup 'Primary:Kerberos' element
905          */
906         pb.names[0] = "Kerberos";
907
908         ret = setup_primary_kerberos(io, old_scb, &pkb);
909         if (ret != LDB_SUCCESS) {
910                 return ret;
911         }
912
913         status = ndr_push_struct_blob(&pkb_blob, io->ac, &pkb,
914                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
915         if (!NT_STATUS_IS_OK(status)) {
916                 ldb_asprintf_errstring(io->ac->module->ldb,
917                                        "setup_supplemental_field: "
918                                        "failed to push package_PrimaryKerberosBlob: %s",
919                                        nt_errstr(status));
920                 return LDB_ERR_OPERATIONS_ERROR;
921         }
922         /*
923          * TODO:
924          *
925          * This is ugly, but we want to generate the same blob as
926          * w2k and w2k3...we should handle this in the idl
927          */
928         if (!data_blob_append(io->ac, &pkb_blob, zero16, sizeof(zero16))) {
929                 ldb_oom(io->ac->module->ldb);
930                 return LDB_ERR_OPERATIONS_ERROR;
931         }
932         pkb_hexstr = data_blob_hex_string(io->ac, &pkb_blob);
933         if (!pkb_hexstr) {
934                 ldb_oom(io->ac->module->ldb);
935                 return LDB_ERR_OPERATIONS_ERROR;
936         }
937         pk->name        = "Primary:Kerberos";
938         pk->unknown1    = 1;
939         pk->data        = pkb_hexstr;
940
941         /*
942          * setup 'Primary:WDigest' element
943          */
944         pb.names[1] = "WDigest";
945
946         ret = setup_primary_wdigest(io, old_scb, &pdb);
947         if (ret != LDB_SUCCESS) {
948                 return ret;
949         }
950
951         status = ndr_push_struct_blob(&pdb_blob, io->ac, &pdb,
952                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
953         if (!NT_STATUS_IS_OK(status)) {
954                 ldb_asprintf_errstring(io->ac->module->ldb,
955                                        "setup_supplemental_field: "
956                                        "failed to push package_PrimaryWDigestBlob: %s",
957                                        nt_errstr(status));
958                 return LDB_ERR_OPERATIONS_ERROR;
959         }
960         pdb_hexstr = data_blob_hex_string(io->ac, &pdb_blob);
961         if (!pdb_hexstr) {
962                 ldb_oom(io->ac->module->ldb);
963                 return LDB_ERR_OPERATIONS_ERROR;
964         }
965         pd->name        = "Primary:WDigest";
966         pd->unknown1    = 1;
967         pd->data        = pdb_hexstr;
968
969         /*
970          * setup 'Primary:CLEARTEXT' element
971          */
972         if (pc) {
973                 pb.names[2]     = "CLEARTEXT";
974
975                 pcb.cleartext   = io->n.cleartext;
976
977                 status = ndr_push_struct_blob(&pcb_blob, io->ac, &pcb,
978                                               (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
979                 if (!NT_STATUS_IS_OK(status)) {
980                         ldb_asprintf_errstring(io->ac->module->ldb,
981                                                "setup_supplemental_field: "
982                                                "failed to push package_PrimaryCLEARTEXTBlob: %s",
983                                                nt_errstr(status));
984                         return LDB_ERR_OPERATIONS_ERROR;
985                 }
986                 pcb_hexstr = data_blob_hex_string(io->ac, &pcb_blob);
987                 if (!pcb_hexstr) {
988                         ldb_oom(io->ac->module->ldb);
989                         return LDB_ERR_OPERATIONS_ERROR;
990                 }
991                 pc->name        = "Primary:CLEARTEXT";
992                 pc->unknown1    = 1;
993                 pc->data        = pcb_hexstr;
994         }
995
996         /*
997          * setup 'Packages' element
998          */
999         status = ndr_push_struct_blob(&pb_blob, io->ac, &pb,
1000                                       (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
1001         if (!NT_STATUS_IS_OK(status)) {
1002                 ldb_asprintf_errstring(io->ac->module->ldb,
1003                                        "setup_supplemental_field: "
1004                                        "failed to push package_PackagesBlob: %s",
1005                                        nt_errstr(status));
1006                 return LDB_ERR_OPERATIONS_ERROR;
1007         }
1008         pb_hexstr = data_blob_hex_string(io->ac, &pb_blob);
1009         if (!pb_hexstr) {
1010                 ldb_oom(io->ac->module->ldb);
1011                 return LDB_ERR_OPERATIONS_ERROR;
1012         }
1013         pp->name        = "Packages";
1014         pp->unknown1    = 2;
1015         pp->data        = pb_hexstr;
1016
1017         /*
1018          * setup 'supplementalCredentials' value
1019          */
1020         scb.sub.num_packages    = num_packages;
1021         scb.sub.packages        = packages;
1022
1023         status = ndr_push_struct_blob(&io->g.supplemental, io->ac, &scb,
1024                                       (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
1025         if (!NT_STATUS_IS_OK(status)) {
1026                 ldb_asprintf_errstring(io->ac->module->ldb,
1027                                        "setup_supplemental_field: "
1028                                        "failed to push supplementalCredentialsBlob: %s",
1029                                        nt_errstr(status));
1030                 return LDB_ERR_OPERATIONS_ERROR;
1031         }
1032
1033         return LDB_SUCCESS;
1034 }
1035
1036 static int setup_last_set_field(struct setup_password_fields_io *io)
1037 {
1038         /* set it as now */
1039         unix_to_nt_time(&io->g.last_set, time(NULL));
1040
1041         return LDB_SUCCESS;
1042 }
1043
1044 static int setup_kvno_field(struct setup_password_fields_io *io)
1045 {
1046         /* increment by one */
1047         io->g.kvno = io->o.kvno + 1;
1048
1049         return LDB_SUCCESS;
1050 }
1051
1052 static int setup_password_fields(struct setup_password_fields_io *io)
1053 {
1054         bool ok;
1055         int ret;
1056
1057         /*
1058          * refuse the change if someone want to change the cleartext
1059          * and supply his own hashes at the same time...
1060          */
1061         if (io->n.cleartext && (io->n.nt_hash || io->n.lm_hash)) {
1062                 ldb_asprintf_errstring(io->ac->module->ldb,
1063                                        "setup_password_fields: "
1064                                        "it's only allowed to set the cleartext password or the password hashes");
1065                 return LDB_ERR_UNWILLING_TO_PERFORM;
1066         }
1067
1068         if (io->n.cleartext && !io->n.nt_hash) {
1069                 struct samr_Password *hash;
1070
1071                 hash = talloc(io->ac, struct samr_Password);
1072                 if (!hash) {
1073                         ldb_oom(io->ac->module->ldb);
1074                         return LDB_ERR_OPERATIONS_ERROR;
1075                 }
1076
1077                 /* compute the new nt hash */
1078                 ok = E_md4hash(io->n.cleartext, hash->hash);
1079                 if (ok) {
1080                         io->n.nt_hash = hash;
1081                 } else {
1082                         ldb_asprintf_errstring(io->ac->module->ldb,
1083                                                "setup_password_fields: "
1084                                                "failed to generate nthash from cleartext password");
1085                         return LDB_ERR_OPERATIONS_ERROR;
1086                 }
1087         }
1088
1089         if (io->n.cleartext && !io->n.lm_hash) {
1090                 struct samr_Password *hash;
1091
1092                 hash = talloc(io->ac, struct samr_Password);
1093                 if (!hash) {
1094                         ldb_oom(io->ac->module->ldb);
1095                         return LDB_ERR_OPERATIONS_ERROR;
1096                 }
1097
1098                 /* compute the new lm hash */
1099                 ok = E_deshash(io->n.cleartext, hash->hash);
1100                 if (ok) {
1101                         io->n.lm_hash = hash;
1102                 } else {
1103                         talloc_free(hash->hash);
1104                 }
1105         }
1106
1107         ret = setup_nt_fields(io);
1108         if (ret != 0) {
1109                 return ret;
1110         }
1111
1112         ret = setup_lm_fields(io);
1113         if (ret != 0) {
1114                 return ret;
1115         }
1116
1117         ret = setup_supplemental_field(io);
1118         if (ret != 0) {
1119                 return ret;
1120         }
1121
1122         ret = setup_last_set_field(io);
1123         if (ret != 0) {
1124                 return ret;
1125         }
1126
1127         ret = setup_kvno_field(io);
1128         if (ret != 0) {
1129                 return ret;
1130         }
1131
1132         return LDB_SUCCESS;
1133 }
1134
1135 static struct ldb_handle *ph_init_handle(struct ldb_request *req, struct ldb_module *module, enum ph_type type)
1136 {
1137         struct ph_context *ac;
1138         struct ldb_handle *h;
1139
1140         h = talloc_zero(req, struct ldb_handle);
1141         if (h == NULL) {
1142                 ldb_set_errstring(module->ldb, "Out of Memory");
1143                 return NULL;
1144         }
1145
1146         h->module = module;
1147
1148         ac = talloc_zero(h, struct ph_context);
1149         if (ac == NULL) {
1150                 ldb_set_errstring(module->ldb, "Out of Memory");
1151                 talloc_free(h);
1152                 return NULL;
1153         }
1154
1155         h->private_data = (void *)ac;
1156
1157         h->state = LDB_ASYNC_INIT;
1158         h->status = LDB_SUCCESS;
1159
1160         ac->type = type;
1161         ac->module = module;
1162         ac->orig_req = req;
1163
1164         return h;
1165 }
1166
1167 static int get_domain_data_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
1168 {
1169         struct ph_context *ac;
1170
1171         ac = talloc_get_type(context, struct ph_context);
1172
1173         /* we are interested only in the single reply (base search) we receive here */
1174         if (ares->type == LDB_REPLY_ENTRY) {
1175                 if (ac->dom_res != NULL) {
1176                         ldb_set_errstring(ldb, "Too many results");
1177                         talloc_free(ares);
1178                         return LDB_ERR_OPERATIONS_ERROR;
1179                 }
1180                 ac->dom_res = talloc_steal(ac, ares);
1181         } else {
1182                 talloc_free(ares);
1183         }
1184
1185         return LDB_SUCCESS;
1186 }
1187
1188 static int build_domain_data_request(struct ph_context *ac)
1189 {
1190         /* attrs[] is returned from this function in
1191            ac->dom_req->op.search.attrs, so it must be static, as
1192            otherwise the compiler can put it on the stack */
1193         static const char * const attrs[] = { "pwdProperties", "pwdHistoryLength", NULL };
1194         char *filter;
1195
1196         ac->dom_req = talloc_zero(ac, struct ldb_request);
1197         if (ac->dom_req == NULL) {
1198                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1199                 return LDB_ERR_OPERATIONS_ERROR;
1200         }
1201         ac->dom_req->operation = LDB_SEARCH;
1202         ac->dom_req->op.search.base = ldb_get_default_basedn(ac->module->ldb);
1203         ac->dom_req->op.search.scope = LDB_SCOPE_SUBTREE;
1204
1205         filter = talloc_asprintf(ac->dom_req, "(&(objectSid=%s)(|(objectClass=domain)(objectClass=builtinDomain)))", 
1206                                  ldap_encode_ndr_dom_sid(ac->dom_req, ac->domain_sid));
1207         if (filter == NULL) {
1208                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1209                 talloc_free(ac->dom_req);
1210                 return LDB_ERR_OPERATIONS_ERROR;
1211         }
1212
1213         ac->dom_req->op.search.tree = ldb_parse_tree(ac->dom_req, filter);
1214         if (ac->dom_req->op.search.tree == NULL) {
1215                 ldb_set_errstring(ac->module->ldb, "Invalid search filter");
1216                 talloc_free(ac->dom_req);
1217                 return LDB_ERR_OPERATIONS_ERROR;
1218         }
1219         ac->dom_req->op.search.attrs = attrs;
1220         ac->dom_req->controls = NULL;
1221         ac->dom_req->context = ac;
1222         ac->dom_req->callback = get_domain_data_callback;
1223         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->dom_req);
1224
1225         return LDB_SUCCESS;
1226 }
1227
1228 static struct domain_data *get_domain_data(struct ldb_module *module, void *ctx, struct ldb_reply *res)
1229 {
1230         struct domain_data *data;
1231         const char *tmp;
1232         struct ph_context *ac;
1233         char *p;
1234
1235         ac = talloc_get_type(ctx, struct ph_context);
1236
1237         data = talloc_zero(ac, struct domain_data);
1238         if (data == NULL) {
1239                 return NULL;
1240         }
1241
1242         if (res == NULL) {
1243                 ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Could not find this user's domain: %s!\n", dom_sid_string(data, ac->domain_sid));
1244                 talloc_free(data);
1245                 return NULL;
1246         }
1247
1248         data->pwdProperties= samdb_result_uint(res->message, "pwdProperties", 0);
1249         data->store_cleartext = data->pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;
1250         data->pwdHistoryLength = samdb_result_uint(res->message, "pwdHistoryLength", 0);
1251
1252         /* For a domain DN, this puts things in dotted notation */
1253         /* For builtin domains, this will give details for the host,
1254          * but that doesn't really matter, as it's just used for salt
1255          * and kerberos principals, which don't exist here */
1256
1257         tmp = ldb_dn_canonical_string(ctx, res->message->dn);
1258         if (!tmp) {
1259                 return NULL;
1260         }
1261         
1262         /* But it puts a trailing (or just before 'builtin') / on things, so kill that */
1263         p = strchr(tmp, '/');
1264         if (p) {
1265                 p[0] = '\0';
1266         }
1267
1268         if (tmp != NULL) {
1269                 data->dns_domain = strlower_talloc(data, tmp);
1270                 if (data->dns_domain == NULL) {
1271                         ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
1272                         return NULL;
1273                 }
1274                 data->realm = strupper_talloc(data, tmp);
1275                 if (data->realm == NULL) {
1276                         ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
1277                         return NULL;
1278                 }
1279                 p = strchr(tmp, '.');
1280                 if (p) {
1281                         p[0] = '\0';
1282                 }
1283                 data->netbios_domain = strupper_talloc(data, tmp);
1284                 if (data->netbios_domain == NULL) {
1285                         ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
1286                         return NULL;
1287                 }
1288         }
1289
1290         return data;
1291 }
1292
1293 static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
1294 {
1295         struct ldb_handle *h;
1296         struct ph_context *ac;
1297         struct ldb_message_element *sambaAttr;
1298         struct ldb_message_element *ntAttr;
1299         struct ldb_message_element *lmAttr;
1300         int ret;
1301
1302         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
1303
1304         if (ldb_dn_is_special(req->op.add.message->dn)) { /* do not manipulate our control entries */
1305                 return ldb_next_request(module, req);
1306         }
1307
1308         /* If the caller is manipulating the local passwords directly, let them pass */
1309         if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
1310                                 req->op.add.message->dn) == 0) {
1311                 return ldb_next_request(module, req);
1312         }
1313
1314         /* nobody must touch this fields */
1315         if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
1316                 return LDB_ERR_UNWILLING_TO_PERFORM;
1317         }
1318         if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
1319                 return LDB_ERR_UNWILLING_TO_PERFORM;
1320         }
1321         if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
1322                 return LDB_ERR_UNWILLING_TO_PERFORM;
1323         }
1324
1325         /* If no part of this ADD touches the sambaPassword, or the NT
1326          * or LM hashes, then we don't need to make any changes.  */
1327
1328         sambaAttr = ldb_msg_find_element(req->op.mod.message, "sambaPassword");
1329         ntAttr = ldb_msg_find_element(req->op.mod.message, "unicodePwd");
1330         lmAttr = ldb_msg_find_element(req->op.mod.message, "dBCSPwd");
1331
1332         if ((!sambaAttr) && (!ntAttr) && (!lmAttr)) {
1333                 return ldb_next_request(module, req);
1334         }
1335
1336         /* if it is not an entry of type person its an error */
1337         /* TODO: remove this when sambaPassword will be in schema */
1338         if (!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "person")) {
1339                 ldb_set_errstring(module->ldb, "Cannot set a password on entry that does not have objectClass 'person'");
1340                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1341         }
1342
1343         /* check sambaPassword is single valued here */
1344         /* TODO: remove this when sambaPassword will be single valued in schema */
1345         if (sambaAttr && sambaAttr->num_values > 1) {
1346                 ldb_set_errstring(module->ldb, "mupltiple values for sambaPassword not allowed!\n");
1347                 return LDB_ERR_CONSTRAINT_VIOLATION;
1348         }
1349
1350         if (ntAttr && (ntAttr->num_values > 1)) {
1351                 ldb_set_errstring(module->ldb, "mupltiple values for unicodePwd not allowed!\n");
1352                 return LDB_ERR_CONSTRAINT_VIOLATION;
1353         }
1354         if (lmAttr && (lmAttr->num_values > 1)) {
1355                 ldb_set_errstring(module->ldb, "mupltiple values for dBCSPwd not allowed!\n");
1356                 return LDB_ERR_CONSTRAINT_VIOLATION;
1357         }
1358
1359         if (sambaAttr && sambaAttr->num_values == 0) {
1360                 ldb_set_errstring(module->ldb, "sambaPassword must have a value!\n");
1361                 return LDB_ERR_CONSTRAINT_VIOLATION;
1362         }
1363
1364         if (ntAttr && (ntAttr->num_values == 0)) {
1365                 ldb_set_errstring(module->ldb, "unicodePwd must have a value!\n");
1366                 return LDB_ERR_CONSTRAINT_VIOLATION;
1367         }
1368         if (lmAttr && (lmAttr->num_values == 0)) {
1369                 ldb_set_errstring(module->ldb, "dBCSPwd must have a value!\n");
1370                 return LDB_ERR_CONSTRAINT_VIOLATION;
1371         }
1372
1373         h = ph_init_handle(req, module, PH_ADD);
1374         if (!h) {
1375                 return LDB_ERR_OPERATIONS_ERROR;
1376         }
1377         ac = talloc_get_type(h->private_data, struct ph_context);
1378
1379         /* get user domain data */
1380         ac->domain_sid = samdb_result_sid_prefix(ac, req->op.add.message, "objectSid");
1381         if (ac->domain_sid == NULL) {
1382                 ldb_debug(module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
1383                 return LDB_ERR_OPERATIONS_ERROR;
1384         }
1385
1386         ret = build_domain_data_request(ac);
1387         if (ret != LDB_SUCCESS) {
1388                 return ret;
1389         }
1390
1391         ac->step = PH_ADD_SEARCH_DOM;
1392
1393         req->handle = h;
1394
1395         return ldb_next_request(module, ac->dom_req);
1396 }
1397
1398 static int password_hash_add_do_add(struct ldb_handle *h) {
1399
1400         struct ph_context *ac;
1401         struct domain_data *domain;
1402         struct smb_krb5_context *smb_krb5_context;
1403         struct ldb_message *msg;
1404         struct setup_password_fields_io io;
1405         int ret;
1406
1407         ac = talloc_get_type(h->private_data, struct ph_context);
1408
1409         domain = get_domain_data(ac->module, ac, ac->dom_res);
1410         if (domain == NULL) {
1411                 return LDB_ERR_OPERATIONS_ERROR;
1412         }
1413
1414         ac->down_req = talloc(ac, struct ldb_request);
1415         if (ac->down_req == NULL) {
1416                 return LDB_ERR_OPERATIONS_ERROR;
1417         }
1418
1419         *(ac->down_req) = *(ac->orig_req);
1420         ac->down_req->op.add.message = msg = ldb_msg_copy_shallow(ac->down_req, ac->orig_req->op.add.message);
1421         if (ac->down_req->op.add.message == NULL) {
1422                 return LDB_ERR_OPERATIONS_ERROR;
1423         }
1424
1425         /* Some operations below require kerberos contexts */
1426         if (smb_krb5_init_context(ac->down_req, 
1427                                   ldb_get_opaque(h->module->ldb, "EventContext"), 
1428                                   &smb_krb5_context) != 0) {
1429                 return LDB_ERR_OPERATIONS_ERROR;
1430         }
1431
1432         ZERO_STRUCT(io);
1433         io.ac                           = ac;
1434         io.domain                       = domain;
1435         io.smb_krb5_context             = smb_krb5_context;
1436
1437         io.u.user_account_control       = samdb_result_uint(msg, "userAccountControl", 0);
1438         io.u.sAMAccountName             = samdb_result_string(msg, "samAccountName", NULL);
1439         io.u.user_principal_name        = samdb_result_string(msg, "userPrincipalName", NULL);
1440         io.u.is_computer                = ldb_msg_check_string_attribute(msg, "objectClass", "computer");
1441
1442         io.n.cleartext                  = samdb_result_string(msg, "sambaPassword", NULL);
1443         io.n.nt_hash                    = samdb_result_hash(io.ac, msg, "unicodePwd");
1444         io.n.lm_hash                    = samdb_result_hash(io.ac, msg, "dBCSPwd");
1445
1446         /* remove attributes */
1447         if (io.n.cleartext) ldb_msg_remove_attr(msg, "sambaPassword");
1448         if (io.n.nt_hash) ldb_msg_remove_attr(msg, "unicodePwd");
1449         if (io.n.lm_hash) ldb_msg_remove_attr(msg, "dBCSPwd");
1450         ldb_msg_remove_attr(msg, "pwdLastSet");
1451         io.o.kvno = samdb_result_uint(msg, "msDs-KeyVersionNumber", 1) - 1;
1452         ldb_msg_remove_attr(msg, "msDs-KeyVersionNumber");
1453
1454         ret = setup_password_fields(&io);
1455         if (ret != LDB_SUCCESS) {
1456                 return ret;
1457         }
1458
1459         if (io.g.nt_hash) {
1460                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1461                                          "unicodePwd", io.g.nt_hash);
1462                 if (ret != LDB_SUCCESS) {
1463                         return ret;
1464                 }
1465         }
1466         if (io.g.lm_hash) {
1467                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1468                                          "dBCSPwd", io.g.lm_hash);
1469                 if (ret != LDB_SUCCESS) {
1470                         return ret;
1471                 }
1472         }
1473         if (io.g.nt_history_len > 0) {
1474                 ret = samdb_msg_add_hashes(ac, msg,
1475                                            "ntPwdHistory",
1476                                            io.g.nt_history,
1477                                            io.g.nt_history_len);
1478                 if (ret != LDB_SUCCESS) {
1479                         return ret;
1480                 }
1481         }
1482         if (io.g.lm_history_len > 0) {
1483                 ret = samdb_msg_add_hashes(ac, msg,
1484                                            "lmPwdHistory",
1485                                            io.g.lm_history,
1486                                            io.g.lm_history_len);
1487                 if (ret != LDB_SUCCESS) {
1488                         return ret;
1489                 }
1490         }
1491         if (io.g.supplemental.length > 0) {
1492                 ret = ldb_msg_add_value(msg, "supplementalCredentials",
1493                                         &io.g.supplemental, NULL);
1494                 if (ret != LDB_SUCCESS) {
1495                         return ret;
1496                 }
1497         }
1498         ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
1499                                    "pwdLastSet",
1500                                    io.g.last_set);
1501         if (ret != LDB_SUCCESS) {
1502                 return ret;
1503         }
1504         ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
1505                                  "msDs-KeyVersionNumber",
1506                                  io.g.kvno);
1507         if (ret != LDB_SUCCESS) {
1508                 return ret;
1509         }
1510
1511         h->state = LDB_ASYNC_INIT;
1512         h->status = LDB_SUCCESS;
1513
1514         ac->step = PH_ADD_DO_ADD;
1515
1516         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->down_req);
1517
1518         /* perform the operation */
1519         return ldb_next_request(ac->module, ac->down_req);
1520 }
1521
1522 static int password_hash_mod_search_self(struct ldb_handle *h);
1523
1524 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
1525 {
1526         struct ldb_handle *h;
1527         struct ph_context *ac;
1528         struct ldb_message_element *sambaAttr;
1529         struct ldb_message_element *ntAttr;
1530         struct ldb_message_element *lmAttr;
1531         struct ldb_message *msg;
1532
1533         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");
1534
1535         if (ldb_dn_is_special(req->op.mod.message->dn)) { /* do not manipulate our control entries */
1536                 return ldb_next_request(module, req);
1537         }
1538         
1539         /* If the caller is manipulating the local passwords directly, let them pass */
1540         if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
1541                                 req->op.mod.message->dn) == 0) {
1542                 return ldb_next_request(module, req);
1543         }
1544
1545         /* nobody must touch password Histories */
1546         if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
1547                 return LDB_ERR_UNWILLING_TO_PERFORM;
1548         }
1549         if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
1550                 return LDB_ERR_UNWILLING_TO_PERFORM;
1551         }
1552         if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
1553                 return LDB_ERR_UNWILLING_TO_PERFORM;
1554         }
1555
1556         sambaAttr = ldb_msg_find_element(req->op.mod.message, "sambaPassword");
1557         ntAttr = ldb_msg_find_element(req->op.mod.message, "unicodePwd");
1558         lmAttr = ldb_msg_find_element(req->op.mod.message, "dBCSPwd");
1559
1560         /* If no part of this touches the sambaPassword OR unicodePwd and/or dBCSPwd, then we don't
1561          * need to make any changes.  For password changes/set there should
1562          * be a 'delete' or a 'modify' on this attribute. */
1563         if ((!sambaAttr) && (!ntAttr) && (!lmAttr)) {
1564                 return ldb_next_request(module, req);
1565         }
1566
1567         /* check passwords are single valued here */
1568         /* TODO: remove this when passwords will be single valued in schema */
1569         if (sambaAttr && (sambaAttr->num_values > 1)) {
1570                 return LDB_ERR_CONSTRAINT_VIOLATION;
1571         }
1572         if (ntAttr && (ntAttr->num_values > 1)) {
1573                 return LDB_ERR_CONSTRAINT_VIOLATION;
1574         }
1575         if (lmAttr && (lmAttr->num_values > 1)) {
1576                 return LDB_ERR_CONSTRAINT_VIOLATION;
1577         }
1578
1579         h = ph_init_handle(req, module, PH_MOD);
1580         if (!h) {
1581                 return LDB_ERR_OPERATIONS_ERROR;
1582         }
1583         ac = talloc_get_type(h->private_data, struct ph_context);
1584
1585         /* return or own handle to deal with this call */
1586         req->handle = h;
1587
1588         /* prepare the first operation */
1589         ac->down_req = talloc_zero(ac, struct ldb_request);
1590         if (ac->down_req == NULL) {
1591                 ldb_set_errstring(module->ldb, "Out of memory!");
1592                 return LDB_ERR_OPERATIONS_ERROR;
1593         }
1594
1595         *(ac->down_req) = *req; /* copy the request */
1596
1597         /* use a new message structure so that we can modify it */
1598         ac->down_req->op.mod.message = msg = ldb_msg_copy_shallow(ac->down_req, req->op.mod.message);
1599
1600         /* - remove any imodification to the password from the first commit
1601          *   we will make the real modification later */
1602         if (sambaAttr) ldb_msg_remove_attr(msg, "sambaPassword");
1603         if (ntAttr) ldb_msg_remove_attr(msg, "unicodePwd");
1604         if (lmAttr) ldb_msg_remove_attr(msg, "dBCSPwd");
1605
1606         /* if there was nothing else to be modify skip to next step */
1607         if (msg->num_elements == 0) {
1608                 talloc_free(ac->down_req);
1609                 ac->down_req = NULL;
1610                 return password_hash_mod_search_self(h);
1611         }
1612         
1613         ac->down_req->context = NULL;
1614         ac->down_req->callback = NULL;
1615
1616         ac->step = PH_MOD_DO_REQ;
1617
1618         ldb_set_timeout_from_prev_req(module->ldb, req, ac->down_req);
1619
1620         return ldb_next_request(module, ac->down_req);
1621 }
1622
1623 static int get_self_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
1624 {
1625         struct ph_context *ac;
1626
1627         ac = talloc_get_type(context, struct ph_context);
1628
1629         /* we are interested only in the single reply (base search) we receive here */
1630         if (ares->type == LDB_REPLY_ENTRY) {
1631                 if (ac->search_res != NULL) {
1632                         ldb_set_errstring(ldb, "Too many results");
1633                         talloc_free(ares);
1634                         return LDB_ERR_OPERATIONS_ERROR;
1635                 }
1636
1637                 /* if it is not an entry of type person this is an error */
1638                 /* TODO: remove this when sambaPassword will be in schema */
1639                 if (!ldb_msg_check_string_attribute(ares->message, "objectClass", "person")) {
1640                         ldb_set_errstring(ldb, "Object class violation");
1641                         talloc_free(ares);
1642                         return LDB_ERR_OBJECT_CLASS_VIOLATION;
1643                 }
1644
1645                 ac->search_res = talloc_steal(ac, ares);
1646         } else {
1647                 talloc_free(ares);
1648         }
1649
1650         return LDB_SUCCESS;
1651 }
1652
1653 static int password_hash_mod_search_self(struct ldb_handle *h) {
1654
1655         struct ph_context *ac;
1656         static const char * const attrs[] = { "userAccountControl", "lmPwdHistory", 
1657                                               "ntPwdHistory", 
1658                                               "objectSid", "msDS-KeyVersionNumber", 
1659                                               "objectClass", "userPrincipalName",
1660                                               "sAMAccountName", 
1661                                               "dBCSPwd", "unicodePwd",
1662                                               "supplementalCredentials",
1663                                               NULL };
1664
1665         ac = talloc_get_type(h->private_data, struct ph_context);
1666
1667         /* prepare the search operation */
1668         ac->search_req = talloc_zero(ac, struct ldb_request);
1669         if (ac->search_req == NULL) {
1670                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
1671                 return LDB_ERR_OPERATIONS_ERROR;
1672         }
1673
1674         ac->search_req->operation = LDB_SEARCH;
1675         ac->search_req->op.search.base = ac->orig_req->op.mod.message->dn;
1676         ac->search_req->op.search.scope = LDB_SCOPE_BASE;
1677         ac->search_req->op.search.tree = ldb_parse_tree(ac->search_req, NULL);
1678         if (ac->search_req->op.search.tree == NULL) {
1679                 ldb_set_errstring(ac->module->ldb, "Invalid search filter");
1680                 return LDB_ERR_OPERATIONS_ERROR;
1681         }
1682         ac->search_req->op.search.attrs = attrs;
1683         ac->search_req->controls = NULL;
1684         ac->search_req->context = ac;
1685         ac->search_req->callback = get_self_callback;
1686         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
1687
1688         ac->step = PH_MOD_SEARCH_SELF;
1689
1690         return ldb_next_request(ac->module, ac->search_req);
1691 }
1692
1693 static int password_hash_mod_search_dom(struct ldb_handle *h) {
1694
1695         struct ph_context *ac;
1696         int ret;
1697
1698         ac = talloc_get_type(h->private_data, struct ph_context);
1699
1700         /* get object domain sid */
1701         ac->domain_sid = samdb_result_sid_prefix(ac, ac->search_res->message, "objectSid");
1702         if (ac->domain_sid == NULL) {
1703                 ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
1704                 return LDB_ERR_OPERATIONS_ERROR;
1705         }
1706
1707         /* get user domain data */
1708         ret = build_domain_data_request(ac);
1709         if (ret != LDB_SUCCESS) {
1710                 return ret;
1711         }
1712
1713         ac->step = PH_MOD_SEARCH_DOM;
1714
1715         return ldb_next_request(ac->module, ac->dom_req);
1716 }
1717
1718 static int password_hash_mod_do_mod(struct ldb_handle *h) {
1719
1720         struct ph_context *ac;
1721         struct domain_data *domain;
1722         struct smb_krb5_context *smb_krb5_context;
1723         struct ldb_message *msg;
1724         struct ldb_message *orig_msg;
1725         struct ldb_message *searched_msg;
1726         struct setup_password_fields_io io;
1727         int ret;
1728
1729         ac = talloc_get_type(h->private_data, struct ph_context);
1730
1731         domain = get_domain_data(ac->module, ac, ac->dom_res);
1732         if (domain == NULL) {
1733                 return LDB_ERR_OPERATIONS_ERROR;
1734         }
1735
1736         ac->mod_req = talloc(ac, struct ldb_request);
1737         if (ac->mod_req == NULL) {
1738                 return LDB_ERR_OPERATIONS_ERROR;
1739         }
1740
1741         *(ac->mod_req) = *(ac->orig_req);
1742         
1743         /* use a new message structure so that we can modify it */
1744         ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
1745         if (msg == NULL) {
1746                 return LDB_ERR_OPERATIONS_ERROR;
1747         }
1748
1749         /* modify dn */
1750         msg->dn = ac->orig_req->op.mod.message->dn;
1751
1752         /* Some operations below require kerberos contexts */
1753         if (smb_krb5_init_context(ac->mod_req, 
1754                                   ldb_get_opaque(h->module->ldb, "EventContext"), 
1755                                   &smb_krb5_context) != 0) {
1756                 return LDB_ERR_OPERATIONS_ERROR;
1757         }
1758
1759         orig_msg        = discard_const(ac->orig_req->op.mod.message);
1760         searched_msg    = ac->search_res->message;
1761
1762         ZERO_STRUCT(io);
1763         io.ac                           = ac;
1764         io.domain                       = domain;
1765         io.smb_krb5_context             = smb_krb5_context;
1766
1767         io.u.user_account_control       = samdb_result_uint(searched_msg, "userAccountControl", 0);
1768         io.u.sAMAccountName             = samdb_result_string(searched_msg, "samAccountName", NULL);
1769         io.u.user_principal_name        = samdb_result_string(searched_msg, "userPrincipalName", NULL);
1770         io.u.is_computer                = ldb_msg_check_string_attribute(searched_msg, "objectClass", "computer");
1771
1772         io.n.cleartext                  = samdb_result_string(orig_msg, "sambaPassword", NULL);
1773         io.n.nt_hash                    = samdb_result_hash(io.ac, orig_msg, "unicodePwd");
1774         io.n.lm_hash                    = samdb_result_hash(io.ac, orig_msg, "dBCSPwd");
1775
1776         io.o.kvno                       = samdb_result_uint(searched_msg, "msDs-KeyVersionNumber", 0);
1777         io.o.nt_history_len             = samdb_result_hashes(io.ac, searched_msg, "ntPwdHistory", &io.o.nt_history);
1778         io.o.lm_history_len             = samdb_result_hashes(io.ac, searched_msg, "lmPwdHistory", &io.o.lm_history);
1779         io.o.supplemental               = ldb_msg_find_ldb_val(searched_msg, "supplementalCredentials");
1780
1781         ret = setup_password_fields(&io);
1782         if (ret != LDB_SUCCESS) {
1783                 return ret;
1784         }
1785
1786         /* make sure we replace all the old attributes */
1787         ret = ldb_msg_add_empty(msg, "unicodePwd", LDB_FLAG_MOD_REPLACE, NULL);
1788         ret = ldb_msg_add_empty(msg, "dBCSPwd", LDB_FLAG_MOD_REPLACE, NULL);
1789         ret = ldb_msg_add_empty(msg, "ntPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1790         ret = ldb_msg_add_empty(msg, "lmPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
1791         ret = ldb_msg_add_empty(msg, "supplementalCredentials", LDB_FLAG_MOD_REPLACE, NULL);
1792         ret = ldb_msg_add_empty(msg, "pwdLastSet", LDB_FLAG_MOD_REPLACE, NULL);
1793         ret = ldb_msg_add_empty(msg, "msDs-KeyVersionNumber", LDB_FLAG_MOD_REPLACE, NULL);
1794
1795         if (io.g.nt_hash) {
1796                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1797                                          "unicodePwd", io.g.nt_hash);
1798                 if (ret != LDB_SUCCESS) {
1799                         return ret;
1800                 }
1801         }
1802         if (io.g.lm_hash) {
1803                 ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
1804                                          "dBCSPwd", io.g.lm_hash);
1805                 if (ret != LDB_SUCCESS) {
1806                         return ret;
1807                 }
1808         }
1809         if (io.g.nt_history_len > 0) {
1810                 ret = samdb_msg_add_hashes(ac, msg,
1811                                            "ntPwdHistory",
1812                                            io.g.nt_history,
1813                                            io.g.nt_history_len);
1814                 if (ret != LDB_SUCCESS) {
1815                         return ret;
1816                 }
1817         }
1818         if (io.g.lm_history_len > 0) {
1819                 ret = samdb_msg_add_hashes(ac, msg,
1820                                            "lmPwdHistory",
1821                                            io.g.lm_history,
1822                                            io.g.lm_history_len);
1823                 if (ret != LDB_SUCCESS) {
1824                         return ret;
1825                 }
1826         }
1827         if (io.g.supplemental.length > 0) {
1828                 ret = ldb_msg_add_value(msg, "supplementalCredentials",
1829                                         &io.g.supplemental, NULL);
1830                 if (ret != LDB_SUCCESS) {
1831                         return ret;
1832                 }
1833         }
1834         ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
1835                                    "pwdLastSet",
1836                                    io.g.last_set);
1837         if (ret != LDB_SUCCESS) {
1838                 return ret;
1839         }
1840         ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
1841                                  "msDs-KeyVersionNumber",
1842                                  io.g.kvno);
1843         if (ret != LDB_SUCCESS) {
1844                 return ret;
1845         }
1846
1847         h->state = LDB_ASYNC_INIT;
1848         h->status = LDB_SUCCESS;
1849
1850         ac->step = PH_MOD_DO_MOD;
1851
1852         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
1853
1854         /* perform the search */
1855         return ldb_next_request(ac->module, ac->mod_req);
1856 }
1857
1858 static int ph_wait(struct ldb_handle *handle) {
1859         struct ph_context *ac;
1860         int ret;
1861     
1862         if (!handle || !handle->private_data) {
1863                 return LDB_ERR_OPERATIONS_ERROR;
1864         }
1865
1866         if (handle->state == LDB_ASYNC_DONE) {
1867                 return handle->status;
1868         }
1869
1870         handle->state = LDB_ASYNC_PENDING;
1871         handle->status = LDB_SUCCESS;
1872
1873         ac = talloc_get_type(handle->private_data, struct ph_context);
1874
1875         switch (ac->step) {
1876         case PH_ADD_SEARCH_DOM:
1877                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1878
1879                 if (ret != LDB_SUCCESS) {
1880                         handle->status = ret;
1881                         goto done;
1882                 }
1883                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1884                         handle->status = ac->dom_req->handle->status;
1885                         goto done;
1886                 }
1887
1888                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1889                         return LDB_SUCCESS;
1890                 }
1891
1892                 /* domain search done, go on */
1893                 return password_hash_add_do_add(handle);
1894
1895         case PH_ADD_DO_ADD:
1896                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1897
1898                 if (ret != LDB_SUCCESS) {
1899                         handle->status = ret;
1900                         goto done;
1901                 }
1902                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1903                         handle->status = ac->down_req->handle->status;
1904                         goto done;
1905                 }
1906
1907                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1908                         return LDB_SUCCESS;
1909                 }
1910
1911                 break;
1912                 
1913         case PH_MOD_DO_REQ:
1914                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
1915
1916                 if (ret != LDB_SUCCESS) {
1917                         handle->status = ret;
1918                         goto done;
1919                 }
1920                 if (ac->down_req->handle->status != LDB_SUCCESS) {
1921                         handle->status = ac->down_req->handle->status;
1922                         goto done;
1923                 }
1924
1925                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
1926                         return LDB_SUCCESS;
1927                 }
1928
1929                 /* non-password mods done, go on */
1930                 return password_hash_mod_search_self(handle);
1931                 
1932         case PH_MOD_SEARCH_SELF:
1933                 ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
1934
1935                 if (ret != LDB_SUCCESS) {
1936                         handle->status = ret;
1937                         goto done;
1938                 }
1939                 if (ac->search_req->handle->status != LDB_SUCCESS) {
1940                         handle->status = ac->search_req->handle->status;
1941                         goto done;
1942                 }
1943
1944                 if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
1945                         return LDB_SUCCESS;
1946                 }
1947
1948                 if (ac->search_res == NULL) {
1949                         return LDB_ERR_NO_SUCH_OBJECT;
1950                 }
1951
1952                 /* self search done, go on */
1953                 return password_hash_mod_search_dom(handle);
1954                 
1955         case PH_MOD_SEARCH_DOM:
1956                 ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
1957
1958                 if (ret != LDB_SUCCESS) {
1959                         handle->status = ret;
1960                         goto done;
1961                 }
1962                 if (ac->dom_req->handle->status != LDB_SUCCESS) {
1963                         handle->status = ac->dom_req->handle->status;
1964                         goto done;
1965                 }
1966
1967                 if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
1968                         return LDB_SUCCESS;
1969                 }
1970
1971                 /* domain search done, go on */
1972                 return password_hash_mod_do_mod(handle);
1973
1974         case PH_MOD_DO_MOD:
1975                 ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
1976
1977                 if (ret != LDB_SUCCESS) {
1978                         handle->status = ret;
1979                         goto done;
1980                 }
1981                 if (ac->mod_req->handle->status != LDB_SUCCESS) {
1982                         handle->status = ac->mod_req->handle->status;
1983                         goto done;
1984                 }
1985
1986                 if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
1987                         return LDB_SUCCESS;
1988                 }
1989
1990                 break;
1991                 
1992         default:
1993                 ret = LDB_ERR_OPERATIONS_ERROR;
1994                 goto done;
1995         }
1996
1997         ret = LDB_SUCCESS;
1998
1999 done:
2000         handle->state = LDB_ASYNC_DONE;
2001         return ret;
2002 }
2003
2004 static int ph_wait_all(struct ldb_handle *handle) {
2005
2006         int ret;
2007
2008         while (handle->state != LDB_ASYNC_DONE) {
2009                 ret = ph_wait(handle);
2010                 if (ret != LDB_SUCCESS) {
2011                         return ret;
2012                 }
2013         }
2014
2015         return handle->status;
2016 }
2017
2018 static int password_hash_wait(struct ldb_handle *handle, enum ldb_wait_type type)
2019 {
2020         if (type == LDB_WAIT_ALL) {
2021                 return ph_wait_all(handle);
2022         } else {
2023                 return ph_wait(handle);
2024         }
2025 }
2026
2027 static const struct ldb_module_ops password_hash_ops = {
2028         .name          = "password_hash",
2029         .add           = password_hash_add,
2030         .modify        = password_hash_modify,
2031         .wait          = password_hash_wait
2032 };
2033
2034
2035 int password_hash_module_init(void)
2036 {
2037         return ldb_register_module(&password_hash_ops);
2038 }