1a88fd4cb84685d50c19d6f9636e04def969a67c
[mat/samba.git] / source3 / winbindd / idmap_autorid.c
1 /*
2  *  idmap_autorid: static map between Active Directory/NT RIDs
3  *  and RFC 2307 accounts
4  *
5  *  based on the idmap_rid module, but this module defines the ranges
6  *  for the domains by automatically allocating a range for each domain
7  *
8  *  Copyright (C) Christian Ambach, 2010-2011
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 3 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include "includes.h"
26 #include "system/filesys.h"
27 #include "winbindd.h"
28 #include "dbwrap/dbwrap.h"
29 #include "dbwrap/dbwrap_open.h"
30 #include "idmap.h"
31 #include "../libcli/security/dom_sid.h"
32 #include "util_tdb.h"
33
34 #undef DBGC_CLASS
35 #define DBGC_CLASS DBGC_IDMAP
36
37 #define HWM "NEXT RANGE"
38 #define ALLOC_HWM_UID "NEXT ALLOC UID"
39 #define ALLOC_HWM_GID "NEXT ALLOC GID"
40 #define ALLOC_RANGE "ALLOC"
41 #define CONFIGKEY "CONFIG"
42
43 struct autorid_global_config {
44         uint32_t minvalue;
45         uint32_t rangesize;
46         uint32_t maxranges;
47 };
48
49 struct autorid_domain_config {
50         fstring sid;
51         uint32_t domainnum;
52         struct autorid_global_config *globalcfg;
53 };
54
55 /* handle to the tdb storing domain <-> range assignments */
56 static struct db_context *autorid_db;
57
58 static NTSTATUS idmap_autorid_get_domainrange(struct db_context *db,
59                                               void *private_data)
60 {
61         NTSTATUS ret;
62         uint32_t domainnum, hwm;
63         char *numstr;
64         struct autorid_domain_config *cfg;
65
66         cfg = (struct autorid_domain_config *)private_data;
67
68         ret = dbwrap_fetch_uint32(db, cfg->sid, &domainnum);
69         if (!NT_STATUS_IS_OK(ret)) {
70                 DEBUG(10, ("Acquiring new range for domain %s\n", cfg->sid));
71
72                 /* fetch the current HWM */
73                 ret = dbwrap_fetch_uint32(db, HWM, &hwm);
74                 if (!NT_STATUS_IS_OK(ret)) {
75                         DEBUG(1, ("Fatal error while fetching current "
76                                   "HWM value: %s\n", nt_errstr(ret)));
77                         ret = NT_STATUS_INTERNAL_ERROR;
78                         goto error;
79                 }
80
81                 /* do we have a range left? */
82                 if (hwm >= cfg->globalcfg->maxranges) {
83                         DEBUG(1, ("No more domain ranges available!\n"));
84                         ret = NT_STATUS_NO_MEMORY;
85                         goto error;
86                 }
87
88                 /* increase the HWM */
89                 ret = dbwrap_change_uint32_atomic(db, HWM, &domainnum, 1);
90                 if (!NT_STATUS_IS_OK(ret)) {
91                         DEBUG(1, ("Fatal error while fetching a new "
92                                   "domain range value!\n"));
93                         goto error;
94                 }
95
96                 /* store away the new mapping in both directions */
97                 ret = dbwrap_trans_store_uint32(db, cfg->sid, domainnum);
98                 if (!NT_STATUS_IS_OK(ret)) {
99                         DEBUG(1, ("Fatal error while storing new "
100                                   "domain->range assignment!\n"));
101                         goto error;
102                 }
103
104                 numstr = talloc_asprintf(db, "%u", domainnum);
105                 if (!numstr) {
106                         ret = NT_STATUS_NO_MEMORY;
107                         goto error;
108                 }
109
110                 ret = dbwrap_trans_store_bystring(db, numstr,
111                                 string_term_tdb_data(cfg->sid), TDB_INSERT);
112
113                 talloc_free(numstr);
114                 if (!NT_STATUS_IS_OK(ret)) {
115                         DEBUG(1, ("Fatal error while storing "
116                                   "new domain->range assignment!\n"));
117                         goto error;
118                 }
119                 DEBUG(5, ("Acquired new range #%d for domain %s\n",
120                           domainnum, cfg->sid));
121         }
122
123         DEBUG(10, ("Using range #%d for domain %s\n", domainnum, cfg->sid));
124         cfg->domainnum = domainnum;
125
126         return NT_STATUS_OK;
127
128       error:
129         return ret;
130
131 }
132
133 static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
134                                         struct id_map *map)
135 {
136         uint32_t range;
137         TDB_DATA data;
138         char *keystr;
139         struct dom_sid sid;
140         NTSTATUS status;
141
142         /* can this be one of our ids? */
143         if (map->xid.id < cfg->minvalue) {
144                 DEBUG(10, ("id %d is lower than minimum value, "
145                            "ignoring mapping request\n", map->xid.id));
146                 map->status = ID_UNKNOWN;
147                 return NT_STATUS_OK;
148         }
149
150         if (map->xid.id > (cfg->minvalue + cfg->rangesize * cfg->maxranges)) {
151                 DEBUG(10, ("id %d is outside of maximum id value, "
152                            "ignoring mapping request\n", map->xid.id));
153                 map->status = ID_UNKNOWN;
154                 return NT_STATUS_OK;
155         }
156
157         /* determine the range of this uid */
158         range = ((map->xid.id - cfg->minvalue) / cfg->rangesize);
159
160         keystr = talloc_asprintf(talloc_tos(), "%u", range);
161         if (!keystr) {
162                 return NT_STATUS_NO_MEMORY;
163         }
164
165         status = dbwrap_fetch_bystring(autorid_db, talloc_tos(), keystr, &data);
166         TALLOC_FREE(keystr);
167
168         if (!NT_STATUS_IS_OK(status)) {
169                 DEBUG(4, ("id %d belongs to range %d which does not have "
170                           "domain mapping, ignoring mapping request\n",
171                           map->xid.id, range));
172                 TALLOC_FREE(data.dptr);
173                 map->status = ID_UNKNOWN;
174                 return NT_STATUS_OK;
175         }
176
177         if (strncmp((const char *)data.dptr,
178                     ALLOC_RANGE,
179                     strlen(ALLOC_RANGE)) == 0) {
180                 /* this is from the alloc range, there is no mapping back */
181                 DEBUG(5, ("id %d belongs to alloc range, cannot map back\n",
182                           map->xid.id));
183                 TALLOC_FREE(data.dptr);
184                 map->status = ID_UNKNOWN;
185                 return NT_STATUS_OK;
186         }
187
188         string_to_sid(&sid, (const char *)data.dptr);
189         TALLOC_FREE(data.dptr);
190
191         sid_compose(map->sid, &sid,
192                     (map->xid.id - cfg->minvalue -
193                      range * cfg->rangesize));
194
195         /* We **really** should have some way of validating
196            the SID exists and is the correct type here.  But
197            that is a deficiency in the idmap_rid design. */
198
199         map->status = ID_MAPPED;
200         return NT_STATUS_OK;
201 }
202
203 /**********************************
204  Single sid to id lookup function.
205 **********************************/
206
207 static NTSTATUS idmap_autorid_sid_to_id(struct autorid_global_config *global,
208                                         struct autorid_domain_config *domain,
209                                         struct id_map *map)
210 {
211         uint32_t rid;
212
213         sid_peek_rid(map->sid, &rid);
214
215         /* if the rid is higher than the size of the range, we cannot map it */
216         if (rid >= global->rangesize) {
217                 map->status = ID_UNKNOWN;
218                 DEBUG(2, ("RID %d is larger then size of range (%d), "
219                           "user cannot be mapped\n", rid, global->rangesize));
220                 return NT_STATUS_UNSUCCESSFUL;
221         }
222         map->xid.id = global->minvalue +
223             (global->rangesize * domain->domainnum)+rid;
224
225         /* We **really** should have some way of validating
226            the SID exists and is the correct type here.  But
227            that is a deficiency in the idmap_rid design. */
228
229         map->status = ID_MAPPED;
230
231         return NT_STATUS_OK;
232 }
233
234 /**********************************
235  lookup a set of unix ids.
236 **********************************/
237
238 static NTSTATUS idmap_autorid_unixids_to_sids(struct idmap_domain *dom,
239                                               struct id_map **ids)
240 {
241         struct autorid_global_config *globalcfg;
242         NTSTATUS ret;
243         int i;
244
245         /* initialize the status to avoid surprise */
246         for (i = 0; ids[i]; i++) {
247                 ids[i]->status = ID_UNKNOWN;
248         }
249
250         globalcfg = talloc_get_type(dom->private_data,
251                                     struct autorid_global_config);
252
253         for (i = 0; ids[i]; i++) {
254
255                 ret = idmap_autorid_id_to_sid(globalcfg, ids[i]);
256
257                 if ((!NT_STATUS_IS_OK(ret)) &&
258                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
259                         /* some fatal error occurred, log it */
260                         DEBUG(3, ("Unexpected error resolving an ID "
261                                   " (%d)\n", ids[i]->xid.id));
262                         goto failure;
263                 }
264         }
265         return NT_STATUS_OK;
266
267       failure:
268         return ret;
269 }
270
271 /**********************************
272  lookup a set of sids.
273 **********************************/
274
275 static NTSTATUS idmap_autorid_sids_to_unixids(struct idmap_domain *dom,
276                                               struct id_map **ids)
277 {
278         struct autorid_global_config *global;
279         NTSTATUS ret;
280         int i;
281
282         /* initialize the status to avoid surprise */
283         for (i = 0; ids[i]; i++) {
284                 ids[i]->status = ID_UNKNOWN;
285         }
286
287         global = talloc_get_type(dom->private_data,
288                                  struct autorid_global_config);
289
290         for (i = 0; ids[i]; i++) {
291                 struct winbindd_tdc_domain *domain;
292                 struct autorid_domain_config domaincfg;
293                 uint32_t rid;
294                 struct dom_sid domainsid;
295
296                 ZERO_STRUCT(domaincfg);
297
298                 sid_copy(&domainsid, ids[i]->sid);
299                 if (!sid_split_rid(&domainsid, &rid)) {
300                         DEBUG(4, ("Could not determine domain SID from %s, "
301                                   "ignoring mapping request\n",
302                                   sid_string_dbg(ids[i]->sid)));
303                         continue;
304                 }
305
306                 /*
307                  * Check if the domain is around
308                  */
309                 domain = wcache_tdc_fetch_domainbysid(talloc_tos(),
310                                                       &domainsid);
311                 if (domain == NULL) {
312                         DEBUG(10, ("Ignoring unknown domain sid %s\n",
313                                    sid_string_dbg(&domainsid)));
314                         continue;
315                 }
316                 TALLOC_FREE(domain);
317
318                 domaincfg.globalcfg = global;
319                 sid_to_fstring(domaincfg.sid, &domainsid);
320
321                 ret = dbwrap_trans_do(autorid_db,
322                                       idmap_autorid_get_domainrange,
323                                       &domaincfg);
324
325                 if (!NT_STATUS_IS_OK(ret)) {
326                         DEBUG(3, ("Could not determine range for domain, "
327                                   "check previous messages for reason\n"));
328                         goto failure;
329                 }
330
331                 ret = idmap_autorid_sid_to_id(global, &domaincfg, ids[i]);
332
333                 if ((!NT_STATUS_IS_OK(ret)) &&
334                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
335                         /* some fatal error occurred, log it */
336                         DEBUG(3, ("Unexpected error resolving a SID (%s)\n",
337                                   sid_string_dbg(ids[i]->sid)));
338                         goto failure;
339                 }
340         }
341         return NT_STATUS_OK;
342
343       failure:
344         return ret;
345
346 }
347
348 /* initialize the given HWM to 0 if it does not exist yet */
349 static NTSTATUS idmap_autorid_init_hwm(const char *hwm) {
350
351         NTSTATUS status;
352         uint32_t hwmval;
353
354         status = dbwrap_fetch_uint32(autorid_db, hwm, &hwmval);
355         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND))  {
356                 status = dbwrap_trans_store_int32(autorid_db, hwm, 0);
357                 if (!NT_STATUS_IS_OK(status)) {
358                         DEBUG(0,
359                               ("Unable to initialise HWM (%s) in autorid "
360                                "database: %s\n", hwm, nt_errstr(status)));
361                         return NT_STATUS_INTERNAL_DB_ERROR;
362                 }
363         } else if (!NT_STATUS_IS_OK(status)) {
364                 DEBUG(0, ("unable to fetch HWM (%s) from autorid "
365                           "database: %s\n", hwm,  nt_errstr(status)));
366                 return status;
367         }
368
369         return NT_STATUS_OK;
370 }
371
372 /*
373  * open and initialize the database which stores the ranges for the domains
374  */
375 static NTSTATUS idmap_autorid_db_init(void)
376 {
377         NTSTATUS status;
378
379         if (autorid_db) {
380                 /* its already open */
381                 return NT_STATUS_OK;
382         }
383
384         /* Open idmap repository */
385         autorid_db = db_open(NULL, state_path("autorid.tdb"), 0,
386                              TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
387
388         if (!autorid_db) {
389                 DEBUG(0, ("Unable to open idmap_autorid database '%s'\n",
390                           state_path("autorid.tdb")));
391                 return NT_STATUS_UNSUCCESSFUL;
392         }
393
394         /* Initialize high water mark for the currently used range to 0 */
395
396         status = idmap_autorid_init_hwm(HWM);
397         NT_STATUS_NOT_OK_RETURN(status);
398
399         status = idmap_autorid_init_hwm(ALLOC_HWM_UID);
400         NT_STATUS_NOT_OK_RETURN(status);
401
402         status = idmap_autorid_init_hwm(ALLOC_HWM_GID);
403
404         return status;
405 }
406
407 static struct autorid_global_config *idmap_autorid_loadconfig(TALLOC_CTX * ctx)
408 {
409
410         TDB_DATA data;
411         struct autorid_global_config *cfg;
412         unsigned long minvalue, rangesize, maxranges;
413         NTSTATUS status;
414
415         status = dbwrap_fetch_bystring(autorid_db, ctx, CONFIGKEY, &data);
416
417         if (!NT_STATUS_IS_OK(status)) {
418                 DEBUG(10, ("No saved config found\n"));
419                 return NULL;
420         }
421
422         cfg = talloc_zero(ctx, struct autorid_global_config);
423         if (!cfg) {
424                 return NULL;
425         }
426
427         if (sscanf((char *)data.dptr,
428                    "minvalue:%lu rangesize:%lu maxranges:%lu",
429                    &minvalue, &rangesize, &maxranges) != 3) {
430                 DEBUG(1,
431                       ("Found invalid configuration data"
432                        "creating new config\n"));
433                 return NULL;
434         }
435
436         cfg->minvalue = minvalue;
437         cfg->rangesize = rangesize;
438         cfg->maxranges = maxranges;
439
440         DEBUG(10, ("Loaded previously stored configuration "
441                    "minvalue:%d rangesize:%d\n",
442                    cfg->minvalue, cfg->rangesize));
443
444         return cfg;
445
446 }
447
448 static NTSTATUS idmap_autorid_saveconfig(struct autorid_global_config *cfg)
449 {
450
451         NTSTATUS status;
452         TDB_DATA data;
453         char *cfgstr;
454
455         cfgstr =
456             talloc_asprintf(talloc_tos(),
457                             "minvalue:%u rangesize:%u maxranges:%u",
458                             cfg->minvalue, cfg->rangesize, cfg->maxranges);
459
460         if (!cfgstr) {
461                 return NT_STATUS_NO_MEMORY;
462         }
463
464         data = string_tdb_data(cfgstr);
465
466         status = dbwrap_trans_store_bystring(autorid_db, CONFIGKEY,
467                                              data, TDB_REPLACE);
468
469         talloc_free(cfgstr);
470
471         return status;
472 }
473
474 static NTSTATUS idmap_autorid_initialize(struct idmap_domain *dom)
475 {
476         struct autorid_global_config *config;
477         struct autorid_global_config *storedconfig = NULL;
478         NTSTATUS status;
479         uint32_t hwm;
480
481         if (!strequal(dom->name, "*")) {
482                 DEBUG(0, ("idmap_autorid_initialize: Error: autorid configured "
483                           "for domain '%s'. But autorid can only be used for "
484                           "the default idmap configuration.\n", dom->name));
485                 return NT_STATUS_INVALID_PARAMETER;
486         }
487
488         config = talloc_zero(dom, struct autorid_global_config);
489         if (!config) {
490                 DEBUG(0, ("Out of memory!\n"));
491                 return NT_STATUS_NO_MEMORY;
492         }
493
494         status = idmap_autorid_db_init();
495         if (!NT_STATUS_IS_OK(status)) {
496                 goto error;
497         }
498
499         config->minvalue = dom->low_id;
500         config->rangesize = lp_parm_int(-1, "idmap config *", "rangesize", 100000);
501
502         if (config->rangesize < 2000) {
503                 DEBUG(1, ("autorid rangesize must be at least 2000\n"));
504                 status = NT_STATUS_INVALID_PARAMETER;
505                 goto error;
506         }
507
508         config->maxranges = (dom->high_id - dom->low_id + 1) /
509             config->rangesize;
510
511         if (config->maxranges == 0) {
512                 DEBUG(1, ("allowed uid range is smaller then rangesize, "
513                           "increase uid range or decrease rangesize\n"));
514                 status = NT_STATUS_INVALID_PARAMETER;
515                 goto error;
516         }
517
518         /* check if the high-low limit is a multiple of the rangesize */
519         if ((dom->high_id - dom->low_id + 1) % config->rangesize != 0) {
520                 DEBUG(5, ("High uid-low uid difference of %d "
521                           "is not a multiple of the rangesize %d, "
522                           "limiting ranges to lower boundary number of %d\n",
523                           (dom->high_id - dom->low_id + 1), config->rangesize,
524                           config->maxranges));
525         }
526
527         DEBUG(10, ("Current configuration in config is "
528                    "minvalue:%d rangesize:%d maxranges:%d\n",
529                    config->minvalue, config->rangesize, config->maxranges));
530
531         /* read previously stored config and current HWM */
532         storedconfig = idmap_autorid_loadconfig(talloc_tos());
533
534         status = dbwrap_fetch_uint32(autorid_db, HWM, &hwm);
535         if (!NT_STATUS_IS_OK(status)) {
536                 DEBUG(1, ("Fatal error while fetching current "
537                           "HWM value: %s\n", nt_errstr(status)));
538                 status = NT_STATUS_INTERNAL_ERROR;
539                 goto error;
540         }
541
542         /* did the minimum value or rangesize change? */
543         if (storedconfig &&
544             ((storedconfig->minvalue != config->minvalue) ||
545              (storedconfig->rangesize != config->rangesize))) {
546                 DEBUG(1, ("New configuration values for rangesize or "
547                           "minimum uid value conflict with previously "
548                           "used values! Aborting initialization\n"));
549                 status = NT_STATUS_INVALID_PARAMETER;
550                 goto error;
551         }
552
553         /*
554          * has the highest uid value been reduced to setting that is not
555          * sufficient any more for already existing ranges?
556          */
557         if (hwm > config->maxranges) {
558                 DEBUG(1, ("New upper uid limit is too low to cover "
559                           "existing mappings! Aborting initialization\n"));
560                 status = NT_STATUS_INVALID_PARAMETER;
561                 goto error;
562         }
563
564         status = idmap_autorid_saveconfig(config);
565
566         if (!NT_STATUS_IS_OK(status)) {
567                 DEBUG(1, ("Failed to store configuration data!\n"));
568                 goto error;
569         }
570
571         DEBUG(5, ("%d domain ranges with a size of %d are available\n",
572                   config->maxranges, config->rangesize));
573
574         dom->private_data = config;
575
576         goto done;
577
578 error:
579         talloc_free(config);
580
581 done:
582         talloc_free(storedconfig);
583
584         return status;
585 }
586
587 static NTSTATUS idmap_autorid_allocate_id(struct idmap_domain *dom,
588                                           struct unixid *xid) {
589
590         NTSTATUS ret;
591         struct autorid_global_config *globalcfg;
592         struct autorid_domain_config domaincfg;
593         uint32_t hwm;
594         const char *hwmkey;
595
596         if (!strequal(dom->name, "*")) {
597                 DEBUG(3, ("idmap_autorid_allocate_id: "
598                           "Refusing creation of mapping for domain'%s'. "
599                           "Currently only supported for the default "
600                           "domain \"*\".\n",
601                            dom->name));
602                 return NT_STATUS_NOT_IMPLEMENTED;
603         }
604
605         if ((xid->type != ID_TYPE_UID) && (xid->type != ID_TYPE_GID)) {
606                 return NT_STATUS_INVALID_PARAMETER;
607         }
608
609
610         globalcfg = talloc_get_type(dom->private_data,
611                                     struct autorid_global_config);
612
613         /* fetch the range for the allocation pool */
614
615         ZERO_STRUCT(domaincfg);
616
617         domaincfg.globalcfg = globalcfg;
618         fstrcpy(domaincfg.sid, ALLOC_RANGE);
619
620         ret = dbwrap_trans_do(autorid_db,
621                               idmap_autorid_get_domainrange,
622                               &domaincfg);
623         if (!NT_STATUS_IS_OK(ret)) {
624                 DEBUG(3, ("Could not determine range for allocation pool, "
625                           "check previous messages for reason\n"));
626                 return ret;
627         }
628
629         /* fetch the current HWM */
630         hwmkey = (xid->type==ID_TYPE_UID)?ALLOC_HWM_UID:ALLOC_HWM_GID;
631
632         ret = dbwrap_fetch_uint32(autorid_db, hwmkey, &hwm);
633
634         if (!NT_STATUS_IS_OK(ret)) {
635                 DEBUG(1, ("Failed to fetch current allocation HWM value: %s\n",
636                           nt_errstr(ret)));
637                 return NT_STATUS_INTERNAL_ERROR;
638         }
639
640         if (hwm >= globalcfg->rangesize) {
641                 DEBUG(1, ("allocation range is depleted!\n"));
642                 return NT_STATUS_NO_MEMORY;
643         }
644
645         ret = dbwrap_change_uint32_atomic(autorid_db, hwmkey, &(xid->id), 1);
646         if (!NT_STATUS_IS_OK(ret)) {
647                 DEBUG(1, ("Fatal error while allocating new ID!\n"));
648                 return ret;
649         }
650
651         xid->id = globalcfg->minvalue +
652                   globalcfg->rangesize * domaincfg.domainnum +
653                   xid->id;
654
655         DEBUG(10, ("Returned new %s %d from allocation range\n",
656                    (xid->type==ID_TYPE_UID)?"uid":"gid", xid->id));
657
658         return ret;
659 }
660
661 /*
662   Close the idmap tdb instance
663 */
664 static struct idmap_methods autorid_methods = {
665         .init = idmap_autorid_initialize,
666         .unixids_to_sids = idmap_autorid_unixids_to_sids,
667         .sids_to_unixids = idmap_autorid_sids_to_unixids,
668         .allocate_id     = idmap_autorid_allocate_id
669 };
670
671 NTSTATUS samba_init_module(void)
672 {
673         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION,
674                                   "autorid", &autorid_methods);
675 }