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