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