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