s3:net idmap restore: correctly abort operation if dbfile could not be determined
[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 #define FOO(x) (x)
21 #include "includes.h"
22 #include "utils/net.h"
23 #include "secrets.h"
24 #include "idmap.h"
25 #include "dbwrap.h"
26 #include "../libcli/security/security.h"
27
28 #define ALLOC_CHECK(mem) do { \
29         if (!mem) { \
30                 d_fprintf(stderr, _("Out of memory!\n")); \
31                 talloc_free(ctx); \
32                 return -1; \
33         } } while(0)
34
35 /***********************************************************
36  Helper function for net_idmap_dump. Dump one entry.
37  **********************************************************/
38 static int net_idmap_dump_one_entry(struct db_record *rec,
39                                     void *unused)
40 {
41         if (strcmp((char *)rec->key.dptr, "USER HWM") == 0) {
42                 printf(_("USER HWM %d\n"), IVAL(rec->value.dptr,0));
43                 return 0;
44         }
45
46         if (strcmp((char *)rec->key.dptr, "GROUP HWM") == 0) {
47                 printf(_("GROUP HWM %d\n"), IVAL(rec->value.dptr,0));
48                 return 0;
49         }
50
51         if (strncmp((char *)rec->key.dptr, "S-", 2) != 0)
52                 return 0;
53
54         printf("%s %s\n", rec->value.dptr, rec->key.dptr);
55         return 0;
56 }
57
58 static const char* net_idmap_dbfile(struct net_context *c)
59 {
60         const char* dbfile = NULL;
61
62         if (c->opt_db != NULL) {
63                 dbfile = talloc_strdup(talloc_tos(), c->opt_db);
64                 if (dbfile == NULL) {
65                         d_fprintf(stderr, _("Out of memory!\n"));
66                 }
67         } else if (strequal(lp_idmap_backend(), "tdb")) {
68                 dbfile = state_path("winbindd_idmap.tdb");
69                 if (dbfile == NULL) {
70                         d_fprintf(stderr, _("Out of memory!\n"));
71                 }
72         } else if (strequal(lp_idmap_backend(), "tdb2")) {
73                 dbfile = lp_parm_talloc_string(-1, "tdb", "idmap2.tdb", NULL);
74                 if (dbfile == NULL) {
75                         dbfile = talloc_asprintf(talloc_tos(), "%s/idmap2.tdb",
76                                                  lp_private_dir());
77                 }
78                 if (dbfile == NULL) {
79                         d_fprintf(stderr, _("Out of memory!\n"));
80                 }
81         } else {
82                 char* backend = talloc_strdup(talloc_tos(), lp_idmap_backend());
83                 char* args = strchr(backend, ':');
84                 if (args != NULL) {
85                         *args = '\0';
86                 }
87
88                 d_printf(_("Sorry, 'idmap backend = %s' is currently not supported\n"),
89                          backend);
90
91                 talloc_free(backend);
92         }
93
94         return dbfile;
95 }
96
97 /***********************************************************
98  Dump the current idmap
99  **********************************************************/
100 static int net_idmap_dump(struct net_context *c, int argc, const char **argv)
101 {
102         struct db_context *db;
103         TALLOC_CTX *mem_ctx;
104
105         if ( argc != 1  || c->display_usage) {
106                 d_printf("%s\n%s",
107                          _("Usage:"),
108                          _("net idmap dump <inputfile>\n"
109                            "  Dump current ID mapping.\n"
110                            "    inputfile\tTDB file to read mappings from.\n"));
111                 return c->display_usage?0:-1;
112         }
113
114         mem_ctx = talloc_stackframe();
115
116         db = db_open(mem_ctx, argv[0], 0, TDB_DEFAULT, O_RDONLY, 0);
117         if (db == NULL) {
118                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
119                           argv[0], strerror(errno));
120                 talloc_free(mem_ctx);
121                 return -1;
122         }
123
124         db->traverse_read(db, net_idmap_dump_one_entry, NULL);
125
126         talloc_free(mem_ctx);
127
128         return 0;
129 }
130
131 /***********************************************************
132  Write entries from stdin to current local idmap
133  **********************************************************/
134
135 static int net_idmap_store_id_mapping(struct db_context *db,
136                                       enum id_type type,
137                                       unsigned long idval,
138                                       const char *sid_string)
139 {
140         NTSTATUS status;
141         char *idstr = NULL;
142
143         switch(type) {
144         case ID_TYPE_UID:
145                 idstr = talloc_asprintf(talloc_tos(), "UID %lu", idval);
146                 break;
147         case ID_TYPE_GID:
148                 idstr = talloc_asprintf(talloc_tos(), "GID %lu", idval);
149                 break;
150         default:
151                 d_fprintf(stderr, "Invalid id mapping type: %d\n", type);
152                 return -1;
153         }
154
155         status = dbwrap_store_bystring(db, idstr,
156                                        string_term_tdb_data(sid_string),
157                                        TDB_REPLACE);
158         if (!NT_STATUS_IS_OK(status)) {
159                 d_fprintf(stderr, "Error storing ID -> SID: "
160                          "%s\n", nt_errstr(status));
161                 talloc_free(idstr);
162                 return -1;
163         }
164         status = dbwrap_store_bystring(db, sid_string,
165                                        string_term_tdb_data(idstr),
166                                        TDB_REPLACE);
167         if (!NT_STATUS_IS_OK(status)) {
168                 d_fprintf(stderr, "Error storing SID -> ID: "
169                          "%s\n", nt_errstr(status));
170                 talloc_free(idstr);
171                 return -1;
172         }
173
174         return 0;
175 }
176
177 static int net_idmap_restore(struct net_context *c, int argc, const char **argv)
178 {
179         TALLOC_CTX *mem_ctx;
180         FILE *input = NULL;
181         struct db_context *db;
182         const char *dbfile = NULL;
183         int ret = 0;
184
185         if (c->display_usage) {
186                 d_printf("%s\n%s",
187                          _("Usage:"),
188                          _("net idmap restore [--db=<TDB>] [<inputfile>]\n"
189                            "  Restore ID mappings from file\n"
190                            "    TDB\tFile to store ID mappings to."
191                            "    inputfile\tFile to load ID mappings from. If not "
192                            "given, load data from stdin.\n"));
193                 return 0;
194         }
195
196         mem_ctx = talloc_stackframe();
197
198         dbfile = net_idmap_dbfile(c);
199
200         if (dbfile == NULL) {
201                 ret = -1;
202                 goto done;
203         }
204
205         d_fprintf(stderr, _("restoring id mapping to %s\n"), dbfile);
206
207         if (argc == 1) {
208                 input = fopen(argv[0], "r");
209                 if (input == NULL) {
210                         d_fprintf(stderr, _("Could not open input file (%s): %s\n"),
211                                   argv[0], strerror(errno));
212                         ret = -1;
213                         goto done;
214                 }
215         } else {
216                 input = stdin;
217         }
218
219         db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644);
220         if (db == NULL) {
221                 d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
222                           dbfile, strerror(errno));
223                 ret = -1;
224                 goto done;
225         }
226
227         if (db->transaction_start(db) != 0) {
228                 d_fprintf(stderr, _("Failed to start transaction.\n"));
229                 ret = -1;
230                 goto done;
231         }
232
233         while (!feof(input)) {
234                 char line[128], sid_string[128];
235                 int len;
236                 unsigned long idval;
237
238                 if (fgets(line, 127, input) == NULL)
239                         break;
240
241                 len = strlen(line);
242
243                 if ( (len > 0) && (line[len-1] == '\n') )
244                         line[len-1] = '\0';
245
246                 if (sscanf(line, "GID %lu %128s", &idval, sid_string) == 2)
247                 {
248                         ret = net_idmap_store_id_mapping(db, ID_TYPE_GID,
249                                                          idval, sid_string);
250                         if (ret != 0) {
251                                 break;
252                         }
253                 } else if (sscanf(line, "UID %lu %128s", &idval, sid_string) == 2)
254                 {
255                         ret = net_idmap_store_id_mapping(db, ID_TYPE_UID,
256                                                          idval, sid_string);
257                         if (ret != 0) {
258                                 break;
259                         }
260                 } else if (sscanf(line, "USER HWM %lu", &idval) == 1) {
261                         ret = dbwrap_store_int32(db, "USER HWM", idval);
262                         if (ret != 0) {
263                                 d_fprintf(stderr, _("Could not store USER HWM.\n"));
264                                 break;
265                         }
266                 } else if (sscanf(line, "GROUP HWM %lu", &idval) == 1) {
267                         ret = dbwrap_store_int32(db, "GROUP HWM", idval);
268                         if (ret != 0) {
269                                 d_fprintf(stderr,
270                                           _("Could not store GROUP HWM.\n"));
271                                 break;
272                         }
273                 } else {
274                         d_fprintf(stderr, _("ignoring invalid line [%s]\n"),
275                                   line);
276                         continue;
277                 }
278         }
279
280         if (ret == 0) {
281                 if(db->transaction_commit(db) != 0) {
282                         d_fprintf(stderr, _("Failed to commit transaction.\n"));
283                         ret = -1;
284                 }
285         } else {
286                 if (db->transaction_cancel(db) != 0) {
287                         d_fprintf(stderr, _("Failed to cancel transaction.\n"));
288                 }
289         }
290
291 done:
292         if ((input != NULL) && (input != stdin)) {
293                 fclose(input);
294         }
295
296         talloc_free(mem_ctx);
297         return ret;
298 }
299
300 /***********************************************************
301  Delete a SID mapping from a winbindd_idmap.tdb
302  **********************************************************/
303 static int net_idmap_delete(struct net_context *c, int argc, const char **argv)
304 {
305         d_printf("%s\n", _("Not implemented yet"));
306         return -1;
307 }
308
309 static int net_idmap_set(struct net_context *c, int argc, const char **argv)
310 {
311         d_printf("%s\n", _("Not implemented yet"));
312         return -1;
313 }
314 static bool idmap_store_secret(const char *backend,
315                                const char *domain,
316                                const char *identity,
317                                const char *secret)
318 {
319         char *tmp;
320         int r;
321         bool ret;
322
323         r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
324
325         if (r < 0) return false;
326
327         strupper_m(tmp); /* make sure the key is case insensitive */
328         ret = secrets_store_generic(tmp, identity, secret);
329
330         free(tmp);
331         return ret;
332 }
333
334
335 static int net_idmap_secret(struct net_context *c, int argc, const char **argv)
336 {
337         TALLOC_CTX *ctx;
338         const char *secret;
339         const char *dn;
340         char *domain;
341         char *backend;
342         char *opt = NULL;
343         bool ret;
344
345         if (argc != 2 || c->display_usage) {
346                 d_printf("%s\n%s",
347                          _("Usage:\n"),
348                          _("net idmap secret <DOMAIN> <secret>\n"
349                            "  Set the secret for the specified domain\n"
350                            "    DOMAIN\tDomain to set secret for.\n"
351                            "    secret\tNew secret to set.\n"));
352                 return c->display_usage?0:-1;
353         }
354
355         secret = argv[1];
356
357         ctx = talloc_new(NULL);
358         ALLOC_CHECK(ctx);
359
360         domain = talloc_strdup(ctx, argv[0]);
361         ALLOC_CHECK(domain);
362
363         opt = talloc_asprintf(ctx, "idmap config %s", domain);
364         ALLOC_CHECK(opt);
365
366         backend = talloc_strdup(ctx, lp_parm_const_string(-1, opt, "backend", "tdb"));
367         ALLOC_CHECK(backend);
368
369         if ( ( ! backend) || ( ! strequal(backend, "ldap"))) {
370                 d_fprintf(stderr,
371                           _("The only currently supported backend is LDAP\n"));
372                 talloc_free(ctx);
373                 return -1;
374         }
375
376         dn = lp_parm_const_string(-1, opt, "ldap_user_dn", NULL);
377         if ( ! dn) {
378                 d_fprintf(stderr,
379                           _("Missing ldap_user_dn option for domain %s\n"),
380                           domain);
381                 talloc_free(ctx);
382                 return -1;
383         }
384
385         ret = idmap_store_secret("ldap", domain, dn, secret);
386
387         if ( ! ret) {
388                 d_fprintf(stderr, _("Failed to store secret\n"));
389                 talloc_free(ctx);
390                 return -1;
391         }
392
393         d_printf(_("Secret stored\n"));
394         return 0;
395 }
396
397 static int net_idmap_aclmapset(struct net_context *c, int argc, const char **argv)
398 {
399         TALLOC_CTX *mem_ctx;
400         int result = -1;
401         struct dom_sid src_sid, dst_sid;
402         char *src, *dst;
403         struct db_context *db;
404         struct db_record *rec;
405         NTSTATUS status;
406
407         if (argc != 3 || c->display_usage) {
408                 d_fprintf(stderr, "%s net idmap aclmapset <tdb> "
409                           "<src-sid> <dst-sid>\n", _("Usage:"));
410                 return -1;
411         }
412
413         if (!(mem_ctx = talloc_init("net idmap aclmapset"))) {
414                 d_fprintf(stderr, _("talloc_init failed\n"));
415                 return -1;
416         }
417
418         if (!(db = db_open(mem_ctx, argv[0], 0, TDB_DEFAULT,
419                            O_RDWR|O_CREAT, 0600))) {
420                 d_fprintf(stderr, _("db_open failed: %s\n"), strerror(errno));
421                 goto fail;
422         }
423
424         if (!string_to_sid(&src_sid, argv[1])) {
425                 d_fprintf(stderr, _("%s is not a valid sid\n"), argv[1]);
426                 goto fail;
427         }
428
429         if (!string_to_sid(&dst_sid, argv[2])) {
430                 d_fprintf(stderr, _("%s is not a valid sid\n"), argv[2]);
431                 goto fail;
432         }
433
434         if (!(src = sid_string_talloc(mem_ctx, &src_sid))
435             || !(dst = sid_string_talloc(mem_ctx, &dst_sid))) {
436                 d_fprintf(stderr, _("talloc_strdup failed\n"));
437                 goto fail;
438         }
439
440         if (!(rec = db->fetch_locked(
441                       db, mem_ctx, string_term_tdb_data(src)))) {
442                 d_fprintf(stderr, _("could not fetch db record\n"));
443                 goto fail;
444         }
445
446         status = rec->store(rec, string_term_tdb_data(dst), 0);
447         TALLOC_FREE(rec);
448
449         if (!NT_STATUS_IS_OK(status)) {
450                 d_fprintf(stderr, _("could not store record: %s\n"),
451                           nt_errstr(status));
452                 goto fail;
453         }
454
455         result = 0;
456 fail:
457         TALLOC_FREE(mem_ctx);
458         return result;
459 }
460
461 /***********************************************************
462  Look at the current idmap
463  **********************************************************/
464 int net_idmap(struct net_context *c, int argc, const char **argv)
465 {
466         struct functable func[] = {
467                 {
468                         "dump",
469                         net_idmap_dump,
470                         NET_TRANSPORT_LOCAL,
471                         N_("Dump the current ID mappings"),
472                         N_("net idmap dump\n"
473                            "  Dump the current ID mappings")
474                 },
475                 {
476                         "restore",
477                         net_idmap_restore,
478                         NET_TRANSPORT_LOCAL,
479                         N_("Restore entries from stdin"),
480                         N_("net idmap restore\n"
481                            "  Restore entries from stdin")
482                 },
483                 {
484                         "setmap",
485                         net_idmap_set,
486                         NET_TRANSPORT_LOCAL,
487                         N_("Not implemented yet"),
488                         N_("net idmap setmap\n"
489                            "  Not implemented yet")
490                 },
491                 {
492                         "delete",
493                         net_idmap_delete,
494                         NET_TRANSPORT_LOCAL,
495                         N_("Not implemented yet"),
496                         N_("net idmap delete\n"
497                            "  Not implemented yet")
498                 },
499                 {
500                         "secret",
501                         net_idmap_secret,
502                         NET_TRANSPORT_LOCAL,
503                         N_("Set secret for specified domain"),
504                         N_("net idmap secret <DOMAIN> <secret>\n"
505                            "  Set secret for specified domain")
506                 },
507                 {
508                         "aclmapset",
509                         net_idmap_aclmapset,
510                         NET_TRANSPORT_LOCAL,
511                         N_("Set acl map"),
512                         N_("net idmap aclmapset\n"
513                            "  Set acl map")
514                 },
515                 {NULL, NULL, 0, NULL, NULL}
516         };
517
518         return net_run_function(c, argc, argv, "net idmap", func);
519 }
520
521