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