s3:dbwrap: move db_open() to a file dbwrap_open.c of its own.
[kai/samba.git] / source3 / utils / net_idmap.c
1 /*
2    Samba Unix/Linux SMB client library
3    Distributed SMB/CIFS Server Management Utility
4    Copyright (C) 2003 Andrew Bartlett (abartlet@samba.org)
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 "system/filesys.h"
22 #include "utils/net.h"
23 #include "secrets.h"
24 #include "idmap.h"
25 #include "dbwrap.h"
26 #include "dbwrap/dbwrap_open.h"
27 #include "../libcli/security/security.h"
28 #include "net_idmap_check.h"
29 #include "util_tdb.h"
30
31 #define ALLOC_CHECK(mem) do { \
32         if (!mem) { \
33                 d_fprintf(stderr, _("Out of memory!\n")); \
34                 talloc_free(ctx); \
35                 return -1; \
36         } } while(0)
37
38 /***********************************************************
39  Helper function for net_idmap_dump. Dump one entry.
40  **********************************************************/
41 static int net_idmap_dump_one_entry(struct db_record *rec,
42                                     void *unused)
43 {
44         if (strcmp((char *)rec->key.dptr, "USER HWM") == 0) {
45                 printf(_("USER HWM %d\n"), IVAL(rec->value.dptr,0));
46                 return 0;
47         }
48
49         if (strcmp((char *)rec->key.dptr, "GROUP HWM") == 0) {
50                 printf(_("GROUP HWM %d\n"), IVAL(rec->value.dptr,0));
51                 return 0;
52         }
53
54         if (strncmp((char *)rec->key.dptr, "S-", 2) != 0)
55                 return 0;
56
57         printf("%s %s\n", rec->value.dptr, rec->key.dptr);
58         return 0;
59 }
60
61 static const char* net_idmap_dbfile(struct net_context *c)
62 {
63         const char* dbfile = NULL;
64
65         if (c->opt_db != NULL) {
66                 dbfile = talloc_strdup(talloc_tos(), c->opt_db);
67                 if (dbfile == NULL) {
68                         d_fprintf(stderr, _("Out of memory!\n"));
69                 }
70         } else if (strequal(lp_idmap_backend(), "tdb")) {
71                 dbfile = state_path("winbindd_idmap.tdb");
72                 if (dbfile == NULL) {
73                         d_fprintf(stderr, _("Out of memory!\n"));
74                 }
75         } else if (strequal(lp_idmap_backend(), "tdb2")) {
76                 dbfile = lp_parm_talloc_string(-1, "tdb", "idmap2.tdb", NULL);
77                 if (dbfile == NULL) {
78                         dbfile = talloc_asprintf(talloc_tos(), "%s/idmap2.tdb",
79                                                  lp_private_dir());
80                 }
81                 if (dbfile == NULL) {
82                         d_fprintf(stderr, _("Out of memory!\n"));
83                 }
84         } else {
85                 char* backend = talloc_strdup(talloc_tos(), lp_idmap_backend());
86                 char* args = strchr(backend, ':');
87                 if (args != NULL) {
88                         *args = '\0';
89                 }
90
91                 d_printf(_("Sorry, 'idmap backend = %s' is currently not supported\n"),
92                          backend);
93
94                 talloc_free(backend);
95         }
96
97         return dbfile;
98 }
99
100 /***********************************************************
101  Dump the current idmap
102  **********************************************************/
103 static int net_idmap_dump(struct net_context *c, int argc, const char **argv)
104 {
105         struct db_context *db;
106         TALLOC_CTX *mem_ctx;
107         const char* dbfile;
108         int ret = -1;
109
110         if ( argc > 1  || c->display_usage) {
111                 d_printf("%s\n%s",
112                          _("Usage:"),
113                          _("net idmap dump [[--db=]<inputfile>]\n"
114                            "  Dump current ID mapping.\n"
115                            "    inputfile\tTDB file to read mappings from.\n"));
116                 return c->display_usage?0:-1;
117         }
118
119         mem_ctx = talloc_stackframe();
120
121         dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c);
122         if (dbfile == NULL) {
123                 goto done;
124         }
125         d_fprintf(stderr, _("dumping id mapping from %s\n"), dbfile);
126
127         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0);
128         if (db == NULL) {
129                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
130                           dbfile, strerror(errno));
131                 goto done;
132         }
133
134         db->traverse_read(db, net_idmap_dump_one_entry, NULL);
135         ret = 0;
136
137 done:
138         talloc_free(mem_ctx);
139         return ret;
140 }
141
142 /***********************************************************
143  Write entries from stdin to current local idmap
144  **********************************************************/
145
146 static int net_idmap_store_id_mapping(struct db_context *db,
147                                       enum id_type type,
148                                       unsigned long idval,
149                                       const char *sid_string)
150 {
151         NTSTATUS status;
152         char *idstr = NULL;
153
154         switch(type) {
155         case ID_TYPE_UID:
156                 idstr = talloc_asprintf(talloc_tos(), "UID %lu", idval);
157                 break;
158         case ID_TYPE_GID:
159                 idstr = talloc_asprintf(talloc_tos(), "GID %lu", idval);
160                 break;
161         default:
162                 d_fprintf(stderr, "Invalid id mapping type: %d\n", type);
163                 return -1;
164         }
165
166         status = dbwrap_store_bystring(db, idstr,
167                                        string_term_tdb_data(sid_string),
168                                        TDB_REPLACE);
169         if (!NT_STATUS_IS_OK(status)) {
170                 d_fprintf(stderr, "Error storing ID -> SID: "
171                          "%s\n", nt_errstr(status));
172                 talloc_free(idstr);
173                 return -1;
174         }
175         status = dbwrap_store_bystring(db, sid_string,
176                                        string_term_tdb_data(idstr),
177                                        TDB_REPLACE);
178         if (!NT_STATUS_IS_OK(status)) {
179                 d_fprintf(stderr, "Error storing SID -> ID: "
180                          "%s\n", nt_errstr(status));
181                 talloc_free(idstr);
182                 return -1;
183         }
184
185         return 0;
186 }
187
188 static int net_idmap_restore(struct net_context *c, int argc, const char **argv)
189 {
190         TALLOC_CTX *mem_ctx;
191         FILE *input = NULL;
192         struct db_context *db;
193         const char *dbfile = NULL;
194         int ret = 0;
195
196         if (c->display_usage) {
197                 d_printf("%s\n%s",
198                          _("Usage:"),
199                          _("net idmap restore [--db=<TDB>] [<inputfile>]\n"
200                            "  Restore ID mappings from file\n"
201                            "    TDB\tFile to store ID mappings to."
202                            "    inputfile\tFile to load ID mappings from. If not "
203                            "given, load data from stdin.\n"));
204                 return 0;
205         }
206
207         mem_ctx = talloc_stackframe();
208
209         dbfile = net_idmap_dbfile(c);
210
211         if (dbfile == NULL) {
212                 ret = -1;
213                 goto done;
214         }
215
216         d_fprintf(stderr, _("restoring id mapping to %s\n"), dbfile);
217
218         if (argc == 1) {
219                 input = fopen(argv[0], "r");
220                 if (input == NULL) {
221                         d_fprintf(stderr, _("Could not open input file (%s): %s\n"),
222                                   argv[0], strerror(errno));
223                         ret = -1;
224                         goto done;
225                 }
226         } else {
227                 input = stdin;
228         }
229
230         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644);
231         if (db == NULL) {
232                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
233                           dbfile, strerror(errno));
234                 ret = -1;
235                 goto done;
236         }
237
238         if (db->transaction_start(db) != 0) {
239                 d_fprintf(stderr, _("Failed to start transaction.\n"));
240                 ret = -1;
241                 goto done;
242         }
243
244         while (!feof(input)) {
245                 char line[128], sid_string[128];
246                 int len;
247                 unsigned long idval;
248
249                 if (fgets(line, 127, input) == NULL)
250                         break;
251
252                 len = strlen(line);
253
254                 if ( (len > 0) && (line[len-1] == '\n') )
255                         line[len-1] = '\0';
256
257                 if (sscanf(line, "GID %lu %128s", &idval, sid_string) == 2)
258                 {
259                         ret = net_idmap_store_id_mapping(db, ID_TYPE_GID,
260                                                          idval, sid_string);
261                         if (ret != 0) {
262                                 break;
263                         }
264                 } else if (sscanf(line, "UID %lu %128s", &idval, sid_string) == 2)
265                 {
266                         ret = net_idmap_store_id_mapping(db, ID_TYPE_UID,
267                                                          idval, sid_string);
268                         if (ret != 0) {
269                                 break;
270                         }
271                 } else if (sscanf(line, "USER HWM %lu", &idval) == 1) {
272                         ret = dbwrap_store_int32(db, "USER HWM", idval);
273                         if (ret != 0) {
274                                 d_fprintf(stderr, _("Could not store USER HWM.\n"));
275                                 break;
276                         }
277                 } else if (sscanf(line, "GROUP HWM %lu", &idval) == 1) {
278                         ret = dbwrap_store_int32(db, "GROUP HWM", idval);
279                         if (ret != 0) {
280                                 d_fprintf(stderr,
281                                           _("Could not store GROUP HWM.\n"));
282                                 break;
283                         }
284                 } else {
285                         d_fprintf(stderr, _("ignoring invalid line [%s]\n"),
286                                   line);
287                         continue;
288                 }
289         }
290
291         if (ret == 0) {
292                 if(db->transaction_commit(db) != 0) {
293                         d_fprintf(stderr, _("Failed to commit transaction.\n"));
294                         ret = -1;
295                 }
296         } else {
297                 if (db->transaction_cancel(db) != 0) {
298                         d_fprintf(stderr, _("Failed to cancel transaction.\n"));
299                 }
300         }
301
302 done:
303         if ((input != NULL) && (input != stdin)) {
304                 fclose(input);
305         }
306
307         talloc_free(mem_ctx);
308         return ret;
309 }
310
311 static
312 NTSTATUS dbwrap_delete_mapping(struct db_context *db, TDB_DATA key1, bool force)
313 {
314         TALLOC_CTX* mem_ctx = talloc_tos();
315         struct db_record *rec1=NULL, *rec2=NULL;
316         TDB_DATA key2;
317         bool is_valid_mapping;
318         NTSTATUS status = NT_STATUS_OK;
319
320         rec1 = db->fetch_locked(db, mem_ctx, key1);
321         if (rec1 == NULL) {
322                 DEBUG(1, ("failed to fetch: %.*s\n", (int)key1.dsize, key1.dptr));
323                 status = NT_STATUS_NO_MEMORY;
324                 goto done;
325         }
326         key2 = rec1->value;
327         if (key2.dptr == NULL) {
328                 DEBUG(1, ("could not find %.*s\n", (int)key1.dsize, key1.dptr));
329                 status = NT_STATUS_NOT_FOUND;
330                 goto done;
331         }
332
333         DEBUG(2, ("mapping: %.*s -> %.*s\n",
334                   (int)key1.dsize, key1.dptr, (int)key2.dsize, key2.dptr));
335
336         rec2 = db->fetch_locked(db, mem_ctx, key2);
337         if (rec2 == NULL) {
338                 DEBUG(1, ("failed to fetch: %.*s\n", (int)key2.dsize, key2.dptr));
339                 status = NT_STATUS_NO_MEMORY;
340                 goto done;
341         }
342
343         is_valid_mapping = tdb_data_equal(key1, rec2->value);
344
345         if (!is_valid_mapping) {
346                 DEBUG(1, ("invalid mapping: %.*s -> %.*s -> %.*s\n",
347                           (int)key1.dsize, key1.dptr, (int)key2.dsize, key2.dptr,
348                           (int)rec2->value.dsize, rec2->value.dptr ));
349                 if ( !force ) {
350                         status = NT_STATUS_FILE_INVALID;
351                         goto done;
352                 }
353         }
354
355         status = rec1->delete_rec(rec1);
356         if (!NT_STATUS_IS_OK(status)) {
357                 DEBUG(1, ("failed to delete: %.*s\n", (int)key1.dsize, key1.dptr));
358                 goto done;
359         }
360
361         if (is_valid_mapping) {
362                 status = rec2->delete_rec(rec2);
363                 if (!NT_STATUS_IS_OK(status)) {
364                         DEBUG(1, ("failed to delete: %.*s\n", (int)key2.dsize, key2.dptr));
365                 }
366         }
367 done:
368         TALLOC_FREE(rec1);
369         TALLOC_FREE(rec2);
370         return status;
371 }
372
373 static
374 NTSTATUS delete_mapping_action(struct db_context *db, void* data)
375 {
376         return dbwrap_delete_mapping(db, *(TDB_DATA*)data, false);
377 }
378 static
379 NTSTATUS delete_mapping_action_force(struct db_context *db, void* data)
380 {
381         return dbwrap_delete_mapping(db, *(TDB_DATA*)data, true);
382 }
383
384 /***********************************************************
385  Delete a SID mapping from a winbindd_idmap.tdb
386  **********************************************************/
387 static bool delete_args_ok(int argc, const char **argv)
388 {
389         if (argc != 1)
390                 return false;
391         if (strncmp(argv[0], "S-", 2) == 0)
392                 return true;
393         if (strncmp(argv[0], "GID ", 4) == 0)
394                 return true;
395         if (strncmp(argv[0], "UID ", 4) == 0)
396                 return true;
397         return false;
398 }
399
400 static int net_idmap_delete(struct net_context *c, int argc, const char **argv)
401 {
402         int ret = -1;
403         struct db_context *db;
404         TALLOC_CTX *mem_ctx;
405         TDB_DATA key;
406         NTSTATUS status;
407         const char* dbfile;
408
409         if ( !delete_args_ok(argc,argv) || c->display_usage) {
410                 d_printf("%s\n%s",
411                          _("Usage:"),
412                          _("net idmap delete [-f] [--db=<TDB>] <ID>\n"
413                            "  Delete mapping of ID from TDB.\n"
414                            "    -f\tforce\n"
415                            "    TDB\tidmap database\n"
416                            "    ID\tSID|GID|UID\n"));
417                 return c->display_usage ? 0 : -1;
418         }
419
420         mem_ctx = talloc_stackframe();
421
422         dbfile = net_idmap_dbfile(c);
423         if (dbfile == NULL) {
424                 goto done;
425         }
426         d_fprintf(stderr, _("deleting id mapping from %s\n"), dbfile);
427
428         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR, 0);
429         if (db == NULL) {
430                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
431                           dbfile, strerror(errno));
432                 goto done;
433         }
434
435         key = string_term_tdb_data(argv[0]);
436
437         status = dbwrap_trans_do(db, (c->opt_force
438                                       ? delete_mapping_action_force
439                                       : delete_mapping_action),  &key);
440
441         if (!NT_STATUS_IS_OK(status)) {
442                 d_fprintf(stderr, _("could not delete mapping: %s\n"),
443                           nt_errstr(status));
444                 goto done;
445         }
446         ret = 0;
447 done:
448         talloc_free(mem_ctx);
449         return ret;
450 }
451
452 static int net_idmap_set(struct net_context *c, int argc, const char **argv)
453 {
454         d_printf("%s\n", _("Not implemented yet"));
455         return -1;
456 }
457 static bool idmap_store_secret(const char *backend,
458                                const char *domain,
459                                const char *identity,
460                                const char *secret)
461 {
462         char *tmp;
463         int r;
464         bool ret;
465
466         r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
467
468         if (r < 0) return false;
469
470         strupper_m(tmp); /* make sure the key is case insensitive */
471         ret = secrets_store_generic(tmp, identity, secret);
472
473         free(tmp);
474         return ret;
475 }
476
477
478 static int net_idmap_secret(struct net_context *c, int argc, const char **argv)
479 {
480         TALLOC_CTX *ctx;
481         const char *secret;
482         const char *dn;
483         char *domain;
484         char *backend;
485         char *opt = NULL;
486         bool ret;
487
488         if (argc != 2 || c->display_usage) {
489                 d_printf("%s\n%s",
490                          _("Usage:\n"),
491                          _("net idmap secret <DOMAIN> <secret>\n"
492                            "  Set the secret for the specified domain\n"
493                            "    DOMAIN\tDomain to set secret for.\n"
494                            "    secret\tNew secret to set.\n"));
495                 return c->display_usage?0:-1;
496         }
497
498         secret = argv[1];
499
500         ctx = talloc_new(NULL);
501         ALLOC_CHECK(ctx);
502
503         domain = talloc_strdup(ctx, argv[0]);
504         ALLOC_CHECK(domain);
505
506         opt = talloc_asprintf(ctx, "idmap config %s", domain);
507         ALLOC_CHECK(opt);
508
509         backend = talloc_strdup(ctx, lp_parm_const_string(-1, opt, "backend", "tdb"));
510         ALLOC_CHECK(backend);
511
512         if ( ( ! backend) || ( ! strequal(backend, "ldap"))) {
513                 d_fprintf(stderr,
514                           _("The only currently supported backend is LDAP\n"));
515                 talloc_free(ctx);
516                 return -1;
517         }
518
519         dn = lp_parm_const_string(-1, opt, "ldap_user_dn", NULL);
520         if ( ! dn) {
521                 d_fprintf(stderr,
522                           _("Missing ldap_user_dn option for domain %s\n"),
523                           domain);
524                 talloc_free(ctx);
525                 return -1;
526         }
527
528         ret = idmap_store_secret("ldap", domain, dn, secret);
529
530         if ( ! ret) {
531                 d_fprintf(stderr, _("Failed to store secret\n"));
532                 talloc_free(ctx);
533                 return -1;
534         }
535
536         d_printf(_("Secret stored\n"));
537         return 0;
538 }
539
540 static int net_idmap_check(struct net_context *c, int argc, const char **argv)
541 {
542         const char* dbfile;
543         struct check_options opts;
544
545         if ( argc > 1 || c->display_usage) {
546                 d_printf("%s\n%s",
547                          _("Usage:"),
548                          _("net idmap check  [-v] [-r] [-a] [-T] [-f] [-l] [[--db=]<TDB>]\n"
549                            "  Check an idmap database.\n"
550                            "    --verbose,-v\tverbose\n"
551                            "    --repair,-r\trepair\n"
552                            "    --auto,-a\tnoninteractive mode\n"
553                            "    --test,-T\tdry run\n"
554                            "    --fore,-f\tforce\n"
555                            "    --lock,-l\tlock db while doing the check\n"
556                            "    TDB\tidmap database\n"));
557                 return c->display_usage ? 0 : -1;
558         }
559
560         dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c);
561         if (dbfile == NULL) {
562                 return -1;
563         }
564         d_fprintf(stderr, _("check database: %s\n"), dbfile);
565
566         opts = (struct check_options) {
567                 .lock = c->opt_lock || c->opt_long_list_entries,
568                 .test = c->opt_testmode,
569                 .automatic = c->opt_auto,
570                 .verbose = c->opt_verbose,
571                 .force = c->opt_force,
572                 .repair = c->opt_repair || c->opt_reboot,
573         };
574
575         return net_idmap_check_db(dbfile, &opts);
576 }
577
578 static int net_idmap_aclmapset(struct net_context *c, int argc, const char **argv)
579 {
580         TALLOC_CTX *mem_ctx;
581         int result = -1;
582         struct dom_sid src_sid, dst_sid;
583         char *src, *dst;
584         struct db_context *db;
585         struct db_record *rec;
586         NTSTATUS status;
587
588         if (argc != 3 || c->display_usage) {
589                 d_fprintf(stderr, "%s net idmap aclmapset <tdb> "
590                           "<src-sid> <dst-sid>\n", _("Usage:"));
591                 return -1;
592         }
593
594         if (!(mem_ctx = talloc_init("net idmap aclmapset"))) {
595                 d_fprintf(stderr, _("talloc_init failed\n"));
596                 return -1;
597         }
598
599         if (!(db = db_open(mem_ctx, argv[0], 0, TDB_DEFAULT,
600                            O_RDWR|O_CREAT, 0600))) {
601                 d_fprintf(stderr, _("db_open failed: %s\n"), strerror(errno));
602                 goto fail;
603         }
604
605         if (!string_to_sid(&src_sid, argv[1])) {
606                 d_fprintf(stderr, _("%s is not a valid sid\n"), argv[1]);
607                 goto fail;
608         }
609
610         if (!string_to_sid(&dst_sid, argv[2])) {
611                 d_fprintf(stderr, _("%s is not a valid sid\n"), argv[2]);
612                 goto fail;
613         }
614
615         if (!(src = sid_string_talloc(mem_ctx, &src_sid))
616             || !(dst = sid_string_talloc(mem_ctx, &dst_sid))) {
617                 d_fprintf(stderr, _("talloc_strdup failed\n"));
618                 goto fail;
619         }
620
621         if (!(rec = db->fetch_locked(
622                       db, mem_ctx, string_term_tdb_data(src)))) {
623                 d_fprintf(stderr, _("could not fetch db record\n"));
624                 goto fail;
625         }
626
627         status = rec->store(rec, string_term_tdb_data(dst), 0);
628         TALLOC_FREE(rec);
629
630         if (!NT_STATUS_IS_OK(status)) {
631                 d_fprintf(stderr, _("could not store record: %s\n"),
632                           nt_errstr(status));
633                 goto fail;
634         }
635
636         result = 0;
637 fail:
638         TALLOC_FREE(mem_ctx);
639         return result;
640 }
641
642 /***********************************************************
643  Look at the current idmap
644  **********************************************************/
645 int net_idmap(struct net_context *c, int argc, const char **argv)
646 {
647         struct functable func[] = {
648                 {
649                         "dump",
650                         net_idmap_dump,
651                         NET_TRANSPORT_LOCAL,
652                         N_("Dump the current ID mappings"),
653                         N_("net idmap dump\n"
654                            "  Dump the current ID mappings")
655                 },
656                 {
657                         "restore",
658                         net_idmap_restore,
659                         NET_TRANSPORT_LOCAL,
660                         N_("Restore entries from stdin"),
661                         N_("net idmap restore\n"
662                            "  Restore entries from stdin")
663                 },
664                 {
665                         "setmap",
666                         net_idmap_set,
667                         NET_TRANSPORT_LOCAL,
668                         N_("Not implemented yet"),
669                         N_("net idmap setmap\n"
670                            "  Not implemented yet")
671                 },
672                 {
673                         "delete",
674                         net_idmap_delete,
675                         NET_TRANSPORT_LOCAL,
676                         N_("Delete ID mapping"),
677                         N_("net idmap delete <ID>\n"
678                            "  Delete ID mapping")
679                 },
680                 {
681                         "secret",
682                         net_idmap_secret,
683                         NET_TRANSPORT_LOCAL,
684                         N_("Set secret for specified domain"),
685                         N_("net idmap secret <DOMAIN> <secret>\n"
686                            "  Set secret for specified domain")
687                 },
688                 {
689                         "aclmapset",
690                         net_idmap_aclmapset,
691                         NET_TRANSPORT_LOCAL,
692                         N_("Set acl map"),
693                         N_("net idmap aclmapset\n"
694                            "  Set acl map")
695                 },
696                 {
697                         "check",
698                         net_idmap_check,
699                         NET_TRANSPORT_LOCAL,
700                         N_("Check id mappings"),
701                         N_("net idmap check\n"
702                            "  Check id mappings")
703                 },
704                 {NULL, NULL, 0, NULL, NULL}
705         };
706
707         return net_run_function(c, argc, argv, "net idmap", func);
708 }
709
710