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