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