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