s3-dssync-passdb: implement accounts, aliases and groups
[metze/samba/wip.git] / source3 / libnet / libnet_dssync_passdb.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Guenther Deschner <gd@samba.org> 2008
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "libnet/libnet_dssync.h"
22 #include "libnet/libnet_samsync.h"
23 #include "../libcli/security/security.h"
24 #include "../libds/common/flags.h"
25 #include "../librpc/gen_ndr/ndr_drsuapi.h"
26 #include "dbwrap.h"
27
28 /****************************************************************
29 ****************************************************************/
30
31 struct dssync_passdb {
32         struct pdb_methods *methods;
33         struct db_context *all;
34         struct db_context *aliases;
35         struct db_context *groups;
36 };
37
38 struct dssync_passdb_obj {
39         struct dssync_passdb_obj *self;
40         uint32_t type;
41         struct drsuapi_DsReplicaObjectListItemEx *cur;
42         TDB_DATA key;
43         TDB_DATA data;
44         struct db_context *members;
45 };
46
47 struct dssync_passdb_mem {
48         struct dssync_passdb_mem *self;
49         bool active;
50         struct drsuapi_DsReplicaObjectIdentifier3 *cur;
51         struct dssync_passdb_obj *obj;
52         TDB_DATA key;
53         TDB_DATA data;
54 };
55
56 static NTSTATUS dssync_insert_obj(struct dssync_passdb *pctx,
57                                   struct db_context *db,
58                                   struct dssync_passdb_obj *obj)
59 {
60         NTSTATUS status;
61         struct db_record *rec;
62
63         rec = db->fetch_locked(db, talloc_tos(), obj->key);
64         if (rec == NULL) {
65                 return NT_STATUS_NO_MEMORY;
66         }
67         if (rec->value.dsize != 0) {
68                 abort();
69         }
70
71         status = rec->store(rec, obj->data, TDB_INSERT);
72         if (!NT_STATUS_IS_OK(status)) {
73                 TALLOC_FREE(rec);
74                 return status;
75         }
76         TALLOC_FREE(rec);
77         return NT_STATUS_OK;
78 }
79
80 static struct dssync_passdb_obj *dssync_parse_obj(const TDB_DATA data)
81 {
82         struct dssync_passdb_obj *obj;
83
84         if (data.dsize != sizeof(obj)) {
85                 return NULL;
86         }
87
88         /*
89          * we need to copy the pointer to avoid alignment problems
90          * on some systems.
91          */
92         memcpy(&obj, data.dptr, sizeof(obj));
93
94         return talloc_get_type_abort(obj, struct dssync_passdb_obj);
95 }
96
97 static struct dssync_passdb_obj *dssync_search_obj_by_guid(struct dssync_passdb *pctx,
98                                                            struct db_context *db,
99                                                            const struct GUID *guid)
100 {
101         struct dssync_passdb_obj *obj;
102         int ret;
103         TDB_DATA key;
104         TDB_DATA data;
105
106         key = make_tdb_data((const uint8_t *)(void *)guid,
107                              sizeof(*guid));
108
109         ret = db->fetch(db, talloc_tos(), key, &data);
110         if (ret != 0) {
111                 return NULL;
112         }
113
114         obj = dssync_parse_obj(data);
115         return obj;
116 }
117
118 static NTSTATUS dssync_create_obj(struct dssync_passdb *pctx,
119                                   struct db_context *db,
120                                   uint32_t type,
121                                   struct drsuapi_DsReplicaObjectListItemEx *cur,
122                                   struct dssync_passdb_obj **_obj)
123 {
124         NTSTATUS status;
125         struct dssync_passdb_obj *obj;
126
127         obj = talloc_zero(pctx, struct dssync_passdb_obj);
128         if (obj == NULL) {
129                 return NT_STATUS_NO_MEMORY;
130         }
131         obj->self = obj;
132         obj->cur = cur;
133         obj->type = type;
134         obj->key = make_tdb_data((const uint8_t *)(void *)&cur->object.identifier->guid,
135                                    sizeof(cur->object.identifier->guid));
136         obj->data = make_tdb_data((const uint8_t *)(void *)&obj->self,
137                                   sizeof(obj->self));
138
139         obj->members = db_open_rbt(obj);
140         if (obj->members == NULL) {
141                 return NT_STATUS_NO_MEMORY;
142         }
143
144         status = dssync_insert_obj(pctx, db, obj);
145         if (!NT_STATUS_IS_OK(status)) {
146                 TALLOC_FREE(obj);
147                 return status;
148         }
149         *_obj = obj;
150         return NT_STATUS_OK;
151 }
152
153 static NTSTATUS dssync_insert_mem(struct dssync_passdb *pctx,
154                                   struct dssync_passdb_obj *obj,
155                                   struct dssync_passdb_mem *mem)
156 {
157         NTSTATUS status;
158         struct db_record *rec;
159
160         rec = obj->members->fetch_locked(obj->members, talloc_tos(), mem->key);
161         if (rec == NULL) {
162                 return NT_STATUS_NO_MEMORY;
163         }
164         if (rec->value.dsize != 0) {
165                 abort();
166         }
167
168         status = rec->store(rec, mem->data, TDB_INSERT);
169         if (!NT_STATUS_IS_OK(status)) {
170                 TALLOC_FREE(rec);
171                 return status;
172         }
173         TALLOC_FREE(rec);
174         return NT_STATUS_OK;
175 }
176
177 static NTSTATUS dssync_create_mem(struct dssync_passdb *pctx,
178                                   struct dssync_passdb_obj *obj,
179                                   bool active,
180                                   struct drsuapi_DsReplicaObjectIdentifier3 *cur,
181                                   struct dssync_passdb_mem **_mem)
182 {
183         NTSTATUS status;
184         struct dssync_passdb_mem *mem;
185
186         mem = talloc_zero(pctx, struct dssync_passdb_mem);
187         if (mem == NULL) {
188                 return NT_STATUS_NO_MEMORY;
189         }
190         mem->self = mem;
191         mem->cur = cur;
192         mem->active = active;
193         mem->obj = NULL;
194         mem->key = make_tdb_data((const uint8_t *)(void *)&cur->guid,
195                                    sizeof(cur->guid));
196         mem->data = make_tdb_data((const uint8_t *)(void *)&mem->self,
197                                   sizeof(mem->self));
198
199         status = dssync_insert_mem(pctx, obj, mem);
200         if (!NT_STATUS_IS_OK(status)) {
201                 TALLOC_FREE(obj);
202                 return status;
203         }
204         *_mem = mem;
205         return NT_STATUS_OK;
206 }
207
208 static struct dssync_passdb_mem *dssync_parse_mem(const TDB_DATA data)
209 {
210         struct dssync_passdb_mem *mem;
211
212         if (data.dsize != sizeof(mem)) {
213                 return NULL;
214         }
215
216         /*
217          * we need to copy the pointer to avoid alignment problems
218          * on some systems.
219          */
220         memcpy(&mem, data.dptr, sizeof(mem));
221
222         return talloc_get_type_abort(mem, struct dssync_passdb_mem);
223 }
224
225 static NTSTATUS passdb_startup(struct dssync_context *ctx, TALLOC_CTX *mem_ctx,
226                                struct replUpToDateVectorBlob **pold_utdv)
227 {
228         NTSTATUS status;
229         struct dssync_passdb *pctx;
230
231         pctx = talloc_zero(mem_ctx, struct dssync_passdb);
232         if (pctx == NULL) {
233                 return NT_STATUS_NO_MEMORY;
234         }
235
236         if (ctx->output_filename) {
237                 status = make_pdb_method_name(&pctx->methods, ctx->output_filename);
238         } else {
239                 status = make_pdb_method_name(&pctx->methods, lp_passdb_backend());
240         }
241
242         if (!NT_STATUS_IS_OK(status)) {
243                 return status;
244         }
245
246         pctx->all = db_open_rbt(pctx);
247         if (pctx->all == NULL) {
248                 return NT_STATUS_NO_MEMORY;
249         }
250         pctx->aliases = db_open_rbt(pctx);
251         if (pctx->aliases == NULL) {
252                 return NT_STATUS_NO_MEMORY;
253         }
254         pctx->groups = db_open_rbt(pctx);
255         if (pctx->groups == NULL) {
256                 return NT_STATUS_NO_MEMORY;
257         }
258
259         ctx->private_data = pctx;
260
261         return status;
262 }
263
264 /****************************************************************
265 ****************************************************************/
266
267 struct dssync_passdb_traverse_amembers {
268         struct dssync_context *ctx;
269         struct dssync_passdb_obj *obj;
270         const char *name;
271         uint32_t idx;
272 };
273
274 struct dssync_passdb_traverse_aliases {
275         struct dssync_context *ctx;
276         const char *name;
277         uint32_t idx;
278 };
279
280 static int dssync_passdb_traverse_amembers(struct db_record *rec,
281                                            void *private_data)
282 {
283         struct dssync_passdb_traverse_amembers *state =
284                 (struct dssync_passdb_traverse_amembers *)private_data;
285         struct dssync_passdb *pctx =
286                 talloc_get_type_abort(state->ctx->private_data,
287                 struct dssync_passdb);
288         struct dssync_passdb_mem *mem;
289         NTSTATUS status;
290         struct dom_sid alias_sid;
291         struct dom_sid member_sid;
292         const char *member_dn;
293         size_t num_members;
294         size_t i;
295         struct dom_sid *members;
296         bool is_member = false;
297         const char *action;
298
299         state->idx++;
300
301         alias_sid = state->obj->cur->object.identifier->sid;
302
303         mem = dssync_parse_mem(rec->value);
304         if (mem == NULL) {
305                 return -1;
306         }
307
308         member_sid = mem->cur->sid;
309         member_dn = mem->cur->dn;
310
311         mem->obj = dssync_search_obj_by_guid(pctx, pctx->all, &mem->cur->guid);
312         if (mem->obj == NULL) {
313                 DEBUG(0,("alias[%s] member[%s] can't resolve member - ignoring\n",
314                          sid_string_dbg(&alias_sid),
315                          is_null_sid(&member_sid)?
316                          sid_string_dbg(&member_sid):
317                          member_dn));
318                 return 0;
319         }
320
321         switch (mem->obj->type) {
322         case ATYPE_DISTRIBUTION_LOCAL_GROUP:
323         case ATYPE_DISTRIBUTION_GLOBAL_GROUP:
324                 DEBUG(0, ("alias[%s] ignore distribution group [%s]\n",
325                           sid_string_dbg(&alias_sid),
326                           member_dn));
327                 return 0;
328         default:
329                 break;
330         }
331
332         DEBUG(0,("alias[%s] member[%s]\n",
333                  sid_string_dbg(&alias_sid),
334                  sid_string_dbg(&member_sid)));
335
336         status = pdb_enum_aliasmem(&alias_sid, talloc_tos(),
337                                    &members, &num_members);
338         if (!NT_STATUS_IS_OK(status)) {
339                 DEBUG(0, ("Could not find current alias members %s - %s\n",
340                           sid_string_dbg(&alias_sid),
341                           nt_errstr(status)));
342                 return -1;
343         }
344
345         for (i=0; i < num_members; i++) {
346                 bool match;
347
348                 match = dom_sid_equal(&members[i], &member_sid);
349                 if (match) {
350                         is_member = true;
351                         break;
352                 }
353         }
354
355         status = NT_STATUS_OK;
356         action = "none";
357         if (!is_member && mem->active) {
358                 action = "add";
359                 pdb_add_aliasmem(&alias_sid, &member_sid);
360         } else if (is_member && !mem->active) {
361                 action = "delete";
362                 pdb_del_aliasmem(&alias_sid, &member_sid);
363         }
364         if (!NT_STATUS_IS_OK(status)) {
365                 DEBUG(0, ("Could not %s %s as alias members of %s - %s\n",
366                           action,
367                           sid_string_dbg(&member_sid),
368                           sid_string_dbg(&alias_sid),
369                           nt_errstr(status)));
370                 return -1;
371         }
372
373         return 0;
374 }
375
376 static int dssync_passdb_traverse_aliases(struct db_record *rec,
377                                           void *private_data)
378 {
379         struct dssync_passdb_traverse_aliases *state =
380                 (struct dssync_passdb_traverse_aliases *)private_data;
381         struct dssync_passdb *pctx =
382                 talloc_get_type_abort(state->ctx->private_data,
383                 struct dssync_passdb);
384         struct dssync_passdb_traverse_amembers mstate;
385         struct dssync_passdb_obj *obj;
386         int ret;
387
388         state->idx++;
389         if (pctx->methods == NULL) {
390                 return -1;
391         }
392
393         obj = dssync_parse_obj(rec->value);
394         if (obj == NULL) {
395                 return -1;
396         }
397
398         ZERO_STRUCT(mstate);
399         mstate.ctx = state->ctx;
400         mstate.name = "members";
401         mstate.obj = obj;
402         ret = obj->members->traverse_read(obj->members,
403                                           dssync_passdb_traverse_amembers,
404                                           &mstate);
405         if (ret < 0) {
406                 return -1;
407         }
408
409         return 0;
410 }
411
412 struct dssync_passdb_traverse_gmembers {
413         struct dssync_context *ctx;
414         struct dssync_passdb_obj *obj;
415         const char *name;
416         uint32_t idx;
417 };
418
419 struct dssync_passdb_traverse_groups {
420         struct dssync_context *ctx;
421         const char *name;
422         uint32_t idx;
423 };
424
425 static int dssync_passdb_traverse_gmembers(struct db_record *rec,
426                                            void *private_data)
427 {
428         struct dssync_passdb_traverse_gmembers *state =
429                 (struct dssync_passdb_traverse_gmembers *)private_data;
430         struct dssync_passdb *pctx =
431                 talloc_get_type_abort(state->ctx->private_data,
432                 struct dssync_passdb);
433         struct dssync_passdb_mem *mem;
434         NTSTATUS status;
435         char *nt_member = NULL;
436         char **unix_members;
437         struct dom_sid group_sid;
438         struct dom_sid member_sid;
439         struct samu *member = NULL;
440         const char *member_dn = NULL;
441         GROUP_MAP map;
442         struct group *grp;
443         uint32_t rid;
444         bool is_unix_member = false;
445
446         state->idx++;
447
448         DEBUG(0,("%s[%u]...\n", state->name, state->idx));
449
450         group_sid = state->obj->cur->object.identifier->sid;
451
452         status = dom_sid_split_rid(talloc_tos(), &group_sid, NULL, &rid);
453         if (!NT_STATUS_IS_OK(status)) {
454                 return -1;
455         }
456
457         mem = dssync_parse_mem(rec->value);
458         if (mem == NULL) {
459                 return -1;
460         }
461
462         member_sid = mem->cur->sid;
463         member_dn = mem->cur->dn;
464
465         mem->obj = dssync_search_obj_by_guid(pctx, pctx->all, &mem->cur->guid);
466         if (mem->obj == NULL) {
467                 DEBUG(0,("group[%s] member[%s] can't resolve member - ignoring\n",
468                          sid_string_dbg(&group_sid),
469                          is_null_sid(&member_sid)?
470                          sid_string_dbg(&member_sid):
471                          member_dn));
472                 return 0;
473         }
474
475         member_sid = mem->obj->cur->object.identifier->sid;
476         member_dn = mem->obj->cur->object.identifier->dn;
477
478         switch (mem->obj->type) {
479         case ATYPE_SECURITY_LOCAL_GROUP:
480         case ATYPE_SECURITY_GLOBAL_GROUP:
481                 DEBUG(0, ("Group[%s] ignore member group [%s]\n",
482                           sid_string_dbg(&group_sid),
483                           sid_string_dbg(&member_sid)));
484                 return 0;
485
486         case ATYPE_DISTRIBUTION_LOCAL_GROUP:
487         case ATYPE_DISTRIBUTION_GLOBAL_GROUP:
488                 DEBUG(0, ("Group[%s] ignore distribution group [%s]\n",
489                           sid_string_dbg(&group_sid),
490                           member_dn));
491                 return 0;
492         default:
493                 break;
494         }
495
496         if (!get_domain_group_from_sid(group_sid, &map)) {
497                 DEBUG(0, ("Could not find global group %s\n",
498                           sid_string_dbg(&group_sid)));
499                 //return NT_STATUS_NO_SUCH_GROUP;
500                 return -1;
501         }
502
503         if (!(grp = getgrgid(map.gid))) {
504                 DEBUG(0, ("Could not find unix group %lu\n", (unsigned long)map.gid));
505                 //return NT_STATUS_NO_SUCH_GROUP;
506                 return -1;
507         }
508
509         DEBUG(0,("Group members of %s: ", grp->gr_name));
510
511         if ( !(member = samu_new(talloc_tos())) ) {
512                 //return NT_STATUS_NO_MEMORY;
513                 return -1;
514         }
515
516         if (!pdb_getsampwsid(member, &member_sid)) {
517                 DEBUG(1, ("Found bogus group member: (member_sid=%s group=%s)\n",
518                           sid_string_tos(&member_sid), grp->gr_name));
519                 TALLOC_FREE(member);
520                 return -1;
521         }
522
523         if (pdb_get_group_rid(member) == rid) {
524                 DEBUGADD(0,("%s(primary),", pdb_get_username(member)));
525                 TALLOC_FREE(member);
526                 return -1;
527         }
528
529         DEBUGADD(0,("%s,", pdb_get_username(member)));
530         nt_member = talloc_strdup(talloc_tos(), pdb_get_username(member));
531         TALLOC_FREE(member);
532
533         DEBUGADD(0,("\n"));
534
535         unix_members = grp->gr_mem;
536
537         while (*unix_members) {
538                 if (strcmp(*unix_members, nt_member) == 0) {
539                         is_unix_member = true;
540                         break;
541                 }
542                 unix_members += 1;
543         }
544
545         if (!is_unix_member && mem->active) {
546                 smb_add_user_group(grp->gr_name, nt_member);
547         } else if (is_unix_member && !mem->active) {
548                 smb_delete_user_group(grp->gr_name, nt_member);
549         }
550
551         return 0;
552 }
553
554 static int dssync_passdb_traverse_groups(struct db_record *rec,
555                                          void *private_data)
556 {
557         struct dssync_passdb_traverse_groups *state =
558                 (struct dssync_passdb_traverse_groups *)private_data;
559         struct dssync_passdb *pctx =
560                 talloc_get_type_abort(state->ctx->private_data,
561                 struct dssync_passdb);
562         struct dssync_passdb_traverse_gmembers mstate;
563         struct dssync_passdb_obj *obj;
564         int ret;
565
566         state->idx++;
567         if (pctx->methods == NULL) {
568                 return -1;
569         }
570
571         DEBUG(0,("%s[%u]...\n", state->name, state->idx));
572
573         obj = dssync_parse_obj(rec->value);
574         if (obj == NULL) {
575                 return -1;
576         }
577
578         ZERO_STRUCT(mstate);
579         mstate.ctx = state->ctx;
580         mstate.name = "members";
581         mstate.obj = obj;
582         ret = obj->members->traverse_read(obj->members,
583                                           dssync_passdb_traverse_gmembers,
584                                           &mstate);
585         if (ret < 0) {
586                 return -1;
587         }
588
589         return 0;
590 }
591
592 static NTSTATUS passdb_finish(struct dssync_context *ctx, TALLOC_CTX *mem_ctx,
593                               struct replUpToDateVectorBlob *new_utdv)
594 {
595         struct dssync_passdb *pctx =
596                 talloc_get_type_abort(ctx->private_data,
597                 struct dssync_passdb);
598         struct dssync_passdb_traverse_aliases astate;
599         struct dssync_passdb_traverse_groups gstate;
600         int ret;
601
602         ZERO_STRUCT(astate);
603         astate.ctx = ctx;
604         astate.name = "aliases";
605         ret = pctx->aliases->traverse_read(pctx->aliases,
606                                            dssync_passdb_traverse_aliases,
607                                            &astate);
608         if (ret < 0) {
609                 return NT_STATUS_INTERNAL_ERROR;
610         }
611
612         ZERO_STRUCT(gstate);
613         gstate.ctx = ctx;
614         gstate.name = "groups";
615         ret = pctx->groups->traverse_read(pctx->groups,
616                                           dssync_passdb_traverse_groups,
617                                           &gstate);
618         if (ret < 0) {
619                 return NT_STATUS_INTERNAL_ERROR;
620         }
621
622         TALLOC_FREE(pctx->methods);
623         TALLOC_FREE(pctx);
624
625         return NT_STATUS_OK;
626 }
627
628 /****************************************************************
629 ****************************************************************/
630
631 static NTSTATUS smb_create_user(TALLOC_CTX *mem_ctx,
632                                 uint32_t acct_flags,
633                                 const char *account,
634                                 struct passwd **passwd_p)
635 {
636         struct passwd *passwd;
637         char *add_script = NULL;
638
639         passwd = Get_Pwnam_alloc(mem_ctx, account);
640         if (passwd) {
641                 *passwd_p = passwd;
642                 return NT_STATUS_OK;
643         }
644
645         /* Create appropriate user */
646         if (acct_flags & ACB_NORMAL) {
647                 add_script = talloc_strdup(mem_ctx, lp_adduser_script());
648         } else if ( (acct_flags & ACB_WSTRUST) ||
649                     (acct_flags & ACB_SVRTRUST) ||
650                     (acct_flags & ACB_DOMTRUST) ) {
651                 add_script = talloc_strdup(mem_ctx, lp_addmachine_script());
652         } else {
653                 DEBUG(1, ("Unknown user type: %s\n",
654                           pdb_encode_acct_ctrl(acct_flags, NEW_PW_FORMAT_SPACE_PADDED_LEN)));
655                 return NT_STATUS_UNSUCCESSFUL;
656         }
657
658         if (!add_script) {
659                 return NT_STATUS_NO_MEMORY;
660         }
661
662         if (*add_script) {
663                 int add_ret;
664                 add_script = talloc_all_string_sub(mem_ctx, add_script,
665                                                    "%u", account);
666                 if (!add_script) {
667                         return NT_STATUS_NO_MEMORY;
668                 }
669                 add_ret = smbrun(add_script, NULL);
670                 DEBUG(add_ret ? 0 : 1,("fetch_account: Running the command `%s' "
671                          "gave %d\n", add_script, add_ret));
672                 if (add_ret == 0) {
673                         smb_nscd_flush_user_cache();
674                 }
675         }
676
677         /* try and find the possible unix account again */
678         passwd = Get_Pwnam_alloc(mem_ctx, account);
679         if (!passwd) {
680                 return NT_STATUS_NO_SUCH_USER;
681         }
682
683         *passwd_p = passwd;
684
685         return NT_STATUS_OK;
686 }
687
688 static struct drsuapi_DsReplicaAttribute *find_drsuapi_attr(
689                         const struct drsuapi_DsReplicaObjectListItemEx *cur,
690                         uint32_t attid)
691 {
692         int i = 0;
693
694         for (i = 0; i < cur->object.attribute_ctr.num_attributes; i++) {
695                 struct drsuapi_DsReplicaAttribute *attr;
696
697                 attr = &cur->object.attribute_ctr.attributes[i];
698
699                 if (attr->attid == attid) {
700                         return attr;
701                 }
702         }
703
704         return NULL;
705 }
706
707 static NTSTATUS find_drsuapi_attr_string(TALLOC_CTX *mem_ctx,
708                                          const struct drsuapi_DsReplicaObjectListItemEx *cur,
709                                          uint32_t attid,
710                                          uint32_t *_count,
711                                          char ***_array)
712 {
713         struct drsuapi_DsReplicaAttribute *attr;
714         char **array;
715         uint32_t a;
716
717         attr = find_drsuapi_attr(cur, attid);
718         if (attr == NULL) {
719                 return NT_STATUS_PROPSET_NOT_FOUND;
720         }
721
722         array = talloc_array(mem_ctx, char *, attr->value_ctr.num_values);
723         if (array == NULL) {
724                 return NT_STATUS_NO_MEMORY;
725         }
726
727         for (a = 0; a < attr->value_ctr.num_values; a++) {
728                 const DATA_BLOB *blob;
729                 ssize_t ret;
730
731                 blob = attr->value_ctr.values[a].blob;
732
733                 if (blob == NULL) {
734                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
735                 }
736
737                 ret = pull_string_talloc(array, NULL, 0, &array[a],
738                                          blob->data, blob->length,
739                                          STR_UNICODE);
740                 if (ret == -1) {
741                         //TODO
742                         return NT_STATUS_INTERNAL_ERROR;
743                 }
744         }
745
746         *_count = attr->value_ctr.num_values;
747         *_array = array;
748         return NT_STATUS_OK;
749 }
750
751 static NTSTATUS find_drsuapi_attr_int32(TALLOC_CTX *mem_ctx,
752                                         const struct drsuapi_DsReplicaObjectListItemEx *cur,
753                                         uint32_t attid,
754                                         uint32_t *_count,
755                                         int32_t **_array)
756 {
757         struct drsuapi_DsReplicaAttribute *attr;
758         int32_t *array;
759         uint32_t a;
760
761         attr = find_drsuapi_attr(cur, attid);
762         if (attr == NULL) {
763                 return NT_STATUS_PROPSET_NOT_FOUND;
764         }
765
766         array = talloc_array(mem_ctx, int32_t, attr->value_ctr.num_values);
767         if (array == NULL) {
768                 return NT_STATUS_NO_MEMORY;
769         }
770
771         for (a = 0; a < attr->value_ctr.num_values; a++) {
772                 const DATA_BLOB *blob;
773
774                 blob = attr->value_ctr.values[a].blob;
775
776                 if (blob == NULL) {
777                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
778                 }
779
780                 if (blob->length != 4) {
781                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
782                 }
783
784                 array[a] = IVAL(blob->data, 0);
785         }
786
787         *_count = attr->value_ctr.num_values;
788         *_array = array;
789         return NT_STATUS_OK;
790 }
791
792 static NTSTATUS find_drsuapi_attr_blob(TALLOC_CTX *mem_ctx,
793                                        const struct drsuapi_DsReplicaObjectListItemEx *cur,
794                                        uint32_t attid,
795                                        uint32_t *_count,
796                                        DATA_BLOB **_array)
797 {
798         struct drsuapi_DsReplicaAttribute *attr;
799         DATA_BLOB *array;
800         uint32_t a;
801
802         attr = find_drsuapi_attr(cur, attid);
803         if (attr == NULL) {
804                 return NT_STATUS_PROPSET_NOT_FOUND;
805         }
806
807         array = talloc_array(mem_ctx, DATA_BLOB, attr->value_ctr.num_values);
808         if (array == NULL) {
809                 return NT_STATUS_NO_MEMORY;
810         }
811
812         for (a = 0; a < attr->value_ctr.num_values; a++) {
813                 const DATA_BLOB *blob;
814
815                 blob = attr->value_ctr.values[a].blob;
816
817                 if (blob == NULL) {
818                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
819                 }
820
821                 array[a] = data_blob_talloc(array, blob->data, blob->length);
822                 if (array[a].length != blob->length) {
823                         return NT_STATUS_NO_MEMORY;
824                 }
825         }
826         *_count = attr->value_ctr.num_values;
827         *_array = array;
828         return NT_STATUS_OK;
829 }
830
831 static NTSTATUS find_drsuapi_attr_int64(TALLOC_CTX *mem_ctx,
832                                         const struct drsuapi_DsReplicaObjectListItemEx *cur,
833                                         uint32_t attid,
834                                         uint32_t *_count,
835                                         int64_t **_array)
836 {
837         struct drsuapi_DsReplicaAttribute *attr;
838         int64_t *array;
839         uint32_t a;
840
841         attr = find_drsuapi_attr(cur, attid);
842         if (attr == NULL) {
843                 return NT_STATUS_PROPSET_NOT_FOUND;
844         }
845
846         array = talloc_array(mem_ctx, int64_t, attr->value_ctr.num_values);
847         if (array == NULL) {
848                 return NT_STATUS_NO_MEMORY;
849         }
850
851         for (a = 0; a < attr->value_ctr.num_values; a++) {
852                 const DATA_BLOB *blob;
853
854                 blob = attr->value_ctr.values[a].blob;
855
856                 if (blob == NULL) {
857                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
858                 }
859
860                 if (blob->length != 8) {
861                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
862                 }
863
864                 array[a] = BVAL(blob->data, 0);
865         }
866         *_count = attr->value_ctr.num_values;
867         *_array = array;
868         return NT_STATUS_OK;
869 }
870
871 static NTSTATUS find_drsuapi_attr_dn(TALLOC_CTX *mem_ctx,
872                                      const struct drsuapi_DsReplicaObjectListItemEx *cur,
873                                      uint32_t attid,
874                                      uint32_t *_count,
875                                      struct drsuapi_DsReplicaObjectIdentifier3 **_array)
876 {
877         struct drsuapi_DsReplicaAttribute *attr;
878         struct drsuapi_DsReplicaObjectIdentifier3 *array;
879         uint32_t a;
880
881         attr = find_drsuapi_attr(cur, attid);
882         if (attr == NULL) {
883                 return NT_STATUS_PROPSET_NOT_FOUND;
884         }
885
886         array = talloc_array(mem_ctx,
887                              struct drsuapi_DsReplicaObjectIdentifier3,
888                              attr->value_ctr.num_values);
889         if (array == NULL) {
890                 return NT_STATUS_NO_MEMORY;
891         }
892
893         for (a = 0; a < attr->value_ctr.num_values; a++) {
894                 const DATA_BLOB *blob;
895                 enum ndr_err_code ndr_err;
896                 NTSTATUS status;
897
898                 blob = attr->value_ctr.values[a].blob;
899
900                 if (blob == NULL) {
901                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
902                 }
903
904                 /* windows sometimes sends an extra two pad bytes here */
905                 ndr_err = ndr_pull_struct_blob(blob, array, &array[a],
906                                 (ndr_pull_flags_fn_t)ndr_pull_drsuapi_DsReplicaObjectIdentifier3);
907                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
908                         status = ndr_map_error2ntstatus(ndr_err);
909                         return status;
910                 }
911         }
912         *_count = attr->value_ctr.num_values;
913         *_array = array;
914         return NT_STATUS_OK;
915 }
916
917 #define GET_BLOB_EX(attr, needed) do { \
918         NTSTATUS _status; \
919         uint32_t _cnt; \
920         DATA_BLOB *_vals = NULL; \
921         attr = data_blob_null; \
922         _status = find_drsuapi_attr_blob(mem_ctx, cur, \
923                                          DRSUAPI_ATTID_ ## attr, \
924                                          &_cnt, &_vals); \
925         if (NT_STATUS_EQUAL(_status, NT_STATUS_PROPSET_NOT_FOUND)) { \
926                 if (!needed) { \
927                         _status = NT_STATUS_OK; \
928                         _cnt = 0; \
929                 } \
930         } \
931         if (!NT_STATUS_IS_OK(_status)) { \
932                 DEBUG(0,(__location__ "attr[%s] %s\n", \
933                         #attr, nt_errstr(_status))); \
934                 return _status; \
935         } \
936         if (_cnt == 0) { \
937                 if (needed) { \
938                         talloc_free(_vals); \
939                         DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
940                         return NT_STATUS_OBJECT_NAME_NOT_FOUND; \
941                 } \
942         } else if (_cnt > 1) { \
943                 talloc_free(_vals); \
944                 DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
945                 return NT_STATUS_INTERNAL_DB_CORRUPTION; \
946         } else { \
947                 attr = _vals[0]; \
948                 (void)talloc_steal(mem_ctx, _vals[0].data); \
949         } \
950         talloc_free(_vals); \
951 } while(0)
952
953 #define GET_STRING_EX(attr, needed) do { \
954         NTSTATUS _status; \
955         uint32_t _cnt; \
956         char **_vals = NULL; \
957         attr = NULL; \
958         _status = find_drsuapi_attr_string(mem_ctx, cur, \
959                                            DRSUAPI_ATTID_ ## attr, \
960                                            &_cnt, &_vals); \
961         if (NT_STATUS_EQUAL(_status, NT_STATUS_PROPSET_NOT_FOUND)) { \
962                 if (!needed) { \
963                         _status = NT_STATUS_OK; \
964                         _cnt = 0; \
965                 } \
966         } \
967         if (!NT_STATUS_IS_OK(_status)) { \
968                 DEBUG(0,(__location__ "attr[%s] %s\n", \
969                         #attr, nt_errstr(_status))); \
970                 return _status; \
971         } \
972         if (_cnt == 0) { \
973                 if (needed) { \
974                         talloc_free(_vals); \
975                         DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
976                         return NT_STATUS_OBJECT_NAME_NOT_FOUND; \
977                 } \
978         } else if (_cnt > 1) { \
979                 talloc_free(_vals); \
980                 DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
981                 return NT_STATUS_INTERNAL_DB_CORRUPTION; \
982         } else { \
983                 attr = talloc_move(mem_ctx, &_vals[0]); \
984         } \
985         talloc_free(_vals); \
986 } while(0)
987
988 #define GET_UINT32_EX(attr, needed) do { \
989         NTSTATUS _status; \
990         uint32_t _cnt; \
991         int32_t*_vals = NULL; \
992         attr = 0; \
993         _status = find_drsuapi_attr_int32(mem_ctx, cur, \
994                                           DRSUAPI_ATTID_ ## attr, \
995                                           &_cnt, &_vals); \
996         if (NT_STATUS_EQUAL(_status, NT_STATUS_PROPSET_NOT_FOUND)) { \
997                 if (!needed) { \
998                         _status = NT_STATUS_OK; \
999                         _cnt = 0; \
1000                 } \
1001         } \
1002         if (!NT_STATUS_IS_OK(_status)) { \
1003                 DEBUG(0,(__location__ "attr[%s] %s\n", \
1004                         #attr, nt_errstr(_status))); \
1005                 return _status; \
1006         } \
1007         if (_cnt == 0) { \
1008                 if (needed) { \
1009                         talloc_free(_vals); \
1010                         DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
1011                         return NT_STATUS_OBJECT_NAME_NOT_FOUND; \
1012                 } \
1013         } else if (_cnt > 1) { \
1014                 talloc_free(_vals); \
1015                 DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
1016                 return NT_STATUS_INTERNAL_DB_CORRUPTION; \
1017         } else { \
1018                 attr = (uint32_t)_vals[0]; \
1019         } \
1020         talloc_free(_vals); \
1021 } while(0)
1022
1023 #define GET_UINT64_EX(attr, needed) do { \
1024         NTSTATUS _status; \
1025         uint32_t _cnt; \
1026         int64_t *_vals = NULL; \
1027         attr = 0; \
1028         _status = find_drsuapi_attr_int64(mem_ctx, cur, \
1029                                           DRSUAPI_ATTID_ ## attr, \
1030                                           &_cnt, &_vals); \
1031         if (NT_STATUS_EQUAL(_status, NT_STATUS_PROPSET_NOT_FOUND)) { \
1032                 if (!needed) { \
1033                         _status = NT_STATUS_OK; \
1034                         _cnt = 0; \
1035                 } \
1036         } \
1037         if (!NT_STATUS_IS_OK(_status)) { \
1038                 DEBUG(0,(__location__ "attr[%s] %s\n", \
1039                         #attr, nt_errstr(_status))); \
1040                 return _status; \
1041         } \
1042         if (_cnt == 0) { \
1043                 if (needed) { \
1044                         talloc_free(_vals); \
1045                         DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
1046                         return NT_STATUS_OBJECT_NAME_NOT_FOUND; \
1047                 } \
1048         } else if (_cnt > 1) { \
1049                 talloc_free(_vals); \
1050                 DEBUG(0,(__location__ "attr[%s] count[%u]\n", #attr, _cnt)); \
1051                 return NT_STATUS_INTERNAL_DB_CORRUPTION; \
1052         } else { \
1053                 attr = (uint64_t)_vals[0]; \
1054         } \
1055         talloc_free(_vals); \
1056 } while(0)
1057
1058 #define GET_BLOB(attr) GET_BLOB_EX(attr, false)
1059 #define GET_STRING(attr) GET_STRING_EX(attr, false)
1060 #define GET_UINT32(attr) GET_UINT32_EX(attr, false)
1061 #define GET_UINT64(attr) GET_UINT64_EX(attr, false)
1062
1063 /* Convert a struct samu_DELTA to a struct samu. */
1064 #define STRING_CHANGED (old_string && !new_string) ||\
1065                     (!old_string && new_string) ||\
1066                 (old_string && new_string && (strcmp(old_string, new_string) != 0))
1067
1068 #define STRING_CHANGED_NC(s1,s2) ((s1) && !(s2)) ||\
1069                     (!(s1) && (s2)) ||\
1070                 ((s1) && (s2) && (strcmp((s1), (s2)) != 0))
1071
1072 /****************************************************************
1073 ****************************************************************/
1074
1075 static NTSTATUS sam_account_from_object(struct samu *account,
1076                                 struct drsuapi_DsReplicaObjectListItemEx *cur)
1077 {
1078         TALLOC_CTX *mem_ctx = account;
1079         const char *old_string, *new_string;
1080         time_t unix_time, stored_time;
1081         uchar zero_buf[16];
1082         NTSTATUS status;
1083
1084         NTTIME lastLogon;
1085         NTTIME lastLogoff;
1086         NTTIME pwdLastSet;
1087         NTTIME accountExpires;
1088         const char *sAMAccountName;
1089         const char *displayName;
1090         const char *homeDirectory;
1091         const char *homeDrive;
1092         const char *scriptPath;
1093         const char *profilePath;
1094         const char *description;
1095         const char *userWorkstations;
1096         const char *comment;
1097         DATA_BLOB userParameters;
1098         struct dom_sid objectSid;
1099         uint32_t primaryGroupID;
1100         uint32_t userAccountControl;
1101         DATA_BLOB logonHours;
1102         uint32_t badPwdCount;
1103         uint32_t logonCount;
1104         DATA_BLOB unicodePwd;
1105         DATA_BLOB dBCSPwd;
1106
1107         uint32_t rid = 0;
1108         uint32_t acct_flags;
1109         uint32_t units_per_week;
1110
1111         memset(zero_buf, '\0', sizeof(zero_buf));
1112
1113         objectSid = cur->object.identifier->sid;
1114         GET_STRING_EX(sAMAccountName, true);
1115         DEBUG(0,("sam_account_from_object(%s, %s) start\n",
1116                  sAMAccountName, sid_string_dbg(&objectSid)));
1117         GET_UINT64(lastLogon);
1118         GET_UINT64(lastLogoff);
1119         GET_UINT64(pwdLastSet);
1120         GET_UINT64(accountExpires);
1121         GET_STRING(displayName);
1122         GET_STRING(homeDirectory);
1123         GET_STRING(homeDrive);
1124         GET_STRING(scriptPath);
1125         GET_STRING(profilePath);
1126         GET_STRING(description);
1127         GET_STRING(userWorkstations);
1128         GET_STRING(comment);
1129         GET_BLOB(userParameters);
1130         GET_UINT32(primaryGroupID);
1131         GET_UINT32(userAccountControl);
1132         GET_BLOB(logonHours);
1133         GET_UINT32(badPwdCount);
1134         GET_UINT32(logonCount);
1135         GET_BLOB(unicodePwd);
1136         GET_BLOB(dBCSPwd);
1137
1138         status = dom_sid_split_rid(mem_ctx, &objectSid, NULL, &rid);
1139         if (!NT_STATUS_IS_OK(status)) {
1140                 return status;
1141         }
1142         acct_flags = ds_uf2acb(userAccountControl);
1143
1144         /* Username, fullname, home dir, dir drive, logon script, acct
1145            desc, workstations, profile. */
1146
1147         if (sAMAccountName) {
1148                 old_string = pdb_get_nt_username(account);
1149                 new_string = sAMAccountName;
1150
1151                 if (STRING_CHANGED) {
1152                         pdb_set_nt_username(account, new_string, PDB_CHANGED);
1153                 }
1154
1155                 /* Unix username is the same - for sanity */
1156                 old_string = pdb_get_username( account );
1157                 if (STRING_CHANGED) {
1158                         pdb_set_username(account, new_string, PDB_CHANGED);
1159                 }
1160         }
1161
1162         if (displayName) {
1163                 old_string = pdb_get_fullname(account);
1164                 new_string = displayName;
1165
1166                 if (STRING_CHANGED)
1167                         pdb_set_fullname(account, new_string, PDB_CHANGED);
1168         }
1169
1170         if (homeDirectory) {
1171                 old_string = pdb_get_homedir(account);
1172                 new_string = homeDirectory;
1173
1174                 if (STRING_CHANGED)
1175                         pdb_set_homedir(account, new_string, PDB_CHANGED);
1176         }
1177
1178         if (homeDrive) {
1179                 old_string = pdb_get_dir_drive(account);
1180                 new_string = homeDrive;
1181
1182                 if (STRING_CHANGED)
1183                         pdb_set_dir_drive(account, new_string, PDB_CHANGED);
1184         }
1185
1186         if (scriptPath) {
1187                 old_string = pdb_get_logon_script(account);
1188                 new_string = scriptPath;
1189
1190                 if (STRING_CHANGED)
1191                         pdb_set_logon_script(account, new_string, PDB_CHANGED);
1192         }
1193
1194         if (description) {
1195                 old_string = pdb_get_acct_desc(account);
1196                 new_string = description;
1197
1198                 if (STRING_CHANGED)
1199                         pdb_set_acct_desc(account, new_string, PDB_CHANGED);
1200         }
1201
1202         if (userWorkstations) {
1203                 old_string = pdb_get_workstations(account);
1204                 new_string = userWorkstations;
1205
1206                 if (STRING_CHANGED)
1207                         pdb_set_workstations(account, new_string, PDB_CHANGED);
1208         }
1209
1210         if (profilePath) {
1211                 old_string = pdb_get_profile_path(account);
1212                 new_string = profilePath;
1213
1214                 if (STRING_CHANGED)
1215                         pdb_set_profile_path(account, new_string, PDB_CHANGED);
1216         }
1217
1218         if (userParameters.data) {
1219                 char *newstr;
1220                 old_string = pdb_get_munged_dial(account);
1221                 newstr = (userParameters.length == 0) ? NULL :
1222                         base64_encode_data_blob(talloc_tos(), userParameters);
1223
1224                 if (STRING_CHANGED_NC(old_string, newstr))
1225                         pdb_set_munged_dial(account, newstr, PDB_CHANGED);
1226                 TALLOC_FREE(newstr);
1227         }
1228
1229         /* User and group sid */
1230         if (rid != 0 && pdb_get_user_rid(account) != rid) {
1231                 pdb_set_user_sid_from_rid(account, rid, PDB_CHANGED);
1232         }
1233         if (primaryGroupID != 0 && pdb_get_group_rid(account) != primaryGroupID) {
1234                 pdb_set_group_sid_from_rid(account, primaryGroupID, PDB_CHANGED);
1235         }
1236
1237         /* Logon and password information */
1238         if (!nt_time_is_zero(&lastLogon)) {
1239                 unix_time = nt_time_to_unix(lastLogon);
1240                 stored_time = pdb_get_logon_time(account);
1241                 if (stored_time != unix_time)
1242                         pdb_set_logon_time(account, unix_time, PDB_CHANGED);
1243         }
1244
1245         if (!nt_time_is_zero(&lastLogoff)) {
1246                 unix_time = nt_time_to_unix(lastLogoff);
1247                 stored_time = pdb_get_logoff_time(account);
1248                 if (stored_time != unix_time)
1249                         pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
1250         }
1251
1252         /* Logon Divs */
1253         units_per_week = logonHours.length * 8;
1254
1255         if (pdb_get_logon_divs(account) != units_per_week) {
1256                 pdb_set_logon_divs(account, units_per_week, PDB_CHANGED);
1257         }
1258
1259         /* Logon Hours Len */
1260         if (units_per_week/8 != pdb_get_hours_len(account)) {
1261                 pdb_set_hours_len(account, units_per_week/8, PDB_CHANGED);
1262         }
1263
1264         /* Logon Hours */
1265         if (logonHours.data) {
1266                 char oldstr[44], newstr[44];
1267                 pdb_sethexhours(oldstr, pdb_get_hours(account));
1268                 pdb_sethexhours(newstr, logonHours.data);
1269                 if (!strequal(oldstr, newstr)) {
1270                         pdb_set_hours(account, logonHours.data, PDB_CHANGED);
1271                 }
1272         }
1273
1274         if (pdb_get_bad_password_count(account) != badPwdCount)
1275                 pdb_set_bad_password_count(account, badPwdCount, PDB_CHANGED);
1276
1277         if (pdb_get_logon_count(account) != logonCount)
1278                 pdb_set_logon_count(account, logonCount, PDB_CHANGED);
1279
1280         if (!nt_time_is_zero(&pwdLastSet)) {
1281                 unix_time = nt_time_to_unix(pwdLastSet);
1282                 stored_time = pdb_get_pass_last_set_time(account);
1283                 if (stored_time != unix_time)
1284                         pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
1285         } else {
1286                 /* no last set time, make it now */
1287                 pdb_set_pass_last_set_time(account, time(NULL), PDB_CHANGED);
1288         }
1289
1290         if (!nt_time_is_zero(&accountExpires)) {
1291                 unix_time = nt_time_to_unix(accountExpires);
1292                 stored_time = pdb_get_kickoff_time(account);
1293                 if (stored_time != unix_time)
1294                         pdb_set_kickoff_time(account, unix_time, PDB_CHANGED);
1295         }
1296
1297         /* Decode hashes from password hash
1298            Note that win2000 may send us all zeros for the hashes if it doesn't
1299            think this channel is secure enough - don't set the passwords at all
1300            in that case
1301         */
1302         if (dBCSPwd.length == 16 && memcmp(dBCSPwd.data, zero_buf, 16) != 0) {
1303                 pdb_set_lanman_passwd(account, dBCSPwd.data, PDB_CHANGED);
1304         }
1305
1306         if (unicodePwd.length == 16 && memcmp(unicodePwd.data, zero_buf, 16) != 0) {
1307                 pdb_set_nt_passwd(account, unicodePwd.data, PDB_CHANGED);
1308         }
1309
1310         /* TODO: history */
1311
1312         /* TODO: account expiry time */
1313
1314         pdb_set_acct_ctrl(account, acct_flags, PDB_CHANGED);
1315
1316         pdb_set_domain(account, lp_workgroup(), PDB_CHANGED);
1317
1318         DEBUG(0,("sam_account_from_object(%s, %s) done\n",
1319                  sAMAccountName, sid_string_dbg(&objectSid)));
1320         return NT_STATUS_OK;
1321 }
1322
1323 /****************************************************************
1324 ****************************************************************/
1325
1326 static NTSTATUS handle_account_object(struct dssync_passdb *pctx,
1327                                       TALLOC_CTX *mem_ctx,
1328                                       struct dssync_passdb_obj *obj)
1329 {
1330         struct drsuapi_DsReplicaObjectListItemEx *cur = obj->cur;
1331         NTSTATUS status;
1332         fstring account;
1333         struct samu *sam_account=NULL;
1334         GROUP_MAP map;
1335         struct group *grp;
1336         struct dom_sid user_sid;
1337         struct dom_sid group_sid;
1338         struct passwd *passwd = NULL;
1339         uint32_t acct_flags;
1340         uint32_t rid;
1341
1342         const char *sAMAccountName;
1343         uint32_t sAMAccountType;
1344         uint32_t userAccountControl;
1345
1346         user_sid = cur->object.identifier->sid;
1347         GET_STRING_EX(sAMAccountName, true);
1348         GET_UINT32_EX(sAMAccountType, true);
1349         GET_UINT32_EX(userAccountControl, true);
1350
1351         status = dom_sid_split_rid(mem_ctx, &user_sid, NULL, &rid);
1352         if (!NT_STATUS_IS_OK(status)) {
1353                 return status;
1354         }
1355
1356         fstrcpy(account, sAMAccountName);
1357         if (rid == DOMAIN_RID_GUEST) {
1358                 /*
1359                  * pdb_getsampwsid() has special handling for DOMAIN_RID_GUEST
1360                  * that's why we need to ignore it here.
1361                  *
1362                  * pdb_smbpasswd.c also has some DOMAIN_RID_GUEST related
1363                  * code...
1364                  */
1365                 DEBUG(0,("Ignore %s - %s\n", account, sid_string_dbg(&user_sid)));
1366                 return NT_STATUS_OK;
1367         }
1368         DEBUG(0,("Creating account: %s\n", account));
1369
1370         if ( !(sam_account = samu_new(mem_ctx)) ) {
1371                 return NT_STATUS_NO_MEMORY;
1372         }
1373
1374         acct_flags = ds_uf2acb(userAccountControl);
1375         status = smb_create_user(sam_account, acct_flags, account, &passwd);
1376         if (!NT_STATUS_IS_OK(status)) {
1377                 DEBUG(0,("Could not create posix account info for '%s'- %s\n",
1378                         account, nt_errstr(status)));
1379                 TALLOC_FREE(sam_account);
1380                 return status;
1381         }
1382
1383         DEBUG(3, ("Attempting to find SID %s for user %s in the passdb\n",
1384                   sid_string_dbg(&user_sid), account));
1385         if (!pdb_getsampwsid(sam_account, &user_sid)) {
1386                 sam_account_from_object(sam_account, cur);
1387                 DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n",
1388                           sid_string_dbg(&user_sid),
1389                           pdb_get_username(sam_account)));
1390                 if (!NT_STATUS_IS_OK(pdb_add_sam_account(sam_account))) {
1391                         DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
1392                                   account));
1393                         TALLOC_FREE(sam_account);
1394                         return NT_STATUS_ACCESS_DENIED;
1395                 }
1396         } else {
1397                 sam_account_from_object(sam_account, cur);
1398                 DEBUG(3, ("Attempting to update user SID %s for user %s in the passdb\n",
1399                           sid_string_dbg(&user_sid),
1400                           pdb_get_username(sam_account)));
1401                 if (!NT_STATUS_IS_OK(pdb_update_sam_account(sam_account))) {
1402                         DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
1403                                   account));
1404                         TALLOC_FREE(sam_account);
1405                         return NT_STATUS_ACCESS_DENIED;
1406                 }
1407         }
1408
1409         if (pdb_get_group_sid(sam_account) == NULL) {
1410                 TALLOC_FREE(sam_account);
1411                 return NT_STATUS_UNSUCCESSFUL;
1412         }
1413
1414         group_sid = *pdb_get_group_sid(sam_account);
1415
1416         if (!pdb_getgrsid(&map, group_sid)) {
1417                 DEBUG(0, ("Primary group of %s has no mapping!\n",
1418                           pdb_get_username(sam_account)));
1419         } else {
1420                 if (map.gid != passwd->pw_gid) {
1421                         if (!(grp = getgrgid(map.gid))) {
1422                                 DEBUG(0, ("Could not find unix group %lu for user %s (group SID=%s)\n",
1423                                           (unsigned long)map.gid, pdb_get_username(sam_account),
1424                                           sid_string_dbg(&group_sid)));
1425                         } else {
1426                                 smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
1427                         }
1428                 }
1429         }
1430
1431         if ( !passwd ) {
1432                 DEBUG(1, ("No unix user for this account (%s), cannot adjust mappings\n",
1433                         pdb_get_username(sam_account)));
1434         }
1435
1436         TALLOC_FREE(sam_account);
1437         return NT_STATUS_OK;
1438 }
1439
1440 /****************************************************************
1441 ****************************************************************/
1442
1443 static NTSTATUS handle_alias_object(struct dssync_passdb *pctx,
1444                                     TALLOC_CTX *mem_ctx,
1445                                     struct dssync_passdb_obj *obj)
1446 {
1447         struct drsuapi_DsReplicaObjectListItemEx *cur = obj->cur;
1448         NTSTATUS status;
1449         fstring name;
1450         fstring comment;
1451         struct group *grp = NULL;
1452         struct dom_sid group_sid;
1453         uint32_t rid = 0;
1454         struct dom_sid *dom_sid = NULL;
1455         fstring sid_string;
1456         GROUP_MAP map;
1457         bool insert = true;
1458
1459         const char *sAMAccountName;
1460         uint32_t sAMAccountType;
1461         uint32_t groupType;
1462         const char *description;
1463         uint32_t i;
1464         uint32_t num_members = 0;
1465         struct drsuapi_DsReplicaObjectIdentifier3 *members = NULL;
1466
1467         group_sid = cur->object.identifier->sid;
1468         GET_STRING_EX(sAMAccountName, true);
1469         GET_UINT32_EX(sAMAccountType, true);
1470         GET_UINT32_EX(groupType, true);
1471         GET_STRING(description);
1472
1473         status = find_drsuapi_attr_dn(obj, cur, DRSUAPI_ATTID_member,
1474                                       &num_members, &members);
1475         if (NT_STATUS_EQUAL(status, NT_STATUS_PROPSET_NOT_FOUND)) {
1476                 status = NT_STATUS_OK;
1477         }
1478         if (!NT_STATUS_IS_OK(status)) {
1479                 return status;
1480         }
1481
1482         fstrcpy(name, sAMAccountName);
1483         fstrcpy(comment, description);
1484
1485         dom_sid_split_rid(mem_ctx, &group_sid, &dom_sid, &rid);
1486
1487         sid_to_fstring(sid_string, &group_sid);
1488         DEBUG(0,("Creating alias[%s] - %s members[%u]\n",
1489                   name, sid_string, num_members));
1490
1491         status = dssync_insert_obj(pctx, pctx->aliases, obj);
1492         if (!NT_STATUS_IS_OK(status)) {
1493                 return status;
1494         }
1495
1496         if (pdb_getgrsid(&map, group_sid)) {
1497                 if ( map.gid != -1 )
1498                         grp = getgrgid(map.gid);
1499                 insert = false;
1500         }
1501
1502         if (grp == NULL) {
1503                 gid_t gid;
1504
1505                 /* No group found from mapping, find it from its name. */
1506                 if ((grp = getgrnam(name)) == NULL) {
1507
1508                         /* No appropriate group found, create one */
1509
1510                         DEBUG(0,("Creating unix group: '%s'\n", name));
1511
1512                         if (smb_create_group(name, &gid) != 0)
1513                                 return NT_STATUS_ACCESS_DENIED;
1514
1515                         if ((grp = getgrgid(gid)) == NULL)
1516                                 return NT_STATUS_ACCESS_DENIED;
1517                 }
1518         }
1519
1520         map.gid = grp->gr_gid;
1521         map.sid = group_sid;
1522
1523         if (dom_sid_equal(dom_sid, &global_sid_Builtin)) {
1524                 /*
1525                  * pdb_ldap does not like SID_NAME_WKN_GRP...
1526                  *
1527                  * map.sid_name_use = SID_NAME_WKN_GRP;
1528                  */
1529                 map.sid_name_use = SID_NAME_ALIAS;
1530         } else {
1531                 map.sid_name_use = SID_NAME_ALIAS;
1532         }
1533
1534         fstrcpy(map.nt_name, name);
1535         if (description) {
1536                 fstrcpy(map.comment, comment);
1537         } else {
1538                 fstrcpy(map.comment, "");
1539         }
1540
1541         if (insert)
1542                 pdb_add_group_mapping_entry(&map);
1543         else
1544                 pdb_update_group_mapping_entry(&map);
1545
1546         for (i=0; i < num_members; i++) {
1547                 struct dssync_passdb_mem *mem;
1548
1549                 status = dssync_create_mem(pctx, obj,
1550                                            true /* active */,
1551                                            &members[i], &mem);
1552                 if (!NT_STATUS_IS_OK(status)) {
1553                         return status;
1554                 }
1555         }
1556
1557         return NT_STATUS_OK;
1558 }
1559
1560 /****************************************************************
1561 ****************************************************************/
1562
1563 static NTSTATUS handle_group_object(struct dssync_passdb *pctx,
1564                                     TALLOC_CTX *mem_ctx,
1565                                     struct dssync_passdb_obj *obj)
1566 {
1567         struct drsuapi_DsReplicaObjectListItemEx *cur = obj->cur;
1568         NTSTATUS status;
1569         fstring name;
1570         fstring comment;
1571         struct group *grp = NULL;
1572         struct dom_sid group_sid;
1573         fstring sid_string;
1574         GROUP_MAP map;
1575         bool insert = true;
1576
1577         const char *sAMAccountName;
1578         uint32_t sAMAccountType;
1579         uint32_t groupType;
1580         const char *description;
1581         uint32_t i;
1582         uint32_t num_members = 0;
1583         struct drsuapi_DsReplicaObjectIdentifier3 *members = NULL;
1584
1585         group_sid = cur->object.identifier->sid;
1586         GET_STRING_EX(sAMAccountName, true);
1587         GET_UINT32_EX(sAMAccountType, true);
1588         GET_UINT32_EX(groupType, true);
1589         GET_STRING(description);
1590
1591         status = find_drsuapi_attr_dn(obj, cur, DRSUAPI_ATTID_member,
1592                                       &num_members, &members);
1593         if (NT_STATUS_EQUAL(status, NT_STATUS_PROPSET_NOT_FOUND)) {
1594                 status = NT_STATUS_OK;
1595         }
1596         if (!NT_STATUS_IS_OK(status)) {
1597                 return status;
1598         }
1599
1600         fstrcpy(name, sAMAccountName);
1601         fstrcpy(comment, description);
1602
1603         sid_to_fstring(sid_string, &group_sid);
1604         DEBUG(0,("Creating group[%s] - %s members [%u]\n",
1605                   name, sid_string, num_members));
1606
1607         status = dssync_insert_obj(pctx, pctx->groups, obj);
1608         if (!NT_STATUS_IS_OK(status)) {
1609                 return status;
1610         }
1611
1612         if (pdb_getgrsid(&map, group_sid)) {
1613                 if ( map.gid != -1 )
1614                         grp = getgrgid(map.gid);
1615                 insert = false;
1616         }
1617
1618         if (grp == NULL) {
1619                 gid_t gid;
1620
1621                 /* No group found from mapping, find it from its name. */
1622                 if ((grp = getgrnam(name)) == NULL) {
1623
1624                         /* No appropriate group found, create one */
1625
1626                         DEBUG(0,("Creating unix group: '%s'\n", name));
1627
1628                         if (smb_create_group(name, &gid) != 0)
1629                                 return NT_STATUS_ACCESS_DENIED;
1630
1631                         if ((grp = getgrnam(name)) == NULL)
1632                                 return NT_STATUS_ACCESS_DENIED;
1633                 }
1634         }
1635
1636         map.gid = grp->gr_gid;
1637         map.sid = group_sid;
1638         map.sid_name_use = SID_NAME_DOM_GRP;
1639         fstrcpy(map.nt_name, name);
1640         if (description) {
1641                 fstrcpy(map.comment, comment);
1642         } else {
1643                 fstrcpy(map.comment, "");
1644         }
1645
1646         if (insert)
1647                 pdb_add_group_mapping_entry(&map);
1648         else
1649                 pdb_update_group_mapping_entry(&map);
1650
1651         for (i=0; i < num_members; i++) {
1652                 struct dssync_passdb_mem *mem;
1653
1654                 status = dssync_create_mem(pctx, obj,
1655                                            true /* active */,
1656                                            &members[i], &mem);
1657                 if (!NT_STATUS_IS_OK(status)) {
1658                         return status;
1659                 }
1660         }
1661
1662         return NT_STATUS_OK;
1663 }
1664
1665 /****************************************************************
1666 ****************************************************************/
1667
1668 static NTSTATUS handle_interdomain_trust_object(struct dssync_passdb *pctx,
1669                                                 TALLOC_CTX *mem_ctx,
1670                                                 struct dssync_passdb_obj *obj)
1671 {
1672         struct drsuapi_DsReplicaObjectListItemEx *cur = obj->cur;
1673         DEBUG(0,("trust: %s\n", cur->object.identifier->dn));
1674         return NT_STATUS_NOT_IMPLEMENTED;
1675 }
1676
1677 /****************************************************************
1678 ****************************************************************/
1679
1680 struct dssync_object_table_t {
1681         uint32_t type;
1682         NTSTATUS (*fn) (struct dssync_passdb *pctx,
1683                         TALLOC_CTX *mem_ctx,
1684                         struct dssync_passdb_obj *obj);
1685 };
1686
1687 static const struct dssync_object_table_t dssync_object_table[] = {
1688         { ATYPE_NORMAL_ACCOUNT,         handle_account_object },
1689         { ATYPE_WORKSTATION_TRUST,      handle_account_object },
1690         { ATYPE_SECURITY_LOCAL_GROUP,   handle_alias_object },
1691         { ATYPE_SECURITY_GLOBAL_GROUP,  handle_group_object },
1692         { ATYPE_INTERDOMAIN_TRUST,      handle_interdomain_trust_object },
1693 };
1694
1695 /****************************************************************
1696 ****************************************************************/
1697
1698 static NTSTATUS parse_object(struct dssync_passdb *pctx,
1699                              TALLOC_CTX *mem_ctx,
1700                              struct drsuapi_DsReplicaObjectListItemEx *cur)
1701 {
1702         NTSTATUS status = NT_STATUS_OK;
1703         DATA_BLOB *blob;
1704         int i = 0;
1705         int a = 0;
1706         struct drsuapi_DsReplicaAttribute *attr;
1707
1708         char *name = NULL;
1709         uint32_t uacc = 0;
1710         uint32_t sam_type = 0;
1711
1712         DEBUG(3, ("parsing object '%s'\n", cur->object.identifier->dn));
1713
1714         for (i=0; i < cur->object.attribute_ctr.num_attributes; i++) {
1715
1716                 attr = &cur->object.attribute_ctr.attributes[i];
1717
1718                 if (attr->value_ctr.num_values != 1) {
1719                         continue;
1720                 }
1721
1722                 if (!attr->value_ctr.values[0].blob) {
1723                         continue;
1724                 }
1725
1726                 blob = attr->value_ctr.values[0].blob;
1727
1728                 switch (attr->attid) {
1729                         case DRSUAPI_ATTID_sAMAccountName:
1730                                 pull_string_talloc(mem_ctx, NULL, 0, &name,
1731                                                    blob->data, blob->length,
1732                                                    STR_UNICODE);
1733                                 break;
1734                         case DRSUAPI_ATTID_sAMAccountType:
1735                                 sam_type = IVAL(blob->data, 0);
1736                                 break;
1737                         case DRSUAPI_ATTID_userAccountControl:
1738                                 uacc = IVAL(blob->data, 0);
1739                                 break;
1740                         default:
1741                                 break;
1742                 }
1743         }
1744
1745         for (a=0; a < ARRAY_SIZE(dssync_object_table); a++) {
1746                 if (sam_type == dssync_object_table[a].type) {
1747                         if (dssync_object_table[a].fn) {
1748                                 struct dssync_passdb_obj *obj;
1749                                 status = dssync_create_obj(pctx, pctx->all,
1750                                                            sam_type, cur, &obj);
1751                                 if (!NT_STATUS_IS_OK(status)) {
1752                                         break;
1753                                 }
1754                                 status = dssync_object_table[a].fn(pctx,
1755                                                                    mem_ctx,
1756                                                                    obj);
1757                                 break;
1758                         }
1759                 }
1760         }
1761
1762         return status;
1763 }
1764
1765 static NTSTATUS parse_link(struct dssync_passdb *pctx,
1766                            TALLOC_CTX *mem_ctx,
1767                            struct drsuapi_DsReplicaLinkedAttribute *cur)
1768 {
1769         struct drsuapi_DsReplicaObjectIdentifier3 *id3;
1770         const DATA_BLOB *blob;
1771         enum ndr_err_code ndr_err;
1772         NTSTATUS status;
1773         bool active = false;
1774         struct dssync_passdb_mem *mem;
1775         struct dssync_passdb_obj *obj;
1776
1777         if (cur->attid != DRSUAPI_ATTID_member) {
1778                 return NT_STATUS_OK;
1779         }
1780
1781         if (cur->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE) {
1782                 active = true;
1783         }
1784
1785         DEBUG(3, ("parsing link '%s' - %s\n",
1786                   cur->identifier->dn, active?"adding":"deleting"));
1787
1788         blob = cur->value.blob;
1789
1790         if (blob == NULL) {
1791                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1792         }
1793
1794         obj = dssync_search_obj_by_guid(pctx, pctx->all, &cur->identifier->guid);
1795         if (obj == NULL) {
1796                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1797         }
1798
1799         id3 = talloc_zero(obj, struct drsuapi_DsReplicaObjectIdentifier3);
1800         if (id3 == NULL) {
1801                 return NT_STATUS_NO_MEMORY;
1802         }
1803
1804         /* windows sometimes sends an extra two pad bytes here */
1805         ndr_err = ndr_pull_struct_blob(blob, id3, id3,
1806                         (ndr_pull_flags_fn_t)ndr_pull_drsuapi_DsReplicaObjectIdentifier3);
1807         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1808                 status = ndr_map_error2ntstatus(ndr_err);
1809                 return status;
1810         }
1811
1812         status = dssync_create_mem(pctx, obj,
1813                                    active,
1814                                    id3, &mem);
1815         if (!NT_STATUS_IS_OK(status)) {
1816                 return status;
1817         }
1818
1819         return NT_STATUS_OK;
1820 }
1821
1822 /****************************************************************
1823 ****************************************************************/
1824
1825 static NTSTATUS passdb_process_objects(struct dssync_context *ctx,
1826                                        TALLOC_CTX *mem_ctx,
1827                                        struct drsuapi_DsReplicaObjectListItemEx *cur,
1828                                        struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr)
1829 {
1830         NTSTATUS status = NT_STATUS_OK;
1831         struct dssync_passdb *pctx =
1832                 talloc_get_type_abort(ctx->private_data,
1833                 struct dssync_passdb);
1834
1835         for (; cur; cur = cur->next_object) {
1836                 status = parse_object(pctx, mem_ctx, cur);
1837                 if (!NT_STATUS_IS_OK(status)) {
1838                         goto out;
1839                 }
1840         }
1841
1842  out:
1843         return status;
1844 }
1845
1846 /****************************************************************
1847 ****************************************************************/
1848
1849 static NTSTATUS passdb_process_links(struct dssync_context *ctx,
1850                                      TALLOC_CTX *mem_ctx,
1851                                      uint32_t count,
1852                                      struct drsuapi_DsReplicaLinkedAttribute *links,
1853                                      struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr)
1854 {
1855         NTSTATUS status = NT_STATUS_OK;
1856         struct dssync_passdb *pctx =
1857                 talloc_get_type_abort(ctx->private_data,
1858                 struct dssync_passdb);
1859         uint32_t i;
1860
1861         for (i = 0; i < count; i++) {
1862                 status = parse_link(pctx, mem_ctx, &links[i]);
1863                 if (!NT_STATUS_IS_OK(status)) {
1864                         goto out;
1865                 }
1866         }
1867
1868  out:
1869         return status;
1870 }
1871
1872 /****************************************************************
1873 ****************************************************************/
1874
1875 const struct dssync_ops libnet_dssync_passdb_ops = {
1876         .startup                = passdb_startup,
1877         .process_objects        = passdb_process_objects,
1878         .process_links          = passdb_process_links,
1879         .finish                 = passdb_finish,
1880 };